]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/ada/checks.ads
Correct a function pre/postcondition [PR102403].
[thirdparty/gcc.git] / gcc / ada / checks.ads
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- C H E C K S --
6 -- --
7 -- S p e c --
8 -- --
9 -- Copyright (C) 1992-2021, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
25
26 -- Package containing routines used to deal with run-time checks. These
27 -- routines are used both by the semantics and by the expander. In some
28 -- cases, checks are enabled simply by setting a flag for the back end,
29 -- and in other cases the code for the check is expanded.
30
31 -- The approach used for range and length checks, in regards to suppressed
32 -- checks, is to attempt to detect at compilation time that a constraint
33 -- error will occur. If this is detected a warning or error is issued and the
34 -- offending expression or statement replaced with a constraint error node.
35 -- This always occurs whether checks are suppressed or not. Dynamic range
36 -- checks are, of course, not inserted if checks are suppressed.
37
38 with Errout; use Errout;
39 with Namet; use Namet;
40 with Table;
41 with Types; use Types;
42 with Uintp; use Uintp;
43 with Urealp; use Urealp;
44
45 package Checks is
46
47 procedure Initialize;
48 -- Called for each new main source program, to initialize internal
49 -- variables used in the package body of the Checks unit.
50
51 function Access_Checks_Suppressed (E : Entity_Id) return Boolean;
52 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean;
53 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean;
54 function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean;
55 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean;
56 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean;
57 function Division_Checks_Suppressed (E : Entity_Id) return Boolean;
58 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean;
59 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean;
60 function Index_Checks_Suppressed (E : Entity_Id) return Boolean;
61 function Length_Checks_Suppressed (E : Entity_Id) return Boolean;
62 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean;
63 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean;
64 function Range_Checks_Suppressed (E : Entity_Id) return Boolean;
65 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean;
66 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean;
67 -- These functions check to see if the named check is suppressed, either
68 -- by an active scope suppress setting, or because the check has been
69 -- specifically suppressed for the given entity. If no entity is relevant
70 -- for the current check, then Empty is used as an argument. Note: the
71 -- reason we insist on specifying Empty is to force the caller to think
72 -- about whether there is any relevant entity that should be checked.
73
74 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean;
75 -- This function is called if Checks_May_Be_Suppressed (E) is True to
76 -- determine whether check C is suppressed either on the entity E or
77 -- as the result of a scope suppress pragma. If Checks_May_Be_Suppressed
78 -- is False, then the status of the check can be determined simply by
79 -- examining Scope_Suppress, so this routine is not called in that case.
80
81 function Overflow_Check_Mode return Overflow_Mode_Type;
82 -- Returns current overflow checking mode, taking into account whether
83 -- we are inside an assertion expression and the assertion policy.
84
85 -----------------------------------------
86 -- Control of Alignment Check Warnings --
87 -----------------------------------------
88
89 -- When we have address clauses, there is an issue of whether the address
90 -- specified is appropriate to the alignment. In the general case where the
91 -- address is dynamic, we generate a check and a possible warning (this
92 -- warning occurs for example if we have a restricted runtime with the
93 -- restriction No_Exception_Propagation). We also issue this warning in
94 -- the case where the address is static, but we don't know the alignment
95 -- at the time we process the address clause. In such a case, we issue the
96 -- warning, but we may be able to find out later (after the back end has
97 -- annotated the actual alignment chosen) that the warning was not needed.
98
99 -- To deal with deleting these potentially annoying warnings, we save the
100 -- warning information in a table, and then delete the warnings in the
101 -- post compilation validation stage if we can tell that the check would
102 -- never fail (in general the back end will also optimize away the check
103 -- in such cases).
104
105 -- Table used to record information
106
107 type Alignment_Warnings_Record is record
108 E : Entity_Id;
109 -- Entity whose alignment possibly warrants a warning
110
111 A : Uint;
112 -- Compile time known value of address clause for which the alignment
113 -- is to be checked once we know the alignment.
114
115 P : Node_Id;
116 -- Prefix of address clause when it is of the form X'Address
117
118 W : Error_Msg_Id;
119 -- Id of warning message we might delete
120 end record;
121
122 package Alignment_Warnings is new Table.Table (
123 Table_Component_Type => Alignment_Warnings_Record,
124 Table_Index_Type => Int,
125 Table_Low_Bound => 0,
126 Table_Initial => 10,
127 Table_Increment => 200,
128 Table_Name => "Alignment_Warnings");
129
130 procedure Validate_Alignment_Check_Warnings;
131 -- This routine is called after back annotation of type data to delete any
132 -- alignment warnings that turn out to be false alarms, based on knowing
133 -- the actual alignment, and a compile-time known alignment value.
134
135 -------------------------------------------
136 -- Procedures to Activate Checking Flags --
137 -------------------------------------------
138
139 procedure Activate_Division_Check (N : Node_Id);
140 pragma Inline (Activate_Division_Check);
141 -- Sets Do_Division_Check flag in node N, and handles possible local raise.
142 -- Always call this routine rather than calling Set_Do_Division_Check to
143 -- set an explicit value of True, to ensure handling the local raise case.
144
145 procedure Activate_Overflow_Check (N : Node_Id);
146 pragma Inline (Activate_Overflow_Check);
147 -- Sets Do_Overflow_Check flag in node N, and handles possible local raise.
148 -- Always call this routine rather than calling Set_Do_Overflow_Check to
149 -- set an explicit value of True, to ensure handling the local raise case.
150 -- Note that for discrete types, this call has no effect for MOD, REM, and
151 -- unary "+" for which overflow is never possible in any case.
152 --
153 -- Note: for the discrete-type case, it is legitimate to call this routine
154 -- on an unanalyzed node where the Etype field is not set. However, for the
155 -- floating-point case, Etype must be set (to a floating-point type).
156 --
157 -- For floating-point, we set the flag if we have automatic overflow checks
158 -- on the target, or if Check_Float_Overflow mode is set. For the floating-
159 -- point case, we ignore all the unary operators ("+", "-", and abs) since
160 -- none of these can result in overflow. If there are no overflow checks on
161 -- the target, and Check_Float_Overflow mode is not set, then the call has
162 -- no effect, since in such cases we want to generate NaN's and infinities.
163
164 procedure Activate_Range_Check (N : Node_Id);
165 pragma Inline (Activate_Range_Check);
166 -- Sets Do_Range_Check flag in node N, and handles possible local raise.
167 -- Always call this routine rather than calling Set_Do_Range_Check to
168 -- set an explicit value of True, to ensure handling the local raise case.
169
170 --------------------------------
171 -- Procedures to Apply Checks --
172 --------------------------------
173
174 -- General note on following checks. These checks are always active if
175 -- Expander_Active and not Inside_A_Generic. They are inactive and have
176 -- no effect Inside_A_Generic. In the case where not Expander_Active
177 -- and not Inside_A_Generic, most of them are inactive, but some of them
178 -- operate anyway since they may generate useful compile time warnings.
179
180 procedure Apply_Access_Check (N : Node_Id);
181 -- Determines whether an expression node requires a run-time access
182 -- check and if so inserts the appropriate run-time check.
183
184 procedure Apply_Accessibility_Check
185 (N : Node_Id;
186 Typ : Entity_Id;
187 Insert_Node : Node_Id);
188 -- Given a name N denoting an access parameter, emits a run-time
189 -- accessibility check (if necessary), checking that the level of
190 -- the object denoted by the access parameter is not deeper than the
191 -- level of the type Typ. Program_Error is raised if the check fails.
192 -- Insert_Node indicates the node where the check should be inserted.
193
194 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id);
195 -- E is the entity for an object which has an address clause. If checks
196 -- are enabled, then this procedure generates a check that the specified
197 -- address has an alignment consistent with the alignment of the object,
198 -- raising PE if this is not the case. The resulting check (if one is
199 -- generated) is prepended to the Actions list of N_Freeze_Entity node N.
200 -- Note that the check references E'Alignment, so it cannot be emitted
201 -- before N (its freeze node), otherwise this would cause an illegal
202 -- access before elaboration error in gigi. For the case of a clear overlay
203 -- situation, we also check that the size of the overlaying object is not
204 -- larger than the overlaid object.
205
206 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id);
207 -- Handle overflow checking for an arithmetic operator. Also handles the
208 -- cases of ELIMINATED and MINIMIZED overflow checking mode. If the mode
209 -- is one of the latter two, then this routine can also be called with
210 -- an if or case expression node to make sure that we properly handle
211 -- overflow checking for dependent expressions. This routine handles
212 -- front end vs back end overflow checks (in the front end case it expands
213 -- the necessary check). Note that divide is handled separately using
214 -- Apply_Divide_Checks. Node N may or may not have Do_Overflow_Check.
215 -- In STRICT mode, there is nothing to do if this flag is off, but in
216 -- MINIMIZED/ELIMINATED mode we still have to deal with possible use
217 -- of doing operations in Long_Long_Integer or Bignum mode.
218
219 procedure Apply_Constraint_Check
220 (N : Node_Id;
221 Typ : Entity_Id;
222 No_Sliding : Boolean := False);
223 -- Top-level procedure, calls all the others depending on the class of
224 -- Typ. Checks that expression N satisfies the constraint of type Typ.
225 -- No_Sliding is only relevant for constrained array types, if set to
226 -- True, it checks that indexes are in range.
227
228 procedure Apply_Discriminant_Check
229 (N : Node_Id;
230 Typ : Entity_Id;
231 Lhs : Node_Id := Empty);
232 -- Given an expression N of a discriminated type, or of an access type
233 -- whose designated type is a discriminanted type, generates a check to
234 -- ensure that the expression can be converted to the subtype given as
235 -- the second parameter. Lhs is empty except in the case of assignments,
236 -- where the target object may be needed to determine the subtype to
237 -- check against (such as the cases of unconstrained formal parameters
238 -- and unconstrained aliased objects). For the case of unconstrained
239 -- formals, the check is performed only if the corresponding actual is
240 -- constrained, i.e., whether Lhs'Constrained is True.
241
242 procedure Apply_Divide_Checks (N : Node_Id);
243 -- The node kind is N_Op_Divide, N_Op_Mod, or N_Op_Rem if either of the
244 -- flags Do_Division_Check or Do_Overflow_Check is set, then this routine
245 -- ensures that the appropriate checks are made. Note that overflow can
246 -- occur in the signed case for the case of the largest negative number
247 -- divided by minus one. This procedure only applies to Integer types.
248
249 procedure Apply_Parameter_Aliasing_Checks
250 (Call : Node_Id;
251 Subp : Entity_Id);
252 -- Given a subprogram call Call, add a check to verify that none of the
253 -- actuals overlap. Subp denotes the subprogram being called.
254
255 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id);
256 -- Given a subprogram Subp, add both a pre and post condition pragmas that
257 -- verify the proper initialization of scalars in parameters and function
258 -- results.
259
260 procedure Apply_Predicate_Check
261 (N : Node_Id;
262 Typ : Entity_Id;
263 Fun : Entity_Id := Empty);
264 -- N is an expression to which a predicate check may need to be applied for
265 -- Typ, if Typ has a predicate function. When N is an actual in a call, Fun
266 -- is the function being called, which is used to generate a better warning
267 -- if the call leads to an infinite recursion.
268
269 procedure Apply_Type_Conversion_Checks (N : Node_Id);
270 -- N is an N_Type_Conversion node. A type conversion actually involves
271 -- two sorts of checks. The first check is the checks that ensures that
272 -- the operand in the type conversion fits onto the base type of the
273 -- subtype it is being converted to (see RM 4.6 (28)-(50)). The second
274 -- check is there to ensure that once the operand has been converted to
275 -- a value of the target type, this converted value meets the
276 -- constraints imposed by the target subtype (see RM 4.6 (51)).
277
278 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id);
279 -- The argument N is an attribute reference node intended for processing
280 -- by gigi. The attribute is one that returns a universal integer, but
281 -- the attribute reference node is currently typed with the expected
282 -- result type. This routine deals with range and overflow checks needed
283 -- to make sure that the universal result is in range.
284
285 function Build_Discriminant_Checks
286 (N : Node_Id;
287 T_Typ : Entity_Id)
288 return Node_Id;
289 -- Subsidiary routine for Apply_Discriminant_Check. Builds the expression
290 -- that compares discriminants of the expression with discriminants of the
291 -- type. Also used directly for membership tests (see Exp_Ch4.Expand_N_In).
292
293 function Convert_From_Bignum (N : Node_Id) return Node_Id;
294 -- Returns result of converting node N from Bignum. The returned value is
295 -- not analyzed, the caller takes responsibility for this. Node N must be
296 -- a subexpression node of type Bignum. The result is Long_Long_Integer.
297
298 function Convert_To_Bignum (N : Node_Id) return Node_Id;
299 -- Returns result of converting node N to Bignum. The returned value is not
300 -- analyzed, the caller takes responsibility for this. Node N must be a
301 -- subexpression node of a signed integer type or Bignum type (if it is
302 -- already a Bignum, the returned value is Relocate_Node (N)).
303
304 procedure Determine_Range
305 (N : Node_Id;
306 OK : out Boolean;
307 Lo : out Uint;
308 Hi : out Uint;
309 Assume_Valid : Boolean := False);
310 -- N is a node for a subexpression. If N is of a discrete type with no
311 -- error indications, and no other peculiarities (e.g. missing Etype),
312 -- then OK is True on return, and Lo and Hi are set to a conservative
313 -- estimate of the possible range of values of N. Thus if OK is True on
314 -- return, the value of the subexpression N is known to lie in the range
315 -- Lo .. Hi (inclusive). For enumeration and character literals the values
316 -- returned are the Pos value in the relevant enumeration type. If the
317 -- expression is not of a discrete type, or some kind of error condition
318 -- is detected, then OK is False on exit, and Lo/Hi are set to No_Uint.
319 -- Thus the significance of OK being False on return is that no useful
320 -- information is available on the range of the expression. Assume_Valid
321 -- determines whether the processing is allowed to assume that values are
322 -- in range of their subtypes. If it is set to True, then this assumption
323 -- is valid, if False, then processing is done using base types to allow
324 -- invalid values.
325
326 procedure Determine_Range_R
327 (N : Node_Id;
328 OK : out Boolean;
329 Lo : out Ureal;
330 Hi : out Ureal;
331 Assume_Valid : Boolean := False);
332 -- Similar to Determine_Range, but for a node N of floating-point type. OK
333 -- is True on return only for IEEE floating-point types and only if we do
334 -- not have to worry about extended precision (i.e. on the x86, we must be
335 -- using -msse2 -mfpmath=sse). At the current time, this is used only in
336 -- GNATprove, though we could consider using it more generally in future.
337 -- For that to happen, the possibility of arguments of infinite or NaN
338 -- value should be taken into account, which is not the case currently.
339
340 procedure Determine_Range_To_Discrete
341 (N : Node_Id;
342 OK : out Boolean;
343 Lo : out Uint;
344 Hi : out Uint;
345 Fixed_Int : Boolean := False;
346 Assume_Valid : Boolean := False);
347 -- Similar to Determine_Range, but attempts to return a discrete range even
348 -- if N is not of a discrete type by doing a conversion. The Fixed_Int flag
349 -- if set causes any fixed-point values to be treated as though they were
350 -- discrete values (i.e. the underlying integer value is used), in which
351 -- case no conversion is needed. At the current time, this is used only for
352 -- discrete types, for fixed-point types if Fixed_Int is set, and also for
353 -- floating-point types in GNATprove, see Determine_Range_R above.
354
355 procedure Install_Null_Excluding_Check (N : Node_Id);
356 -- Determines whether an access node requires a run-time access check and
357 -- if so inserts the appropriate run-time check.
358
359 procedure Install_Primitive_Elaboration_Check (Subp_Body : Node_Id);
360 -- Insert a check to ensure that subprogram body Subp_Body has been
361 -- properly elaborated. The check is installed only when Subp_Body is the
362 -- body of a nonabstract library-level primitive of a tagged type. Further
363 -- restrictions may apply, see the body for details.
364
365 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id;
366 -- This function is used by top level overflow checking routines to do a
367 -- mark/release operation on the secondary stack around bignum operations.
368 -- The block created looks like:
369 --
370 -- declare
371 -- M : Mark_Id := SS_Mark;
372 -- begin
373 -- SS_Release (M);
374 -- end;
375 --
376 -- The idea is that the caller will insert any needed extra declarations
377 -- after the declaration of M, and any needed statements (in particular
378 -- the bignum operations) before the call to SS_Release, and then do an
379 -- Insert_Action of the whole block (it is returned unanalyzed). The Loc
380 -- parameter is used to supply Sloc values for the constructed tree.
381
382 procedure Minimize_Eliminate_Overflows
383 (N : Node_Id;
384 Lo : out Uint;
385 Hi : out Uint;
386 Top_Level : Boolean);
387 -- This is the main routine for handling MINIMIZED and ELIMINATED overflow
388 -- processing. On entry N is a node whose result is a signed integer
389 -- subtype. The Do_Overflow_Check flag may or may not be set on N. If the
390 -- node is an arithmetic operation, then a range analysis is carried out,
391 -- and there are three possibilities:
392 --
393 -- The node is left unchanged (apart from expansion of an exponentiation
394 -- operation). This happens if the routine can determine that the result
395 -- is definitely in range. The Do_Overflow_Check flag is turned off in
396 -- this case.
397 --
398 -- The node is transformed into an arithmetic operation with a result
399 -- type of Long_Long_Integer.
400 --
401 -- The node is transformed into a function call that calls an appropriate
402 -- function in the System.Bignums package to compute a Bignum result.
403 --
404 -- In the first two cases, Lo and Hi are set to the bounds of the possible
405 -- range of results, computed as accurately as possible. In the third case
406 -- Lo and Hi are set to No_Uint (there are some cases where we could get an
407 -- advantage from keeping result ranges for Bignum values, but it could use
408 -- a lot of space and is very unlikely to be valuable).
409 --
410 -- If the node is not an arithmetic operation, then it is unchanged but
411 -- Lo and Hi are still set (to the bounds of the result subtype if nothing
412 -- better can be determined).
413 --
414 -- Note: this function is recursive, if called with an arithmetic operator,
415 -- recursive calls are made to process the operands using this procedure.
416 -- So we end up doing things top down. Nothing happens to an arithmetic
417 -- expression until this procedure is called on the top level node and
418 -- then the recursive calls process all the children. We have to do it
419 -- this way. If we try to do it bottom up in natural expansion order, then
420 -- there are two problems. First, where do we stash the bounds, and more
421 -- importantly, semantic processing will be messed up. Consider A+B+C where
422 -- A,B,C are all of type integer, if we processed A+B before doing semantic
423 -- analysis of the addition of this result to C, that addition could end up
424 -- with a Long_Long_Integer left operand and an Integer right operand, and
425 -- we would get a semantic error.
426 --
427 -- The routine is called in three situations if we are operating in either
428 -- MINIMIZED or ELIMINATED modes.
429 --
430 -- Overflow processing applied to the top node of an expression tree when
431 -- that node is an arithmetic operator. In this case the result is
432 -- converted to the appropriate result type (there is special processing
433 -- when the parent is a conversion, see body for details).
434 --
435 -- Overflow processing applied to the operands of a comparison operation.
436 -- In this case, the comparison is done on the result Long_Long_Integer
437 -- or Bignum values, without raising any exceptions.
438 --
439 -- Overflow processing applied to the left operand of a membership test.
440 -- In this case no exception is raised if a Long_Long_Integer or Bignum
441 -- result is outside the range of the type of that left operand (it is
442 -- just that the result of IN is false in that case).
443 --
444 -- Note that if Bignum values appear, the caller must take care of doing
445 -- the appropriate mark/release operations on the secondary stack.
446 --
447 -- Top_Level is used to avoid inefficient unnecessary transitions into the
448 -- Bignum domain. If Top_Level is True, it means that the caller will have
449 -- to convert any Bignum value back to Long_Long_Integer, possibly checking
450 -- that the value is in range. This is the normal case for a top level
451 -- operator in a subexpression. There is no point in going into Bignum mode
452 -- to avoid an overflow just so we can check for overflow the next moment.
453 -- For calls from comparisons and membership tests, and for all recursive
454 -- calls, we do want to transition into the Bignum domain if necessary.
455 -- Note that this setting is only relevant in ELIMINATED mode.
456
457 -------------------------------------------------------
458 -- Control and Optimization of Range/Overflow Checks --
459 -------------------------------------------------------
460
461 -- Range checks are controlled by the Do_Range_Check flag. The front end
462 -- is responsible for setting this flag in relevant nodes. Originally the
463 -- back end generated all the corresponding range checks, but later on we
464 -- decided to generate all the range checks in the front end and this is
465 -- the current situation.
466
467 -- Overflow checks are similarly controlled by the Do_Overflow_Check flag.
468 -- The difference here is that if back end overflow checks are inactive
469 -- (Backend_Overflow_Checks_On_Target set False), then the actual overflow
470 -- checks are generated by the front end, but if back end overflow checks
471 -- are active (Backend_Overflow_Checks_On_Target set True), then the back
472 -- end does generate the checks.
473
474 -- The following two routines are used to set these flags, they allow
475 -- for the possibility of eliminating checks. Checks can be eliminated
476 -- if an identical check has already been performed.
477
478 procedure Enable_Overflow_Check (N : Node_Id);
479 -- First this routine determines if an overflow check is needed by doing
480 -- an appropriate range check. If a check is not needed, then the call
481 -- has no effect. If a check is needed then this routine sets the flag
482 -- Do_Overflow_Check in node N to True, unless it can be determined that
483 -- the check is not needed. The only condition under which this is the
484 -- case is if there was an identical check earlier on.
485
486 procedure Enable_Range_Check (N : Node_Id);
487 -- Set Do_Range_Check flag in node N True, unless it can be determined
488 -- that the check is not needed. The only condition under which this is
489 -- the case is if there was an identical check earlier on. This routine
490 -- is not responsible for doing range analysis to determine whether or
491 -- not such a check is needed -- the caller is expected to do this. The
492 -- one other case in which the request to set the flag is ignored is
493 -- when Kill_Range_Check is set in an N_Unchecked_Conversion node.
494
495 -- The following routines are used to keep track of processing sequences
496 -- of statements (e.g. the THEN statements of an IF statement). A check
497 -- that appears within such a sequence can eliminate an identical check
498 -- within this sequence of statements. However, after the end of the
499 -- sequence of statements, such a check is no longer of interest, since
500 -- it may not have been executed.
501
502 procedure Conditional_Statements_Begin;
503 -- This call marks the start of processing of a sequence of statements.
504 -- Every call to this procedure must be followed by a matching call to
505 -- Conditional_Statements_End.
506
507 procedure Conditional_Statements_End;
508 -- This call removes from consideration all saved checks since the
509 -- corresponding call to Conditional_Statements_Begin. These two
510 -- procedures operate in a stack like manner.
511
512 -- The mechanism for optimizing checks works by remembering checks
513 -- that have already been made, but certain conditions, for example
514 -- an assignment to a variable involved in a check, may mean that the
515 -- remembered check is no longer valid, in the sense that if the same
516 -- expression appears again, another check is required because the
517 -- value may have changed.
518
519 -- The following routines are used to note conditions which may render
520 -- some or all of the stored and remembered checks to be invalidated.
521
522 procedure Kill_Checks (V : Entity_Id);
523 -- This procedure records an assignment or other condition that causes
524 -- the value of the variable to be changed, invalidating any stored
525 -- checks that reference the value. Note that all such checks must
526 -- be discarded, even if they are not in the current statement range.
527
528 procedure Kill_All_Checks;
529 -- This procedure kills all remembered checks
530
531 -----------------------------
532 -- Length and Range Checks --
533 -----------------------------
534
535 -- In the following procedures, there are three arguments which have
536 -- a common meaning as follows:
537
538 -- Expr The expression to be checked. If a check is required,
539 -- the appropriate flag will be placed on this node. Whether
540 -- this node is further examined depends on the setting of
541 -- the parameter Source_Typ, as described below.
542
543 -- Target_Typ The target type on which the check is to be based. For
544 -- example, if we have a scalar range check, then the check
545 -- is that we are in range of this type.
546
547 -- Source_Typ Normally Empty, but can be set to a type, in which case
548 -- this type is used for the check, see below.
549
550 -- The checks operate in one of two modes:
551
552 -- If Source_Typ is Empty, then the node Expr is examined, at the very
553 -- least to get the source subtype. In addition for some of the checks,
554 -- the actual form of the node may be examined. For example, a node of
555 -- type Integer whose actual form is an Integer conversion from a type
556 -- with range 0 .. 3 can be determined to have a value in range 0 .. 3.
557
558 -- If Source_Typ is given, then nothing can be assumed about the Expr,
559 -- and indeed its contents are not examined. In this case the check is
560 -- based on the assumption that Expr can be an arbitrary value of the
561 -- given Source_Typ.
562
563 -- Currently, the only case in which a Source_Typ is explicitly supplied
564 -- is for the case of Out and In_Out parameters, where, for the conversion
565 -- on return (the Out direction), the types must be reversed. This is
566 -- handled by the caller.
567
568 procedure Apply_Length_Check
569 (Expr : Node_Id;
570 Target_Typ : Entity_Id;
571 Source_Typ : Entity_Id := Empty);
572 -- This procedure builds a sequence of declarations to do a length check
573 -- that checks if the lengths of the two arrays Target_Typ and source type
574 -- are the same. The resulting actions are inserted at Node using a call
575 -- to Insert_Actions.
576 --
577 -- For access types, the Directly_Designated_Type is retrieved and
578 -- processing continues as enumerated above, with a guard against null
579 -- values.
580 --
581 -- Note: calls to Apply_Length_Check currently never supply an explicit
582 -- Source_Typ parameter, but Apply_Length_Check takes this parameter and
583 -- processes it as described above for consistency with the other routines
584 -- in this section.
585
586 procedure Apply_Length_Check_On_Assignment
587 (Expr : Node_Id;
588 Target_Typ : Entity_Id;
589 Target : Node_Id;
590 Source_Typ : Entity_Id := Empty);
591 -- Similar to Apply_Length_Check, but takes the target of an assignment for
592 -- which the check is to be done. Used to filter out specific cases where
593 -- the check is superfluous.
594
595 procedure Apply_Static_Length_Check
596 (Expr : Node_Id;
597 Target_Typ : Entity_Id;
598 Source_Typ : Entity_Id := Empty);
599 -- Tries to determine statically whether the two array types source type
600 -- and Target_Typ have the same length. If it can be determined at compile
601 -- time that they do not, then an N_Raise_Constraint_Error node replaces
602 -- Expr, and a warning message is issued.
603
604 procedure Apply_Range_Check
605 (Expr : Node_Id;
606 Target_Typ : Entity_Id;
607 Source_Typ : Entity_Id := Empty;
608 Insert_Node : Node_Id := Empty);
609 -- For a Node of kind N_Range, constructs a range check action that tests
610 -- first that the range is not null and then that the range is contained in
611 -- the Target_Typ range.
612 --
613 -- For scalar types, constructs a range check action that first tests that
614 -- the expression is contained in the Target_Typ range. The difference
615 -- between this and Apply_Scalar_Range_Check is that the latter generates
616 -- the actual checking code against the Etype of the expression.
617 --
618 -- For constrained array types, construct series of range check actions
619 -- to check that each Expr range is properly contained in the range of
620 -- Target_Typ.
621 --
622 -- For a type conversion to an unconstrained array type, constructs a range
623 -- check action to check that the bounds of the source type are within the
624 -- constraints imposed by the Target_Typ.
625 --
626 -- For access types, the Directly_Designated_Type is retrieved and
627 -- processing continues as enumerated above, with a guard against null
628 -- values.
629 --
630 -- The source type is used by type conversions to unconstrained array
631 -- types to retrieve the corresponding bounds.
632
633 -- Insert_Node indicates the node where the check should be inserted.
634 -- If it is empty, then the check is inserted directly at Expr instead.
635
636 procedure Apply_Scalar_Range_Check
637 (Expr : Node_Id;
638 Target_Typ : Entity_Id;
639 Source_Typ : Entity_Id := Empty;
640 Fixed_Int : Boolean := False);
641 -- For scalar types, determines whether an expression node should be
642 -- flagged as needing a run-time range check. If the node requires such a
643 -- check, the Do_Range_Check flag is turned on. The Fixed_Int flag if set
644 -- causes any fixed-point values to be treated as though they were discrete
645 -- values (i.e. the underlying integer value is used).
646
647 type Check_Result is private;
648 -- Type used to return result of Get_Range_Checks call, for later use in
649 -- call to Insert_Range_Checks procedure.
650
651 function Get_Range_Checks
652 (Expr : Node_Id;
653 Target_Typ : Entity_Id;
654 Source_Typ : Entity_Id := Empty;
655 Warn_Node : Node_Id := Empty) return Check_Result;
656 -- Like Apply_Range_Check, except it does not modify anything. Instead
657 -- it returns an encapsulated result of the check operations for later
658 -- use in a call to Insert_Range_Checks. If Warn_Node is non-empty, its
659 -- Sloc is used, in the static case, for the generated warning or error.
660 -- Additionally, it is used rather than Expr (or Low/High_Bound of Expr)
661 -- in constructing the check.
662
663 procedure Append_Range_Checks
664 (Checks : Check_Result;
665 Stmts : List_Id;
666 Suppress_Typ : Entity_Id;
667 Static_Sloc : Source_Ptr);
668 -- Called to append range checks as returned by a call to Get_Range_Checks.
669 -- Stmts is a list to which either the dynamic check is appended or the
670 -- raise Constraint_Error statement is appended (for static checks).
671 -- Suppress_Typ is the type to check to determine if checks are suppressed.
672 -- Static_Sloc is the Sloc at which the raise CE node points.
673
674 procedure Insert_Range_Checks
675 (Checks : Check_Result;
676 Node : Node_Id;
677 Suppress_Typ : Entity_Id;
678 Static_Sloc : Source_Ptr;
679 Do_Before : Boolean := False);
680 -- Called to insert range checks as returned by a call to Get_Range_Checks.
681 -- Node is the node after which either the dynamic check is inserted or
682 -- the raise Constraint_Error statement is inserted (for static checks).
683 -- Suppress_Typ is the type to check to determine if checks are suppressed.
684 -- Static_Sloc is the Sloc at which the raise CE node points. Normally the
685 -- checks are inserted after Node; if Do_Before is True, they are before.
686
687 -----------------------
688 -- Expander Routines --
689 -----------------------
690
691 -- In most cases, the processing for range checks done by semantic analysis
692 -- only results in setting the Do_Range_Check flag, rather than actually
693 -- generating checks. The following routines must be called later on in the
694 -- expansion process upon seeing the Do_Range_Check flag; they generate the
695 -- actual checks and reset the flag. The remaining cases where range checks
696 -- are still directly generated during semantic analysis occur as part of
697 -- the processing of constraints in (sub)type and object declarations.
698
699 procedure Generate_Range_Check
700 (N : Node_Id;
701 Target_Type : Entity_Id;
702 Reason : RT_Exception_Code);
703 -- This procedure is called to actually generate and insert a range check.
704 -- A check is generated to ensure that the value of N lies within the range
705 -- of the target type. Note that the base type of N may be different from
706 -- the base type of the target type. This happens in the conversion case.
707 -- The Reason parameter is the exception code to be used for the exception
708 -- if raised.
709 --
710 -- Note: if the expander is not active, or if we are in GNATprove mode,
711 -- then we do not generate explicit range checks. Instead we just turn the
712 -- Do_Range_Check flag on, since in these cases that's what we want to see
713 -- in the tree (GNATprove in particular depends on this flag being set). If
714 -- we generate the actual range checks, then we make sure the flag is off
715 -- afterward, since the code we generate takes complete care of the checks.
716 --
717 -- Historical note: We used to just pass on the Do_Range_Check flag to the
718 -- back end to generate the check, but now in code-generation mode we never
719 -- have this flag set, since the front end takes care of the check. The
720 -- normal processing flow now is that the analyzer typically turns on the
721 -- Do_Range_Check flag, and if it is set, this routine is called, which
722 -- turns the flag off in code-generation mode.
723
724 procedure Generate_Index_Checks (N : Node_Id);
725 -- This procedure is called to generate index checks on the subscripts for
726 -- the indexed component node N. Each subscript expression is examined, and
727 -- if the Do_Range_Check flag is set, an appropriate index check is
728 -- generated and the flag is reset.
729
730 -- Similarly, we set the flag Do_Discriminant_Check in the semantic
731 -- analysis to indicate that a discriminant check is required for selected
732 -- component of a discriminated type. The following routine is called from
733 -- the expander to actually generate the call.
734
735 procedure Generate_Discriminant_Check (N : Node_Id);
736 -- N is a selected component for which a discriminant check is required to
737 -- make sure that the discriminants have appropriate values for the
738 -- selection. This is done by calling the appropriate discriminant checking
739 -- routine for the selector.
740
741 -----------------------
742 -- Validity Checking --
743 -----------------------
744
745 -- In (RM 13.9.1(9-11)) we have the following rules on invalid values
746
747 -- If the representation of a scalar object does not represent value of
748 -- the object's subtype (perhaps because the object was not initialized),
749 -- the object is said to have an invalid representation. It is a bounded
750 -- error to evaluate the value of such an object. If the error is
751 -- detected, either Constraint_Error or Program_Error is raised.
752 -- Otherwise, execution continues using the invalid representation. The
753 -- rules of the language outside this subclause assume that all objects
754 -- have valid representations. The semantics of operations on invalid
755 -- representations are as follows:
756 --
757 -- 10 If the representation of the object represents a value of the
758 -- object's type, the value of the type is used.
759 --
760 -- 11 If the representation of the object does not represent a value
761 -- of the object's type, the semantics of operations on such
762 -- representations is implementation-defined, but does not by
763 -- itself lead to erroneous or unpredictable execution, or to
764 -- other objects becoming abnormal.
765
766 -- We quote the rules in full here since they are quite delicate. Most
767 -- of the time, we can just compute away with wrong values, and get a
768 -- possibly wrong result, which is well within the range of allowed
769 -- implementation defined behavior. The two tricky cases are subscripted
770 -- array assignments, where we don't want to do wild stores, and case
771 -- statements where we don't want to do wild jumps.
772
773 -- In GNAT, we control validity checking with a switch -gnatV that can take
774 -- three parameters, n/d/f for None/Default/Full. These modes have the
775 -- following meanings:
776
777 -- None (no validity checking)
778
779 -- In this mode, there is no specific checking for invalid values
780 -- and the code generator assumes that all stored values are always
781 -- within the bounds of the object subtype. The consequences are as
782 -- follows:
783
784 -- For case statements, an out of range invalid value will cause
785 -- Constraint_Error to be raised, or an arbitrary one of the case
786 -- alternatives will be executed. Wild jumps cannot result even
787 -- in this mode, since we always do a range check
788
789 -- For subscripted array assignments, wild stores will result in
790 -- the expected manner when addresses are calculated using values
791 -- of subscripts that are out of range.
792
793 -- It could perhaps be argued that this mode is still conformant with
794 -- the letter of the RM, since implementation defined is a rather
795 -- broad category, but certainly it is not in the spirit of the
796 -- RM requirement, since wild stores certainly seem to be a case of
797 -- erroneous behavior.
798
799 -- Default (default standard RM-compatible validity checking)
800
801 -- In this mode, which is the default, minimal validity checking is
802 -- performed to ensure no erroneous behavior as follows:
803
804 -- For case statements, an out of range invalid value will cause
805 -- Constraint_Error to be raised.
806
807 -- For subscripted array assignments, invalid out of range
808 -- subscript values will cause Constraint_Error to be raised.
809
810 -- Full (Full validity checking)
811
812 -- In this mode, the protections guaranteed by the standard mode are
813 -- in place, and the following additional checks are made:
814
815 -- For every assignment, the right side is checked for validity
816
817 -- For every call, IN and IN OUT parameters are checked for validity
818
819 -- For every subscripted array reference, both for stores and loads,
820 -- all subscripts are checked for validity.
821
822 -- These checks are not required by the RM, but will in practice
823 -- improve the detection of uninitialized variables, particularly
824 -- if used in conjunction with pragma Normalize_Scalars.
825
826 -- In the above description, we talk about performing validity checks,
827 -- but we don't actually generate a check in a case where the compiler
828 -- can be sure that the value is valid. Note that this assurance must
829 -- be achieved without assuming that any uninitialized value lies within
830 -- the range of its type. The following are cases in which values are
831 -- known to be valid. The flag Is_Known_Valid is used to keep track of
832 -- some of these cases.
833
834 -- If all possible stored values are valid, then any uninitialized
835 -- value must be valid.
836
837 -- Literals, including enumeration literals, are clearly always valid
838
839 -- Constants are always assumed valid, with a validity check being
840 -- performed on the initializing value where necessary to ensure that
841 -- this is the case.
842
843 -- For variables, the status is set to known valid if there is an
844 -- initializing expression. Again a check is made on the initializing
845 -- value if necessary to ensure that this assumption is valid. The
846 -- status can change as a result of local assignments to a variable.
847 -- If a known valid value is unconditionally assigned, then we mark
848 -- the left side as known valid. If a value is assigned that is not
849 -- known to be valid, then we mark the left side as invalid. This
850 -- kind of processing does NOT apply to non-local variables since we
851 -- are not following the flow graph (more properly the flow of actual
852 -- processing only corresponds to the flow graph for local assignments).
853 -- For non-local variables, we preserve the current setting, i.e. a
854 -- validity check is performed when assigning to a known valid global.
855
856 -- Note: no validity checking is required if range checks are suppressed
857 -- regardless of the setting of the validity checking mode.
858
859 -- The following procedures are used in handling validity checking
860
861 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id);
862 -- Expr is the node for an indexed component. If validity checking and
863 -- range checking are enabled, all subscripts for this indexed component
864 -- are checked for validity.
865
866 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id);
867 -- Expr is a lvalue, i.e. an expression representing the target of an
868 -- assignment. This procedure checks for this expression involving an
869 -- assignment to an array value. We have to be sure that all the subscripts
870 -- in such a case are valid, since according to the rules in (RM
871 -- 13.9.1(9-11)) such assignments are not permitted to result in erroneous
872 -- behavior in the case of invalid subscript values.
873
874 procedure Ensure_Valid
875 (Expr : Node_Id;
876 Holes_OK : Boolean := False;
877 Related_Id : Entity_Id := Empty;
878 Is_Low_Bound : Boolean := False;
879 Is_High_Bound : Boolean := False);
880 -- Ensure that Expr represents a valid value of its type. If this type
881 -- is not a scalar type, then the call has no effect, since validity
882 -- is only an issue for scalar types. The effect of this call is to
883 -- check if the value is known valid, if so, nothing needs to be done.
884 -- If this is not known, then either Expr is set to be range checked,
885 -- or specific checking code is inserted so that an exception is raised
886 -- if the value is not valid.
887 --
888 -- The optional argument Holes_OK indicates whether it is necessary to
889 -- worry about enumeration types with non-standard representations leading
890 -- to "holes" in the range of possible representations. If Holes_OK is
891 -- True, then such values are assumed valid (this is used when the caller
892 -- will make a separate check for this case anyway). If Holes_OK is False,
893 -- then this case is checked, and code is inserted to ensure that Expr is
894 -- valid, raising Constraint_Error if the value is not valid.
895 --
896 -- Related_Id denotes the entity of the context where Expr appears. Flags
897 -- Is_Low_Bound and Is_High_Bound specify whether the expression to check
898 -- is the low or the high bound of a range. These three optional arguments
899 -- signal Remove_Side_Effects to create an external symbol of the form
900 -- Chars (Related_Id)_FIRST/_LAST. For suggested use of these parameters
901 -- see the warning in the body of Sem_Ch3.Process_Range_Expr_In_Decl.
902
903 function Expr_Known_Valid (Expr : Node_Id) return Boolean;
904 -- This function tests it the value of Expr is known to be valid in the
905 -- sense of RM 13.9.1(9-11). In the case of GNAT, it is only discrete types
906 -- which are a concern, since for non-discrete types we simply continue
907 -- computation with invalid values, which does not lead to erroneous
908 -- behavior. Thus Expr_Known_Valid always returns True if the type of Expr
909 -- is non-discrete. For discrete types the value returned is True only if
910 -- it can be determined that the value is Valid. Otherwise False is
911 -- returned.
912
913 procedure Insert_Valid_Check
914 (Expr : Node_Id;
915 Related_Id : Entity_Id := Empty;
916 Is_Low_Bound : Boolean := False;
917 Is_High_Bound : Boolean := False);
918 -- Inserts code that will check for the value of Expr being valid, in the
919 -- sense of the 'Valid attribute returning True. Constraint_Error will be
920 -- raised if the value is not valid.
921 --
922 -- Related_Id denotes the entity of the context where Expr appears. Flags
923 -- Is_Low_Bound and Is_High_Bound specify whether the expression to check
924 -- is the low or the high bound of a range. These three optional arguments
925 -- signal Remove_Side_Effects to create an external symbol of the form
926 -- Chars (Related_Id)_FIRST/_LAST. For suggested use of these parameters
927 -- see the warning in the body of Sem_Ch3.Process_Range_Expr_In_Decl.
928
929 procedure Null_Exclusion_Static_Checks
930 (N : Node_Id;
931 Comp : Node_Id := Empty;
932 Array_Comp : Boolean := False);
933 -- Ada 2005 (AI-231): Test for and warn on null-excluding objects or
934 -- components that will raise an exception due to initialization by null.
935 --
936 -- When a value for Comp is supplied (as in the case of an uninitialized
937 -- null-excluding component within a composite object), a reported warning
938 -- will indicate the offending component instead of the object itself.
939 -- Array_Comp being True indicates an array object with null-excluding
940 -- components, and any reported warning will indicate that.
941
942 procedure Remove_Checks (Expr : Node_Id);
943 -- Remove all checks from Expr except those that are only executed
944 -- conditionally (on the right side of And Then/Or Else. This call
945 -- removes only embedded checks (Do_Range_Check, Do_Overflow_Check).
946
947 procedure Validity_Check_Range
948 (N : Node_Id;
949 Related_Id : Entity_Id := Empty);
950 -- If N is an N_Range node, then Ensure_Valid is called on its bounds, if
951 -- validity checking of operands is enabled. Related_Id denotes the entity
952 -- of the context where N appears.
953
954 -----------------------------
955 -- Handling of Check Names --
956 -----------------------------
957
958 -- The following table contains Name_Id's for recognized checks. The first
959 -- entries (corresponding to the values of the subtype Predefined_Check_Id)
960 -- contain the Name_Id values for the checks that are predefined, including
961 -- All_Checks (see Types). Remaining entries are those that are introduced
962 -- by pragma Check_Names.
963
964 package Check_Names is new Table.Table (
965 Table_Component_Type => Name_Id,
966 Table_Index_Type => Check_Id,
967 Table_Low_Bound => 1,
968 Table_Initial => 30,
969 Table_Increment => 200,
970 Table_Name => "Name_Check_Names");
971
972 function Get_Check_Id (N : Name_Id) return Check_Id;
973 -- Function to search above table for matching name. If found returns the
974 -- corresponding Check_Id value in the range 1 .. Check_Name.Last. If not
975 -- found returns No_Check_Id.
976
977 private
978
979 type Check_Result is array (Positive range 1 .. 2) of Node_Id;
980 -- There are two cases for the result returned by Range_Check:
981 --
982 -- For the static case the result is one or two nodes that should cause
983 -- a Constraint_Error. Typically these will include Expr itself or the
984 -- direct descendants of Expr, such as Low/High_Bound (Expr)). It is the
985 -- responsibility of the caller to rewrite and substitute the nodes with
986 -- N_Raise_Constraint_Error nodes.
987 --
988 -- For the non-static case a single N_Raise_Constraint_Error node with a
989 -- non-empty Condition field is returned.
990 --
991 -- Unused entries in Check_Result, if any, are simply set to Empty For
992 -- external clients, the required processing on this result is achieved
993 -- using the Insert_Range_Checks routine.
994
995 pragma Inline (Apply_Length_Check);
996 pragma Inline (Apply_Range_Check);
997 pragma Inline (Apply_Static_Length_Check);
998 end Checks;