Debian Codegraph @

rpython/rlib/rarithmetic.py

raw symbols SCIP
1 """
2 This file defines restricted arithmetic:
3
4 classes and operations to express integer arithmetic,
5 such that before and after translation semantics are
6 consistent
7
8 r_uint an unsigned integer which has no overflow
9 checking. It is always positive and always
10 truncated to the internal machine word size.
11 intmask mask a possibly long value when running on CPython
12 back to a signed int value
13 ovfcheck check on CPython whether the result of a signed
14 integer operation did overflow (add, sub, mul)
15 ovfcheck_float_to_int
16 convert to an integer or raise OverflowError
17 ovfcheck_float_to_longlong
18 convert to a longlong or raise OverflowError
19 r_longlong
20 like r_int but double word size
21 r_ulonglong
22 like r_uint but double word size
23 widen(x)
24 if x is of a type smaller than lltype.Signed or
25 lltype.Unsigned, widen it to lltype.Signed.
26 Useful because the translator doesn't support
27 arithmetic on the smaller types.
28 ovfcheck_int32_add/sub/mul(x, y)
29 perform an add/sub/mul between two regular integers,
30 but assumes that they fit inside signed 32-bit ints
31 and raises OverflowError if the result no longer does
32
33 These are meant to be erased by translation, r_uint
34 in the process should mark unsigned values, ovfcheck should
35 mark where overflow checking is required.
36
37
38 """
39 import sys, struct, math
40 from rpython.rtyper import extregistry
41 from rpython.rlib import objectmodel
42 from rpython.flowspace.model import Constant, const
43 from rpython.flowspace.specialcase import register_flow_sc
44 from rpython.rlib.objectmodel import specialize, not_rpython
45
46 """
47 Long-term target:
48 We want to make pypy very flexible concerning its data type layout.
49 This is a larger task for later.
50
51 Short-term target:
52 We want to run PyPy on windows 64 bit.
53
54 Problem:
55 On windows 64 bit, integers are only 32 bit. This is a problem for PyPy
56 right now, since it assumes that a c long can hold a pointer.
57 We therefore set up the target machine constants to obey this rule.
58 Right now this affects 64 bit Python only on windows.
59
60 Note: We use the struct module, because the array module doesn's support
61 all typecodes.
62 """
63
64 def _get_bitsize(typecode):
65 return len(struct.pack(typecode, 1)) * 8
66
67 long_typecode = 'l'
68 if _get_bitsize('P') > _get_bitsize('l'):
69 long_typecode = 'P'
70
71 def _get_long_bit():
72 # whatever size a long has, make it big enough for a pointer.
73 return _get_bitsize(long_typecode)
74
75 # exported for now for testing array values.
76 # might go into its own module.
77 def get_long_pattern(x):
78 """get the bit pattern for a long, adjusted to pointer size"""
79 return struct.pack(long_typecode, x)
80
81 # used in tests for ctypes and for genc and friends
82 # to handle the win64 special case:
83 is_emulated_long = long_typecode != 'l'
84
85 LONG_BIT = _get_long_bit()
86 LONG_MASK = (2**LONG_BIT)-1
87 LONG_TEST = 2**(LONG_BIT-1)
88
89 # XXX this is a good guess, but what if a long long is 128 bit?
90 LONGLONG_BIT = 64
91 LONGLONG_MASK = (2**LONGLONG_BIT)-1
92 LONGLONG_TEST = 2**(LONGLONG_BIT-1)
93
94 LONG_BIT_SHIFT = 0
95 while (1 << LONG_BIT_SHIFT) != LONG_BIT:
96 LONG_BIT_SHIFT += 1
97 assert LONG_BIT_SHIFT < 99, "LONG_BIT_SHIFT value not found?"
98
99 LONGLONGLONG_BIT = 128
100 LONGLONGLONG_MASK = (2**LONGLONGLONG_BIT)-1
101 LONGLONGLONG_TEST = 2**(LONGLONGLONG_BIT-1)
102
103 """
104 int is no longer necessarily the same size as the target int.
105 We therefore can no longer use the int type as it is, but need
106 to use long everywhere.
107 """
108
109 # XXX returning int(n) should not be necessary and should be simply n.
110 # XXX TODO: replace all int(n) by long(n) and fix everything that breaks.
111 # XXX Then relax it and replace int(n) by n.
112 @not_rpython
113 def intmask(n):
114 if isinstance(n, objectmodel.Symbolic):
115 return n # assume Symbolics don't overflow
116 assert not isinstance(n, float)
117 if is_valid_int(n):
118 return int(n)
119 n = long(n)
120 n &= LONG_MASK
121 if n >= LONG_TEST:
122 n -= 2*LONG_TEST
123 return int(n)
124
125 @not_rpython
126 def longlongmask(n):
127 assert isinstance(n, (int, long))
128 n = long(n)
129 n &= LONGLONG_MASK
130 if n >= LONGLONG_TEST:
131 n -= 2*LONGLONG_TEST
132 return r_longlong(n)
133
134 def longlonglongmask(n):
135 # Assume longlonglong doesn't overflow. This is perfectly fine for rbigint.
136 # We deal directly with overflow there anyway.
137 return r_longlonglong(n)
138
139 @specialize.argtype(0)
140 def widen(n):
141 from rpython.rtyper.lltypesystem import lltype
142 if _should_widen_type(lltype.typeOf(n)):
143 return intmask(n)
144 else:
145 return n
146
147 @specialize.memo()
148 def _should_widen_type(tp):
149 from rpython.rtyper.lltypesystem import lltype, rffi
150 if tp is lltype.Bool:
151 return True
152 if tp is lltype.Signed:
153 return False
154 r_class = rffi.platform.numbertype_to_rclass[tp]
155 assert issubclass(r_class, base_int)
156 return r_class.BITS < LONG_BIT or (
157 r_class.BITS == LONG_BIT and r_class.SIGNED)
158
159 # the replacement for sys.maxint
160 maxint = int(LONG_TEST - 1)
161 # for now, it should be equal to sys.maxint on all supported platforms
162 assert maxint == sys.maxint
163
164 @specialize.argtype(0)
165 def is_valid_int(r):
166 if objectmodel.we_are_translated():
167 return isinstance(r, int)
168 return isinstance(r, (base_int, int, long, bool)) and (
169 -maxint - 1 <= r <= maxint)
170
171 @not_rpython
172 def ovfcheck(r):
173 # to be used as ovfcheck(x <op> y)
174 # raise OverflowError if the operation did overflow
175 # Nowadays, only supports '+', '-' or '*' as the operation.
176 assert not isinstance(r, r_uint), "unexpected ovf check on unsigned"
177 assert not isinstance(r, r_longlong), "ovfcheck not supported on r_longlong"
178 assert not isinstance(r, r_ulonglong), "ovfcheck not supported on r_ulonglong"
179 if type(r) is long and not is_valid_int(r):
180 # checks only if applicable to r's type.
181 # this happens in the garbage collector.
182 raise OverflowError("signed integer expression did overflow")
183 return r
184
185 # Strange things happening for float to int on 64 bit:
186 # int(float(i)) != i because of rounding issues.
187 # These are the minimum and maximum float value that can
188 # successfully be casted to an int.
189
190 # The following values are not quite +/-sys.maxint.
191 # Note the "<= x <" here, as opposed to "< x <" above.
192 # This is justified by test_typed in translator/c/test.
193 def ovfcheck_float_to_longlong(x):
194 if math.isnan(x):
195 raise OverflowError
196 if -9223372036854776832.0 <= x < 9223372036854775296.0:
197 return r_longlong(x)
198 raise OverflowError
199
200 if sys.maxint == 2147483647:
201 def ovfcheck_float_to_int(x):
202 if math.isnan(x):
203 raise OverflowError
204 if -2147483649.0 < x < 2147483648.0:
205 return int(x)
206 raise OverflowError
207 else:
208 def ovfcheck_float_to_int(x):
209 return int(ovfcheck_float_to_longlong(x))
210
211 def compute_restype(self_type, other_type):
212 if self_type is other_type:
213 if self_type is bool:
214 return int
215 return self_type
216 if other_type in (bool, int, long):
217 if self_type is bool:
218 return int
219 return self_type
220 if self_type in (bool, int, long):
221 return other_type
222 if self_type is float or other_type is float:
223 return float
224 if self_type.SIGNED == other_type.SIGNED:
225 return build_int(None, self_type.SIGNED, max(self_type.BITS, other_type.BITS))
226 raise AssertionError("Merging these types (%s, %s) is not supported" % (self_type, other_type))
227
228 @specialize.memo()
229 def signedtype(t):
230 if t in (bool, int, long):
231 return True
232 else:
233 return t.SIGNED
234
235 def normalizedinttype(t):
236 if t is int:
237 return int
238 if t.BITS <= r_int.BITS:
239 return build_int(None, t.SIGNED, r_int.BITS)
240 else:
241 assert t.BITS <= r_longlong.BITS
242 return build_int(None, t.SIGNED, r_longlong.BITS)
243
244 @specialize.argtype(0)
245 def most_neg_value_of_same_type(x):
246 from rpython.rtyper.lltypesystem import lltype
247 return most_neg_value_of(lltype.typeOf(x))
248
249 @specialize.memo()
250 def most_neg_value_of(tp):
251 from rpython.rtyper.lltypesystem import lltype, rffi
252 if tp is lltype.Signed:
253 return -sys.maxint-1
254 r_class = rffi.platform.numbertype_to_rclass[tp]
255 assert issubclass(r_class, base_int)
256 if r_class.SIGNED:
257 return r_class(-(r_class.MASK >> 1) - 1)
258 else:
259 return r_class(0)
260
261 @specialize.argtype(0)
262 def most_pos_value_of_same_type(x):
263 from rpython.rtyper.lltypesystem import lltype
264 return most_pos_value_of(lltype.typeOf(x))
265
266 @specialize.memo()
267 def most_pos_value_of(tp):
268 from rpython.rtyper.lltypesystem import lltype, rffi
269 if tp is lltype.Signed:
270 return sys.maxint
271 r_class = rffi.platform.numbertype_to_rclass[tp]
272 assert issubclass(r_class, base_int)
273 if r_class.SIGNED:
274 return r_class(r_class.MASK >> 1)
275 else:
276 return r_class(r_class.MASK)
277
278 @specialize.memo()
279 def is_signed_integer_type(tp):
280 from rpython.rtyper.lltypesystem import lltype, rffi
281 if tp is lltype.Signed:
282 return True
283 try:
284 r_class = rffi.platform.numbertype_to_rclass[tp]
285 return r_class.SIGNED
286 except KeyError:
287 return False # not an integer type
288
289 def highest_bit(n):
290 """
291 Calculates the highest set bit in n. This function assumes that n is a
292 power of 2 (and thus only has a single set bit).
293 """
294 assert n and (n & (n - 1)) == 0
295 i = -1
296 while n:
297 i += 1
298 n >>= 1
299 return i
300
301
302 class base_int(long):
303 """ fake unsigned integer implementation """
304
305 def _widen(self, other, value):
306 """
307 if one argument is int or long, the other type wins.
308 if one argument is float, the result is float.
309 otherwise, produce the largest class to hold the result.
310 """
311 self_type = type(self)
312 other_type = type(other)
313 try:
314 return self.typemap[self_type, other_type](value)
315 except KeyError:
316 pass
317 restype = compute_restype(self_type, other_type)
318 self.typemap[self_type, other_type] = restype
319 return restype(value)
320
321 def __new__(klass, val):
322 if klass is base_int:
323 raise TypeError("abstract base!")
324 else:
325 return super(base_int, klass).__new__(klass, val)
326
327 def __add__(self, other):
328 x = long(self)
329 if not isinstance(other, (int, long)):
330 return x + other
331 y = long(other)
332 return self._widen(other, x + y)
333
334 def __radd__(self, other):
335 x = long(self)
336 if not isinstance(other, (int, long)):
337 return other + x
338 y = long(other)
339 return self._widen(other, x + y)
340
341 def __sub__(self, other):
342 x = long(self)
343 if not isinstance(other, (int, long)):
344 return x - other
345 y = long(other)
346 return self._widen(other, x - y)
347
348 def __rsub__(self, other):
349 y = long(self)
350 if not isinstance(other, (int, long)):
351 return other - y
352 x = long(other)
353 return self._widen(other, x - y)
354
355 def __mul__(self, other):
356 x = long(self)
357 if not isinstance(other, (int, long)):
358 return x * other
359 y = long(other)
360 return self._widen(other, x * y)
361
362 def __rmul__(self, other):
363 x = long(self)
364 if not isinstance(other, (int, long)):
365 return other * x
366 y = long(other)
367 return self._widen(other, x * y)
368
369 def __div__(self, other):
370 x = long(self)
371 if not isinstance(other, (int, long)):
372 return x / other
373 y = long(other)
374 return self._widen(other, x // y)
375
376 def __rdiv__(self, other):
377 y = long(self)
378 if not isinstance(other, (int, long)):
379 return other / y
380 x = long(other)
381 return self._widen(other, x // y)
382
383 def __floordiv__(self, other):
384 x = long(self)
385 if not isinstance(other, (int, long)):
386 return x // other
387 y = long(other)
388 return self._widen(other, x // y)
389
390 def __rfloordiv__(self, other):
391 y = long(self)
392 if not isinstance(other, (int, long)):
393 return other // y
394 x = long(other)
395 return self._widen(other, x // y)
396
397 def __mod__(self, other):
398 x = long(self)
399 if not isinstance(other, (int, long)):
400 return x % other
401 y = long(other)
402 return self._widen(other, x % y)
403
404 def __rmod__(self, other):
405 y = long(self)
406 if not isinstance(other, (int, long)):
407 return other % y
408 x = long(other)
409 return self._widen(other, x % y)
410
411 def __divmod__(self, other):
412 x = long(self)
413 if not isinstance(other, (int, long)):
414 return divmod(x, other)
415 y = long(other)
416 res = divmod(x, y)
417 return (self._widen(other, res[0]), self._widen(other, res[1]))
418
419 def __lshift__(self, n):
420 x = long(self)
421 if not isinstance(n, (int, long)):
422 raise TypeError
423 y = long(n)
424 return self.__class__(x << y)
425
426 def __rlshift__(self, n):
427 y = long(self)
428 if not isinstance(n, (int, long)):
429 raise TypeError
430 x = long(n)
431 return n.__class__(x << y)
432
433 def __rshift__(self, n):
434 x = long(self)
435 if not isinstance(n, (int, long)):
436 raise TypeError
437 y = long(n)
438 return self.__class__(x >> y)
439
440 def __rrshift__(self, n):
441 y = long(self)
442 if not isinstance(n, (int, long)):
443 raise TypeError
444 x = long(n)
445 return n.__class__(x >> y)
446
447 def __or__(self, other):
448 x = long(self)
449 if not isinstance(other, (int, long)):
450 return x | other
451 y = long(other)
452 return self._widen(other, x | y)
453
454 def __ror__(self, other):
455 x = long(self)
456 if not isinstance(other, (int, long)):
457 return other | x
458 y = long(other)
459 return self._widen(other, x | y)
460
461 def __and__(self, other):
462 x = long(self)
463 if not isinstance(other, (int, long)):
464 return x & other
465 y = long(other)
466 return self._widen(other, x & y)
467
468 def __rand__(self, other):
469 x = long(self)
470 if not isinstance(other, (int, long)):
471 return other & x
472 y = long(other)
473 return self._widen(other, x & y)
474
475 def __xor__(self, other):
476 x = long(self)
477 if not isinstance(other, (int, long)):
478 return x ^ other
479 y = long(other)
480 return self._widen(other, x ^ y)
481
482 def __rxor__(self, other):
483 x = long(self)
484 if not isinstance(other, (int, long)):
485 return other ^ x
486 y = long(other)
487 return self._widen(other, x ^ y)
488
489 def __neg__(self):
490 x = long(self)
491 return self.__class__(-x)
492
493 def __abs__(self):
494 x = long(self)
495 return self.__class__(abs(x))
496
497 def __pos__(self):
498 return self.__class__(self)
499
500 def __invert__(self):
501 x = long(self)
502 return self.__class__(~x)
503
504 def __pow__(self, other, m=None):
505 x = long(self)
506 if not isinstance(other, (int, long)):
507 return pow(x, other, m)
508 y = long(other)
509 res = pow(x, y, m)
510 return self._widen(other, res)
511
512 def __rpow__(self, other, m=None):
513 y = long(self)
514 if not isinstance(other, (int, long)):
515 return pow(other, y, m)
516 x = long(other)
517 res = pow(x, y, m)
518 return self._widen(other, res)
519
520
521 class signed_int(base_int):
522 SIGNED = True
523
524 def __new__(klass, val=0):
525 if isinstance(val, (float, str)):
526 val = long(val)
527 if val > klass.MASK >> 1 or val < -(klass.MASK >> 1) - 1:
528 raise OverflowError("%s does not fit in signed %d-bit integer" % (val, klass.BITS))
529 if val < 0:
530 val = ~ ((~val) & klass.MASK)
531 return super(signed_int, klass).__new__(klass, val)
532 typemap = {}
533
534
535 class unsigned_int(base_int):
536 SIGNED = False
537
538 def __new__(klass, val=0):
539 if isinstance(val, (float, long, str)):
540 val = long(val)
541 return super(unsigned_int, klass).__new__(klass, val & klass.MASK)
542 typemap = {}
543
544 _inttypes = {}
545
546 def build_int(name, sign, bits, force_creation=False):
547 sign = bool(sign)
548 if not force_creation:
549 try:
550 return _inttypes[sign, bits]
551 except KeyError:
552 pass
553 if sign:
554 base_int_type = signed_int
555 else:
556 base_int_type = unsigned_int
557 mask = (2 ** bits) - 1
558 if name is None:
559 raise TypeError('No predefined %sint%d'%(['u', ''][sign], bits))
560 int_type = type(name, (base_int_type,), {'MASK': mask,
561 'BITS': bits,
562 'SIGN': sign})
563 if not force_creation:
564 _inttypes[sign, bits] = int_type
565 class ForValuesEntry(extregistry.ExtRegistryEntry):
566 _type_ = int_type
567
568 def compute_annotation(self):
569 from rpython.annotator import model as annmodel
570 return annmodel.SomeInteger(knowntype=int_type)
571
572 class ForTypeEntry(extregistry.ExtRegistryEntry):
573 _about_ = int_type
574
575 def compute_result_annotation(self, *args_s, **kwds_s):
576 from rpython.annotator import model as annmodel
577 return annmodel.SomeInteger(knowntype=int_type)
578
579 def specialize_call(self, hop):
580 v_result, = hop.inputargs(hop.r_result.lowleveltype)
581 hop.exception_cannot_occur()
582 return v_result
583
584 return int_type
585
586 class BaseIntValueEntry(extregistry.ExtRegistryEntry):
587 _type_ = base_int
588
589 def compute_annotation(self):
590 from rpython.annotator import model as annmodel
591 return annmodel.SomeInteger(knowntype=r_ulonglong)
592
593 class BaseIntTypeEntry(extregistry.ExtRegistryEntry):
594 _about_ = base_int
595
596 def compute_result_annotation(self, *args_s, **kwds_s):
597 raise TypeError("abstract base!")
598
599 r_int = build_int('r_int', True, LONG_BIT)
600 r_uint = build_int('r_uint', False, LONG_BIT)
601
602 @register_flow_sc(r_uint)
603 def sc_r_uint(ctx, w_value):
604 # (normally, the 32-bit constant is a long, and is not allowed to
605 # show up in the flow graphs at all)
606 if isinstance(w_value, Constant):
607 return Constant(r_uint(w_value.value))
608 return ctx.appcall(r_uint, w_value)
609
610
611 r_longlong = build_int('r_longlong', True, 64)
612 r_ulonglong = build_int('r_ulonglong', False, 64)
613
614 r_longlonglong = build_int('r_longlonglong', True, 128)
615 r_ulonglonglong = build_int('r_ulonglonglong', False, 128)
616 longlongmax = r_longlong(LONGLONG_TEST - 1)
617
618 if r_longlong is not r_int:
619 r_int64 = r_longlong
620 r_uint64 = r_ulonglong
621 r_int32 = int # XXX: what about r_int
622 r_uint32 = r_uint
623 else:
624 r_int64 = int # XXX: what about r_int
625 r_uint64 = r_uint # is r_ulonglong
626 r_int32 = build_int('r_int32', True, 32) # also needed for rposix_stat.time_t_to_FILE_TIME in the 64 bit case
627 r_uint32 = build_int('r_uint32', False, 32)
628
629
630 SHRT_MIN = -2**(_get_bitsize('h') - 1)
631 SHRT_MAX = 2**(_get_bitsize('h') - 1) - 1
632 USHRT_MAX = 2**_get_bitsize('h') - 1
633 INT_MIN = int(-2**(_get_bitsize('i') - 1))
634 INT_MAX = int(2**(_get_bitsize('i') - 1) - 1)
635 UINT_MAX = r_uint(2**_get_bitsize('i') - 1)
636
637 # the 'float' C type
638
639 class r_singlefloat(object):
640 """A value of the C type 'float'.
641
642 This is a single-precision floating-point number.
643 Regular 'float' values in Python and RPython are double-precision.
644 Note that we consider this as a black box for now - the only thing
645 you can do with it is cast it back to a regular float."""
646
647 def __init__(self, floatval):
648 import struct
649 # simulates the loss of precision
650 self._bytes = struct.pack("f", floatval)
651
652 def __float__(self):
653 import struct
654 return struct.unpack("f", self._bytes)[0]
655
656 def __nonzero__(self):
657 raise TypeError("not supported on r_singlefloat instances")
658
659 def __cmp__(self, other):
660 raise TypeError("not supported on r_singlefloat instances")
661
662 def __eq__(self, other):
663 return self.__class__ is other.__class__ and self._bytes == other._bytes
664
665 def __ne__(self, other):
666 return not self.__eq__(other)
667
668 def __hash__(self):
669 return hash(self._bytes)
670
671 def __repr__(self):
672 return 'r_singlefloat(%s)' % (float(self),)
673
674 class r_longfloat(object):
675 """A value of the C type 'long double'.
676
677 Note that we consider this as a black box for now - the only thing
678 you can do with it is cast it back to a regular float."""
679
680 def __init__(self, floatval):
681 self.value = floatval
682
683 def __float__(self):
684 return self.value
685
686 def __nonzero__(self):
687 raise TypeError("not supported on r_longfloat instances")
688
689 def __cmp__(self, other):
690 raise TypeError("not supported on r_longfloat instances")
691
692 def __eq__(self, other):
693 return self.__class__ is other.__class__ and self.value == other.value
694
695 def __ne__(self, other):
696 return not self.__eq__(other)
697
698 def __hash__(self):
699 return hash(self.value)
700
701
702 class For_r_singlefloat_values_Entry(extregistry.ExtRegistryEntry):
703 _type_ = r_singlefloat
704
705 def compute_annotation(self):
706 from rpython.annotator import model as annmodel
707 return annmodel.SomeSingleFloat()
708
709 class For_r_singlefloat_type_Entry(extregistry.ExtRegistryEntry):
710 _about_ = r_singlefloat
711
712 def compute_result_annotation(self, *args_s, **kwds_s):
713 from rpython.annotator import model as annmodel
714 return annmodel.SomeSingleFloat()
715
716 def specialize_call(self, hop):
717 from rpython.rtyper.lltypesystem import lltype
718 v, = hop.inputargs(lltype.Float)
719 hop.exception_cannot_occur()
720 # we use cast_primitive to go between Float and SingleFloat.
721 return hop.genop('cast_primitive', [v],
722 resulttype = lltype.SingleFloat)
723
724 class For_r_longfloat_values_Entry(extregistry.ExtRegistryEntry):
725 _type_ = r_longfloat
726
727 def compute_annotation(self):
728 from rpython.annotator import model as annmodel
729 return annmodel.SomeLongFloat()
730
731
732 def int_between(n, m, p):
733 """ check that n <= m < p. This assumes that n <= p. This is useful because
734 the JIT special-cases it. """
735 from rpython.rtyper.lltypesystem import lltype
736 from rpython.rtyper.lltypesystem.lloperation import llop
737 if not objectmodel.we_are_translated():
738 assert n <= p
739 return llop.int_between(lltype.Bool, n, m, p)
740
741 def int_force_ge_zero(n):
742 """ The JIT special-cases this too. """
743 from rpython.rtyper.lltypesystem import lltype
744 from rpython.rtyper.lltypesystem.lloperation import llop
745 n = llop.int_force_ge_zero(lltype.Signed, n)
746 assert n >= 0
747 return n
748
749 def int_c_div(x, y):
750 """Return the result of the C-style 'x / y'. This differs from the
751 Python-style division if (x < 0 xor y < 0). The JIT implements it
752 with a Python-style division followed by correction code. This
753 is not that bad, because the JIT removes the correction code if
754 x and y are both nonnegative, and if y is any nonnegative constant
755 then the division turns into a rshift or a mul.
756 """
757 from rpython.rtyper.lltypesystem import lltype
758 from rpython.rtyper.lltypesystem.lloperation import llop
759 return llop.int_floordiv(lltype.Signed, x, y)
760
761 def int_c_mod(x, y):
762 """Return the result of the C-style 'x % y'. This differs from the
763 Python-style division if (x < 0 xor y < 0).
764 """
765 from rpython.rtyper.lltypesystem import lltype
766 from rpython.rtyper.lltypesystem.lloperation import llop
767 return llop.int_mod(lltype.Signed, x, y)
768
769 @specialize.ll()
770 def byteswap(arg):
771 """ Convert little->big endian and the opposite
772 """
773 from rpython.rtyper.lltypesystem import lltype, rffi
774 from rpython.rlib.longlong2float import longlong2float, float2longlong,\
775 uint2singlefloat, singlefloat2uint
776
777 T = lltype.typeOf(arg)
778 if T == lltype.SingleFloat:
779 arg = singlefloat2uint(arg)
780 elif T == lltype.Float:
781 arg = float2longlong(arg)
782 elif T == lltype.LongFloat:
783 assert False
784 else:
785 # we cannot do arithmetics on small ints
786 arg = widen(arg)
787
788 if rffi.sizeof(T) == 1:
789 res = arg
790 elif rffi.sizeof(T) == 2:
791 a, b = arg & 0xFF, arg & 0xFF00
792 res = (a << 8) | (b >> 8)
793 elif rffi.sizeof(T) == 4:
794 FF = r_uint(0xFF)
795 arg = r_uint(arg)
796 a, b, c, d = (arg & FF, arg & (FF << 8), arg & (FF << 16),
797 arg & (FF << 24))
798 res = (a << 24) | (b << 8) | (c >> 8) | (d >> 24)
799 elif rffi.sizeof(T) == 8:
800 FF = r_ulonglong(0xFF)
801 arg = r_ulonglong(arg)
802 a, b, c, d = (arg & FF, arg & (FF << 8), arg & (FF << 16),
803 arg & (FF << 24))
804 e, f, g, h = (arg & (FF << 32), arg & (FF << 40), arg & (FF << 48),
805 arg & (FF << 56))
806 res = ((a << 56) | (b << 40) | (c << 24) | (d << 8) | (e >> 8) |
807 (f >> 24) | (g >> 40) | (h >> 56))
808 else:
809 assert False # unreachable code
810
811 if T == lltype.SingleFloat:
812 return uint2singlefloat(rffi.cast(rffi.UINT, res))
813 if T == lltype.Float:
814 return longlong2float(rffi.cast(rffi.LONGLONG, res))
815 return rffi.cast(T, res)
816
817 if sys.maxint == 2147483647:
818 def ovfcheck_int32_add(x, y):
819 return ovfcheck(x + y)
820 def ovfcheck_int32_sub(x, y):
821 return ovfcheck(x - y)
822 def ovfcheck_int32_mul(x, y):
823 return ovfcheck(x * y)
824 else:
825 def ovfcheck_int32_add(x, y):
826 """x and y are assumed to fit inside the 32-bit rffi.INT;
827 raises OverflowError if the result doesn't fit rffi.INT"""
828 from rpython.rtyper.lltypesystem import lltype, rffi
829 x = rffi.cast(lltype.Signed, x)
830 y = rffi.cast(lltype.Signed, y)
831 z = x + y
832 if z != rffi.cast(lltype.Signed, rffi.cast(rffi.INT, z)):
833 raise OverflowError
834 return z
835
836 def ovfcheck_int32_sub(x, y):
837 """x and y are assumed to fit inside the 32-bit rffi.INT;
838 raises OverflowError if the result doesn't fit rffi.INT"""
839 from rpython.rtyper.lltypesystem import lltype, rffi
840 x = rffi.cast(lltype.Signed, x)
841 y = rffi.cast(lltype.Signed, y)
842 z = x - y
843 if z != rffi.cast(lltype.Signed, rffi.cast(rffi.INT, z)):
844 raise OverflowError
845 return z
846
847 def ovfcheck_int32_mul(x, y):
848 """x and y are assumed to fit inside the 32-bit rffi.INT;
849 raises OverflowError if the result doesn't fit rffi.INT"""
850 from rpython.rtyper.lltypesystem import lltype, rffi
851 x = rffi.cast(lltype.Signed, x)
852 y = rffi.cast(lltype.Signed, y)
853 z = x * y
854 if z != rffi.cast(lltype.Signed, rffi.cast(rffi.INT, z)):
855 raise OverflowError
856 return z
857
858
859 @specialize.memo()
860 def check_support_int128():
861 from rpython.rtyper.lltypesystem import rffi
862 return hasattr(rffi, '__INT128_T')
863
864 def mulmod(a, b, c):
865 """Computes (a * b) % c.
866 Assumes c > 0, and returns a nonnegative result.
867 """
868 assert c > 0
869 if LONG_BIT < LONGLONG_BIT:
870 a = r_longlong(a)
871 b = r_longlong(b)
872 return intmask((a * b) % c)
873 elif check_support_int128():
874 a = r_longlonglong(a)
875 b = r_longlonglong(b)
876 return intmask((a * b) % c)
877 else:
878 from rpython.rlib.rbigint import rbigint
879 a = rbigint.fromint(a)
880 return a.int_mul(b).int_mod(c).toint()
881
882 def uint_mul_high(a, b):
883 """ Computes the high word of the unsigned multiplication a * b """
884 if LONG_BIT < LONGLONG_BIT:
885 a = r_ulonglong(a)
886 b = r_ulonglong(b)
887 return r_uint((a * b) >> LONG_BIT)
888 elif check_support_int128():
889 a = r_ulonglonglong(a)
890 b = r_ulonglonglong(b)
891 return r_uint((a * b) >> LONG_BIT)
892 else:
893 return _uint_mul_high(a, b)
894 # can't use decorator due to recursive imports
895 uint_mul_high.oopspec = "int.uint_mul_high(a, b)"
896
897 def _uint_mul_high(a, b):
898 DIGIT = LONG_BIT / 2
899 MASK = (1 << DIGIT) - 1
900
901 ah = a >> DIGIT
902 al = a & MASK
903 bh = b >> DIGIT
904 bl = b & MASK
905
906 rll = al * bl; assert rll == r_uint(rll)
907 rlh = al * bh; assert rlh == r_uint(rlh)
908 rhl = ah * bl; assert rhl == r_uint(rhl)
909 rhh = ah * bh; assert rhh == r_uint(rhh)
910
911 r1 = (rll >> DIGIT) + rhl
912 assert r1 == r_uint(r1)
913
914 r1 = r_uint(r1)
915 r2 = r_uint(r1 + rlh)
916 borrow = r_uint(r2 < r1) << DIGIT
917
918 r3 = (r2 >> DIGIT) + borrow + r_uint(rhh)
919 return r3
920
921 # String parsing support
922 # ---------------------------
923
924 OVF_DIGITS = len(str(sys.maxint))
925
926 def string_to_int(s, base=10, allow_underscores=False, no_implicit_octal=False,
927 max_str_digits=0, disallow_whitespace_after_sign=False):
928 """Utility to converts a string to an integer.
929 If base is 0, the proper base is guessed based on the leading
930 characters of 's'. Raises ParseStringError in case of error.
931 Raises ParseStringOverflowError in case the result does not fit.
932 """
933 from rpython.rlib.rstring import (
934 NumberStringParser, ParseStringOverflowError)
935
936 if base == 10 and 0 < len(s) < OVF_DIGITS:
937 # fast path for simple cases, just supporting (+/-)[0-9]* with not too
938 # many digits
939 start = 0
940 sign = 1
941 if s[0] == "-":
942 start = 1
943 sign = -1
944 elif s[0] == "+":
945 start = 1
946 if start != len(s):
947 result = 0
948 for i in range(start, len(s)):
949 char = s[i]
950 value = ord(char) - ord('0')
951 if 0 <= value <= 9:
952 result = result * 10 + value
953 else:
954 # non digit char, let the NumberStringParser do the work
955 break
956 else:
957 return result * sign
958
959 p = NumberStringParser(s, s, base, 'int',
960 allow_underscores=allow_underscores,
961 no_implicit_octal=no_implicit_octal,
962 max_str_digits=max_str_digits,
963 disallow_whitespace_after_sign=disallow_whitespace_after_sign)
964 base = p.base
965 result = 0
966 while True:
967 digit = p.next_digit()
968 if digit == -1:
969 return result
970
971 if p.sign == -1:
972 digit = -digit
973
974 try:
975 result = ovfcheck(result * base)
976 result = ovfcheck(result + digit)
977 except OverflowError:
978 raise ParseStringOverflowError(p)
979 string_to_int._elidable_function_ = True # can't use decorator due to circular imports