Debian Codegraph @

rpython/jit/metainterp/optimizeopt/intutils.py

raw symbols SCIP
1 """
2 This file contains an abstract domain IntBound for word-sized integers. This is
3 used to perform abstract interpretation on traces, specifically the integer
4 operations on them.
5
6 The abstract domain tracks a (signed) upper and lower bound (both ends
7 inclusive) for every integer variable in the trace. It also tracks which bits
8 of a range are known 0 or known 1 (the remaining bits are unknown. The ranges
9 and the known bits feed back into each other, ie we can improve the range if
10 some upper bits have known values, and we can learn some known bits from the
11 range too. Every instance of IntBound represents a set of concrete integers.
12
13 We do the analysis at the same time as optimization. We initialize all integer
14 variables to have an unknown range, with no known bits. Then we proceed along
15 the trace and improve the ranges. We can shrink ranges if we see integer
16 comparisons followed by guards. We can learn some bits of an integer if there
17 are bit-operations such as `and` (masking out some bits), followed by a guard.
18
19 For every operation in the trace we use a "transfer function" that computes an
20 IntBound instance for the result of that operation, given the IntBounds of the
21 arguments. Those functions are called `..._bound`, eg `add_bound`, `and_bound`,
22 `neg_bound`, etc. Applying the transfer functions while we encounter them along
23 the trace is forwards reasoning.
24
25 We can also reason backwards (but we only do that in a limited way). Here's an
26 example:
27
28 i1 = int_add(i0, 1)
29 i2 = int_lt(i1, 100)
30 guard_true(i2)
31
32 At the last guard we learn that i1 < 100 must be true, and from that we can
33 conclude that i0 < 99 in the rest of the trace (this is not quite true due to
34 possible overflow of the int_add).
35
36 More generally, when we shrink (ie make more precise) an IntBound instance due
37 to a guard, we can often conclude something about earlier variables in the
38 trace. To reason backwards we look at the operation that created a variable and
39 then compute the implications.
40
41 The reason for having both a range and known bits are that each of them is good
42 for different situations. Range knownledge is useful for comparisons and
43 "linear" operations like additions, subtractions, multiplications, etc.
44 Knowledge about certain bits is good for bit twiddling code, bitfields, stuff
45 like that.
46 """
47
48 import sys
49 from rpython.rlib.rarithmetic import ovfcheck, LONG_BIT, maxint, is_valid_int, r_uint, intmask
50 from rpython.rlib.objectmodel import we_are_translated, always_inline
51 from rpython.rtyper.lltypesystem import lltype
52 from rpython.rtyper.lltypesystem.lloperation import llop
53 from rpython.jit.metainterp.resoperation import rop, ResOperation
54 from rpython.jit.metainterp.optimize import InvalidLoop
55 from rpython.jit.metainterp.optimizeopt.info import AbstractInfo, INFO_NONNULL,\
56 INFO_UNKNOWN, INFO_NULL
57 from rpython.jit.metainterp.history import ConstInt
58
59
60 MAXINT = maxint
61 MININT = -maxint - 1
62
63 IS_64_BIT = sys.maxint > 2**32
64
65 TNUM_UNKNOWN = r_uint(0), r_uint(-1)
66 TNUM_KNOWN_ZERO = r_uint(0), r_uint(0)
67 TNUM_KNOWN_BITWISEONE = r_uint(-1), r_uint(0)
68 TNUM_ONLY_VALUE_DEFAULT = r_uint(0)
69 TNUM_ONLY_MASK_UNKNOWN = r_uint(-1)
70 TNUM_ONLY_MASK_DEFAULT = TNUM_ONLY_MASK_UNKNOWN
71
72
73 class IntBound(AbstractInfo):
74 """
75 Abstract domain representation of an integer,
76 approximating via integer bounds and known-bits
77 tri-state numbers.
78 """
79 _attrs_ = ('upper', 'lower', 'tvalue', 'tmask')
80
81 def __init__(self, lower=MININT, upper=MAXINT,
82 tvalue=TNUM_ONLY_VALUE_DEFAULT,
83 tmask=TNUM_ONLY_MASK_DEFAULT,
84 do_shrinking=True):
85 """
86 Instantiates an abstract representation of integer.
87 The default parameters set this abstract int to
88 contain all integers.
89
90 It is recommended to use the indirect constructors
91 below instead of this one.
92 """
93
94 self.lower = lower
95 self.upper = upper
96
97 # known-bit analysis using tristate/knownbits numbers:
98 # every bit can be either 0, 1, or unknown (?).
99 # the encoding of these three states is:
100 # value 0 1 ?
101 # tvalue bit 0 1 0
102 # tmask bit 0 0 1
103 # the combination tvalue=tmask=1 is forbidden
104 assert is_valid_tnum(tvalue, tmask)
105 self.tvalue = tvalue
106 self.tmask = tmask # bit=1 means unknown
107
108 # check for unexpected overflows:
109 if not we_are_translated():
110 assert type(upper) is not long or is_valid_int(upper)
111 assert type(lower) is not long or is_valid_int(lower)
112
113 if do_shrinking:
114 self.shrink()
115 assert self._debug_check()
116
117 @staticmethod
118 def from_constant(value):
119 """
120 Constructs an abstract integer that represents a constant (a completely
121 known integer).
122 """
123 # this one does NOT require a r_uint for `value`.
124 assert not isinstance(value, r_uint)
125 tvalue = value
126 tmask = 0
127 bvalue = value
128 do_shrinking = False
129 if not isinstance(value, int):
130 # workaround for AddressAsInt / symbolic ints
131 # by CF
132 tvalue = 0
133 tmask = -1
134 bvalue = 0
135 do_shrinking = True
136 b = IntBound(lower=bvalue,
137 upper=bvalue,
138 tvalue=r_uint(tvalue),
139 tmask=r_uint(tmask), do_shrinking=do_shrinking)
140 return b
141
142 @staticmethod
143 def unbounded():
144 """
145 Constructs an abstract integer that is completely unknown (e.g. it
146 contains every integer).
147 """
148 return IntBound(do_shrinking=False)
149
150 @staticmethod
151 def nonnegative():
152 """
153 Construct a non-negative abstract integer.
154 """
155 return IntBound(lower=0)
156
157 @staticmethod
158 def from_knownbits(tvalue, tmask, do_unmask=False):
159 """
160 Constructs an abstract integer where the bits determined by `tvalue`
161 and `tmask` are (un-)known. tvalue and tmask must be r_uints.
162 """
163 assert isinstance(tvalue, r_uint) and isinstance(tmask, r_uint)
164 if do_unmask:
165 tvalue = unmask_zero(tvalue, tmask)
166 return IntBound(tvalue=tvalue,
167 tmask=tmask)
168
169 # ____________________________________________________________
170 # a bunch of slightly artificial methods that are needed to make some of
171 # the Z3 proofs in test_z3intbound possible, they are overridden there
172
173 @staticmethod
174 @always_inline
175 def new(lower, upper, tvalue, tmask):
176 """ helper factory to construct a new IntBound. overridden in
177 test_z3intbound """
178 return IntBound(lower, upper, tvalue, tmask)
179
180 intmask = staticmethod(intmask)
181 r_uint = staticmethod(r_uint)
182
183 @staticmethod
184 @always_inline
185 def _add_check_overflow(a, b, value_if_overflow):
186 """ returns a + b, or value_if_overflow if that (signed) addition would
187 overflow """
188 try:
189 return ovfcheck(a + b)
190 except OverflowError:
191 return value_if_overflow
192
193 @staticmethod
194 @always_inline
195 def _sub_check_overflow(a, b, value_if_overflow):
196 """ returns a - b, or value_if_overflow if that (signed) subtraction would
197 overflow """
198 try:
199 return ovfcheck(a - b)
200 except OverflowError:
201 return value_if_overflow
202
203 @staticmethod
204 @always_inline
205 def _urshift(a, b):
206 return r_uint(a) >> r_uint(b)
207
208 # ____________________________________________________________
209
210 @staticmethod
211 def _to_dec_or_hex_str_heuristics(num):
212 # a few formatting heuristics
213 if -1000 <= num <= 1000:
214 return str(num)
215 if num == MININT:
216 return "MININT"
217 if num == MAXINT:
218 return "MAXINT"
219 if num >= 0:
220 diff = MAXINT - num
221 if diff < 1000:
222 return "MAXINT - %s" % diff
223 else:
224 diff = -(MININT - num) # can't overflow because num < 0
225 if diff < 1000:
226 return "MININT + %s" % diff
227 uintnum = r_uint(num)
228 if uintnum & (uintnum - 1) == 0:
229 # power of two, use hex
230 return hex(num)
231 # format number as decimal if fewer than 6 significant
232 # digits, otherwise use hex
233 curr = num
234 exp10 = 0
235 while curr % 10 == 0:
236 curr //= 10
237 exp10 += 1
238 s = str(num)
239 if len(s) - exp10 >= 6:
240 return hex(num)
241 return s
242
243 def _are_knownbits_implied(self):
244 """ return True if the knownbits of self are a direct consequence of
245 the range of self (and thus carry no extra information) """
246 tvalue, tmask = self._tnum_implied_by_bounds()
247 return self.tmask == tmask and self.tvalue == tvalue
248
249 def _are_bounds_implied(self):
250 """ return True if the bounds of self are a direct consequence of the
251 knownbits of self (and thus carry no extra information) """
252 lower = self._get_minimum_signed_by_knownbits()
253 upper = self._get_maximum_signed_by_knownbits()
254 return self.lower == lower and self.upper == upper
255
256 def __repr__(self):
257 if self.is_unbounded():
258 return "IntBound.unbounded()"
259 if self.lower == 0 and self.upper == MAXINT and self._are_knownbits_implied():
260 return "IntBound.nonnegative()"
261 if self.is_constant():
262 return "IntBound.from_constant(%s)" % self._to_dec_or_hex_str_heuristics(self.get_constant_int())
263 s_bounds = "%s, %s" % (self._to_dec_or_hex_str_heuristics(self.lower),
264 self._to_dec_or_hex_str_heuristics(self.upper))
265
266 if self._are_knownbits_implied():
267 return "IntBound(%s)" % s_bounds
268
269 s_tnum = "r_uint(%s), r_uint(%s)" % (bin(intmask(self.tvalue)), bin(intmask(self.tmask)))
270 if self._are_bounds_implied():
271 return "IntBound.from_knownbits(%s)" % s_tnum
272 return "IntBound(%s, %s)" % (s_bounds, s_tnum)
273
274 def __str__(self):
275 if self.is_constant():
276 return '(%s)' % self._to_dec_or_hex_str_heuristics(self.get_constant_int())
277 if self.lower == 0 and self.upper == 1:
278 return '(bool)'
279 if self.lower == MININT:
280 lower = ''
281 else:
282 lower = '%s <= ' % self._to_dec_or_hex_str_heuristics(self.lower)
283 if self.upper == MAXINT:
284 upper = ''
285 else:
286 upper = ' <= %s' % self._to_dec_or_hex_str_heuristics(self.upper)
287 s = self.knownbits_string()
288 if "0" not in s and "1" not in s:
289 s = '?'
290 else:
291 # replace the longest sequence of same characters by ...
292 prev_char = s[0]
293 count = 0
294 max_length = 0
295 max_char = '\x00'
296 start_pos = 0
297 max_pos = -1
298 for pos, char in enumerate(s):
299 if char == prev_char:
300 count += 1
301 else:
302 if count > max_length:
303 max_length = count
304 max_char = prev_char
305 max_pos = start_pos
306 prev_char = char
307 count = 1
308 start_pos = pos
309 if count > max_length:
310 max_length = count
311 max_char = prev_char
312 max_pos = start_pos
313 if max_length > 5:
314 assert max_pos >= 0
315 s = s[:max_pos] + max_char + "..." + max_char + s[max_pos + max_length:]
316 s = '0b' + s
317 return '(%s%s%s)' % (lower, s, upper)
318
319 def set_tvalue_tmask(self, tvalue, tmask):
320 changed = self.tvalue != tvalue or self.tmask != tmask
321 if changed:
322 self.tvalue = tvalue
323 self.tmask = tmask
324 self.shrink()
325 return changed
326
327 def make_le(self, other):
328 """
329 Sets the bounds of `self` so that it only contains values lower than or
330 equal to the values contained in `other`. Returns `True` iff the bound
331 was updated. Will raise InvalidLoop if the resulting interval is empty.
332 Mutates `self`.
333 """
334 return self.make_le_const(other.upper)
335
336 def make_le_const(self, value):
337 """
338 Sets the bounds of `self` so that it only contains values lower than or
339 equal to `value`. Returns `True` iff the bound was updated. Will raise
340 InvalidLoop if the resulting interval is empty.
341 Mutates `self`.
342 """
343 if value < self.upper:
344 if value < self.lower:
345 raise InvalidLoop
346 self.upper = value
347 self.shrink()
348 return True
349 return False
350
351 def make_lt(self, other):
352 """
353 Sets the bounds of `self` so that it only contains values lower than
354 the values contained in `other`. Returns `True` iff the bound was
355 updated. Will raise InvalidLoop if the resulting interval is empty.
356 (Mutates `self`.)
357 """
358 return self.make_lt_const(other.upper)
359
360 def make_lt_const(self, value):
361 """
362 Sets the bounds of `self` so that it only contains values lower than
363 `value`. Returns `True` iff the bound was updated. Will raise
364 InvalidLoop if the resulting interval is empty. (Mutates `self`.)
365 """
366 if value == MININT:
367 raise InvalidLoop("intbound can't be made smaller than MININT")
368 return self.make_le_const(value - 1)
369
370 def make_ge(self, other):
371 """
372 Sets the bounds of `self` so that it only contains values greater than
373 or equal to the values contained in `other`. Returns `True` iff the
374 bound was updated. Will raise InvalidLoop if the resulting interval is
375 empty. (Mutates `self`.)
376 """
377 return self.make_ge_const(other.lower)
378
379 def make_ge_const(self, value):
380 """
381 Sets the bounds of `self` so that it only contains values greater than
382 or equal to `value`. Returns `True` iff the bound was updated. Will
383 raise InvalidLoop if the resulting interval is empty. (Mutates `self`.)
384 """
385 if value > self.lower:
386 if value > self.upper:
387 raise InvalidLoop
388 self.lower = value
389 self.shrink()
390 return True
391 return False
392
393 def make_gt(self, other):
394 """
395 Sets the bounds of `self` so that it only contains values greater than
396 the values contained in `other`. Returns `True` iff the bound was
397 updated. Will raise InvalidLoop if the resulting interval is empty.
398 (Mutates `self`.)
399 """
400 return self.make_gt_const(other.lower)
401
402 def make_gt_const(self, value):
403 """
404 Sets the bounds of `self` so that it only contains values greater than
405 `value`. Returns `True` iff the bound was updated. Will raise
406 InvalidLoop if the resulting interval is empty. (Mutates `self`.)
407 """
408 if value == MAXINT:
409 raise InvalidLoop
410 return self.make_ge_const(value + 1)
411
412 def make_eq_const(self, intval):
413 """
414 Sets the properties of this abstract integer
415 so that it is constant and equals `intval`.
416 (Mutates `self`.)
417 """
418 if not self.contains(intval):
419 raise InvalidLoop("constant int is outside of interval")
420 self.upper = intval
421 self.lower = intval
422 self.tvalue = r_uint(intval)
423 self.tmask = r_uint(0)
424
425 def make_ne_const(self, intval):
426 if self.lower < intval == self.upper:
427 self.upper -= 1
428 self.shrink()
429 return True
430 if self.lower == intval < self.upper:
431 self.lower += 1
432 self.shrink()
433 return True
434 return False
435
436 def is_constant(self):
437 """
438 Returns `True` iff this abstract integer
439 does contain only one concrete integer.
440 """
441 # both the bounds and the tnum encode the concrete integer
442 res = self.lower == self.upper
443 assert res == (self.tmask == r_uint(0))
444 if res:
445 assert self.lower == intmask(self.tvalue)
446 return res
447
448 def get_constant_int(self):
449 """
450 Returns the only integer contained in this abstract integer. Caller
451 needs to check that `.is_constant()` returns True, before calling.
452 """
453 assert self.is_constant()
454 return self.lower
455
456 def known_eq_const(self, value):
457 """
458 Returns `True` iff this abstract integer contains only one (1) integer
459 that does equal `value`.
460 """
461 if not self.is_constant():
462 return False
463 else:
464 return self.lower == value
465
466 def known_lt_const(self, value):
467 """
468 Returns `True` iff each number contained in this abstract integer is
469 lower than `value`.
470 """
471 return self.upper < value
472
473 def known_le_const(self, value):
474 """
475 Returns `True` iff each number contained in this abstract integer is
476 lower than or equal to `value`.
477 """
478 return self.upper <= value
479
480 def known_gt_const(self, value):
481 """
482 Returns `True` iff each number contained in this abstract integer is
483 greater than `value`.
484 """
485 return self.lower > value
486
487 def known_ge_const(self, value):
488 """
489 Returns `True` iff each number contained in this abstract integer is
490 greater than equal to `value`.
491 """
492 return self.lower >= value
493
494 def known_lt(self, other):
495 """
496 Returns `True` iff each number contained in this abstract integer is
497 lower than each integer contained in `other`.
498 """
499 return self.known_lt_const(other.lower)
500
501 def known_le(self, other):
502 """
503 Returns `True` iff each number contained in this abstract integer is
504 lower than or equal to each integer contained in `other`.
505 """
506 return self.known_le_const(other.lower)
507
508 def known_gt(self, other):
509 """
510 Returns `True` iff each number contained in this abstract integer is
511 greater than each integer contained in `other`.
512 """
513 return other.known_lt(self)
514
515 def known_ge(self, other):
516 """
517 Returns `True` iff each number contained in this abstract integer is
518 greater than or equal to each integer contained in `other`.
519 """
520 return other.known_le(self)
521
522 def known_ne(self, other):
523 """ return True if the sets of numbers self and other must be disjoint.
524 """
525 # easy cases part 1: ranges don't overlap
526 if self.known_lt(other):
527 return True
528 if self.known_gt(other):
529 return True
530 # easy case part 2: check whether the knownbits contradict
531 both_known = self.tmask | other.tmask
532 if unmask_zero(self.tvalue, both_known) != unmask_zero(other.tvalue, both_known):
533 return True
534 # for more complicated interactions between ranges and knownbits use
535 # the logic in intersect
536 newself = self.clone()
537 try:
538 newself.intersect(other)
539 except InvalidLoop:
540 return True
541 return False
542
543 def known_nonnegative(self):
544 """
545 Returns `True` if this abstract integer only contains numbers greater
546 than or equal to `0` (zero).
547 """
548 return 0 <= self.lower
549
550 def make_unsigned_le(self, other):
551 if other.known_nonnegative():
552 return self.intersect_const(0, other.upper)
553 return False
554
555 def make_unsigned_lt(self, other):
556 if other.known_nonnegative():
557 assert other.upper >= 0
558 if other.upper == 0:
559 raise InvalidLoop
560 return self.intersect_const(0, other.upper - 1)
561 return False
562
563 def make_unsigned_ge(self, other):
564 if other.upper < 0:
565 changed = self.make_lt_const(0)
566 return self.make_ge(other) or changed
567 if self.known_nonnegative() and other.known_nonnegative():
568 return self.make_ge(other)
569 return False
570
571 def make_unsigned_gt(self, other):
572 if other.upper < 0:
573 changed = self.make_lt_const(0)
574 return self.make_gt(other) or changed
575 if self.known_nonnegative() and other.known_nonnegative():
576 return self.make_gt(other)
577 return False
578
579 def _known_same_sign(self, other):
580 # return True if self and other are both either known non-negative or
581 # both known negative
582 if self.known_nonnegative() and other.known_nonnegative():
583 return True
584 return self.known_lt_const(0) and other.known_lt_const(0)
585
586 def known_unsigned_lt(self, other):
587 """
588 Returns `True` iff each unsigned integer contained in this abstract
589 integer is lower than each unsigned integer contained in `other`.
590 """
591 # if they have the same sign, we can reason with signed comparison
592 # see test_uint_cmp_equivalent_int_cmp_if_same_sign
593 if self._known_same_sign(other) and self.known_lt(other):
594 return True
595 other_min_unsigned_by_knownbits = other.get_minimum_unsigned_by_knownbits()
596 self_max_unsigned_by_knownbits = self.get_maximum_unsigned_by_knownbits()
597 return self_max_unsigned_by_knownbits < other_min_unsigned_by_knownbits
598
599 def known_unsigned_le(self, other):
600 """
601 Returns `True` iff each unsigned integer contained in this abstract
602 integer is lower or equal than each unsigned integer contained in
603 `other`. """
604 # if they have the same sign, we can reason with signed comparison
605 if self._known_same_sign(other) and self.known_le(other):
606 return True
607 other_min_unsigned_by_knownbits = other.get_minimum_unsigned_by_knownbits()
608 self_max_unsigned_by_knownbits = self.get_maximum_unsigned_by_knownbits()
609 return self_max_unsigned_by_knownbits <= other_min_unsigned_by_knownbits
610
611 def known_unsigned_gt(self, other):
612 """
613 Returns `True` iff each unsigned integer contained in this abstract
614 integer is greater than each unsigned integer contained in `other`.
615 """
616 return other.known_unsigned_lt(self)
617
618 def known_unsigned_ge(self, other):
619 """
620 Returns `True` iff each unsigned integer contained in this abstract
621 integer is greater or equal than each unsigned integer contained in
622 `other`.
623 """
624 return other.known_unsigned_le(self)
625
626 def get_minimum_unsigned_by_knownbits(self):
627 """
628 Returns the minimum unsigned number, but only using the knownbits as
629 information."""
630 return unmask_zero(self.tvalue, self.tmask)
631
632 def get_maximum_unsigned_by_knownbits(self):
633 """
634 returns the maximum unsigned number, but only using the knownbits as
635 information."""
636 return unmask_one(self.tvalue, self.tmask)
637
638 def _get_minimum_signed_by_knownbits(self):
639 """ for internal use only!
640 returns the minimum signed number, but only using the knownbits as
641 information."""
642 return self.intmask(self.tvalue | msbonly(self.tmask))
643
644 def _get_maximum_signed_by_knownbits(self):
645 """ for internal use only!
646 returns the maximum signed number, but only using the knownbits as
647 information."""
648 unsigned_mask = self.tmask & ~msbonly(self.tmask)
649 return self.intmask(self.tvalue | unsigned_mask)
650
651 def _get_minimum_signed_by_knownbits_atleast(self, threshold=MININT):
652 """ for internal use only!
653 return the smallest number permitted by the known bits that is above
654 (or equal) threshold. will raise InvalidLoop if no such number exists.
655 """
656 if self._get_maximum_signed_by_knownbits() < threshold:
657 raise InvalidLoop("threshold and knownbits don't overlap")
658 min_by_knownbits = self._get_minimum_signed_by_knownbits()
659 if min_by_knownbits > self.upper:
660 raise InvalidLoop("range and knownbits don't overlap")
661 if min_by_knownbits >= threshold:
662 return min_by_knownbits
663 # see "Sharpening Constraint Programming
664 # approaches for Bit-Vector Theory"
665 u_min_threshold = r_uint(threshold)
666 # create our working value, the to-be minimum
667 working_min, cl2set, set2cl = self._helper_min_max_prepare(u_min_threshold)
668 if working_min == u_min_threshold:
669 return threshold
670 elif cl2set > set2cl:
671 return self._helper_min_case1(working_min, cl2set)
672 else:
673 return self._helper_min_case2(working_min, set2cl)
674
675 @always_inline
676 def _helper_min_max_prepare(self, u_threshold):
677 working_value = u_threshold # start at given threshold
678 working_value &= unmask_one(self.tvalue, self.tmask) # clear known 0s
679 working_value |= self.tvalue # set known 1s
680 # inspect changed bits
681 cl2set = ~u_threshold & working_value
682 set2cl = u_threshold & ~working_value
683 return working_value, cl2set, set2cl
684
685 @always_inline
686 def _helper_min_case1(self, working_min, cl2set):
687 # we have set the correct bit already
688 clear_mask = leading_zeros_mask(self._urshift(cl2set, 1))
689 working_min &= clear_mask | ~self.tmask
690 return self.intmask(working_min)
691
692 @always_inline
693 def _helper_min_case2(self, working_min, set2cl):
694 # flip the sign bit to handle -1 -> 0 overflow
695 working_min = flip_msb(working_min)
696 # we have to find the proper bit to set...
697 possible_bits = ~working_min \
698 & self.tmask \
699 & leading_zeros_mask(set2cl)
700 bit_to_set = lowest_set_bit_only(possible_bits)
701 working_min |= bit_to_set
702 # and clear all lower than that
703 clear_mask = leading_zeros_mask(bit_to_set) \
704 | bit_to_set | ~self.tmask
705 working_min &= clear_mask
706 return self.intmask(flip_msb(working_min))
707
708 def _get_maximum_signed_by_knownbits_atmost(self, threshold=MAXINT):
709 """ for internal use only!
710 return the largest number permitted by the known bits that is below or
711 equal to threshold. will raise InvalidLoop if no such number exists.
712 """
713 if self._get_minimum_signed_by_knownbits() > threshold:
714 raise InvalidLoop("threshold and knownbits don't overlap")
715 max_by_knownbits = self._get_maximum_signed_by_knownbits()
716 if max_by_knownbits < self.lower:
717 raise InvalidLoop("range and knownbits don't overlap")
718 if max_by_knownbits <= threshold:
719 return max_by_knownbits
720 # see "Sharpening Constraint Programming
721 # approaches for Bit-Vector Theory"
722 u_max_threshold = r_uint(threshold)
723 # now create our working value, the to-be maximum
724 working_max, cl2set, set2cl = self._helper_min_max_prepare(u_max_threshold)
725 if working_max == u_max_threshold:
726 return threshold
727 elif cl2set < set2cl:
728 # we have cleared the right bit already
729 result = self._helper_max_case1(working_max, set2cl)
730 else:
731 result = self._helper_max_case2(working_max, cl2set)
732 assert result <= threshold
733 return result
734
735 def _helper_max_case1(self, working_max, set2cl):
736 # we have cleared the right bit already
737 set_mask = next_pow2_m1(self._urshift(set2cl, 1)) & self.tmask
738 working_max |= set_mask
739 return self.intmask(working_max)
740
741 def _helper_max_case2(self, working_max, cl2set):
742 # flip the sign bit to handle 1 -> 0 overflow
743 working_max = flip_msb(working_max)
744 # find the right bit to clear
745 possible_bits = working_max \
746 & self.tmask \
747 & leading_zeros_mask(cl2set)
748 bit_to_clear = lowest_set_bit_only(possible_bits)
749 working_max &= ~bit_to_clear
750 # and set all lower than that
751 set_mask = next_pow2_m1(self._urshift(bit_to_clear, 1)) & self.tmask
752 working_max |= set_mask
753 return self.intmask(flip_msb(working_max))
754
755
756 def _get_minimum_signed(self):
757 """ for tests only """
758 ret_b = self.lower
759 result = self._get_minimum_signed_by_knownbits_atleast(ret_b)
760 assert isinstance(result, int)
761 return result
762
763 def _get_maximum_signed(self):
764 """ for tests only """
765 ret_b = self.upper
766 result = self._get_maximum_signed_by_knownbits_atmost(ret_b)
767 assert isinstance(result, int)
768 return result
769
770 def intersect(self, other):
771 """
772 Mutates `self` so that it contains integers that are contained in
773 `self` and `other`, and only those. Basically intersection of sets.
774 Throws InvalidLoop if `self` and `other` "disagree", meaning the result
775 would not contain any integers.
776 """
777 if self.known_gt(other) or self.known_lt(other):
778 # they don't overlap, which makes the loop invalid
779 # this never happens in regular linear traces, but it can happen in
780 # combination with unrolling/loop peeling
781 raise InvalidLoop("two integer ranges don't overlap")
782
783 r = self.intersect_const(other.lower, other.upper, do_shrinking=False)
784
785 tvalue, tmask, valid = self._tnum_intersect(other.tvalue, other.tmask)
786 if not valid:
787 raise InvalidLoop("knownbits contradict each other")
788 # calculate intersect value and mask
789 if self.tmask != tmask:
790 # this can also raise InvalidLoop, if the ranges and knownbits
791 # contradict in more complicated ways
792 r = self.set_tvalue_tmask(tvalue, tmask) # this shrinks
793 assert r
794 elif r:
795 # we didn't shrink yet
796 self.shrink()
797 assert self._debug_check()
798 return r
799
800 @always_inline
801 def _tnum_intersect(self, other_tvalue, other_tmask):
802 union_val = self.tvalue | other_tvalue
803 either_known = self.tmask & other_tmask
804 both_known = self.tmask | other_tmask
805 unmasked_self = unmask_zero(self.tvalue, both_known)
806 unmasked_other = unmask_zero(other_tvalue, both_known)
807 tvalue = unmask_zero(union_val, either_known)
808 valid = unmasked_self == unmasked_other
809 return tvalue, either_known, valid
810
811 def intersect_const(self, lower, upper, do_shrinking=True):
812 """
813 Mutates `self` so that it contains integers that are contained in
814 `self` and the range [`lower`, `upper`], and only those. Basically
815 intersection of sets.
816 """
817 changed = False
818 if lower > self.lower:
819 if lower > self.upper:
820 raise InvalidLoop
821 self.lower = lower
822 changed = True
823 if upper < self.upper:
824 if upper < self.lower:
825 raise InvalidLoop
826 self.upper = upper
827 changed = True
828 if changed and do_shrinking:
829 self.shrink()
830 return changed
831
832 def add(self, value):
833 return self.add_bound(self.from_constant(value))
834
835 def add_bound(self, other):
836 """
837 Adds the `other` abstract integer to `self` and returns the result.
838 Must be correct in the presence of possible overflows.
839 (Does not mutate `self`.)
840 """
841
842 tvalue, tmask = self._tnum_add(other)
843
844 # the lower and upper logic is proven in test_prove_add_bounds_logic
845 try:
846 lower = ovfcheck(self.lower + other.lower)
847 except OverflowError:
848 return IntBound.from_knownbits(tvalue, tmask)
849 try:
850 upper = ovfcheck(self.upper + other.upper)
851 except OverflowError:
852 return IntBound.from_knownbits(tvalue, tmask)
853 return IntBound(lower, upper, tvalue, tmask)
854
855 @always_inline
856 def _tnum_add(self, other):
857 sum_values = self.tvalue + other.tvalue
858 sum_masks = self.tmask + other.tmask
859 all_carries = sum_values + sum_masks
860 val_carries = all_carries ^ sum_values
861 tmask = self.tmask | other.tmask | val_carries
862 tvalue = unmask_zero(sum_values, tmask)
863 return tvalue, tmask
864
865 def add_bound_cannot_overflow(self, other):
866 """ returns True if self + other can never overflow """
867 try:
868 ovfcheck(self.upper + other.upper)
869 ovfcheck(self.lower + other.lower)
870 except OverflowError:
871 return False
872 return True
873
874 def add_bound_no_overflow(self, other):
875 """ return the bound that self + other must have, if no overflow occured,
876 eg after an int_add_ovf(...), guard_no_overflow() """
877 tvalue, tmask = self._tnum_add(other)
878
879 # returning add_bound is always correct, but let's improve the range
880 lower = self._add_check_overflow(self.lower, other.lower, MININT)
881 upper = self._add_check_overflow(self.upper, other.upper, MAXINT)
882 return self.new(lower, upper, tvalue, tmask)
883
884 def mul2_bound_no_overflow(self):
885 """ return the bound that self + self must have, if no overflow occured,
886 eg after an int_add_ovf(a, a), guard_no_overflow() """
887 tvalue, tmask = self._tnum_lshift(1) # to know that the result is even
888
889 # returning add_bound is always correct, but let's improve the range
890 lower = self._add_check_overflow(self.lower, self.lower, MININT)
891 upper = self._add_check_overflow(self.upper, self.upper, MAXINT)
892 return self.new(lower, upper, tvalue, tmask)
893
894 def sub_bound(self, other):
895 """
896 Subtracts the `other` abstract integer from `self` and returns the
897 result. (Does not mutate `self`.)
898 """
899 tvalue, tmask = self._tnum_sub(other)
900 # the lower and upper logic is proven in test_prove_sub_bound_logic
901 try:
902 lower = ovfcheck(self.lower - other.upper)
903 except OverflowError:
904 return IntBound.from_knownbits(tvalue, tmask)
905 try:
906 upper = ovfcheck(self.upper - other.lower)
907 except OverflowError:
908 return IntBound.from_knownbits(tvalue, tmask)
909 return IntBound(lower, upper, tvalue, tmask)
910
911 def _tnum_sub(self, other):
912 diff_values = self.tvalue - other.tvalue
913 val_borrows = (diff_values + self.tmask) ^ (diff_values - other.tmask)
914 tmask = self.tmask | other.tmask | val_borrows
915 tvalue = unmask_zero(diff_values, tmask)
916 return tvalue, tmask
917
918 def sub_bound_cannot_overflow(self, other):
919 try:
920 ovfcheck(self.lower - other.upper)
921 ovfcheck(self.upper - other.lower)
922 except OverflowError:
923 return False
924 return True
925
926 def sub_bound_no_overflow(self, other):
927 """ return the bound that self - other must have, if no overflow occured,
928 eg after an int_sub_ovf(...), guard_no_overflow() """
929 tvalue, tmask = self._tnum_sub(other)
930 # returning sub_bound is always correct, but let's improve the range
931 lower = self._sub_check_overflow(self.lower, other.upper, MININT)
932 upper = self._sub_check_overflow(self.upper, other.lower, MAXINT)
933 return self.new(lower, upper, tvalue, tmask)
934
935 def mul_bound(self, other):
936 """
937 Multiplies the `other` abstract
938 integer with `self` and returns the
939 result.
940 (Does not mutate `self`.)
941 """
942 try:
943 vals = (ovfcheck(self.upper * other.upper),
944 ovfcheck(self.upper * other.lower),
945 ovfcheck(self.lower * other.upper),
946 ovfcheck(self.lower * other.lower))
947 return IntBound(min4(vals), max4(vals))
948 except OverflowError:
949 return IntBound.unbounded()
950 mul_bound_no_overflow = mul_bound # can be improved
951
952 def mul_bound_cannot_overflow(self, other):
953 try:
954 ovfcheck(self.upper * other.upper)
955 ovfcheck(self.upper * other.lower)
956 ovfcheck(self.lower * other.upper)
957 ovfcheck(self.lower * other.lower)
958 except OverflowError:
959 return False
960 return True
961
962 def square_bound_no_overflow(self):
963 """
964 returns the bound of self**2, if no overflow occurred.
965 """
966 val0 = saturating_mul(self.lower, self.lower) # self.lower**2, or MAXINT
967 val1 = saturating_mul(self.upper, self.upper) # self.upper**2, or MAXINT
968 lower = min(val0, val1)
969 upper = max(val0, val1)
970 if not same_sign(self.upper, self.lower): # 0 is contained in the range
971 lower = 0
972 return IntBound(lower, upper)
973
974 def py_div_bound(self, other):
975 """
976 Divides this abstract integer by the
977 `other` abstract integer and returns
978 the result.
979 (Does not mutate `self`.)
980 """
981 # we need to make sure that the 0 is not in the interval because
982 # otherwise [-4, 4] / [-4, 4] would return [-1, 1], which is nonsense
983 # see test_knownbits_div_bug. the first part of the check is not
984 # enough, because 0 could be excluded by the known bits
985 if not other.contains(0) and not (other.lower < 0 < other.upper):
986 try:
987 # this gives the bounds for 'int_py_div', so use the
988 # Python-style handling of negative numbers and not
989 # the C-style one
990 vals = (ovfcheck(self.upper / other.upper),
991 ovfcheck(self.upper / other.lower),
992 ovfcheck(self.lower / other.upper),
993 ovfcheck(self.lower / other.lower))
994 return IntBound(min4(vals), max4(vals))
995 except OverflowError:
996 pass
997 return IntBound.unbounded()
998
999 def mod_bound(self, other):
1000 """
1001 Calculates the mod of this abstract
1002 integer by the `other` abstract
1003 integer and returns the result.
1004 (Does not mutate `self`.)
1005 """
1006 r = IntBound.unbounded()
1007 if other.is_constant() and other.get_constant_int() == 0:
1008 return IntBound.unbounded()
1009 # with Python's modulo: 0 <= (x % pos) < pos
1010 # neg < (x % neg) <= 0
1011 # see test_prove_mod_bound_logic
1012 if other.upper > 0:
1013 upper = other.upper - 1
1014 else:
1015 upper = 0
1016 if other.lower < 0:
1017 lower = other.lower + 1
1018 else:
1019 lower = 0
1020 return IntBound(lower, upper)
1021
1022 def lshift_bound(self, other):
1023 """
1024 Shifts this abstract integer `other`
1025 bits to the left, where `other` is
1026 another abstract integer.
1027 (Does not mutate `self`.)
1028 """
1029
1030 tvalue, tmask = TNUM_UNKNOWN
1031 if other.is_constant():
1032 c_other = other.get_constant_int()
1033 if c_other >= LONG_BIT:
1034 tvalue, tmask = TNUM_KNOWN_ZERO
1035 elif 0 <= c_other < LONG_BIT:
1036 tvalue, tmask = self._tnum_lshift(c_other)
1037 # else: bits are unknown because arguments invalid
1038
1039 if other.known_nonnegative() and other.known_lt_const(LONG_BIT):
1040 try:
1041 vals = (ovfcheck(self.upper << other.upper),
1042 ovfcheck(self.upper << other.lower),
1043 ovfcheck(self.lower << other.upper),
1044 ovfcheck(self.lower << other.lower))
1045 return IntBound(min4(vals), max4(vals), tvalue, tmask)
1046 except (OverflowError, ValueError):
1047 pass
1048
1049 return IntBound.from_knownbits(tvalue, tmask)
1050
1051 @always_inline
1052 def _tnum_lshift(self, c_other):
1053 # use signed integer sign extension logic
1054 tvalue = self.tvalue << c_other
1055 tmask = self.tmask << c_other
1056 return tvalue, tmask
1057
1058 def rshift_bound(self, other):
1059 """
1060 Shifts this abstract integer `other` bits to the right, where `other`
1061 is another abstract integer, and extends its sign. This is the
1062 arithmetic shift on signed integers, ie the shifted in values are 0/1,
1063 depending on the sign.
1064 (Does not mutate `self`.)
1065 """
1066
1067 tvalue, tmask = TNUM_UNKNOWN
1068 if other.is_constant():
1069 c_other = other.get_constant_int()
1070 if c_other >= LONG_BIT:
1071 # shift value out to the right, but do sign extend
1072 if msbonly(self.tmask): # sign-extend mask
1073 tvalue, tmask = TNUM_UNKNOWN
1074 elif msbonly(self.tvalue): # sign-extend value
1075 tvalue, tmask = TNUM_KNOWN_BITWISEONE
1076 else: # sign is 0 on both
1077 tvalue, tmask = TNUM_KNOWN_ZERO
1078 elif c_other >= 0:
1079 tvalue, tmask = self._tnum_rshift(c_other)
1080 # else: bits are unknown because arguments invalid
1081
1082 lower = MININT
1083 upper = MAXINT
1084 if other.known_nonnegative() and other.known_lt_const(LONG_BIT):
1085 vals = (self.upper >> other.upper,
1086 self.upper >> other.lower,
1087 self.lower >> other.upper,
1088 self.lower >> other.lower)
1089 lower = min4(vals)
1090 upper = max4(vals)
1091 return IntBound(lower, upper, tvalue, tmask)
1092
1093 @always_inline
1094 def _tnum_rshift(self, c_other):
1095 # use signed integer sign extension logic
1096 tvalue = self.r_uint(self.intmask(self.tvalue) >> c_other)
1097 tmask = self.r_uint(self.intmask(self.tmask) >> c_other)
1098 return tvalue, tmask
1099
1100 def lshift_bound_cannot_overflow(self, other):
1101 """ returns True if self << other can never overflow """
1102 if other.known_nonnegative() and \
1103 other.known_lt_const(LONG_BIT):
1104 try:
1105 ovfcheck(self.upper << other.upper)
1106 ovfcheck(self.upper << other.lower)
1107 ovfcheck(self.lower << other.upper)
1108 ovfcheck(self.lower << other.lower)
1109 return True
1110 except (OverflowError, ValueError):
1111 pass
1112 return False
1113
1114 def urshift_bound(self, other):
1115 """
1116 Shifts this abstract integer `other` bits to the right, where `other`
1117 is another abstract integer, *without* extending its sign. (Does not
1118 mutate `self`.)
1119 """
1120
1121 # this seems to always be the signed variant..?
1122 lower = MININT
1123 upper = MAXINT
1124 tvalue, tmask = TNUM_UNKNOWN
1125 if other.is_constant():
1126 c_other = other.get_constant_int()
1127 if c_other >= LONG_BIT:
1128 # no sign to extend, we get constant 0
1129 tvalue, tmask = TNUM_KNOWN_ZERO
1130 elif c_other >= 0:
1131 tvalue, tmask = self._tnum_urshift(c_other)
1132 if self.lower >= 0:
1133 upper = intmask(r_uint(self.upper) >> c_other)
1134 lower = intmask(r_uint(self.lower) >> c_other)
1135 # else: bits are unknown because arguments invalid
1136 return IntBound(lower, upper, tvalue, tmask)
1137
1138 # we don't do bounds on unsigned
1139 return IntBound.from_knownbits(tvalue, tmask)
1140
1141 @always_inline
1142 def _tnum_urshift(self, c_other):
1143 tvalue = self._urshift(self.tvalue, c_other)
1144 tmask = self._urshift(self.tmask, c_other)
1145 return tvalue, tmask
1146
1147 def and_bound(self, other):
1148 """
1149 Performs bit-wise AND of this abstract integer and the `other`,
1150 returning its result. (Does not mutate `self`.)
1151 """
1152
1153 pos1 = self.known_nonnegative()
1154 pos2 = other.known_nonnegative()
1155 # the next three if-conditions are proven by test_prove_and_bound_logic
1156 lower = MININT
1157 upper = MAXINT
1158 if pos1 or pos2:
1159 lower = 0
1160 if pos1:
1161 upper = self.upper
1162 if pos2:
1163 upper = min(upper, other.upper)
1164
1165 res_tvalue, res_tmask = self._tnum_and(other)
1166 return IntBound(lower, upper, res_tvalue, res_tmask)
1167
1168 @always_inline
1169 def _tnum_and(self, other):
1170 self_pmask = self.tvalue | self.tmask
1171 other_pmask = other.tvalue | other.tmask
1172 and_vals = self.tvalue & other.tvalue
1173 return and_vals, self_pmask & other_pmask & ~and_vals
1174
1175 def or_bound(self, other):
1176 """
1177 Performs bit-wise OR of this abstract integer and the `other`,
1178 returning its result. (Does not mutate `self`.)
1179 """
1180
1181 tvalue, tmask = self._tnum_or(other)
1182 return self.from_knownbits(tvalue, tmask)
1183
1184 @always_inline
1185 def _tnum_or(self, other):
1186 union_vals = self.tvalue | other.tvalue
1187 union_masks = self.tmask | other.tmask
1188 return union_vals, union_masks & ~union_vals
1189
1190 def xor_bound(self, other):
1191 """
1192 Performs bit-wise XOR of this abstract integer and the `other`,
1193 returning its result.
1194 (Does not mutate `self`.)
1195 """
1196 tvalue, tmask = self._tnum_xor(other)
1197 return self.from_knownbits(tvalue, tmask)
1198
1199 @always_inline
1200 def _tnum_xor(self, other):
1201 xor_vals = self.tvalue ^ other.tvalue
1202 union_masks = self.tmask | other.tmask
1203 return unmask_zero(xor_vals, union_masks), union_masks
1204
1205 def neg_bound(self):
1206 """
1207 Arithmetically negates this abstract integer and returns the result.
1208 (Does not mutate `self`.)
1209 """
1210 res = self.invert_bound()
1211 res = res.add(1)
1212 return res
1213
1214 def invert_bound(self):
1215 """
1216 Performs bit-wise NOT on this abstract integer returning its result.
1217 (Does not mutate `self`.)
1218 """
1219 upper = ~self.lower
1220 lower = ~self.upper
1221 tvalue = unmask_zero(~self.tvalue, self.tmask)
1222 tmask = self.tmask
1223 return self.new(lower, upper, tvalue, tmask)
1224
1225 def contains(self, value):
1226 """
1227 Returns `True` iff this abstract integer contains the given `value`.
1228 """
1229
1230 assert not isinstance(value, IntBound)
1231
1232 if not we_are_translated():
1233 assert not isinstance(value, long)
1234 if not isinstance(value, int):
1235 if (self.lower == MININT and self.upper == MAXINT):
1236 return True # workaround for address as int
1237 if value < self.lower:
1238 return False
1239 if value > self.upper:
1240 return False
1241
1242 u_vself = unmask_zero(self.tvalue, self.tmask)
1243 u_value = unmask_zero(r_uint(value), self.tmask)
1244 if u_vself != u_value:
1245 return False
1246
1247 return True
1248
1249 def is_within_range(self, lower, upper):
1250 """
1251 Check if all the numbers contained in this instance have are between
1252 lower and upper.
1253 """
1254 return lower <= self.lower and self.upper <= upper
1255
1256 def clone(self):
1257 """
1258 Returns a copy of this abstract integer.
1259 """
1260 res = IntBound(self.lower, self.upper,
1261 self.tvalue, self.tmask)
1262 return res
1263
1264 def make_guards(self, box, guards, optimizer):
1265 """
1266 Generates guards from the information we have about the numbers this
1267 abstract integer contains.
1268 """
1269 if self.is_constant():
1270 guards.append(ResOperation(rop.GUARD_VALUE,
1271 [box, ConstInt(self.upper)]))
1272 return
1273 if self.lower > MININT:
1274 bound = self.lower
1275 op = ResOperation(rop.INT_GE, [box, ConstInt(bound)])
1276 guards.append(op)
1277 op = ResOperation(rop.GUARD_TRUE, [op])
1278 guards.append(op)
1279 if self.upper < MAXINT:
1280 bound = self.upper
1281 op = ResOperation(rop.INT_LE, [box, ConstInt(bound)])
1282 guards.append(op)
1283 op = ResOperation(rop.GUARD_TRUE, [op])
1284 guards.append(op)
1285 if not self._are_knownbits_implied():
1286 op = ResOperation(rop.INT_AND, [box, ConstInt(intmask(~self.tmask))])
1287 guards.append(op)
1288 op = ResOperation(rop.GUARD_VALUE, [op, ConstInt(intmask(self.tvalue))])
1289 guards.append(op)
1290
1291 def is_bool(self):
1292 """
1293 Returns `True` iff self is exactly the set {0, 1}
1294 """
1295 return (self.known_nonnegative() and self.known_le_const(1))
1296
1297 def is_unbounded(self):
1298 return (self.lower == MININT and self.upper == MAXINT and
1299 self.tvalue == r_uint(0) and self.tmask == r_uint(-1))
1300
1301
1302 def make_bool(self):
1303 """
1304 Mutates this abstract integer so that it does represent a conventional
1305 boolean value.
1306 (Mutates `self`.)
1307 """
1308 self.intersect_const(0, 1)
1309
1310 def getconst(self):
1311 """
1312 Returns ConstInt with the only integer contained in this abstract
1313 integer. Caller needs to check that `.is_constant()` returns True,
1314 before calling.
1315 """
1316 return ConstInt(self.get_constant_int())
1317
1318 def getnullness(self):
1319 """
1320 Returns information about whether this this abstract integer is known
1321 to be zero or not to be zero.
1322 """
1323 if self.known_gt_const(0) or \
1324 self.known_lt_const(0) or \
1325 self.tvalue != 0:
1326 return INFO_NONNULL
1327 if self.is_constant() and self.get_constant_int() == 0:
1328 return INFO_NULL
1329 return INFO_UNKNOWN
1330
1331 def widen(self):
1332 info = self.clone()
1333 info.widen_update()
1334 return info
1335
1336 def widen_update(self):
1337 if self.lower < MININT / 2:
1338 self.lower = MININT
1339 if self.upper > MAXINT / 2:
1340 self.upper = MAXINT
1341 self.tvalue, self.tmask = TNUM_UNKNOWN
1342 self.shrink()
1343
1344
1345 def and_bound_backwards(self, result):
1346 """
1347 result == int_and(self, other)
1348 We want to learn some bits about other, using the information from self
1349 and result_int.
1350
1351 regular &:
1352 other
1353 & 0 1 ?
1354 0 0 0 0
1355 1 0 1 ?
1356 ? 0 ? ? <- result
1357 self
1358
1359 backwards & (this one):
1360 self
1361 0 1 ?
1362 0 ? 0 ?
1363 1 X 1 1
1364 ? ? ? ? <- other
1365 result
1366
1367 (X marks an inconsistent result).
1368
1369 We can see that we only learn something about other at the places
1370 where a bit from self is 1. At those places, the corresponding bit in
1371 other has to be the corresponding bit in result.
1372 """
1373
1374 tvalue, tmask, valid = self._tnum_and_backwards(result)
1375 if not valid:
1376 raise InvalidLoop("inconsistency in and_bound_backwards")
1377 return IntBound.from_knownbits(tvalue, tmask)
1378
1379 @always_inline
1380 def _tnum_and_backwards(self, result):
1381 # in all the places where the result is 1 both arguments have to 1. in
1382 # the places where result is 0, other has to be 0 iff self is known 1.
1383 tvalue = result.tvalue
1384 tmask = ((~self.tvalue) | result.tmask) & ~tvalue
1385 # if we have a place where result is 1 but self is 0, then we are
1386 # inconsistent
1387 inconsistent = result.tvalue & ~self.tmask & ~self.tvalue
1388 return tvalue, tmask, inconsistent == 0
1389
1390 def or_bound_backwards(self, result):
1391 """
1392 result_int == int_or(self, other)
1393 We want to refine our knowledge about other
1394 using this information
1395
1396 regular |:
1397 other
1398 & 0 1 ?
1399 0 0 1 ?
1400 1 1 1 1
1401 ? ? 1 ? <- result
1402 self
1403
1404 backwards | (this one):
1405 self
1406 0 1 ?
1407 0 0 X 0
1408 1 1 ? ?
1409 ? ? ? ? <- other (where X=invalid)
1410 result
1411
1412 """
1413 tvalue, tmask, valid = self._tnum_or_backwards(result)
1414 if not valid:
1415 raise InvalidLoop("inconsistency in or_bound_backwards")
1416 return IntBound.from_knownbits(tvalue, tmask)
1417
1418 @always_inline
1419 def _tnum_or_backwards(self, result):
1420 # in all the places where the result is 0 both arguments have to be 0.
1421 zeros = (~result.tmask & ~result.tvalue)
1422 # apart from that, in the places where self is 0 and where result is 1
1423 # other must be 1
1424 tvalue = (result.tvalue & ~self.tvalue & ~self.tmask)
1425 tmask = ~(zeros | tvalue)
1426 # if we have a place where result is 0 but self is 1, then we are
1427 # inconsistent
1428 inconsistent = self.tvalue & zeros
1429 return tvalue, tmask, inconsistent == 0
1430
1431 def rshift_bound_backwards(self, other):
1432 """
1433 Performs a `urshift`/`rshift` backwards on `self`. Basically
1434 left-shifts `self` by `other` binary digits, filling the lower part
1435 with ?, and returns the result.
1436 """
1437 if not other.is_constant():
1438 return IntBound.unbounded()
1439 c_other = other.get_constant_int()
1440 tvalue, tmask = TNUM_UNKNOWN
1441 if 0 <= c_other < LONG_BIT:
1442 tvalue = self.tvalue << r_uint(c_other)
1443 tmask = self.tmask << r_uint(c_other)
1444 # shift ? in from the right,
1445 tmask |= (r_uint(1) << r_uint(c_other)) - 1
1446 return IntBound.from_knownbits(tvalue, tmask)
1447 urshift_bound_backwards = rshift_bound_backwards
1448
1449 def lshift_bound_backwards(self, other):
1450 """
1451 Performs a `lshift` backwards on `self`. Basically right-shifts `self`
1452 by `other` binary digits, filling the upper part with ?, and returns
1453 the result.
1454 """
1455 if not other.is_constant():
1456 return IntBound.unbounded()
1457 c_other = r_uint(other.get_constant_int())
1458 tvalue, tmask = TNUM_UNKNOWN
1459 if 0 <= c_other < LONG_BIT:
1460 tvalue = self.tvalue >> c_other
1461 tmask = self.tmask >> c_other
1462 # shift ? in from the left,
1463 s_tmask = ~(r_uint(-1) >> c_other)
1464 tmask |= s_tmask
1465 inconsistent = self.tvalue & ((1 << c_other) - 1)
1466 if inconsistent:
1467 raise InvalidLoop("lshift_bound_backwards inconsistent known bits")
1468 return IntBound.from_knownbits(tvalue, tmask)
1469
1470 def shrink(self):
1471 """ Shrink the bounds and the knownbits to be more precise, but without
1472 changing the set of integers that is represented by self.
1473
1474 Here's a diagram to show what is happening. This is the number line:
1475 MININT <---------0-----------------------------------------------> MAXINT
1476
1477 We have a range in the number line
1478 [lower ... upper]
1479
1480 We also known bits, they represent a set of ints maybe looking like this:
1481 X X X X X X X X X X X X X X X X
1482 (an X means the number matches the known bits, ' ' means it doesn't)
1483
1484 Note that the lower and upper bounds could be more precise (ie bigger
1485 and smaller, respectively), because they don't match the known bits.
1486 Also, there are numbers that match the known bits to the left of lower
1487 and the right of upper, that are excluded by the range and thus
1488 unnecessary. We want to fix both of that.
1489
1490 First we shrink the bounds so that they both match the known bits,
1491 then things look like this:
1492 [lower ... upper]
1493 X X X X X X X X X X X X X X X X
1494 This is achieved by moving lower to the right to the first number >=
1495 lower that matches the known bits (and mutatis mutandis for upper).
1496
1497 Afterwards we use the information from the bounds to add more known
1498 bits. Having done that, things look maybe something like this:
1499 [lower ... upper]
1500 X X X X X X X X
1501 Then we're done with shrinking.
1502
1503 The set that is described by these two pieces of information together
1504 is neither expressible as purely a range, nor purely by known bits.
1505 It looks like this:
1506 X X X X X X X
1507 The set did not change through this process, but the bounds and the
1508 known bits becoming more precise makes it possible to compute more
1509 precise results when doing further operations with self.
1510 """
1511 # there's a proof in test_z3intbound that one pass of shrinking is
1512 # always enough. let's still assert that a second pass doesn't change
1513 # anything.
1514 changed = self._shrink_bounds_by_knownbits()
1515 changed |= self._shrink_knownbits_by_bounds()
1516 if not changed:
1517 return changed
1518 changed_again = self._shrink_bounds_by_knownbits()
1519 changed_again |= self._shrink_knownbits_by_bounds()
1520 assert not changed_again
1521 return changed
1522
1523 def _shrink_bounds_by_knownbits(self):
1524 """
1525 Shrinks the bounds by the known bits.
1526 """
1527 # lower bound
1528 min_by_knownbits = self._get_minimum_signed_by_knownbits_atleast(self.lower)
1529 max_by_knownbits = self._get_maximum_signed_by_knownbits_atmost(self.upper)
1530 if min_by_knownbits > max_by_knownbits:
1531 raise InvalidLoop("range and knownbits contradict each other")
1532 changed = self.lower < min_by_knownbits or self.upper > max_by_knownbits
1533 if changed:
1534 self.lower = min_by_knownbits
1535 self.upper = max_by_knownbits
1536 return changed
1537
1538 def _shrink_knownbits_by_bounds(self):
1539 """
1540 Infers known bits from the bounds. Basically fills a common prefix from
1541 lower and upper bound into the knownbits.
1542 """
1543 tvalue, tmask, valid = self._tnum_improve_knownbits_by_bounds()
1544 if not valid:
1545 raise InvalidLoop("knownbits and bounds don't agree")
1546 changed = self.tvalue != tvalue or self.tmask != tmask
1547 if changed:
1548 self.tmask = tmask
1549 self.tvalue = tvalue
1550 return changed
1551
1552 @always_inline
1553 def _tnum_implied_by_bounds(self):
1554 # calculate higher bit mask by bounds
1555 hbm_bounds = leading_zeros_mask(
1556 self.r_uint(self.lower) ^ self.r_uint(self.upper))
1557 bounds_common = self.r_uint(self.lower) & hbm_bounds
1558 tmask = ~hbm_bounds
1559 return unmask_zero(bounds_common, tmask), tmask
1560
1561 @always_inline
1562 def _tnum_improve_knownbits_by_bounds(self):
1563 # knownbits that are implied by the bounds
1564 tvalue, tmask = self._tnum_implied_by_bounds()
1565 # intersect them with the current knownbits
1566 return self._tnum_intersect(tvalue, tmask)
1567
1568 def _debug_check(self):
1569 """
1570 Very simple debug check. Returns `True` iff the span of knownbits and
1571 the span of the bounds have a non-empty intersection. That does not
1572 guarantee for the actual concrete value set to contain any values!
1573 """
1574 assert self.lower <= self.upper
1575 min_knownbits = self._get_minimum_signed_by_knownbits()
1576 max_knownbits = self._get_maximum_signed_by_knownbits()
1577 if not min_knownbits <= self.upper:
1578 return False
1579 if not max_knownbits >= self.lower:
1580 return False
1581 # just to make sure
1582 if not min_knownbits <= max_knownbits:
1583 return False
1584 # make sure the set is not empty
1585 if self.is_constant():
1586 # does one constraint exclude the constant value?
1587 val = self.get_constant_int()
1588 if min_knownbits > val or max_knownbits < val \
1589 or self.lower > val or self.upper < val:
1590 return False
1591 else:
1592 # we have no constant, so keep checking
1593 u_lower = r_uint(self.lower)
1594 u_upper = r_uint(self.upper)
1595 # check if bounds common prefix agrees with known-bits
1596 hbm_bounds = leading_zeros_mask(u_lower ^ u_upper)
1597 bounds_common_prefix = u_lower & hbm_bounds
1598 if unmask_zero(bounds_common_prefix, self.tmask) != self.tvalue & hbm_bounds:
1599 return False
1600 # for the rest of the bunch, check by minima/maxima with threshold.
1601 # (side note: the whole check can be reduced to this, but for the
1602 # sake of robustness we want to keep the other checks above.)
1603 if self._get_minimum_signed_by_knownbits_atleast(self.lower) > self.upper \
1604 or self._get_maximum_signed_by_knownbits_atmost(self.upper) < self.lower:
1605 return False
1606 return True
1607
1608 def knownbits_string(self, unk_sym='?'):
1609 """
1610 Returns a string representation about the knownbits part of this
1611 abstract integer. You can give any symbol or string for the "unknown
1612 bits" (default: '?'), the other digits are written as '1' and '0'.
1613 """
1614 results = []
1615 for bit in range(LONG_BIT):
1616 if self.tmask & (1 << bit):
1617 results.append(unk_sym)
1618 else:
1619 results.append(str((self.tvalue >> bit) & 1))
1620 results.reverse()
1621 return "".join(results)
1622
1623
1624 def flip_msb(val_uint):
1625 return val_uint ^ r_uint(MININT)
1626
1627 def is_valid_tnum(tvalue, tmask):
1628 """
1629 Returns `True` iff `tvalue` and `tmask` would be valid tri-state number
1630 fields of an abstract integer, meeting all conventions and requirements.
1631 """
1632 if not isinstance(tvalue, r_uint):
1633 return False
1634 if not isinstance(tmask, r_uint):
1635 return False
1636 return 0 == (r_uint(tvalue) & r_uint(tmask))
1637
1638 def leading_zeros_mask(n):
1639 """
1640 calculates a bitmask in which only the leading zeros of `n` are set (1).
1641 """
1642 return ~next_pow2_m1(n)
1643
1644 def lowest_set_bit_only(val_uint):
1645 """
1646 Returns an val_int, but with all bits deleted but the lowest one that was
1647 set.
1648 """
1649 #assert isinstance(val_uint, r_uint)
1650 working_val = ~val_uint
1651 increased_val = working_val + 1
1652 result = (working_val^increased_val) & val_uint
1653 return result
1654
1655 def min4(t):
1656 """
1657 Returns the minimum of the values in the quadruplet t.
1658 """
1659 return min(min(t[0], t[1]), min(t[2], t[3]))
1660
1661 def max4(t):
1662 """
1663 Returns the maximum of the values in the quadruplet t.
1664 """
1665 return max(max(t[0], t[1]), max(t[2], t[3]))
1666
1667 def msbonly(v):
1668 """
1669 Returns `v` with all bits except the most significant bit set to 0 (zero).
1670 """
1671 return v & (1 << (LONG_BIT-1))
1672
1673 def next_pow2_m1(n):
1674 """Calculate next power of 2 minus one, greater than n"""
1675 n |= n >> 1
1676 n |= n >> 2
1677 n |= n >> 4
1678 n |= n >> 8
1679 n |= n >> 16
1680 if IS_64_BIT:
1681 n |= n >> 32
1682 return n
1683
1684 def unmask_one(value, mask):
1685 """
1686 Sets all unknowns determined by `mask` in `value` bit-wise to 1 (one) and
1687 returns the result.
1688 """
1689 return value | mask
1690
1691 def unmask_zero(value, mask):
1692 """
1693 Sets all unknowns determined by `mask` in `value` bit-wise to 0 (zero) and
1694 returns the result.
1695 """
1696 return value & ~mask
1697
1698 def saturating_mul(a, b):
1699 """
1700 Returns a * b. If the multiplication overflows it returns either MININT or
1701 MAXINT, whichever is closer to the "correct" value.
1702 """
1703 try:
1704 return ovfcheck(a * b)
1705 except OverflowError:
1706 if same_sign(a, b):
1707 return MAXINT
1708 return MININT
1709
1710 def same_sign(a, b):
1711 """ Return True iff a and b have the same sign """
1712 return (a ^ b) >= 0