]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/ada/checks.adb
[Ada] Minor reformattings
[thirdparty/gcc.git] / gcc / ada / checks.adb
CommitLineData
ee6ba406 1------------------------------------------------------------------------------
2-- --
3-- GNAT COMPILER COMPONENTS --
4-- --
5-- C H E C K S --
6-- --
7-- B o d y --
8-- --
e9c75a1a 9-- Copyright (C) 1992-2019, Free Software Foundation, Inc. --
ee6ba406 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- --
80df182a 13-- ware Foundation; either version 3, or (at your option) any later ver- --
ee6ba406 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 --
80df182a 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. --
ee6ba406 20-- --
21-- GNAT was originally developed by the GNAT team at New York University. --
e78e8c8e 22-- Extensive contributions were provided by Ada Core Technologies Inc. --
ee6ba406 23-- --
24------------------------------------------------------------------------------
25
26with Atree; use Atree;
29448168 27with Casing; use Casing;
ee6ba406 28with Debug; use Debug;
29with Einfo; use Einfo;
7b8fa048 30with Elists; use Elists;
31with Eval_Fat; use Eval_Fat;
32with Exp_Ch11; use Exp_Ch11;
ee6ba406 33with Exp_Ch2; use Exp_Ch2;
df40eeb0 34with Exp_Ch4; use Exp_Ch4;
05fcfafb 35with Exp_Pakd; use Exp_Pakd;
ee6ba406 36with Exp_Util; use Exp_Util;
4fb5f0a0 37with Expander; use Expander;
ee6ba406 38with Freeze; use Freeze;
9dfe12ae 39with Lib; use Lib;
ee6ba406 40with Nlists; use Nlists;
41with Nmake; use Nmake;
42with Opt; use Opt;
9dfe12ae 43with Output; use Output;
c2b56224 44with Restrict; use Restrict;
1e16c51c 45with Rident; use Rident;
ee6ba406 46with Rtsfind; use Rtsfind;
47with Sem; use Sem;
d60c9ff7 48with Sem_Aux; use Sem_Aux;
00f91aef 49with Sem_Ch3; use Sem_Ch3;
9dfe12ae 50with Sem_Ch8; use Sem_Ch8;
7e933b61 51with Sem_Disp; use Sem_Disp;
7b8fa048 52with Sem_Eval; use Sem_Eval;
becb6111 53with Sem_Mech; use Sem_Mech;
ee6ba406 54with Sem_Res; use Sem_Res;
55with Sem_Util; use Sem_Util;
56with Sem_Warn; use Sem_Warn;
57with Sinfo; use Sinfo;
9dfe12ae 58with Sinput; use Sinput;
ee6ba406 59with Snames; use Snames;
9dfe12ae 60with Sprint; use Sprint;
ee6ba406 61with Stand; use Stand;
bb569db0 62with Stringt; use Stringt;
f15731c4 63with Targparm; use Targparm;
ee6ba406 64with Tbuild; use Tbuild;
65with Ttypes; use Ttypes;
ee6ba406 66with Validsw; use Validsw;
67
68package body Checks is
69
70 -- General note: many of these routines are concerned with generating
71 -- checking code to make sure that constraint error is raised at runtime.
72 -- Clearly this code is only needed if the expander is active, since
73 -- otherwise we will not be generating code or going into the runtime
74 -- execution anyway.
75
76 -- We therefore disconnect most of these checks if the expander is
77 -- inactive. This has the additional benefit that we do not need to
78 -- worry about the tree being messed up by previous errors (since errors
79 -- turn off expansion anyway).
80
81 -- There are a few exceptions to the above rule. For instance routines
82 -- such as Apply_Scalar_Range_Check that do not insert any code can be
83 -- safely called even when the Expander is inactive (but Errors_Detected
84 -- is 0). The benefit of executing this code when expansion is off, is
85 -- the ability to emit constraint error warning for static expressions
86 -- even when we are not generating code.
87
20cf157b 88 -- The above is modified in gnatprove mode to ensure that proper check
89 -- flags are always placed, even if expansion is off.
90
9dfe12ae 91 -------------------------------------
92 -- Suppression of Redundant Checks --
93 -------------------------------------
94
95 -- This unit implements a limited circuit for removal of redundant
96 -- checks. The processing is based on a tracing of simple sequential
97 -- flow. For any sequence of statements, we save expressions that are
98 -- marked to be checked, and then if the same expression appears later
99 -- with the same check, then under certain circumstances, the second
100 -- check can be suppressed.
101
102 -- Basically, we can suppress the check if we know for certain that
103 -- the previous expression has been elaborated (together with its
104 -- check), and we know that the exception frame is the same, and that
105 -- nothing has happened to change the result of the exception.
106
107 -- Let us examine each of these three conditions in turn to describe
108 -- how we ensure that this condition is met.
109
110 -- First, we need to know for certain that the previous expression has
6fb3c314 111 -- been executed. This is done principally by the mechanism of calling
9dfe12ae 112 -- Conditional_Statements_Begin at the start of any statement sequence
113 -- and Conditional_Statements_End at the end. The End call causes all
114 -- checks remembered since the Begin call to be discarded. This does
115 -- miss a few cases, notably the case of a nested BEGIN-END block with
116 -- no exception handlers. But the important thing is to be conservative.
117 -- The other protection is that all checks are discarded if a label
118 -- is encountered, since then the assumption of sequential execution
119 -- is violated, and we don't know enough about the flow.
120
121 -- Second, we need to know that the exception frame is the same. We
122 -- do this by killing all remembered checks when we enter a new frame.
123 -- Again, that's over-conservative, but generally the cases we can help
124 -- with are pretty local anyway (like the body of a loop for example).
125
126 -- Third, we must be sure to forget any checks which are no longer valid.
127 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
128 -- used to note any changes to local variables. We only attempt to deal
129 -- with checks involving local variables, so we do not need to worry
130 -- about global variables. Second, a call to any non-global procedure
131 -- causes us to abandon all stored checks, since such a all may affect
132 -- the values of any local variables.
133
134 -- The following define the data structures used to deal with remembering
135 -- checks so that redundant checks can be eliminated as described above.
136
137 -- Right now, the only expressions that we deal with are of the form of
138 -- simple local objects (either declared locally, or IN parameters) or
139 -- such objects plus/minus a compile time known constant. We can do
140 -- more later on if it seems worthwhile, but this catches many simple
141 -- cases in practice.
142
143 -- The following record type reflects a single saved check. An entry
144 -- is made in the stack of saved checks if and only if the expression
145 -- has been elaborated with the indicated checks.
146
147 type Saved_Check is record
148 Killed : Boolean;
149 -- Set True if entry is killed by Kill_Checks
150
151 Entity : Entity_Id;
152 -- The entity involved in the expression that is checked
153
154 Offset : Uint;
155 -- A compile time value indicating the result of adding or
156 -- subtracting a compile time value. This value is to be
157 -- added to the value of the Entity. A value of zero is
158 -- used for the case of a simple entity reference.
159
160 Check_Type : Character;
161 -- This is set to 'R' for a range check (in which case Target_Type
162 -- is set to the target type for the range check) or to 'O' for an
163 -- overflow check (in which case Target_Type is set to Empty).
164
165 Target_Type : Entity_Id;
166 -- Used only if Do_Range_Check is set. Records the target type for
167 -- the check. We need this, because a check is a duplicate only if
6fb3c314 168 -- it has the same target type (or more accurately one with a
9dfe12ae 169 -- range that is smaller or equal to the stored target type of a
170 -- saved check).
171 end record;
172
173 -- The following table keeps track of saved checks. Rather than use an
bbbfe30c 174 -- extensible table, we just use a table of fixed size, and we discard
9dfe12ae 175 -- any saved checks that do not fit. That's very unlikely to happen and
176 -- this is only an optimization in any case.
177
178 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
179 -- Array of saved checks
180
181 Num_Saved_Checks : Nat := 0;
182 -- Number of saved checks
183
184 -- The following stack keeps track of statement ranges. It is treated
185 -- as a stack. When Conditional_Statements_Begin is called, an entry
186 -- is pushed onto this stack containing the value of Num_Saved_Checks
187 -- at the time of the call. Then when Conditional_Statements_End is
188 -- called, this value is popped off and used to reset Num_Saved_Checks.
189
190 -- Note: again, this is a fixed length stack with a size that should
191 -- always be fine. If the value of the stack pointer goes above the
192 -- limit, then we just forget all saved checks.
193
194 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
195 Saved_Checks_TOS : Nat := 0;
196
197 -----------------------
198 -- Local Subprograms --
199 -----------------------
ee6ba406 200
0df9d43f 201 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id);
3cce7f32 202 -- Used to apply arithmetic overflow checks for all cases except operators
691fe9e0 203 -- on signed arithmetic types in MINIMIZED/ELIMINATED case (for which we
0df9d43f 204 -- call Apply_Arithmetic_Overflow_Minimized_Eliminated below). N can be a
205 -- signed integer arithmetic operator (but not an if or case expression).
206 -- It is also called for types other than signed integers.
3cce7f32 207
208 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id);
209 -- Used to apply arithmetic overflow checks for the case where the overflow
0df9d43f 210 -- checking mode is MINIMIZED or ELIMINATED and we have a signed integer
211 -- arithmetic op (which includes the case of if and case expressions). Note
212 -- that Do_Overflow_Check may or may not be set for node Op. In these modes
213 -- we have work to do even if overflow checking is suppressed.
3cce7f32 214
2fe22c69 215 procedure Apply_Division_Check
216 (N : Node_Id;
217 Rlo : Uint;
218 Rhi : Uint;
219 ROK : Boolean);
220 -- N is an N_Op_Div, N_Op_Rem, or N_Op_Mod node. This routine applies
221 -- division checks as required if the Do_Division_Check flag is set.
222 -- Rlo and Rhi give the possible range of the right operand, these values
223 -- can be referenced and trusted only if ROK is set True.
224
225 procedure Apply_Float_Conversion_Check
226 (Ck_Node : Node_Id;
227 Target_Typ : Entity_Id);
228 -- The checks on a conversion from a floating-point type to an integer
229 -- type are delicate. They have to be performed before conversion, they
230 -- have to raise an exception when the operand is a NaN, and rounding must
231 -- be taken into account to determine the safe bounds of the operand.
232
ee6ba406 233 procedure Apply_Selected_Length_Checks
234 (Ck_Node : Node_Id;
235 Target_Typ : Entity_Id;
236 Source_Typ : Entity_Id;
237 Do_Static : Boolean);
238 -- This is the subprogram that does all the work for Apply_Length_Check
239 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
240 -- described for the above routines. The Do_Static flag indicates that
241 -- only a static check is to be done.
242
243 procedure Apply_Selected_Range_Checks
244 (Ck_Node : Node_Id;
245 Target_Typ : Entity_Id;
246 Source_Typ : Entity_Id;
247 Do_Static : Boolean);
248 -- This is the subprogram that does all the work for Apply_Range_Check.
249 -- Expr, Target_Typ and Source_Typ are as described for the above
250 -- routine. The Do_Static flag indicates that only a static check is
251 -- to be done.
252
2af58f67 253 type Check_Type is new Check_Id range Access_Check .. Division_Check;
13dbf220 254 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
255 -- This function is used to see if an access or division by zero check is
256 -- needed. The check is to be applied to a single variable appearing in the
257 -- source, and N is the node for the reference. If N is not of this form,
258 -- True is returned with no further processing. If N is of the right form,
259 -- then further processing determines if the given Check is needed.
260 --
261 -- The particular circuit is to see if we have the case of a check that is
262 -- not needed because it appears in the right operand of a short circuited
263 -- conditional where the left operand guards the check. For example:
264 --
265 -- if Var = 0 or else Q / Var > 12 then
266 -- ...
267 -- end if;
268 --
269 -- In this example, the division check is not required. At the same time
270 -- we can issue warnings for suspicious use of non-short-circuited forms,
271 -- such as:
272 --
273 -- if Var = 0 or Q / Var > 12 then
274 -- ...
275 -- end if;
276
9dfe12ae 277 procedure Find_Check
278 (Expr : Node_Id;
279 Check_Type : Character;
280 Target_Type : Entity_Id;
281 Entry_OK : out Boolean;
282 Check_Num : out Nat;
283 Ent : out Entity_Id;
284 Ofs : out Uint);
285 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
286 -- to see if a check is of the form for optimization, and if so, to see
287 -- if it has already been performed. Expr is the expression to check,
288 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
289 -- Target_Type is the target type for a range check, and Empty for an
290 -- overflow check. If the entry is not of the form for optimization,
291 -- then Entry_OK is set to False, and the remaining out parameters
292 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
293 -- entity and offset from the expression. Check_Num is the number of
294 -- a matching saved entry in Saved_Checks, or zero if no such entry
295 -- is located.
296
ee6ba406 297 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
298 -- If a discriminal is used in constraining a prival, Return reference
299 -- to the discriminal of the protected body (which renames the parameter
300 -- of the enclosing protected operation). This clumsy transformation is
301 -- needed because privals are created too late and their actual subtypes
302 -- are not available when analysing the bodies of the protected operations.
0577b0b1 303 -- This function is called whenever the bound is an entity and the scope
304 -- indicates a protected operation. If the bound is an in-parameter of
305 -- a protected operation that is not a prival, the function returns the
306 -- bound itself.
ee6ba406 307 -- To be cleaned up???
308
309 function Guard_Access
310 (Cond : Node_Id;
311 Loc : Source_Ptr;
314a23b6 312 Ck_Node : Node_Id) return Node_Id;
ee6ba406 313 -- In the access type case, guard the test with a test to ensure
314 -- that the access value is non-null, since the checks do not
315 -- not apply to null access values.
316
317 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
318 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
319 -- Constraint_Error node.
320
3cce7f32 321 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean;
322 -- Returns True if node N is for an arithmetic operation with signed
0326b4d4 323 -- integer operands. This includes unary and binary operators, and also
324 -- if and case expression nodes where the dependent expressions are of
325 -- a signed integer type. These are the kinds of nodes for which special
691fe9e0 326 -- handling applies in MINIMIZED or ELIMINATED overflow checking mode.
3cce7f32 327
0577b0b1 328 function Range_Or_Validity_Checks_Suppressed
329 (Expr : Node_Id) return Boolean;
330 -- Returns True if either range or validity checks or both are suppressed
331 -- for the type of the given expression, or, if the expression is the name
332 -- of an entity, if these checks are suppressed for the entity.
333
ee6ba406 334 function Selected_Length_Checks
335 (Ck_Node : Node_Id;
336 Target_Typ : Entity_Id;
337 Source_Typ : Entity_Id;
314a23b6 338 Warn_Node : Node_Id) return Check_Result;
ee6ba406 339 -- Like Apply_Selected_Length_Checks, except it doesn't modify
340 -- anything, just returns a list of nodes as described in the spec of
341 -- this package for the Range_Check function.
18cb6d78 342 -- ??? In fact it does construct the test and insert it into the tree,
343 -- and insert actions in various ways (calling Insert_Action directly
344 -- in particular) so we do not call it in GNATprove mode, contrary to
345 -- Selected_Range_Checks.
ee6ba406 346
347 function Selected_Range_Checks
348 (Ck_Node : Node_Id;
349 Target_Typ : Entity_Id;
350 Source_Typ : Entity_Id;
314a23b6 351 Warn_Node : Node_Id) return Check_Result;
ee6ba406 352 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
353 -- just returns a list of nodes as described in the spec of this package
354 -- for the Range_Check function.
355
356 ------------------------------
357 -- Access_Checks_Suppressed --
358 ------------------------------
359
360 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
361 begin
9dfe12ae 362 if Present (E) and then Checks_May_Be_Suppressed (E) then
363 return Is_Check_Suppressed (E, Access_Check);
364 else
fafc6b97 365 return Scope_Suppress.Suppress (Access_Check);
9dfe12ae 366 end if;
ee6ba406 367 end Access_Checks_Suppressed;
368
369 -------------------------------------
370 -- Accessibility_Checks_Suppressed --
371 -------------------------------------
372
373 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
374 begin
9dfe12ae 375 if Present (E) and then Checks_May_Be_Suppressed (E) then
376 return Is_Check_Suppressed (E, Accessibility_Check);
377 else
fafc6b97 378 return Scope_Suppress.Suppress (Accessibility_Check);
9dfe12ae 379 end if;
ee6ba406 380 end Accessibility_Checks_Suppressed;
381
00c403ee 382 -----------------------------
383 -- Activate_Division_Check --
384 -----------------------------
385
386 procedure Activate_Division_Check (N : Node_Id) is
387 begin
388 Set_Do_Division_Check (N, True);
389 Possible_Local_Raise (N, Standard_Constraint_Error);
390 end Activate_Division_Check;
391
392 -----------------------------
393 -- Activate_Overflow_Check --
394 -----------------------------
395
396 procedure Activate_Overflow_Check (N : Node_Id) is
c8e92b5f 397 Typ : constant Entity_Id := Etype (N);
398
00c403ee 399 begin
c8e92b5f 400 -- Floating-point case. If Etype is not set (this can happen when we
401 -- activate a check on a node that has not yet been analyzed), then
402 -- we assume we do not have a floating-point type (as per our spec).
403
404 if Present (Typ) and then Is_Floating_Point_Type (Typ) then
405
406 -- Ignore call if we have no automatic overflow checks on the target
407 -- and Check_Float_Overflow mode is not set. These are the cases in
408 -- which we expect to generate infinities and NaN's with no check.
409
410 if not (Machine_Overflows_On_Target or Check_Float_Overflow) then
411 return;
412
413 -- Ignore for unary operations ("+", "-", abs) since these can never
414 -- result in overflow for floating-point cases.
b8446e0d 415
c8e92b5f 416 elsif Nkind (N) in N_Unary_Op then
417 return;
418
419 -- Otherwise we will set the flag
420
421 else
422 null;
423 end if;
424
425 -- Discrete case
426
427 else
428 -- Nothing to do for Rem/Mod/Plus (overflow not possible, the check
429 -- for zero-divide is a divide check, not an overflow check).
b8446e0d 430
c8e92b5f 431 if Nkind_In (N, N_Op_Rem, N_Op_Mod, N_Op_Plus) then
432 return;
433 end if;
b8446e0d 434 end if;
435
c8e92b5f 436 -- Fall through for cases where we do set the flag
b8446e0d 437
79ee9e76 438 Set_Do_Overflow_Check (N);
b8446e0d 439 Possible_Local_Raise (N, Standard_Constraint_Error);
00c403ee 440 end Activate_Overflow_Check;
441
442 --------------------------
443 -- Activate_Range_Check --
444 --------------------------
445
446 procedure Activate_Range_Check (N : Node_Id) is
447 begin
df1c131a 448 Set_Do_Range_Check (N);
00c403ee 449 Possible_Local_Raise (N, Standard_Constraint_Error);
450 end Activate_Range_Check;
451
0577b0b1 452 ---------------------------------
453 -- Alignment_Checks_Suppressed --
454 ---------------------------------
455
456 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
457 begin
458 if Present (E) and then Checks_May_Be_Suppressed (E) then
459 return Is_Check_Suppressed (E, Alignment_Check);
460 else
fafc6b97 461 return Scope_Suppress.Suppress (Alignment_Check);
0577b0b1 462 end if;
463 end Alignment_Checks_Suppressed;
464
2d70530c 465 ----------------------------------
466 -- Allocation_Checks_Suppressed --
467 ----------------------------------
468
fa771c05 469 -- Note: at the current time there are no calls to this function, because
470 -- the relevant check is in the run-time, so it is not a check that the
471 -- compiler can suppress anyway, but we still have to recognize the check
472 -- name Allocation_Check since it is part of the standard.
473
2d70530c 474 function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean is
475 begin
476 if Present (E) and then Checks_May_Be_Suppressed (E) then
477 return Is_Check_Suppressed (E, Allocation_Check);
478 else
479 return Scope_Suppress.Suppress (Allocation_Check);
480 end if;
481 end Allocation_Checks_Suppressed;
482
ee6ba406 483 -------------------------
484 -- Append_Range_Checks --
485 -------------------------
486
487 procedure Append_Range_Checks
488 (Checks : Check_Result;
489 Stmts : List_Id;
490 Suppress_Typ : Entity_Id;
491 Static_Sloc : Source_Ptr;
492 Flag_Node : Node_Id)
493 is
2b4f2458 494 Checks_On : constant Boolean :=
495 not Index_Checks_Suppressed (Suppress_Typ)
496 or else
497 not Range_Checks_Suppressed (Suppress_Typ);
498
9dfe12ae 499 Internal_Flag_Node : constant Node_Id := Flag_Node;
500 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
501
ee6ba406 502 begin
2b4f2458 503 -- For now we just return if Checks_On is false, however this should be
504 -- enhanced to check for an always True value in the condition and to
505 -- generate a compilation warning???
ee6ba406 506
507 if not Checks_On then
508 return;
509 end if;
510
511 for J in 1 .. 2 loop
512 exit when No (Checks (J));
513
514 if Nkind (Checks (J)) = N_Raise_Constraint_Error
515 and then Present (Condition (Checks (J)))
516 then
517 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
518 Append_To (Stmts, Checks (J));
519 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
520 end if;
521
522 else
523 Append_To
f15731c4 524 (Stmts,
525 Make_Raise_Constraint_Error (Internal_Static_Sloc,
526 Reason => CE_Range_Check_Failed));
ee6ba406 527 end if;
528 end loop;
529 end Append_Range_Checks;
530
531 ------------------------
532 -- Apply_Access_Check --
533 ------------------------
534
535 procedure Apply_Access_Check (N : Node_Id) is
536 P : constant Node_Id := Prefix (N);
537
538 begin
13dbf220 539 -- We do not need checks if we are not generating code (i.e. the
540 -- expander is not active). This is not just an optimization, there
541 -- are cases (e.g. with pragma Debug) where generating the checks
542 -- can cause real trouble).
284faf8b 543
a33565dd 544 if not Expander_Active then
13dbf220 545 return;
9dfe12ae 546 end if;
ee6ba406 547
84d0d4a5 548 -- No check if short circuiting makes check unnecessary
9dfe12ae 549
84d0d4a5 550 if not Check_Needed (P, Access_Check) then
551 return;
ee6ba406 552 end if;
9dfe12ae 553
cc60bd16 554 -- No check if accessing the Offset_To_Top component of a dispatch
555 -- table. They are safe by construction.
556
040277b1 557 if Tagged_Type_Expansion
558 and then Present (Etype (P))
cc60bd16 559 and then RTU_Loaded (Ada_Tags)
560 and then RTE_Available (RE_Offset_To_Top_Ptr)
561 and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
562 then
563 return;
564 end if;
565
84d0d4a5 566 -- Otherwise go ahead and install the check
9dfe12ae 567
fa7497e8 568 Install_Null_Excluding_Check (P);
ee6ba406 569 end Apply_Access_Check;
570
571 -------------------------------
572 -- Apply_Accessibility_Check --
573 -------------------------------
574
55dc6dc2 575 procedure Apply_Accessibility_Check
576 (N : Node_Id;
577 Typ : Entity_Id;
578 Insert_Node : Node_Id)
579 is
53904d64 580 Loc : constant Source_Ptr := Sloc (N);
581
b1118eb8 582 Check_Cond : Node_Id;
53904d64 583 Param_Ent : Entity_Id := Param_Entity (N);
ee6ba406 584 Param_Level : Node_Id;
585 Type_Level : Node_Id;
586
587 begin
47d210a3 588 if Ada_Version >= Ada_2012
589 and then not Present (Param_Ent)
590 and then Is_Entity_Name (N)
591 and then Ekind_In (Entity (N), E_Constant, E_Variable)
592 and then Present (Effective_Extra_Accessibility (Entity (N)))
593 then
594 Param_Ent := Entity (N);
595 while Present (Renamed_Object (Param_Ent)) loop
1a9cc6cd 596
47d210a3 597 -- Renamed_Object must return an Entity_Name here
598 -- because of preceding "Present (E_E_A (...))" test.
599
600 Param_Ent := Entity (Renamed_Object (Param_Ent));
601 end loop;
602 end if;
603
ee6ba406 604 if Inside_A_Generic then
605 return;
606
6ffc64fc 607 -- Only apply the run-time check if the access parameter has an
608 -- associated extra access level parameter and when the level of the
609 -- type is less deep than the level of the access parameter, and
610 -- accessibility checks are not suppressed.
ee6ba406 611
612 elsif Present (Param_Ent)
613 and then Present (Extra_Accessibility (Param_Ent))
47d210a3 614 and then UI_Gt (Object_Access_Level (N),
1a9cc6cd 615 Deepest_Type_Access_Level (Typ))
ee6ba406 616 and then not Accessibility_Checks_Suppressed (Param_Ent)
617 and then not Accessibility_Checks_Suppressed (Typ)
618 then
619 Param_Level :=
620 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
621
e1415398 622 -- Use the dynamic accessibility parameter for the function's result
623 -- when one has been created instead of statically referring to the
624 -- deepest type level so as to appropriatly handle the rules for
625 -- RM 3.10.2 (10.1/3).
626
627 if Ekind_In (Scope (Param_Ent), E_Function,
628 E_Operator,
629 E_Subprogram_Type)
630 and then Present (Extra_Accessibility_Of_Result (Scope (Param_Ent)))
631 then
632 Type_Level :=
633 New_Occurrence_Of
634 (Extra_Accessibility_Of_Result (Scope (Param_Ent)), Loc);
635 else
636 Type_Level :=
637 Make_Integer_Literal (Loc, Deepest_Type_Access_Level (Typ));
638 end if;
ee6ba406 639
bf3e1520 640 -- Raise Program_Error if the accessibility level of the access
84d0d4a5 641 -- parameter is deeper than the level of the target access type.
ee6ba406 642
53904d64 643 Check_Cond :=
644 Make_Op_Gt (Loc,
645 Left_Opnd => Param_Level,
646 Right_Opnd => Type_Level);
b1118eb8 647
55dc6dc2 648 Insert_Action (Insert_Node,
ee6ba406 649 Make_Raise_Program_Error (Loc,
b1118eb8 650 Condition => Check_Cond,
651 Reason => PE_Accessibility_Check_Failed));
ee6ba406 652
653 Analyze_And_Resolve (N);
b1118eb8 654
655 -- If constant folding has happened on the condition for the
656 -- generated error, then warn about it being unconditional.
657
658 if Nkind (Check_Cond) = N_Identifier
659 and then Entity (Check_Cond) = Standard_True
660 then
661 Error_Msg_Warn := SPARK_Mode /= On;
53904d64 662 Error_Msg_N ("accessibility check fails<<", N);
663 Error_Msg_N ("\Program_Error [<<", N);
b1118eb8 664 end if;
ee6ba406 665 end if;
666 end Apply_Accessibility_Check;
667
0577b0b1 668 --------------------------------
669 -- Apply_Address_Clause_Check --
670 --------------------------------
671
672 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
d950dc79 673 pragma Assert (Nkind (N) = N_Freeze_Entity);
674
8650387e 675 AC : constant Node_Id := Address_Clause (E);
676 Loc : constant Source_Ptr := Sloc (AC);
677 Typ : constant Entity_Id := Etype (E);
c2b56224 678
c2b56224 679 Expr : Node_Id;
0577b0b1 680 -- Address expression (not necessarily the same as Aexp, for example
681 -- when Aexp is a reference to a constant, in which case Expr gets
7b8fa048 682 -- reset to reference the value expression of the constant).
0577b0b1 683
c2b56224 684 begin
d6da7448 685 -- See if alignment check needed. Note that we never need a check if the
686 -- maximum alignment is one, since the check will always succeed.
687
688 -- Note: we do not check for checks suppressed here, since that check
689 -- was done in Sem_Ch13 when the address clause was processed. We are
690 -- only called if checks were not suppressed. The reason for this is
691 -- that we have to delay the call to Apply_Alignment_Check till freeze
692 -- time (so that all types etc are elaborated), but we have to check
693 -- the status of check suppressing at the point of the address clause.
694
695 if No (AC)
696 or else not Check_Address_Alignment (AC)
697 or else Maximum_Alignment = 1
698 then
699 return;
700 end if;
701
702 -- Obtain expression from address clause
9dfe12ae 703
514a5555 704 Expr := Address_Value (Expression (AC));
0577b0b1 705
514a5555 706 -- See if we know that Expr has an acceptable value at compile time. If
707 -- it hasn't or we don't know, we defer issuing the warning until the
708 -- end of the compilation to take into account back end annotations.
c2b56224 709
710 if Compile_Time_Known_Value (Expr)
f2a06be9 711 and then (Known_Alignment (E) or else Known_Alignment (Typ))
c2b56224 712 then
f2a06be9 713 declare
714 AL : Uint := Alignment (Typ);
715
716 begin
8650387e 717 -- The object alignment might be more restrictive than the type
718 -- alignment.
f2a06be9 719
720 if Known_Alignment (E) then
721 AL := Alignment (E);
722 end if;
723
514a5555 724 if Expr_Value (Expr) mod AL = 0 then
0577b0b1 725 return;
f2a06be9 726 end if;
727 end;
c2b56224 728
7161e166 729 -- If the expression has the form X'Address, then we can find out if the
730 -- object X has an alignment that is compatible with the object E. If it
731 -- hasn't or we don't know, we defer issuing the warning until the end
732 -- of the compilation to take into account back end annotations.
c2b56224 733
0577b0b1 734 elsif Nkind (Expr) = N_Attribute_Reference
735 and then Attribute_Name (Expr) = Name_Address
7161e166 736 and then
737 Has_Compatible_Alignment (E, Prefix (Expr), False) = Known_Compatible
0577b0b1 738 then
d6da7448 739 return;
0577b0b1 740 end if;
c2b56224 741
6fb3c314 742 -- Here we do not know if the value is acceptable. Strictly we don't
743 -- have to do anything, since if the alignment is bad, we have an
744 -- erroneous program. However we are allowed to check for erroneous
745 -- conditions and we decide to do this by default if the check is not
746 -- suppressed.
0577b0b1 747
748 -- However, don't do the check if elaboration code is unwanted
749
750 if Restriction_Active (No_Elaboration_Code) then
751 return;
752
753 -- Generate a check to raise PE if alignment may be inappropriate
754
755 else
1916d94e 756 -- If the original expression is a nonstatic constant, use the name
8650387e 757 -- of the constant itself rather than duplicating its initialization
758 -- expression, which was extracted above.
0577b0b1 759
00c403ee 760 -- Note: Expr is empty if the address-clause is applied to in-mode
761 -- actuals (allowed by 13.1(22)).
762
763 if not Present (Expr)
764 or else
765 (Is_Entity_Name (Expression (AC))
766 and then Ekind (Entity (Expression (AC))) = E_Constant
8650387e 767 and then Nkind (Parent (Entity (Expression (AC)))) =
768 N_Object_Declaration)
0577b0b1 769 then
770 Expr := New_Copy_Tree (Expression (AC));
771 else
772 Remove_Side_Effects (Expr);
c2b56224 773 end if;
c2b56224 774
d950dc79 775 if No (Actions (N)) then
776 Set_Actions (N, New_List);
777 end if;
778
779 Prepend_To (Actions (N),
0577b0b1 780 Make_Raise_Program_Error (Loc,
781 Condition =>
782 Make_Op_Ne (Loc,
8650387e 783 Left_Opnd =>
0577b0b1 784 Make_Op_Mod (Loc,
8650387e 785 Left_Opnd =>
0577b0b1 786 Unchecked_Convert_To
787 (RTE (RE_Integer_Address), Expr),
788 Right_Opnd =>
789 Make_Attribute_Reference (Loc,
d950dc79 790 Prefix => New_Occurrence_Of (E, Loc),
0577b0b1 791 Attribute_Name => Name_Alignment)),
792 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
8650387e 793 Reason => PE_Misaligned_Address_Value));
7b8fa048 794
795 Warning_Msg := No_Error_Msg;
d950dc79 796 Analyze (First (Actions (N)), Suppress => All_Checks);
cd309f05 797
514a5555 798 -- If the above raise action generated a warning message (for example
7b8fa048 799 -- from Warn_On_Non_Local_Exception mode with the active restriction
800 -- No_Exception_Propagation).
801
802 if Warning_Msg /= No_Error_Msg then
8650387e 803
7b8fa048 804 -- If the expression has a known at compile time value, then
805 -- once we know the alignment of the type, we can check if the
806 -- exception will be raised or not, and if not, we don't need
807 -- the warning so we will kill the warning later on.
808
809 if Compile_Time_Known_Value (Expr) then
810 Alignment_Warnings.Append
811 ((E => E, A => Expr_Value (Expr), W => Warning_Msg));
cd309f05 812
8650387e 813 -- Add explanation of the warning generated by the check
814
815 else
514a5555 816 Error_Msg_N
8650387e 817 ("\address value may be incompatible with alignment of "
818 & "object?X?", AC);
514a5555 819 end if;
cd309f05 820 end if;
78be29d1 821
0577b0b1 822 return;
823 end if;
9dfe12ae 824
825 exception
8650387e 826
0577b0b1 827 -- If we have some missing run time component in configurable run time
828 -- mode then just skip the check (it is not required in any case).
829
9dfe12ae 830 when RE_Not_Available =>
831 return;
0577b0b1 832 end Apply_Address_Clause_Check;
c2b56224 833
ee6ba406 834 -------------------------------------
835 -- Apply_Arithmetic_Overflow_Check --
836 -------------------------------------
837
3cce7f32 838 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
839 begin
840 -- Use old routine in almost all cases (the only case we are treating
21a55437 841 -- specially is the case of a signed integer arithmetic op with the
0df9d43f 842 -- overflow checking mode set to MINIMIZED or ELIMINATED).
3cce7f32 843
0df9d43f 844 if Overflow_Check_Mode = Strict
3cce7f32 845 or else not Is_Signed_Integer_Arithmetic_Op (N)
846 then
0df9d43f 847 Apply_Arithmetic_Overflow_Strict (N);
3cce7f32 848
21a55437 849 -- Otherwise use the new routine for the case of a signed integer
850 -- arithmetic op, with Do_Overflow_Check set to True, and the checking
851 -- mode is MINIMIZED or ELIMINATED.
3cce7f32 852
853 else
854 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
855 end if;
856 end Apply_Arithmetic_Overflow_Check;
857
0df9d43f 858 --------------------------------------
859 -- Apply_Arithmetic_Overflow_Strict --
860 --------------------------------------
3cce7f32 861
fc1dbe36 862 -- This routine is called only if the type is an integer type and an
863 -- arithmetic overflow check may be needed for op (add, subtract, or
864 -- multiply). This check is performed if Backend_Overflow_Checks_On_Target
865 -- is not enabled and Do_Overflow_Check is set. In this case we expand the
f40f9731 866 -- operation into a more complex sequence of tests that ensures that
867 -- overflow is properly caught.
ee6ba406 868
0df9d43f 869 -- This is used in CHECKED modes. It is identical to the code for this
870 -- cases before the big overflow earthquake, thus ensuring that in this
871 -- modes we have compatible behavior (and reliability) to what was there
872 -- before. It is also called for types other than signed integers, and if
873 -- the Do_Overflow_Check flag is off.
3cce7f32 874
875 -- Note: we also call this routine if we decide in the MINIMIZED case
876 -- to give up and just generate an overflow check without any fuss.
877
0df9d43f 878 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id) is
21a55437 879 Loc : constant Source_Ptr := Sloc (N);
880 Typ : constant Entity_Id := Etype (N);
881 Rtyp : constant Entity_Id := Root_Type (Typ);
ee6ba406 882
883 begin
0df9d43f 884 -- Nothing to do if Do_Overflow_Check not set or overflow checks
885 -- suppressed.
886
887 if not Do_Overflow_Check (N) then
888 return;
889 end if;
890
f40f9731 891 -- An interesting special case. If the arithmetic operation appears as
892 -- the operand of a type conversion:
893
894 -- type1 (x op y)
895
896 -- and all the following conditions apply:
897
898 -- arithmetic operation is for a signed integer type
899 -- target type type1 is a static integer subtype
900 -- range of x and y are both included in the range of type1
901 -- range of x op y is included in the range of type1
902 -- size of type1 is at least twice the result size of op
903
a36d34e4 904 -- then we don't do an overflow check in any case. Instead, we transform
f40f9731 905 -- the operation so that we end up with:
906
907 -- type1 (type1 (x) op type1 (y))
908
909 -- This avoids intermediate overflow before the conversion. It is
910 -- explicitly permitted by RM 3.5.4(24):
911
912 -- For the execution of a predefined operation of a signed integer
913 -- type, the implementation need not raise Constraint_Error if the
914 -- result is outside the base range of the type, so long as the
915 -- correct result is produced.
916
917 -- It's hard to imagine that any programmer counts on the exception
918 -- being raised in this case, and in any case it's wrong coding to
919 -- have this expectation, given the RM permission. Furthermore, other
920 -- Ada compilers do allow such out of range results.
921
922 -- Note that we do this transformation even if overflow checking is
923 -- off, since this is precisely about giving the "right" result and
924 -- avoiding the need for an overflow check.
925
8eb4a5eb 926 -- Note: this circuit is partially redundant with respect to the similar
927 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
928 -- with cases that do not come through here. We still need the following
929 -- processing even with the Exp_Ch4 code in place, since we want to be
930 -- sure not to generate the arithmetic overflow check in these cases
931 -- (Exp_Ch4 would have a hard time removing them once generated).
932
f40f9731 933 if Is_Signed_Integer_Type (Typ)
934 and then Nkind (Parent (N)) = N_Type_Conversion
ee6ba406 935 then
f32c377d 936 Conversion_Optimization : declare
f40f9731 937 Target_Type : constant Entity_Id :=
b6341c67 938 Base_Type (Entity (Subtype_Mark (Parent (N))));
f40f9731 939
940 Llo, Lhi : Uint;
941 Rlo, Rhi : Uint;
942 LOK, ROK : Boolean;
943
944 Vlo : Uint;
945 Vhi : Uint;
946 VOK : Boolean;
947
948 Tlo : Uint;
949 Thi : Uint;
950
951 begin
952 if Is_Integer_Type (Target_Type)
953 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
954 then
955 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
956 Thi := Expr_Value (Type_High_Bound (Target_Type));
957
9c486805 958 Determine_Range
959 (Left_Opnd (N), LOK, Llo, Lhi, Assume_Valid => True);
960 Determine_Range
961 (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
f40f9731 962
963 if (LOK and ROK)
964 and then Tlo <= Llo and then Lhi <= Thi
965 and then Tlo <= Rlo and then Rhi <= Thi
966 then
9c486805 967 Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
f40f9731 968
969 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
970 Rewrite (Left_Opnd (N),
971 Make_Type_Conversion (Loc,
972 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
973 Expression => Relocate_Node (Left_Opnd (N))));
974
975 Rewrite (Right_Opnd (N),
976 Make_Type_Conversion (Loc,
977 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
978 Expression => Relocate_Node (Right_Opnd (N))));
979
780bfb21 980 -- Rewrite the conversion operand so that the original
981 -- node is retained, in order to avoid the warning for
982 -- redundant conversions in Resolve_Type_Conversion.
983
984 Rewrite (N, Relocate_Node (N));
985
f40f9731 986 Set_Etype (N, Target_Type);
780bfb21 987
f40f9731 988 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
989 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
990
991 -- Given that the target type is twice the size of the
992 -- source type, overflow is now impossible, so we can
993 -- safely kill the overflow check and return.
994
995 Set_Do_Overflow_Check (N, False);
996 return;
997 end if;
998 end if;
999 end if;
f32c377d 1000 end Conversion_Optimization;
ee6ba406 1001 end if;
1002
f40f9731 1003 -- Now see if an overflow check is required
1004
1005 declare
1006 Siz : constant Int := UI_To_Int (Esize (Rtyp));
1007 Dsiz : constant Int := Siz * 2;
1008 Opnod : Node_Id;
1009 Ctyp : Entity_Id;
1010 Opnd : Node_Id;
1011 Cent : RE_Id;
ee6ba406 1012
f40f9731 1013 begin
1014 -- Skip check if back end does overflow checks, or the overflow flag
df40eeb0 1015 -- is not set anyway, or we are not doing code expansion, or the
1016 -- parent node is a type conversion whose operand is an arithmetic
1017 -- operation on signed integers on which the expander can promote
bbbed24b 1018 -- later the operands to type Integer (see Expand_N_Type_Conversion).
ee6ba406 1019
f40f9731 1020 if Backend_Overflow_Checks_On_Target
1021 or else not Do_Overflow_Check (N)
a33565dd 1022 or else not Expander_Active
df40eeb0 1023 or else (Present (Parent (N))
1024 and then Nkind (Parent (N)) = N_Type_Conversion
1025 and then Integer_Promotion_Possible (Parent (N)))
f40f9731 1026 then
1027 return;
1028 end if;
ee6ba406 1029
f40f9731 1030 -- Otherwise, generate the full general code for front end overflow
1031 -- detection, which works by doing arithmetic in a larger type:
ee6ba406 1032
f40f9731 1033 -- x op y
ee6ba406 1034
f40f9731 1035 -- is expanded into
ee6ba406 1036
f40f9731 1037 -- Typ (Checktyp (x) op Checktyp (y));
ee6ba406 1038
f40f9731 1039 -- where Typ is the type of the original expression, and Checktyp is
1040 -- an integer type of sufficient length to hold the largest possible
1041 -- result.
ee6ba406 1042
f40f9731 1043 -- If the size of check type exceeds the size of Long_Long_Integer,
1044 -- we use a different approach, expanding to:
ee6ba406 1045
f40f9731 1046 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
ee6ba406 1047
f40f9731 1048 -- where xxx is Add, Multiply or Subtract as appropriate
ee6ba406 1049
f40f9731 1050 -- Find check type if one exists
1051
1052 if Dsiz <= Standard_Integer_Size then
1053 Ctyp := Standard_Integer;
ee6ba406 1054
f40f9731 1055 elsif Dsiz <= Standard_Long_Long_Integer_Size then
1056 Ctyp := Standard_Long_Long_Integer;
1057
c9f84db7 1058 -- No check type exists, use runtime call
ee6ba406 1059
1060 else
f40f9731 1061 if Nkind (N) = N_Op_Add then
1062 Cent := RE_Add_With_Ovflo_Check;
ee6ba406 1063
f40f9731 1064 elsif Nkind (N) = N_Op_Multiply then
1065 Cent := RE_Multiply_With_Ovflo_Check;
ee6ba406 1066
f40f9731 1067 else
1068 pragma Assert (Nkind (N) = N_Op_Subtract);
1069 Cent := RE_Subtract_With_Ovflo_Check;
1070 end if;
1071
1072 Rewrite (N,
1073 OK_Convert_To (Typ,
1074 Make_Function_Call (Loc,
83c6c069 1075 Name => New_Occurrence_Of (RTE (Cent), Loc),
f40f9731 1076 Parameter_Associations => New_List (
1077 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
1078 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
ee6ba406 1079
f40f9731 1080 Analyze_And_Resolve (N, Typ);
1081 return;
1082 end if;
ee6ba406 1083
f40f9731 1084 -- If we fall through, we have the case where we do the arithmetic
1085 -- in the next higher type and get the check by conversion. In these
1086 -- cases Ctyp is set to the type to be used as the check type.
ee6ba406 1087
f40f9731 1088 Opnod := Relocate_Node (N);
ee6ba406 1089
f40f9731 1090 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
ee6ba406 1091
f40f9731 1092 Analyze (Opnd);
1093 Set_Etype (Opnd, Ctyp);
1094 Set_Analyzed (Opnd, True);
1095 Set_Left_Opnd (Opnod, Opnd);
ee6ba406 1096
f40f9731 1097 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
ee6ba406 1098
f40f9731 1099 Analyze (Opnd);
1100 Set_Etype (Opnd, Ctyp);
1101 Set_Analyzed (Opnd, True);
1102 Set_Right_Opnd (Opnod, Opnd);
ee6ba406 1103
f40f9731 1104 -- The type of the operation changes to the base type of the check
1105 -- type, and we reset the overflow check indication, since clearly no
1106 -- overflow is possible now that we are using a double length type.
1107 -- We also set the Analyzed flag to avoid a recursive attempt to
1108 -- expand the node.
ee6ba406 1109
f40f9731 1110 Set_Etype (Opnod, Base_Type (Ctyp));
1111 Set_Do_Overflow_Check (Opnod, False);
1112 Set_Analyzed (Opnod, True);
ee6ba406 1113
f40f9731 1114 -- Now build the outer conversion
ee6ba406 1115
f40f9731 1116 Opnd := OK_Convert_To (Typ, Opnod);
1117 Analyze (Opnd);
1118 Set_Etype (Opnd, Typ);
9dfe12ae 1119
f40f9731 1120 -- In the discrete type case, we directly generate the range check
1121 -- for the outer operand. This range check will implement the
1122 -- required overflow check.
9dfe12ae 1123
f40f9731 1124 if Is_Discrete_Type (Typ) then
1125 Rewrite (N, Opnd);
1126 Generate_Range_Check
1127 (Expression (N), Typ, CE_Overflow_Check_Failed);
9dfe12ae 1128
f40f9731 1129 -- For other types, we enable overflow checking on the conversion,
1130 -- after setting the node as analyzed to prevent recursive attempts
1131 -- to expand the conversion node.
9dfe12ae 1132
f40f9731 1133 else
1134 Set_Analyzed (Opnd, True);
1135 Enable_Overflow_Check (Opnd);
1136 Rewrite (N, Opnd);
1137 end if;
1138
1139 exception
1140 when RE_Not_Available =>
1141 return;
1142 end;
0df9d43f 1143 end Apply_Arithmetic_Overflow_Strict;
3cce7f32 1144
1145 ----------------------------------------------------
1146 -- Apply_Arithmetic_Overflow_Minimized_Eliminated --
1147 ----------------------------------------------------
1148
1149 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id) is
1150 pragma Assert (Is_Signed_Integer_Arithmetic_Op (Op));
3cce7f32 1151
1152 Loc : constant Source_Ptr := Sloc (Op);
1153 P : constant Node_Id := Parent (Op);
1154
49b3a812 1155 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
1156 -- Operands and results are of this type when we convert
1157
3cce7f32 1158 Result_Type : constant Entity_Id := Etype (Op);
1159 -- Original result type
1160
db415383 1161 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
3cce7f32 1162 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
1163
1164 Lo, Hi : Uint;
1165 -- Ranges of values for result
1166
1167 begin
1168 -- Nothing to do if our parent is one of the following:
1169
0326b4d4 1170 -- Another signed integer arithmetic op
3cce7f32 1171 -- A membership operation
1172 -- A comparison operation
1173
1174 -- In all these cases, we will process at the higher level (and then
1175 -- this node will be processed during the downwards recursion that
0df9d43f 1176 -- is part of the processing in Minimize_Eliminate_Overflows).
3cce7f32 1177
1178 if Is_Signed_Integer_Arithmetic_Op (P)
b8a17a21 1179 or else Nkind (P) in N_Membership_Test
1180 or else Nkind (P) in N_Op_Compare
aa4b16cb 1181
70a2dff4 1182 -- This is also true for an alternative in a case expression
1183
1184 or else Nkind (P) = N_Case_Expression_Alternative
1185
1186 -- This is also true for a range operand in a membership test
aa4b16cb 1187
b8a17a21 1188 or else (Nkind (P) = N_Range
1189 and then Nkind (Parent (P)) in N_Membership_Test)
3cce7f32 1190 then
af90720d 1191 -- If_Expressions and Case_Expressions are treated as arithmetic
1192 -- ops, but if they appear in an assignment or similar contexts
1193 -- there is no overflow check that starts from that parent node,
1194 -- so apply check now.
1195
1196 if Nkind_In (P, N_If_Expression, N_Case_Expression)
1197 and then not Is_Signed_Integer_Arithmetic_Op (Parent (P))
1198 then
1199 null;
1200 else
1201 return;
1202 end if;
3cce7f32 1203 end if;
1204
0326b4d4 1205 -- Otherwise, we have a top level arithmetic operation node, and this
21a55437 1206 -- is where we commence the special processing for MINIMIZED/ELIMINATED
1207 -- modes. This is the case where we tell the machinery not to move into
1208 -- Bignum mode at this top level (of course the top level operation
1209 -- will still be in Bignum mode if either of its operands are of type
1210 -- Bignum).
3cce7f32 1211
0df9d43f 1212 Minimize_Eliminate_Overflows (Op, Lo, Hi, Top_Level => True);
3cce7f32 1213
1214 -- That call may but does not necessarily change the result type of Op.
1215 -- It is the job of this routine to undo such changes, so that at the
1216 -- top level, we have the proper type. This "undoing" is a point at
1217 -- which a final overflow check may be applied.
1218
f32c377d 1219 -- If the result type was not fiddled we are all set. We go to base
1220 -- types here because things may have been rewritten to generate the
1221 -- base type of the operand types.
3cce7f32 1222
f32c377d 1223 if Base_Type (Etype (Op)) = Base_Type (Result_Type) then
3cce7f32 1224 return;
1225
1226 -- Bignum case
1227
49b3a812 1228 elsif Is_RTE (Etype (Op), RE_Bignum) then
3cce7f32 1229
d94b5da2 1230 -- We need a sequence that looks like:
3cce7f32 1231
1232 -- Rnn : Result_Type;
1233
1234 -- declare
d94b5da2 1235 -- M : Mark_Id := SS_Mark;
3cce7f32 1236 -- begin
49b3a812 1237 -- Rnn := Long_Long_Integer'Base (From_Bignum (Op));
3cce7f32 1238 -- SS_Release (M);
1239 -- end;
1240
1241 -- This block is inserted (using Insert_Actions), and then the node
1242 -- is replaced with a reference to Rnn.
1243
75b45a21 1244 -- If our parent is a conversion node then there is no point in
a36d34e4 1245 -- generating a conversion to Result_Type. Instead, we let the parent
75b45a21 1246 -- handle this. Note that this special case is not just about
1247 -- optimization. Consider
3cce7f32 1248
1249 -- A,B,C : Integer;
1250 -- ...
49b3a812 1251 -- X := Long_Long_Integer'Base (A * (B ** C));
3cce7f32 1252
1253 -- Now the product may fit in Long_Long_Integer but not in Integer.
21a55437 1254 -- In MINIMIZED/ELIMINATED mode, we don't want to introduce an
1255 -- overflow exception for this intermediate value.
3cce7f32 1256
1257 declare
49b3a812 1258 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3cce7f32 1259 Rnn : constant Entity_Id := Make_Temporary (Loc, 'R', Op);
1260 RHS : Node_Id;
1261
1262 Rtype : Entity_Id;
1263
1264 begin
1265 RHS := Convert_From_Bignum (Op);
1266
1267 if Nkind (P) /= N_Type_Conversion then
49b3a812 1268 Convert_To_And_Rewrite (Result_Type, RHS);
3cce7f32 1269 Rtype := Result_Type;
1270
1271 -- Interesting question, do we need a check on that conversion
1272 -- operation. Answer, not if we know the result is in range.
1273 -- At the moment we are not taking advantage of this. To be
1274 -- looked at later ???
1275
1276 else
49b3a812 1277 Rtype := LLIB;
3cce7f32 1278 end if;
1279
1280 Insert_Before
1281 (First (Statements (Handled_Statement_Sequence (Blk))),
1282 Make_Assignment_Statement (Loc,
1283 Name => New_Occurrence_Of (Rnn, Loc),
1284 Expression => RHS));
1285
1286 Insert_Actions (Op, New_List (
1287 Make_Object_Declaration (Loc,
1288 Defining_Identifier => Rnn,
1289 Object_Definition => New_Occurrence_Of (Rtype, Loc)),
1290 Blk));
1291
1292 Rewrite (Op, New_Occurrence_Of (Rnn, Loc));
1293 Analyze_And_Resolve (Op);
1294 end;
1295
af90720d 1296 -- Here we know the result is Long_Long_Integer'Base, or that it has
412f75eb 1297 -- been rewritten because the parent operation is a conversion. See
0df9d43f 1298 -- Apply_Arithmetic_Overflow_Strict.Conversion_Optimization.
3cce7f32 1299
1300 else
f32c377d 1301 pragma Assert
1302 (Etype (Op) = LLIB or else Nkind (Parent (Op)) = N_Type_Conversion);
3cce7f32 1303
1304 -- All we need to do here is to convert the result to the proper
1305 -- result type. As explained above for the Bignum case, we can
1306 -- omit this if our parent is a type conversion.
1307
1308 if Nkind (P) /= N_Type_Conversion then
1309 Convert_To_And_Rewrite (Result_Type, Op);
1310 end if;
1311
1312 Analyze_And_Resolve (Op);
1313 end if;
1314 end Apply_Arithmetic_Overflow_Minimized_Eliminated;
ee6ba406 1315
ee6ba406 1316 ----------------------------
1317 -- Apply_Constraint_Check --
1318 ----------------------------
1319
1320 procedure Apply_Constraint_Check
1321 (N : Node_Id;
1322 Typ : Entity_Id;
1323 No_Sliding : Boolean := False)
1324 is
1325 Desig_Typ : Entity_Id;
1326
1327 begin
7aafae1c 1328 -- No checks inside a generic (check the instantiations)
1329
ee6ba406 1330 if Inside_A_Generic then
1331 return;
7aafae1c 1332 end if;
ee6ba406 1333
6fb3c314 1334 -- Apply required constraint checks
7aafae1c 1335
1336 if Is_Scalar_Type (Typ) then
ee6ba406 1337 Apply_Scalar_Range_Check (N, Typ);
1338
1339 elsif Is_Array_Type (Typ) then
1340
05fcfafb 1341 -- A useful optimization: an aggregate with only an others clause
5f260d20 1342 -- always has the right bounds.
1343
1344 if Nkind (N) = N_Aggregate
1345 and then No (Expressions (N))
1346 and then Nkind
1347 (First (Choices (First (Component_Associations (N)))))
1348 = N_Others_Choice
1349 then
1350 return;
1351 end if;
1352
ee6ba406 1353 if Is_Constrained (Typ) then
1354 Apply_Length_Check (N, Typ);
1355
1356 if No_Sliding then
1357 Apply_Range_Check (N, Typ);
1358 end if;
1359 else
1360 Apply_Range_Check (N, Typ);
1361 end if;
1362
4fb5f0a0 1363 elsif (Is_Record_Type (Typ) or else Is_Private_Type (Typ))
ee6ba406 1364 and then Has_Discriminants (Base_Type (Typ))
1365 and then Is_Constrained (Typ)
1366 then
1367 Apply_Discriminant_Check (N, Typ);
1368
1369 elsif Is_Access_Type (Typ) then
1370
1371 Desig_Typ := Designated_Type (Typ);
1372
1373 -- No checks necessary if expression statically null
1374
2af58f67 1375 if Known_Null (N) then
00c403ee 1376 if Can_Never_Be_Null (Typ) then
1377 Install_Null_Excluding_Check (N);
1378 end if;
ee6ba406 1379
1380 -- No sliding possible on access to arrays
1381
1382 elsif Is_Array_Type (Desig_Typ) then
1383 if Is_Constrained (Desig_Typ) then
1384 Apply_Length_Check (N, Typ);
1385 end if;
1386
1387 Apply_Range_Check (N, Typ);
1388
a63a0aad 1389 -- Do not install a discriminant check for a constrained subtype
1390 -- created for an unconstrained nominal type because the subtype
1391 -- has the correct constraints by construction.
1392
ee6ba406 1393 elsif Has_Discriminants (Base_Type (Desig_Typ))
a63a0aad 1394 and then Is_Constrained (Desig_Typ)
1395 and then not Is_Constr_Subt_For_U_Nominal (Desig_Typ)
ee6ba406 1396 then
1397 Apply_Discriminant_Check (N, Typ);
1398 end if;
fa7497e8 1399
bf3e1520 1400 -- Apply the 2005 Null_Excluding check. Note that we do not apply
00c403ee 1401 -- this check if the constraint node is illegal, as shown by having
1402 -- an error posted. This additional guard prevents cascaded errors
1403 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1404
fa7497e8 1405 if Can_Never_Be_Null (Typ)
1406 and then not Can_Never_Be_Null (Etype (N))
00c403ee 1407 and then not Error_Posted (N)
fa7497e8 1408 then
1409 Install_Null_Excluding_Check (N);
1410 end if;
ee6ba406 1411 end if;
1412 end Apply_Constraint_Check;
1413
1414 ------------------------------
1415 -- Apply_Discriminant_Check --
1416 ------------------------------
1417
1418 procedure Apply_Discriminant_Check
1419 (N : Node_Id;
1420 Typ : Entity_Id;
1421 Lhs : Node_Id := Empty)
1422 is
1423 Loc : constant Source_Ptr := Sloc (N);
1424 Do_Access : constant Boolean := Is_Access_Type (Typ);
1425 S_Typ : Entity_Id := Etype (N);
1426 Cond : Node_Id;
1427 T_Typ : Entity_Id;
1428
7be5088a 1429 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1430 -- A heap object with an indefinite subtype is constrained by its
1431 -- initial value, and assigning to it requires a constraint_check.
1432 -- The target may be an explicit dereference, or a renaming of one.
1433
ee6ba406 1434 function Is_Aliased_Unconstrained_Component return Boolean;
1435 -- It is possible for an aliased component to have a nominal
1436 -- unconstrained subtype (through instantiation). If this is a
1437 -- discriminated component assigned in the expansion of an aggregate
1438 -- in an initialization, the check must be suppressed. This unusual
2af58f67 1439 -- situation requires a predicate of its own.
ee6ba406 1440
7be5088a 1441 ----------------------------------
1442 -- Denotes_Explicit_Dereference --
1443 ----------------------------------
1444
1445 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1446 begin
1447 return
1448 Nkind (Obj) = N_Explicit_Dereference
1449 or else
1450 (Is_Entity_Name (Obj)
1451 and then Present (Renamed_Object (Entity (Obj)))
9474aa9c 1452 and then Nkind (Renamed_Object (Entity (Obj))) =
1453 N_Explicit_Dereference);
7be5088a 1454 end Denotes_Explicit_Dereference;
1455
ee6ba406 1456 ----------------------------------------
1457 -- Is_Aliased_Unconstrained_Component --
1458 ----------------------------------------
1459
1460 function Is_Aliased_Unconstrained_Component return Boolean is
1461 Comp : Entity_Id;
1462 Pref : Node_Id;
1463
1464 begin
1465 if Nkind (Lhs) /= N_Selected_Component then
1466 return False;
1467 else
1468 Comp := Entity (Selector_Name (Lhs));
1469 Pref := Prefix (Lhs);
1470 end if;
1471
1472 if Ekind (Comp) /= E_Component
1473 or else not Is_Aliased (Comp)
1474 then
1475 return False;
1476 end if;
1477
1478 return not Comes_From_Source (Pref)
1479 and then In_Instance
1480 and then not Is_Constrained (Etype (Comp));
1481 end Is_Aliased_Unconstrained_Component;
1482
1483 -- Start of processing for Apply_Discriminant_Check
1484
1485 begin
1486 if Do_Access then
1487 T_Typ := Designated_Type (Typ);
1488 else
1489 T_Typ := Typ;
1490 end if;
1491
105fa703 1492 -- If the expression is a function call that returns a limited object
1493 -- it cannot be copied. It is not clear how to perform the proper
1494 -- discriminant check in this case because the discriminant value must
1495 -- be retrieved from the constructed object itself.
1496
1497 if Nkind (N) = N_Function_Call
1498 and then Is_Limited_Type (Typ)
1499 and then Is_Entity_Name (Name (N))
1500 and then Returns_By_Ref (Entity (Name (N)))
1501 then
1502 return;
1503 end if;
1504
f0d65dae 1505 -- Only apply checks when generating code and discriminant checks are
1506 -- not suppressed. In GNATprove mode, we do not apply the checks, but we
1507 -- still analyze the expression to possibly issue errors on SPARK code
1508 -- when a run-time error can be detected at compile time.
1509
1510 if not GNATprove_Mode then
1511 if not Expander_Active
1512 or else Discriminant_Checks_Suppressed (T_Typ)
1513 then
1514 return;
1515 end if;
ee6ba406 1516 end if;
1517
feff2f05 1518 -- No discriminant checks necessary for an access when expression is
1519 -- statically Null. This is not only an optimization, it is fundamental
1520 -- because otherwise discriminant checks may be generated in init procs
1521 -- for types containing an access to a not-yet-frozen record, causing a
1522 -- deadly forward reference.
ee6ba406 1523
feff2f05 1524 -- Also, if the expression is of an access type whose designated type is
1525 -- incomplete, then the access value must be null and we suppress the
1526 -- check.
ee6ba406 1527
2af58f67 1528 if Known_Null (N) then
ee6ba406 1529 return;
1530
1531 elsif Is_Access_Type (S_Typ) then
1532 S_Typ := Designated_Type (S_Typ);
1533
1534 if Ekind (S_Typ) = E_Incomplete_Type then
1535 return;
1536 end if;
1537 end if;
1538
0577b0b1 1539 -- If an assignment target is present, then we need to generate the
1540 -- actual subtype if the target is a parameter or aliased object with
1541 -- an unconstrained nominal subtype.
1542
1543 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1544 -- subtype to the parameter and dereference cases, since other aliased
1545 -- objects are unconstrained (unless the nominal subtype is explicitly
7be5088a 1546 -- constrained).
ee6ba406 1547
1548 if Present (Lhs)
1549 and then (Present (Param_Entity (Lhs))
de54c5ab 1550 or else (Ada_Version < Ada_2005
0577b0b1 1551 and then not Is_Constrained (T_Typ)
ee6ba406 1552 and then Is_Aliased_View (Lhs)
0577b0b1 1553 and then not Is_Aliased_Unconstrained_Component)
de54c5ab 1554 or else (Ada_Version >= Ada_2005
0577b0b1 1555 and then not Is_Constrained (T_Typ)
7be5088a 1556 and then Denotes_Explicit_Dereference (Lhs)
0577b0b1 1557 and then Nkind (Original_Node (Lhs)) /=
1558 N_Function_Call))
ee6ba406 1559 then
1560 T_Typ := Get_Actual_Subtype (Lhs);
1561 end if;
1562
feff2f05 1563 -- Nothing to do if the type is unconstrained (this is the case where
1564 -- the actual subtype in the RM sense of N is unconstrained and no check
1565 -- is required).
ee6ba406 1566
1567 if not Is_Constrained (T_Typ) then
1568 return;
05fcfafb 1569
1570 -- Ada 2005: nothing to do if the type is one for which there is a
1571 -- partial view that is constrained.
1572
de54c5ab 1573 elsif Ada_Version >= Ada_2005
0d78d2d4 1574 and then Object_Type_Has_Constrained_Partial_View
d41a3f41 1575 (Typ => Base_Type (T_Typ),
1576 Scop => Current_Scope)
05fcfafb 1577 then
1578 return;
ee6ba406 1579 end if;
1580
00f91aef 1581 -- Nothing to do if the type is an Unchecked_Union
1582
1583 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1584 return;
1585 end if;
1586
8d11916f 1587 -- Suppress checks if the subtypes are the same. The check must be
feff2f05 1588 -- preserved in an assignment to a formal, because the constraint is
1589 -- given by the actual.
ee6ba406 1590
1591 if Nkind (Original_Node (N)) /= N_Allocator
1592 and then (No (Lhs)
8143bf7c 1593 or else not Is_Entity_Name (Lhs)
1594 or else No (Param_Entity (Lhs)))
ee6ba406 1595 then
1596 if (Etype (N) = Typ
1597 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1598 and then not Is_Aliased_View (Lhs)
1599 then
1600 return;
1601 end if;
1602
feff2f05 1603 -- We can also eliminate checks on allocators with a subtype mark that
1604 -- coincides with the context type. The context type may be a subtype
1605 -- without a constraint (common case, a generic actual).
ee6ba406 1606
1607 elsif Nkind (Original_Node (N)) = N_Allocator
1608 and then Is_Entity_Name (Expression (Original_Node (N)))
1609 then
1610 declare
9dfe12ae 1611 Alloc_Typ : constant Entity_Id :=
b6341c67 1612 Entity (Expression (Original_Node (N)));
ee6ba406 1613
1614 begin
1615 if Alloc_Typ = T_Typ
1616 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1617 and then Is_Entity_Name (
1618 Subtype_Indication (Parent (T_Typ)))
1619 and then Alloc_Typ = Base_Type (T_Typ))
1620
1621 then
1622 return;
1623 end if;
1624 end;
1625 end if;
1626
feff2f05 1627 -- See if we have a case where the types are both constrained, and all
1628 -- the constraints are constants. In this case, we can do the check
1629 -- successfully at compile time.
ee6ba406 1630
8d11916f 1631 -- We skip this check for the case where the node is rewritten as
d7ec9a29 1632 -- an allocator, because it already carries the context subtype,
1633 -- and extracting the discriminants from the aggregate is messy.
ee6ba406 1634
1635 if Is_Constrained (S_Typ)
1636 and then Nkind (Original_Node (N)) /= N_Allocator
1637 then
1638 declare
1639 DconT : Elmt_Id;
1640 Discr : Entity_Id;
1641 DconS : Elmt_Id;
1642 ItemS : Node_Id;
1643 ItemT : Node_Id;
1644
1645 begin
1646 -- S_Typ may not have discriminants in the case where it is a
feff2f05 1647 -- private type completed by a default discriminated type. In that
8d11916f 1648 -- case, we need to get the constraints from the underlying type.
feff2f05 1649 -- If the underlying type is unconstrained (i.e. has no default
1650 -- discriminants) no check is needed.
ee6ba406 1651
1652 if Has_Discriminants (S_Typ) then
1653 Discr := First_Discriminant (S_Typ);
1654 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1655
1656 else
1657 Discr := First_Discriminant (Underlying_Type (S_Typ));
1658 DconS :=
1659 First_Elmt
1660 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1661
1662 if No (DconS) then
1663 return;
1664 end if;
fccb5da7 1665
1666 -- A further optimization: if T_Typ is derived from S_Typ
1667 -- without imposing a constraint, no check is needed.
1668
1669 if Nkind (Original_Node (Parent (T_Typ))) =
1670 N_Full_Type_Declaration
1671 then
1672 declare
5c61a0ff 1673 Type_Def : constant Node_Id :=
b6341c67 1674 Type_Definition (Original_Node (Parent (T_Typ)));
fccb5da7 1675 begin
1676 if Nkind (Type_Def) = N_Derived_Type_Definition
1677 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1678 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1679 then
1680 return;
1681 end if;
1682 end;
1683 end if;
ee6ba406 1684 end if;
1685
86594966 1686 -- Constraint may appear in full view of type
1687
1688 if Ekind (T_Typ) = E_Private_Subtype
1689 and then Present (Full_View (T_Typ))
1690 then
d7ec9a29 1691 DconT :=
86594966 1692 First_Elmt (Discriminant_Constraint (Full_View (T_Typ)));
86594966 1693 else
d7ec9a29 1694 DconT :=
1695 First_Elmt (Discriminant_Constraint (T_Typ));
86594966 1696 end if;
ee6ba406 1697
1698 while Present (Discr) loop
1699 ItemS := Node (DconS);
1700 ItemT := Node (DconT);
1701
00c403ee 1702 -- For a discriminated component type constrained by the
1703 -- current instance of an enclosing type, there is no
1704 -- applicable discriminant check.
1705
1706 if Nkind (ItemT) = N_Attribute_Reference
1707 and then Is_Access_Type (Etype (ItemT))
1708 and then Is_Entity_Name (Prefix (ItemT))
1709 and then Is_Type (Entity (Prefix (ItemT)))
1710 then
1711 return;
1712 end if;
1713
cc60bd16 1714 -- If the expressions for the discriminants are identical
1715 -- and it is side-effect free (for now just an entity),
1716 -- this may be a shared constraint, e.g. from a subtype
1717 -- without a constraint introduced as a generic actual.
1718 -- Examine other discriminants if any.
1719
1720 if ItemS = ItemT
1721 and then Is_Entity_Name (ItemS)
1722 then
1723 null;
1724
1725 elsif not Is_OK_Static_Expression (ItemS)
1726 or else not Is_OK_Static_Expression (ItemT)
1727 then
1728 exit;
ee6ba406 1729
cc60bd16 1730 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
ee6ba406 1731 if Do_Access then -- needs run-time check.
1732 exit;
1733 else
1734 Apply_Compile_Time_Constraint_Error
cb97ae5c 1735 (N, "incorrect value for discriminant&??",
f15731c4 1736 CE_Discriminant_Check_Failed, Ent => Discr);
ee6ba406 1737 return;
1738 end if;
1739 end if;
1740
1741 Next_Elmt (DconS);
1742 Next_Elmt (DconT);
1743 Next_Discriminant (Discr);
1744 end loop;
1745
1746 if No (Discr) then
1747 return;
1748 end if;
1749 end;
1750 end if;
1751
f0d65dae 1752 -- In GNATprove mode, we do not apply the checks
1753
1754 if GNATprove_Mode then
1755 return;
1756 end if;
1757
ee6ba406 1758 -- Here we need a discriminant check. First build the expression
1759 -- for the comparisons of the discriminants:
1760
1761 -- (n.disc1 /= typ.disc1) or else
1762 -- (n.disc2 /= typ.disc2) or else
1763 -- ...
1764 -- (n.discn /= typ.discn)
1765
1766 Cond := Build_Discriminant_Checks (N, T_Typ);
1767
3cce7f32 1768 -- If Lhs is set and is a parameter, then the condition is guarded by:
1769 -- lhs'constrained and then (condition built above)
ee6ba406 1770
1771 if Present (Param_Entity (Lhs)) then
1772 Cond :=
1773 Make_And_Then (Loc,
1774 Left_Opnd =>
1775 Make_Attribute_Reference (Loc,
1776 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1777 Attribute_Name => Name_Constrained),
1778 Right_Opnd => Cond);
1779 end if;
1780
1781 if Do_Access then
1782 Cond := Guard_Access (Cond, Loc, N);
1783 end if;
1784
1785 Insert_Action (N,
f15731c4 1786 Make_Raise_Constraint_Error (Loc,
1787 Condition => Cond,
1788 Reason => CE_Discriminant_Check_Failed));
ee6ba406 1789 end Apply_Discriminant_Check;
1790
2fe22c69 1791 -------------------------
1792 -- Apply_Divide_Checks --
1793 -------------------------
ee6ba406 1794
2fe22c69 1795 procedure Apply_Divide_Checks (N : Node_Id) is
ee6ba406 1796 Loc : constant Source_Ptr := Sloc (N);
1797 Typ : constant Entity_Id := Etype (N);
1798 Left : constant Node_Id := Left_Opnd (N);
1799 Right : constant Node_Id := Right_Opnd (N);
1800
db415383 1801 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
2fe22c69 1802 -- Current overflow checking mode
1803
ee6ba406 1804 LLB : Uint;
1805 Llo : Uint;
1806 Lhi : Uint;
1807 LOK : Boolean;
1808 Rlo : Uint;
1809 Rhi : Uint;
2fe22c69 1810 ROK : Boolean;
96da3284 1811
1812 pragma Warnings (Off, Lhi);
1813 -- Don't actually use this value
ee6ba406 1814
1815 begin
0df9d43f 1816 -- If we are operating in MINIMIZED or ELIMINATED mode, and we are
1817 -- operating on signed integer types, then the only thing this routine
1818 -- does is to call Apply_Arithmetic_Overflow_Minimized_Eliminated. That
1819 -- procedure will (possibly later on during recursive downward calls),
1820 -- ensure that any needed overflow/division checks are properly applied.
2fe22c69 1821
1822 if Mode in Minimized_Or_Eliminated
2fe22c69 1823 and then Is_Signed_Integer_Type (Typ)
1824 then
1825 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
1826 return;
1827 end if;
1828
1829 -- Proceed here in SUPPRESSED or CHECKED modes
1830
a33565dd 1831 if Expander_Active
13dbf220 1832 and then not Backend_Divide_Checks_On_Target
1833 and then Check_Needed (Right, Division_Check)
ee6ba406 1834 then
9c486805 1835 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
ee6ba406 1836
2fe22c69 1837 -- Deal with division check
ee6ba406 1838
2fe22c69 1839 if Do_Division_Check (N)
1840 and then not Division_Checks_Suppressed (Typ)
1841 then
1842 Apply_Division_Check (N, Rlo, Rhi, ROK);
ee6ba406 1843 end if;
1844
2fe22c69 1845 -- Deal with overflow check
1846
0df9d43f 1847 if Do_Overflow_Check (N)
1848 and then not Overflow_Checks_Suppressed (Etype (N))
1849 then
f3ccbbb3 1850 Set_Do_Overflow_Check (N, False);
1851
2fe22c69 1852 -- Test for extremely annoying case of xxx'First divided by -1
1853 -- for division of signed integer types (only overflow case).
ee6ba406 1854
ee6ba406 1855 if Nkind (N) = N_Op_Divide
1856 and then Is_Signed_Integer_Type (Typ)
1857 then
9c486805 1858 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
ee6ba406 1859 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1860
1861 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
2fe22c69 1862 and then
1863 ((not LOK) or else (Llo = LLB))
ee6ba406 1864 then
f72e7b2a 1865 -- Ensure that expressions are not evaluated twice (once
1866 -- for their runtime checks and once for their regular
1867 -- computation).
1868
1869 Force_Evaluation (Left, Mode => Strict);
1870 Force_Evaluation (Right, Mode => Strict);
1871
ee6ba406 1872 Insert_Action (N,
1873 Make_Raise_Constraint_Error (Loc,
1874 Condition =>
1875 Make_And_Then (Loc,
2fe22c69 1876 Left_Opnd =>
1877 Make_Op_Eq (Loc,
1878 Left_Opnd =>
1879 Duplicate_Subexpr_Move_Checks (Left),
1880 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
ee6ba406 1881
2fe22c69 1882 Right_Opnd =>
1883 Make_Op_Eq (Loc,
1884 Left_Opnd => Duplicate_Subexpr (Right),
1885 Right_Opnd => Make_Integer_Literal (Loc, -1))),
ee6ba406 1886
f15731c4 1887 Reason => CE_Overflow_Check_Failed));
ee6ba406 1888 end if;
1889 end if;
1890 end if;
1891 end if;
2fe22c69 1892 end Apply_Divide_Checks;
1893
1894 --------------------------
1895 -- Apply_Division_Check --
1896 --------------------------
1897
1898 procedure Apply_Division_Check
1899 (N : Node_Id;
1900 Rlo : Uint;
1901 Rhi : Uint;
1902 ROK : Boolean)
1903 is
1904 pragma Assert (Do_Division_Check (N));
1905
1906 Loc : constant Source_Ptr := Sloc (N);
f81a201b 1907 Right : constant Node_Id := Right_Opnd (N);
1908 Opnd : Node_Id;
2fe22c69 1909
1910 begin
a33565dd 1911 if Expander_Active
2fe22c69 1912 and then not Backend_Divide_Checks_On_Target
1913 and then Check_Needed (Right, Division_Check)
2fe22c69 1914
f81a201b 1915 -- See if division by zero possible, and if so generate test. This
1916 -- part of the test is not controlled by the -gnato switch, since it
1917 -- is a Division_Check and not an Overflow_Check.
f3ccbbb3 1918
f81a201b 1919 and then Do_Division_Check (N)
1920 then
1921 Set_Do_Division_Check (N, False);
75f4b34c 1922
f81a201b 1923 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1924 if Is_Floating_Point_Type (Etype (N)) then
1925 Opnd := Make_Real_Literal (Loc, Ureal_0);
1926 else
1927 Opnd := Make_Integer_Literal (Loc, 0);
2fe22c69 1928 end if;
f81a201b 1929
1930 Insert_Action (N,
1931 Make_Raise_Constraint_Error (Loc,
1932 Condition =>
1933 Make_Op_Eq (Loc,
1934 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1935 Right_Opnd => Opnd),
1936 Reason => CE_Divide_By_Zero));
2fe22c69 1937 end if;
1938 end if;
1939 end Apply_Division_Check;
ee6ba406 1940
5329ca64 1941 ----------------------------------
1942 -- Apply_Float_Conversion_Check --
1943 ----------------------------------
1944
feff2f05 1945 -- Let F and I be the source and target types of the conversion. The RM
1946 -- specifies that a floating-point value X is rounded to the nearest
1947 -- integer, with halfway cases being rounded away from zero. The rounded
1948 -- value of X is checked against I'Range.
1949
1950 -- The catch in the above paragraph is that there is no good way to know
1951 -- whether the round-to-integer operation resulted in overflow. A remedy is
1952 -- to perform a range check in the floating-point domain instead, however:
5329ca64 1953
5329ca64 1954 -- (1) The bounds may not be known at compile time
2af58f67 1955 -- (2) The check must take into account rounding or truncation.
5329ca64 1956 -- (3) The range of type I may not be exactly representable in F.
2af58f67 1957 -- (4) For the rounding case, The end-points I'First - 0.5 and
1958 -- I'Last + 0.5 may or may not be in range, depending on the
1959 -- sign of I'First and I'Last.
5329ca64 1960 -- (5) X may be a NaN, which will fail any comparison
1961
2af58f67 1962 -- The following steps correctly convert X with rounding:
feff2f05 1963
5329ca64 1964 -- (1) If either I'First or I'Last is not known at compile time, use
1965 -- I'Base instead of I in the next three steps and perform a
1966 -- regular range check against I'Range after conversion.
1967 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1968 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
2af58f67 1969 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1970 -- In other words, take one of the closest floating-point numbers
1971 -- (which is an integer value) to I'First, and see if it is in
1972 -- range or not.
5329ca64 1973 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1974 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
2af58f67 1975 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
5329ca64 1976 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1977 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1978
2af58f67 1979 -- For the truncating case, replace steps (2) and (3) as follows:
1980 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1981 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1982 -- Lo_OK be True.
1983 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1984 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
141d591a 1985 -- Hi_OK be True.
2af58f67 1986
5329ca64 1987 procedure Apply_Float_Conversion_Check
1988 (Ck_Node : Node_Id;
1989 Target_Typ : Entity_Id)
1990 is
feff2f05 1991 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1992 HB : constant Node_Id := Type_High_Bound (Target_Typ);
5329ca64 1993 Loc : constant Source_Ptr := Sloc (Ck_Node);
1994 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
feff2f05 1995 Target_Base : constant Entity_Id :=
b6341c67 1996 Implementation_Base_Type (Target_Typ);
feff2f05 1997
2af58f67 1998 Par : constant Node_Id := Parent (Ck_Node);
1999 pragma Assert (Nkind (Par) = N_Type_Conversion);
2000 -- Parent of check node, must be a type conversion
2001
2002 Truncate : constant Boolean := Float_Truncate (Par);
2003 Max_Bound : constant Uint :=
b6341c67 2004 UI_Expon
2005 (Machine_Radix_Value (Expr_Type),
2006 Machine_Mantissa_Value (Expr_Type) - 1) - 1;
2af58f67 2007
5329ca64 2008 -- Largest bound, so bound plus or minus half is a machine number of F
2009
feff2f05 2010 Ifirst, Ilast : Uint;
2011 -- Bounds of integer type
2012
2013 Lo, Hi : Ureal;
2014 -- Bounds to check in floating-point domain
5329ca64 2015
feff2f05 2016 Lo_OK, Hi_OK : Boolean;
2017 -- True iff Lo resp. Hi belongs to I'Range
5329ca64 2018
feff2f05 2019 Lo_Chk, Hi_Chk : Node_Id;
2020 -- Expressions that are False iff check fails
2021
2022 Reason : RT_Exception_Code;
5329ca64 2023
2024 begin
41f06abf 2025 -- We do not need checks if we are not generating code (i.e. the full
2026 -- expander is not active). In SPARK mode, we specifically don't want
2027 -- the frontend to expand these checks, which are dealt with directly
2028 -- in the formal verification backend.
2029
a33565dd 2030 if not Expander_Active then
41f06abf 2031 return;
2032 end if;
2033
df1c131a 2034 -- Here we will generate an explicit range check, so we don't want to
2035 -- set the Do_Range check flag, since the range check is taken care of
2036 -- by the code we will generate.
2037
2038 Set_Do_Range_Check (Ck_Node, False);
2039
5329ca64 2040 if not Compile_Time_Known_Value (LB)
2041 or not Compile_Time_Known_Value (HB)
2042 then
2043 declare
feff2f05 2044 -- First check that the value falls in the range of the base type,
2045 -- to prevent overflow during conversion and then perform a
2046 -- regular range check against the (dynamic) bounds.
5329ca64 2047
5329ca64 2048 pragma Assert (Target_Base /= Target_Typ);
5329ca64 2049
46eb6933 2050 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
5329ca64 2051
2052 begin
2053 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
2054 Set_Etype (Temp, Target_Base);
2055
2056 Insert_Action (Parent (Par),
2057 Make_Object_Declaration (Loc,
2058 Defining_Identifier => Temp,
2059 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
2060 Expression => New_Copy_Tree (Par)),
2061 Suppress => All_Checks);
2062
2063 Insert_Action (Par,
2064 Make_Raise_Constraint_Error (Loc,
2065 Condition =>
2066 Make_Not_In (Loc,
2067 Left_Opnd => New_Occurrence_Of (Temp, Loc),
2068 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
2069 Reason => CE_Range_Check_Failed));
2070 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
2071
2072 return;
2073 end;
2074 end if;
2075
7d86aa98 2076 -- Get the (static) bounds of the target type
5329ca64 2077
2078 Ifirst := Expr_Value (LB);
2079 Ilast := Expr_Value (HB);
2080
7d86aa98 2081 -- A simple optimization: if the expression is a universal literal,
2082 -- we can do the comparison with the bounds and the conversion to
2083 -- an integer type statically. The range checks are unchanged.
2084
2085 if Nkind (Ck_Node) = N_Real_Literal
2086 and then Etype (Ck_Node) = Universal_Real
2087 and then Is_Integer_Type (Target_Typ)
7d86aa98 2088 then
2089 declare
2090 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
2091
2092 begin
2093 if Int_Val <= Ilast and then Int_Val >= Ifirst then
2094
4309515d 2095 -- Conversion is safe
7d86aa98 2096
2097 Rewrite (Parent (Ck_Node),
2098 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
2099 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
2100 return;
2101 end if;
2102 end;
2103 end if;
2104
5329ca64 2105 -- Check against lower bound
2106
2af58f67 2107 if Truncate and then Ifirst > 0 then
2108 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
2109 Lo_OK := False;
2110
2111 elsif Truncate then
2112 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
2113 Lo_OK := True;
2114
2115 elsif abs (Ifirst) < Max_Bound then
5329ca64 2116 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
2117 Lo_OK := (Ifirst > 0);
2af58f67 2118
5329ca64 2119 else
2120 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
2121 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
2122 end if;
2123
2124 if Lo_OK then
2125
2126 -- Lo_Chk := (X >= Lo)
2127
2128 Lo_Chk := Make_Op_Ge (Loc,
2129 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2130 Right_Opnd => Make_Real_Literal (Loc, Lo));
2131
2132 else
2133 -- Lo_Chk := (X > Lo)
2134
2135 Lo_Chk := Make_Op_Gt (Loc,
2136 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2137 Right_Opnd => Make_Real_Literal (Loc, Lo));
2138 end if;
2139
2140 -- Check against higher bound
2141
2af58f67 2142 if Truncate and then Ilast < 0 then
2143 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
b2c42753 2144 Hi_OK := False;
2af58f67 2145
2146 elsif Truncate then
2147 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
2148 Hi_OK := True;
2149
2150 elsif abs (Ilast) < Max_Bound then
5329ca64 2151 Hi := UR_From_Uint (Ilast) + Ureal_Half;
2152 Hi_OK := (Ilast < 0);
2153 else
2154 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
2155 Hi_OK := (Hi <= UR_From_Uint (Ilast));
2156 end if;
2157
2158 if Hi_OK then
2159
2160 -- Hi_Chk := (X <= Hi)
2161
2162 Hi_Chk := Make_Op_Le (Loc,
2163 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2164 Right_Opnd => Make_Real_Literal (Loc, Hi));
2165
2166 else
2167 -- Hi_Chk := (X < Hi)
2168
2169 Hi_Chk := Make_Op_Lt (Loc,
2170 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2171 Right_Opnd => Make_Real_Literal (Loc, Hi));
2172 end if;
2173
feff2f05 2174 -- If the bounds of the target type are the same as those of the base
2175 -- type, the check is an overflow check as a range check is not
2176 -- performed in these cases.
5329ca64 2177
2178 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
2179 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
2180 then
2181 Reason := CE_Overflow_Check_Failed;
2182 else
2183 Reason := CE_Range_Check_Failed;
2184 end if;
2185
2186 -- Raise CE if either conditions does not hold
2187
2188 Insert_Action (Ck_Node,
2189 Make_Raise_Constraint_Error (Loc,
05fcfafb 2190 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
5329ca64 2191 Reason => Reason));
2192 end Apply_Float_Conversion_Check;
2193
ee6ba406 2194 ------------------------
2195 -- Apply_Length_Check --
2196 ------------------------
2197
2198 procedure Apply_Length_Check
2199 (Ck_Node : Node_Id;
2200 Target_Typ : Entity_Id;
2201 Source_Typ : Entity_Id := Empty)
2202 is
2203 begin
2204 Apply_Selected_Length_Checks
2205 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2206 end Apply_Length_Check;
2207
3b045963 2208 -------------------------------------
2209 -- Apply_Parameter_Aliasing_Checks --
2210 -------------------------------------
b73adb97 2211
3b045963 2212 procedure Apply_Parameter_Aliasing_Checks
2213 (Call : Node_Id;
2214 Subp : Entity_Id)
2215 is
bb569db0 2216 Loc : constant Source_Ptr := Sloc (Call);
2217
3b045963 2218 function May_Cause_Aliasing
2219 (Formal_1 : Entity_Id;
2220 Formal_2 : Entity_Id) return Boolean;
2221 -- Determine whether two formal parameters can alias each other
2222 -- depending on their modes.
2223
2224 function Original_Actual (N : Node_Id) return Node_Id;
2225 -- The expander may replace an actual with a temporary for the sake of
2226 -- side effect removal. The temporary may hide a potential aliasing as
2227 -- it does not share the address of the actual. This routine attempts
2228 -- to retrieve the original actual.
2229
bb569db0 2230 procedure Overlap_Check
2231 (Actual_1 : Node_Id;
2232 Actual_2 : Node_Id;
2233 Formal_1 : Entity_Id;
2234 Formal_2 : Entity_Id;
2235 Check : in out Node_Id);
2236 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2237 -- If detailed exception messages are enabled, the check is augmented to
2238 -- provide information about the names of the corresponding formals. See
2239 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2240 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2241 -- Check contains all and-ed simple tests generated so far or remains
2242 -- unchanged in the case of detailed exception messaged.
2243
3b045963 2244 ------------------------
2245 -- May_Cause_Aliasing --
2246 ------------------------
b73adb97 2247
3b045963 2248 function May_Cause_Aliasing
4a9e7f0c 2249 (Formal_1 : Entity_Id;
3b045963 2250 Formal_2 : Entity_Id) return Boolean
2251 is
2252 begin
2253 -- The following combination cannot lead to aliasing
2254
2255 -- Formal 1 Formal 2
2256 -- IN IN
2257
2258 if Ekind (Formal_1) = E_In_Parameter
a45d946f 2259 and then
2260 Ekind (Formal_2) = E_In_Parameter
3b045963 2261 then
2262 return False;
2263
2264 -- The following combinations may lead to aliasing
2265
2266 -- Formal 1 Formal 2
2267 -- IN OUT
2268 -- IN IN OUT
2269 -- OUT IN
2270 -- OUT IN OUT
2271 -- OUT OUT
2272
2273 else
2274 return True;
2275 end if;
2276 end May_Cause_Aliasing;
2277
2278 ---------------------
2279 -- Original_Actual --
2280 ---------------------
2281
2282 function Original_Actual (N : Node_Id) return Node_Id is
2283 begin
2284 if Nkind (N) = N_Type_Conversion then
2285 return Expression (N);
2286
2287 -- The expander created a temporary to capture the result of a type
2288 -- conversion where the expression is the real actual.
2289
2290 elsif Nkind (N) = N_Identifier
2291 and then Present (Original_Node (N))
2292 and then Nkind (Original_Node (N)) = N_Type_Conversion
2293 then
2294 return Expression (Original_Node (N));
2295 end if;
2296
2297 return N;
2298 end Original_Actual;
2299
bb569db0 2300 -------------------
2301 -- Overlap_Check --
2302 -------------------
2303
2304 procedure Overlap_Check
2305 (Actual_1 : Node_Id;
2306 Actual_2 : Node_Id;
2307 Formal_1 : Entity_Id;
2308 Formal_2 : Entity_Id;
2309 Check : in out Node_Id)
2310 is
29448168 2311 Cond : Node_Id;
2312 ID_Casing : constant Casing_Type :=
2313 Identifier_Casing (Source_Index (Current_Sem_Unit));
bb569db0 2314
2315 begin
2316 -- Generate:
2317 -- Actual_1'Overlaps_Storage (Actual_2)
2318
2319 Cond :=
2320 Make_Attribute_Reference (Loc,
2321 Prefix => New_Copy_Tree (Original_Actual (Actual_1)),
2322 Attribute_Name => Name_Overlaps_Storage,
2323 Expressions =>
2324 New_List (New_Copy_Tree (Original_Actual (Actual_2))));
2325
2326 -- Generate the following check when detailed exception messages are
2327 -- enabled:
2328
2329 -- if Actual_1'Overlaps_Storage (Actual_2) then
2330 -- raise Program_Error with <detailed message>;
2331 -- end if;
2332
2333 if Exception_Extra_Info then
2334 Start_String;
2335
2336 -- Do not generate location information for internal calls
2337
2338 if Comes_From_Source (Call) then
2339 Store_String_Chars (Build_Location_String (Loc));
2340 Store_String_Char (' ');
2341 end if;
2342
2343 Store_String_Chars ("aliased parameters, actuals for """);
29448168 2344
2345 Get_Name_String (Chars (Formal_1));
2346 Set_Casing (ID_Casing);
2347 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2348
bb569db0 2349 Store_String_Chars (""" and """);
29448168 2350
2351 Get_Name_String (Chars (Formal_2));
2352 Set_Casing (ID_Casing);
2353 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2354
bb569db0 2355 Store_String_Chars (""" overlap");
2356
2357 Insert_Action (Call,
2358 Make_If_Statement (Loc,
2359 Condition => Cond,
2360 Then_Statements => New_List (
2361 Make_Raise_Statement (Loc,
2362 Name =>
83c6c069 2363 New_Occurrence_Of (Standard_Program_Error, Loc),
bb569db0 2364 Expression => Make_String_Literal (Loc, End_String)))));
2365
2366 -- Create a sequence of overlapping checks by and-ing them all
2367 -- together.
2368
2369 else
2370 if No (Check) then
2371 Check := Cond;
2372 else
2373 Check :=
2374 Make_And_Then (Loc,
2375 Left_Opnd => Check,
2376 Right_Opnd => Cond);
2377 end if;
2378 end if;
2379 end Overlap_Check;
2380
3b045963 2381 -- Local variables
2382
15fca308 2383 Actual_1 : Node_Id;
2384 Actual_2 : Node_Id;
2385 Check : Node_Id;
2386 Formal_1 : Entity_Id;
2387 Formal_2 : Entity_Id;
2388 Orig_Act_1 : Node_Id;
2389 Orig_Act_2 : Node_Id;
3b045963 2390
2391 -- Start of processing for Apply_Parameter_Aliasing_Checks
2392
2393 begin
bb569db0 2394 Check := Empty;
3b045963 2395
2396 Actual_1 := First_Actual (Call);
2397 Formal_1 := First_Formal (Subp);
2398 while Present (Actual_1) and then Present (Formal_1) loop
15fca308 2399 Orig_Act_1 := Original_Actual (Actual_1);
3b045963 2400
2401 -- Ensure that the actual is an object that is not passed by value.
2402 -- Elementary types are always passed by value, therefore actuals of
747426db 2403 -- such types cannot lead to aliasing. An aggregate is an object in
2404 -- Ada 2012, but an actual that is an aggregate cannot overlap with
4dc3174c 2405 -- another actual. A type that is By_Reference (such as an array of
2406 -- controlled types) is not subject to the check because any update
2407 -- will be done in place and a subsequent read will always see the
2408 -- correct value, see RM 6.2 (12/3).
3b045963 2409
15fca308 2410 if Nkind (Orig_Act_1) = N_Aggregate
2411 or else (Nkind (Orig_Act_1) = N_Qualified_Expression
2412 and then Nkind (Expression (Orig_Act_1)) = N_Aggregate)
747426db 2413 then
2414 null;
2415
15fca308 2416 elsif Is_Object_Reference (Orig_Act_1)
2417 and then not Is_Elementary_Type (Etype (Orig_Act_1))
2418 and then not Is_By_Reference_Type (Etype (Orig_Act_1))
3b045963 2419 then
2420 Actual_2 := Next_Actual (Actual_1);
2421 Formal_2 := Next_Formal (Formal_1);
2422 while Present (Actual_2) and then Present (Formal_2) loop
15fca308 2423 Orig_Act_2 := Original_Actual (Actual_2);
3b045963 2424
2425 -- The other actual we are testing against must also denote
2426 -- a non pass-by-value object. Generate the check only when
2427 -- the mode of the two formals may lead to aliasing.
2428
15fca308 2429 if Is_Object_Reference (Orig_Act_2)
2430 and then not Is_Elementary_Type (Etype (Orig_Act_2))
3b045963 2431 and then May_Cause_Aliasing (Formal_1, Formal_2)
2432 then
72f889fa 2433 Remove_Side_Effects (Actual_1);
2434 Remove_Side_Effects (Actual_2);
2435
bb569db0 2436 Overlap_Check
2437 (Actual_1 => Actual_1,
2438 Actual_2 => Actual_2,
2439 Formal_1 => Formal_1,
2440 Formal_2 => Formal_2,
2441 Check => Check);
3b045963 2442 end if;
2443
2444 Next_Actual (Actual_2);
2445 Next_Formal (Formal_2);
2446 end loop;
2447 end if;
2448
2449 Next_Actual (Actual_1);
2450 Next_Formal (Formal_1);
2451 end loop;
2452
bb569db0 2453 -- Place a simple check right before the call
3b045963 2454
bb569db0 2455 if Present (Check) and then not Exception_Extra_Info then
3b045963 2456 Insert_Action (Call,
2457 Make_Raise_Program_Error (Loc,
bb569db0 2458 Condition => Check,
2459 Reason => PE_Aliased_Parameters));
3b045963 2460 end if;
2461 end Apply_Parameter_Aliasing_Checks;
2462
2463 -------------------------------------
2464 -- Apply_Parameter_Validity_Checks --
2465 -------------------------------------
2466
2467 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id) is
2468 Subp_Decl : Node_Id;
b73adb97 2469
4a9e7f0c 2470 procedure Add_Validity_Check
ed695684 2471 (Formal : Entity_Id;
2472 Prag_Nam : Name_Id;
4a9e7f0c 2473 For_Result : Boolean := False);
7a5b8c31 2474 -- Add a single 'Valid[_Scalars] check which verifies the initialization
ed695684 2475 -- of Formal. Prag_Nam denotes the pre or post condition pragma name.
4a9e7f0c 2476 -- Set flag For_Result when to verify the result of a function.
b73adb97 2477
b73adb97 2478 ------------------------
2479 -- Add_Validity_Check --
2480 ------------------------
2481
2482 procedure Add_Validity_Check
ed695684 2483 (Formal : Entity_Id;
2484 Prag_Nam : Name_Id;
b73adb97 2485 For_Result : Boolean := False)
2486 is
ed695684 2487 procedure Build_Pre_Post_Condition (Expr : Node_Id);
2488 -- Create a pre/postcondition pragma that tests expression Expr
2489
2490 ------------------------------
2491 -- Build_Pre_Post_Condition --
2492 ------------------------------
2493
2494 procedure Build_Pre_Post_Condition (Expr : Node_Id) is
2495 Loc : constant Source_Ptr := Sloc (Subp);
2496 Decls : List_Id;
2497 Prag : Node_Id;
2498
2499 begin
2500 Prag :=
2501 Make_Pragma (Loc,
c33cb5ff 2502 Chars => Prag_Nam,
ed695684 2503 Pragma_Argument_Associations => New_List (
2504 Make_Pragma_Argument_Association (Loc,
2505 Chars => Name_Check,
2506 Expression => Expr)));
2507
2508 -- Add a message unless exception messages are suppressed
2509
2510 if not Exception_Locations_Suppressed then
2511 Append_To (Pragma_Argument_Associations (Prag),
2512 Make_Pragma_Argument_Association (Loc,
2513 Chars => Name_Message,
2514 Expression =>
2515 Make_String_Literal (Loc,
2516 Strval => "failed "
2517 & Get_Name_String (Prag_Nam)
2518 & " from "
2519 & Build_Location_String (Loc))));
2520 end if;
2521
2522 -- Insert the pragma in the tree
2523
2524 if Nkind (Parent (Subp_Decl)) = N_Compilation_Unit then
2525 Add_Global_Declaration (Prag);
2526 Analyze (Prag);
2527
2528 -- PPC pragmas associated with subprogram bodies must be inserted
2529 -- in the declarative part of the body.
2530
2531 elsif Nkind (Subp_Decl) = N_Subprogram_Body then
2532 Decls := Declarations (Subp_Decl);
2533
2534 if No (Decls) then
2535 Decls := New_List;
2536 Set_Declarations (Subp_Decl, Decls);
2537 end if;
2538
2539 Prepend_To (Decls, Prag);
2540 Analyze (Prag);
2541
2542 -- For subprogram declarations insert the PPC pragma right after
2543 -- the declarative node.
2544
2545 else
2546 Insert_After_And_Analyze (Subp_Decl, Prag);
2547 end if;
2548 end Build_Pre_Post_Condition;
2549
2550 -- Local variables
2551
4a9e7f0c 2552 Loc : constant Source_Ptr := Sloc (Subp);
ed695684 2553 Typ : constant Entity_Id := Etype (Formal);
b73adb97 2554 Check : Node_Id;
2555 Nam : Name_Id;
2556
ed695684 2557 -- Start of processing for Add_Validity_Check
2558
b73adb97 2559 begin
9916a361 2560 -- For scalars, generate 'Valid test
b73adb97 2561
2562 if Is_Scalar_Type (Typ) then
2563 Nam := Name_Valid;
9916a361 2564
2565 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2566
2567 elsif Scalar_Part_Present (Typ) then
b73adb97 2568 Nam := Name_Valid_Scalars;
9916a361 2569
2570 -- No test needed for other cases (no scalars to test)
2571
b73adb97 2572 else
2573 return;
2574 end if;
2575
2576 -- Step 1: Create the expression to verify the validity of the
2577 -- context.
2578
ed695684 2579 Check := New_Occurrence_Of (Formal, Loc);
b73adb97 2580
2581 -- When processing a function result, use 'Result. Generate
2582 -- Context'Result
2583
2584 if For_Result then
2585 Check :=
2586 Make_Attribute_Reference (Loc,
2587 Prefix => Check,
2588 Attribute_Name => Name_Result);
2589 end if;
2590
2591 -- Generate:
2592 -- Context['Result]'Valid[_Scalars]
2593
2594 Check :=
2595 Make_Attribute_Reference (Loc,
2596 Prefix => Check,
2597 Attribute_Name => Nam);
2598
4a9e7f0c 2599 -- Step 2: Create a pre or post condition pragma
2600
ed695684 2601 Build_Pre_Post_Condition (Check);
4a9e7f0c 2602 end Add_Validity_Check;
2603
4a9e7f0c 2604 -- Local variables
2605
2606 Formal : Entity_Id;
4a9e7f0c 2607 Subp_Spec : Node_Id;
2608
3b045963 2609 -- Start of processing for Apply_Parameter_Validity_Checks
b73adb97 2610
2611 begin
4a9e7f0c 2612 -- Extract the subprogram specification and declaration nodes
b73adb97 2613
4a9e7f0c 2614 Subp_Spec := Parent (Subp);
a45d946f 2615
4a9e7f0c 2616 if Nkind (Subp_Spec) = N_Defining_Program_Unit_Name then
2617 Subp_Spec := Parent (Subp_Spec);
2618 end if;
a45d946f 2619
4a9e7f0c 2620 Subp_Decl := Parent (Subp_Spec);
9e58d7ed 2621
b73adb97 2622 if not Comes_From_Source (Subp)
4a9e7f0c 2623
2624 -- Do not process formal subprograms because the corresponding actual
2625 -- will receive the proper checks when the instance is analyzed.
2626
2627 or else Is_Formal_Subprogram (Subp)
2628
95ac2d90 2629 -- Do not process imported subprograms since pre and postconditions
a45d946f 2630 -- are never verified on routines coming from a different language.
4a9e7f0c 2631
b73adb97 2632 or else Is_Imported (Subp)
2633 or else Is_Intrinsic_Subprogram (Subp)
4a9e7f0c 2634
a45d946f 2635 -- The PPC pragmas generated by this routine do not correspond to
2636 -- source aspects, therefore they cannot be applied to abstract
2637 -- subprograms.
4a9e7f0c 2638
7c443ae8 2639 or else Nkind (Subp_Decl) = N_Abstract_Subprogram_Declaration
4a9e7f0c 2640
a45d946f 2641 -- Do not consider subprogram renaminds because the renamed entity
2642 -- already has the proper PPC pragmas.
1bd93de5 2643
2644 or else Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
2645
a45d946f 2646 -- Do not process null procedures because there is no benefit of
2647 -- adding the checks to a no action routine.
4a9e7f0c 2648
2649 or else (Nkind (Subp_Spec) = N_Procedure_Specification
a45d946f 2650 and then Null_Present (Subp_Spec))
b73adb97 2651 then
2652 return;
2653 end if;
2654
4a9e7f0c 2655 -- Inspect all the formals applying aliasing and scalar initialization
2656 -- checks where applicable.
b73adb97 2657
2658 Formal := First_Formal (Subp);
2659 while Present (Formal) loop
4a9e7f0c 2660
2661 -- Generate the following scalar initialization checks for each
2662 -- formal parameter:
2663
2664 -- mode IN - Pre => Formal'Valid[_Scalars]
2665 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2666 -- mode OUT - Post => Formal'Valid[_Scalars]
2667
2668 if Check_Validity_Of_Parameters then
2669 if Ekind_In (Formal, E_In_Parameter, E_In_Out_Parameter) then
2670 Add_Validity_Check (Formal, Name_Precondition, False);
2671 end if;
2672
2673 if Ekind_In (Formal, E_In_Out_Parameter, E_Out_Parameter) then
2674 Add_Validity_Check (Formal, Name_Postcondition, False);
2675 end if;
b73adb97 2676 end if;
2677
b73adb97 2678 Next_Formal (Formal);
2679 end loop;
2680
a45d946f 2681 -- Generate following scalar initialization check for function result:
4a9e7f0c 2682
2683 -- Post => Subp'Result'Valid[_Scalars]
b73adb97 2684
a45d946f 2685 if Check_Validity_Of_Parameters and then Ekind (Subp) = E_Function then
4a9e7f0c 2686 Add_Validity_Check (Subp, Name_Postcondition, True);
b73adb97 2687 end if;
3b045963 2688 end Apply_Parameter_Validity_Checks;
b73adb97 2689
7aafae1c 2690 ---------------------------
2691 -- Apply_Predicate_Check --
2692 ---------------------------
2693
e60047e5 2694 procedure Apply_Predicate_Check
2695 (N : Node_Id;
2696 Typ : Entity_Id;
2697 Fun : Entity_Id := Empty)
2698 is
301d5ec3 2699 S : Entity_Id;
9e58d7ed 2700
7aafae1c 2701 begin
da2270e7 2702 if Predicate_Checks_Suppressed (Empty) then
2703 return;
301d5ec3 2704
2c011bc5 2705 elsif Predicates_Ignored (Typ) then
2706 return;
2707
da2270e7 2708 elsif Present (Predicate_Function (Typ)) then
301d5ec3 2709 S := Current_Scope;
9e58d7ed 2710 while Present (S) and then not Is_Subprogram (S) loop
301d5ec3 2711 S := Scope (S);
2712 end loop;
2713
ea822fd4 2714 -- A predicate check does not apply within internally generated
2715 -- subprograms, such as TSS functions.
2716
2717 if Within_Internal_Subprogram then
301d5ec3 2718 return;
22631b41 2719
96a2d100 2720 -- If the check appears within the predicate function itself, it
2721 -- means that the user specified a check whose formal is the
2722 -- predicated subtype itself, rather than some covering type. This
2723 -- is likely to be a common error, and thus deserves a warning.
22631b41 2724
0e9014a7 2725 elsif Present (S) and then S = Predicate_Function (Typ) then
e60047e5 2726 Error_Msg_NE
0c4abd51 2727 ("predicate check includes a call to& that requires a "
2728 & "predicate check??", Parent (N), Fun);
96a2d100 2729 Error_Msg_N
cb97ae5c 2730 ("\this will result in infinite recursion??", Parent (N));
e60047e5 2731
2732 if Is_First_Subtype (Typ) then
2733 Error_Msg_NE
0c4abd51 2734 ("\use an explicit subtype of& to carry the predicate",
e60047e5 2735 Parent (N), Typ);
2736 end if;
2737
96a2d100 2738 Insert_Action (N,
61016a7a 2739 Make_Raise_Storage_Error (Sloc (N),
2740 Reason => SE_Infinite_Recursion));
22631b41 2741
64cc9e5d 2742 -- Here for normal case of predicate active
e6281d47 2743
61016a7a 2744 else
164597c5 2745 -- If the expression is an IN parameter, the predicate will have
2746 -- been applied at the point of call. An additional check would
2747 -- be redundant, or will lead to out-of-scope references if the
2748 -- call appears within an aspect specification for a precondition.
2749
2750 -- However, if the reference is within the body of the subprogram
2751 -- that declares the formal, the predicate can safely be applied,
2752 -- which may be necessary for a nested call whose formal has a
2753 -- different predicate.
2754
2755 if Is_Entity_Name (N)
2756 and then Ekind (Entity (N)) = E_In_Parameter
2757 then
2758 declare
2759 In_Body : Boolean := False;
50948c8a 2760 P : Node_Id := Parent (N);
164597c5 2761
2762 begin
2763 while Present (P) loop
2764 if Nkind (P) = N_Subprogram_Body
2765 and then Corresponding_Spec (P) = Scope (Entity (N))
2766 then
2767 In_Body := True;
2768 exit;
2769 end if;
2770
2771 P := Parent (P);
2772 end loop;
2773
2774 if not In_Body then
2775 return;
2776 end if;
2777 end;
2778 end if;
2779
b04165c4 2780 -- If the type has a static predicate and the expression is known
2781 -- at compile time, see if the expression satisfies the predicate.
3a75f20b 2782
2783 Check_Expression_Against_Static_Predicate (N, Typ);
e6281d47 2784
e34cd69d 2785 if not Expander_Active then
2786 return;
2787 end if;
2788
2789 -- For an entity of the type, generate a call to the predicate
2790 -- function, unless its type is an actual subtype, which is not
2791 -- visible outside of the enclosing subprogram.
2792
2793 if Is_Entity_Name (N)
2794 and then not Is_Actual_Subtype (Typ)
2795 then
da2270e7 2796 Insert_Action (N,
2797 Make_Predicate_Check
2798 (Typ, New_Occurrence_Of (Entity (N), Sloc (N))));
2799
f9906591 2800 -- If the expression is not an entity it may have side effects,
bc885df9 2801 -- and the following call will create an object declaration for
2802 -- it. We disable checks during its analysis, to prevent an
2803 -- infinite recursion.
da2270e7 2804
e3b910d8 2805 -- If the prefix is an aggregate in an assignment, apply the
2806 -- check to the LHS after assignment, rather than create a
2807 -- redundant temporary. This is only necessary in rare cases
2808 -- of array types (including strings) initialized with an
2809 -- aggregate with an "others" clause, either coming from source
2810 -- or generated by an Initialize_Scalars pragma.
2811
2812 elsif Nkind (N) = N_Aggregate
2813 and then Nkind (Parent (N)) = N_Assignment_Statement
2814 then
2815 Insert_Action_After (Parent (N),
2816 Make_Predicate_Check
2817 (Typ, Duplicate_Subexpr (Name (Parent (N)))));
2818
da2270e7 2819 else
2820 Insert_Action (N,
bc885df9 2821 Make_Predicate_Check
2822 (Typ, Duplicate_Subexpr (N)), Suppress => All_Checks);
da2270e7 2823 end if;
301d5ec3 2824 end if;
7aafae1c 2825 end if;
2826 end Apply_Predicate_Check;
2827
ee6ba406 2828 -----------------------
2829 -- Apply_Range_Check --
2830 -----------------------
2831
2832 procedure Apply_Range_Check
2833 (Ck_Node : Node_Id;
2834 Target_Typ : Entity_Id;
2835 Source_Typ : Entity_Id := Empty)
2836 is
2837 begin
2838 Apply_Selected_Range_Checks
2839 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2840 end Apply_Range_Check;
2841
2842 ------------------------------
2843 -- Apply_Scalar_Range_Check --
2844 ------------------------------
2845
feff2f05 2846 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
2847 -- off if it is already set on.
ee6ba406 2848
2849 procedure Apply_Scalar_Range_Check
2850 (Expr : Node_Id;
2851 Target_Typ : Entity_Id;
2852 Source_Typ : Entity_Id := Empty;
2853 Fixed_Int : Boolean := False)
2854 is
2855 Parnt : constant Node_Id := Parent (Expr);
2856 S_Typ : Entity_Id;
2857 Arr : Node_Id := Empty; -- initialize to prevent warning
2858 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
ee6ba406 2859
2860 Is_Subscr_Ref : Boolean;
2861 -- Set true if Expr is a subscript
2862
2863 Is_Unconstrained_Subscr_Ref : Boolean;
2864 -- Set true if Expr is a subscript of an unconstrained array. In this
2865 -- case we do not attempt to do an analysis of the value against the
2866 -- range of the subscript, since we don't know the actual subtype.
2867
2868 Int_Real : Boolean;
feff2f05 2869 -- Set to True if Expr should be regarded as a real value even though
2870 -- the type of Expr might be discrete.
ee6ba406 2871
a0a15971 2872 procedure Bad_Value (Warn : Boolean := False);
2873 -- Procedure called if value is determined to be out of range. Warn is
2874 -- True to force a warning instead of an error, even when SPARK_Mode is
2875 -- On.
ee6ba406 2876
9dfe12ae 2877 ---------------
2878 -- Bad_Value --
2879 ---------------
2880
a0a15971 2881 procedure Bad_Value (Warn : Boolean := False) is
ee6ba406 2882 begin
2883 Apply_Compile_Time_Constraint_Error
cb97ae5c 2884 (Expr, "value not in range of}??", CE_Range_Check_Failed,
a0a15971 2885 Ent => Target_Typ,
2886 Typ => Target_Typ,
2887 Warn => Warn);
ee6ba406 2888 end Bad_Value;
2889
9dfe12ae 2890 -- Start of processing for Apply_Scalar_Range_Check
2891
ee6ba406 2892 begin
2af58f67 2893 -- Return if check obviously not needed
ee6ba406 2894
2af58f67 2895 if
2896 -- Not needed inside generic
ee6ba406 2897
2af58f67 2898 Inside_A_Generic
2899
2900 -- Not needed if previous error
2901
2902 or else Target_Typ = Any_Type
2903 or else Nkind (Expr) = N_Error
2904
2905 -- Not needed for non-scalar type
2906
2907 or else not Is_Scalar_Type (Target_Typ)
2908
2909 -- Not needed if we know node raises CE already
2910
2911 or else Raises_Constraint_Error (Expr)
ee6ba406 2912 then
2913 return;
2914 end if;
2915
2916 -- Now, see if checks are suppressed
2917
2918 Is_Subscr_Ref :=
2919 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
2920
2921 if Is_Subscr_Ref then
2922 Arr := Prefix (Parnt);
2923 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
cce84b09 2924
a3a76ccc 2925 if Is_Access_Type (Arr_Typ) then
245e87df 2926 Arr_Typ := Designated_Type (Arr_Typ);
a3a76ccc 2927 end if;
ee6ba406 2928 end if;
2929
2930 if not Do_Range_Check (Expr) then
2931
2932 -- Subscript reference. Check for Index_Checks suppressed
2933
2934 if Is_Subscr_Ref then
2935
2936 -- Check array type and its base type
2937
2938 if Index_Checks_Suppressed (Arr_Typ)
9dfe12ae 2939 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
ee6ba406 2940 then
2941 return;
2942
2943 -- Check array itself if it is an entity name
2944
2945 elsif Is_Entity_Name (Arr)
9dfe12ae 2946 and then Index_Checks_Suppressed (Entity (Arr))
ee6ba406 2947 then
2948 return;
2949
2950 -- Check expression itself if it is an entity name
2951
2952 elsif Is_Entity_Name (Expr)
9dfe12ae 2953 and then Index_Checks_Suppressed (Entity (Expr))
ee6ba406 2954 then
2955 return;
2956 end if;
2957
2958 -- All other cases, check for Range_Checks suppressed
2959
2960 else
2961 -- Check target type and its base type
2962
2963 if Range_Checks_Suppressed (Target_Typ)
9dfe12ae 2964 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
ee6ba406 2965 then
2966 return;
2967
2968 -- Check expression itself if it is an entity name
2969
2970 elsif Is_Entity_Name (Expr)
9dfe12ae 2971 and then Range_Checks_Suppressed (Entity (Expr))
ee6ba406 2972 then
2973 return;
2974
feff2f05 2975 -- If Expr is part of an assignment statement, then check left
2976 -- side of assignment if it is an entity name.
ee6ba406 2977
2978 elsif Nkind (Parnt) = N_Assignment_Statement
2979 and then Is_Entity_Name (Name (Parnt))
9dfe12ae 2980 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
ee6ba406 2981 then
2982 return;
2983 end if;
2984 end if;
2985 end if;
2986
9dfe12ae 2987 -- Do not set range checks if they are killed
2988
2989 if Nkind (Expr) = N_Unchecked_Type_Conversion
2990 and then Kill_Range_Check (Expr)
2991 then
2992 return;
2993 end if;
2994
2995 -- Do not set range checks for any values from System.Scalar_Values
39a0c1d3 2996 -- since the whole idea of such values is to avoid checking them.
9dfe12ae 2997
2998 if Is_Entity_Name (Expr)
2999 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
3000 then
3001 return;
3002 end if;
3003
ee6ba406 3004 -- Now see if we need a check
3005
3006 if No (Source_Typ) then
3007 S_Typ := Etype (Expr);
3008 else
3009 S_Typ := Source_Typ;
3010 end if;
3011
3012 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
3013 return;
3014 end if;
3015
3016 Is_Unconstrained_Subscr_Ref :=
3017 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
3018
b40670e1 3019 -- Special checks for floating-point type
ee6ba406 3020
b40670e1 3021 if Is_Floating_Point_Type (S_Typ) then
3022
3023 -- Always do a range check if the source type includes infinities and
3024 -- the target type does not include infinities. We do not do this if
3025 -- range checks are killed.
cb388b10 3026 -- If the expression is a literal and the bounds of the type are
3027 -- static constants it may be possible to optimize the check.
b40670e1 3028
3029 if Has_Infinities (S_Typ)
3030 and then not Has_Infinities (Target_Typ)
3031 then
cb388b10 3032 -- If the expression is a literal and the bounds of the type are
3033 -- static constants it may be possible to optimize the check.
3034
3035 if Nkind (Expr) = N_Real_Literal then
3036 declare
3037 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
3038 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
3039
3040 begin
3041 if Compile_Time_Known_Value (Tlo)
3042 and then Compile_Time_Known_Value (Thi)
3043 and then Expr_Value_R (Expr) >= Expr_Value_R (Tlo)
3044 and then Expr_Value_R (Expr) <= Expr_Value_R (Thi)
3045 then
3046 return;
3047 else
3048 Enable_Range_Check (Expr);
3049 end if;
3050 end;
3051
3052 else
3053 Enable_Range_Check (Expr);
3054 end if;
b40670e1 3055 end if;
ee6ba406 3056 end if;
3057
feff2f05 3058 -- Return if we know expression is definitely in the range of the target
3059 -- type as determined by Determine_Range. Right now we only do this for
3060 -- discrete types, and not fixed-point or floating-point types.
ee6ba406 3061
f2a06be9 3062 -- The additional less-precise tests below catch these cases
ee6ba406 3063
54022749 3064 -- In GNATprove_Mode, also deal with the case of a conversion from
3065 -- floating-point to integer. It is only possible because analysis
3066 -- in GNATprove rules out the possibility of a NaN or infinite value.
3067
feff2f05 3068 -- Note: skip this if we are given a source_typ, since the point of
3069 -- supplying a Source_Typ is to stop us looking at the expression.
3070 -- We could sharpen this test to be out parameters only ???
ee6ba406 3071
3072 if Is_Discrete_Type (Target_Typ)
54022749 3073 and then (Is_Discrete_Type (Etype (Expr))
3074 or else (GNATprove_Mode
3075 and then Is_Floating_Point_Type (Etype (Expr))))
ee6ba406 3076 and then not Is_Unconstrained_Subscr_Ref
3077 and then No (Source_Typ)
3078 then
3079 declare
ee6ba406 3080 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
552d7cbc 3081 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
ee6ba406 3082
3083 begin
3084 if Compile_Time_Known_Value (Tlo)
3085 and then Compile_Time_Known_Value (Thi)
3086 then
9dfe12ae 3087 declare
5bb74b99 3088 OK : Boolean := False; -- initialize to prevent warning
9dfe12ae 3089 Hiv : constant Uint := Expr_Value (Thi);
552d7cbc 3090 Lov : constant Uint := Expr_Value (Tlo);
5bb74b99 3091 Hi : Uint := No_Uint;
3092 Lo : Uint := No_Uint;
ee6ba406 3093
9dfe12ae 3094 begin
552d7cbc 3095 -- If range is null, we for sure have a constraint error (we
3096 -- don't even need to look at the value involved, since all
3097 -- possible values will raise CE).
9dfe12ae 3098
3099 if Lov > Hiv then
f4f2bf51 3100
a0a15971 3101 -- When SPARK_Mode is On, force a warning instead of
3102 -- an error in that case, as this likely corresponds
3103 -- to deactivated code.
3104
3105 Bad_Value (Warn => SPARK_Mode = On);
3106
3107 -- In GNATprove mode, we enable the range check so that
3108 -- GNATprove will issue a message if it cannot be proved.
f4f2bf51 3109
3110 if GNATprove_Mode then
3111 Enable_Range_Check (Expr);
f4f2bf51 3112 end if;
3113
9dfe12ae 3114 return;
3115 end if;
3116
3117 -- Otherwise determine range of value
3118
54022749 3119 if Is_Discrete_Type (Etype (Expr)) then
552d7cbc 3120 Determine_Range
3121 (Expr, OK, Lo, Hi, Assume_Valid => True);
54022749 3122
3123 -- When converting a float to an integer type, determine the
3124 -- range in real first, and then convert the bounds using
3125 -- UR_To_Uint which correctly rounds away from zero when
3126 -- half way between two integers, as required by normal
3127 -- Ada 95 rounding semantics. It is only possible because
3128 -- analysis in GNATprove rules out the possibility of a NaN
3129 -- or infinite value.
3130
3131 elsif GNATprove_Mode
3132 and then Is_Floating_Point_Type (Etype (Expr))
3133 then
3134 declare
54022749 3135 Hir : Ureal;
552d7cbc 3136 Lor : Ureal;
3137
54022749 3138 begin
552d7cbc 3139 Determine_Range_R
3140 (Expr, OK, Lor, Hir, Assume_Valid => True);
54022749 3141
3142 if OK then
3143 Lo := UR_To_Uint (Lor);
3144 Hi := UR_To_Uint (Hir);
3145 end if;
3146 end;
3147 end if;
9dfe12ae 3148
3149 if OK then
3150
3151 -- If definitely in range, all OK
ee6ba406 3152
ee6ba406 3153 if Lo >= Lov and then Hi <= Hiv then
3154 return;
3155
9dfe12ae 3156 -- If definitely not in range, warn
3157
ee6ba406 3158 elsif Lov > Hi or else Hiv < Lo then
e9dae6c3 3159
c59854a0 3160 -- Ignore out of range values for System.Priority in
3161 -- CodePeer mode since the actual target compiler may
3162 -- provide a wider range.
3163
3164 if not CodePeer_Mode
3165 or else Target_Typ /= RTE (RE_Priority)
3166 then
3167 Bad_Value;
3168 end if;
3169
ee6ba406 3170 return;
9dfe12ae 3171
3172 -- Otherwise we don't know
3173
3174 else
3175 null;
ee6ba406 3176 end if;
9dfe12ae 3177 end if;
3178 end;
ee6ba406 3179 end if;
3180 end;
3181 end if;
3182
3183 Int_Real :=
3184 Is_Floating_Point_Type (S_Typ)
3185 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
3186
3187 -- Check if we can determine at compile time whether Expr is in the
9dfe12ae 3188 -- range of the target type. Note that if S_Typ is within the bounds
3189 -- of Target_Typ then this must be the case. This check is meaningful
3190 -- only if this is not a conversion between integer and real types.
ee6ba406 3191
3192 if not Is_Unconstrained_Subscr_Ref
b40670e1 3193 and then Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
ee6ba406 3194 and then
7a1dabb3 3195 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
ac5f5168 3196
3197 -- Also check if the expression itself is in the range of the
3198 -- target type if it is a known at compile time value. We skip
3199 -- this test if S_Typ is set since for OUT and IN OUT parameters
3200 -- the Expr itself is not relevant to the checking.
3201
ee6ba406 3202 or else
ac5f5168 3203 (No (Source_Typ)
3204 and then Is_In_Range (Expr, Target_Typ,
3205 Assume_Valid => True,
3206 Fixed_Int => Fixed_Int,
3207 Int_Real => Int_Real)))
ee6ba406 3208 then
3209 return;
3210
9c486805 3211 elsif Is_Out_Of_Range (Expr, Target_Typ,
3212 Assume_Valid => True,
3213 Fixed_Int => Fixed_Int,
3214 Int_Real => Int_Real)
3215 then
ee6ba406 3216 Bad_Value;
3217 return;
3218
b40670e1 3219 -- Floating-point case
feff2f05 3220 -- In the floating-point case, we only do range checks if the type is
3221 -- constrained. We definitely do NOT want range checks for unconstrained
29d958a7 3222 -- types, since we want to have infinities, except when
3223 -- Check_Float_Overflow is set.
ee6ba406 3224
9dfe12ae 3225 elsif Is_Floating_Point_Type (S_Typ) then
29d958a7 3226 if Is_Constrained (S_Typ) or else Check_Float_Overflow then
9dfe12ae 3227 Enable_Range_Check (Expr);
3228 end if;
ee6ba406 3229
9dfe12ae 3230 -- For all other cases we enable a range check unconditionally
ee6ba406 3231
3232 else
3233 Enable_Range_Check (Expr);
3234 return;
3235 end if;
ee6ba406 3236 end Apply_Scalar_Range_Check;
3237
3238 ----------------------------------
3239 -- Apply_Selected_Length_Checks --
3240 ----------------------------------
3241
3242 procedure Apply_Selected_Length_Checks
3243 (Ck_Node : Node_Id;
3244 Target_Typ : Entity_Id;
3245 Source_Typ : Entity_Id;
3246 Do_Static : Boolean)
3247 is
2b4f2458 3248 Checks_On : constant Boolean :=
3249 not Index_Checks_Suppressed (Target_Typ)
3250 or else
3251 not Length_Checks_Suppressed (Target_Typ);
3252
3253 Loc : constant Source_Ptr := Sloc (Ck_Node);
3254
ee6ba406 3255 Cond : Node_Id;
ee6ba406 3256 R_Cno : Node_Id;
2b4f2458 3257 R_Result : Check_Result;
ee6ba406 3258
3259 begin
18cb6d78 3260 -- Only apply checks when generating code
f0d65dae 3261
4098232e 3262 -- Note: this means that we lose some useful warnings if the expander
f0d65dae 3263 -- is not active.
4098232e 3264
18cb6d78 3265 if not Expander_Active then
ee6ba406 3266 return;
3267 end if;
3268
3269 R_Result :=
3270 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3271
3272 for J in 1 .. 2 loop
ee6ba406 3273 R_Cno := R_Result (J);
3274 exit when No (R_Cno);
3275
3276 -- A length check may mention an Itype which is attached to a
3277 -- subsequent node. At the top level in a package this can cause
3278 -- an order-of-elaboration problem, so we make sure that the itype
3279 -- is referenced now.
3280
3281 if Ekind (Current_Scope) = E_Package
3282 and then Is_Compilation_Unit (Current_Scope)
3283 then
3284 Ensure_Defined (Target_Typ, Ck_Node);
3285
3286 if Present (Source_Typ) then
3287 Ensure_Defined (Source_Typ, Ck_Node);
3288
3289 elsif Is_Itype (Etype (Ck_Node)) then
3290 Ensure_Defined (Etype (Ck_Node), Ck_Node);
3291 end if;
3292 end if;
3293
feff2f05 3294 -- If the item is a conditional raise of constraint error, then have
3295 -- a look at what check is being performed and ???
ee6ba406 3296
3297 if Nkind (R_Cno) = N_Raise_Constraint_Error
3298 and then Present (Condition (R_Cno))
3299 then
3300 Cond := Condition (R_Cno);
3301
0577b0b1 3302 -- Case where node does not now have a dynamic check
ee6ba406 3303
0577b0b1 3304 if not Has_Dynamic_Length_Check (Ck_Node) then
3305
3306 -- If checks are on, just insert the check
3307
3308 if Checks_On then
3309 Insert_Action (Ck_Node, R_Cno);
3310
3311 if not Do_Static then
3312 Set_Has_Dynamic_Length_Check (Ck_Node);
3313 end if;
3314
3315 -- If checks are off, then analyze the length check after
3316 -- temporarily attaching it to the tree in case the relevant
6fb3c314 3317 -- condition can be evaluated at compile time. We still want a
0577b0b1 3318 -- compile time warning in this case.
3319
3320 else
3321 Set_Parent (R_Cno, Ck_Node);
3322 Analyze (R_Cno);
ee6ba406 3323 end if;
ee6ba406 3324 end if;
3325
3326 -- Output a warning if the condition is known to be True
3327
3328 if Is_Entity_Name (Cond)
3329 and then Entity (Cond) = Standard_True
3330 then
3331 Apply_Compile_Time_Constraint_Error
cb97ae5c 3332 (Ck_Node, "wrong length for array of}??",
f15731c4 3333 CE_Length_Check_Failed,
ee6ba406 3334 Ent => Target_Typ,
3335 Typ => Target_Typ);
3336
3337 -- If we were only doing a static check, or if checks are not
3338 -- on, then we want to delete the check, since it is not needed.
3339 -- We do this by replacing the if statement by a null statement
3340
3341 elsif Do_Static or else not Checks_On then
00c403ee 3342 Remove_Warning_Messages (R_Cno);
ee6ba406 3343 Rewrite (R_Cno, Make_Null_Statement (Loc));
3344 end if;
3345
3346 else
3347 Install_Static_Check (R_Cno, Loc);
3348 end if;
ee6ba406 3349 end loop;
ee6ba406 3350 end Apply_Selected_Length_Checks;
3351
3352 ---------------------------------
3353 -- Apply_Selected_Range_Checks --
3354 ---------------------------------
3355
3356 procedure Apply_Selected_Range_Checks
3357 (Ck_Node : Node_Id;
3358 Target_Typ : Entity_Id;
3359 Source_Typ : Entity_Id;
3360 Do_Static : Boolean)
3361 is
ee6ba406 3362 Checks_On : constant Boolean :=
f9bcba0d 3363 not Index_Checks_Suppressed (Target_Typ)
5372d110 3364 or else
3365 not Range_Checks_Suppressed (Target_Typ);
f9bcba0d 3366
2b4f2458 3367 Loc : constant Source_Ptr := Sloc (Ck_Node);
3368
f9bcba0d 3369 Cond : Node_Id;
3370 R_Cno : Node_Id;
3371 R_Result : Check_Result;
ee6ba406 3372
3373 begin
f0d65dae 3374 -- Only apply checks when generating code. In GNATprove mode, we do not
3375 -- apply the checks, but we still call Selected_Range_Checks to possibly
3376 -- issue errors on SPARK code when a run-time error can be detected at
3377 -- compile time.
3378
3379 if not GNATprove_Mode then
3380 if not Expander_Active or not Checks_On then
3381 return;
3382 end if;
ee6ba406 3383 end if;
3384
3385 R_Result :=
3386 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3387
f0d65dae 3388 if GNATprove_Mode then
3389 return;
3390 end if;
3391
ee6ba406 3392 for J in 1 .. 2 loop
ee6ba406 3393 R_Cno := R_Result (J);
3394 exit when No (R_Cno);
3395
f9bcba0d 3396 -- The range check requires runtime evaluation. Depending on what its
3397 -- triggering condition is, the check may be converted into a compile
3398 -- time constraint check.
ee6ba406 3399
3400 if Nkind (R_Cno) = N_Raise_Constraint_Error
3401 and then Present (Condition (R_Cno))
3402 then
3403 Cond := Condition (R_Cno);
3404
f9bcba0d 3405 -- Insert the range check before the related context. Note that
3406 -- this action analyses the triggering condition.
ee6ba406 3407
f9bcba0d 3408 Insert_Action (Ck_Node, R_Cno);
3409
3410 -- This old code doesn't make sense, why is the context flagged as
3411 -- requiring dynamic range checks now in the middle of generating
3412 -- them ???
3413
3414 if not Do_Static then
3415 Set_Has_Dynamic_Range_Check (Ck_Node);
ee6ba406 3416 end if;
3417
f9bcba0d 3418 -- The triggering condition evaluates to True, the range check
3419 -- can be converted into a compile time constraint check.
ee6ba406 3420
3421 if Is_Entity_Name (Cond)
3422 and then Entity (Cond) = Standard_True
3423 then
feff2f05 3424 -- Since an N_Range is technically not an expression, we have
3425 -- to set one of the bounds to C_E and then just flag the
3426 -- N_Range. The warning message will point to the lower bound
3427 -- and complain about a range, which seems OK.
ee6ba406 3428
3429 if Nkind (Ck_Node) = N_Range then
3430 Apply_Compile_Time_Constraint_Error
5372d110 3431 (Low_Bound (Ck_Node),
3432 "static range out of bounds of}??",
f15731c4 3433 CE_Range_Check_Failed,
ee6ba406 3434 Ent => Target_Typ,
3435 Typ => Target_Typ);
3436
3437 Set_Raises_Constraint_Error (Ck_Node);
3438
3439 else
3440 Apply_Compile_Time_Constraint_Error
5372d110 3441 (Ck_Node,
1581f2d7 3442 "static value out of range of}??",
f15731c4 3443 CE_Range_Check_Failed,
ee6ba406 3444 Ent => Target_Typ,
3445 Typ => Target_Typ);
3446 end if;
3447
3448 -- If we were only doing a static check, or if checks are not
3449 -- on, then we want to delete the check, since it is not needed.
3450 -- We do this by replacing the if statement by a null statement
3451
3fabf0ca 3452 elsif Do_Static then
00c403ee 3453 Remove_Warning_Messages (R_Cno);
ee6ba406 3454 Rewrite (R_Cno, Make_Null_Statement (Loc));
3455 end if;
3456
4ee78e36 3457 -- The range check raises Constraint_Error explicitly
f9bcba0d 3458
ee6ba406 3459 else
3460 Install_Static_Check (R_Cno, Loc);
3461 end if;
ee6ba406 3462 end loop;
ee6ba406 3463 end Apply_Selected_Range_Checks;
3464
3465 -------------------------------
3466 -- Apply_Static_Length_Check --
3467 -------------------------------
3468
3469 procedure Apply_Static_Length_Check
3470 (Expr : Node_Id;
3471 Target_Typ : Entity_Id;
3472 Source_Typ : Entity_Id := Empty)
3473 is
3474 begin
3475 Apply_Selected_Length_Checks
3476 (Expr, Target_Typ, Source_Typ, Do_Static => True);
3477 end Apply_Static_Length_Check;
3478
3479 -------------------------------------
3480 -- Apply_Subscript_Validity_Checks --
3481 -------------------------------------
3482
3483 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
3484 Sub : Node_Id;
3485
3486 begin
3487 pragma Assert (Nkind (Expr) = N_Indexed_Component);
3488
3489 -- Loop through subscripts
3490
3491 Sub := First (Expressions (Expr));
3492 while Present (Sub) loop
3493
feff2f05 3494 -- Check one subscript. Note that we do not worry about enumeration
3495 -- type with holes, since we will convert the value to a Pos value
3496 -- for the subscript, and that convert will do the necessary validity
3497 -- check.
ee6ba406 3498
3499 Ensure_Valid (Sub, Holes_OK => True);
3500
3501 -- Move to next subscript
3502
3503 Sub := Next (Sub);
3504 end loop;
3505 end Apply_Subscript_Validity_Checks;
3506
3507 ----------------------------------
3508 -- Apply_Type_Conversion_Checks --
3509 ----------------------------------
3510
3511 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
3512 Target_Type : constant Entity_Id := Etype (N);
3513 Target_Base : constant Entity_Id := Base_Type (Target_Type);
9dfe12ae 3514 Expr : constant Node_Id := Expression (N);
f4532fe1 3515
3516 Expr_Type : constant Entity_Id := Underlying_Type (Etype (Expr));
141d591a 3517 -- Note: if Etype (Expr) is a private type without discriminants, its
3518 -- full view might have discriminants with defaults, so we need the
3519 -- full view here to retrieve the constraints.
ee6ba406 3520
3521 begin
3522 if Inside_A_Generic then
3523 return;
3524
f15731c4 3525 -- Skip these checks if serious errors detected, there are some nasty
ee6ba406 3526 -- situations of incomplete trees that blow things up.
3527
f15731c4 3528 elsif Serious_Errors_Detected > 0 then
ee6ba406 3529 return;
3530
ea822fd4 3531 -- Never generate discriminant checks for Unchecked_Union types
3532
3533 elsif Present (Expr_Type)
3534 and then Is_Unchecked_Union (Expr_Type)
3535 then
3536 return;
3537
feff2f05 3538 -- Scalar type conversions of the form Target_Type (Expr) require a
3539 -- range check if we cannot be sure that Expr is in the base type of
3540 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3541 -- are not quite the same condition from an implementation point of
3542 -- view, but clearly the second includes the first.
ee6ba406 3543
3544 elsif Is_Scalar_Type (Target_Type) then
3545 declare
3546 Conv_OK : constant Boolean := Conversion_OK (N);
feff2f05 3547 -- If the Conversion_OK flag on the type conversion is set and no
ea822fd4 3548 -- floating-point type is involved in the type conversion then
3549 -- fixed-point values must be read as integral values.
ee6ba406 3550
5329ca64 3551 Float_To_Int : constant Boolean :=
b6341c67 3552 Is_Floating_Point_Type (Expr_Type)
3553 and then Is_Integer_Type (Target_Type);
5329ca64 3554
ee6ba406 3555 begin
ee6ba406 3556 if not Overflow_Checks_Suppressed (Target_Base)
0df9d43f 3557 and then not Overflow_Checks_Suppressed (Target_Type)
e254d721 3558 and then not
7a1dabb3 3559 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
5329ca64 3560 and then not Float_To_Int
ee6ba406 3561 then
4642b679 3562 -- A small optimization: the attribute 'Pos applied to an
c59f2b2d 3563 -- enumeration type has a known range, even though its type is
3564 -- Universal_Integer. So in numeric conversions it is usually
3565 -- within range of the target integer type. Use the static
3566 -- bounds of the base types to check. Disable this optimization
3567 -- in case of a generic formal discrete type, because we don't
3568 -- necessarily know the upper bound yet.
259716a0 3569
3570 if Nkind (Expr) = N_Attribute_Reference
3571 and then Attribute_Name (Expr) = Name_Pos
3572 and then Is_Enumeration_Type (Etype (Prefix (Expr)))
c59f2b2d 3573 and then not Is_Generic_Type (Etype (Prefix (Expr)))
259716a0 3574 and then Is_Integer_Type (Target_Type)
3575 then
3576 declare
4642b679 3577 Enum_T : constant Entity_Id :=
3578 Root_Type (Etype (Prefix (Expr)));
3579 Int_T : constant Entity_Id := Base_Type (Target_Type);
3580 Last_I : constant Uint :=
3581 Intval (High_Bound (Scalar_Range (Int_T)));
3582 Last_E : Uint;
259716a0 3583
3584 begin
4642b679 3585 -- Character types have no explicit literals, so we use
259716a0 3586 -- the known number of characters in the type.
3587
3588 if Root_Type (Enum_T) = Standard_Character then
3589 Last_E := UI_From_Int (255);
3590
3591 elsif Enum_T = Standard_Wide_Character
3592 or else Enum_T = Standard_Wide_Wide_Character
3593 then
3594 Last_E := UI_From_Int (65535);
3595
3596 else
4642b679 3597 Last_E :=
3598 Enumeration_Pos
259716a0 3599 (Entity (High_Bound (Scalar_Range (Enum_T))));
3600 end if;
3601
3602 if Last_E <= Last_I then
3603 null;
3604
3605 else
3606 Activate_Overflow_Check (N);
3607 end if;
3608 end;
3609
3610 else
3611 Activate_Overflow_Check (N);
3612 end if;
ee6ba406 3613 end if;
3614
3615 if not Range_Checks_Suppressed (Target_Type)
3616 and then not Range_Checks_Suppressed (Expr_Type)
3617 then
54022749 3618 if Float_To_Int
3619 and then not GNATprove_Mode
3620 then
5329ca64 3621 Apply_Float_Conversion_Check (Expr, Target_Type);
f81a201b 3622
5329ca64 3623 else
7d97dbc9 3624 -- Conversions involving fixed-point types are expanded
3625 -- separately, and do not need a Range_Check flag, except
c6056dd1 3626 -- in GNATprove_Mode, where the explicit constraint check
3627 -- will not be generated.
7d97dbc9 3628
95c16286 3629 if GNATprove_Mode
72c474b5 3630 or else (not Is_Fixed_Point_Type (Expr_Type)
3631 and then not Is_Fixed_Point_Type (Target_Type))
7d97dbc9 3632 then
3633 Apply_Scalar_Range_Check
3634 (Expr, Target_Type, Fixed_Int => Conv_OK);
3635
3636 else
72c474b5 3637 Set_Do_Range_Check (Expr, False);
7d97dbc9 3638 end if;
798afddc 3639
3640 -- If the target type has predicates, we need to indicate
ea822fd4 3641 -- the need for a check, even if Determine_Range finds that
3642 -- the value is within bounds. This may be the case e.g for
3643 -- a division with a constant denominator.
798afddc 3644
3645 if Has_Predicates (Target_Type) then
3646 Enable_Range_Check (Expr);
3647 end if;
5329ca64 3648 end if;
ee6ba406 3649 end if;
3650 end;
3651
3652 elsif Comes_From_Source (N)
f40f9731 3653 and then not Discriminant_Checks_Suppressed (Target_Type)
ee6ba406 3654 and then Is_Record_Type (Target_Type)
3655 and then Is_Derived_Type (Target_Type)
3656 and then not Is_Tagged_Type (Target_Type)
3657 and then not Is_Constrained (Target_Type)
9dfe12ae 3658 and then Present (Stored_Constraint (Target_Type))
ee6ba406 3659 then
141d591a 3660 -- An unconstrained derived type may have inherited discriminant.
9dfe12ae 3661 -- Build an actual discriminant constraint list using the stored
ee6ba406 3662 -- constraint, to verify that the expression of the parent type
ea822fd4 3663 -- satisfies the constraints imposed by the (unconstrained) derived
3664 -- type. This applies to value conversions, not to view conversions
3665 -- of tagged types.
ee6ba406 3666
3667 declare
9dfe12ae 3668 Loc : constant Source_Ptr := Sloc (N);
3669 Cond : Node_Id;
3670 Constraint : Elmt_Id;
3671 Discr_Value : Node_Id;
3672 Discr : Entity_Id;
3673
3674 New_Constraints : constant Elist_Id := New_Elmt_List;
3675 Old_Constraints : constant Elist_Id :=
b6341c67 3676 Discriminant_Constraint (Expr_Type);
ee6ba406 3677
3678 begin
9dfe12ae 3679 Constraint := First_Elmt (Stored_Constraint (Target_Type));
ee6ba406 3680 while Present (Constraint) loop
3681 Discr_Value := Node (Constraint);
3682
3683 if Is_Entity_Name (Discr_Value)
3684 and then Ekind (Entity (Discr_Value)) = E_Discriminant
3685 then
3686 Discr := Corresponding_Discriminant (Entity (Discr_Value));
3687
3688 if Present (Discr)
3689 and then Scope (Discr) = Base_Type (Expr_Type)
3690 then
3691 -- Parent is constrained by new discriminant. Obtain
feff2f05 3692 -- Value of original discriminant in expression. If the
3693 -- new discriminant has been used to constrain more than
3694 -- one of the stored discriminants, this will provide the
3695 -- required consistency check.
ee6ba406 3696
55868293 3697 Append_Elmt
3698 (Make_Selected_Component (Loc,
3699 Prefix =>
9dfe12ae 3700 Duplicate_Subexpr_No_Checks
3701 (Expr, Name_Req => True),
ee6ba406 3702 Selector_Name =>
3703 Make_Identifier (Loc, Chars (Discr))),
55868293 3704 New_Constraints);
ee6ba406 3705
3706 else
3707 -- Discriminant of more remote ancestor ???
3708
3709 return;
3710 end if;
3711
feff2f05 3712 -- Derived type definition has an explicit value for this
3713 -- stored discriminant.
ee6ba406 3714
3715 else
3716 Append_Elmt
9dfe12ae 3717 (Duplicate_Subexpr_No_Checks (Discr_Value),
3718 New_Constraints);
ee6ba406 3719 end if;
3720
3721 Next_Elmt (Constraint);
3722 end loop;
3723
3724 -- Use the unconstrained expression type to retrieve the
3725 -- discriminants of the parent, and apply momentarily the
3726 -- discriminant constraint synthesized above.
3727
3728 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
3729 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
3730 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
3731
3732 Insert_Action (N,
f15731c4 3733 Make_Raise_Constraint_Error (Loc,
3734 Condition => Cond,
3735 Reason => CE_Discriminant_Check_Failed));
ee6ba406 3736 end;
3737
175a6969 3738 -- For arrays, checks are set now, but conversions are applied during
3739 -- expansion, to take into accounts changes of representation. The
3740 -- checks become range checks on the base type or length checks on the
3741 -- subtype, depending on whether the target type is unconstrained or
8e802312 3742 -- constrained. Note that the range check is put on the expression of a
3743 -- type conversion, while the length check is put on the type conversion
3744 -- itself.
175a6969 3745
3746 elsif Is_Array_Type (Target_Type) then
3747 if Is_Constrained (Target_Type) then
3748 Set_Do_Length_Check (N);
3749 else
3750 Set_Do_Range_Check (Expr);
3751 end if;
ee6ba406 3752 end if;
ee6ba406 3753 end Apply_Type_Conversion_Checks;
3754
3755 ----------------------------------------------
3756 -- Apply_Universal_Integer_Attribute_Checks --
3757 ----------------------------------------------
3758
3759 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
3760 Loc : constant Source_Ptr := Sloc (N);
3761 Typ : constant Entity_Id := Etype (N);
3762
3763 begin
3764 if Inside_A_Generic then
3765 return;
3766
3767 -- Nothing to do if checks are suppressed
3768
3769 elsif Range_Checks_Suppressed (Typ)
3770 and then Overflow_Checks_Suppressed (Typ)
3771 then
3772 return;
3773
3774 -- Nothing to do if the attribute does not come from source. The
3775 -- internal attributes we generate of this type do not need checks,
3776 -- and furthermore the attempt to check them causes some circular
3777 -- elaboration orders when dealing with packed types.
3778
3779 elsif not Comes_From_Source (N) then
3780 return;
3781
9dfe12ae 3782 -- If the prefix is a selected component that depends on a discriminant
3783 -- the check may improperly expose a discriminant instead of using
3784 -- the bounds of the object itself. Set the type of the attribute to
3785 -- the base type of the context, so that a check will be imposed when
3786 -- needed (e.g. if the node appears as an index).
3787
3788 elsif Nkind (Prefix (N)) = N_Selected_Component
3789 and then Ekind (Typ) = E_Signed_Integer_Subtype
3790 and then Depends_On_Discriminant (Scalar_Range (Typ))
3791 then
3792 Set_Etype (N, Base_Type (Typ));
3793
feff2f05 3794 -- Otherwise, replace the attribute node with a type conversion node
3795 -- whose expression is the attribute, retyped to universal integer, and
3796 -- whose subtype mark is the target type. The call to analyze this
3797 -- conversion will set range and overflow checks as required for proper
3798 -- detection of an out of range value.
ee6ba406 3799
3800 else
3801 Set_Etype (N, Universal_Integer);
3802 Set_Analyzed (N, True);
3803
3804 Rewrite (N,
3805 Make_Type_Conversion (Loc,
3806 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
3807 Expression => Relocate_Node (N)));
3808
3809 Analyze_And_Resolve (N, Typ);
3810 return;
3811 end if;
ee6ba406 3812 end Apply_Universal_Integer_Attribute_Checks;
3813
07c191b0 3814 -------------------------------------
3815 -- Atomic_Synchronization_Disabled --
3816 -------------------------------------
3817
3818 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3819 -- using a bogus check called Atomic_Synchronization. This is to make it
3820 -- more convenient to get exactly the same semantics as [Un]Suppress.
3821
3822 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean is
3823 begin
b444f81d 3824 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3825 -- looks enabled, since it is never disabled.
3826
3827 if Debug_Flag_Dot_E then
3828 return False;
3829
3830 -- If debug flag d.d is set then always return True, i.e. all atomic
3831 -- sync looks disabled, since it always tests True.
3832
3833 elsif Debug_Flag_Dot_D then
3834 return True;
3835
3836 -- If entity present, then check result for that entity
3837
3838 elsif Present (E) and then Checks_May_Be_Suppressed (E) then
07c191b0 3839 return Is_Check_Suppressed (E, Atomic_Synchronization);
b444f81d 3840
3841 -- Otherwise result depends on current scope setting
3842
07c191b0 3843 else
fafc6b97 3844 return Scope_Suppress.Suppress (Atomic_Synchronization);
07c191b0 3845 end if;
3846 end Atomic_Synchronization_Disabled;
3847
ee6ba406 3848 -------------------------------
3849 -- Build_Discriminant_Checks --
3850 -------------------------------
3851
3852 function Build_Discriminant_Checks
3853 (N : Node_Id;
314a23b6 3854 T_Typ : Entity_Id) return Node_Id
ee6ba406 3855 is
3856 Loc : constant Source_Ptr := Sloc (N);
3857 Cond : Node_Id;
3858 Disc : Elmt_Id;
3859 Disc_Ent : Entity_Id;
9dfe12ae 3860 Dref : Node_Id;
ee6ba406 3861 Dval : Node_Id;
3862
84d0d4a5 3863 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
3864
bacd5059 3865 --------------------------------
3866 -- Aggregate_Discriminant_Val --
3867 --------------------------------
84d0d4a5 3868
3869 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
3870 Assoc : Node_Id;
3871
3872 begin
feff2f05 3873 -- The aggregate has been normalized with named associations. We use
3874 -- the Chars field to locate the discriminant to take into account
3875 -- discriminants in derived types, which carry the same name as those
3876 -- in the parent.
84d0d4a5 3877
3878 Assoc := First (Component_Associations (N));
3879 while Present (Assoc) loop
3880 if Chars (First (Choices (Assoc))) = Chars (Disc) then
3881 return Expression (Assoc);
3882 else
3883 Next (Assoc);
3884 end if;
3885 end loop;
3886
3887 -- Discriminant must have been found in the loop above
3888
3889 raise Program_Error;
3890 end Aggregate_Discriminant_Val;
3891
3892 -- Start of processing for Build_Discriminant_Checks
3893
ee6ba406 3894 begin
84d0d4a5 3895 -- Loop through discriminants evolving the condition
3896
ee6ba406 3897 Cond := Empty;
3898 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
3899
9dfe12ae 3900 -- For a fully private type, use the discriminants of the parent type
ee6ba406 3901
3902 if Is_Private_Type (T_Typ)
3903 and then No (Full_View (T_Typ))
3904 then
3905 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
3906 else
3907 Disc_Ent := First_Discriminant (T_Typ);
3908 end if;
3909
3910 while Present (Disc) loop
ee6ba406 3911 Dval := Node (Disc);
3912
3913 if Nkind (Dval) = N_Identifier
3914 and then Ekind (Entity (Dval)) = E_Discriminant
3915 then
3916 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
3917 else
9dfe12ae 3918 Dval := Duplicate_Subexpr_No_Checks (Dval);
ee6ba406 3919 end if;
3920
00f91aef 3921 -- If we have an Unchecked_Union node, we can infer the discriminants
3922 -- of the node.
9dfe12ae 3923
00f91aef 3924 if Is_Unchecked_Union (Base_Type (T_Typ)) then
3925 Dref := New_Copy (
3926 Get_Discriminant_Value (
3927 First_Discriminant (T_Typ),
3928 T_Typ,
3929 Stored_Constraint (T_Typ)));
3930
84d0d4a5 3931 elsif Nkind (N) = N_Aggregate then
3932 Dref :=
3933 Duplicate_Subexpr_No_Checks
3934 (Aggregate_Discriminant_Val (Disc_Ent));
3935
00f91aef 3936 else
3937 Dref :=
3938 Make_Selected_Component (Loc,
20cf157b 3939 Prefix =>
00f91aef 3940 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
20cf157b 3941 Selector_Name => Make_Identifier (Loc, Chars (Disc_Ent)));
00f91aef 3942
3943 Set_Is_In_Discriminant_Check (Dref);
3944 end if;
9dfe12ae 3945
ee6ba406 3946 Evolve_Or_Else (Cond,
3947 Make_Op_Ne (Loc,
20cf157b 3948 Left_Opnd => Dref,
ee6ba406 3949 Right_Opnd => Dval));
3950
3951 Next_Elmt (Disc);
3952 Next_Discriminant (Disc_Ent);
3953 end loop;
3954
3955 return Cond;
3956 end Build_Discriminant_Checks;
3957
13dbf220 3958 ------------------
3959 -- Check_Needed --
3960 ------------------
3961
3962 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
3963 N : Node_Id;
3964 P : Node_Id;
3965 K : Node_Kind;
3966 L : Node_Id;
3967 R : Node_Id;
3968
9b2068d4 3969 function Left_Expression (Op : Node_Id) return Node_Id;
3970 -- Return the relevant expression from the left operand of the given
3971 -- short circuit form: this is LO itself, except if LO is a qualified
3972 -- expression, a type conversion, or an expression with actions, in
3973 -- which case this is Left_Expression (Expression (LO)).
3974
3975 ---------------------
3976 -- Left_Expression --
3977 ---------------------
3978
3979 function Left_Expression (Op : Node_Id) return Node_Id is
3980 LE : Node_Id := Left_Opnd (Op);
3981 begin
20cf157b 3982 while Nkind_In (LE, N_Qualified_Expression,
3983 N_Type_Conversion,
3984 N_Expression_With_Actions)
9b2068d4 3985 loop
3986 LE := Expression (LE);
3987 end loop;
3988
3989 return LE;
3990 end Left_Expression;
3991
3992 -- Start of processing for Check_Needed
3993
13dbf220 3994 begin
3995 -- Always check if not simple entity
3996
3997 if Nkind (Nod) not in N_Has_Entity
3998 or else not Comes_From_Source (Nod)
3999 then
4000 return True;
4001 end if;
4002
4003 -- Look up tree for short circuit
4004
4005 N := Nod;
4006 loop
4007 P := Parent (N);
4008 K := Nkind (P);
4009
7b17e51b 4010 -- Done if out of subexpression (note that we allow generated stuff
4011 -- such as itype declarations in this context, to keep the loop going
4012 -- since we may well have generated such stuff in complex situations.
4013 -- Also done if no parent (probably an error condition, but no point
39a0c1d3 4014 -- in behaving nasty if we find it).
7b17e51b 4015
4016 if No (P)
4017 or else (K not in N_Subexpr and then Comes_From_Source (P))
4018 then
13dbf220 4019 return True;
4020
7b17e51b 4021 -- Or/Or Else case, where test is part of the right operand, or is
4022 -- part of one of the actions associated with the right operand, and
4023 -- the left operand is an equality test.
13dbf220 4024
7b17e51b 4025 elsif K = N_Op_Or then
13dbf220 4026 exit when N = Right_Opnd (P)
9b2068d4 4027 and then Nkind (Left_Expression (P)) = N_Op_Eq;
13dbf220 4028
7b17e51b 4029 elsif K = N_Or_Else then
4030 exit when (N = Right_Opnd (P)
4031 or else
4032 (Is_List_Member (N)
4033 and then List_Containing (N) = Actions (P)))
9b2068d4 4034 and then Nkind (Left_Expression (P)) = N_Op_Eq;
13dbf220 4035
7b17e51b 4036 -- Similar test for the And/And then case, where the left operand
4037 -- is an inequality test.
4038
4039 elsif K = N_Op_And then
13dbf220 4040 exit when N = Right_Opnd (P)
9b2068d4 4041 and then Nkind (Left_Expression (P)) = N_Op_Ne;
7b17e51b 4042
4043 elsif K = N_And_Then then
4044 exit when (N = Right_Opnd (P)
4045 or else
4046 (Is_List_Member (N)
20cf157b 4047 and then List_Containing (N) = Actions (P)))
9b2068d4 4048 and then Nkind (Left_Expression (P)) = N_Op_Ne;
13dbf220 4049 end if;
4050
4051 N := P;
4052 end loop;
4053
4054 -- If we fall through the loop, then we have a conditional with an
9b2068d4 4055 -- appropriate test as its left operand, so look further.
4056
4057 L := Left_Expression (P);
4058
4059 -- L is an "=" or "/=" operator: extract its operands
13dbf220 4060
13dbf220 4061 R := Right_Opnd (L);
4062 L := Left_Opnd (L);
4063
4064 -- Left operand of test must match original variable
4065
20cf157b 4066 if Nkind (L) not in N_Has_Entity or else Entity (L) /= Entity (Nod) then
13dbf220 4067 return True;
4068 end if;
4069
2af58f67 4070 -- Right operand of test must be key value (zero or null)
13dbf220 4071
4072 case Check is
4073 when Access_Check =>
2af58f67 4074 if not Known_Null (R) then
13dbf220 4075 return True;
4076 end if;
4077
4078 when Division_Check =>
4079 if not Compile_Time_Known_Value (R)
4080 or else Expr_Value (R) /= Uint_0
4081 then
4082 return True;
4083 end if;
2af58f67 4084
4085 when others =>
4086 raise Program_Error;
13dbf220 4087 end case;
4088
4089 -- Here we have the optimizable case, warn if not short-circuited
4090
4091 if K = N_Op_And or else K = N_Op_Or then
c4968aa2 4092 Error_Msg_Warn := SPARK_Mode /= On;
4098232e 4093
13dbf220 4094 case Check is
4095 when Access_Check =>
4098232e 4096 if GNATprove_Mode then
4097 Error_Msg_N
4098 ("Constraint_Error might have been raised (access check)",
4099 Parent (Nod));
4100 else
4101 Error_Msg_N
4102 ("Constraint_Error may be raised (access check)??",
4103 Parent (Nod));
4104 end if;
4105
13dbf220 4106 when Division_Check =>
4098232e 4107 if GNATprove_Mode then
4108 Error_Msg_N
4109 ("Constraint_Error might have been raised (zero divide)",
4110 Parent (Nod));
4111 else
4112 Error_Msg_N
4113 ("Constraint_Error may be raised (zero divide)??",
4114 Parent (Nod));
4115 end if;
2af58f67 4116
4117 when others =>
4118 raise Program_Error;
13dbf220 4119 end case;
4120
4121 if K = N_Op_And then
e977c0cf 4122 Error_Msg_N -- CODEFIX
cb97ae5c 4123 ("use `AND THEN` instead of AND??", P);
13dbf220 4124 else
e977c0cf 4125 Error_Msg_N -- CODEFIX
cb97ae5c 4126 ("use `OR ELSE` instead of OR??", P);
13dbf220 4127 end if;
4128
6fb3c314 4129 -- If not short-circuited, we need the check
13dbf220 4130
4131 return True;
4132
4133 -- If short-circuited, we can omit the check
4134
4135 else
4136 return False;
4137 end if;
4138 end Check_Needed;
4139
ee6ba406 4140 -----------------------------------
4141 -- Check_Valid_Lvalue_Subscripts --
4142 -----------------------------------
4143
4144 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
4145 begin
4146 -- Skip this if range checks are suppressed
4147
4148 if Range_Checks_Suppressed (Etype (Expr)) then
4149 return;
4150
feff2f05 4151 -- Only do this check for expressions that come from source. We assume
4152 -- that expander generated assignments explicitly include any necessary
4153 -- checks. Note that this is not just an optimization, it avoids
39a0c1d3 4154 -- infinite recursions.
ee6ba406 4155
4156 elsif not Comes_From_Source (Expr) then
4157 return;
4158
4159 -- For a selected component, check the prefix
4160
4161 elsif Nkind (Expr) = N_Selected_Component then
4162 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4163 return;
4164
4165 -- Case of indexed component
4166
4167 elsif Nkind (Expr) = N_Indexed_Component then
4168 Apply_Subscript_Validity_Checks (Expr);
4169
feff2f05 4170 -- Prefix may itself be or contain an indexed component, and these
4171 -- subscripts need checking as well.
ee6ba406 4172
4173 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4174 end if;
4175 end Check_Valid_Lvalue_Subscripts;
4176
fa7497e8 4177 ----------------------------------
4178 -- Null_Exclusion_Static_Checks --
4179 ----------------------------------
4180
e9998840 4181 procedure Null_Exclusion_Static_Checks
69733a9a 4182 (N : Node_Id;
4183 Comp : Node_Id := Empty;
4184 Array_Comp : Boolean := False)
e9998840 4185 is
b1e656fb 4186 Has_Null : constant Boolean := Has_Null_Exclusion (N);
4187 Kind : constant Node_Kind := Nkind (N);
4188 Error_Nod : Node_Id;
4189 Expr : Node_Id;
4190 Typ : Entity_Id;
fa7497e8 4191
13dbf220 4192 begin
0577b0b1 4193 pragma Assert
b1e656fb 4194 (Nkind_In (Kind, N_Component_Declaration,
4195 N_Discriminant_Specification,
4196 N_Function_Specification,
4197 N_Object_Declaration,
4198 N_Parameter_Specification));
0577b0b1 4199
b1e656fb 4200 if Kind = N_Function_Specification then
0577b0b1 4201 Typ := Etype (Defining_Entity (N));
4202 else
4203 Typ := Etype (Defining_Identifier (N));
4204 end if;
fa7497e8 4205
b1e656fb 4206 case Kind is
13dbf220 4207 when N_Component_Declaration =>
4208 if Present (Access_Definition (Component_Definition (N))) then
b1e656fb 4209 Error_Nod := Component_Definition (N);
13dbf220 4210 else
b1e656fb 4211 Error_Nod := Subtype_Indication (Component_Definition (N));
13dbf220 4212 end if;
5329ca64 4213
0577b0b1 4214 when N_Discriminant_Specification =>
b1e656fb 4215 Error_Nod := Discriminant_Type (N);
0577b0b1 4216
4217 when N_Function_Specification =>
b1e656fb 4218 Error_Nod := Result_Definition (N);
0577b0b1 4219
4220 when N_Object_Declaration =>
b1e656fb 4221 Error_Nod := Object_Definition (N);
0577b0b1 4222
4223 when N_Parameter_Specification =>
b1e656fb 4224 Error_Nod := Parameter_Type (N);
0577b0b1 4225
13dbf220 4226 when others =>
4227 raise Program_Error;
4228 end case;
5329ca64 4229
0577b0b1 4230 if Has_Null then
5329ca64 4231
0577b0b1 4232 -- Enforce legality rule 3.10 (13): A null exclusion can only be
4233 -- applied to an access [sub]type.
5329ca64 4234
0577b0b1 4235 if not Is_Access_Type (Typ) then
503f7fd3 4236 Error_Msg_N
b1e656fb 4237 ("`NOT NULL` allowed only for an access type", Error_Nod);
5329ca64 4238
feff2f05 4239 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
0577b0b1 4240 -- be applied to a [sub]type that does not exclude null already.
4241
b1e656fb 4242 elsif Can_Never_Be_Null (Typ) and then Comes_From_Source (Typ) then
503f7fd3 4243 Error_Msg_NE
00c403ee 4244 ("`NOT NULL` not allowed (& already excludes null)",
b1e656fb 4245 Error_Nod, Typ);
0577b0b1 4246 end if;
13dbf220 4247 end if;
5329ca64 4248
cc60bd16 4249 -- Check that null-excluding objects are always initialized, except for
4250 -- deferred constants, for which the expression will appear in the full
4251 -- declaration.
13dbf220 4252
b1e656fb 4253 if Kind = N_Object_Declaration
84d0d4a5 4254 and then No (Expression (N))
cc60bd16 4255 and then not Constant_Present (N)
feff2f05 4256 and then not No_Initialization (N)
13dbf220 4257 then
e9998840 4258 if Present (Comp) then
4259
b1ff36e7 4260 -- Specialize the warning message to indicate that we are dealing
e9998840 4261 -- with an uninitialized composite object that has a defaulted
4262 -- null-excluding component.
4263
4264 Error_Msg_Name_1 := Chars (Defining_Identifier (Comp));
4265 Error_Msg_Name_2 := Chars (Defining_Identifier (N));
4266
69733a9a 4267 Discard_Node
4268 (Compile_Time_Constraint_Error
4269 (N => N,
4270 Msg =>
4271 "(Ada 2005) null-excluding component % of object % must "
4272 & "be initialized??",
4273 Ent => Defining_Identifier (Comp)));
4274
4275 -- This is a case of an array with null-excluding components, so
4276 -- indicate that in the warning.
4277
4278 elsif Array_Comp then
4279 Discard_Node
4280 (Compile_Time_Constraint_Error
4281 (N => N,
4282 Msg =>
4283 "(Ada 2005) null-excluding array components must "
4284 & "be initialized??",
4285 Ent => Defining_Identifier (N)));
4286
4287 -- Normal case of object of a null-excluding access type
b1ff36e7 4288
e9998840 4289 else
69733a9a 4290 -- Add an expression that assigns null. This node is needed by
4291 -- Apply_Compile_Time_Constraint_Error, which will replace this
4292 -- with a Constraint_Error node.
4293
4294 Set_Expression (N, Make_Null (Sloc (N)));
4295 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
4296
e9998840 4297 Apply_Compile_Time_Constraint_Error
4298 (N => Expression (N),
4299 Msg =>
4300 "(Ada 2005) null-excluding objects must be initialized??",
4301 Reason => CE_Null_Not_Allowed);
4302 end if;
13dbf220 4303 end if;
5329ca64 4304
cc60bd16 4305 -- Check that a null-excluding component, formal or object is not being
4306 -- assigned a null value. Otherwise generate a warning message and
2c145f84 4307 -- replace Expression (N) by an N_Constraint_Error node.
13dbf220 4308
b1e656fb 4309 if Kind /= N_Function_Specification then
0577b0b1 4310 Expr := Expression (N);
5329ca64 4311
2af58f67 4312 if Present (Expr) and then Known_Null (Expr) then
b1e656fb 4313 case Kind is
99378362 4314 when N_Component_Declaration
4315 | N_Discriminant_Specification
4316 =>
7189d17f 4317 Apply_Compile_Time_Constraint_Error
0577b0b1 4318 (N => Expr,
99378362 4319 Msg =>
4320 "(Ada 2005) null not allowed in null-excluding "
4321 & "components??",
0577b0b1 4322 Reason => CE_Null_Not_Allowed);
5329ca64 4323
0577b0b1 4324 when N_Object_Declaration =>
7189d17f 4325 Apply_Compile_Time_Constraint_Error
0577b0b1 4326 (N => Expr,
99378362 4327 Msg =>
4328 "(Ada 2005) null not allowed in null-excluding "
4329 & "objects??",
0577b0b1 4330 Reason => CE_Null_Not_Allowed);
5329ca64 4331
0577b0b1 4332 when N_Parameter_Specification =>
7189d17f 4333 Apply_Compile_Time_Constraint_Error
0577b0b1 4334 (N => Expr,
99378362 4335 Msg =>
4336 "(Ada 2005) null not allowed in null-excluding "
4337 & "formals??",
0577b0b1 4338 Reason => CE_Null_Not_Allowed);
13dbf220 4339
4340 when others =>
4341 null;
5329ca64 4342 end case;
4343 end if;
0577b0b1 4344 end if;
fa7497e8 4345 end Null_Exclusion_Static_Checks;
4346
9dfe12ae 4347 ----------------------------------
4348 -- Conditional_Statements_Begin --
4349 ----------------------------------
4350
4351 procedure Conditional_Statements_Begin is
4352 begin
4353 Saved_Checks_TOS := Saved_Checks_TOS + 1;
4354
feff2f05 4355 -- If stack overflows, kill all checks, that way we know to simply reset
4356 -- the number of saved checks to zero on return. This should never occur
4357 -- in practice.
9dfe12ae 4358
4359 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4360 Kill_All_Checks;
4361
feff2f05 4362 -- In the normal case, we just make a new stack entry saving the current
4363 -- number of saved checks for a later restore.
9dfe12ae 4364
4365 else
4366 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
4367
4368 if Debug_Flag_CC then
4369 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
4370 Num_Saved_Checks);
4371 end if;
4372 end if;
4373 end Conditional_Statements_Begin;
4374
4375 --------------------------------
4376 -- Conditional_Statements_End --
4377 --------------------------------
4378
4379 procedure Conditional_Statements_End is
4380 begin
4381 pragma Assert (Saved_Checks_TOS > 0);
4382
feff2f05 4383 -- If the saved checks stack overflowed, then we killed all checks, so
4384 -- setting the number of saved checks back to zero is correct. This
4385 -- should never occur in practice.
9dfe12ae 4386
4387 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4388 Num_Saved_Checks := 0;
4389
feff2f05 4390 -- In the normal case, restore the number of saved checks from the top
4391 -- stack entry.
9dfe12ae 4392
4393 else
4394 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
20cf157b 4395
9dfe12ae 4396 if Debug_Flag_CC then
4397 w ("Conditional_Statements_End: Num_Saved_Checks = ",
4398 Num_Saved_Checks);
4399 end if;
4400 end if;
4401
4402 Saved_Checks_TOS := Saved_Checks_TOS - 1;
4403 end Conditional_Statements_End;
4404
3cce7f32 4405 -------------------------
4406 -- Convert_From_Bignum --
4407 -------------------------
4408
4409 function Convert_From_Bignum (N : Node_Id) return Node_Id is
4410 Loc : constant Source_Ptr := Sloc (N);
4411
4412 begin
4413 pragma Assert (Is_RTE (Etype (N), RE_Bignum));
4414
4415 -- Construct call From Bignum
4416
4417 return
4418 Make_Function_Call (Loc,
4419 Name =>
4420 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
4421 Parameter_Associations => New_List (Relocate_Node (N)));
4422 end Convert_From_Bignum;
4423
4424 -----------------------
4425 -- Convert_To_Bignum --
4426 -----------------------
4427
4428 function Convert_To_Bignum (N : Node_Id) return Node_Id is
4429 Loc : constant Source_Ptr := Sloc (N);
4430
4431 begin
0326b4d4 4432 -- Nothing to do if Bignum already except call Relocate_Node
3cce7f32 4433
4434 if Is_RTE (Etype (N), RE_Bignum) then
4435 return Relocate_Node (N);
4436
21a55437 4437 -- Otherwise construct call to To_Bignum, converting the operand to the
4438 -- required Long_Long_Integer form.
3cce7f32 4439
4440 else
4441 pragma Assert (Is_Signed_Integer_Type (Etype (N)));
4442 return
4443 Make_Function_Call (Loc,
4444 Name =>
4445 New_Occurrence_Of (RTE (RE_To_Bignum), Loc),
4446 Parameter_Associations => New_List (
4447 Convert_To (Standard_Long_Long_Integer, Relocate_Node (N))));
4448 end if;
4449 end Convert_To_Bignum;
4450
ee6ba406 4451 ---------------------
4452 -- Determine_Range --
4453 ---------------------
4454
6af1bdbc 4455 Cache_Size : constant := 2 ** 10;
ee6ba406 4456 type Cache_Index is range 0 .. Cache_Size - 1;
39a0c1d3 4457 -- Determine size of below cache (power of 2 is more efficient)
ee6ba406 4458
7ac8c2b1 4459 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
4460 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
4461 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
4462 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
4463 Determine_Range_Cache_Lo_R : array (Cache_Index) of Ureal;
4464 Determine_Range_Cache_Hi_R : array (Cache_Index) of Ureal;
feff2f05 4465 -- The above arrays are used to implement a small direct cache for
7ac8c2b1 4466 -- Determine_Range and Determine_Range_R calls. Because of the way these
4467 -- subprograms recursively traces subexpressions, and because overflow
4468 -- checking calls the routine on the way up the tree, a quadratic behavior
4469 -- can otherwise be encountered in large expressions. The cache entry for
4470 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4471 -- by checking the actual node value stored there. The Range_Cache_V array
4472 -- records the setting of Assume_Valid for the cache entry.
ee6ba406 4473
4474 procedure Determine_Range
9c486805 4475 (N : Node_Id;
4476 OK : out Boolean;
4477 Lo : out Uint;
4478 Hi : out Uint;
4479 Assume_Valid : Boolean := False)
ee6ba406 4480 is
e254d721 4481 Typ : Entity_Id := Etype (N);
4482 -- Type to use, may get reset to base type for possibly invalid entity
8880be85 4483
4484 Lo_Left : Uint;
4485 Hi_Left : Uint;
4486 -- Lo and Hi bounds of left operand
ee6ba406 4487
5bb74b99 4488 Lo_Right : Uint := No_Uint;
4489 Hi_Right : Uint := No_Uint;
8880be85 4490 -- Lo and Hi bounds of right (or only) operand
4491
4492 Bound : Node_Id;
4493 -- Temp variable used to hold a bound node
4494
4495 Hbound : Uint;
4496 -- High bound of base type of expression
4497
4498 Lor : Uint;
4499 Hir : Uint;
4500 -- Refined values for low and high bounds, after tightening
4501
4502 OK1 : Boolean;
4503 -- Used in lower level calls to indicate if call succeeded
4504
4505 Cindex : Cache_Index;
4506 -- Used to search cache
ee6ba406 4507
094ed68e 4508 Btyp : Entity_Id;
4509 -- Base type
4510
ee6ba406 4511 function OK_Operands return Boolean;
4512 -- Used for binary operators. Determines the ranges of the left and
4513 -- right operands, and if they are both OK, returns True, and puts
341bd953 4514 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
ee6ba406 4515
4516 -----------------
4517 -- OK_Operands --
4518 -----------------
4519
4520 function OK_Operands return Boolean is
4521 begin
9c486805 4522 Determine_Range
4523 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
ee6ba406 4524
4525 if not OK1 then
4526 return False;
4527 end if;
4528
9c486805 4529 Determine_Range
4530 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
ee6ba406 4531 return OK1;
4532 end OK_Operands;
4533
4534 -- Start of processing for Determine_Range
4535
4536 begin
e12b2502 4537 -- Prevent junk warnings by initializing range variables
4538
4539 Lo := No_Uint;
4540 Hi := No_Uint;
4541 Lor := No_Uint;
4542 Hir := No_Uint;
4543
87bdc21d 4544 -- For temporary constants internally generated to remove side effects
4545 -- we must use the corresponding expression to determine the range of
e12b2502 4546 -- the expression. But note that the expander can also generate
4547 -- constants in other cases, including deferred constants.
87bdc21d 4548
4549 if Is_Entity_Name (N)
4550 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
4551 and then Ekind (Entity (N)) = E_Constant
4552 and then Is_Internal_Name (Chars (Entity (N)))
4553 then
e12b2502 4554 if Present (Expression (Parent (Entity (N)))) then
4555 Determine_Range
4556 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
87bdc21d 4557
e12b2502 4558 elsif Present (Full_View (Entity (N))) then
4559 Determine_Range
4560 (Expression (Parent (Full_View (Entity (N)))),
4561 OK, Lo, Hi, Assume_Valid);
ee6ba406 4562
e12b2502 4563 else
4564 OK := False;
4565 end if;
4566 return;
4567 end if;
ee6ba406 4568
a781c0fc 4569 -- If type is not defined, we can't determine its range
ee6ba406 4570
a781c0fc 4571 if No (Typ)
4572
4573 -- We don't deal with anything except discrete types
4574
4575 or else not Is_Discrete_Type (Typ)
4576
cdfda0e3 4577 -- Don't deal with enumerated types with non-standard representation
4578
4579 or else (Is_Enumeration_Type (Typ)
4580 and then Present (Enum_Pos_To_Rep (Base_Type (Typ))))
4581
a781c0fc 4582 -- Ignore type for which an error has been posted, since range in
4583 -- this case may well be a bogosity deriving from the error. Also
4584 -- ignore if error posted on the reference node.
4585
4586 or else Error_Posted (N) or else Error_Posted (Typ)
ee6ba406 4587 then
4588 OK := False;
4589 return;
4590 end if;
4591
4592 -- For all other cases, we can determine the range
4593
4594 OK := True;
4595
feff2f05 4596 -- If value is compile time known, then the possible range is the one
39a0c1d3 4597 -- value that we know this expression definitely has.
ee6ba406 4598
4599 if Compile_Time_Known_Value (N) then
4600 Lo := Expr_Value (N);
4601 Hi := Lo;
4602 return;
4603 end if;
4604
4605 -- Return if already in the cache
4606
4607 Cindex := Cache_Index (N mod Cache_Size);
4608
9c486805 4609 if Determine_Range_Cache_N (Cindex) = N
4610 and then
4611 Determine_Range_Cache_V (Cindex) = Assume_Valid
4612 then
ee6ba406 4613 Lo := Determine_Range_Cache_Lo (Cindex);
4614 Hi := Determine_Range_Cache_Hi (Cindex);
4615 return;
4616 end if;
4617
feff2f05 4618 -- Otherwise, start by finding the bounds of the type of the expression,
4619 -- the value cannot be outside this range (if it is, then we have an
4620 -- overflow situation, which is a separate check, we are talking here
4621 -- only about the expression value).
ee6ba406 4622
341bd953 4623 -- First a check, never try to find the bounds of a generic type, since
4624 -- these bounds are always junk values, and it is only valid to look at
4625 -- the bounds in an instance.
4626
4627 if Is_Generic_Type (Typ) then
4628 OK := False;
4629 return;
4630 end if;
4631
9c486805 4632 -- First step, change to use base type unless we know the value is valid
e254d721 4633
9c486805 4634 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
4635 or else Assume_No_Invalid_Values
4636 or else Assume_Valid
e254d721 4637 then
1916d94e 4638 -- If this is a known valid constant with a nonstatic value, it may
4639 -- have inherited a narrower subtype from its initial value; use this
4640 -- saved subtype (see sem_ch3.adb).
4641
4642 if Is_Entity_Name (N)
4643 and then Ekind (Entity (N)) = E_Constant
4644 and then Present (Actual_Subtype (Entity (N)))
4645 then
4646 Typ := Actual_Subtype (Entity (N));
4647 end if;
4648
9c486805 4649 else
4650 Typ := Underlying_Type (Base_Type (Typ));
e254d721 4651 end if;
4652
094ed68e 4653 -- Retrieve the base type. Handle the case where the base type is a
4654 -- private enumeration type.
4655
4656 Btyp := Base_Type (Typ);
4657
4658 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
4659 Btyp := Full_View (Btyp);
4660 end if;
4661
feff2f05 4662 -- We use the actual bound unless it is dynamic, in which case use the
4663 -- corresponding base type bound if possible. If we can't get a bound
4664 -- then we figure we can't determine the range (a peculiar case, that
4665 -- perhaps cannot happen, but there is no point in bombing in this
4666 -- optimization circuit.
8880be85 4667
4668 -- First the low bound
ee6ba406 4669
4670 Bound := Type_Low_Bound (Typ);
4671
4672 if Compile_Time_Known_Value (Bound) then
4673 Lo := Expr_Value (Bound);
4674
094ed68e 4675 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
4676 Lo := Expr_Value (Type_Low_Bound (Btyp));
ee6ba406 4677
4678 else
4679 OK := False;
4680 return;
4681 end if;
4682
8880be85 4683 -- Now the high bound
4684
ee6ba406 4685 Bound := Type_High_Bound (Typ);
4686
8880be85 4687 -- We need the high bound of the base type later on, and this should
4688 -- always be compile time known. Again, it is not clear that this
4689 -- can ever be false, but no point in bombing.
ee6ba406 4690
094ed68e 4691 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
4692 Hbound := Expr_Value (Type_High_Bound (Btyp));
ee6ba406 4693 Hi := Hbound;
4694
4695 else
4696 OK := False;
4697 return;
4698 end if;
4699
feff2f05 4700 -- If we have a static subtype, then that may have a tighter bound so
4701 -- use the upper bound of the subtype instead in this case.
8880be85 4702
4703 if Compile_Time_Known_Value (Bound) then
4704 Hi := Expr_Value (Bound);
4705 end if;
4706
feff2f05 4707 -- We may be able to refine this value in certain situations. If any
4708 -- refinement is possible, then Lor and Hir are set to possibly tighter
4709 -- bounds, and OK1 is set to True.
ee6ba406 4710
4711 case Nkind (N) is
4712
4713 -- For unary plus, result is limited by range of operand
4714
4715 when N_Op_Plus =>
9c486805 4716 Determine_Range
4717 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
ee6ba406 4718
4719 -- For unary minus, determine range of operand, and negate it
4720
4721 when N_Op_Minus =>
9c486805 4722 Determine_Range
4723 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
ee6ba406 4724
4725 if OK1 then
4726 Lor := -Hi_Right;
4727 Hir := -Lo_Right;
4728 end if;
4729
4730 -- For binary addition, get range of each operand and do the
4731 -- addition to get the result range.
4732
4733 when N_Op_Add =>
4734 if OK_Operands then
4735 Lor := Lo_Left + Lo_Right;
4736 Hir := Hi_Left + Hi_Right;
4737 end if;
4738
feff2f05 4739 -- Division is tricky. The only case we consider is where the right
4740 -- operand is a positive constant, and in this case we simply divide
4741 -- the bounds of the left operand
ee6ba406 4742
4743 when N_Op_Divide =>
4744 if OK_Operands then
4745 if Lo_Right = Hi_Right
4746 and then Lo_Right > 0
4747 then
4748 Lor := Lo_Left / Lo_Right;
4749 Hir := Hi_Left / Lo_Right;
ee6ba406 4750 else
4751 OK1 := False;
4752 end if;
4753 end if;
4754
feff2f05 4755 -- For binary subtraction, get range of each operand and do the worst
4756 -- case subtraction to get the result range.
ee6ba406 4757
4758 when N_Op_Subtract =>
4759 if OK_Operands then
4760 Lor := Lo_Left - Hi_Right;
4761 Hir := Hi_Left - Lo_Right;
4762 end if;
4763
feff2f05 4764 -- For MOD, if right operand is a positive constant, then result must
4765 -- be in the allowable range of mod results.
ee6ba406 4766
4767 when N_Op_Mod =>
4768 if OK_Operands then
9dfe12ae 4769 if Lo_Right = Hi_Right
4770 and then Lo_Right /= 0
4771 then
ee6ba406 4772 if Lo_Right > 0 then
4773 Lor := Uint_0;
4774 Hir := Lo_Right - 1;
4775
9dfe12ae 4776 else -- Lo_Right < 0
ee6ba406 4777 Lor := Lo_Right + 1;
4778 Hir := Uint_0;
4779 end if;
4780
4781 else
4782 OK1 := False;
4783 end if;
4784 end if;
4785
feff2f05 4786 -- For REM, if right operand is a positive constant, then result must
4787 -- be in the allowable range of mod results.
ee6ba406 4788
4789 when N_Op_Rem =>
4790 if OK_Operands then
99378362 4791 if Lo_Right = Hi_Right and then Lo_Right /= 0 then
ee6ba406 4792 declare
4793 Dval : constant Uint := (abs Lo_Right) - 1;
4794
4795 begin
4796 -- The sign of the result depends on the sign of the
4797 -- dividend (but not on the sign of the divisor, hence
4798 -- the abs operation above).
4799
4800 if Lo_Left < 0 then
4801 Lor := -Dval;
4802 else
4803 Lor := Uint_0;
4804 end if;
4805
4806 if Hi_Left < 0 then
4807 Hir := Uint_0;
4808 else
4809 Hir := Dval;
4810 end if;
4811 end;
4812
4813 else
4814 OK1 := False;
4815 end if;
4816 end if;
4817
4818 -- Attribute reference cases
4819
4820 when N_Attribute_Reference =>
4821 case Attribute_Name (N) is
4822
4823 -- For Pos/Val attributes, we can refine the range using the
ddbf7f2e 4824 -- possible range of values of the attribute expression.
ee6ba406 4825
99378362 4826 when Name_Pos
4827 | Name_Val
4828 =>
9c486805 4829 Determine_Range
4830 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
ee6ba406 4831
4832 -- For Length attribute, use the bounds of the corresponding
4833 -- index type to refine the range.
4834
4835 when Name_Length =>
4836 declare
4837 Atyp : Entity_Id := Etype (Prefix (N));
4838 Inum : Nat;
4839 Indx : Node_Id;
4840
4841 LL, LU : Uint;
4842 UL, UU : Uint;
4843
4844 begin
4845 if Is_Access_Type (Atyp) then
4846 Atyp := Designated_Type (Atyp);
4847 end if;
4848
4849 -- For string literal, we know exact value
4850
4851 if Ekind (Atyp) = E_String_Literal_Subtype then
4852 OK := True;
4853 Lo := String_Literal_Length (Atyp);
4854 Hi := String_Literal_Length (Atyp);
4855 return;
4856 end if;
4857
4858 -- Otherwise check for expression given
4859
4860 if No (Expressions (N)) then
4861 Inum := 1;
4862 else
4863 Inum :=
4864 UI_To_Int (Expr_Value (First (Expressions (N))));
4865 end if;
4866
4867 Indx := First_Index (Atyp);
4868 for J in 2 .. Inum loop
4869 Indx := Next_Index (Indx);
4870 end loop;
4871
9116df93 4872 -- If the index type is a formal type or derived from
c8da6114 4873 -- one, the bounds are not static.
4874
4875 if Is_Generic_Type (Root_Type (Etype (Indx))) then
4876 OK := False;
4877 return;
4878 end if;
4879
ee6ba406 4880 Determine_Range
9c486805 4881 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
4882 Assume_Valid);
ee6ba406 4883
4884 if OK1 then
4885 Determine_Range
9c486805 4886 (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
4887 Assume_Valid);
ee6ba406 4888
4889 if OK1 then
4890
4891 -- The maximum value for Length is the biggest
4892 -- possible gap between the values of the bounds.
4893 -- But of course, this value cannot be negative.
4894
9c486805 4895 Hir := UI_Max (Uint_0, UU - LL + 1);
ee6ba406 4896
4897 -- For constrained arrays, the minimum value for
4898 -- Length is taken from the actual value of the
9116df93 4899 -- bounds, since the index will be exactly of this
4900 -- subtype.
ee6ba406 4901
4902 if Is_Constrained (Atyp) then
9c486805 4903 Lor := UI_Max (Uint_0, UL - LU + 1);
ee6ba406 4904
4905 -- For an unconstrained array, the minimum value
4906 -- for length is always zero.
4907
4908 else
4909 Lor := Uint_0;
4910 end if;
4911 end if;
4912 end if;
4913 end;
4914
4915 -- No special handling for other attributes
9116df93 4916 -- Probably more opportunities exist here???
ee6ba406 4917
4918 when others =>
4919 OK1 := False;
4920
4921 end case;
4922
ee6ba406 4923 when N_Type_Conversion =>
54022749 4924
4925 -- For type conversion from one discrete type to another, we can
4926 -- refine the range using the converted value.
4927
4928 if Is_Discrete_Type (Etype (Expression (N))) then
4929 Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
4930
4931 -- When converting a float to an integer type, determine the range
4932 -- in real first, and then convert the bounds using UR_To_Uint
4933 -- which correctly rounds away from zero when half way between two
4934 -- integers, as required by normal Ada 95 rounding semantics. It
4935 -- is only possible because analysis in GNATprove rules out the
4936 -- possibility of a NaN or infinite value.
4937
4938 elsif GNATprove_Mode
4939 and then Is_Floating_Point_Type (Etype (Expression (N)))
4940 then
4941 declare
4942 Lor_Real, Hir_Real : Ureal;
4943 begin
4944 Determine_Range_R (Expression (N), OK1, Lor_Real, Hir_Real,
4945 Assume_Valid);
4946
4947 if OK1 then
4948 Lor := UR_To_Uint (Lor_Real);
4949 Hir := UR_To_Uint (Hir_Real);
4950 end if;
4951 end;
4952
4953 else
4954 OK1 := False;
4955 end if;
ee6ba406 4956
4957 -- Nothing special to do for all other expression kinds
4958
4959 when others =>
4960 OK1 := False;
4961 Lor := No_Uint;
4962 Hir := No_Uint;
4963 end case;
4964
9116df93 4965 -- At this stage, if OK1 is true, then we know that the actual result of
4966 -- the computed expression is in the range Lor .. Hir. We can use this
4967 -- to restrict the possible range of results.
ee6ba406 4968
4969 if OK1 then
4970
9116df93 4971 -- If the refined value of the low bound is greater than the type
7ac8c2b1 4972 -- low bound, then reset it to the more restrictive value. However,
9116df93 4973 -- we do NOT do this for the case of a modular type where the
4974 -- possible upper bound on the value is above the base type high
4975 -- bound, because that means the result could wrap.
ee6ba406 4976
4977 if Lor > Lo
9116df93 4978 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
ee6ba406 4979 then
4980 Lo := Lor;
4981 end if;
4982
9116df93 4983 -- Similarly, if the refined value of the high bound is less than the
4984 -- value so far, then reset it to the more restrictive value. Again,
4985 -- we do not do this if the refined low bound is negative for a
4986 -- modular type, since this would wrap.
ee6ba406 4987
4988 if Hir < Hi
9116df93 4989 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
ee6ba406 4990 then
4991 Hi := Hir;
4992 end if;
4993 end if;
4994
4995 -- Set cache entry for future call and we are all done
4996
4997 Determine_Range_Cache_N (Cindex) := N;
9c486805 4998 Determine_Range_Cache_V (Cindex) := Assume_Valid;
ee6ba406 4999 Determine_Range_Cache_Lo (Cindex) := Lo;
5000 Determine_Range_Cache_Hi (Cindex) := Hi;
5001 return;
5002
9116df93 5003 -- If any exception occurs, it means that we have some bug in the compiler,
5004 -- possibly triggered by a previous error, or by some unforeseen peculiar
ee6ba406 5005 -- occurrence. However, this is only an optimization attempt, so there is
5006 -- really no point in crashing the compiler. Instead we just decide, too
5007 -- bad, we can't figure out a range in this case after all.
5008
5009 exception
5010 when others =>
5011
5012 -- Debug flag K disables this behavior (useful for debugging)
5013
5014 if Debug_Flag_K then
5015 raise;
5016 else
5017 OK := False;
5018 Lo := No_Uint;
5019 Hi := No_Uint;
5020 return;
5021 end if;
ee6ba406 5022 end Determine_Range;
5023
7ac8c2b1 5024 -----------------------
5025 -- Determine_Range_R --
5026 -----------------------
5027
5028 procedure Determine_Range_R
5029 (N : Node_Id;
5030 OK : out Boolean;
5031 Lo : out Ureal;
5032 Hi : out Ureal;
5033 Assume_Valid : Boolean := False)
5034 is
5035 Typ : Entity_Id := Etype (N);
5036 -- Type to use, may get reset to base type for possibly invalid entity
5037
5038 Lo_Left : Ureal;
5039 Hi_Left : Ureal;
5040 -- Lo and Hi bounds of left operand
5041
5bb74b99 5042 Lo_Right : Ureal := No_Ureal;
5043 Hi_Right : Ureal := No_Ureal;
7ac8c2b1 5044 -- Lo and Hi bounds of right (or only) operand
5045
5046 Bound : Node_Id;
5047 -- Temp variable used to hold a bound node
5048
5049 Hbound : Ureal;
5050 -- High bound of base type of expression
5051
5052 Lor : Ureal;
5053 Hir : Ureal;
5054 -- Refined values for low and high bounds, after tightening
5055
5056 OK1 : Boolean;
5057 -- Used in lower level calls to indicate if call succeeded
5058
5059 Cindex : Cache_Index;
5060 -- Used to search cache
5061
5062 Btyp : Entity_Id;
5063 -- Base type
5064
5065 function OK_Operands return Boolean;
5066 -- Used for binary operators. Determines the ranges of the left and
5067 -- right operands, and if they are both OK, returns True, and puts
5068 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
5069
5070 function Round_Machine (B : Ureal) return Ureal;
5071 -- B is a real bound. Round it using mode Round_Even.
5072
5073 -----------------
5074 -- OK_Operands --
5075 -----------------
5076
5077 function OK_Operands return Boolean is
5078 begin
5079 Determine_Range_R
5080 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
5081
5082 if not OK1 then
5083 return False;
5084 end if;
5085
5086 Determine_Range_R
5087 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5088 return OK1;
5089 end OK_Operands;
5090
5091 -------------------
5092 -- Round_Machine --
5093 -------------------
5094
5095 function Round_Machine (B : Ureal) return Ureal is
5096 begin
5097 return Machine (Typ, B, Round_Even, N);
5098 end Round_Machine;
5099
5100 -- Start of processing for Determine_Range_R
5101
5102 begin
5103 -- Prevent junk warnings by initializing range variables
5104
5105 Lo := No_Ureal;
5106 Hi := No_Ureal;
5107 Lor := No_Ureal;
5108 Hir := No_Ureal;
5109
5110 -- For temporary constants internally generated to remove side effects
5111 -- we must use the corresponding expression to determine the range of
5112 -- the expression. But note that the expander can also generate
5113 -- constants in other cases, including deferred constants.
5114
5115 if Is_Entity_Name (N)
5116 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
5117 and then Ekind (Entity (N)) = E_Constant
5118 and then Is_Internal_Name (Chars (Entity (N)))
5119 then
5120 if Present (Expression (Parent (Entity (N)))) then
5121 Determine_Range_R
5122 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
5123
5124 elsif Present (Full_View (Entity (N))) then
5125 Determine_Range_R
5126 (Expression (Parent (Full_View (Entity (N)))),
5127 OK, Lo, Hi, Assume_Valid);
5128
5129 else
5130 OK := False;
5131 end if;
4c1c7f3f 5132
7ac8c2b1 5133 return;
5134 end if;
5135
5136 -- If type is not defined, we can't determine its range
5137
5138 if No (Typ)
5139
5140 -- We don't deal with anything except IEEE floating-point types
5141
5142 or else not Is_Floating_Point_Type (Typ)
5143 or else Float_Rep (Typ) /= IEEE_Binary
5144
5145 -- Ignore type for which an error has been posted, since range in
5146 -- this case may well be a bogosity deriving from the error. Also
5147 -- ignore if error posted on the reference node.
5148
5149 or else Error_Posted (N) or else Error_Posted (Typ)
5150 then
5151 OK := False;
5152 return;
5153 end if;
5154
5155 -- For all other cases, we can determine the range
5156
5157 OK := True;
5158
5159 -- If value is compile time known, then the possible range is the one
5160 -- value that we know this expression definitely has.
5161
5162 if Compile_Time_Known_Value (N) then
5163 Lo := Expr_Value_R (N);
5164 Hi := Lo;
5165 return;
5166 end if;
5167
5168 -- Return if already in the cache
5169
5170 Cindex := Cache_Index (N mod Cache_Size);
5171
5172 if Determine_Range_Cache_N (Cindex) = N
5173 and then
5174 Determine_Range_Cache_V (Cindex) = Assume_Valid
5175 then
5176 Lo := Determine_Range_Cache_Lo_R (Cindex);
5177 Hi := Determine_Range_Cache_Hi_R (Cindex);
5178 return;
5179 end if;
5180
5181 -- Otherwise, start by finding the bounds of the type of the expression,
5182 -- the value cannot be outside this range (if it is, then we have an
5183 -- overflow situation, which is a separate check, we are talking here
5184 -- only about the expression value).
5185
5186 -- First a check, never try to find the bounds of a generic type, since
5187 -- these bounds are always junk values, and it is only valid to look at
5188 -- the bounds in an instance.
5189
5190 if Is_Generic_Type (Typ) then
5191 OK := False;
5192 return;
5193 end if;
5194
5195 -- First step, change to use base type unless we know the value is valid
5196
5197 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
5198 or else Assume_No_Invalid_Values
5199 or else Assume_Valid
5200 then
5201 null;
5202 else
5203 Typ := Underlying_Type (Base_Type (Typ));
5204 end if;
5205
5206 -- Retrieve the base type. Handle the case where the base type is a
5207 -- private type.
5208
5209 Btyp := Base_Type (Typ);
5210
5211 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
5212 Btyp := Full_View (Btyp);
5213 end if;
5214
5215 -- We use the actual bound unless it is dynamic, in which case use the
5216 -- corresponding base type bound if possible. If we can't get a bound
5217 -- then we figure we can't determine the range (a peculiar case, that
5218 -- perhaps cannot happen, but there is no point in bombing in this
5219 -- optimization circuit).
5220
5221 -- First the low bound
5222
5223 Bound := Type_Low_Bound (Typ);
5224
5225 if Compile_Time_Known_Value (Bound) then
5226 Lo := Expr_Value_R (Bound);
5227
5228 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
5229 Lo := Expr_Value_R (Type_Low_Bound (Btyp));
5230
5231 else
5232 OK := False;
5233 return;
5234 end if;
5235
5236 -- Now the high bound
5237
5238 Bound := Type_High_Bound (Typ);
5239
5240 -- We need the high bound of the base type later on, and this should
5241 -- always be compile time known. Again, it is not clear that this
5242 -- can ever be false, but no point in bombing.
5243
5244 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
5245 Hbound := Expr_Value_R (Type_High_Bound (Btyp));
5246 Hi := Hbound;
5247
5248 else
5249 OK := False;
5250 return;
5251 end if;
5252
5253 -- If we have a static subtype, then that may have a tighter bound so
5254 -- use the upper bound of the subtype instead in this case.
5255
5256 if Compile_Time_Known_Value (Bound) then
5257 Hi := Expr_Value_R (Bound);
5258 end if;
5259
5260 -- We may be able to refine this value in certain situations. If any
5261 -- refinement is possible, then Lor and Hir are set to possibly tighter
5262 -- bounds, and OK1 is set to True.
5263
5264 case Nkind (N) is
5265
5266 -- For unary plus, result is limited by range of operand
5267
5268 when N_Op_Plus =>
5269 Determine_Range_R
5270 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
5271
5272 -- For unary minus, determine range of operand, and negate it
5273
5274 when N_Op_Minus =>
5275 Determine_Range_R
5276 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5277
5278 if OK1 then
5279 Lor := -Hi_Right;
5280 Hir := -Lo_Right;
5281 end if;
5282
5283 -- For binary addition, get range of each operand and do the
5284 -- addition to get the result range.
5285
5286 when N_Op_Add =>
5287 if OK_Operands then
5288 Lor := Round_Machine (Lo_Left + Lo_Right);
5289 Hir := Round_Machine (Hi_Left + Hi_Right);
5290 end if;
5291
5292 -- For binary subtraction, get range of each operand and do the worst
5293 -- case subtraction to get the result range.
5294
5295 when N_Op_Subtract =>
5296 if OK_Operands then
5297 Lor := Round_Machine (Lo_Left - Hi_Right);
5298 Hir := Round_Machine (Hi_Left - Lo_Right);
5299 end if;
5300
5301 -- For multiplication, get range of each operand and do the
5302 -- four multiplications to get the result range.
5303
5304 when N_Op_Multiply =>
5305 if OK_Operands then
5306 declare
5307 M1 : constant Ureal := Round_Machine (Lo_Left * Lo_Right);
5308 M2 : constant Ureal := Round_Machine (Lo_Left * Hi_Right);
5309 M3 : constant Ureal := Round_Machine (Hi_Left * Lo_Right);
5310 M4 : constant Ureal := Round_Machine (Hi_Left * Hi_Right);
552d7cbc 5311
7ac8c2b1 5312 begin
5313 Lor := UR_Min (UR_Min (M1, M2), UR_Min (M3, M4));
5314 Hir := UR_Max (UR_Max (M1, M2), UR_Max (M3, M4));
5315 end;
5316 end if;
5317
5318 -- For division, consider separately the cases where the right
5319 -- operand is positive or negative. Otherwise, the right operand
5320 -- can be arbitrarily close to zero, so the result is likely to
5321 -- be unbounded in one direction, do not attempt to compute it.
5322
5323 when N_Op_Divide =>
5324 if OK_Operands then
5325
5326 -- Right operand is positive
5327
5328 if Lo_Right > Ureal_0 then
5329
5330 -- If the low bound of the left operand is negative, obtain
5331 -- the overall low bound by dividing it by the smallest
5332 -- value of the right operand, and otherwise by the largest
5333 -- value of the right operand.
5334
5335 if Lo_Left < Ureal_0 then
5336 Lor := Round_Machine (Lo_Left / Lo_Right);
5337 else
5338 Lor := Round_Machine (Lo_Left / Hi_Right);
5339 end if;
5340
5341 -- If the high bound of the left operand is negative, obtain
5342 -- the overall high bound by dividing it by the largest
5343 -- value of the right operand, and otherwise by the
5344 -- smallest value of the right operand.
5345
5346 if Hi_Left < Ureal_0 then
5347 Hir := Round_Machine (Hi_Left / Hi_Right);
5348 else
5349 Hir := Round_Machine (Hi_Left / Lo_Right);
5350 end if;
5351
5352 -- Right operand is negative
5353
5354 elsif Hi_Right < Ureal_0 then
5355
5356 -- If the low bound of the left operand is negative, obtain
5357 -- the overall low bound by dividing it by the largest
5358 -- value of the right operand, and otherwise by the smallest
5359 -- value of the right operand.
5360
5361 if Lo_Left < Ureal_0 then
5362 Lor := Round_Machine (Lo_Left / Hi_Right);
5363 else
5364 Lor := Round_Machine (Lo_Left / Lo_Right);
5365 end if;
5366
5367 -- If the high bound of the left operand is negative, obtain
5368 -- the overall high bound by dividing it by the smallest
5369 -- value of the right operand, and otherwise by the
5370 -- largest value of the right operand.
5371
5372 if Hi_Left < Ureal_0 then
5373 Hir := Round_Machine (Hi_Left / Lo_Right);
5374 else
5375 Hir := Round_Machine (Hi_Left / Hi_Right);
5376 end if;
5377
5378 else
5379 OK1 := False;
5380 end if;
5381 end if;
5382
7ac8c2b1 5383 when N_Type_Conversion =>
3c5c732f 5384
5385 -- For type conversion from one floating-point type to another, we
5386 -- can refine the range using the converted value.
5387
5388 if Is_Floating_Point_Type (Etype (Expression (N))) then
5389 Determine_Range_R (Expression (N), OK1, Lor, Hir, Assume_Valid);
5390
5391 -- When converting an integer to a floating-point type, determine
5392 -- the range in integer first, and then convert the bounds.
5393
5394 elsif Is_Discrete_Type (Etype (Expression (N))) then
5395 declare
552d7cbc 5396 Hir_Int : Uint;
5397 Lor_Int : Uint;
5398
3c5c732f 5399 begin
552d7cbc 5400 Determine_Range
5401 (Expression (N), OK1, Lor_Int, Hir_Int, Assume_Valid);
3c5c732f 5402
5403 if OK1 then
5404 Lor := Round_Machine (UR_From_Uint (Lor_Int));
5405 Hir := Round_Machine (UR_From_Uint (Hir_Int));
5406 end if;
5407 end;
5408
5409 else
5410 OK1 := False;
5411 end if;
7ac8c2b1 5412
5413 -- Nothing special to do for all other expression kinds
5414
5415 when others =>
5416 OK1 := False;
5417 Lor := No_Ureal;
5418 Hir := No_Ureal;
5419 end case;
5420
5421 -- At this stage, if OK1 is true, then we know that the actual result of
5422 -- the computed expression is in the range Lor .. Hir. We can use this
5423 -- to restrict the possible range of results.
5424
5425 if OK1 then
5426
5427 -- If the refined value of the low bound is greater than the type
5428 -- low bound, then reset it to the more restrictive value.
5429
5430 if Lor > Lo then
5431 Lo := Lor;
5432 end if;
5433
5434 -- Similarly, if the refined value of the high bound is less than the
5435 -- value so far, then reset it to the more restrictive value.
5436
5437 if Hir < Hi then
5438 Hi := Hir;
5439 end if;
5440 end if;
5441
5442 -- Set cache entry for future call and we are all done
5443
5444 Determine_Range_Cache_N (Cindex) := N;
5445 Determine_Range_Cache_V (Cindex) := Assume_Valid;
5446 Determine_Range_Cache_Lo_R (Cindex) := Lo;
5447 Determine_Range_Cache_Hi_R (Cindex) := Hi;
5448 return;
5449
5450 -- If any exception occurs, it means that we have some bug in the compiler,
5451 -- possibly triggered by a previous error, or by some unforeseen peculiar
5452 -- occurrence. However, this is only an optimization attempt, so there is
5453 -- really no point in crashing the compiler. Instead we just decide, too
5454 -- bad, we can't figure out a range in this case after all.
5455
5456 exception
5457 when others =>
5458
5459 -- Debug flag K disables this behavior (useful for debugging)
5460
5461 if Debug_Flag_K then
5462 raise;
5463 else
5464 OK := False;
5465 Lo := No_Ureal;
5466 Hi := No_Ureal;
5467 return;
5468 end if;
5469 end Determine_Range_R;
5470
ee6ba406 5471 ------------------------------------
5472 -- Discriminant_Checks_Suppressed --
5473 ------------------------------------
5474
5475 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
5476 begin
9dfe12ae 5477 if Present (E) then
5478 if Is_Unchecked_Union (E) then
5479 return True;
5480 elsif Checks_May_Be_Suppressed (E) then
5481 return Is_Check_Suppressed (E, Discriminant_Check);
5482 end if;
5483 end if;
5484
fafc6b97 5485 return Scope_Suppress.Suppress (Discriminant_Check);
ee6ba406 5486 end Discriminant_Checks_Suppressed;
5487
5488 --------------------------------
5489 -- Division_Checks_Suppressed --
5490 --------------------------------
5491
5492 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
5493 begin
9dfe12ae 5494 if Present (E) and then Checks_May_Be_Suppressed (E) then
5495 return Is_Check_Suppressed (E, Division_Check);
5496 else
fafc6b97 5497 return Scope_Suppress.Suppress (Division_Check);
9dfe12ae 5498 end if;
ee6ba406 5499 end Division_Checks_Suppressed;
5500
fa771c05 5501 --------------------------------------
5502 -- Duplicated_Tag_Checks_Suppressed --
5503 --------------------------------------
5504
5505 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
5506 begin
5507 if Present (E) and then Checks_May_Be_Suppressed (E) then
5508 return Is_Check_Suppressed (E, Duplicated_Tag_Check);
5509 else
5510 return Scope_Suppress.Suppress (Duplicated_Tag_Check);
5511 end if;
5512 end Duplicated_Tag_Checks_Suppressed;
5513
ee6ba406 5514 -----------------------------------
5515 -- Elaboration_Checks_Suppressed --
5516 -----------------------------------
5517
5518 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
5519 begin
38f5559f 5520 -- The complication in this routine is that if we are in the dynamic
5521 -- model of elaboration, we also check All_Checks, since All_Checks
5522 -- does not set Elaboration_Check explicitly.
5523
9dfe12ae 5524 if Present (E) then
5525 if Kill_Elaboration_Checks (E) then
5526 return True;
38f5559f 5527
9dfe12ae 5528 elsif Checks_May_Be_Suppressed (E) then
38f5559f 5529 if Is_Check_Suppressed (E, Elaboration_Check) then
5530 return True;
fe48a434 5531
38f5559f 5532 elsif Dynamic_Elaboration_Checks then
5533 return Is_Check_Suppressed (E, All_Checks);
fe48a434 5534
38f5559f 5535 else
5536 return False;
5537 end if;
9dfe12ae 5538 end if;
5539 end if;
5540
fafc6b97 5541 if Scope_Suppress.Suppress (Elaboration_Check) then
38f5559f 5542 return True;
fe48a434 5543
38f5559f 5544 elsif Dynamic_Elaboration_Checks then
fafc6b97 5545 return Scope_Suppress.Suppress (All_Checks);
fe48a434 5546
38f5559f 5547 else
5548 return False;
5549 end if;
ee6ba406 5550 end Elaboration_Checks_Suppressed;
5551
9dfe12ae 5552 ---------------------------
5553 -- Enable_Overflow_Check --
5554 ---------------------------
5555
5556 procedure Enable_Overflow_Check (N : Node_Id) is
4c1c7f3f 5557 Typ : constant Entity_Id := Base_Type (Etype (N));
db415383 5558 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
3cce7f32 5559 Chk : Nat;
5560 OK : Boolean;
5561 Ent : Entity_Id;
5562 Ofs : Uint;
5563 Lo : Uint;
5564 Hi : Uint;
ee6ba406 5565
f3ccbbb3 5566 Do_Ovflow_Check : Boolean;
5567
ee6ba406 5568 begin
9dfe12ae 5569 if Debug_Flag_CC then
5570 w ("Enable_Overflow_Check for node ", Int (N));
5571 Write_Str (" Source location = ");
5572 wl (Sloc (N));
00c403ee 5573 pg (Union_Id (N));
ee6ba406 5574 end if;
ee6ba406 5575
75209ec5 5576 -- No check if overflow checks suppressed for type of node
5577
0df9d43f 5578 if Overflow_Checks_Suppressed (Etype (N)) then
75209ec5 5579 return;
5580
49260fa5 5581 -- Nothing to do for unsigned integer types, which do not overflow
5582
5583 elsif Is_Modular_Integer_Type (Typ) then
5584 return;
3cce7f32 5585 end if;
5586
0df9d43f 5587 -- This is the point at which processing for STRICT mode diverges
21a55437 5588 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
5589 -- probably more extreme that it needs to be, but what is going on here
5590 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
0df9d43f 5591 -- to leave the processing for STRICT mode untouched. There were
21a55437 5592 -- two reasons for this. First it avoided any incompatible change of
0df9d43f 5593 -- behavior. Second, it guaranteed that STRICT mode continued to be
21a55437 5594 -- legacy reliable.
3cce7f32 5595
0df9d43f 5596 -- The big difference is that in STRICT mode there is a fair amount of
3cce7f32 5597 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
5598 -- know that no check is needed. We skip all that in the two new modes,
5599 -- since really overflow checking happens over a whole subtree, and we
5600 -- do the corresponding optimizations later on when applying the checks.
5601
5602 if Mode in Minimized_Or_Eliminated then
0df9d43f 5603 if not (Overflow_Checks_Suppressed (Etype (N)))
5604 and then not (Is_Entity_Name (N)
5605 and then Overflow_Checks_Suppressed (Entity (N)))
5606 then
5607 Activate_Overflow_Check (N);
5608 end if;
3cce7f32 5609
5610 if Debug_Flag_CC then
5611 w ("Minimized/Eliminated mode");
5612 end if;
5613
5614 return;
5615 end if;
5616
0df9d43f 5617 -- Remainder of processing is for STRICT case, and is unchanged from
691fe9e0 5618 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
49260fa5 5619
feff2f05 5620 -- Nothing to do if the range of the result is known OK. We skip this
5621 -- for conversions, since the caller already did the check, and in any
5622 -- case the condition for deleting the check for a type conversion is
cc60bd16 5623 -- different.
ee6ba406 5624
3cce7f32 5625 if Nkind (N) /= N_Type_Conversion then
9c486805 5626 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
ee6ba406 5627
cc60bd16 5628 -- Note in the test below that we assume that the range is not OK
5629 -- if a bound of the range is equal to that of the type. That's not
5630 -- quite accurate but we do this for the following reasons:
ee6ba406 5631
9dfe12ae 5632 -- a) The way that Determine_Range works, it will typically report
5633 -- the bounds of the value as being equal to the bounds of the
5634 -- type, because it either can't tell anything more precise, or
5635 -- does not think it is worth the effort to be more precise.
ee6ba406 5636
9dfe12ae 5637 -- b) It is very unusual to have a situation in which this would
5638 -- generate an unnecessary overflow check (an example would be
5639 -- a subtype with a range 0 .. Integer'Last - 1 to which the
cc60bd16 5640 -- literal value one is added).
ee6ba406 5641
9dfe12ae 5642 -- c) The alternative is a lot of special casing in this routine
5643 -- which would partially duplicate Determine_Range processing.
ee6ba406 5644
f3ccbbb3 5645 if OK then
5646 Do_Ovflow_Check := True;
5647
5648 -- Note that the following checks are quite deliberately > and <
5649 -- rather than >= and <= as explained above.
5650
5651 if Lo > Expr_Value (Type_Low_Bound (Typ))
5652 and then
5653 Hi < Expr_Value (Type_High_Bound (Typ))
5654 then
5655 Do_Ovflow_Check := False;
5656
5657 -- Despite the comments above, it is worth dealing specially with
5658 -- division specially. The only case where integer division can
5659 -- overflow is (largest negative number) / (-1). So we will do
5660 -- an extra range analysis to see if this is possible.
5661
5662 elsif Nkind (N) = N_Op_Divide then
5663 Determine_Range
5664 (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5665
5666 if OK and then Lo > Expr_Value (Type_Low_Bound (Typ)) then
5667 Do_Ovflow_Check := False;
5668
5669 else
5670 Determine_Range
5671 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5672
5673 if OK and then (Lo > Uint_Minus_1
5674 or else
5675 Hi < Uint_Minus_1)
5676 then
5677 Do_Ovflow_Check := False;
5678 end if;
5679 end if;
9dfe12ae 5680 end if;
5681
f3ccbbb3 5682 -- If no overflow check required, we are done
5683
5684 if not Do_Ovflow_Check then
5685 if Debug_Flag_CC then
5686 w ("No overflow check required");
5687 end if;
5688
5689 return;
5690 end if;
9dfe12ae 5691 end if;
5692 end if;
5693
feff2f05 5694 -- If not in optimizing mode, set flag and we are done. We are also done
5695 -- (and just set the flag) if the type is not a discrete type, since it
5696 -- is not worth the effort to eliminate checks for other than discrete
5697 -- types. In addition, we take this same path if we have stored the
5698 -- maximum number of checks possible already (a very unlikely situation,
39a0c1d3 5699 -- but we do not want to blow up).
9dfe12ae 5700
5701 if Optimization_Level = 0
5702 or else not Is_Discrete_Type (Etype (N))
5703 or else Num_Saved_Checks = Saved_Checks'Last
ee6ba406 5704 then
00c403ee 5705 Activate_Overflow_Check (N);
9dfe12ae 5706
5707 if Debug_Flag_CC then
5708 w ("Optimization off");
5709 end if;
5710
ee6ba406 5711 return;
9dfe12ae 5712 end if;
ee6ba406 5713
9dfe12ae 5714 -- Otherwise evaluate and check the expression
5715
5716 Find_Check
5717 (Expr => N,
5718 Check_Type => 'O',
5719 Target_Type => Empty,
5720 Entry_OK => OK,
5721 Check_Num => Chk,
5722 Ent => Ent,
5723 Ofs => Ofs);
5724
5725 if Debug_Flag_CC then
5726 w ("Called Find_Check");
5727 w (" OK = ", OK);
5728
5729 if OK then
5730 w (" Check_Num = ", Chk);
5731 w (" Ent = ", Int (Ent));
5732 Write_Str (" Ofs = ");
5733 pid (Ofs);
5734 end if;
5735 end if;
ee6ba406 5736
9dfe12ae 5737 -- If check is not of form to optimize, then set flag and we are done
5738
5739 if not OK then
00c403ee 5740 Activate_Overflow_Check (N);
ee6ba406 5741 return;
9dfe12ae 5742 end if;
ee6ba406 5743
9dfe12ae 5744 -- If check is already performed, then return without setting flag
5745
5746 if Chk /= 0 then
5747 if Debug_Flag_CC then
5748 w ("Check suppressed!");
5749 end if;
ee6ba406 5750
ee6ba406 5751 return;
9dfe12ae 5752 end if;
ee6ba406 5753
9dfe12ae 5754 -- Here we will make a new entry for the new check
5755
00c403ee 5756 Activate_Overflow_Check (N);
9dfe12ae 5757 Num_Saved_Checks := Num_Saved_Checks + 1;
5758 Saved_Checks (Num_Saved_Checks) :=
5759 (Killed => False,
5760 Entity => Ent,
5761 Offset => Ofs,
5762 Check_Type => 'O',
5763 Target_Type => Empty);
5764
5765 if Debug_Flag_CC then
5766 w ("Make new entry, check number = ", Num_Saved_Checks);
5767 w (" Entity = ", Int (Ent));
5768 Write_Str (" Offset = ");
5769 pid (Ofs);
5770 w (" Check_Type = O");
5771 w (" Target_Type = Empty");
5772 end if;
ee6ba406 5773
feff2f05 5774 -- If we get an exception, then something went wrong, probably because of
20cf157b 5775 -- an error in the structure of the tree due to an incorrect program. Or
5776 -- it may be a bug in the optimization circuit. In either case the safest
feff2f05 5777 -- thing is simply to set the check flag unconditionally.
9dfe12ae 5778
5779 exception
5780 when others =>
00c403ee 5781 Activate_Overflow_Check (N);
9dfe12ae 5782
5783 if Debug_Flag_CC then
5784 w (" exception occurred, overflow flag set");
5785 end if;
5786
5787 return;
5788 end Enable_Overflow_Check;
5789
5790 ------------------------
5791 -- Enable_Range_Check --
5792 ------------------------
5793
5794 procedure Enable_Range_Check (N : Node_Id) is
5795 Chk : Nat;
5796 OK : Boolean;
5797 Ent : Entity_Id;
5798 Ofs : Uint;
5799 Ttyp : Entity_Id;
5800 P : Node_Id;
5801
5802 begin
feff2f05 5803 -- Return if unchecked type conversion with range check killed. In this
39a0c1d3 5804 -- case we never set the flag (that's what Kill_Range_Check is about).
9dfe12ae 5805
5806 if Nkind (N) = N_Unchecked_Type_Conversion
5807 and then Kill_Range_Check (N)
ee6ba406 5808 then
5809 return;
9dfe12ae 5810 end if;
ee6ba406 5811
55e8372b 5812 -- Do not set range check flag if parent is assignment statement or
5813 -- object declaration with Suppress_Assignment_Checks flag set
5814
5815 if Nkind_In (Parent (N), N_Assignment_Statement, N_Object_Declaration)
5816 and then Suppress_Assignment_Checks (Parent (N))
5817 then
5818 return;
5819 end if;
5820
0577b0b1 5821 -- Check for various cases where we should suppress the range check
5822
5823 -- No check if range checks suppressed for type of node
5824
20cf157b 5825 if Present (Etype (N)) and then Range_Checks_Suppressed (Etype (N)) then
0577b0b1 5826 return;
5827
5828 -- No check if node is an entity name, and range checks are suppressed
5829 -- for this entity, or for the type of this entity.
5830
5831 elsif Is_Entity_Name (N)
5832 and then (Range_Checks_Suppressed (Entity (N))
20cf157b 5833 or else Range_Checks_Suppressed (Etype (Entity (N))))
0577b0b1 5834 then
5835 return;
5836
5837 -- No checks if index of array, and index checks are suppressed for
5838 -- the array object or the type of the array.
5839
5840 elsif Nkind (Parent (N)) = N_Indexed_Component then
5841 declare
5842 Pref : constant Node_Id := Prefix (Parent (N));
5843 begin
5844 if Is_Entity_Name (Pref)
5845 and then Index_Checks_Suppressed (Entity (Pref))
5846 then
5847 return;
5848 elsif Index_Checks_Suppressed (Etype (Pref)) then
5849 return;
5850 end if;
5851 end;
5852 end if;
5853
9dfe12ae 5854 -- Debug trace output
ee6ba406 5855
9dfe12ae 5856 if Debug_Flag_CC then
5857 w ("Enable_Range_Check for node ", Int (N));
5858 Write_Str (" Source location = ");
5859 wl (Sloc (N));
00c403ee 5860 pg (Union_Id (N));
9dfe12ae 5861 end if;
5862
feff2f05 5863 -- If not in optimizing mode, set flag and we are done. We are also done
5864 -- (and just set the flag) if the type is not a discrete type, since it
5865 -- is not worth the effort to eliminate checks for other than discrete
5866 -- types. In addition, we take this same path if we have stored the
5867 -- maximum number of checks possible already (a very unlikely situation,
39a0c1d3 5868 -- but we do not want to blow up).
9dfe12ae 5869
5870 if Optimization_Level = 0
5871 or else No (Etype (N))
5872 or else not Is_Discrete_Type (Etype (N))
5873 or else Num_Saved_Checks = Saved_Checks'Last
ee6ba406 5874 then
00c403ee 5875 Activate_Range_Check (N);
9dfe12ae 5876
5877 if Debug_Flag_CC then
5878 w ("Optimization off");
5879 end if;
5880
ee6ba406 5881 return;
9dfe12ae 5882 end if;
ee6ba406 5883
9dfe12ae 5884 -- Otherwise find out the target type
ee6ba406 5885
9dfe12ae 5886 P := Parent (N);
ee6ba406 5887
9dfe12ae 5888 -- For assignment, use left side subtype
5889
5890 if Nkind (P) = N_Assignment_Statement
5891 and then Expression (P) = N
5892 then
5893 Ttyp := Etype (Name (P));
5894
5895 -- For indexed component, use subscript subtype
5896
5897 elsif Nkind (P) = N_Indexed_Component then
5898 declare
5899 Atyp : Entity_Id;
5900 Indx : Node_Id;
5901 Subs : Node_Id;
5902
5903 begin
5904 Atyp := Etype (Prefix (P));
5905
5906 if Is_Access_Type (Atyp) then
5907 Atyp := Designated_Type (Atyp);
f07ea091 5908
5909 -- If the prefix is an access to an unconstrained array,
feff2f05 5910 -- perform check unconditionally: it depends on the bounds of
5911 -- an object and we cannot currently recognize whether the test
5912 -- may be redundant.
f07ea091 5913
5914 if not Is_Constrained (Atyp) then
00c403ee 5915 Activate_Range_Check (N);
f07ea091 5916 return;
5917 end if;
7189d17f 5918
31831d39 5919 -- Ditto if prefix is simply an unconstrained array. We used
5920 -- to think this case was OK, if the prefix was not an explicit
5921 -- dereference, but we have now seen a case where this is not
5922 -- true, so it is safer to just suppress the optimization in this
5923 -- case. The back end is getting better at eliminating redundant
5924 -- checks in any case, so the loss won't be important.
7189d17f 5925
31831d39 5926 elsif Is_Array_Type (Atyp)
7189d17f 5927 and then not Is_Constrained (Atyp)
5928 then
00c403ee 5929 Activate_Range_Check (N);
7189d17f 5930 return;
9dfe12ae 5931 end if;
5932
5933 Indx := First_Index (Atyp);
5934 Subs := First (Expressions (P));
5935 loop
5936 if Subs = N then
5937 Ttyp := Etype (Indx);
5938 exit;
5939 end if;
5940
5941 Next_Index (Indx);
5942 Next (Subs);
5943 end loop;
5944 end;
5945
5946 -- For now, ignore all other cases, they are not so interesting
5947
5948 else
5949 if Debug_Flag_CC then
5950 w (" target type not found, flag set");
5951 end if;
5952
00c403ee 5953 Activate_Range_Check (N);
9dfe12ae 5954 return;
5955 end if;
5956
5957 -- Evaluate and check the expression
5958
5959 Find_Check
5960 (Expr => N,
5961 Check_Type => 'R',
5962 Target_Type => Ttyp,
5963 Entry_OK => OK,
5964 Check_Num => Chk,
5965 Ent => Ent,
5966 Ofs => Ofs);
5967
5968 if Debug_Flag_CC then
5969 w ("Called Find_Check");
5970 w ("Target_Typ = ", Int (Ttyp));
5971 w (" OK = ", OK);
5972
5973 if OK then
5974 w (" Check_Num = ", Chk);
5975 w (" Ent = ", Int (Ent));
5976 Write_Str (" Ofs = ");
5977 pid (Ofs);
5978 end if;
5979 end if;
5980
5981 -- If check is not of form to optimize, then set flag and we are done
5982
5983 if not OK then
5984 if Debug_Flag_CC then
5985 w (" expression not of optimizable type, flag set");
5986 end if;
5987
00c403ee 5988 Activate_Range_Check (N);
9dfe12ae 5989 return;
5990 end if;
5991
5992 -- If check is already performed, then return without setting flag
5993
5994 if Chk /= 0 then
5995 if Debug_Flag_CC then
5996 w ("Check suppressed!");
5997 end if;
5998
5999 return;
6000 end if;
6001
6002 -- Here we will make a new entry for the new check
6003
00c403ee 6004 Activate_Range_Check (N);
9dfe12ae 6005 Num_Saved_Checks := Num_Saved_Checks + 1;
6006 Saved_Checks (Num_Saved_Checks) :=
6007 (Killed => False,
6008 Entity => Ent,
6009 Offset => Ofs,
6010 Check_Type => 'R',
6011 Target_Type => Ttyp);
6012
6013 if Debug_Flag_CC then
6014 w ("Make new entry, check number = ", Num_Saved_Checks);
6015 w (" Entity = ", Int (Ent));
6016 Write_Str (" Offset = ");
6017 pid (Ofs);
6018 w (" Check_Type = R");
6019 w (" Target_Type = ", Int (Ttyp));
00c403ee 6020 pg (Union_Id (Ttyp));
9dfe12ae 6021 end if;
6022
feff2f05 6023 -- If we get an exception, then something went wrong, probably because of
6024 -- an error in the structure of the tree due to an incorrect program. Or
6025 -- it may be a bug in the optimization circuit. In either case the safest
6026 -- thing is simply to set the check flag unconditionally.
9dfe12ae 6027
6028 exception
6029 when others =>
00c403ee 6030 Activate_Range_Check (N);
9dfe12ae 6031
6032 if Debug_Flag_CC then
6033 w (" exception occurred, range flag set");
6034 end if;
6035
6036 return;
6037 end Enable_Range_Check;
6038
6039 ------------------
6040 -- Ensure_Valid --
6041 ------------------
6042
aaec8d13 6043 procedure Ensure_Valid
6044 (Expr : Node_Id;
6045 Holes_OK : Boolean := False;
6046 Related_Id : Entity_Id := Empty;
6047 Is_Low_Bound : Boolean := False;
6048 Is_High_Bound : Boolean := False)
6049 is
9dfe12ae 6050 Typ : constant Entity_Id := Etype (Expr);
6051
6052 begin
6053 -- Ignore call if we are not doing any validity checking
6054
6055 if not Validity_Checks_On then
6056 return;
6057
0577b0b1 6058 -- Ignore call if range or validity checks suppressed on entity or type
9dfe12ae 6059
0577b0b1 6060 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
9dfe12ae 6061 return;
6062
feff2f05 6063 -- No check required if expression is from the expander, we assume the
6064 -- expander will generate whatever checks are needed. Note that this is
39a0c1d3 6065 -- not just an optimization, it avoids infinite recursions.
9dfe12ae 6066
6067 -- Unchecked conversions must be checked, unless they are initialized
6068 -- scalar values, as in a component assignment in an init proc.
6069
6070 -- In addition, we force a check if Force_Validity_Checks is set
6071
6072 elsif not Comes_From_Source (Expr)
404eb7da 6073 and then not
6074 (Nkind (Expr) = N_Identifier
6075 and then Present (Renamed_Object (Entity (Expr)))
6076 and then Comes_From_Source (Renamed_Object (Entity (Expr))))
9dfe12ae 6077 and then not Force_Validity_Checks
6078 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
6079 or else Kill_Range_Check (Expr))
6080 then
6081 return;
6082
6083 -- No check required if expression is known to have valid value
6084
6085 elsif Expr_Known_Valid (Expr) then
6086 return;
6087
ea1f4b87 6088 -- No check needed within a generated predicate function. Validity
6089 -- of input value will have been checked earlier.
6090
6091 elsif Ekind (Current_Scope) = E_Function
6092 and then Is_Predicate_Function (Current_Scope)
6093 then
6094 return;
6095
feff2f05 6096 -- Ignore case of enumeration with holes where the flag is set not to
6097 -- worry about holes, since no special validity check is needed
9dfe12ae 6098
6099 elsif Is_Enumeration_Type (Typ)
6100 and then Has_Non_Standard_Rep (Typ)
6101 and then Holes_OK
6102 then
6103 return;
6104
f2a06be9 6105 -- No check required on the left-hand side of an assignment
9dfe12ae 6106
6107 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
6108 and then Expr = Name (Parent (Expr))
6109 then
6110 return;
6111
6fb3c314 6112 -- No check on a universal real constant. The context will eventually
38f5559f 6113 -- convert it to a machine number for some target type, or report an
6114 -- illegality.
6115
6116 elsif Nkind (Expr) = N_Real_Literal
6117 and then Etype (Expr) = Universal_Real
6118 then
6119 return;
6120
6fb3c314 6121 -- If the expression denotes a component of a packed boolean array,
0577b0b1 6122 -- no possible check applies. We ignore the old ACATS chestnuts that
6123 -- involve Boolean range True..True.
6124
6125 -- Note: validity checks are generated for expressions that yield a
6126 -- scalar type, when it is possible to create a value that is outside of
6127 -- the type. If this is a one-bit boolean no such value exists. This is
6128 -- an optimization, and it also prevents compiler blowing up during the
6129 -- elaboration of improperly expanded packed array references.
6130
6131 elsif Nkind (Expr) = N_Indexed_Component
6132 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
6133 and then Root_Type (Etype (Expr)) = Standard_Boolean
6134 then
6135 return;
6136
737e8460 6137 -- For an expression with actions, we want to insert the validity check
6138 -- on the final Expression.
6139
6140 elsif Nkind (Expr) = N_Expression_With_Actions then
6141 Ensure_Valid (Expression (Expr));
6142 return;
6143
9dfe12ae 6144 -- An annoying special case. If this is an out parameter of a scalar
6145 -- type, then the value is not going to be accessed, therefore it is
becb6111 6146 -- inappropriate to do any validity check at the call site. Likewise
6147 -- if the parameter is passed by reference.
9dfe12ae 6148
6149 else
6150 -- Only need to worry about scalar types
6151
6152 if Is_Scalar_Type (Typ) then
ee6ba406 6153 declare
6154 P : Node_Id;
6155 N : Node_Id;
6156 E : Entity_Id;
6157 F : Entity_Id;
6158 A : Node_Id;
6159 L : List_Id;
6160
6161 begin
6162 -- Find actual argument (which may be a parameter association)
6163 -- and the parent of the actual argument (the call statement)
6164
6165 N := Expr;
6166 P := Parent (Expr);
6167
6168 if Nkind (P) = N_Parameter_Association then
6169 N := P;
6170 P := Parent (N);
6171 end if;
6172
becb6111 6173 -- If this is an indirect or dispatching call, get signature
6174 -- from the subprogram type.
ee6ba406 6175
becb6111 6176 if Nkind_In (P, N_Entry_Call_Statement,
6177 N_Function_Call,
6178 N_Procedure_Call_Statement)
6179 then
6180 E := Get_Called_Entity (P);
ee6ba406 6181 L := Parameter_Associations (P);
9dfe12ae 6182
feff2f05 6183 -- Only need to worry if there are indeed actuals, and if
becb6111 6184 -- this could be a subprogram call, otherwise we cannot get
6185 -- a match (either we are not an argument, or the mode of
6186 -- the formal is not OUT). This test also filters out the
feff2f05 6187 -- generic case.
ee6ba406 6188
20cf157b 6189 if Is_Non_Empty_List (L) and then Is_Subprogram (E) then
6190
feff2f05 6191 -- This is the loop through parameters, looking for an
6192 -- OUT parameter for which we are the argument.
ee6ba406 6193
6194 F := First_Formal (E);
6195 A := First (L);
ee6ba406 6196 while Present (F) loop
becb6111 6197 if A = N
6198 and then (Ekind (F) = E_Out_Parameter
6199 or else Mechanism (F) = By_Reference)
6200 then
ee6ba406 6201 return;
6202 end if;
6203
6204 Next_Formal (F);
6205 Next (A);
6206 end loop;
6207 end if;
6208 end if;
6209 end;
6210 end if;
6211 end if;
6212
fa6a6949 6213 -- If this is a boolean expression, only its elementary operands need
90a07d4c 6214 -- checking: if they are valid, a boolean or short-circuit operation
6215 -- with them will be valid as well.
784d4230 6216
6217 if Base_Type (Typ) = Standard_Boolean
7af38999 6218 and then
fa6a6949 6219 (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
784d4230 6220 then
6221 return;
6222 end if;
6223
0577b0b1 6224 -- If we fall through, a validity check is required
ee6ba406 6225
aaec8d13 6226 Insert_Valid_Check (Expr, Related_Id, Is_Low_Bound, Is_High_Bound);
ce7498d3 6227
6228 if Is_Entity_Name (Expr)
6229 and then Safe_To_Capture_Value (Expr, Entity (Expr))
6230 then
6231 Set_Is_Known_Valid (Entity (Expr));
6232 end if;
ee6ba406 6233 end Ensure_Valid;
6234
6235 ----------------------
6236 -- Expr_Known_Valid --
6237 ----------------------
6238
6239 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
6240 Typ : constant Entity_Id := Etype (Expr);
6241
6242 begin
feff2f05 6243 -- Non-scalar types are always considered valid, since they never give
6244 -- rise to the issues of erroneous or bounded error behavior that are
6245 -- the concern. In formal reference manual terms the notion of validity
6246 -- only applies to scalar types. Note that even when packed arrays are
6247 -- represented using modular types, they are still arrays semantically,
6248 -- so they are also always valid (in particular, the unused bits can be
6249 -- random rubbish without affecting the validity of the array value).
ee6ba406 6250
a88a5773 6251 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Impl_Type (Typ) then
ee6ba406 6252 return True;
6253
6254 -- If no validity checking, then everything is considered valid
6255
6256 elsif not Validity_Checks_On then
6257 return True;
6258
6259 -- Floating-point types are considered valid unless floating-point
6260 -- validity checks have been specifically turned on.
6261
6262 elsif Is_Floating_Point_Type (Typ)
6263 and then not Validity_Check_Floating_Point
6264 then
6265 return True;
6266
feff2f05 6267 -- If the expression is the value of an object that is known to be
6268 -- valid, then clearly the expression value itself is valid.
ee6ba406 6269
6270 elsif Is_Entity_Name (Expr)
6271 and then Is_Known_Valid (Entity (Expr))
985fe5d6 6272
6273 -- Exclude volatile variables
6274
6275 and then not Treat_As_Volatile (Entity (Expr))
ee6ba406 6276 then
6277 return True;
6278
0577b0b1 6279 -- References to discriminants are always considered valid. The value
6280 -- of a discriminant gets checked when the object is built. Within the
6281 -- record, we consider it valid, and it is important to do so, since
6282 -- otherwise we can try to generate bogus validity checks which
feff2f05 6283 -- reference discriminants out of scope. Discriminants of concurrent
6284 -- types are excluded for the same reason.
0577b0b1 6285
6286 elsif Is_Entity_Name (Expr)
feff2f05 6287 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
0577b0b1 6288 then
6289 return True;
6290
feff2f05 6291 -- If the type is one for which all values are known valid, then we are
6292 -- sure that the value is valid except in the slightly odd case where
6293 -- the expression is a reference to a variable whose size has been
6294 -- explicitly set to a value greater than the object size.
ee6ba406 6295
6296 elsif Is_Known_Valid (Typ) then
6297 if Is_Entity_Name (Expr)
6298 and then Ekind (Entity (Expr)) = E_Variable
6299 and then Esize (Entity (Expr)) > Esize (Typ)
6300 then
6301 return False;
6302 else
6303 return True;
6304 end if;
6305
6306 -- Integer and character literals always have valid values, where
6307 -- appropriate these will be range checked in any case.
6308
20cf157b 6309 elsif Nkind_In (Expr, N_Integer_Literal, N_Character_Literal) then
ee6ba406 6310 return True;
91e47010 6311
ee6ba406 6312 -- If we have a type conversion or a qualification of a known valid
6313 -- value, then the result will always be valid.
6314
20cf157b 6315 elsif Nkind_In (Expr, N_Type_Conversion, N_Qualified_Expression) then
ee6ba406 6316 return Expr_Known_Valid (Expression (Expr));
6317
1eb1395f 6318 -- Case of expression is a non-floating-point operator. In this case we
6319 -- can assume the result is valid the generated code for the operator
6320 -- will include whatever checks are needed (e.g. range checks) to ensure
6321 -- validity. This assumption does not hold for the floating-point case,
6322 -- since floating-point operators can generate Infinite or NaN results
6323 -- which are considered invalid.
6324
6325 -- Historical note: in older versions, the exemption of floating-point
6326 -- types from this assumption was done only in cases where the parent
6327 -- was an assignment, function call or parameter association. Presumably
6328 -- the idea was that in other contexts, the result would be checked
6329 -- elsewhere, but this list of cases was missing tests (at least the
6330 -- N_Object_Declaration case, as shown by a reported missing validity
6331 -- check), and it is not clear why function calls but not procedure
6332 -- calls were tested for. It really seems more accurate and much
6333 -- safer to recognize that expressions which are the result of a
6334 -- floating-point operator can never be assumed to be valid.
6335
6336 elsif Nkind (Expr) in N_Op and then not Is_Floating_Point_Type (Typ) then
6337 return True;
1d90d657 6338
feff2f05 6339 -- The result of a membership test is always valid, since it is true or
6340 -- false, there are no other possibilities.
0577b0b1 6341
6342 elsif Nkind (Expr) in N_Membership_Test then
6343 return True;
6344
ee6ba406 6345 -- For all other cases, we do not know the expression is valid
6346
6347 else
6348 return False;
6349 end if;
6350 end Expr_Known_Valid;
6351
9dfe12ae 6352 ----------------
6353 -- Find_Check --
6354 ----------------
6355
6356 procedure Find_Check
6357 (Expr : Node_Id;
6358 Check_Type : Character;
6359 Target_Type : Entity_Id;
6360 Entry_OK : out Boolean;
6361 Check_Num : out Nat;
6362 Ent : out Entity_Id;
6363 Ofs : out Uint)
6364 is
6365 function Within_Range_Of
6366 (Target_Type : Entity_Id;
314a23b6 6367 Check_Type : Entity_Id) return Boolean;
9dfe12ae 6368 -- Given a requirement for checking a range against Target_Type, and
6369 -- and a range Check_Type against which a check has already been made,
6370 -- determines if the check against check type is sufficient to ensure
6371 -- that no check against Target_Type is required.
6372
6373 ---------------------
6374 -- Within_Range_Of --
6375 ---------------------
6376
6377 function Within_Range_Of
6378 (Target_Type : Entity_Id;
314a23b6 6379 Check_Type : Entity_Id) return Boolean
9dfe12ae 6380 is
6381 begin
6382 if Target_Type = Check_Type then
6383 return True;
6384
6385 else
6386 declare
6387 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
6388 Thi : constant Node_Id := Type_High_Bound (Target_Type);
6389 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
6390 Chi : constant Node_Id := Type_High_Bound (Check_Type);
6391
6392 begin
6393 if (Tlo = Clo
6394 or else (Compile_Time_Known_Value (Tlo)
6395 and then
6396 Compile_Time_Known_Value (Clo)
6397 and then
6398 Expr_Value (Clo) >= Expr_Value (Tlo)))
6399 and then
6400 (Thi = Chi
6401 or else (Compile_Time_Known_Value (Thi)
6402 and then
6403 Compile_Time_Known_Value (Chi)
6404 and then
6405 Expr_Value (Chi) <= Expr_Value (Clo)))
6406 then
6407 return True;
6408 else
6409 return False;
6410 end if;
6411 end;
6412 end if;
6413 end Within_Range_Of;
6414
6415 -- Start of processing for Find_Check
6416
6417 begin
ed195555 6418 -- Establish default, in case no entry is found
9dfe12ae 6419
6420 Check_Num := 0;
6421
6422 -- Case of expression is simple entity reference
6423
6424 if Is_Entity_Name (Expr) then
6425 Ent := Entity (Expr);
6426 Ofs := Uint_0;
6427
6428 -- Case of expression is entity + known constant
6429
6430 elsif Nkind (Expr) = N_Op_Add
6431 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6432 and then Is_Entity_Name (Left_Opnd (Expr))
6433 then
6434 Ent := Entity (Left_Opnd (Expr));
6435 Ofs := Expr_Value (Right_Opnd (Expr));
6436
6437 -- Case of expression is entity - known constant
6438
6439 elsif Nkind (Expr) = N_Op_Subtract
6440 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6441 and then Is_Entity_Name (Left_Opnd (Expr))
6442 then
6443 Ent := Entity (Left_Opnd (Expr));
6444 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
6445
6446 -- Any other expression is not of the right form
6447
6448 else
6449 Ent := Empty;
6450 Ofs := Uint_0;
6451 Entry_OK := False;
6452 return;
6453 end if;
6454
feff2f05 6455 -- Come here with expression of appropriate form, check if entity is an
6456 -- appropriate one for our purposes.
9dfe12ae 6457
6458 if (Ekind (Ent) = E_Variable
cc60bd16 6459 or else Is_Constant_Object (Ent))
9dfe12ae 6460 and then not Is_Library_Level_Entity (Ent)
6461 then
6462 Entry_OK := True;
6463 else
6464 Entry_OK := False;
6465 return;
6466 end if;
6467
6468 -- See if there is matching check already
6469
6470 for J in reverse 1 .. Num_Saved_Checks loop
6471 declare
6472 SC : Saved_Check renames Saved_Checks (J);
9dfe12ae 6473 begin
6474 if SC.Killed = False
6475 and then SC.Entity = Ent
6476 and then SC.Offset = Ofs
6477 and then SC.Check_Type = Check_Type
6478 and then Within_Range_Of (Target_Type, SC.Target_Type)
6479 then
6480 Check_Num := J;
6481 return;
6482 end if;
6483 end;
6484 end loop;
6485
6486 -- If we fall through entry was not found
6487
9dfe12ae 6488 return;
6489 end Find_Check;
6490
6491 ---------------------------------
6492 -- Generate_Discriminant_Check --
6493 ---------------------------------
6494
6495 -- Note: the code for this procedure is derived from the
feff2f05 6496 -- Emit_Discriminant_Check Routine in trans.c.
9dfe12ae 6497
6498 procedure Generate_Discriminant_Check (N : Node_Id) is
6499 Loc : constant Source_Ptr := Sloc (N);
6500 Pref : constant Node_Id := Prefix (N);
6501 Sel : constant Node_Id := Selector_Name (N);
6502
6503 Orig_Comp : constant Entity_Id :=
b6341c67 6504 Original_Record_Component (Entity (Sel));
9dfe12ae 6505 -- The original component to be checked
6506
6507 Discr_Fct : constant Entity_Id :=
b6341c67 6508 Discriminant_Checking_Func (Orig_Comp);
9dfe12ae 6509 -- The discriminant checking function
6510
6511 Discr : Entity_Id;
6512 -- One discriminant to be checked in the type
6513
6514 Real_Discr : Entity_Id;
6515 -- Actual discriminant in the call
6516
6517 Pref_Type : Entity_Id;
6518 -- Type of relevant prefix (ignoring private/access stuff)
6519
6520 Args : List_Id;
6521 -- List of arguments for function call
6522
6523 Formal : Entity_Id;
feff2f05 6524 -- Keep track of the formal corresponding to the actual we build for
6525 -- each discriminant, in order to be able to perform the necessary type
6526 -- conversions.
9dfe12ae 6527
6528 Scomp : Node_Id;
6529 -- Selected component reference for checking function argument
6530
6531 begin
6532 Pref_Type := Etype (Pref);
6533
6534 -- Force evaluation of the prefix, so that it does not get evaluated
6535 -- twice (once for the check, once for the actual reference). Such a
20cf157b 6536 -- double evaluation is always a potential source of inefficiency, and
6537 -- is functionally incorrect in the volatile case, or when the prefix
f9906591 6538 -- may have side effects. A nonvolatile entity or a component of a
6539 -- nonvolatile entity requires no evaluation.
9dfe12ae 6540
6541 if Is_Entity_Name (Pref) then
6542 if Treat_As_Volatile (Entity (Pref)) then
6543 Force_Evaluation (Pref, Name_Req => True);
6544 end if;
6545
6546 elsif Treat_As_Volatile (Etype (Pref)) then
20cf157b 6547 Force_Evaluation (Pref, Name_Req => True);
9dfe12ae 6548
6549 elsif Nkind (Pref) = N_Selected_Component
6550 and then Is_Entity_Name (Prefix (Pref))
6551 then
6552 null;
6553
6554 else
6555 Force_Evaluation (Pref, Name_Req => True);
6556 end if;
6557
6558 -- For a tagged type, use the scope of the original component to
6559 -- obtain the type, because ???
6560
6561 if Is_Tagged_Type (Scope (Orig_Comp)) then
6562 Pref_Type := Scope (Orig_Comp);
6563
feff2f05 6564 -- For an untagged derived type, use the discriminants of the parent
6565 -- which have been renamed in the derivation, possibly by a one-to-many
d1a2e31b 6566 -- discriminant constraint. For untagged type, initially get the Etype
feff2f05 6567 -- of the prefix
9dfe12ae 6568
6569 else
6570 if Is_Derived_Type (Pref_Type)
6571 and then Number_Discriminants (Pref_Type) /=
6572 Number_Discriminants (Etype (Base_Type (Pref_Type)))
6573 then
6574 Pref_Type := Etype (Base_Type (Pref_Type));
6575 end if;
6576 end if;
6577
6578 -- We definitely should have a checking function, This routine should
6579 -- not be called if no discriminant checking function is present.
6580
6581 pragma Assert (Present (Discr_Fct));
6582
6583 -- Create the list of the actual parameters for the call. This list
6584 -- is the list of the discriminant fields of the record expression to
6585 -- be discriminant checked.
6586
6587 Args := New_List;
6588 Formal := First_Formal (Discr_Fct);
6589 Discr := First_Discriminant (Pref_Type);
6590 while Present (Discr) loop
6591
6592 -- If we have a corresponding discriminant field, and a parent
6593 -- subtype is present, then we want to use the corresponding
6594 -- discriminant since this is the one with the useful value.
6595
6596 if Present (Corresponding_Discriminant (Discr))
6597 and then Ekind (Pref_Type) = E_Record_Type
6598 and then Present (Parent_Subtype (Pref_Type))
6599 then
6600 Real_Discr := Corresponding_Discriminant (Discr);
6601 else
6602 Real_Discr := Discr;
6603 end if;
6604
6605 -- Construct the reference to the discriminant
6606
6607 Scomp :=
6608 Make_Selected_Component (Loc,
6609 Prefix =>
6610 Unchecked_Convert_To (Pref_Type,
6611 Duplicate_Subexpr (Pref)),
6612 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
6613
6614 -- Manually analyze and resolve this selected component. We really
6615 -- want it just as it appears above, and do not want the expander
feff2f05 6616 -- playing discriminal games etc with this reference. Then we append
6617 -- the argument to the list we are gathering.
9dfe12ae 6618
6619 Set_Etype (Scomp, Etype (Real_Discr));
6620 Set_Analyzed (Scomp, True);
6621 Append_To (Args, Convert_To (Etype (Formal), Scomp));
6622
6623 Next_Formal_With_Extras (Formal);
6624 Next_Discriminant (Discr);
6625 end loop;
6626
6627 -- Now build and insert the call
6628
6629 Insert_Action (N,
6630 Make_Raise_Constraint_Error (Loc,
6631 Condition =>
6632 Make_Function_Call (Loc,
20cf157b 6633 Name => New_Occurrence_Of (Discr_Fct, Loc),
9dfe12ae 6634 Parameter_Associations => Args),
6635 Reason => CE_Discriminant_Check_Failed));
6636 end Generate_Discriminant_Check;
6637
5c99c290 6638 ---------------------------
6639 -- Generate_Index_Checks --
6640 ---------------------------
9dfe12ae 6641
6642 procedure Generate_Index_Checks (N : Node_Id) is
05f3e139 6643
6644 function Entity_Of_Prefix return Entity_Id;
6645 -- Returns the entity of the prefix of N (or Empty if not found)
6646
3f42e2a7 6647 ----------------------
6648 -- Entity_Of_Prefix --
6649 ----------------------
6650
05f3e139 6651 function Entity_Of_Prefix return Entity_Id is
e5d38095 6652 P : Node_Id;
6653
05f3e139 6654 begin
e5d38095 6655 P := Prefix (N);
05f3e139 6656 while not Is_Entity_Name (P) loop
6657 if not Nkind_In (P, N_Selected_Component,
6658 N_Indexed_Component)
6659 then
6660 return Empty;
6661 end if;
6662
6663 P := Prefix (P);
6664 end loop;
6665
6666 return Entity (P);
6667 end Entity_Of_Prefix;
6668
6669 -- Local variables
6670
6671 Loc : constant Source_Ptr := Sloc (N);
6672 A : constant Node_Id := Prefix (N);
6673 A_Ent : constant Entity_Id := Entity_Of_Prefix;
6674 Sub : Node_Id;
9dfe12ae 6675
3f42e2a7 6676 -- Start of processing for Generate_Index_Checks
6677
9dfe12ae 6678 begin
05f3e139 6679 -- Ignore call if the prefix is not an array since we have a serious
6680 -- error in the sources. Ignore it also if index checks are suppressed
6681 -- for array object or type.
0577b0b1 6682
05f3e139 6683 if not Is_Array_Type (Etype (A))
20cf157b 6684 or else (Present (A_Ent) and then Index_Checks_Suppressed (A_Ent))
0577b0b1 6685 or else Index_Checks_Suppressed (Etype (A))
6686 then
6687 return;
df9fba45 6688
6689 -- The indexed component we are dealing with contains 'Loop_Entry in its
6690 -- prefix. This case arises when analysis has determined that constructs
6691 -- such as
6692
6693 -- Prefix'Loop_Entry (Expr)
6694 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
6695
6696 -- require rewriting for error detection purposes. A side effect of this
6697 -- action is the generation of index checks that mention 'Loop_Entry.
6698 -- Delay the generation of the check until 'Loop_Entry has been properly
6699 -- expanded. This is done in Expand_Loop_Entry_Attributes.
6700
6701 elsif Nkind (Prefix (N)) = N_Attribute_Reference
6702 and then Attribute_Name (Prefix (N)) = Name_Loop_Entry
6703 then
6704 return;
0577b0b1 6705 end if;
6706
05f3e139 6707 -- Generate a raise of constraint error with the appropriate reason and
6708 -- a condition of the form:
6709
3f42e2a7 6710 -- Base_Type (Sub) not in Array'Range (Subscript)
05f3e139 6711
6712 -- Note that the reason we generate the conversion to the base type here
6713 -- is that we definitely want the range check to take place, even if it
6714 -- looks like the subtype is OK. Optimization considerations that allow
6715 -- us to omit the check have already been taken into account in the
6716 -- setting of the Do_Range_Check flag earlier on.
0577b0b1 6717
9dfe12ae 6718 Sub := First (Expressions (N));
05f3e139 6719
6720 -- Handle string literals
6721
6722 if Ekind (Etype (A)) = E_String_Literal_Subtype then
9dfe12ae 6723 if Do_Range_Check (Sub) then
6724 Set_Do_Range_Check (Sub, False);
6725
05f3e139 6726 -- For string literals we obtain the bounds of the string from the
6727 -- associated subtype.
9dfe12ae 6728
05f3e139 6729 Insert_Action (N,
094ed68e 6730 Make_Raise_Constraint_Error (Loc,
6731 Condition =>
6732 Make_Not_In (Loc,
6733 Left_Opnd =>
6734 Convert_To (Base_Type (Etype (Sub)),
6735 Duplicate_Subexpr_Move_Checks (Sub)),
6736 Right_Opnd =>
6737 Make_Attribute_Reference (Loc,
83c6c069 6738 Prefix => New_Occurrence_Of (Etype (A), Loc),
094ed68e 6739 Attribute_Name => Name_Range)),
6740 Reason => CE_Index_Check_Failed));
05f3e139 6741 end if;
9dfe12ae 6742
05f3e139 6743 -- General case
9dfe12ae 6744
05f3e139 6745 else
6746 declare
6747 A_Idx : Node_Id := Empty;
6748 A_Range : Node_Id;
6749 Ind : Nat;
6750 Num : List_Id;
6751 Range_N : Node_Id;
9dfe12ae 6752
05f3e139 6753 begin
6754 A_Idx := First_Index (Etype (A));
6755 Ind := 1;
6756 while Present (Sub) loop
6757 if Do_Range_Check (Sub) then
6758 Set_Do_Range_Check (Sub, False);
9dfe12ae 6759
05f3e139 6760 -- Force evaluation except for the case of a simple name of
f9906591 6761 -- a nonvolatile entity.
9dfe12ae 6762
05f3e139 6763 if not Is_Entity_Name (Sub)
6764 or else Treat_As_Volatile (Entity (Sub))
6765 then
6766 Force_Evaluation (Sub);
6767 end if;
9dfe12ae 6768
05f3e139 6769 if Nkind (A_Idx) = N_Range then
6770 A_Range := A_Idx;
6771
6772 elsif Nkind (A_Idx) = N_Identifier
6773 or else Nkind (A_Idx) = N_Expanded_Name
6774 then
6775 A_Range := Scalar_Range (Entity (A_Idx));
6776
6777 else pragma Assert (Nkind (A_Idx) = N_Subtype_Indication);
6778 A_Range := Range_Expression (Constraint (A_Idx));
6779 end if;
6780
6781 -- For array objects with constant bounds we can generate
6782 -- the index check using the bounds of the type of the index
6783
6784 if Present (A_Ent)
6785 and then Ekind (A_Ent) = E_Variable
6786 and then Is_Constant_Bound (Low_Bound (A_Range))
6787 and then Is_Constant_Bound (High_Bound (A_Range))
6788 then
6789 Range_N :=
6790 Make_Attribute_Reference (Loc,
3f42e2a7 6791 Prefix =>
83c6c069 6792 New_Occurrence_Of (Etype (A_Idx), Loc),
05f3e139 6793 Attribute_Name => Name_Range);
6794
6795 -- For arrays with non-constant bounds we cannot generate
6796 -- the index check using the bounds of the type of the index
6797 -- since it may reference discriminants of some enclosing
6798 -- type. We obtain the bounds directly from the prefix
6799 -- object.
6800
6801 else
6802 if Ind = 1 then
6803 Num := No_List;
6804 else
6805 Num := New_List (Make_Integer_Literal (Loc, Ind));
6806 end if;
6807
6808 Range_N :=
6809 Make_Attribute_Reference (Loc,
6810 Prefix =>
6811 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
6812 Attribute_Name => Name_Range,
6813 Expressions => Num);
6814 end if;
6815
6816 Insert_Action (N,
094ed68e 6817 Make_Raise_Constraint_Error (Loc,
6818 Condition =>
6819 Make_Not_In (Loc,
6820 Left_Opnd =>
6821 Convert_To (Base_Type (Etype (Sub)),
6822 Duplicate_Subexpr_Move_Checks (Sub)),
6823 Right_Opnd => Range_N),
6824 Reason => CE_Index_Check_Failed));
05f3e139 6825 end if;
6826
6827 A_Idx := Next_Index (A_Idx);
6828 Ind := Ind + 1;
6829 Next (Sub);
6830 end loop;
6831 end;
6832 end if;
9dfe12ae 6833 end Generate_Index_Checks;
6834
6835 --------------------------
6836 -- Generate_Range_Check --
6837 --------------------------
6838
6839 procedure Generate_Range_Check
6840 (N : Node_Id;
6841 Target_Type : Entity_Id;
6842 Reason : RT_Exception_Code)
6843 is
6844 Loc : constant Source_Ptr := Sloc (N);
6845 Source_Type : constant Entity_Id := Etype (N);
6846 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
6847 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
6848
0275bc70 6849 procedure Convert_And_Check_Range (Suppress : Check_Id);
6850 -- Convert N to the target base type and save the result in a temporary.
6851 -- The action is analyzed using the default checks as modified by the
6852 -- given Suppress argument. Then check the converted value against the
6853 -- range of the target subtype.
1f5d83cf 6854
124f1911 6855 -----------------------------
6856 -- Convert_And_Check_Range --
6857 -----------------------------
1f5d83cf 6858
0275bc70 6859 procedure Convert_And_Check_Range (Suppress : Check_Id) is
6860 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
6861 Conv_N : Node_Id;
1f5d83cf 6862
124f1911 6863 begin
cdfda0e3 6864 -- For enumeration types with non-standard representation this is a
6865 -- direct conversion from the enumeration type to the target integer
6866 -- type, which is treated by the back end as a normal integer type
6867 -- conversion, treating the enumeration type as an integer, which is
6868 -- exactly what we want. We set Conversion_OK to make sure that the
6869 -- analyzer does not complain about what otherwise might be an
6870 -- illegal conversion.
6871
6872 if Is_Enumeration_Type (Source_Base_Type)
6873 and then Present (Enum_Pos_To_Rep (Source_Base_Type))
6874 and then Is_Integer_Type (Target_Base_Type)
6875 then
0275bc70 6876 Conv_N := OK_Convert_To (Target_Base_Type, Duplicate_Subexpr (N));
cdfda0e3 6877 else
0275bc70 6878 Conv_N := Convert_To (Target_Base_Type, Duplicate_Subexpr (N));
cdfda0e3 6879 end if;
6880
0275bc70 6881 -- We make a temporary to hold the value of the conversion to the
6882 -- target base type, and then do the test against this temporary.
6883 -- N itself is replaced by an occurrence of Tnn and followed by
6884 -- the explicit range check.
1f5d83cf 6885
124f1911 6886 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
6887 -- [constraint_error when Tnn not in Target_Type]
0275bc70 6888 -- Tnn
124f1911 6889
1f5d83cf 6890 Insert_Actions (N, New_List (
6891 Make_Object_Declaration (Loc,
6892 Defining_Identifier => Tnn,
6893 Object_Definition => New_Occurrence_Of (Target_Base_Type, Loc),
6894 Constant_Present => True,
0275bc70 6895 Expression => Conv_N),
1f5d83cf 6896
6897 Make_Raise_Constraint_Error (Loc,
6898 Condition =>
6899 Make_Not_In (Loc,
6900 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
6901 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6902 Reason => Reason)),
0275bc70 6903 Suppress => Suppress);
1f5d83cf 6904
6905 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
6906
6907 -- Set the type of N, because the declaration for Tnn might not
6908 -- be analyzed yet, as is the case if N appears within a record
6909 -- declaration, as a discriminant constraint or expression.
6910
6911 Set_Etype (N, Target_Base_Type);
6912 end Convert_And_Check_Range;
6913
6914 -- Start of processing for Generate_Range_Check
6915
9dfe12ae 6916 begin
feff2f05 6917 -- First special case, if the source type is already within the range
6918 -- of the target type, then no check is needed (probably we should have
6919 -- stopped Do_Range_Check from being set in the first place, but better
0275bc70 6920 -- late than never in preventing junk code and junk flag settings).
9dfe12ae 6921
7a1dabb3 6922 if In_Subrange_Of (Source_Type, Target_Type)
b40670e1 6923
6924 -- We do NOT apply this if the source node is a literal, since in this
6925 -- case the literal has already been labeled as having the subtype of
6926 -- the target.
6927
9dfe12ae 6928 and then not
b40670e1 6929 (Nkind_In (N, N_Integer_Literal, N_Real_Literal, N_Character_Literal)
9dfe12ae 6930 or else
b40670e1 6931 (Is_Entity_Name (N)
6932 and then Ekind (Entity (N)) = E_Enumeration_Literal))
9dfe12ae 6933 then
cda40848 6934 Set_Do_Range_Check (N, False);
9dfe12ae 6935 return;
6936 end if;
6937
cda40848 6938 -- Here a check is needed. If the expander is not active, or if we are
6939 -- in GNATProve mode, then simply set the Do_Range_Check flag and we
6940 -- are done. In both these cases, we just want to see the range check
6941 -- flag set, we do not want to generate the explicit range check code.
6942
6943 if GNATprove_Mode or else not Expander_Active then
df1c131a 6944 Set_Do_Range_Check (N);
cda40848 6945 return;
6946 end if;
6947
6948 -- Here we will generate an explicit range check, so we don't want to
6949 -- set the Do_Range check flag, since the range check is taken care of
6950 -- by the code we will generate.
6951
6952 Set_Do_Range_Check (N, False);
6953
6954 -- Force evaluation of the node, so that it does not get evaluated twice
6955 -- (once for the check, once for the actual reference). Such a double
6956 -- evaluation is always a potential source of inefficiency, and is
6957 -- functionally incorrect in the volatile case.
9dfe12ae 6958
f47b9548 6959 -- We skip the evaluation of attribute references because, after these
6960 -- runtime checks are generated, the expander may need to rewrite this
6961 -- node (for example, see Attribute_Max_Size_In_Storage_Elements in
6962 -- Expand_N_Attribute_Reference).
6963
6964 if Nkind (N) /= N_Attribute_Reference
6965 and then (not Is_Entity_Name (N)
ca09bfdb 6966 or else Treat_As_Volatile (Entity (N)))
f47b9548 6967 then
6968 Force_Evaluation (N, Mode => Strict);
9dfe12ae 6969 end if;
6970
feff2f05 6971 -- The easiest case is when Source_Base_Type and Target_Base_Type are
6972 -- the same since in this case we can simply do a direct check of the
6973 -- value of N against the bounds of Target_Type.
9dfe12ae 6974
6975 -- [constraint_error when N not in Target_Type]
6976
6977 -- Note: this is by far the most common case, for example all cases of
6978 -- checks on the RHS of assignments are in this category, but not all
6979 -- cases are like this. Notably conversions can involve two types.
6980
6981 if Source_Base_Type = Target_Base_Type then
99ed4b4c 6982
6983 -- Insert the explicit range check. Note that we suppress checks for
6984 -- this code, since we don't want a recursive range check popping up.
6985
9dfe12ae 6986 Insert_Action (N,
6987 Make_Raise_Constraint_Error (Loc,
6988 Condition =>
6989 Make_Not_In (Loc,
6990 Left_Opnd => Duplicate_Subexpr (N),
6991 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
99ed4b4c 6992 Reason => Reason),
6993 Suppress => All_Checks);
9dfe12ae 6994
6995 -- Next test for the case where the target type is within the bounds
6996 -- of the base type of the source type, since in this case we can
0275bc70 6997 -- simply convert the bounds of the target type to this base bype
6998 -- to do the test.
9dfe12ae 6999
7000 -- [constraint_error when N not in
7001 -- Source_Base_Type (Target_Type'First)
7002 -- ..
7003 -- Source_Base_Type(Target_Type'Last))]
7004
f2a06be9 7005 -- The conversions will always work and need no check
9dfe12ae 7006
a9b57347 7007 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
7008 -- of converting from an enumeration value to an integer type, such as
7009 -- occurs for the case of generating a range check on Enum'Val(Exp)
7010 -- (which used to be handled by gigi). This is OK, since the conversion
7011 -- itself does not require a check.
7012
7a1dabb3 7013 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
99ed4b4c 7014
7015 -- Insert the explicit range check. Note that we suppress checks for
7016 -- this code, since we don't want a recursive range check popping up.
7017
1f5d83cf 7018 if Is_Discrete_Type (Source_Base_Type)
7019 and then
7020 Is_Discrete_Type (Target_Base_Type)
7021 then
7022 Insert_Action (N,
7023 Make_Raise_Constraint_Error (Loc,
7024 Condition =>
7025 Make_Not_In (Loc,
7026 Left_Opnd => Duplicate_Subexpr (N),
7027
7028 Right_Opnd =>
7029 Make_Range (Loc,
7030 Low_Bound =>
7031 Unchecked_Convert_To (Source_Base_Type,
7032 Make_Attribute_Reference (Loc,
7033 Prefix =>
7034 New_Occurrence_Of (Target_Type, Loc),
7035 Attribute_Name => Name_First)),
7036
7037 High_Bound =>
7038 Unchecked_Convert_To (Source_Base_Type,
7039 Make_Attribute_Reference (Loc,
7040 Prefix =>
7041 New_Occurrence_Of (Target_Type, Loc),
7042 Attribute_Name => Name_Last)))),
7043 Reason => Reason),
7044 Suppress => All_Checks);
9dfe12ae 7045
1f5d83cf 7046 -- For conversions involving at least one type that is not discrete,
0275bc70 7047 -- first convert to the target base type and then generate the range
7048 -- check. This avoids problems with values that are close to a bound
7049 -- of the target type that would fail a range check when done in a
7050 -- larger source type before converting but pass if converted with
1f5d83cf 7051 -- rounding and then checked (such as in float-to-float conversions).
7052
0275bc70 7053 -- Note that overflow checks are not suppressed for this code because
7054 -- we do not know whether the source type is in range of the target
7055 -- base type (unlike in the next case below).
7056
1f5d83cf 7057 else
0275bc70 7058 Convert_And_Check_Range (Suppress => Range_Check);
1f5d83cf 7059 end if;
9dfe12ae 7060
56903255 7061 -- Note that at this stage we know that the Target_Base_Type is not in
feff2f05 7062 -- the range of the Source_Base_Type (since even the Target_Type itself
7063 -- is not in this range). It could still be the case that Source_Type is
7064 -- in range of the target base type since we have not checked that case.
9dfe12ae 7065
feff2f05 7066 -- If that is the case, we can freely convert the source to the target,
0275bc70 7067 -- and then test the target result against the bounds. Note that checks
7068 -- are suppressed for this code, since we don't want a recursive range
7069 -- check popping up.
9dfe12ae 7070
7a1dabb3 7071 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
0275bc70 7072 Convert_And_Check_Range (Suppress => All_Checks);
9dfe12ae 7073
7074 -- At this stage, we know that we have two scalar types, which are
7075 -- directly convertible, and where neither scalar type has a base
7076 -- range that is in the range of the other scalar type.
7077
7078 -- The only way this can happen is with a signed and unsigned type.
7079 -- So test for these two cases:
7080
7081 else
7082 -- Case of the source is unsigned and the target is signed
7083
7084 if Is_Unsigned_Type (Source_Base_Type)
7085 and then not Is_Unsigned_Type (Target_Base_Type)
7086 then
7087 -- If the source is unsigned and the target is signed, then we
7088 -- know that the source is not shorter than the target (otherwise
7089 -- the source base type would be in the target base type range).
7090
feff2f05 7091 -- In other words, the unsigned type is either the same size as
7092 -- the target, or it is larger. It cannot be smaller.
9dfe12ae 7093
7094 pragma Assert
7095 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
7096
7097 -- We only need to check the low bound if the low bound of the
7098 -- target type is non-negative. If the low bound of the target
7099 -- type is negative, then we know that we will fit fine.
7100
7101 -- If the high bound of the target type is negative, then we
7102 -- know we have a constraint error, since we can't possibly
7103 -- have a negative source.
7104
7105 -- With these two checks out of the way, we can do the check
7106 -- using the source type safely
7107
39a0c1d3 7108 -- This is definitely the most annoying case.
9dfe12ae 7109
7110 -- [constraint_error
7111 -- when (Target_Type'First >= 0
7112 -- and then
7113 -- N < Source_Base_Type (Target_Type'First))
7114 -- or else Target_Type'Last < 0
7115 -- or else N > Source_Base_Type (Target_Type'Last)];
7116
7117 -- We turn off all checks since we know that the conversions
7118 -- will work fine, given the guards for negative values.
7119
7120 Insert_Action (N,
7121 Make_Raise_Constraint_Error (Loc,
7122 Condition =>
7123 Make_Or_Else (Loc,
7124 Make_Or_Else (Loc,
7125 Left_Opnd =>
7126 Make_And_Then (Loc,
7127 Left_Opnd => Make_Op_Ge (Loc,
7128 Left_Opnd =>
7129 Make_Attribute_Reference (Loc,
7130 Prefix =>
7131 New_Occurrence_Of (Target_Type, Loc),
7132 Attribute_Name => Name_First),
7133 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7134
7135 Right_Opnd =>
7136 Make_Op_Lt (Loc,
7137 Left_Opnd => Duplicate_Subexpr (N),
7138 Right_Opnd =>
7139 Convert_To (Source_Base_Type,
7140 Make_Attribute_Reference (Loc,
7141 Prefix =>
7142 New_Occurrence_Of (Target_Type, Loc),
7143 Attribute_Name => Name_First)))),
7144
7145 Right_Opnd =>
7146 Make_Op_Lt (Loc,
7147 Left_Opnd =>
7148 Make_Attribute_Reference (Loc,
7149 Prefix => New_Occurrence_Of (Target_Type, Loc),
7150 Attribute_Name => Name_Last),
7151 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
7152
7153 Right_Opnd =>
7154 Make_Op_Gt (Loc,
7155 Left_Opnd => Duplicate_Subexpr (N),
7156 Right_Opnd =>
7157 Convert_To (Source_Base_Type,
7158 Make_Attribute_Reference (Loc,
7159 Prefix => New_Occurrence_Of (Target_Type, Loc),
7160 Attribute_Name => Name_Last)))),
7161
7162 Reason => Reason),
7163 Suppress => All_Checks);
7164
7165 -- Only remaining possibility is that the source is signed and
fc75802a 7166 -- the target is unsigned.
9dfe12ae 7167
7168 else
7169 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
20cf157b 7170 and then Is_Unsigned_Type (Target_Base_Type));
9dfe12ae 7171
feff2f05 7172 -- If the source is signed and the target is unsigned, then we
7173 -- know that the target is not shorter than the source (otherwise
7174 -- the target base type would be in the source base type range).
9dfe12ae 7175
feff2f05 7176 -- In other words, the unsigned type is either the same size as
7177 -- the target, or it is larger. It cannot be smaller.
9dfe12ae 7178
feff2f05 7179 -- Clearly we have an error if the source value is negative since
7180 -- no unsigned type can have negative values. If the source type
7181 -- is non-negative, then the check can be done using the target
7182 -- type.
9dfe12ae 7183
7184 -- Tnn : constant Target_Base_Type (N) := Target_Type;
7185
7186 -- [constraint_error
7187 -- when N < 0 or else Tnn not in Target_Type];
7188
feff2f05 7189 -- We turn off all checks for the conversion of N to the target
7190 -- base type, since we generate the explicit check to ensure that
7191 -- the value is non-negative
9dfe12ae 7192
7193 declare
46eb6933 7194 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
9dfe12ae 7195
7196 begin
7197 Insert_Actions (N, New_List (
7198 Make_Object_Declaration (Loc,
7199 Defining_Identifier => Tnn,
7200 Object_Definition =>
7201 New_Occurrence_Of (Target_Base_Type, Loc),
7202 Constant_Present => True,
7203 Expression =>
a9b57347 7204 Make_Unchecked_Type_Conversion (Loc,
9dfe12ae 7205 Subtype_Mark =>
7206 New_Occurrence_Of (Target_Base_Type, Loc),
7207 Expression => Duplicate_Subexpr (N))),
7208
7209 Make_Raise_Constraint_Error (Loc,
7210 Condition =>
7211 Make_Or_Else (Loc,
7212 Left_Opnd =>
7213 Make_Op_Lt (Loc,
7214 Left_Opnd => Duplicate_Subexpr (N),
7215 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7216
7217 Right_Opnd =>
7218 Make_Not_In (Loc,
7219 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
7220 Right_Opnd =>
7221 New_Occurrence_Of (Target_Type, Loc))),
7222
20cf157b 7223 Reason => Reason)),
9dfe12ae 7224 Suppress => All_Checks);
7225
feff2f05 7226 -- Set the Etype explicitly, because Insert_Actions may have
7227 -- placed the declaration in the freeze list for an enclosing
7228 -- construct, and thus it is not analyzed yet.
9dfe12ae 7229
7230 Set_Etype (Tnn, Target_Base_Type);
7231 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
7232 end;
7233 end if;
7234 end if;
7235 end Generate_Range_Check;
7236
2af58f67 7237 ------------------
7238 -- Get_Check_Id --
7239 ------------------
7240
7241 function Get_Check_Id (N : Name_Id) return Check_Id is
7242 begin
7243 -- For standard check name, we can do a direct computation
7244
7245 if N in First_Check_Name .. Last_Check_Name then
7246 return Check_Id (N - (First_Check_Name - 1));
7247
7248 -- For non-standard names added by pragma Check_Name, search table
7249
7250 else
7251 for J in All_Checks + 1 .. Check_Names.Last loop
7252 if Check_Names.Table (J) = N then
7253 return J;
7254 end if;
7255 end loop;
7256 end if;
7257
7258 -- No matching name found
7259
7260 return No_Check_Id;
7261 end Get_Check_Id;
7262
ee6ba406 7263 ---------------------
7264 -- Get_Discriminal --
7265 ---------------------
7266
7267 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
7268 Loc : constant Source_Ptr := Sloc (E);
7269 D : Entity_Id;
7270 Sc : Entity_Id;
7271
7272 begin
0577b0b1 7273 -- The bound can be a bona fide parameter of a protected operation,
7274 -- rather than a prival encoded as an in-parameter.
7275
7276 if No (Discriminal_Link (Entity (Bound))) then
7277 return Bound;
7278 end if;
7279
2af58f67 7280 -- Climb the scope stack looking for an enclosing protected type. If
7281 -- we run out of scopes, return the bound itself.
7282
7283 Sc := Scope (E);
7284 while Present (Sc) loop
7285 if Sc = Standard_Standard then
7286 return Bound;
2af58f67 7287 elsif Ekind (Sc) = E_Protected_Type then
7288 exit;
7289 end if;
7290
7291 Sc := Scope (Sc);
7292 end loop;
7293
ee6ba406 7294 D := First_Discriminant (Sc);
2af58f67 7295 while Present (D) loop
7296 if Chars (D) = Chars (Bound) then
7297 return New_Occurrence_Of (Discriminal (D), Loc);
7298 end if;
ee6ba406 7299
ee6ba406 7300 Next_Discriminant (D);
7301 end loop;
7302
2af58f67 7303 return Bound;
ee6ba406 7304 end Get_Discriminal;
7305
2af58f67 7306 ----------------------
7307 -- Get_Range_Checks --
7308 ----------------------
7309
7310 function Get_Range_Checks
7311 (Ck_Node : Node_Id;
7312 Target_Typ : Entity_Id;
7313 Source_Typ : Entity_Id := Empty;
7314 Warn_Node : Node_Id := Empty) return Check_Result
7315 is
7316 begin
20cf157b 7317 return
7318 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
2af58f67 7319 end Get_Range_Checks;
7320
ee6ba406 7321 ------------------
7322 -- Guard_Access --
7323 ------------------
7324
7325 function Guard_Access
7326 (Cond : Node_Id;
7327 Loc : Source_Ptr;
314a23b6 7328 Ck_Node : Node_Id) return Node_Id
ee6ba406 7329 is
7330 begin
7331 if Nkind (Cond) = N_Or_Else then
7332 Set_Paren_Count (Cond, 1);
7333 end if;
7334
7335 if Nkind (Ck_Node) = N_Allocator then
7336 return Cond;
20cf157b 7337
ee6ba406 7338 else
7339 return
7340 Make_And_Then (Loc,
7341 Left_Opnd =>
7342 Make_Op_Ne (Loc,
9dfe12ae 7343 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
ee6ba406 7344 Right_Opnd => Make_Null (Loc)),
7345 Right_Opnd => Cond);
7346 end if;
7347 end Guard_Access;
7348
7349 -----------------------------
7350 -- Index_Checks_Suppressed --
7351 -----------------------------
7352
7353 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
7354 begin
9dfe12ae 7355 if Present (E) and then Checks_May_Be_Suppressed (E) then
7356 return Is_Check_Suppressed (E, Index_Check);
7357 else
fafc6b97 7358 return Scope_Suppress.Suppress (Index_Check);
9dfe12ae 7359 end if;
ee6ba406 7360 end Index_Checks_Suppressed;
7361
7362 ----------------
7363 -- Initialize --
7364 ----------------
7365
7366 procedure Initialize is
7367 begin
7368 for J in Determine_Range_Cache_N'Range loop
7369 Determine_Range_Cache_N (J) := Empty;
7370 end loop;
2af58f67 7371
7372 Check_Names.Init;
7373
7374 for J in Int range 1 .. All_Checks loop
7375 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
7376 end loop;
ee6ba406 7377 end Initialize;
7378
7379 -------------------------
7380 -- Insert_Range_Checks --
7381 -------------------------
7382
7383 procedure Insert_Range_Checks
7384 (Checks : Check_Result;
7385 Node : Node_Id;
7386 Suppress_Typ : Entity_Id;
7387 Static_Sloc : Source_Ptr := No_Location;
7388 Flag_Node : Node_Id := Empty;
7389 Do_Before : Boolean := False)
7390 is
2b4f2458 7391 Checks_On : constant Boolean :=
7392 not Index_Checks_Suppressed (Suppress_Typ)
7393 or else
7394 not Range_Checks_Suppressed (Suppress_Typ);
7395
7396 Check_Node : Node_Id;
ee6ba406 7397 Internal_Flag_Node : Node_Id := Flag_Node;
7398 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
7399
ee6ba406 7400 begin
feff2f05 7401 -- For now we just return if Checks_On is false, however this should be
7402 -- enhanced to check for an always True value in the condition and to
7403 -- generate a compilation warning???
ee6ba406 7404
ac9184ed 7405 if not Expander_Active or not Checks_On then
ee6ba406 7406 return;
7407 end if;
7408
7409 if Static_Sloc = No_Location then
7410 Internal_Static_Sloc := Sloc (Node);
7411 end if;
7412
7413 if No (Flag_Node) then
7414 Internal_Flag_Node := Node;
7415 end if;
7416
7417 for J in 1 .. 2 loop
7418 exit when No (Checks (J));
7419
7420 if Nkind (Checks (J)) = N_Raise_Constraint_Error
7421 and then Present (Condition (Checks (J)))
7422 then
7423 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
7424 Check_Node := Checks (J);
7425 Mark_Rewrite_Insertion (Check_Node);
7426
7427 if Do_Before then
7428 Insert_Before_And_Analyze (Node, Check_Node);
7429 else
7430 Insert_After_And_Analyze (Node, Check_Node);
7431 end if;
7432
7433 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
7434 end if;
7435
7436 else
7437 Check_Node :=
f15731c4 7438 Make_Raise_Constraint_Error (Internal_Static_Sloc,
7439 Reason => CE_Range_Check_Failed);
ee6ba406 7440 Mark_Rewrite_Insertion (Check_Node);
7441
7442 if Do_Before then
7443 Insert_Before_And_Analyze (Node, Check_Node);
7444 else
7445 Insert_After_And_Analyze (Node, Check_Node);
7446 end if;
7447 end if;
7448 end loop;
7449 end Insert_Range_Checks;
7450
7451 ------------------------
7452 -- Insert_Valid_Check --
7453 ------------------------
7454
aaec8d13 7455 procedure Insert_Valid_Check
7456 (Expr : Node_Id;
7457 Related_Id : Entity_Id := Empty;
7458 Is_Low_Bound : Boolean := False;
7459 Is_High_Bound : Boolean := False)
7460 is
ee6ba406 7461 Loc : constant Source_Ptr := Sloc (Expr);
70580828 7462 Typ : constant Entity_Id := Etype (Expr);
8b718dab 7463 Exp : Node_Id;
ee6ba406 7464
7465 begin
aaec8d13 7466 -- Do not insert if checks off, or if not checking validity or if
7467 -- expression is known to be valid.
ee6ba406 7468
0577b0b1 7469 if not Validity_Checks_On
7470 or else Range_Or_Validity_Checks_Suppressed (Expr)
06ad5813 7471 or else Expr_Known_Valid (Expr)
ee6ba406 7472 then
8b718dab 7473 return;
ee6ba406 7474
42c57d55 7475 -- Do not insert checks within a predicate function. This will arise
7476 -- if the current unit and the predicate function are being compiled
7477 -- with validity checks enabled.
70580828 7478
89e864b9 7479 elsif Present (Predicate_Function (Typ))
70580828 7480 and then Current_Scope = Predicate_Function (Typ)
7481 then
7482 return;
70580828 7483
310c1cde 7484 -- If the expression is a packed component of a modular type of the
7485 -- right size, the data is always valid.
7486
89e864b9 7487 elsif Nkind (Expr) = N_Selected_Component
310c1cde 7488 and then Present (Component_Clause (Entity (Selector_Name (Expr))))
7489 and then Is_Modular_Integer_Type (Typ)
7490 and then Modulus (Typ) = 2 ** Esize (Entity (Selector_Name (Expr)))
7491 then
7492 return;
89e864b9 7493
7494 -- Do not generate a validity check when inside a generic unit as this
7495 -- is an expansion activity.
7496
7497 elsif Inside_A_Generic then
7498 return;
310c1cde 7499 end if;
7500
7a42b778 7501 -- Entities declared in Lock_free protected types must be treated as
7502 -- volatile, and we must inhibit validity checks to prevent improper
7503 -- constant folding.
866fa2d0 7504
7505 if Is_Entity_Name (Expr)
7506 and then Is_Subprogram (Scope (Entity (Expr)))
7507 and then Present (Protected_Subprogram (Scope (Entity (Expr))))
7508 and then Uses_Lock_Free
7a42b778 7509 (Scope (Protected_Subprogram (Scope (Entity (Expr)))))
866fa2d0 7510 then
7511 return;
7512 end if;
7513
8b718dab 7514 -- If we have a checked conversion, then validity check applies to
7515 -- the expression inside the conversion, not the result, since if
7516 -- the expression inside is valid, then so is the conversion result.
ee6ba406 7517
8b718dab 7518 Exp := Expr;
7519 while Nkind (Exp) = N_Type_Conversion loop
7520 Exp := Expression (Exp);
7521 end loop;
7522
fdb8488b 7523 -- Do not generate a check for a variable which already validates the
7524 -- value of an assignable object.
7525
7526 if Is_Validation_Variable_Reference (Exp) then
7527 return;
7528 end if;
7529
0577b0b1 7530 declare
49adf385 7531 CE : Node_Id;
49adf385 7532 PV : Node_Id;
7533 Var_Id : Entity_Id;
05fcfafb 7534
0577b0b1 7535 begin
fdb8488b 7536 -- If the expression denotes an assignable object, capture its value
7537 -- in a variable and replace the original expression by the variable.
7538 -- This approach has several effects:
06ad5813 7539
fdb8488b 7540 -- 1) The evaluation of the object results in only one read in the
7541 -- case where the object is atomic or volatile.
fa771c05 7542
49adf385 7543 -- Var ... := Object; -- read
fa771c05 7544
fdb8488b 7545 -- 2) The captured value is the one verified by attribute 'Valid.
7546 -- As a result the object is not evaluated again, which would
7547 -- result in an unwanted read in the case where the object is
7548 -- atomic or volatile.
7549
49adf385 7550 -- if not Var'Valid then -- OK, no read of Object
fdb8488b 7551
7552 -- if not Object'Valid then -- Wrong, extra read of Object
7553
7554 -- 3) The captured value replaces the original object reference.
7555 -- As a result the object is not evaluated again, in the same
7556 -- vein as 2).
7557
49adf385 7558 -- ... Var ... -- OK, no read of Object
fdb8488b 7559
7560 -- ... Object ... -- Wrong, extra read of Object
06ad5813 7561
fdb8488b 7562 -- 4) The use of a variable to capture the value of the object
7563 -- allows the propagation of any changes back to the original
7564 -- object.
7565
7566 -- procedure Call (Val : in out ...);
7567
49adf385 7568 -- Var : ... := Object; -- read Object
7569 -- if not Var'Valid then -- validity check
7570 -- Call (Var); -- modify Var
7571 -- Object := Var; -- update Object
fdb8488b 7572
7573 if Is_Variable (Exp) then
49adf385 7574 Var_Id := Make_Temporary (Loc, 'T', Exp);
fdb8488b 7575
4cb8adff 7576 -- Because we could be dealing with a transient scope which would
7577 -- cause our object declaration to remain unanalyzed we must do
7578 -- some manual decoration.
7579
7580 Set_Ekind (Var_Id, E_Variable);
7581 Set_Etype (Var_Id, Typ);
7582
fdb8488b 7583 Insert_Action (Exp,
7584 Make_Object_Declaration (Loc,
49adf385 7585 Defining_Identifier => Var_Id,
fdb8488b 7586 Object_Definition => New_Occurrence_Of (Typ, Loc),
bf5f89dc 7587 Expression => New_Copy_Tree (Exp)),
7588 Suppress => Validity_Check);
7589
7590 Set_Validated_Object (Var_Id, New_Copy_Tree (Exp));
e54cffd1 7591
49adf385 7592 Rewrite (Exp, New_Occurrence_Of (Var_Id, Loc));
fdb8488b 7593
138c6242 7594 -- Move the Do_Range_Check flag over to the new Exp so it doesn't
7595 -- get lost and doesn't leak elsewhere.
02585eb0 7596
138c6242 7597 if Do_Range_Check (Validated_Object (Var_Id)) then
7598 Set_Do_Range_Check (Exp);
7599 Set_Do_Range_Check (Validated_Object (Var_Id), False);
02585eb0 7600 end if;
7601
e54cffd1 7602 PV := New_Occurrence_Of (Var_Id, Loc);
7603
fdb8488b 7604 -- Otherwise the expression does not denote a variable. Force its
7605 -- evaluation by capturing its value in a constant. Generate:
7606
7607 -- Temp : constant ... := Exp;
7608
7609 else
7610 Force_Evaluation
7611 (Exp => Exp,
7612 Related_Id => Related_Id,
7613 Is_Low_Bound => Is_Low_Bound,
7614 Is_High_Bound => Is_High_Bound);
7615
7616 PV := New_Copy_Tree (Exp);
7617 end if;
0577b0b1 7618
443bdccb 7619 -- A rather specialized test. If PV is an analyzed expression which
7620 -- is an indexed component of a packed array that has not been
7621 -- properly expanded, turn off its Analyzed flag to make sure it
5f46de53 7622 -- gets properly reexpanded. If the prefix is an access value,
7623 -- the dereference will be added later.
23abd64d 7624
7625 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
7626 -- an analyze with the old parent pointer. This may point e.g. to
7627 -- a subprogram call, which deactivates this expansion.
7628
7629 if Analyzed (PV)
7630 and then Nkind (PV) = N_Indexed_Component
5f46de53 7631 and then Is_Array_Type (Etype (Prefix (PV)))
a88a5773 7632 and then Present (Packed_Array_Impl_Type (Etype (Prefix (PV))))
23abd64d 7633 then
7634 Set_Analyzed (PV, False);
7635 end if;
7636
fa771c05 7637 -- Build the raise CE node to check for validity. We build a type
7638 -- qualification for the prefix, since it may not be of the form of
7639 -- a name, and we don't care in this context!
23abd64d 7640
7641 CE :=
aaec8d13 7642 Make_Raise_Constraint_Error (Loc,
7643 Condition =>
7644 Make_Op_Not (Loc,
7645 Right_Opnd =>
7646 Make_Attribute_Reference (Loc,
7647 Prefix => PV,
7648 Attribute_Name => Name_Valid)),
7649 Reason => CE_Invalid_Data);
23abd64d 7650
7651 -- Insert the validity check. Note that we do this with validity
7652 -- checks turned off, to avoid recursion, we do not want validity
39a0c1d3 7653 -- checks on the validity checking code itself.
23abd64d 7654
7655 Insert_Action (Expr, CE, Suppress => Validity_Check);
0577b0b1 7656
6fb3c314 7657 -- If the expression is a reference to an element of a bit-packed
0577b0b1 7658 -- array, then it is rewritten as a renaming declaration. If the
7659 -- expression is an actual in a call, it has not been expanded,
7660 -- waiting for the proper point at which to do it. The same happens
7661 -- with renamings, so that we have to force the expansion now. This
7662 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
7663 -- and exp_ch6.adb.
7664
7665 if Is_Entity_Name (Exp)
7666 and then Nkind (Parent (Entity (Exp))) =
20cf157b 7667 N_Object_Renaming_Declaration
0577b0b1 7668 then
7669 declare
7670 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
7671 begin
7672 if Nkind (Old_Exp) = N_Indexed_Component
7673 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
7674 then
7675 Expand_Packed_Element_Reference (Old_Exp);
7676 end if;
7677 end;
7678 end if;
0577b0b1 7679 end;
ee6ba406 7680 end Insert_Valid_Check;
7681
3cce7f32 7682 -------------------------------------
7683 -- Is_Signed_Integer_Arithmetic_Op --
7684 -------------------------------------
7685
7686 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean is
7687 begin
7688 case Nkind (N) is
99378362 7689 when N_Op_Abs
7690 | N_Op_Add
7691 | N_Op_Divide
7692 | N_Op_Expon
7693 | N_Op_Minus
7694 | N_Op_Mod
7695 | N_Op_Multiply
7696 | N_Op_Plus
7697 | N_Op_Rem
7698 | N_Op_Subtract
7699 =>
3cce7f32 7700 return Is_Signed_Integer_Type (Etype (N));
7701
99378362 7702 when N_Case_Expression
7703 | N_If_Expression
7704 =>
0326b4d4 7705 return Is_Signed_Integer_Type (Etype (N));
7706
3cce7f32 7707 when others =>
7708 return False;
7709 end case;
7710 end Is_Signed_Integer_Arithmetic_Op;
7711
fa7497e8 7712 ----------------------------------
7713 -- Install_Null_Excluding_Check --
7714 ----------------------------------
7715
7716 procedure Install_Null_Excluding_Check (N : Node_Id) is
9f294c82 7717 Loc : constant Source_Ptr := Sloc (Parent (N));
84d0d4a5 7718 Typ : constant Entity_Id := Etype (N);
7719
7b31b357 7720 function Safe_To_Capture_In_Parameter_Value return Boolean;
7721 -- Determines if it is safe to capture Known_Non_Null status for an
7722 -- the entity referenced by node N. The caller ensures that N is indeed
7723 -- an entity name. It is safe to capture the non-null status for an IN
7724 -- parameter when the reference occurs within a declaration that is sure
7725 -- to be executed as part of the declarative region.
7870823d 7726
84d0d4a5 7727 procedure Mark_Non_Null;
7870823d 7728 -- After installation of check, if the node in question is an entity
7729 -- name, then mark this entity as non-null if possible.
7730
7b31b357 7731 function Safe_To_Capture_In_Parameter_Value return Boolean is
7870823d 7732 E : constant Entity_Id := Entity (N);
7733 S : constant Entity_Id := Current_Scope;
7734 S_Par : Node_Id;
7735
7736 begin
7b31b357 7737 if Ekind (E) /= E_In_Parameter then
7738 return False;
7739 end if;
7870823d 7740
7741 -- Two initial context checks. We must be inside a subprogram body
7742 -- with declarations and reference must not appear in nested scopes.
7743
7b31b357 7744 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
7870823d 7745 or else Scope (E) /= S
7746 then
7747 return False;
7748 end if;
7749
7750 S_Par := Parent (Parent (S));
7751
7752 if Nkind (S_Par) /= N_Subprogram_Body
7753 or else No (Declarations (S_Par))
7754 then
7755 return False;
7756 end if;
7757
7758 declare
7759 N_Decl : Node_Id;
7760 P : Node_Id;
7761
7762 begin
7763 -- Retrieve the declaration node of N (if any). Note that N
7764 -- may be a part of a complex initialization expression.
7765
7766 P := Parent (N);
7767 N_Decl := Empty;
7768 while Present (P) loop
7769
7b31b357 7770 -- If we have a short circuit form, and we are within the right
7771 -- hand expression, we return false, since the right hand side
7772 -- is not guaranteed to be elaborated.
7773
7774 if Nkind (P) in N_Short_Circuit
7775 and then N = Right_Opnd (P)
7776 then
7777 return False;
7778 end if;
7779
92f1631f 7780 -- Similarly, if we are in an if expression and not part of the
7781 -- condition, then we return False, since neither the THEN or
7782 -- ELSE dependent expressions will always be elaborated.
7b31b357 7783
92f1631f 7784 if Nkind (P) = N_If_Expression
7b31b357 7785 and then N /= First (Expressions (P))
7786 then
7787 return False;
e977c0cf 7788 end if;
7789
20cf157b 7790 -- If within a case expression, and not part of the expression,
7791 -- then return False, since a particular dependent expression
7792 -- may not always be elaborated
e977c0cf 7793
7794 if Nkind (P) = N_Case_Expression
7795 and then N /= Expression (P)
7796 then
7797 return False;
7b31b357 7798 end if;
7799
20cf157b 7800 -- While traversing the parent chain, if node N belongs to a
7801 -- statement, then it may never appear in a declarative region.
7870823d 7802
7803 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
7804 or else Nkind (P) = N_Procedure_Call_Statement
7805 then
7806 return False;
7807 end if;
7808
7b31b357 7809 -- If we are at a declaration, record it and exit
7810
7870823d 7811 if Nkind (P) in N_Declaration
7812 and then Nkind (P) not in N_Subprogram_Specification
7813 then
7814 N_Decl := P;
7815 exit;
7816 end if;
7817
7818 P := Parent (P);
7819 end loop;
7820
7821 if No (N_Decl) then
7822 return False;
7823 end if;
7824
7825 return List_Containing (N_Decl) = Declarations (S_Par);
7826 end;
7b31b357 7827 end Safe_To_Capture_In_Parameter_Value;
84d0d4a5 7828
7829 -------------------
7830 -- Mark_Non_Null --
7831 -------------------
7832
7833 procedure Mark_Non_Null is
7834 begin
7870823d 7835 -- Only case of interest is if node N is an entity name
7836
84d0d4a5 7837 if Is_Entity_Name (N) then
7870823d 7838
7839 -- For sure, we want to clear an indication that this is known to
39a0c1d3 7840 -- be null, since if we get past this check, it definitely is not.
7870823d 7841
84d0d4a5 7842 Set_Is_Known_Null (Entity (N), False);
7843
7870823d 7844 -- We can mark the entity as known to be non-null if either it is
7845 -- safe to capture the value, or in the case of an IN parameter,
7846 -- which is a constant, if the check we just installed is in the
7847 -- declarative region of the subprogram body. In this latter case,
7b31b357 7848 -- a check is decisive for the rest of the body if the expression
7849 -- is sure to be elaborated, since we know we have to elaborate
7850 -- all declarations before executing the body.
7851
7852 -- Couldn't this always be part of Safe_To_Capture_Value ???
7870823d 7853
7854 if Safe_To_Capture_Value (N, Entity (N))
7b31b357 7855 or else Safe_To_Capture_In_Parameter_Value
7870823d 7856 then
7857 Set_Is_Known_Non_Null (Entity (N));
84d0d4a5 7858 end if;
7859 end if;
7860 end Mark_Non_Null;
7861
7862 -- Start of processing for Install_Null_Excluding_Check
fa7497e8 7863
7864 begin
c9bbc06b 7865 -- No need to add null-excluding checks when the tree may not be fully
7866 -- decorated.
7867
7868 if Serious_Errors_Detected > 0 then
7869 return;
7870 end if;
7871
84d0d4a5 7872 pragma Assert (Is_Access_Type (Typ));
fa7497e8 7873
46e32b5e 7874 -- No check inside a generic, check will be emitted in instance
fa7497e8 7875
84d0d4a5 7876 if Inside_A_Generic then
fa7497e8 7877 return;
84d0d4a5 7878 end if;
7879
7880 -- No check needed if known to be non-null
7881
7882 if Known_Non_Null (N) then
05fcfafb 7883 return;
84d0d4a5 7884 end if;
fa7497e8 7885
84d0d4a5 7886 -- If known to be null, here is where we generate a compile time check
7887
7888 if Known_Null (N) then
d16989f1 7889
20cf157b 7890 -- Avoid generating warning message inside init procs. In SPARK mode
7891 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
46e32b5e 7892 -- since it will be turned into an error in any case.
d16989f1 7893
46e32b5e 7894 if (not Inside_Init_Proc or else SPARK_Mode = On)
7895
28d5d68f 7896 -- Do not emit the warning within a conditional expression,
7897 -- where the expression might not be evaluated, and the warning
7898 -- appear as extraneous noise.
46e32b5e 7899
7900 and then not Within_Case_Or_If_Expression (N)
7901 then
d16989f1 7902 Apply_Compile_Time_Constraint_Error
4098232e 7903 (N, "null value not allowed here??", CE_Access_Check_Failed);
46e32b5e 7904
7905 -- Remaining cases, where we silently insert the raise
7906
d16989f1 7907 else
7908 Insert_Action (N,
7909 Make_Raise_Constraint_Error (Loc,
7910 Reason => CE_Access_Check_Failed));
7911 end if;
7912
84d0d4a5 7913 Mark_Non_Null;
7914 return;
7915 end if;
7916
7917 -- If entity is never assigned, for sure a warning is appropriate
7918
7919 if Is_Entity_Name (N) then
7920 Check_Unset_Reference (N);
fa7497e8 7921 end if;
84d0d4a5 7922
7923 -- No check needed if checks are suppressed on the range. Note that we
7924 -- don't set Is_Known_Non_Null in this case (we could legitimately do
7925 -- so, since the program is erroneous, but we don't like to casually
7926 -- propagate such conclusions from erroneosity).
7927
7928 if Access_Checks_Suppressed (Typ) then
7929 return;
7930 end if;
7931
2af58f67 7932 -- No check needed for access to concurrent record types generated by
7933 -- the expander. This is not just an optimization (though it does indeed
7934 -- remove junk checks). It also avoids generation of junk warnings.
7935
7936 if Nkind (N) in N_Has_Chars
7937 and then Chars (N) = Name_uObject
7938 and then Is_Concurrent_Record_Type
7939 (Directly_Designated_Type (Etype (N)))
7940 then
7941 return;
7942 end if;
7943
228836e8 7944 -- No check needed in interface thunks since the runtime check is
7945 -- already performed at the caller side.
7946
7947 if Is_Thunk (Current_Scope) then
7948 return;
7949 end if;
7950
472ea160 7951 -- No check needed for the Get_Current_Excep.all.all idiom generated by
7952 -- the expander within exception handlers, since we know that the value
7953 -- can never be null.
7954
7955 -- Is this really the right way to do this? Normally we generate such
7956 -- code in the expander with checks off, and that's how we suppress this
7957 -- kind of junk check ???
7958
7959 if Nkind (N) = N_Function_Call
7960 and then Nkind (Name (N)) = N_Explicit_Dereference
7961 and then Nkind (Prefix (Name (N))) = N_Identifier
7962 and then Is_RTE (Entity (Prefix (Name (N))), RE_Get_Current_Excep)
7963 then
7964 return;
7965 end if;
7966
84d0d4a5 7967 -- Otherwise install access check
7968
7969 Insert_Action (N,
7970 Make_Raise_Constraint_Error (Loc,
7971 Condition =>
7972 Make_Op_Eq (Loc,
7973 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
7974 Right_Opnd => Make_Null (Loc)),
7975 Reason => CE_Access_Check_Failed));
7976
7977 Mark_Non_Null;
fa7497e8 7978 end Install_Null_Excluding_Check;
7979
7e933b61 7980 -----------------------------------------
7981 -- Install_Primitive_Elaboration_Check --
7982 -----------------------------------------
7983
7984 procedure Install_Primitive_Elaboration_Check (Subp_Body : Node_Id) is
7e933b61 7985 function Within_Compilation_Unit_Instance
7986 (Subp_Id : Entity_Id) return Boolean;
7987 -- Determine whether subprogram Subp_Id appears within an instance which
7988 -- acts as a compilation unit.
7989
7990 --------------------------------------
7991 -- Within_Compilation_Unit_Instance --
7992 --------------------------------------
7993
7994 function Within_Compilation_Unit_Instance
7995 (Subp_Id : Entity_Id) return Boolean
7996 is
7997 Pack : Entity_Id;
7998
7999 begin
8000 -- Examine the scope chain looking for a compilation-unit-level
8001 -- instance.
8002
8003 Pack := Scope (Subp_Id);
8004 while Present (Pack) and then Pack /= Standard_Standard loop
8005 if Ekind (Pack) = E_Package
8006 and then Is_Generic_Instance (Pack)
8007 and then Nkind (Parent (Unit_Declaration_Node (Pack))) =
8008 N_Compilation_Unit
8009 then
8010 return True;
8011 end if;
8012
8013 Pack := Scope (Pack);
8014 end loop;
8015
8016 return False;
8017 end Within_Compilation_Unit_Instance;
8018
8019 -- Local declarations
8020
8021 Context : constant Node_Id := Parent (Subp_Body);
8022 Loc : constant Source_Ptr := Sloc (Subp_Body);
8023 Subp_Id : constant Entity_Id := Unique_Defining_Entity (Subp_Body);
8024 Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
8025
e2293a63 8026 Decls : List_Id;
8027 Flag_Id : Entity_Id;
8028 Set_Ins : Node_Id;
8029 Set_Stmt : Node_Id;
8030 Tag_Typ : Entity_Id;
7e933b61 8031
8032 -- Start of processing for Install_Primitive_Elaboration_Check
8033
8034 begin
8035 -- Do not generate an elaboration check in compilation modes where
8036 -- expansion is not desirable.
8037
8038 if ASIS_Mode or GNATprove_Mode then
8039 return;
8040
f0e731f2 8041 -- Do not generate an elaboration check if all checks have been
8042 -- suppressed.
62c62e4b 8043
f0e731f2 8044 elsif Suppress_Checks then
62c62e4b 8045 return;
8046
7e933b61 8047 -- Do not generate an elaboration check if the related subprogram is
8048 -- not subjected to accessibility checks.
8049
8050 elsif Elaboration_Checks_Suppressed (Subp_Id) then
8051 return;
f0e731f2 8052
8053 -- Do not generate an elaboration check if such code is not desirable
8054
8055 elsif Restriction_Active (No_Elaboration_Code) then
8056 return;
7e933b61 8057
77b577f9 8058 -- Do not generate an elaboration check if exceptions cannot be used,
8059 -- caught, or propagated.
8060
8061 elsif not Exceptions_OK then
8062 return;
8063
7e933b61 8064 -- Do not consider subprograms which act as compilation units, because
8065 -- they cannot be the target of a dispatching call.
8066
8067 elsif Nkind (Context) = N_Compilation_Unit then
8068 return;
8069
e2293a63 8070 -- Do not consider anything other than nonabstract library-level source
8071 -- primitives.
7e933b61 8072
8073 elsif not
8074 (Comes_From_Source (Subp_Id)
8075 and then Is_Library_Level_Entity (Subp_Id)
8076 and then Is_Primitive (Subp_Id)
8077 and then not Is_Abstract_Subprogram (Subp_Id))
8078 then
8079 return;
8080
8081 -- Do not consider inlined primitives, because once the body is inlined
8082 -- the reference to the elaboration flag will be out of place and will
8083 -- result in an undefined symbol.
8084
8085 elsif Is_Inlined (Subp_Id) or else Has_Pragma_Inline (Subp_Id) then
8086 return;
8087
8088 -- Do not generate a duplicate elaboration check. This happens only in
8089 -- the case of primitives completed by an expression function, as the
8090 -- corresponding body is apparently analyzed and expanded twice.
8091
8092 elsif Analyzed (Subp_Body) then
8093 return;
8094
8095 -- Do not consider primitives which occur within an instance that acts
8096 -- as a compilation unit. Such an instance defines its spec and body out
8097 -- of order (body is first) within the tree, which causes the reference
8098 -- to the elaboration flag to appear as an undefined symbol.
8099
8100 elsif Within_Compilation_Unit_Instance (Subp_Id) then
8101 return;
8102 end if;
8103
8104 Tag_Typ := Find_Dispatching_Type (Subp_Id);
8105
8106 -- Only tagged primitives may be the target of a dispatching call
8107
8108 if No (Tag_Typ) then
8109 return;
8110
8111 -- Do not consider finalization-related primitives, because they may
8112 -- need to be called while elaboration is taking place.
8113
8114 elsif Is_Controlled (Tag_Typ)
8115 and then Nam_In (Chars (Subp_Id), Name_Adjust,
8116 Name_Finalize,
8117 Name_Initialize)
8118 then
8119 return;
8120 end if;
8121
8122 -- Create the declaration of the elaboration flag. The name carries a
8123 -- unique counter in case of name overloading.
8124
8125 Flag_Id :=
8126 Make_Defining_Identifier (Loc,
fe48a434 8127 Chars => New_External_Name (Chars (Subp_Id), 'E', -1));
7e933b61 8128 Set_Is_Frozen (Flag_Id);
8129
8130 -- Insert the declaration of the elaboration flag in front of the
8131 -- primitive spec and analyze it in the proper context.
8132
8133 Push_Scope (Scope (Subp_Id));
8134
8135 -- Generate:
fe48a434 8136 -- E : Boolean := False;
7e933b61 8137
8138 Insert_Action (Subp_Decl,
8139 Make_Object_Declaration (Loc,
8140 Defining_Identifier => Flag_Id,
8141 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
8142 Expression => New_Occurrence_Of (Standard_False, Loc)));
8143 Pop_Scope;
8144
8145 -- Prevent the compiler from optimizing the elaboration check by killing
8146 -- the current value of the flag and the associated assignment.
8147
8148 Set_Current_Value (Flag_Id, Empty);
8149 Set_Last_Assignment (Flag_Id, Empty);
8150
8151 -- Add a check at the top of the body declarations to ensure that the
8152 -- elaboration flag has been set.
8153
8154 Decls := Declarations (Subp_Body);
8155
8156 if No (Decls) then
8157 Decls := New_List;
8158 Set_Declarations (Subp_Body, Decls);
8159 end if;
8160
8161 -- Generate:
8162 -- if not F then
8163 -- raise Program_Error with "access before elaboration";
8164 -- end if;
8165
8166 Prepend_To (Decls,
8167 Make_Raise_Program_Error (Loc,
8168 Condition =>
8169 Make_Op_Not (Loc,
8170 Right_Opnd => New_Occurrence_Of (Flag_Id, Loc)),
8171 Reason => PE_Access_Before_Elaboration));
8172
8173 Analyze (First (Decls));
8174
8175 -- Set the elaboration flag once the body has been elaborated. Insert
8176 -- the statement after the subprogram stub when the primitive body is
8177 -- a subunit.
8178
8179 if Nkind (Context) = N_Subunit then
8180 Set_Ins := Corresponding_Stub (Context);
8181 else
8182 Set_Ins := Subp_Body;
8183 end if;
8184
8185 -- Generate:
fe48a434 8186 -- E := True;
7e933b61 8187
e2293a63 8188 Set_Stmt :=
7e933b61 8189 Make_Assignment_Statement (Loc,
8190 Name => New_Occurrence_Of (Flag_Id, Loc),
e2293a63 8191 Expression => New_Occurrence_Of (Standard_True, Loc));
8192
8193 -- Mark the assignment statement as elaboration code. This allows the
8194 -- early call region mechanism (see Sem_Elab) to properly ignore such
8195 -- assignments even though they are non-preelaborable code.
8196
8197 Set_Is_Elaboration_Code (Set_Stmt);
8198
8199 Insert_After_And_Analyze (Set_Ins, Set_Stmt);
7e933b61 8200 end Install_Primitive_Elaboration_Check;
8201
ee6ba406 8202 --------------------------
8203 -- Install_Static_Check --
8204 --------------------------
8205
8206 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
cda40848 8207 Stat : constant Boolean := Is_OK_Static_Expression (R_Cno);
ee6ba406 8208 Typ : constant Entity_Id := Etype (R_Cno);
8209
8210 begin
f15731c4 8211 Rewrite (R_Cno,
8212 Make_Raise_Constraint_Error (Loc,
8213 Reason => CE_Range_Check_Failed));
ee6ba406 8214 Set_Analyzed (R_Cno);
8215 Set_Etype (R_Cno, Typ);
8216 Set_Raises_Constraint_Error (R_Cno);
8217 Set_Is_Static_Expression (R_Cno, Stat);
840ab274 8218
8219 -- Now deal with possible local raise handling
8220
8221 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
ee6ba406 8222 end Install_Static_Check;
8223
3cce7f32 8224 -------------------------
8225 -- Is_Check_Suppressed --
8226 -------------------------
8227
8228 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean is
8229 Ptr : Suppress_Stack_Entry_Ptr;
8230
8231 begin
8232 -- First search the local entity suppress stack. We search this from the
8233 -- top of the stack down so that we get the innermost entry that applies
8234 -- to this case if there are nested entries.
8235
8236 Ptr := Local_Suppress_Stack_Top;
8237 while Ptr /= null loop
8238 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8239 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8240 then
8241 return Ptr.Suppress;
8242 end if;
8243
8244 Ptr := Ptr.Prev;
8245 end loop;
8246
8247 -- Now search the global entity suppress table for a matching entry.
8248 -- We also search this from the top down so that if there are multiple
8249 -- pragmas for the same entity, the last one applies (not clear what
8250 -- or whether the RM specifies this handling, but it seems reasonable).
8251
8252 Ptr := Global_Suppress_Stack_Top;
8253 while Ptr /= null loop
8254 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8255 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8256 then
8257 return Ptr.Suppress;
8258 end if;
8259
8260 Ptr := Ptr.Prev;
8261 end loop;
8262
8263 -- If we did not find a matching entry, then use the normal scope
8264 -- suppress value after all (actually this will be the global setting
8265 -- since it clearly was not overridden at any point). For a predefined
8266 -- check, we test the specific flag. For a user defined check, we check
8267 -- the All_Checks flag. The Overflow flag requires special handling to
fe48a434 8268 -- deal with the General vs Assertion case.
3cce7f32 8269
8270 if C = Overflow_Check then
8271 return Overflow_Checks_Suppressed (Empty);
fe48a434 8272
3cce7f32 8273 elsif C in Predefined_Check_Id then
8274 return Scope_Suppress.Suppress (C);
fe48a434 8275
3cce7f32 8276 else
8277 return Scope_Suppress.Suppress (All_Checks);
8278 end if;
8279 end Is_Check_Suppressed;
8280
9dfe12ae 8281 ---------------------
8282 -- Kill_All_Checks --
8283 ---------------------
8284
8285 procedure Kill_All_Checks is
8286 begin
8287 if Debug_Flag_CC then
8288 w ("Kill_All_Checks");
8289 end if;
8290
feff2f05 8291 -- We reset the number of saved checks to zero, and also modify all
8292 -- stack entries for statement ranges to indicate that the number of
8293 -- checks at each level is now zero.
9dfe12ae 8294
8295 Num_Saved_Checks := 0;
8296
96da3284 8297 -- Note: the Int'Min here avoids any possibility of J being out of
8298 -- range when called from e.g. Conditional_Statements_Begin.
8299
8300 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
9dfe12ae 8301 Saved_Checks_Stack (J) := 0;
8302 end loop;
8303 end Kill_All_Checks;
8304
8305 -----------------
8306 -- Kill_Checks --
8307 -----------------
8308
8309 procedure Kill_Checks (V : Entity_Id) is
8310 begin
8311 if Debug_Flag_CC then
8312 w ("Kill_Checks for entity", Int (V));
8313 end if;
8314
8315 for J in 1 .. Num_Saved_Checks loop
8316 if Saved_Checks (J).Entity = V then
8317 if Debug_Flag_CC then
8318 w (" Checks killed for saved check ", J);
8319 end if;
8320
8321 Saved_Checks (J).Killed := True;
8322 end if;
8323 end loop;
8324 end Kill_Checks;
8325
ee6ba406 8326 ------------------------------
8327 -- Length_Checks_Suppressed --
8328 ------------------------------
8329
8330 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
8331 begin
9dfe12ae 8332 if Present (E) and then Checks_May_Be_Suppressed (E) then
8333 return Is_Check_Suppressed (E, Length_Check);
8334 else
fafc6b97 8335 return Scope_Suppress.Suppress (Length_Check);
9dfe12ae 8336 end if;
ee6ba406 8337 end Length_Checks_Suppressed;
8338
3cce7f32 8339 -----------------------
8340 -- Make_Bignum_Block --
8341 -----------------------
8342
8343 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id is
8344 M : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uM);
3cce7f32 8345 begin
8346 return
8347 Make_Block_Statement (Loc,
97c15ab0 8348 Declarations =>
8349 New_List (Build_SS_Mark_Call (Loc, M)),
3cce7f32 8350 Handled_Statement_Sequence =>
8351 Make_Handled_Sequence_Of_Statements (Loc,
97c15ab0 8352 Statements => New_List (Build_SS_Release_Call (Loc, M))));
3cce7f32 8353 end Make_Bignum_Block;
8354
0df9d43f 8355 ----------------------------------
8356 -- Minimize_Eliminate_Overflows --
8357 ----------------------------------
3cce7f32 8358
f32c377d 8359 -- This is a recursive routine that is called at the top of an expression
8360 -- tree to properly process overflow checking for a whole subtree by making
8361 -- recursive calls to process operands. This processing may involve the use
8362 -- of bignum or long long integer arithmetic, which will change the types
8363 -- of operands and results. That's why we can't do this bottom up (since
21a55437 8364 -- it would interfere with semantic analysis).
f32c377d 8365
21a55437 8366 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
0df9d43f 8367 -- the operator expansion routines, as well as the expansion routines for
8368 -- if/case expression, do nothing (for the moment) except call the routine
8369 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
8370 -- routine does nothing for non top-level nodes, so at the point where the
8371 -- call is made for the top level node, the entire expression subtree has
8372 -- not been expanded, or processed for overflow. All that has to happen as
8373 -- a result of the top level call to this routine.
f32c377d 8374
8375 -- As noted above, the overflow processing works by making recursive calls
8376 -- for the operands, and figuring out what to do, based on the processing
8377 -- of these operands (e.g. if a bignum operand appears, the parent op has
8378 -- to be done in bignum mode), and the determined ranges of the operands.
8379
8380 -- After possible rewriting of a constituent subexpression node, a call is
4fb5f0a0 8381 -- made to either reexpand the node (if nothing has changed) or reanalyze
21a55437 8382 -- the node (if it has been modified by the overflow check processing). The
8383 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
8384 -- a recursive call into the whole overflow apparatus, an important rule
0df9d43f 8385 -- for this call is that the overflow handling mode must be temporarily set
8386 -- to STRICT.
f32c377d 8387
0df9d43f 8388 procedure Minimize_Eliminate_Overflows
61016a7a 8389 (N : Node_Id;
8390 Lo : out Uint;
8391 Hi : out Uint;
8392 Top_Level : Boolean)
3cce7f32 8393 is
0326b4d4 8394 Rtyp : constant Entity_Id := Etype (N);
8395 pragma Assert (Is_Signed_Integer_Type (Rtyp));
8396 -- Result type, must be a signed integer type
3cce7f32 8397
db415383 8398 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
3cce7f32 8399 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
8400
8401 Loc : constant Source_Ptr := Sloc (N);
8402
8403 Rlo, Rhi : Uint;
0326b4d4 8404 -- Ranges of values for right operand (operator case)
3cce7f32 8405
16149377 8406 Llo : Uint := No_Uint; -- initialize to prevent warning
8407 Lhi : Uint := No_Uint; -- initialize to prevent warning
0326b4d4 8408 -- Ranges of values for left operand (operator case)
3cce7f32 8409
49b3a812 8410 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
8411 -- Operands and results are of this type when we convert
8412
0326b4d4 8413 LLLo : constant Uint := Intval (Type_Low_Bound (LLIB));
8414 LLHi : constant Uint := Intval (Type_High_Bound (LLIB));
3cce7f32 8415 -- Bounds of Long_Long_Integer
8416
8417 Binary : constant Boolean := Nkind (N) in N_Binary_Op;
8418 -- Indicates binary operator case
8419
8420 OK : Boolean;
8421 -- Used in call to Determine_Range
8422
61016a7a 8423 Bignum_Operands : Boolean;
8424 -- Set True if one or more operands is already of type Bignum, meaning
8425 -- that for sure (regardless of Top_Level setting) we are committed to
0326b4d4 8426 -- doing the operation in Bignum mode (or in the case of a case or if
21a55437 8427 -- expression, converting all the dependent expressions to Bignum).
0326b4d4 8428
8429 Long_Long_Integer_Operands : Boolean;
21a55437 8430 -- Set True if one or more operands is already of type Long_Long_Integer
0326b4d4 8431 -- which means that if the result is known to be in the result type
8432 -- range, then we must convert such operands back to the result type.
0df9d43f 8433
8434 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False);
8435 -- This is called when we have modified the node and we therefore need
8436 -- to reanalyze it. It is important that we reset the mode to STRICT for
8437 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
39a0c1d3 8438 -- we would reenter this routine recursively which would not be good.
0df9d43f 8439 -- The argument Suppress is set True if we also want to suppress
8440 -- overflow checking for the reexpansion (this is set when we know
8441 -- overflow is not possible). Typ is the type for the reanalysis.
8442
8443 procedure Reexpand (Suppress : Boolean := False);
8444 -- This is like Reanalyze, but does not do the Analyze step, it only
8445 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
8446 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
8447 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
8448 -- Note that skipping reanalysis is not just an optimization, testing
8449 -- has showed up several complex cases in which reanalyzing an already
8450 -- analyzed node causes incorrect behavior.
4fb5f0a0 8451
0326b4d4 8452 function In_Result_Range return Boolean;
8453 -- Returns True iff Lo .. Hi are within range of the result type
61016a7a 8454
2fe22c69 8455 procedure Max (A : in out Uint; B : Uint);
21a55437 8456 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
2fe22c69 8457
8458 procedure Min (A : in out Uint; B : Uint);
21a55437 8459 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
2fe22c69 8460
0326b4d4 8461 ---------------------
8462 -- In_Result_Range --
8463 ---------------------
8464
8465 function In_Result_Range return Boolean is
8466 begin
f32c377d 8467 if Lo = No_Uint or else Hi = No_Uint then
8468 return False;
8469
cda40848 8470 elsif Is_OK_Static_Subtype (Etype (N)) then
0326b4d4 8471 return Lo >= Expr_Value (Type_Low_Bound (Rtyp))
8472 and then
8473 Hi <= Expr_Value (Type_High_Bound (Rtyp));
f32c377d 8474
0326b4d4 8475 else
8476 return Lo >= Expr_Value (Type_Low_Bound (Base_Type (Rtyp)))
8477 and then
8478 Hi <= Expr_Value (Type_High_Bound (Base_Type (Rtyp)));
8479 end if;
8480 end In_Result_Range;
8481
2fe22c69 8482 ---------
8483 -- Max --
8484 ---------
8485
8486 procedure Max (A : in out Uint; B : Uint) is
8487 begin
8488 if A = No_Uint or else B > A then
8489 A := B;
8490 end if;
8491 end Max;
8492
8493 ---------
8494 -- Min --
8495 ---------
8496
8497 procedure Min (A : in out Uint; B : Uint) is
8498 begin
8499 if A = No_Uint or else B < A then
8500 A := B;
8501 end if;
8502 end Min;
8503
0df9d43f 8504 ---------------
8505 -- Reanalyze --
8506 ---------------
8507
8508 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False) is
db415383 8509 Svg : constant Overflow_Mode_Type :=
8510 Scope_Suppress.Overflow_Mode_General;
8511 Sva : constant Overflow_Mode_Type :=
8512 Scope_Suppress.Overflow_Mode_Assertions;
0df9d43f 8513 Svo : constant Boolean :=
8514 Scope_Suppress.Suppress (Overflow_Check);
8515
8516 begin
db415383 8517 Scope_Suppress.Overflow_Mode_General := Strict;
8518 Scope_Suppress.Overflow_Mode_Assertions := Strict;
0df9d43f 8519
8520 if Suppress then
8521 Scope_Suppress.Suppress (Overflow_Check) := True;
8522 end if;
8523
8524 Analyze_And_Resolve (N, Typ);
8525
2b108e18 8526 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8527 Scope_Suppress.Overflow_Mode_General := Svg;
8528 Scope_Suppress.Overflow_Mode_Assertions := Sva;
0df9d43f 8529 end Reanalyze;
8530
4fb5f0a0 8531 --------------
8532 -- Reexpand --
8533 --------------
8534
0df9d43f 8535 procedure Reexpand (Suppress : Boolean := False) is
db415383 8536 Svg : constant Overflow_Mode_Type :=
8537 Scope_Suppress.Overflow_Mode_General;
8538 Sva : constant Overflow_Mode_Type :=
8539 Scope_Suppress.Overflow_Mode_Assertions;
0df9d43f 8540 Svo : constant Boolean :=
8541 Scope_Suppress.Suppress (Overflow_Check);
8542
4fb5f0a0 8543 begin
db415383 8544 Scope_Suppress.Overflow_Mode_General := Strict;
8545 Scope_Suppress.Overflow_Mode_Assertions := Strict;
4fb5f0a0 8546 Set_Analyzed (N, False);
0df9d43f 8547
8548 if Suppress then
8549 Scope_Suppress.Suppress (Overflow_Check) := True;
8550 end if;
8551
4fb5f0a0 8552 Expand (N);
0df9d43f 8553
2b108e18 8554 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8555 Scope_Suppress.Overflow_Mode_General := Svg;
8556 Scope_Suppress.Overflow_Mode_Assertions := Sva;
4fb5f0a0 8557 end Reexpand;
8558
0df9d43f 8559 -- Start of processing for Minimize_Eliminate_Overflows
2fe22c69 8560
3cce7f32 8561 begin
02038e4e 8562 -- Default initialize Lo and Hi since these are not guaranteed to be
8563 -- set otherwise.
8564
8565 Lo := No_Uint;
8566 Hi := No_Uint;
8567
0326b4d4 8568 -- Case where we do not have a signed integer arithmetic operation
3cce7f32 8569
8570 if not Is_Signed_Integer_Arithmetic_Op (N) then
8571
8572 -- Use the normal Determine_Range routine to get the range. We
8573 -- don't require operands to be valid, invalid values may result in
8574 -- rubbish results where the result has not been properly checked for
39a0c1d3 8575 -- overflow, that's fine.
3cce7f32 8576
8577 Determine_Range (N, OK, Lo, Hi, Assume_Valid => False);
8578
21a55437 8579 -- If Determine_Range did not work (can this in fact happen? Not
3cce7f32 8580 -- clear but might as well protect), use type bounds.
8581
8582 if not OK then
8583 Lo := Intval (Type_Low_Bound (Base_Type (Etype (N))));
8584 Hi := Intval (Type_High_Bound (Base_Type (Etype (N))));
8585 end if;
8586
8587 -- If we don't have a binary operator, all we have to do is to set
20cf157b 8588 -- the Hi/Lo range, so we are done.
3cce7f32 8589
8590 return;
8591
0326b4d4 8592 -- Processing for if expression
8593
92f1631f 8594 elsif Nkind (N) = N_If_Expression then
0326b4d4 8595 declare
8596 Then_DE : constant Node_Id := Next (First (Expressions (N)));
8597 Else_DE : constant Node_Id := Next (Then_DE);
8598
8599 begin
8600 Bignum_Operands := False;
8601
0df9d43f 8602 Minimize_Eliminate_Overflows
0326b4d4 8603 (Then_DE, Lo, Hi, Top_Level => False);
8604
8605 if Lo = No_Uint then
8606 Bignum_Operands := True;
8607 end if;
8608
0df9d43f 8609 Minimize_Eliminate_Overflows
0326b4d4 8610 (Else_DE, Rlo, Rhi, Top_Level => False);
8611
8612 if Rlo = No_Uint then
8613 Bignum_Operands := True;
8614 else
8615 Long_Long_Integer_Operands :=
8616 Etype (Then_DE) = LLIB or else Etype (Else_DE) = LLIB;
8617
8618 Min (Lo, Rlo);
8619 Max (Hi, Rhi);
8620 end if;
8621
21a55437 8622 -- If at least one of our operands is now Bignum, we must rebuild
8623 -- the if expression to use Bignum operands. We will analyze the
0326b4d4 8624 -- rebuilt if expression with overflow checks off, since once we
39a0c1d3 8625 -- are in bignum mode, we are all done with overflow checks.
0326b4d4 8626
8627 if Bignum_Operands then
8628 Rewrite (N,
92f1631f 8629 Make_If_Expression (Loc,
0326b4d4 8630 Expressions => New_List (
8631 Remove_Head (Expressions (N)),
8632 Convert_To_Bignum (Then_DE),
8633 Convert_To_Bignum (Else_DE)),
8634 Is_Elsif => Is_Elsif (N)));
8635
0df9d43f 8636 Reanalyze (RTE (RE_Bignum), Suppress => True);
0326b4d4 8637
8638 -- If we have no Long_Long_Integer operands, then we are in result
8639 -- range, since it means that none of our operands felt the need
8640 -- to worry about overflow (otherwise it would have already been
4fb5f0a0 8641 -- converted to long long integer or bignum). We reexpand to
8642 -- complete the expansion of the if expression (but we do not
8643 -- need to reanalyze).
0326b4d4 8644
8645 elsif not Long_Long_Integer_Operands then
8646 Set_Do_Overflow_Check (N, False);
0df9d43f 8647 Reexpand;
0326b4d4 8648
8649 -- Otherwise convert us to long long integer mode. Note that we
8650 -- don't need any further overflow checking at this level.
8651
8652 else
8653 Convert_To_And_Rewrite (LLIB, Then_DE);
8654 Convert_To_And_Rewrite (LLIB, Else_DE);
8655 Set_Etype (N, LLIB);
f32c377d 8656
8657 -- Now reanalyze with overflow checks off
8658
0326b4d4 8659 Set_Do_Overflow_Check (N, False);
0df9d43f 8660 Reanalyze (LLIB, Suppress => True);
0326b4d4 8661 end if;
8662 end;
8663
8664 return;
8665
8666 -- Here for case expression
8667
8668 elsif Nkind (N) = N_Case_Expression then
8669 Bignum_Operands := False;
8670 Long_Long_Integer_Operands := False;
0326b4d4 8671
8672 declare
f32c377d 8673 Alt : Node_Id;
0326b4d4 8674
8675 begin
8676 -- Loop through expressions applying recursive call
8677
8678 Alt := First (Alternatives (N));
8679 while Present (Alt) loop
8680 declare
8681 Aexp : constant Node_Id := Expression (Alt);
8682
8683 begin
0df9d43f 8684 Minimize_Eliminate_Overflows
0326b4d4 8685 (Aexp, Lo, Hi, Top_Level => False);
8686
8687 if Lo = No_Uint then
8688 Bignum_Operands := True;
8689 elsif Etype (Aexp) = LLIB then
8690 Long_Long_Integer_Operands := True;
8691 end if;
8692 end;
8693
8694 Next (Alt);
8695 end loop;
8696
8697 -- If we have no bignum or long long integer operands, it means
8698 -- that none of our dependent expressions could raise overflow.
8699 -- In this case, we simply return with no changes except for
8700 -- resetting the overflow flag, since we are done with overflow
4fb5f0a0 8701 -- checks for this node. We will reexpand to get the needed
8702 -- expansion for the case expression, but we do not need to
21a55437 8703 -- reanalyze, since nothing has changed.
0326b4d4 8704
f32c377d 8705 if not (Bignum_Operands or Long_Long_Integer_Operands) then
0326b4d4 8706 Set_Do_Overflow_Check (N, False);
0df9d43f 8707 Reexpand (Suppress => True);
0326b4d4 8708
8709 -- Otherwise we are going to rebuild the case expression using
8710 -- either bignum or long long integer operands throughout.
8711
8712 else
f32c377d 8713 declare
8714 Rtype : Entity_Id;
16149377 8715 pragma Warnings (Off, Rtype);
f32c377d 8716 New_Alts : List_Id;
8717 New_Exp : Node_Id;
8718
8719 begin
8720 New_Alts := New_List;
8721 Alt := First (Alternatives (N));
8722 while Present (Alt) loop
8723 if Bignum_Operands then
8724 New_Exp := Convert_To_Bignum (Expression (Alt));
8725 Rtype := RTE (RE_Bignum);
8726 else
8727 New_Exp := Convert_To (LLIB, Expression (Alt));
8728 Rtype := LLIB;
8729 end if;
0326b4d4 8730
f32c377d 8731 Append_To (New_Alts,
8732 Make_Case_Expression_Alternative (Sloc (Alt),
8733 Actions => No_List,
8734 Discrete_Choices => Discrete_Choices (Alt),
8735 Expression => New_Exp));
0326b4d4 8736
f32c377d 8737 Next (Alt);
8738 end loop;
0326b4d4 8739
f32c377d 8740 Rewrite (N,
8741 Make_Case_Expression (Loc,
8742 Expression => Expression (N),
8743 Alternatives => New_Alts));
0326b4d4 8744
0df9d43f 8745 Reanalyze (Rtype, Suppress => True);
f32c377d 8746 end;
0326b4d4 8747 end if;
8748 end;
8749
8750 return;
8751 end if;
8752
8753 -- If we have an arithmetic operator we make recursive calls on the
3cce7f32 8754 -- operands to get the ranges (and to properly process the subtree
20cf157b 8755 -- that lies below us).
3cce7f32 8756
0df9d43f 8757 Minimize_Eliminate_Overflows
0326b4d4 8758 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
3cce7f32 8759
0326b4d4 8760 if Binary then
0df9d43f 8761 Minimize_Eliminate_Overflows
0326b4d4 8762 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
3cce7f32 8763 end if;
8764
f32c377d 8765 -- Record if we have Long_Long_Integer operands
8766
8767 Long_Long_Integer_Operands :=
8768 Etype (Right_Opnd (N)) = LLIB
8769 or else (Binary and then Etype (Left_Opnd (N)) = LLIB);
8770
8771 -- If either operand is a bignum, then result will be a bignum and we
8772 -- don't need to do any range analysis. As previously discussed we could
8773 -- do range analysis in such cases, but it could mean working with giant
8774 -- numbers at compile time for very little gain (the number of cases
21a55437 8775 -- in which we could slip back from bignum mode is small).
3cce7f32 8776
8777 if Rlo = No_Uint or else (Binary and then Llo = No_Uint) then
8778 Lo := No_Uint;
8779 Hi := No_Uint;
61016a7a 8780 Bignum_Operands := True;
3cce7f32 8781
8782 -- Otherwise compute result range
8783
8784 else
61016a7a 8785 Bignum_Operands := False;
8786
3cce7f32 8787 case Nkind (N) is
8788
8789 -- Absolute value
8790
8791 when N_Op_Abs =>
8792 Lo := Uint_0;
de922300 8793 Hi := UI_Max (abs Rlo, abs Rhi);
3cce7f32 8794
8795 -- Addition
8796
8797 when N_Op_Add =>
8798 Lo := Llo + Rlo;
8799 Hi := Lhi + Rhi;
8800
8801 -- Division
8802
8803 when N_Op_Divide =>
2fe22c69 8804
5f4275e1 8805 -- If the right operand can only be zero, set 0..0
2fe22c69 8806
5f4275e1 8807 if Rlo = 0 and then Rhi = 0 then
8808 Lo := Uint_0;
8809 Hi := Uint_0;
2fe22c69 8810
5f4275e1 8811 -- Possible bounds of division must come from dividing end
8812 -- values of the input ranges (four possibilities), provided
8813 -- zero is not included in the possible values of the right
8814 -- operand.
8815
8816 -- Otherwise, we just consider two intervals of values for
8817 -- the right operand: the interval of negative values (up to
8818 -- -1) and the interval of positive values (starting at 1).
8819 -- Since division by 1 is the identity, and division by -1
8820 -- is negation, we get all possible bounds of division in that
8821 -- case by considering:
8822 -- - all values from the division of end values of input
8823 -- ranges;
8824 -- - the end values of the left operand;
8825 -- - the negation of the end values of the left operand.
2fe22c69 8826
5f4275e1 8827 else
8828 declare
8829 Mrk : constant Uintp.Save_Mark := Mark;
8830 -- Mark so we can release the RR and Ev values
2fe22c69 8831
5f4275e1 8832 Ev1 : Uint;
8833 Ev2 : Uint;
8834 Ev3 : Uint;
8835 Ev4 : Uint;
2fe22c69 8836
5f4275e1 8837 begin
8838 -- Discard extreme values of zero for the divisor, since
8839 -- they will simply result in an exception in any case.
2fe22c69 8840
5f4275e1 8841 if Rlo = 0 then
8842 Rlo := Uint_1;
8843 elsif Rhi = 0 then
8844 Rhi := -Uint_1;
2fe22c69 8845 end if;
2fe22c69 8846
5f4275e1 8847 -- Compute possible bounds coming from dividing end
8848 -- values of the input ranges.
2fe22c69 8849
5f4275e1 8850 Ev1 := Llo / Rlo;
8851 Ev2 := Llo / Rhi;
8852 Ev3 := Lhi / Rlo;
8853 Ev4 := Lhi / Rhi;
2fe22c69 8854
5f4275e1 8855 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8856 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
2fe22c69 8857
5f4275e1 8858 -- If the right operand can be both negative or positive,
8859 -- include the end values of the left operand in the
8860 -- extreme values, as well as their negation.
2fe22c69 8861
5f4275e1 8862 if Rlo < 0 and then Rhi > 0 then
8863 Ev1 := Llo;
8864 Ev2 := -Llo;
8865 Ev3 := Lhi;
8866 Ev4 := -Lhi;
2fe22c69 8867
5f4275e1 8868 Min (Lo,
8869 UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4)));
8870 Max (Hi,
8871 UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4)));
2fe22c69 8872 end if;
2fe22c69 8873
5f4275e1 8874 -- Release the RR and Ev values
2fe22c69 8875
5f4275e1 8876 Release_And_Save (Mrk, Lo, Hi);
8877 end;
8878 end if;
3cce7f32 8879
8880 -- Exponentiation
8881
8882 when N_Op_Expon =>
de922300 8883
8884 -- Discard negative values for the exponent, since they will
8885 -- simply result in an exception in any case.
8886
8887 if Rhi < 0 then
8888 Rhi := Uint_0;
8889 elsif Rlo < 0 then
8890 Rlo := Uint_0;
8891 end if;
8892
8893 -- Estimate number of bits in result before we go computing
8894 -- giant useless bounds. Basically the number of bits in the
8895 -- result is the number of bits in the base multiplied by the
8896 -- value of the exponent. If this is big enough that the result
8897 -- definitely won't fit in Long_Long_Integer, switch to bignum
8898 -- mode immediately, and avoid computing giant bounds.
8899
8900 -- The comparison here is approximate, but conservative, it
8901 -- only clicks on cases that are sure to exceed the bounds.
8902
8903 if Num_Bits (UI_Max (abs Llo, abs Lhi)) * Rhi + 1 > 100 then
8904 Lo := No_Uint;
8905 Hi := No_Uint;
8906
8907 -- If right operand is zero then result is 1
8908
8909 elsif Rhi = 0 then
8910 Lo := Uint_1;
8911 Hi := Uint_1;
8912
8913 else
8914 -- High bound comes either from exponentiation of largest
5f4275e1 8915 -- positive value to largest exponent value, or from
8916 -- the exponentiation of most negative value to an
8917 -- even exponent.
de922300 8918
8919 declare
8920 Hi1, Hi2 : Uint;
8921
8922 begin
5f4275e1 8923 if Lhi > 0 then
de922300 8924 Hi1 := Lhi ** Rhi;
8925 else
8926 Hi1 := Uint_0;
8927 end if;
8928
8929 if Llo < 0 then
8930 if Rhi mod 2 = 0 then
de922300 8931 Hi2 := Llo ** Rhi;
5f4275e1 8932 else
8933 Hi2 := Llo ** (Rhi - 1);
de922300 8934 end if;
8935 else
8936 Hi2 := Uint_0;
8937 end if;
8938
8939 Hi := UI_Max (Hi1, Hi2);
8940 end;
8941
8942 -- Result can only be negative if base can be negative
8943
8944 if Llo < 0 then
21a55437 8945 if Rhi mod 2 = 0 then
de922300 8946 Lo := Llo ** (Rhi - 1);
8947 else
8948 Lo := Llo ** Rhi;
8949 end if;
8950
21a55437 8951 -- Otherwise low bound is minimum ** minimum
de922300 8952
8953 else
8954 Lo := Llo ** Rlo;
8955 end if;
8956 end if;
3cce7f32 8957
8958 -- Negation
8959
8960 when N_Op_Minus =>
8961 Lo := -Rhi;
8962 Hi := -Rlo;
8963
8964 -- Mod
8965
8966 when N_Op_Mod =>
2fe22c69 8967 declare
5f4275e1 8968 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
2fe22c69 8969 -- This is the maximum absolute value of the result
8970
8971 begin
8972 Lo := Uint_0;
8973 Hi := Uint_0;
8974
8975 -- The result depends only on the sign and magnitude of
8976 -- the right operand, it does not depend on the sign or
8977 -- magnitude of the left operand.
8978
8979 if Rlo < 0 then
8980 Lo := -Maxabs;
8981 end if;
8982
8983 if Rhi > 0 then
8984 Hi := Maxabs;
8985 end if;
8986 end;
3cce7f32 8987
8988 -- Multiplication
8989
8990 when N_Op_Multiply =>
49b3a812 8991
8992 -- Possible bounds of multiplication must come from multiplying
8993 -- end values of the input ranges (four possibilities).
8994
8995 declare
8996 Mrk : constant Uintp.Save_Mark := Mark;
8997 -- Mark so we can release the Ev values
8998
8999 Ev1 : constant Uint := Llo * Rlo;
9000 Ev2 : constant Uint := Llo * Rhi;
9001 Ev3 : constant Uint := Lhi * Rlo;
9002 Ev4 : constant Uint := Lhi * Rhi;
9003
9004 begin
9005 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
9006 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
9007
9008 -- Release the Ev values
9009
9010 Release_And_Save (Mrk, Lo, Hi);
9011 end;
3cce7f32 9012
9013 -- Plus operator (affirmation)
9014
9015 when N_Op_Plus =>
9016 Lo := Rlo;
9017 Hi := Rhi;
9018
9019 -- Remainder
9020
9021 when N_Op_Rem =>
2fe22c69 9022 declare
5f4275e1 9023 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
2fe22c69 9024 -- This is the maximum absolute value of the result. Note
5f4275e1 9025 -- that the result range does not depend on the sign of the
9026 -- right operand.
2fe22c69 9027
9028 begin
9029 Lo := Uint_0;
9030 Hi := Uint_0;
9031
9032 -- Case of left operand negative, which results in a range
9033 -- of -Maxabs .. 0 for those negative values. If there are
9034 -- no negative values then Lo value of result is always 0.
9035
9036 if Llo < 0 then
9037 Lo := -Maxabs;
9038 end if;
9039
9040 -- Case of left operand positive
9041
9042 if Lhi > 0 then
9043 Hi := Maxabs;
9044 end if;
9045 end;
3cce7f32 9046
9047 -- Subtract
9048
9049 when N_Op_Subtract =>
9050 Lo := Llo - Rhi;
9051 Hi := Lhi - Rlo;
9052
9053 -- Nothing else should be possible
9054
9055 when others =>
9056 raise Program_Error;
3cce7f32 9057 end case;
9058 end if;
9059
4fb5f0a0 9060 -- Here for the case where we have not rewritten anything (no bignum
21a55437 9061 -- operands or long long integer operands), and we know the result.
9062 -- If we know we are in the result range, and we do not have Bignum
9063 -- operands or Long_Long_Integer operands, we can just reexpand with
9064 -- overflow checks turned off (since we know we cannot have overflow).
9065 -- As always the reexpansion is required to complete expansion of the
9066 -- operator, but we do not need to reanalyze, and we prevent recursion
9067 -- by suppressing the check.
f32c377d 9068
9069 if not (Bignum_Operands or Long_Long_Integer_Operands)
9070 and then In_Result_Range
9071 then
9072 Set_Do_Overflow_Check (N, False);
0df9d43f 9073 Reexpand (Suppress => True);
f32c377d 9074 return;
9075
9076 -- Here we know that we are not in the result range, and in the general
21a55437 9077 -- case we will move into either the Bignum or Long_Long_Integer domain
9078 -- to compute the result. However, there is one exception. If we are
9079 -- at the top level, and we do not have Bignum or Long_Long_Integer
9080 -- operands, we will have to immediately convert the result back to
9081 -- the result type, so there is no point in Bignum/Long_Long_Integer
9082 -- fiddling.
f32c377d 9083
9084 elsif Top_Level
9085 and then not (Bignum_Operands or Long_Long_Integer_Operands)
b6a8f264 9086
9087 -- One further refinement. If we are at the top level, but our parent
9088 -- is a type conversion, then go into bignum or long long integer node
9089 -- since the result will be converted to that type directly without
9090 -- going through the result type, and we may avoid an overflow. This
9091 -- is the case for example of Long_Long_Integer (A ** 4), where A is
9092 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
9093 -- but does not fit in Integer.
9094
9095 and then Nkind (Parent (N)) /= N_Type_Conversion
f32c377d 9096 then
0df9d43f 9097 -- Here keep original types, but we need to complete analysis
f32c377d 9098
9099 -- One subtlety. We can't just go ahead and do an analyze operation
21a55437 9100 -- here because it will cause recursion into the whole MINIMIZED/
9101 -- ELIMINATED overflow processing which is not what we want. Here
f32c377d 9102 -- we are at the top level, and we need a check against the result
39a0c1d3 9103 -- mode (i.e. we want to use STRICT mode). So do exactly that.
4fb5f0a0 9104 -- Also, we have not modified the node, so this is a case where
9105 -- we need to reexpand, but not reanalyze.
f32c377d 9106
0df9d43f 9107 Reexpand;
f32c377d 9108 return;
9109
9110 -- Cases where we do the operation in Bignum mode. This happens either
3cce7f32 9111 -- because one of our operands is in Bignum mode already, or because
de922300 9112 -- the computed bounds are outside the bounds of Long_Long_Integer,
9113 -- which in some cases can be indicated by Hi and Lo being No_Uint.
3cce7f32 9114
9115 -- Note: we could do better here and in some cases switch back from
9116 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
9117 -- 0 .. 1, but the cases are rare and it is not worth the effort.
9118 -- Failing to do this switching back is only an efficiency issue.
9119
f32c377d 9120 elsif Lo = No_Uint or else Lo < LLLo or else Hi > LLHi then
3cce7f32 9121
61016a7a 9122 -- OK, we are definitely outside the range of Long_Long_Integer. The
f32c377d 9123 -- question is whether to move to Bignum mode, or stay in the domain
61016a7a 9124 -- of Long_Long_Integer, signalling that an overflow check is needed.
9125
9126 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
9127 -- the Bignum business. In ELIMINATED mode, we will normally move
9128 -- into Bignum mode, but there is an exception if neither of our
9129 -- operands is Bignum now, and we are at the top level (Top_Level
9130 -- set True). In this case, there is no point in moving into Bignum
9131 -- mode to prevent overflow if the caller will immediately convert
9132 -- the Bignum value back to LLI with an overflow check. It's more
0df9d43f 9133 -- efficient to stay in LLI mode with an overflow check (if needed)
61016a7a 9134
9135 if Check_Mode = Minimized
9136 or else (Top_Level and not Bignum_Operands)
9137 then
0df9d43f 9138 if Do_Overflow_Check (N) then
9139 Enable_Overflow_Check (N);
9140 end if;
3cce7f32 9141
0df9d43f 9142 -- The result now has to be in Long_Long_Integer mode, so adjust
9143 -- the possible range to reflect this. Note these calls also
9144 -- change No_Uint values from the top level case to LLI bounds.
61016a7a 9145
9146 Max (Lo, LLLo);
9147 Min (Hi, LLHi);
9148
9149 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
3cce7f32 9150
9151 else
9152 pragma Assert (Check_Mode = Eliminated);
9153
9154 declare
9155 Fent : Entity_Id;
9156 Args : List_Id;
9157
9158 begin
9159 case Nkind (N) is
99378362 9160 when N_Op_Abs =>
3cce7f32 9161 Fent := RTE (RE_Big_Abs);
9162
99378362 9163 when N_Op_Add =>
3cce7f32 9164 Fent := RTE (RE_Big_Add);
9165
99378362 9166 when N_Op_Divide =>
3cce7f32 9167 Fent := RTE (RE_Big_Div);
9168
99378362 9169 when N_Op_Expon =>
3cce7f32 9170 Fent := RTE (RE_Big_Exp);
9171
99378362 9172 when N_Op_Minus =>
3cce7f32 9173 Fent := RTE (RE_Big_Neg);
9174
99378362 9175 when N_Op_Mod =>
3cce7f32 9176 Fent := RTE (RE_Big_Mod);
9177
9178 when N_Op_Multiply =>
9179 Fent := RTE (RE_Big_Mul);
9180
99378362 9181 when N_Op_Rem =>
3cce7f32 9182 Fent := RTE (RE_Big_Rem);
9183
9184 when N_Op_Subtract =>
9185 Fent := RTE (RE_Big_Sub);
9186
9187 -- Anything else is an internal error, this includes the
9188 -- N_Op_Plus case, since how can plus cause the result
9189 -- to be out of range if the operand is in range?
9190
9191 when others =>
9192 raise Program_Error;
9193 end case;
9194
9195 -- Construct argument list for Bignum call, converting our
9196 -- operands to Bignum form if they are not already there.
9197
9198 Args := New_List;
9199
9200 if Binary then
9201 Append_To (Args, Convert_To_Bignum (Left_Opnd (N)));
9202 end if;
9203
9204 Append_To (Args, Convert_To_Bignum (Right_Opnd (N)));
9205
9206 -- Now rewrite the arithmetic operator with a call to the
9207 -- corresponding bignum function.
9208
9209 Rewrite (N,
9210 Make_Function_Call (Loc,
9211 Name => New_Occurrence_Of (Fent, Loc),
9212 Parameter_Associations => Args));
0df9d43f 9213 Reanalyze (RTE (RE_Bignum), Suppress => True);
61016a7a 9214
9215 -- Indicate result is Bignum mode
9216
9217 Lo := No_Uint;
9218 Hi := No_Uint;
de922300 9219 return;
3cce7f32 9220 end;
9221 end if;
9222
9223 -- Otherwise we are in range of Long_Long_Integer, so no overflow
de922300 9224 -- check is required, at least not yet.
3cce7f32 9225
9226 else
de922300 9227 Set_Do_Overflow_Check (N, False);
9228 end if;
3cce7f32 9229
f32c377d 9230 -- Here we are not in Bignum territory, but we may have long long
9231 -- integer operands that need special handling. First a special check:
9232 -- If an exponentiation operator exponent is of type Long_Long_Integer,
9233 -- it means we converted it to prevent overflow, but exponentiation
9234 -- requires a Natural right operand, so convert it back to Natural.
9235 -- This conversion may raise an exception which is fine.
0326b4d4 9236
f32c377d 9237 if Nkind (N) = N_Op_Expon and then Etype (Right_Opnd (N)) = LLIB then
9238 Convert_To_And_Rewrite (Standard_Natural, Right_Opnd (N));
0326b4d4 9239 end if;
9240
de922300 9241 -- Here we will do the operation in Long_Long_Integer. We do this even
9242 -- if we know an overflow check is required, better to do this in long
39a0c1d3 9243 -- long integer mode, since we are less likely to overflow.
3cce7f32 9244
de922300 9245 -- Convert right or only operand to Long_Long_Integer, except that
9246 -- we do not touch the exponentiation right operand.
3cce7f32 9247
de922300 9248 if Nkind (N) /= N_Op_Expon then
9249 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
9250 end if;
3cce7f32 9251
de922300 9252 -- Convert left operand to Long_Long_Integer for binary case
49b3a812 9253
de922300 9254 if Binary then
9255 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
9256 end if;
9257
9258 -- Reset node to unanalyzed
9259
9260 Set_Analyzed (N, False);
9261 Set_Etype (N, Empty);
9262 Set_Entity (N, Empty);
9263
2fe22c69 9264 -- Now analyze this new node. This reanalysis will complete processing
9265 -- for the node. In particular we will complete the expansion of an
9266 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
9267 -- we will complete any division checks (since we have not changed the
9268 -- setting of the Do_Division_Check flag).
3cce7f32 9269
0df9d43f 9270 -- We do this reanalysis in STRICT mode to avoid recursion into the
39a0c1d3 9271 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
3cce7f32 9272
0df9d43f 9273 declare
db415383 9274 SG : constant Overflow_Mode_Type :=
9275 Scope_Suppress.Overflow_Mode_General;
9276 SA : constant Overflow_Mode_Type :=
9277 Scope_Suppress.Overflow_Mode_Assertions;
de922300 9278
0df9d43f 9279 begin
db415383 9280 Scope_Suppress.Overflow_Mode_General := Strict;
9281 Scope_Suppress.Overflow_Mode_Assertions := Strict;
de922300 9282
0df9d43f 9283 if not Do_Overflow_Check (N) then
9284 Reanalyze (LLIB, Suppress => True);
9285 else
9286 Reanalyze (LLIB);
9287 end if;
9288
db415383 9289 Scope_Suppress.Overflow_Mode_General := SG;
9290 Scope_Suppress.Overflow_Mode_Assertions := SA;
0df9d43f 9291 end;
9292 end Minimize_Eliminate_Overflows;
3cce7f32 9293
9294 -------------------------
9295 -- Overflow_Check_Mode --
9296 -------------------------
9297
db415383 9298 function Overflow_Check_Mode return Overflow_Mode_Type is
ee6ba406 9299 begin
724d2bd8 9300 if In_Assertion_Expr = 0 then
db415383 9301 return Scope_Suppress.Overflow_Mode_General;
9dfe12ae 9302 else
db415383 9303 return Scope_Suppress.Overflow_Mode_Assertions;
9dfe12ae 9304 end if;
3cce7f32 9305 end Overflow_Check_Mode;
9306
9307 --------------------------------
9308 -- Overflow_Checks_Suppressed --
9309 --------------------------------
9310
9311 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
9312 begin
0df9d43f 9313 if Present (E) and then Checks_May_Be_Suppressed (E) then
9314 return Is_Check_Suppressed (E, Overflow_Check);
9315 else
9316 return Scope_Suppress.Suppress (Overflow_Check);
9317 end if;
ee6ba406 9318 end Overflow_Checks_Suppressed;
fc75802a 9319
37baba83 9320 ---------------------------------
9321 -- Predicate_Checks_Suppressed --
9322 ---------------------------------
9323
9324 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean is
9325 begin
9326 if Present (E) and then Checks_May_Be_Suppressed (E) then
9327 return Is_Check_Suppressed (E, Predicate_Check);
9328 else
9329 return Scope_Suppress.Suppress (Predicate_Check);
9330 end if;
9331 end Predicate_Checks_Suppressed;
9332
ee6ba406 9333 -----------------------------
9334 -- Range_Checks_Suppressed --
9335 -----------------------------
9336
9337 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
9338 begin
9dfe12ae 9339 if Present (E) then
ce4d14c4 9340 if Kill_Range_Checks (E) then
9dfe12ae 9341 return True;
5f46de53 9342
9dfe12ae 9343 elsif Checks_May_Be_Suppressed (E) then
9344 return Is_Check_Suppressed (E, Range_Check);
9345 end if;
9346 end if;
ee6ba406 9347
fafc6b97 9348 return Scope_Suppress.Suppress (Range_Check);
ee6ba406 9349 end Range_Checks_Suppressed;
9350
0577b0b1 9351 -----------------------------------------
9352 -- Range_Or_Validity_Checks_Suppressed --
9353 -----------------------------------------
9354
9355 -- Note: the coding would be simpler here if we simply made appropriate
9356 -- calls to Range/Validity_Checks_Suppressed, but that would result in
9357 -- duplicated checks which we prefer to avoid.
9358
9359 function Range_Or_Validity_Checks_Suppressed
9360 (Expr : Node_Id) return Boolean
9361 is
9362 begin
9363 -- Immediate return if scope checks suppressed for either check
9364
fafc6b97 9365 if Scope_Suppress.Suppress (Range_Check)
9366 or
9367 Scope_Suppress.Suppress (Validity_Check)
9368 then
0577b0b1 9369 return True;
9370 end if;
9371
9372 -- If no expression, that's odd, decide that checks are suppressed,
9373 -- since we don't want anyone trying to do checks in this case, which
9374 -- is most likely the result of some other error.
9375
9376 if No (Expr) then
9377 return True;
9378 end if;
9379
9380 -- Expression is present, so perform suppress checks on type
9381
9382 declare
9383 Typ : constant Entity_Id := Etype (Expr);
9384 begin
ce4d14c4 9385 if Checks_May_Be_Suppressed (Typ)
0577b0b1 9386 and then (Is_Check_Suppressed (Typ, Range_Check)
9387 or else
9388 Is_Check_Suppressed (Typ, Validity_Check))
9389 then
9390 return True;
9391 end if;
9392 end;
9393
9394 -- If expression is an entity name, perform checks on this entity
9395
9396 if Is_Entity_Name (Expr) then
9397 declare
9398 Ent : constant Entity_Id := Entity (Expr);
9399 begin
9400 if Checks_May_Be_Suppressed (Ent) then
9401 return Is_Check_Suppressed (Ent, Range_Check)
9402 or else Is_Check_Suppressed (Ent, Validity_Check);
9403 end if;
9404 end;
9405 end if;
9406
9407 -- If we fall through, no checks suppressed
9408
9409 return False;
9410 end Range_Or_Validity_Checks_Suppressed;
9411
226494a3 9412 -------------------
9413 -- Remove_Checks --
9414 -------------------
9415
9416 procedure Remove_Checks (Expr : Node_Id) is
226494a3 9417 function Process (N : Node_Id) return Traverse_Result;
9418 -- Process a single node during the traversal
9419
8f6e4fd5 9420 procedure Traverse is new Traverse_Proc (Process);
9421 -- The traversal procedure itself
226494a3 9422
9423 -------------
9424 -- Process --
9425 -------------
9426
9427 function Process (N : Node_Id) return Traverse_Result is
9428 begin
9429 if Nkind (N) not in N_Subexpr then
9430 return Skip;
9431 end if;
9432
9433 Set_Do_Range_Check (N, False);
9434
9435 case Nkind (N) is
9436 when N_And_Then =>
8f6e4fd5 9437 Traverse (Left_Opnd (N));
226494a3 9438 return Skip;
9439
9440 when N_Attribute_Reference =>
226494a3 9441 Set_Do_Overflow_Check (N, False);
9442
226494a3 9443 when N_Function_Call =>
9444 Set_Do_Tag_Check (N, False);
9445
226494a3 9446 when N_Op =>
9447 Set_Do_Overflow_Check (N, False);
9448
9449 case Nkind (N) is
9450 when N_Op_Divide =>
9451 Set_Do_Division_Check (N, False);
9452
9453 when N_Op_And =>
9454 Set_Do_Length_Check (N, False);
9455
9456 when N_Op_Mod =>
9457 Set_Do_Division_Check (N, False);
9458
9459 when N_Op_Or =>
9460 Set_Do_Length_Check (N, False);
9461
9462 when N_Op_Rem =>
9463 Set_Do_Division_Check (N, False);
9464
9465 when N_Op_Xor =>
9466 Set_Do_Length_Check (N, False);
9467
9468 when others =>
9469 null;
9470 end case;
9471
9472 when N_Or_Else =>
8f6e4fd5 9473 Traverse (Left_Opnd (N));
226494a3 9474 return Skip;
9475
9476 when N_Selected_Component =>
226494a3 9477 Set_Do_Discriminant_Check (N, False);
9478
226494a3 9479 when N_Type_Conversion =>
9dfe12ae 9480 Set_Do_Length_Check (N, False);
9481 Set_Do_Tag_Check (N, False);
226494a3 9482 Set_Do_Overflow_Check (N, False);
226494a3 9483
9484 when others =>
9485 null;
9486 end case;
9487
9488 return OK;
9489 end Process;
9490
9491 -- Start of processing for Remove_Checks
9492
9493 begin
8f6e4fd5 9494 Traverse (Expr);
226494a3 9495 end Remove_Checks;
9496
ee6ba406 9497 ----------------------------
9498 -- Selected_Length_Checks --
9499 ----------------------------
9500
9501 function Selected_Length_Checks
9502 (Ck_Node : Node_Id;
9503 Target_Typ : Entity_Id;
9504 Source_Typ : Entity_Id;
314a23b6 9505 Warn_Node : Node_Id) return Check_Result
ee6ba406 9506 is
9507 Loc : constant Source_Ptr := Sloc (Ck_Node);
9508 S_Typ : Entity_Id;
9509 T_Typ : Entity_Id;
9510 Expr_Actual : Node_Id;
9511 Exptyp : Entity_Id;
9512 Cond : Node_Id := Empty;
9513 Do_Access : Boolean := False;
9514 Wnode : Node_Id := Warn_Node;
9515 Ret_Result : Check_Result := (Empty, Empty);
9516 Num_Checks : Natural := 0;
9517
9518 procedure Add_Check (N : Node_Id);
9519 -- Adds the action given to Ret_Result if N is non-Empty
9520
9521 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
9522 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
314a23b6 9523 -- Comments required ???
ee6ba406 9524
9525 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
9526 -- True for equal literals and for nodes that denote the same constant
5f260d20 9527 -- entity, even if its value is not a static constant. This includes the
9dfe12ae 9528 -- case of a discriminal reference within an init proc. Removes some
5f260d20 9529 -- obviously superfluous checks.
ee6ba406 9530
9531 function Length_E_Cond
9532 (Exptyp : Entity_Id;
9533 Typ : Entity_Id;
314a23b6 9534 Indx : Nat) return Node_Id;
ee6ba406 9535 -- Returns expression to compute:
9536 -- Typ'Length /= Exptyp'Length
9537
9538 function Length_N_Cond
9539 (Expr : Node_Id;
9540 Typ : Entity_Id;
314a23b6 9541 Indx : Nat) return Node_Id;
ee6ba406 9542 -- Returns expression to compute:
9543 -- Typ'Length /= Expr'Length
9544
a4a3cc3d 9545 function Length_Mismatch_Info_Message
9546 (Left_Element_Count : Uint;
9547 Right_Element_Count : Uint) return String;
9548 -- Returns a message indicating how many elements were expected
9549 -- (Left_Element_Count) and how many were found (Right_Element_Count).
9550
ee6ba406 9551 ---------------
9552 -- Add_Check --
9553 ---------------
9554
9555 procedure Add_Check (N : Node_Id) is
9556 begin
9557 if Present (N) then
9558
20cf157b 9559 -- For now, ignore attempt to place more than two checks ???
9560 -- This is really worrisome, are we really discarding checks ???
ee6ba406 9561
9562 if Num_Checks = 2 then
9563 return;
9564 end if;
9565
9566 pragma Assert (Num_Checks <= 1);
9567 Num_Checks := Num_Checks + 1;
9568 Ret_Result (Num_Checks) := N;
9569 end if;
9570 end Add_Check;
9571
9572 ------------------
9573 -- Get_E_Length --
9574 ------------------
9575
9576 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
00c403ee 9577 SE : constant Entity_Id := Scope (E);
ee6ba406 9578 N : Node_Id;
9579 E1 : Entity_Id := E;
ee6ba406 9580
9581 begin
9582 if Ekind (Scope (E)) = E_Record_Type
9583 and then Has_Discriminants (Scope (E))
9584 then
9585 N := Build_Discriminal_Subtype_Of_Component (E);
9586
9587 if Present (N) then
9588 Insert_Action (Ck_Node, N);
9589 E1 := Defining_Identifier (N);
9590 end if;
9591 end if;
9592
9593 if Ekind (E1) = E_String_Literal_Subtype then
9594 return
9595 Make_Integer_Literal (Loc,
9596 Intval => String_Literal_Length (E1));
9597
00c403ee 9598 elsif SE /= Standard_Standard
9599 and then Ekind (Scope (SE)) = E_Protected_Type
9600 and then Has_Discriminants (Scope (SE))
9601 and then Has_Completion (Scope (SE))
ee6ba406 9602 and then not Inside_Init_Proc
9603 then
ee6ba406 9604 -- If the type whose length is needed is a private component
9605 -- constrained by a discriminant, we must expand the 'Length
9606 -- attribute into an explicit computation, using the discriminal
9607 -- of the current protected operation. This is because the actual
9608 -- type of the prival is constructed after the protected opera-
9609 -- tion has been fully expanded.
9610
9611 declare
9612 Indx_Type : Node_Id;
9613 Lo : Node_Id;
9614 Hi : Node_Id;
9615 Do_Expand : Boolean := False;
9616
9617 begin
9618 Indx_Type := First_Index (E);
9619
9620 for J in 1 .. Indx - 1 loop
9621 Next_Index (Indx_Type);
9622 end loop;
9623
2af58f67 9624 Get_Index_Bounds (Indx_Type, Lo, Hi);
ee6ba406 9625
9626 if Nkind (Lo) = N_Identifier
9627 and then Ekind (Entity (Lo)) = E_In_Parameter
9628 then
9629 Lo := Get_Discriminal (E, Lo);
9630 Do_Expand := True;
9631 end if;
9632
9633 if Nkind (Hi) = N_Identifier
9634 and then Ekind (Entity (Hi)) = E_In_Parameter
9635 then
9636 Hi := Get_Discriminal (E, Hi);
9637 Do_Expand := True;
9638 end if;
9639
9640 if Do_Expand then
9641 if not Is_Entity_Name (Lo) then
9dfe12ae 9642 Lo := Duplicate_Subexpr_No_Checks (Lo);
ee6ba406 9643 end if;
9644
9645 if not Is_Entity_Name (Hi) then
9dfe12ae 9646 Lo := Duplicate_Subexpr_No_Checks (Hi);
ee6ba406 9647 end if;
9648
9649 N :=
9650 Make_Op_Add (Loc,
9651 Left_Opnd =>
9652 Make_Op_Subtract (Loc,
9653 Left_Opnd => Hi,
9654 Right_Opnd => Lo),
9655
9656 Right_Opnd => Make_Integer_Literal (Loc, 1));
9657 return N;
9658
9659 else
9660 N :=
9661 Make_Attribute_Reference (Loc,
9662 Attribute_Name => Name_Length,
9663 Prefix =>
9664 New_Occurrence_Of (E1, Loc));
9665
9666 if Indx > 1 then
9667 Set_Expressions (N, New_List (
9668 Make_Integer_Literal (Loc, Indx)));
9669 end if;
9670
9671 return N;
9672 end if;
9673 end;
9674
9675 else
9676 N :=
9677 Make_Attribute_Reference (Loc,
9678 Attribute_Name => Name_Length,
9679 Prefix =>
9680 New_Occurrence_Of (E1, Loc));
9681
9682 if Indx > 1 then
9683 Set_Expressions (N, New_List (
9684 Make_Integer_Literal (Loc, Indx)));
9685 end if;
9686
9687 return N;
ee6ba406 9688 end if;
9689 end Get_E_Length;
9690
9691 ------------------
9692 -- Get_N_Length --
9693 ------------------
9694
9695 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
9696 begin
9697 return
9698 Make_Attribute_Reference (Loc,
9699 Attribute_Name => Name_Length,
9700 Prefix =>
9dfe12ae 9701 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
ee6ba406 9702 Expressions => New_List (
9703 Make_Integer_Literal (Loc, Indx)));
ee6ba406 9704 end Get_N_Length;
9705
9706 -------------------
9707 -- Length_E_Cond --
9708 -------------------
9709
9710 function Length_E_Cond
9711 (Exptyp : Entity_Id;
9712 Typ : Entity_Id;
314a23b6 9713 Indx : Nat) return Node_Id
ee6ba406 9714 is
9715 begin
9716 return
9717 Make_Op_Ne (Loc,
9718 Left_Opnd => Get_E_Length (Typ, Indx),
9719 Right_Opnd => Get_E_Length (Exptyp, Indx));
ee6ba406 9720 end Length_E_Cond;
9721
9722 -------------------
9723 -- Length_N_Cond --
9724 -------------------
9725
9726 function Length_N_Cond
9727 (Expr : Node_Id;
9728 Typ : Entity_Id;
314a23b6 9729 Indx : Nat) return Node_Id
ee6ba406 9730 is
9731 begin
9732 return
9733 Make_Op_Ne (Loc,
9734 Left_Opnd => Get_E_Length (Typ, Indx),
9735 Right_Opnd => Get_N_Length (Expr, Indx));
ee6ba406 9736 end Length_N_Cond;
9737
a4a3cc3d 9738 ----------------------------------
9739 -- Length_Mismatch_Info_Message --
9740 ----------------------------------
9741
9742 function Length_Mismatch_Info_Message
9743 (Left_Element_Count : Uint;
9744 Right_Element_Count : Uint) return String
9745 is
9746
9747 function Plural_Vs_Singular_Ending (Count : Uint) return String;
9748 -- Returns an empty string if Count is 1; otherwise returns "s"
9749
9750 function Plural_Vs_Singular_Ending (Count : Uint) return String is
9751 begin
9752 if Count = 1 then
9753 return "";
9754 else
9755 return "s";
9756 end if;
9757 end Plural_Vs_Singular_Ending;
9758
9759 begin
9760 return "expected " & UI_Image (Left_Element_Count)
9761 & " element"
9762 & Plural_Vs_Singular_Ending (Left_Element_Count)
9763 & "; found " & UI_Image (Right_Element_Count)
9764 & " element"
9765 & Plural_Vs_Singular_Ending (Right_Element_Count);
9766 end Length_Mismatch_Info_Message;
9767
feff2f05 9768 -----------------
9769 -- Same_Bounds --
9770 -----------------
9771
ee6ba406 9772 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
9773 begin
9774 return
9775 (Nkind (L) = N_Integer_Literal
9776 and then Nkind (R) = N_Integer_Literal
9777 and then Intval (L) = Intval (R))
9778
9779 or else
9780 (Is_Entity_Name (L)
9781 and then Ekind (Entity (L)) = E_Constant
9782 and then ((Is_Entity_Name (R)
9783 and then Entity (L) = Entity (R))
9784 or else
9785 (Nkind (R) = N_Type_Conversion
9786 and then Is_Entity_Name (Expression (R))
9787 and then Entity (L) = Entity (Expression (R)))))
9788
9789 or else
9790 (Is_Entity_Name (R)
9791 and then Ekind (Entity (R)) = E_Constant
9792 and then Nkind (L) = N_Type_Conversion
9793 and then Is_Entity_Name (Expression (L))
5f260d20 9794 and then Entity (R) = Entity (Expression (L)))
9795
9796 or else
9797 (Is_Entity_Name (L)
9798 and then Is_Entity_Name (R)
9799 and then Entity (L) = Entity (R)
9800 and then Ekind (Entity (L)) = E_In_Parameter
9801 and then Inside_Init_Proc);
ee6ba406 9802 end Same_Bounds;
9803
9804 -- Start of processing for Selected_Length_Checks
9805
9806 begin
18cb6d78 9807 -- Checks will be applied only when generating code
f0d65dae 9808
18cb6d78 9809 if not Expander_Active then
ee6ba406 9810 return Ret_Result;
9811 end if;
9812
9813 if Target_Typ = Any_Type
9814 or else Target_Typ = Any_Composite
9815 or else Raises_Constraint_Error (Ck_Node)
9816 then
9817 return Ret_Result;
9818 end if;
9819
9820 if No (Wnode) then
9821 Wnode := Ck_Node;
9822 end if;
9823
9824 T_Typ := Target_Typ;
9825
9826 if No (Source_Typ) then
9827 S_Typ := Etype (Ck_Node);
9828 else
9829 S_Typ := Source_Typ;
9830 end if;
9831
9832 if S_Typ = Any_Type or else S_Typ = Any_Composite then
9833 return Ret_Result;
9834 end if;
9835
9836 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
9837 S_Typ := Designated_Type (S_Typ);
9838 T_Typ := Designated_Type (T_Typ);
9839 Do_Access := True;
9840
2af58f67 9841 -- A simple optimization for the null case
ee6ba406 9842
2af58f67 9843 if Known_Null (Ck_Node) then
ee6ba406 9844 return Ret_Result;
9845 end if;
9846 end if;
9847
9848 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
9849 if Is_Constrained (T_Typ) then
9850
92f1631f 9851 -- The checking code to be generated will freeze the corresponding
9852 -- array type. However, we must freeze the type now, so that the
9853 -- freeze node does not appear within the generated if expression,
9854 -- but ahead of it.
ee6ba406 9855
9856 Freeze_Before (Ck_Node, T_Typ);
9857
9858 Expr_Actual := Get_Referenced_Object (Ck_Node);
84d0d4a5 9859 Exptyp := Get_Actual_Subtype (Ck_Node);
ee6ba406 9860
9861 if Is_Access_Type (Exptyp) then
9862 Exptyp := Designated_Type (Exptyp);
9863 end if;
9864
9865 -- String_Literal case. This needs to be handled specially be-
9866 -- cause no index types are available for string literals. The
9867 -- condition is simply:
9868
9869 -- T_Typ'Length = string-literal-length
9870
9dfe12ae 9871 if Nkind (Expr_Actual) = N_String_Literal
9872 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
9873 then
ee6ba406 9874 Cond :=
9875 Make_Op_Ne (Loc,
9876 Left_Opnd => Get_E_Length (T_Typ, 1),
9877 Right_Opnd =>
9878 Make_Integer_Literal (Loc,
9879 Intval =>
9880 String_Literal_Length (Etype (Expr_Actual))));
9881
9882 -- General array case. Here we have a usable actual subtype for
9883 -- the expression, and the condition is built from the two types
9884 -- (Do_Length):
9885
9886 -- T_Typ'Length /= Exptyp'Length or else
9887 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
9888 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
9889 -- ...
9890
9891 elsif Is_Constrained (Exptyp) then
9892 declare
9dfe12ae 9893 Ndims : constant Nat := Number_Dimensions (T_Typ);
9894
9895 L_Index : Node_Id;
9896 R_Index : Node_Id;
9897 L_Low : Node_Id;
9898 L_High : Node_Id;
9899 R_Low : Node_Id;
9900 R_High : Node_Id;
ee6ba406 9901 L_Length : Uint;
9902 R_Length : Uint;
9dfe12ae 9903 Ref_Node : Node_Id;
ee6ba406 9904
9905 begin
feff2f05 9906 -- At the library level, we need to ensure that the type of
9907 -- the object is elaborated before the check itself is
9908 -- emitted. This is only done if the object is in the
9909 -- current compilation unit, otherwise the type is frozen
9910 -- and elaborated in its unit.
9dfe12ae 9911
9912 if Is_Itype (Exptyp)
9913 and then
9914 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
9915 and then
9916 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
d66aa9f6 9917 and then In_Open_Scopes (Scope (Exptyp))
9dfe12ae 9918 then
9919 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
9920 Set_Itype (Ref_Node, Exptyp);
9921 Insert_Action (Ck_Node, Ref_Node);
9922 end if;
9923
ee6ba406 9924 L_Index := First_Index (T_Typ);
9925 R_Index := First_Index (Exptyp);
9926
9927 for Indx in 1 .. Ndims loop
9928 if not (Nkind (L_Index) = N_Raise_Constraint_Error
f15731c4 9929 or else
9930 Nkind (R_Index) = N_Raise_Constraint_Error)
ee6ba406 9931 then
9932 Get_Index_Bounds (L_Index, L_Low, L_High);
9933 Get_Index_Bounds (R_Index, R_Low, R_High);
9934
9935 -- Deal with compile time length check. Note that we
9936 -- skip this in the access case, because the access
9937 -- value may be null, so we cannot know statically.
9938
9939 if not Do_Access
9940 and then Compile_Time_Known_Value (L_Low)
9941 and then Compile_Time_Known_Value (L_High)
9942 and then Compile_Time_Known_Value (R_Low)
9943 and then Compile_Time_Known_Value (R_High)
9944 then
9945 if Expr_Value (L_High) >= Expr_Value (L_Low) then
9946 L_Length := Expr_Value (L_High) -
9947 Expr_Value (L_Low) + 1;
9948 else
9949 L_Length := UI_From_Int (0);
9950 end if;
9951
9952 if Expr_Value (R_High) >= Expr_Value (R_Low) then
9953 R_Length := Expr_Value (R_High) -
9954 Expr_Value (R_Low) + 1;
9955 else
9956 R_Length := UI_From_Int (0);
9957 end if;
9958
9959 if L_Length > R_Length then
9960 Add_Check
9961 (Compile_Time_Constraint_Error
a4a3cc3d 9962 (Wnode, "too few elements for}??", T_Typ,
9963 Extra_Msg => Length_Mismatch_Info_Message
9964 (L_Length, R_Length)));
ee6ba406 9965
b8eacb12 9966 elsif L_Length < R_Length then
ee6ba406 9967 Add_Check
9968 (Compile_Time_Constraint_Error
a4a3cc3d 9969 (Wnode, "too many elements for}??", T_Typ,
9970 Extra_Msg => Length_Mismatch_Info_Message
9971 (L_Length, R_Length)));
ee6ba406 9972 end if;
9973
9974 -- The comparison for an individual index subtype
9975 -- is omitted if the corresponding index subtypes
9976 -- statically match, since the result is known to
9977 -- be true. Note that this test is worth while even
9978 -- though we do static evaluation, because non-static
9979 -- subtypes can statically match.
9980
9981 elsif not
9982 Subtypes_Statically_Match
9983 (Etype (L_Index), Etype (R_Index))
9984
9985 and then not
9986 (Same_Bounds (L_Low, R_Low)
9987 and then Same_Bounds (L_High, R_High))
9988 then
9989 Evolve_Or_Else
9990 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
9991 end if;
9992
9993 Next (L_Index);
9994 Next (R_Index);
9995 end if;
9996 end loop;
9997 end;
9998
9999 -- Handle cases where we do not get a usable actual subtype that
10000 -- is constrained. This happens for example in the function call
10001 -- and explicit dereference cases. In these cases, we have to get
10002 -- the length or range from the expression itself, making sure we
10003 -- do not evaluate it more than once.
10004
10005 -- Here Ck_Node is the original expression, or more properly the
feff2f05 10006 -- result of applying Duplicate_Expr to the original tree, forcing
10007 -- the result to be a name.
ee6ba406 10008
10009 else
10010 declare
9dfe12ae 10011 Ndims : constant Nat := Number_Dimensions (T_Typ);
ee6ba406 10012
10013 begin
10014 -- Build the condition for the explicit dereference case
10015
10016 for Indx in 1 .. Ndims loop
10017 Evolve_Or_Else
10018 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
10019 end loop;
10020 end;
10021 end if;
10022 end if;
10023 end if;
10024
10025 -- Construct the test and insert into the tree
10026
10027 if Present (Cond) then
10028 if Do_Access then
10029 Cond := Guard_Access (Cond, Loc, Ck_Node);
10030 end if;
10031
f15731c4 10032 Add_Check
10033 (Make_Raise_Constraint_Error (Loc,
10034 Condition => Cond,
10035 Reason => CE_Length_Check_Failed));
ee6ba406 10036 end if;
10037
10038 return Ret_Result;
ee6ba406 10039 end Selected_Length_Checks;
10040
10041 ---------------------------
10042 -- Selected_Range_Checks --
10043 ---------------------------
10044
10045 function Selected_Range_Checks
10046 (Ck_Node : Node_Id;
10047 Target_Typ : Entity_Id;
10048 Source_Typ : Entity_Id;
314a23b6 10049 Warn_Node : Node_Id) return Check_Result
ee6ba406 10050 is
10051 Loc : constant Source_Ptr := Sloc (Ck_Node);
10052 S_Typ : Entity_Id;
10053 T_Typ : Entity_Id;
10054 Expr_Actual : Node_Id;
10055 Exptyp : Entity_Id;
10056 Cond : Node_Id := Empty;
10057 Do_Access : Boolean := False;
10058 Wnode : Node_Id := Warn_Node;
10059 Ret_Result : Check_Result := (Empty, Empty);
5bb74b99 10060 Num_Checks : Natural := 0;
ee6ba406 10061
10062 procedure Add_Check (N : Node_Id);
10063 -- Adds the action given to Ret_Result if N is non-Empty
10064
10065 function Discrete_Range_Cond
10066 (Expr : Node_Id;
314a23b6 10067 Typ : Entity_Id) return Node_Id;
ee6ba406 10068 -- Returns expression to compute:
10069 -- Low_Bound (Expr) < Typ'First
10070 -- or else
10071 -- High_Bound (Expr) > Typ'Last
10072
10073 function Discrete_Expr_Cond
10074 (Expr : Node_Id;
314a23b6 10075 Typ : Entity_Id) return Node_Id;
ee6ba406 10076 -- Returns expression to compute:
10077 -- Expr < Typ'First
10078 -- or else
10079 -- Expr > Typ'Last
10080
10081 function Get_E_First_Or_Last
3cb12758 10082 (Loc : Source_Ptr;
10083 E : Entity_Id;
ee6ba406 10084 Indx : Nat;
314a23b6 10085 Nam : Name_Id) return Node_Id;
79212397 10086 -- Returns an attribute reference
ee6ba406 10087 -- E'First or E'Last
79212397 10088 -- with a source location of Loc.
f73ee678 10089 --
79212397 10090 -- Nam is Name_First or Name_Last, according to which attribute is
10091 -- desired. If Indx is non-zero, it is passed as a literal in the
10092 -- Expressions of the attribute reference (identifying the desired
10093 -- array dimension).
ee6ba406 10094
10095 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
10096 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
10097 -- Returns expression to compute:
9dfe12ae 10098 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
ee6ba406 10099
10100 function Range_E_Cond
10101 (Exptyp : Entity_Id;
10102 Typ : Entity_Id;
10103 Indx : Nat)
10104 return Node_Id;
10105 -- Returns expression to compute:
10106 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
10107
10108 function Range_Equal_E_Cond
10109 (Exptyp : Entity_Id;
10110 Typ : Entity_Id;
314a23b6 10111 Indx : Nat) return Node_Id;
ee6ba406 10112 -- Returns expression to compute:
10113 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
10114
10115 function Range_N_Cond
10116 (Expr : Node_Id;
10117 Typ : Entity_Id;
314a23b6 10118 Indx : Nat) return Node_Id;
ee6ba406 10119 -- Return expression to compute:
10120 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
10121
10122 ---------------
10123 -- Add_Check --
10124 ---------------
10125
10126 procedure Add_Check (N : Node_Id) is
10127 begin
10128 if Present (N) then
10129
10130 -- For now, ignore attempt to place more than 2 checks ???
10131
10132 if Num_Checks = 2 then
10133 return;
10134 end if;
10135
10136 pragma Assert (Num_Checks <= 1);
10137 Num_Checks := Num_Checks + 1;
10138 Ret_Result (Num_Checks) := N;
10139 end if;
10140 end Add_Check;
10141
10142 -------------------------
10143 -- Discrete_Expr_Cond --
10144 -------------------------
10145
10146 function Discrete_Expr_Cond
10147 (Expr : Node_Id;
314a23b6 10148 Typ : Entity_Id) return Node_Id
ee6ba406 10149 is
10150 begin
10151 return
10152 Make_Or_Else (Loc,
10153 Left_Opnd =>
10154 Make_Op_Lt (Loc,
10155 Left_Opnd =>
9dfe12ae 10156 Convert_To (Base_Type (Typ),
10157 Duplicate_Subexpr_No_Checks (Expr)),
ee6ba406 10158 Right_Opnd =>
10159 Convert_To (Base_Type (Typ),
3cb12758 10160 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
ee6ba406 10161
10162 Right_Opnd =>
10163 Make_Op_Gt (Loc,
10164 Left_Opnd =>
9dfe12ae 10165 Convert_To (Base_Type (Typ),
10166 Duplicate_Subexpr_No_Checks (Expr)),
ee6ba406 10167 Right_Opnd =>
10168 Convert_To
10169 (Base_Type (Typ),
3cb12758 10170 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
ee6ba406 10171 end Discrete_Expr_Cond;
10172
10173 -------------------------
10174 -- Discrete_Range_Cond --
10175 -------------------------
10176
10177 function Discrete_Range_Cond
10178 (Expr : Node_Id;
314a23b6 10179 Typ : Entity_Id) return Node_Id
ee6ba406 10180 is
10181 LB : Node_Id := Low_Bound (Expr);
10182 HB : Node_Id := High_Bound (Expr);
10183
10184 Left_Opnd : Node_Id;
10185 Right_Opnd : Node_Id;
10186
10187 begin
10188 if Nkind (LB) = N_Identifier
feff2f05 10189 and then Ekind (Entity (LB)) = E_Discriminant
10190 then
ee6ba406 10191 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10192 end if;
10193
ee6ba406 10194 Left_Opnd :=
10195 Make_Op_Lt (Loc,
10196 Left_Opnd =>
10197 Convert_To
9dfe12ae 10198 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
ee6ba406 10199
10200 Right_Opnd =>
10201 Convert_To
3cb12758 10202 (Base_Type (Typ),
10203 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
ee6ba406 10204
ba9b1a39 10205 if Nkind (HB) = N_Identifier
10206 and then Ekind (Entity (HB)) = E_Discriminant
ee6ba406 10207 then
ba9b1a39 10208 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
ee6ba406 10209 end if;
10210
10211 Right_Opnd :=
10212 Make_Op_Gt (Loc,
10213 Left_Opnd =>
10214 Convert_To
9dfe12ae 10215 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
ee6ba406 10216
10217 Right_Opnd =>
10218 Convert_To
10219 (Base_Type (Typ),
3cb12758 10220 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
ee6ba406 10221
10222 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
10223 end Discrete_Range_Cond;
10224
10225 -------------------------
10226 -- Get_E_First_Or_Last --
10227 -------------------------
10228
10229 function Get_E_First_Or_Last
3cb12758 10230 (Loc : Source_Ptr;
10231 E : Entity_Id;
ee6ba406 10232 Indx : Nat;
314a23b6 10233 Nam : Name_Id) return Node_Id
ee6ba406 10234 is
3cb12758 10235 Exprs : List_Id;
ee6ba406 10236 begin
3cb12758 10237 if Indx > 0 then
10238 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
ee6ba406 10239 else
3cb12758 10240 Exprs := No_List;
ee6ba406 10241 end if;
10242
3cb12758 10243 return Make_Attribute_Reference (Loc,
10244 Prefix => New_Occurrence_Of (E, Loc),
10245 Attribute_Name => Nam,
10246 Expressions => Exprs);
ee6ba406 10247 end Get_E_First_Or_Last;
10248
10249 -----------------
10250 -- Get_N_First --
10251 -----------------
10252
10253 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
10254 begin
10255 return
10256 Make_Attribute_Reference (Loc,
10257 Attribute_Name => Name_First,
10258 Prefix =>
9dfe12ae 10259 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
ee6ba406 10260 Expressions => New_List (
10261 Make_Integer_Literal (Loc, Indx)));
ee6ba406 10262 end Get_N_First;
10263
10264 ----------------
10265 -- Get_N_Last --
10266 ----------------
10267
10268 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
10269 begin
10270 return
10271 Make_Attribute_Reference (Loc,
10272 Attribute_Name => Name_Last,
10273 Prefix =>
9dfe12ae 10274 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
ee6ba406 10275 Expressions => New_List (
10276 Make_Integer_Literal (Loc, Indx)));
ee6ba406 10277 end Get_N_Last;
10278
10279 ------------------
10280 -- Range_E_Cond --
10281 ------------------
10282
10283 function Range_E_Cond
10284 (Exptyp : Entity_Id;
10285 Typ : Entity_Id;
314a23b6 10286 Indx : Nat) return Node_Id
ee6ba406 10287 is
10288 begin
10289 return
10290 Make_Or_Else (Loc,
10291 Left_Opnd =>
10292 Make_Op_Lt (Loc,
3cb12758 10293 Left_Opnd =>
10294 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10295 Right_Opnd =>
10296 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
ee6ba406 10297
10298 Right_Opnd =>
10299 Make_Op_Gt (Loc,
3cb12758 10300 Left_Opnd =>
10301 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10302 Right_Opnd =>
10303 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
ee6ba406 10304 end Range_E_Cond;
10305
10306 ------------------------
10307 -- Range_Equal_E_Cond --
10308 ------------------------
10309
10310 function Range_Equal_E_Cond
10311 (Exptyp : Entity_Id;
10312 Typ : Entity_Id;
314a23b6 10313 Indx : Nat) return Node_Id
ee6ba406 10314 is
10315 begin
10316 return
10317 Make_Or_Else (Loc,
10318 Left_Opnd =>
10319 Make_Op_Ne (Loc,
3cb12758 10320 Left_Opnd =>
10321 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10322 Right_Opnd =>
10323 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10324
ee6ba406 10325 Right_Opnd =>
10326 Make_Op_Ne (Loc,
3cb12758 10327 Left_Opnd =>
10328 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10329 Right_Opnd =>
10330 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
ee6ba406 10331 end Range_Equal_E_Cond;
10332
10333 ------------------
10334 -- Range_N_Cond --
10335 ------------------
10336
10337 function Range_N_Cond
10338 (Expr : Node_Id;
10339 Typ : Entity_Id;
314a23b6 10340 Indx : Nat) return Node_Id
ee6ba406 10341 is
10342 begin
10343 return
10344 Make_Or_Else (Loc,
10345 Left_Opnd =>
10346 Make_Op_Lt (Loc,
3cb12758 10347 Left_Opnd =>
10348 Get_N_First (Expr, Indx),
10349 Right_Opnd =>
10350 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
ee6ba406 10351
10352 Right_Opnd =>
10353 Make_Op_Gt (Loc,
3cb12758 10354 Left_Opnd =>
10355 Get_N_Last (Expr, Indx),
10356 Right_Opnd =>
10357 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
ee6ba406 10358 end Range_N_Cond;
10359
10360 -- Start of processing for Selected_Range_Checks
10361
10362 begin
f0d65dae 10363 -- Checks will be applied only when generating code. In GNATprove mode,
10364 -- we do not apply the checks, but we still call Selected_Range_Checks
10365 -- to possibly issue errors on SPARK code when a run-time error can be
10366 -- detected at compile time.
10367
10368 if not Expander_Active and not GNATprove_Mode then
ee6ba406 10369 return Ret_Result;
10370 end if;
10371
10372 if Target_Typ = Any_Type
10373 or else Target_Typ = Any_Composite
10374 or else Raises_Constraint_Error (Ck_Node)
10375 then
10376 return Ret_Result;
10377 end if;
10378
10379 if No (Wnode) then
10380 Wnode := Ck_Node;
10381 end if;
10382
10383 T_Typ := Target_Typ;
10384
10385 if No (Source_Typ) then
10386 S_Typ := Etype (Ck_Node);
10387 else
10388 S_Typ := Source_Typ;
10389 end if;
10390
10391 if S_Typ = Any_Type or else S_Typ = Any_Composite then
10392 return Ret_Result;
10393 end if;
10394
10395 -- The order of evaluating T_Typ before S_Typ seems to be critical
10396 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
10397 -- in, and since Node can be an N_Range node, it might be invalid.
10398 -- Should there be an assert check somewhere for taking the Etype of
10399 -- an N_Range node ???
10400
10401 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
10402 S_Typ := Designated_Type (S_Typ);
10403 T_Typ := Designated_Type (T_Typ);
10404 Do_Access := True;
10405
2af58f67 10406 -- A simple optimization for the null case
ee6ba406 10407
2af58f67 10408 if Known_Null (Ck_Node) then
ee6ba406 10409 return Ret_Result;
10410 end if;
10411 end if;
10412
10413 -- For an N_Range Node, check for a null range and then if not
10414 -- null generate a range check action.
10415
10416 if Nkind (Ck_Node) = N_Range then
10417
10418 -- There's no point in checking a range against itself
10419
10420 if Ck_Node = Scalar_Range (T_Typ) then
10421 return Ret_Result;
10422 end if;
10423
10424 declare
10425 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
10426 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
eefa141b 10427 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
10428 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
ee6ba406 10429
eefa141b 10430 LB : Node_Id := Low_Bound (Ck_Node);
10431 HB : Node_Id := High_Bound (Ck_Node);
3fabf0ca 10432 Known_LB : Boolean := False;
10433 Known_HB : Boolean := False;
eefa141b 10434
10435 Null_Range : Boolean;
ee6ba406 10436 Out_Of_Range_L : Boolean;
10437 Out_Of_Range_H : Boolean;
10438
10439 begin
eefa141b 10440 -- Compute what is known at compile time
10441
10442 if Known_T_LB and Known_T_HB then
10443 if Compile_Time_Known_Value (LB) then
10444 Known_LB := True;
10445
10446 -- There's no point in checking that a bound is within its
10447 -- own range so pretend that it is known in this case. First
10448 -- deal with low bound.
10449
10450 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
10451 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
10452 then
10453 LB := T_LB;
10454 Known_LB := True;
eefa141b 10455 end if;
10456
10457 -- Likewise for the high bound
10458
10459 if Compile_Time_Known_Value (HB) then
10460 Known_HB := True;
10461
10462 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
10463 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
10464 then
10465 HB := T_HB;
10466 Known_HB := True;
eefa141b 10467 end if;
10468 end if;
10469
10470 -- Check for case where everything is static and we can do the
10471 -- check at compile time. This is skipped if we have an access
10472 -- type, since the access value may be null.
10473
10474 -- ??? This code can be improved since you only need to know that
10475 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
10476 -- compile time to emit pertinent messages.
10477
10478 if Known_T_LB and Known_T_HB and Known_LB and Known_HB
10479 and not Do_Access
ee6ba406 10480 then
10481 -- Floating-point case
10482
10483 if Is_Floating_Point_Type (S_Typ) then
10484 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
10485 Out_Of_Range_L :=
10486 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
eefa141b 10487 or else
ee6ba406 10488 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
10489
10490 Out_Of_Range_H :=
10491 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
eefa141b 10492 or else
ee6ba406 10493 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
10494
10495 -- Fixed or discrete type case
10496
10497 else
10498 Null_Range := Expr_Value (HB) < Expr_Value (LB);
10499 Out_Of_Range_L :=
10500 (Expr_Value (LB) < Expr_Value (T_LB))
eefa141b 10501 or else
ee6ba406 10502 (Expr_Value (LB) > Expr_Value (T_HB));
10503
10504 Out_Of_Range_H :=
10505 (Expr_Value (HB) > Expr_Value (T_HB))
eefa141b 10506 or else
ee6ba406 10507 (Expr_Value (HB) < Expr_Value (T_LB));
10508 end if;
10509
10510 if not Null_Range then
10511 if Out_Of_Range_L then
10512 if No (Warn_Node) then
10513 Add_Check
10514 (Compile_Time_Constraint_Error
10515 (Low_Bound (Ck_Node),
cb97ae5c 10516 "static value out of range of}??", T_Typ));
ee6ba406 10517
10518 else
10519 Add_Check
10520 (Compile_Time_Constraint_Error
10521 (Wnode,
cb97ae5c 10522 "static range out of bounds of}??", T_Typ));
ee6ba406 10523 end if;
10524 end if;
10525
10526 if Out_Of_Range_H then
10527 if No (Warn_Node) then
10528 Add_Check
10529 (Compile_Time_Constraint_Error
10530 (High_Bound (Ck_Node),
cb97ae5c 10531 "static value out of range of}??", T_Typ));
ee6ba406 10532
10533 else
10534 Add_Check
10535 (Compile_Time_Constraint_Error
10536 (Wnode,
cb97ae5c 10537 "static range out of bounds of}??", T_Typ));
ee6ba406 10538 end if;
10539 end if;
ee6ba406 10540 end if;
10541
10542 else
10543 declare
10544 LB : Node_Id := Low_Bound (Ck_Node);
10545 HB : Node_Id := High_Bound (Ck_Node);
10546
10547 begin
feff2f05 10548 -- If either bound is a discriminant and we are within the
10549 -- record declaration, it is a use of the discriminant in a
10550 -- constraint of a component, and nothing can be checked
10551 -- here. The check will be emitted within the init proc.
10552 -- Before then, the discriminal has no real meaning.
10553 -- Similarly, if the entity is a discriminal, there is no
10554 -- check to perform yet.
10555
10556 -- The same holds within a discriminated synchronized type,
10557 -- where the discriminant may constrain a component or an
10558 -- entry family.
ee6ba406 10559
10560 if Nkind (LB) = N_Identifier
0577b0b1 10561 and then Denotes_Discriminant (LB, True)
ee6ba406 10562 then
0577b0b1 10563 if Current_Scope = Scope (Entity (LB))
10564 or else Is_Concurrent_Type (Current_Scope)
10565 or else Ekind (Entity (LB)) /= E_Discriminant
10566 then
ee6ba406 10567 return Ret_Result;
10568 else
10569 LB :=
10570 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10571 end if;
10572 end if;
10573
10574 if Nkind (HB) = N_Identifier
0577b0b1 10575 and then Denotes_Discriminant (HB, True)
ee6ba406 10576 then
0577b0b1 10577 if Current_Scope = Scope (Entity (HB))
10578 or else Is_Concurrent_Type (Current_Scope)
10579 or else Ekind (Entity (HB)) /= E_Discriminant
10580 then
ee6ba406 10581 return Ret_Result;
10582 else
10583 HB :=
10584 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10585 end if;
10586 end if;
10587
10588 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
10589 Set_Paren_Count (Cond, 1);
10590
10591 Cond :=
10592 Make_And_Then (Loc,
10593 Left_Opnd =>
10594 Make_Op_Ge (Loc,
86d32751 10595 Left_Opnd =>
10596 Convert_To (Base_Type (Etype (HB)),
10597 Duplicate_Subexpr_No_Checks (HB)),
10598 Right_Opnd =>
10599 Convert_To (Base_Type (Etype (LB)),
10600 Duplicate_Subexpr_No_Checks (LB))),
ee6ba406 10601 Right_Opnd => Cond);
10602 end;
ee6ba406 10603 end if;
10604 end;
10605
10606 elsif Is_Scalar_Type (S_Typ) then
10607
10608 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
10609 -- except the above simply sets a flag in the node and lets
10610 -- gigi generate the check base on the Etype of the expression.
10611 -- Sometimes, however we want to do a dynamic check against an
10612 -- arbitrary target type, so we do that here.
10613
10614 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
10615 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10616
10617 -- For literals, we can tell if the constraint error will be
10618 -- raised at compile time, so we never need a dynamic check, but
10619 -- if the exception will be raised, then post the usual warning,
10620 -- and replace the literal with a raise constraint error
10621 -- expression. As usual, skip this for access types
10622
20cf157b 10623 elsif Compile_Time_Known_Value (Ck_Node) and then not Do_Access then
ee6ba406 10624 declare
10625 LB : constant Node_Id := Type_Low_Bound (T_Typ);
10626 UB : constant Node_Id := Type_High_Bound (T_Typ);
10627
10628 Out_Of_Range : Boolean;
10629 Static_Bounds : constant Boolean :=
b6341c67 10630 Compile_Time_Known_Value (LB)
10631 and Compile_Time_Known_Value (UB);
ee6ba406 10632
10633 begin
10634 -- Following range tests should use Sem_Eval routine ???
10635
10636 if Static_Bounds then
10637 if Is_Floating_Point_Type (S_Typ) then
10638 Out_Of_Range :=
10639 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
10640 or else
10641 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
10642
eefa141b 10643 -- Fixed or discrete type
10644
10645 else
ee6ba406 10646 Out_Of_Range :=
10647 Expr_Value (Ck_Node) < Expr_Value (LB)
10648 or else
10649 Expr_Value (Ck_Node) > Expr_Value (UB);
10650 end if;
10651
eefa141b 10652 -- Bounds of the type are static and the literal is out of
10653 -- range so output a warning message.
ee6ba406 10654
10655 if Out_Of_Range then
10656 if No (Warn_Node) then
10657 Add_Check
10658 (Compile_Time_Constraint_Error
10659 (Ck_Node,
cb97ae5c 10660 "static value out of range of}??", T_Typ));
ee6ba406 10661
10662 else
10663 Add_Check
10664 (Compile_Time_Constraint_Error
10665 (Wnode,
cb97ae5c 10666 "static value out of range of}??", T_Typ));
ee6ba406 10667 end if;
10668 end if;
10669
10670 else
10671 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10672 end if;
10673 end;
10674
10675 -- Here for the case of a non-static expression, we need a runtime
10676 -- check unless the source type range is guaranteed to be in the
10677 -- range of the target type.
10678
10679 else
7a1dabb3 10680 if not In_Subrange_Of (S_Typ, T_Typ) then
ee6ba406 10681 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10682 end if;
10683 end if;
10684 end if;
10685
10686 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
10687 if Is_Constrained (T_Typ) then
10688
10689 Expr_Actual := Get_Referenced_Object (Ck_Node);
10690 Exptyp := Get_Actual_Subtype (Expr_Actual);
10691
10692 if Is_Access_Type (Exptyp) then
10693 Exptyp := Designated_Type (Exptyp);
10694 end if;
10695
10696 -- String_Literal case. This needs to be handled specially be-
10697 -- cause no index types are available for string literals. The
10698 -- condition is simply:
10699
10700 -- T_Typ'Length = string-literal-length
10701
10702 if Nkind (Expr_Actual) = N_String_Literal then
10703 null;
10704
10705 -- General array case. Here we have a usable actual subtype for
10706 -- the expression, and the condition is built from the two types
10707
10708 -- T_Typ'First < Exptyp'First or else
10709 -- T_Typ'Last > Exptyp'Last or else
10710 -- T_Typ'First(1) < Exptyp'First(1) or else
10711 -- T_Typ'Last(1) > Exptyp'Last(1) or else
10712 -- ...
10713
10714 elsif Is_Constrained (Exptyp) then
10715 declare
9dfe12ae 10716 Ndims : constant Nat := Number_Dimensions (T_Typ);
10717
ee6ba406 10718 L_Index : Node_Id;
10719 R_Index : Node_Id;
ee6ba406 10720
10721 begin
10722 L_Index := First_Index (T_Typ);
10723 R_Index := First_Index (Exptyp);
10724
10725 for Indx in 1 .. Ndims loop
10726 if not (Nkind (L_Index) = N_Raise_Constraint_Error
f15731c4 10727 or else
10728 Nkind (R_Index) = N_Raise_Constraint_Error)
ee6ba406 10729 then
ee6ba406 10730 -- Deal with compile time length check. Note that we
10731 -- skip this in the access case, because the access
10732 -- value may be null, so we cannot know statically.
10733
10734 if not
10735 Subtypes_Statically_Match
10736 (Etype (L_Index), Etype (R_Index))
10737 then
10738 -- If the target type is constrained then we
10739 -- have to check for exact equality of bounds
10740 -- (required for qualified expressions).
10741
10742 if Is_Constrained (T_Typ) then
10743 Evolve_Or_Else
10744 (Cond,
10745 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
ee6ba406 10746 else
10747 Evolve_Or_Else
10748 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
10749 end if;
10750 end if;
10751
10752 Next (L_Index);
10753 Next (R_Index);
ee6ba406 10754 end if;
10755 end loop;
10756 end;
10757
10758 -- Handle cases where we do not get a usable actual subtype that
10759 -- is constrained. This happens for example in the function call
10760 -- and explicit dereference cases. In these cases, we have to get
10761 -- the length or range from the expression itself, making sure we
10762 -- do not evaluate it more than once.
10763
10764 -- Here Ck_Node is the original expression, or more properly the
10765 -- result of applying Duplicate_Expr to the original tree,
10766 -- forcing the result to be a name.
10767
10768 else
10769 declare
9dfe12ae 10770 Ndims : constant Nat := Number_Dimensions (T_Typ);
ee6ba406 10771
10772 begin
10773 -- Build the condition for the explicit dereference case
10774
10775 for Indx in 1 .. Ndims loop
10776 Evolve_Or_Else
10777 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
10778 end loop;
10779 end;
ee6ba406 10780 end if;
10781
10782 else
feff2f05 10783 -- For a conversion to an unconstrained array type, generate an
10784 -- Action to check that the bounds of the source value are within
10785 -- the constraints imposed by the target type (RM 4.6(38)). No
10786 -- check is needed for a conversion to an access to unconstrained
10787 -- array type, as 4.6(24.15/2) requires the designated subtypes
10788 -- of the two access types to statically match.
10789
10790 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
10791 and then not Do_Access
10792 then
ee6ba406 10793 declare
10794 Opnd_Index : Node_Id;
10795 Targ_Index : Node_Id;
00c403ee 10796 Opnd_Range : Node_Id;
ee6ba406 10797
10798 begin
feff2f05 10799 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
ee6ba406 10800 Targ_Index := First_Index (T_Typ);
00c403ee 10801 while Present (Opnd_Index) loop
10802
10803 -- If the index is a range, use its bounds. If it is an
10804 -- entity (as will be the case if it is a named subtype
10805 -- or an itype created for a slice) retrieve its range.
10806
10807 if Is_Entity_Name (Opnd_Index)
10808 and then Is_Type (Entity (Opnd_Index))
10809 then
10810 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
10811 else
10812 Opnd_Range := Opnd_Index;
10813 end if;
10814
10815 if Nkind (Opnd_Range) = N_Range then
9c486805 10816 if Is_In_Range
10817 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10818 Assume_Valid => True)
ee6ba406 10819 and then
10820 Is_In_Range
9c486805 10821 (High_Bound (Opnd_Range), Etype (Targ_Index),
10822 Assume_Valid => True)
ee6ba406 10823 then
10824 null;
10825
feff2f05 10826 -- If null range, no check needed
f2a06be9 10827
9dfe12ae 10828 elsif
00c403ee 10829 Compile_Time_Known_Value (High_Bound (Opnd_Range))
9dfe12ae 10830 and then
00c403ee 10831 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
9dfe12ae 10832 and then
00c403ee 10833 Expr_Value (High_Bound (Opnd_Range)) <
10834 Expr_Value (Low_Bound (Opnd_Range))
9dfe12ae 10835 then
10836 null;
10837
ee6ba406 10838 elsif Is_Out_Of_Range
9c486805 10839 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10840 Assume_Valid => True)
ee6ba406 10841 or else
10842 Is_Out_Of_Range
9c486805 10843 (High_Bound (Opnd_Range), Etype (Targ_Index),
10844 Assume_Valid => True)
ee6ba406 10845 then
10846 Add_Check
10847 (Compile_Time_Constraint_Error
cb97ae5c 10848 (Wnode, "value out of range of}??", T_Typ));
ee6ba406 10849
10850 else
10851 Evolve_Or_Else
10852 (Cond,
10853 Discrete_Range_Cond
00c403ee 10854 (Opnd_Range, Etype (Targ_Index)));
ee6ba406 10855 end if;
10856 end if;
10857
10858 Next_Index (Opnd_Index);
10859 Next_Index (Targ_Index);
10860 end loop;
10861 end;
10862 end if;
10863 end if;
10864 end if;
10865
10866 -- Construct the test and insert into the tree
10867
10868 if Present (Cond) then
10869 if Do_Access then
10870 Cond := Guard_Access (Cond, Loc, Ck_Node);
10871 end if;
10872
f15731c4 10873 Add_Check
10874 (Make_Raise_Constraint_Error (Loc,
eefa141b 10875 Condition => Cond,
22d3a5a3 10876 Reason => CE_Range_Check_Failed));
ee6ba406 10877 end if;
10878
10879 return Ret_Result;
ee6ba406 10880 end Selected_Range_Checks;
10881
10882 -------------------------------
10883 -- Storage_Checks_Suppressed --
10884 -------------------------------
10885
10886 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
10887 begin
9dfe12ae 10888 if Present (E) and then Checks_May_Be_Suppressed (E) then
10889 return Is_Check_Suppressed (E, Storage_Check);
10890 else
fafc6b97 10891 return Scope_Suppress.Suppress (Storage_Check);
9dfe12ae 10892 end if;
ee6ba406 10893 end Storage_Checks_Suppressed;
10894
10895 ---------------------------
10896 -- Tag_Checks_Suppressed --
10897 ---------------------------
10898
10899 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
10900 begin
89f1e35c 10901 if Present (E)
10902 and then Checks_May_Be_Suppressed (E)
10903 then
10904 return Is_Check_Suppressed (E, Tag_Check);
20cf157b 10905 else
10906 return Scope_Suppress.Suppress (Tag_Check);
9dfe12ae 10907 end if;
ee6ba406 10908 end Tag_Checks_Suppressed;
10909
7b8fa048 10910 ---------------------------------------
10911 -- Validate_Alignment_Check_Warnings --
10912 ---------------------------------------
10913
10914 procedure Validate_Alignment_Check_Warnings is
10915 begin
10916 for J in Alignment_Warnings.First .. Alignment_Warnings.Last loop
10917 declare
10918 AWR : Alignment_Warnings_Record
10919 renames Alignment_Warnings.Table (J);
10920 begin
10921 if Known_Alignment (AWR.E)
10922 and then AWR.A mod Alignment (AWR.E) = 0
10923 then
10924 Delete_Warning_And_Continuations (AWR.W);
10925 end if;
10926 end;
10927 end loop;
10928 end Validate_Alignment_Check_Warnings;
10929
0577b0b1 10930 --------------------------
10931 -- Validity_Check_Range --
10932 --------------------------
10933
aaec8d13 10934 procedure Validity_Check_Range
10935 (N : Node_Id;
10936 Related_Id : Entity_Id := Empty)
10937 is
0577b0b1 10938 begin
10939 if Validity_Checks_On and Validity_Check_Operands then
10940 if Nkind (N) = N_Range then
aaec8d13 10941 Ensure_Valid
10942 (Expr => Low_Bound (N),
10943 Related_Id => Related_Id,
10944 Is_Low_Bound => True);
10945
10946 Ensure_Valid
10947 (Expr => High_Bound (N),
10948 Related_Id => Related_Id,
10949 Is_High_Bound => True);
0577b0b1 10950 end if;
10951 end if;
10952 end Validity_Check_Range;
10953
10954 --------------------------------
10955 -- Validity_Checks_Suppressed --
10956 --------------------------------
10957
10958 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
10959 begin
10960 if Present (E) and then Checks_May_Be_Suppressed (E) then
10961 return Is_Check_Suppressed (E, Validity_Check);
10962 else
fafc6b97 10963 return Scope_Suppress.Suppress (Validity_Check);
0577b0b1 10964 end if;
10965 end Validity_Checks_Suppressed;
10966
ee6ba406 10967end Checks;