Debian Codegraph @

rpython/jit/metainterp/resoperation.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import weakref, os
4 from rpython.rlib.objectmodel import we_are_translated, specialize
5 from rpython.rtyper.lltypesystem.lloperation import llop
6 from rpython.rlib.objectmodel import compute_identity_hash
7 from rpython.rtyper.lltypesystem import lltype, llmemory
8 from rpython.jit.codewriter import longlong
9 from rpython.jit.backend.llsupport.symbolic import (WORD as INT_WORD,
10 SIZEOF_FLOAT as FLOAT_WORD)
11
12 class SettingForwardedOnAbstractValue(Exception):
13 pass
14
15 class CountingDict(object):
16 def __init__(self):
17 self._d = weakref.WeakKeyDictionary()
18 self.counter = 0
19
20 def __getitem__(self, item):
21 try:
22 return self._d[item]
23 except KeyError:
24 c = self.counter
25 self.counter += 1
26 self._d[item] = c
27 return c
28
29 class AbstractValue(object):
30 _repr_memo = CountingDict()
31 is_info_class = False
32 namespace = None
33 _attrs_ = ()
34
35 def _get_hash_(self):
36 return compute_identity_hash(self)
37
38 def same_box(self, other):
39 return self is other
40
41 def same_shape(self, other):
42 return True
43
44 def repr_short(self, memo):
45 return self.repr(memo)
46
47 def is_constant(self):
48 return False
49
50 def get_forwarded(self):
51 return None
52
53 def set_forwarded(self, forwarded_to):
54 llop.debug_print(lltype.Void, "setting forwarded on:", self.__class__.__name__)
55 raise SettingForwardedOnAbstractValue()
56
57 @specialize.arg(1)
58 def get_box_replacement(op, not_const=False):
59 # Read the chain "op, op._forwarded, op._forwarded._forwarded..."
60 # until we reach None or an Info instance, and return the last
61 # item before that.
62 while isinstance(op, AbstractResOpOrInputArg): # else, _forwarded is None
63 next_op = op._forwarded
64 if (next_op is None or next_op.is_info_class or
65 (not_const and next_op.is_constant())):
66 return op
67 op = next_op
68 return op
69
70 def reset_value(self):
71 pass
72
73 def is_inputarg(self):
74 return False
75
76 def returns_vector(self):
77 return False
78
79 def is_vector(self):
80 return False
81
82 def returns_void(self):
83 return False
84
85
86 def ResOperation(opnum, args, descr=None):
87 cls = opclasses[opnum]
88 op = cls()
89 op.initarglist(args)
90 if descr is not None:
91 assert isinstance(op, ResOpWithDescr)
92 if opnum == rop.FINISH:
93 assert descr.final_descr
94 elif OpHelpers.is_guard(opnum):
95 assert not descr.final_descr
96 op.setdescr(descr)
97 return op
98
99 def VecOperation(opnum, args, baseop, count, descr=None):
100 vecinfo = baseop.get_forwarded()
101 assert isinstance(vecinfo, VectorizationInfo)
102 datatype = vecinfo.datatype
103 bytesize = vecinfo.bytesize
104 signed = vecinfo.signed
105 if baseop.is_typecast():
106 ft,tt = baseop.cast_types()
107 datatype = tt
108 bytesize = baseop.cast_to_bytesize()
109 return VecOperationNew(opnum, args, datatype, bytesize, signed, count, descr)
110
111 def VecOperationNew(opnum, args, datatype, bytesize, signed, count, descr=None):
112 op = ResOperation(opnum, args, descr=descr)
113 vecinfo = VectorizationInfo(None)
114 vecinfo.setinfo(datatype, bytesize, signed)
115 vecinfo.count = count
116 op.set_forwarded(vecinfo)
117 if isinstance(op,VectorOp):
118 op.datatype = datatype
119 op.bytesize = bytesize
120 op.signed = signed
121 op.count = count
122 else:
123 assert isinstance(op, VectorGuardOp)
124 op.datatype = datatype
125 op.bytesize = bytesize
126 op.signed = signed
127 op.count = count
128 assert op.count > 0
129
130 if not we_are_translated():
131 # for the test suite
132 op._vec_debug_info = vecinfo
133 return op
134
135 def vector_repr(self, num):
136 if we_are_translated():
137 # the set_forwarded solution is volatile, we CANNOT acquire
138 # the information (e.g. count, bytesize) here easily
139 return 'v' + str(num)
140 if hasattr(self, '_vec_debug_info'):
141 vecinfo = self._vec_debug_info
142 count = vecinfo.count
143 datatype = vecinfo.datatype
144 bytesize = vecinfo.bytesize
145 elif self.vector == -2:
146 count = self.count
147 datatype = self.datatype
148 bytesize = self.bytesize
149 else:
150 assert 0, "cannot debug print variable"
151 if self.opnum in (rop.VEC_UNPACK_I, rop.VEC_UNPACK_F):
152 return self.type + str(num)
153 return 'v%d[%dx%s%d]' % (num, count, datatype,
154 bytesize * 8)
155
156 class VectorizationInfo(AbstractValue):
157 _attrs_ = ('datatype', 'bytesize', 'signed', 'count')
158 datatype = '\x00'
159 bytesize = -1 # -1 means the biggest size known to the machine
160 signed = True
161 count = -1
162
163 def __init__(self, op):
164 if op is None:
165 return
166 from rpython.jit.metainterp.history import Const
167 if isinstance(op, Const) or isinstance(op, AbstractInputArg):
168 self.setinfo(op.type, -1, op.type == 'i')
169 return
170 if op.is_primitive_array_access():
171 from rpython.jit.backend.llsupport.descr import ArrayDescr
172 descr = op.getdescr()
173 if not we_are_translated():
174 from rpython.jit.backend.llgraph.runner import _getdescr
175 descr = _getdescr(op)
176 type = op.type
177 bytesize = descr.get_item_size_in_bytes()
178 signed = descr.is_item_signed()
179 datatype = type
180 self.setinfo(datatype, bytesize, signed)
181 elif op.opnum == rop.INT_SIGNEXT:
182 from rpython.jit.metainterp import history
183 arg0 = op.getarg(0)
184 arg1 = op.getarg(1)
185 assert isinstance(arg1, history.ConstInt)
186 self.setinfo('i', arg1.value, True)
187 elif op.is_typecast():
188 ft,tt = op.cast_types()
189 bytesize = op.cast_to_bytesize()
190 self.setinfo(tt, bytesize, True)
191 else:
192 # pass through the type of the first input argument
193 type = op.type
194 signed = type == 'i'
195 bytesize = -1
196 if op.numargs() > 0:
197 i = 0
198 arg = op.getarg(i)
199 while arg.is_constant() and i+1 < op.numargs():
200 i += 1
201 arg = op.getarg(i)
202 if not arg.is_constant():
203 vecinfo = arg.get_forwarded()
204 if vecinfo is not None and isinstance(vecinfo, VectorizationInfo):
205 if vecinfo.datatype != '\x00' and \
206 vecinfo.bytesize != -1:
207 type = vecinfo.datatype
208 signed = vecinfo.signed
209 bytesize = vecinfo.bytesize
210 if rop.returns_bool_result(op.opnum):
211 type = 'i'
212 self.setinfo(type, bytesize, signed)
213
214 def setinfo(self, datatype, bytesize, signed):
215 self.datatype = datatype
216 if bytesize == -1:
217 if datatype == 'i':
218 bytesize = INT_WORD
219 elif datatype == 'f':
220 bytesize = FLOAT_WORD
221 elif datatype == 'r':
222 bytesize = INT_WORD
223 elif datatype == 'v':
224 bytesize = 0
225 elif datatype == 'V': # input arg vector
226 bytesize = INT_WORD
227 else:
228 assert 0, "unknown datasize"
229 self.bytesize = bytesize
230 self.signed = signed
231
232
233 class AbstractResOpOrInputArg(AbstractValue):
234 _attrs_ = ('_forwarded',)
235 _forwarded = None # either another resop or OptInfo
236
237 def get_forwarded(self):
238 return self._forwarded
239
240 def set_forwarded(self, forwarded_to):
241 assert forwarded_to is not self
242 self._forwarded = forwarded_to
243
244 def getdescr(self):
245 return None
246
247 def forget_value(self):
248 pass
249
250 class AbstractResOp(AbstractResOpOrInputArg):
251 """The central ResOperation class, representing one operation."""
252
253 _attrs_ = ()
254
255 # debug
256 name = ""
257 pc = 0
258 opnum = 0
259 _cls_has_bool_result = False
260 type = 'v'
261 boolreflex = -1
262 boolinverse = -1
263 vector = -1 # -1 means, no vector equivalent, -2 it is a vector statement
264 cls_casts = ('\x00', -1, '\x00', -1, -1)
265
266 def getopnum(self):
267 return self.opnum
268
269 #def same_box(self, other):
270 # if self.is_same_as():
271 # return self is other or self.getarg(0).same_box(other)
272 # return self is other
273
274 # methods implemented by the arity mixins
275 # ---------------------------------------
276
277 def initarglist(self, args):
278 "This is supposed to be called only just after the ResOp has been created"
279 raise NotImplementedError
280
281 def getarglist(self):
282 raise NotImplementedError
283
284 def getarglist_copy(self):
285 return self.getarglist()
286
287 def getarg(self, i):
288 raise NotImplementedError
289
290 def setarg(self, i, box):
291 raise NotImplementedError
292
293 def numargs(self):
294 raise NotImplementedError
295
296 # methods implemented by GuardResOp
297 # ---------------------------------
298
299 def getfailargs(self):
300 return None
301
302 def setfailargs(self, fail_args):
303 raise NotImplementedError
304
305 # methods implemented by ResOpWithDescr
306 # -------------------------------------
307
308 #def getdescr(self): -- in the base class, AbstractResOpOrInputArg
309 # return None
310
311 def setdescr(self, descr):
312 raise NotImplementedError
313
314 def cleardescr(self):
315 pass
316
317 # common methods
318 # --------------
319
320 def copy(self):
321 return self.copy_and_change(self.opnum)
322
323 def copy_and_change(self, opnum, args=None, descr=None):
324 "shallow copy: the returned operation is meant to be used in place of self"
325 # XXX specialize
326 from rpython.jit.metainterp.history import DONT_CHANGE
327
328 if args is None:
329 args = self.getarglist_copy()
330 if descr is None:
331 descr = self.getdescr()
332 if descr is DONT_CHANGE:
333 descr = None
334 return ResOperation(opnum, args, descr)
335
336 def repr(self, memo, graytext=False):
337 # RPython-friendly version
338 if self.type != 'v':
339 try:
340 num = memo[self]
341 except KeyError:
342 num = len(memo)
343 memo[self] = num
344 if self.is_vector():
345 sres = vector_repr(self, num) + ' = '
346 else:
347 sres = self.type + str(num) + ' = '
348 #if self.result is not None:
349 # sres = '%s = ' % (self.result,)
350 else:
351 sres = ''
352 if self.name:
353 prefix = "%s:%s " % (self.name, self.pc)
354 if graytext:
355 prefix = "\f%s\f" % prefix
356 else:
357 prefix = ""
358 args = self.getarglist()
359 descr = self.getdescr()
360 if descr is None or we_are_translated():
361 s = '%s%s%s(%s)' % (prefix, sres, self.getopname(),
362 ', '.join([a.repr_short(memo) for a in args]))
363 else:
364 s = '%s%s%s(%s)' % (prefix, sres, self.getopname(),
365 ', '.join([a.repr_short(memo) for a in args] +
366 ['descr=%r' % descr]))
367 # --- enable to display the failargs too:
368 #if isinstance(self, GuardResOp):
369 # s += ' [%s]' % (', '.join([a.repr_short(memo) for a in
370 # self.getfailargs()]),)
371 return s
372
373 def repr_short(self, memo):
374 try:
375 num = memo[self]
376 except KeyError:
377 num = len(memo)
378 memo[self] = num
379 if self.is_vector():
380 return vector_repr(self, num)
381 return self.type + str(num)
382
383 def __repr__(self):
384 r = self.repr(self._repr_memo)
385 if self.namespace is not None:
386 return "<" + self.namespace + ">" + r
387 return r
388
389 def getopname(self):
390 try:
391 return opname[self.getopnum()].lower()
392 except KeyError:
393 return '<%d>' % self.getopnum()
394
395 def is_guard(self):
396 return rop.is_guard(self.getopnum())
397
398 def is_ovf(self):
399 return rop.is_ovf(self.getopnum())
400
401 def can_raise(self):
402 return rop.can_raise(self.getopnum())
403
404 def is_foldable_guard(self):
405 return rop.is_foldable_guard(self.getopnum())
406
407 def is_primitive_array_access(self):
408 """ Indicates that this operations loads/stores a
409 primitive type (int,float) """
410 if rop.is_primitive_load(self.opnum) or rop.is_primitive_store(self.opnum):
411 descr = self.getdescr()
412 if not we_are_translated():
413 from rpython.jit.backend.llgraph.runner import _getdescr
414 descr = _getdescr(self)
415 if descr and descr.is_array_of_primitives():
416 return True
417 return False
418
419 def is_vector(self):
420 return False
421
422 def returns_void(self):
423 return self.type == 'v'
424
425 def returns_vector(self):
426 return self.type != 'v' and self.vector == -2
427
428 def is_typecast(self):
429 return False
430
431 def cast_count(self, vec_reg_size):
432 return self.cls_casts[4]
433
434 def cast_types(self):
435 return self.cls_casts[0], self.cls_casts[2]
436
437 def cast_to_bytesize(self):
438 return self.cls_casts[3]
439
440 def cast_from_bytesize(self):
441 return self.cls_casts[1]
442
443 def casts_up(self):
444 return self.cast_to_bytesize() > self.cast_from_bytesize()
445
446 def casts_down(self):
447 # includes the cast as noop
448 return self.cast_to_bytesize() <= self.cast_from_bytesize()
449
450 # ===================
451 # Top of the hierachy
452 # ===================
453
454 class PlainResOp(AbstractResOp):
455 pass
456
457
458 class ResOpWithDescr(AbstractResOp):
459
460 _descr = None
461
462 def getdescr(self):
463 return self._descr
464
465 def setdescr(self, descr):
466 # for 'call', 'new', 'getfield_gc'...: the descr is a prebuilt
467 # instance provided by the backend holding details about the type
468 # of the operation. It must inherit from AbstractDescr. The
469 # backend provides it with cpu.fielddescrof(), cpu.arraydescrof(),
470 # cpu.calldescrof(), and cpu.typedescrof().
471 self._check_descr(descr)
472 self._descr = descr
473
474 def cleardescr(self):
475 self._descr = None
476
477 def _check_descr(self, descr):
478 if not we_are_translated() and getattr(descr, 'I_am_a_descr', False):
479 return # needed for the mock case in oparser_model
480 from rpython.jit.metainterp.history import check_descr
481 check_descr(descr)
482
483
484 class GuardResOp(ResOpWithDescr):
485
486 _fail_args = None
487 rd_resume_position = -1
488
489 def getfailargs(self):
490 return self._fail_args
491
492 def getfailargs_copy(self):
493 return self._fail_args[:]
494
495 def setfailargs(self, fail_args):
496 self._fail_args = fail_args
497
498 def copy_and_change(self, opnum, args=None, descr=None):
499 newop = AbstractResOp.copy_and_change(self, opnum, args, descr)
500 assert isinstance(newop, GuardResOp)
501 newop.setfailargs(self.getfailargs())
502 newop.rd_resume_position = self.rd_resume_position
503 return newop
504
505 class VectorGuardOp(GuardResOp):
506 bytesize = 0
507 datatype = '\x00'
508 signed = True
509 count = 0
510
511 def copy_and_change(self, opnum, args=None, descr=None):
512 newop = GuardResOp.copy_and_change(self, opnum, args, descr)
513 assert isinstance(newop, VectorGuardOp)
514 newop.datatype = self.datatype
515 newop.bytesize = self.bytesize
516 newop.signed = self.signed
517 newop.count = self.count
518 return newop
519
520 class VectorOp(ResOpWithDescr):
521 bytesize = 0
522 datatype = '\x00'
523 signed = True
524 count = 0
525
526 def is_vector(self):
527 if self.getopnum() in (rop.VEC_UNPACK_I, rop.VEC_UNPACK_F):
528 arg = self.getarg(2)
529 from rpython.jit.metainterp.history import ConstInt
530 assert isinstance(arg, ConstInt)
531 return arg.value > 1
532 return True
533
534 def copy_and_change(self, opnum, args=None, descr=None):
535 newop = ResOpWithDescr.copy_and_change(self, opnum, args, descr)
536 assert isinstance(newop, VectorOp)
537 newop.datatype = self.datatype
538 newop.bytesize = self.bytesize
539 newop.signed = self.signed
540 newop.count = self.count
541 return newop
542
543 def same_shape(self, other):
544 """ NOT_RPYTHON """
545 myvecinfo = self.get_forwarded()
546 othervecinfo = other.get_forwarded()
547 if other.is_vector() != self.is_vector():
548 return False
549 if myvecinfo.datatype != othervecinfo.datatype:
550 return False
551 if myvecinfo.bytesize != othervecinfo.bytesize:
552 return False
553 if myvecinfo.signed != othervecinfo.signed:
554 return False
555 if myvecinfo.count != othervecinfo.count:
556 return False
557 return True
558
559
560 # ===========
561 # type mixins
562 # ===========
563
564 class IntOp(object):
565 _mixin_ = True
566
567 type = 'i'
568
569 _resint = 0
570
571 def getint(self):
572 return self._resint
573
574 getvalue = getint
575
576 def setint(self, intval):
577 self._resint = intval
578
579 def constbox(self):
580 from rpython.jit.metainterp import history
581 return history.ConstInt(self.getint())
582
583 def nonnull(self):
584 return self._resint != 0
585
586 class FloatOp(object):
587 _mixin_ = True
588
589 type = 'f'
590
591 _resfloat = longlong.ZEROF
592
593 def getfloatstorage(self):
594 return self._resfloat
595
596 getvalue = getfloatstorage
597
598 def getfloat(self):
599 return longlong.getrealfloat(self.getfloatstorage())
600
601 def setfloatstorage(self, floatval):
602 assert lltype.typeOf(floatval) is longlong.FLOATSTORAGE
603 self._resfloat = floatval
604
605 def constbox(self):
606 from rpython.jit.metainterp import history
607 return history.ConstFloat(self.getfloatstorage())
608
609 def nonnull(self):
610 return bool(longlong.extract_bits(self._resfloat))
611
612 class RefOp(object):
613 _mixin_ = True
614
615 type = 'r'
616
617 _resref = lltype.nullptr(llmemory.GCREF.TO)
618
619 def getref_base(self):
620 return self._resref
621
622 def reset_value(self):
623 self.setref_base(lltype.nullptr(llmemory.GCREF.TO))
624
625 getvalue = getref_base
626
627 def forget_value(self):
628 self._resref = lltype.nullptr(llmemory.GCREF.TO)
629
630 def setref_base(self, refval):
631 self._resref = refval
632
633 def getref(self, PTR):
634 return lltype.cast_opaque_ptr(PTR, self.getref_base())
635 getref._annspecialcase_ = 'specialize:arg(1)'
636
637 def nonnull(self):
638 return bool(self._resref)
639
640 def constbox(self):
641 from rpython.jit.metainterp import history
642 return history.ConstPtr(self.getref_base())
643
644 class CastOp(object):
645 _mixin_ = True
646
647 def is_typecast(self):
648 return True
649
650 def cast_to(self):
651 to_type, size = self.cls_casts[2], self.cls_casts[3]
652 if self.cls_casts[3] == 0:
653 if self.getopnum() == rop.INT_SIGNEXT:
654 from rpython.jit.metainterp.history import ConstInt
655 arg = self.getarg(1)
656 assert isinstance(arg, ConstInt)
657 return (to_type,arg.value)
658 else:
659 raise NotImplementedError
660 return (to_type,size)
661
662 def cast_from(self):
663 type, size, a, b = self.cls_casts
664 if size == -1:
665 return self.bytesize
666 return (type, size)
667
668 def cast_input_bytesize(self, vec_reg_size):
669 count = vec_reg_size // self.cast_to_bytesize()
670 size = self.cast_from_bytesize() * self.cast_count(vec_reg_size)
671 return size
672
673 class SignExtOp(object):
674 _mixin_ = True
675
676 def is_typecast(self):
677 return True
678
679 def cast_types(self):
680 return self.cls_casts[0], self.cls_casts[2]
681
682 def cast_to_bytesize(self):
683 from rpython.jit.metainterp.history import ConstInt
684 arg = self.getarg(1)
685 assert isinstance(arg, ConstInt)
686 return arg.value
687
688 def cast_from_bytesize(self):
689 arg = self.getarg(0)
690 vecinfo = arg.get_forwarded()
691 if vecinfo is None or not isinstance(vecinfo, VectorizationInfo):
692 vecinfo = VectorizationInfo(arg)
693 return vecinfo.bytesize
694
695 def cast_input_bytesize(self, vec_reg_size):
696 return vec_reg_size # self.cast_from_bytesize() * self.cast_count(vec_reg_size)
697
698
699 class AbstractInputArg(AbstractResOpOrInputArg):
700 _attrs_ = ('_forwarded', 'position')
701
702 def repr(self, memo):
703 try:
704 num = memo[self]
705 except KeyError:
706 num = len(memo)
707 memo[self] = num
708 return self.type + str(num)
709
710 def get_position(self):
711 return self.position
712
713 def __repr__(self):
714 return self.repr(self._repr_memo)
715
716 def is_inputarg(self):
717 return True
718
719 class InputArgInt(IntOp, AbstractInputArg):
720 datatype = 'i'
721 bytesize = INT_WORD
722 signed = True
723
724 def __init__(self, intval=0):
725 self.setint(intval)
726
727 class InputArgFloat(FloatOp, AbstractInputArg):
728 datatype = 'f'
729 bytesize = FLOAT_WORD
730 signed = True
731
732 def __init__(self, f=longlong.ZEROF):
733 self.setfloatstorage(f)
734
735 @staticmethod
736 def fromfloat(x):
737 return InputArgFloat(longlong.getfloatstorage(x))
738
739 class InputArgRef(RefOp, AbstractInputArg):
740 datatype = 'r'
741
742 def __init__(self, r=lltype.nullptr(llmemory.GCREF.TO)):
743 self.setref_base(r)
744
745 def reset_value(self):
746 self.setref_base(lltype.nullptr(llmemory.GCREF.TO))
747
748 class InputArgVector(AbstractInputArg):
749 type = 'V'
750 def __init__(self):
751 pass
752
753 def returns_vector(self):
754 return True
755
756 # ============
757 # arity mixins
758 # ============
759
760 class NullaryOp(object):
761 _mixin_ = True
762
763 def initarglist(self, args):
764 assert len(args) == 0
765
766 def getarglist(self):
767 return []
768
769 def numargs(self):
770 return 0
771
772 def getarg(self, i):
773 raise IndexError
774
775 def setarg(self, i, box):
776 raise IndexError
777
778
779 class UnaryOp(object):
780 _mixin_ = True
781 _arg0 = None
782
783 def initarglist(self, args):
784 assert len(args) == 1
785 self._arg0, = args
786
787 def getarglist(self):
788 return [self._arg0]
789
790 def numargs(self):
791 return 1
792
793 def getarg(self, i):
794 if i == 0:
795 return self._arg0
796 else:
797 raise IndexError
798
799 def setarg(self, i, box):
800 if i == 0:
801 self._arg0 = box
802 else:
803 raise IndexError
804
805 class BinaryOp(object):
806 _mixin_ = True
807 _arg0 = None
808 _arg1 = None
809
810 def initarglist(self, args):
811 assert len(args) == 2
812 self._arg0, self._arg1 = args
813
814 def numargs(self):
815 return 2
816
817 def getarg(self, i):
818 if i == 0:
819 return self._arg0
820 elif i == 1:
821 return self._arg1
822 else:
823 raise IndexError
824
825 def setarg(self, i, box):
826 if i == 0:
827 self._arg0 = box
828 elif i == 1:
829 self._arg1 = box
830 else:
831 raise IndexError
832
833 def getarglist(self):
834 return [self._arg0, self._arg1]
835
836
837 class TernaryOp(object):
838 _mixin_ = True
839 _arg0 = None
840 _arg1 = None
841 _arg2 = None
842
843 def initarglist(self, args):
844 assert len(args) == 3
845 self._arg0, self._arg1, self._arg2 = args
846
847 def getarglist(self):
848 return [self._arg0, self._arg1, self._arg2]
849
850 def numargs(self):
851 return 3
852
853 def getarg(self, i):
854 if i == 0:
855 return self._arg0
856 elif i == 1:
857 return self._arg1
858 elif i == 2:
859 return self._arg2
860 else:
861 raise IndexError
862
863 def setarg(self, i, box):
864 if i == 0:
865 self._arg0 = box
866 elif i == 1:
867 self._arg1 = box
868 elif i == 2:
869 self._arg2 = box
870 else:
871 raise IndexError
872
873
874 class N_aryOp(object):
875 _mixin_ = True
876 _args = None
877
878 def initarglist(self, args):
879 self._args = args
880 if not we_are_translated() and \
881 self.__class__.__name__.startswith('FINISH'): # XXX remove me
882 assert len(args) <= 1 # FINISH operations take 0 or 1 arg now
883
884 def getarglist(self):
885 return self._args
886
887 def getarglist_copy(self):
888 return self._args[:]
889
890 def numargs(self):
891 return len(self._args)
892
893 def getarg(self, i):
894 return self._args[i]
895
896 def setarg(self, i, box):
897 self._args[i] = box
898
899
900 # ____________________________________________________________
901
902 """ All the operations are desribed like this:
903
904 NAME/no-of-args-or-*[b][d]/types-of-result
905
906 if b is present it means the operation produces a boolean
907 if d is present it means there is a descr
908 type of result can be one or more of r i f n
909 """
910
911 _oplist = [
912 '_FINAL_FIRST',
913 'JUMP/*d/n',
914 'FINISH/*d/n',
915 '_FINAL_LAST',
916
917 'LABEL/*d/n',
918
919 '_GUARD_FIRST',
920 '_GUARD_FOLDABLE_FIRST',
921 'GUARD_TRUE/1d/n',
922 'GUARD_FALSE/1d/n',
923 'VEC_GUARD_TRUE/1d/n',
924 'VEC_GUARD_FALSE/1d/n',
925 'GUARD_VALUE/2d/n',
926 'GUARD_CLASS/2d/n',
927 'GUARD_NONNULL/1d/n',
928 'GUARD_ISNULL/1d/n',
929 'GUARD_NONNULL_CLASS/2d/n',
930 'GUARD_GC_TYPE/2d/n', # only if supports_guard_gc_type
931 'GUARD_IS_OBJECT/1d/n', # only if supports_guard_gc_type
932 'GUARD_SUBCLASS/2d/n', # only if supports_guard_gc_type
933 '_GUARD_FOLDABLE_LAST',
934 'GUARD_NO_EXCEPTION/0d/n', # may be called with an exception currently set
935 'GUARD_EXCEPTION/1d/r', # XXX kill me, use only SAVE_EXCEPTION
936 'GUARD_NO_OVERFLOW/0d/n',
937 'GUARD_OVERFLOW/0d/n',
938 'GUARD_NOT_FORCED/0d/n', # may be called with an exception currently set
939 'GUARD_NOT_FORCED_2/0d/n', # same as GUARD_NOT_FORCED, but for finish()
940 'GUARD_NOT_INVALIDATED/0d/n',
941 'GUARD_FUTURE_CONDITION/0d/n',
942 'GUARD_ALWAYS_FAILS/0d/n', # to end really long traces
943 # is removable, may be patched by an optimization
944 '_GUARD_LAST', # ----- end of guard operations -----
945
946 '_NOSIDEEFFECT_FIRST', # ----- start of no_side_effect operations -----
947 '_ALWAYS_PURE_FIRST', # ----- start of always_pure operations -----
948 'INT_ADD/2/i',
949 'INT_SUB/2/i',
950 'INT_MUL/2/i',
951 'UINT_MUL_HIGH/2/i', # a * b as a double-word, keep the high word
952 'INT_AND/2/i',
953 'INT_OR/2/i',
954 'INT_XOR/2/i',
955 'INT_RSHIFT/2/i',
956 'INT_LSHIFT/2/i',
957 'UINT_RSHIFT/2/i',
958 'INT_SIGNEXT/2/i',
959 'FLOAT_ADD/2/f',
960 'FLOAT_SUB/2/f',
961 'FLOAT_MUL/2/f',
962 'FLOAT_TRUEDIV/2/f',
963 'FLOAT_NEG/1/f',
964 'FLOAT_ABS/1/f',
965 'CAST_FLOAT_TO_INT/1/i', # don't use for unsigned ints; we would
966 'CAST_INT_TO_FLOAT/1/f', # need some messy code in the backend
967 'CAST_FLOAT_TO_SINGLEFLOAT/1/i',
968 'CAST_SINGLEFLOAT_TO_FLOAT/1/f',
969 'CONVERT_FLOAT_BYTES_TO_LONGLONG/1/' + ('i' if longlong.is_64_bit else 'f'),
970 'CONVERT_LONGLONG_BYTES_TO_FLOAT/1/f',
971 #
972 # vector operations
973 '_VEC_PURE_FIRST',
974 '_VEC_ARITHMETIC_FIRST',
975 'VEC_INT_ADD/2/i',
976 'VEC_INT_SUB/2/i',
977 'VEC_INT_MUL/2/i',
978 'VEC_INT_AND/2/i',
979 'VEC_INT_OR/2/i',
980 'VEC_INT_XOR/2/i',
981 'VEC_FLOAT_ADD/2/f',
982 'VEC_FLOAT_SUB/2/f',
983 'VEC_FLOAT_MUL/2/f',
984 'VEC_FLOAT_TRUEDIV/2/f',
985 'VEC_FLOAT_NEG/1/f',
986 'VEC_FLOAT_ABS/1/f',
987 '_VEC_ARITHMETIC_LAST',
988 'VEC_FLOAT_EQ/2b/i',
989 'VEC_FLOAT_NE/2b/i',
990 'VEC_FLOAT_XOR/2/f',
991 'VEC_INT_IS_TRUE/1b/i',
992 'VEC_INT_NE/2b/i',
993 'VEC_INT_EQ/2b/i',
994
995 '_VEC_CAST_FIRST',
996 'VEC_INT_SIGNEXT/2/i',
997 # double -> float: v2 = cast(v1, 2) equal to v2 = (v1[0], v1[1], X, X)
998 'VEC_CAST_FLOAT_TO_SINGLEFLOAT/1/i',
999 # v4 = cast(v3, 0, 2), v4 = (v3[0], v3[1])
1000 'VEC_CAST_SINGLEFLOAT_TO_FLOAT/1/f',
1001 'VEC_CAST_FLOAT_TO_INT/1/i',
1002 'VEC_CAST_INT_TO_FLOAT/1/f',
1003 '_VEC_CAST_LAST',
1004
1005 'VEC/0/if',
1006 'VEC_UNPACK/3/if', # iX|fX = VEC_INT_UNPACK(vX, index, count)
1007 'VEC_PACK/4/if', # VEC_INT_PACK(vX, var/const, index, count)
1008 'VEC_EXPAND/1/if', # vX = VEC_INT_EXPAND(var/const)
1009 '_VEC_PURE_LAST',
1010 #
1011 'INT_LT/2b/i',
1012 'INT_LE/2b/i',
1013 'INT_EQ/2b/i',
1014 'INT_NE/2b/i',
1015 'INT_GT/2b/i',
1016 'INT_GE/2b/i',
1017 'UINT_LT/2b/i',
1018 'UINT_LE/2b/i',
1019 'UINT_GT/2b/i',
1020 'UINT_GE/2b/i',
1021 'FLOAT_LT/2b/i',
1022 'FLOAT_LE/2b/i',
1023 'FLOAT_EQ/2b/i',
1024 'FLOAT_NE/2b/i',
1025 'FLOAT_GT/2b/i',
1026 'FLOAT_GE/2b/i',
1027 #
1028 'INT_IS_ZERO/1b/i',
1029 'INT_IS_TRUE/1b/i',
1030 'INT_NEG/1/i',
1031 'INT_INVERT/1/i',
1032 'INT_FORCE_GE_ZERO/1/i',
1033 #
1034 'SAME_AS/1/ifr', # gets a Const or a Box, turns it into another Box
1035 'CAST_PTR_TO_INT/1/i',
1036 'CAST_INT_TO_PTR/1/r',
1037 #
1038 'PTR_EQ/2b/i',
1039 'PTR_NE/2b/i',
1040 'INSTANCE_PTR_EQ/2b/i',
1041 'INSTANCE_PTR_NE/2b/i',
1042 'NURSERY_PTR_INCREMENT/2/r',
1043 #
1044 'ARRAYLEN_GC/1d/i',
1045 'STRLEN/1/i',
1046 'STRGETITEM/2/i',
1047 'GETARRAYITEM_GC_PURE/2d/rfi',
1048 'UNICODELEN/1/i',
1049 'UNICODEGETITEM/2/i',
1050 #
1051 'LOAD_FROM_GC_TABLE/1/r', # only emitted by rewrite.py
1052 'LOAD_EFFECTIVE_ADDRESS/4/i', # only emitted by rewrite.py, only if
1053 # cpu.supports_load_effective_address. [v_gcptr,v_index,c_baseofs,c_shift]
1054 # res = arg0 + (arg1 << arg3) + arg2
1055 #
1056 '_ALWAYS_PURE_LAST', # ----- end of always_pure operations -----
1057
1058 # parameters GC_LOAD
1059 # 1: pointer to complex object
1060 # 2: integer describing the offset
1061 # 3: constant integer. byte size of datatype to load (negative if it is signed)
1062 'GC_LOAD/3/rfi',
1063 # parameters GC_LOAD_INDEXED
1064 # 1: pointer to complex object
1065 # 2: integer describing the index
1066 # 3: constant integer scale factor
1067 # 4: constant integer base offset (final offset is 'base + scale * index')
1068 # 5: constant integer. byte size of datatype to load (negative if it is signed)
1069 # (GC_LOAD is equivalent to GC_LOAD_INDEXED with arg3==1, arg4==0)
1070 'GC_LOAD_INDEXED/5/rfi',
1071
1072 '_RAW_LOAD_FIRST',
1073 'GETARRAYITEM_GC/2d/rfi',
1074 'GETARRAYITEM_RAW/2d/fi',
1075 'RAW_LOAD/2d/fi',
1076 'VEC_LOAD/4d/fi',
1077 '_RAW_LOAD_LAST',
1078
1079 'GETINTERIORFIELD_GC/2d/rfi',
1080 'GETFIELD_GC/1d/rfi',
1081 'GETFIELD_RAW/1d/rfi',
1082 '_MALLOC_FIRST',
1083 'NEW/0d/r', #-> GcStruct, gcptrs inside are zeroed (not the rest)
1084 'NEW_WITH_VTABLE/0d/r',#-> GcStruct with vtable, gcptrs inside are zeroed
1085 'NEW_ARRAY/1d/r', #-> GcArray, not zeroed. only for arrays of primitives
1086 'NEW_ARRAY_CLEAR/1d/r',#-> GcArray, fully zeroed
1087 'NEWSTR/1/r', #-> STR, the hash field is zeroed
1088 'NEWUNICODE/1/r', #-> UNICODE, the hash field is zeroed
1089 '_MALLOC_LAST',
1090 'FORCE_TOKEN/0/r', # historical name; nowadays, returns the jitframe
1091 'VIRTUAL_REF/2/r', # removed before it's passed to the backend
1092 'STRHASH/1/i', # only reading the .hash field, might be zero so far
1093 'UNICODEHASH/1/i', # (unless applied on consts, where .hash is forced)
1094 # this one has no *visible* side effect, since the virtualizable
1095 # must be forced, however we need to execute it anyway
1096 '_NOSIDEEFFECT_LAST', # ----- end of no_side_effect operations -----
1097
1098 # same paramters as GC_LOAD, but one additional for the value to store
1099 # note that the itemsize is not signed (always > 0)
1100 # (gcptr, index, value, [scale, base_offset,] itemsize)
1101 # invariants for GC_STORE: index is constant, but can be large
1102 # invariants for GC_STORE_INDEXED: index is a non-constant box;
1103 # scale is a constant;
1104 # base_offset is a small constant
1105 'GC_STORE/4d/n',
1106 'GC_STORE_INDEXED/6d/n',
1107
1108 'INCREMENT_DEBUG_COUNTER/1/n',
1109 '_RAW_STORE_FIRST',
1110 'SETARRAYITEM_GC/3d/n',
1111 'SETARRAYITEM_RAW/3d/n',
1112 'RAW_STORE/3d/n',
1113 'VEC_STORE/5d/n',
1114 '_RAW_STORE_LAST',
1115 'SETINTERIORFIELD_GC/3d/n',
1116 'SETINTERIORFIELD_RAW/3d/n', # right now, only used by tests
1117 'SETFIELD_GC/2d/n',
1118 'ZERO_ARRAY/5d/n', # only emitted by the rewrite, clears (part of) an array
1119 # [arraygcptr, firstindex, length, scale_firstindex,
1120 # scale_length], descr=ArrayDescr
1121 'SETFIELD_RAW/2d/n',
1122 'STRSETITEM/3/n',
1123 'UNICODESETITEM/3/n',
1124 'COND_CALL_GC_WB/1d/n', # [objptr] (for the write barrier)
1125 'COND_CALL_GC_WB_ARRAY/2d/n', # [objptr, arrayindex] (write barr. for array)
1126 '_JIT_DEBUG_FIRST',
1127 'DEBUG_MERGE_POINT/*/n', # debugging only
1128 'ENTER_PORTAL_FRAME/2/n', # debugging only
1129 'LEAVE_PORTAL_FRAME/1/n', # debugging only
1130 'JIT_DEBUG/*/n', # debugging only
1131 '_JIT_DEBUG_LAST',
1132 'ESCAPE/*/rfin', # tests only
1133 'FORCE_SPILL/1/n', # tests only
1134 'VIRTUAL_REF_FINISH/2/n', # removed before it's passed to the backend
1135 'COPYSTRCONTENT/5/n', # src, dst, srcstart, dststart, length
1136 'COPYUNICODECONTENT/5/n',
1137 'QUASIIMMUT_FIELD/1d/n', # [objptr], descr=SlowMutateDescr
1138 'ASSERT_NOT_NONE/1/n', # [objptr]
1139 'RECORD_EXACT_CLASS/2/n', # [objptr, clsptr]
1140 'RECORD_EXACT_VALUE_R/2/n', # [objptr, objptr]
1141 'RECORD_EXACT_VALUE_I/2/n', # [int, int]
1142 'KEEPALIVE/1/n',
1143 'SAVE_EXCEPTION/0/r',
1144 'SAVE_EXC_CLASS/0/i', # XXX kill me
1145 'RESTORE_EXCEPTION/2/n', # XXX kill me
1146
1147 '_CANRAISE_FIRST', # ----- start of can_raise operations -----
1148 '_CALL_FIRST',
1149 'CALL/*d/rfin',
1150 'COND_CALL/*d/n', # a conditional call, with first argument as a condition
1151 'COND_CALL_VALUE/*d/ri', # "return a0 or a1(a2, ..)", a1 elidable
1152 'CALL_ASSEMBLER/*d/rfin', # call already compiled assembler
1153 'CALL_MAY_FORCE/*d/rfin',
1154 'CALL_LOOPINVARIANT/*d/rfin',
1155 'CALL_RELEASE_GIL/*d/fin', # release the GIL around the call
1156 'CALL_PURE/*d/rfin', # removed before it's passed to the backend
1157 'CHECK_MEMORY_ERROR/1/n', # after a CALL: NULL => propagate MemoryError
1158 'CALL_MALLOC_NURSERY/1/r', # nursery malloc, const number of bytes, zeroed
1159 'CALL_MALLOC_NURSERY_VARSIZE/3d/r',
1160 'CALL_MALLOC_NURSERY_VARSIZE_FRAME/1/r',
1161 # nursery malloc, non-const number of bytes, zeroed
1162 # note that the number of bytes must be well known to be small enough
1163 # to fulfill allocating in the nursery rules (and no card markings)
1164
1165 'RECORD_KNOWN_RESULT/*d/n', # arguments known_result, funcarg1, funcarg2, funcarg3, descr is calldescr
1166 '_CALL_LAST',
1167 '_CANRAISE_LAST', # ----- end of can_raise operations -----
1168
1169 '_OVF_FIRST', # ----- start of is_ovf operations -----
1170 'INT_ADD_OVF/2/i', # note that the orded has to match INT_ADD order
1171 'INT_SUB_OVF/2/i',
1172 'INT_MUL_OVF/2/i',
1173 '_OVF_LAST', # ----- end of is_ovf operations -----
1174 '_LAST', # for the backend to add more internal operations
1175 ]
1176
1177 _cast_ops = {
1178 'CAST_FLOAT_TO_INT': ('f', 8, 'i', 4, 2),
1179 'VEC_CAST_FLOAT_TO_INT': ('f', 8, 'i', 4, 2),
1180 'CAST_INT_TO_FLOAT': ('i', 4, 'f', 8, 2),
1181 'VEC_CAST_INT_TO_FLOAT': ('i', 4, 'f', 8, 2),
1182 'CAST_FLOAT_TO_SINGLEFLOAT': ('f', 8, 'i', 4, 2),
1183 'VEC_CAST_FLOAT_TO_SINGLEFLOAT': ('f', 8, 'i', 4, 2),
1184 'CAST_SINGLEFLOAT_TO_FLOAT': ('i', 4, 'f', 8, 2),
1185 'VEC_CAST_SINGLEFLOAT_TO_FLOAT': ('i', 4, 'f', 8, 2),
1186 'INT_SIGNEXT': ('i', 0, 'i', 0, 0),
1187 'VEC_INT_SIGNEXT': ('i', 0, 'i', 0, 0),
1188 }
1189
1190 import platform
1191 if not platform.machine().startswith('x86'):
1192 # Uh, that should be moved to vector_ext really!
1193 _cast_ops['CAST_FLOAT_TO_INT'] = ('f', 8, 'i', 8, 2)
1194 _cast_ops['VEC_CAST_FLOAT_TO_INT'] = ('f', 8, 'i', 8, 2)
1195 _cast_ops['CAST_INT_TO_FLOAT'] = ('i', 8, 'f', 8, 2)
1196 _cast_ops['VEC_CAST_INT_TO_FLOAT'] = ('i', 8, 'f', 8, 2)
1197
1198 # ____________________________________________________________
1199
1200 class rop(object):
1201 @staticmethod
1202 def call_for_descr(descr):
1203 tp = descr.get_normalized_result_type()
1204 if tp == 'i':
1205 return rop.CALL_I
1206 elif tp == 'r':
1207 return rop.CALL_R
1208 elif tp == 'f':
1209 return rop.CALL_F
1210 assert tp == 'v'
1211 return rop.CALL_N
1212
1213 @staticmethod
1214 def call_pure_for_descr(descr):
1215 tp = descr.get_normalized_result_type()
1216 if tp == 'i':
1217 return rop.CALL_PURE_I
1218 elif tp == 'r':
1219 return rop.CALL_PURE_R
1220 elif tp == 'f':
1221 return rop.CALL_PURE_F
1222 assert tp == 'v'
1223 return rop.CALL_PURE_N
1224
1225 @staticmethod
1226 def call_may_force_for_descr(descr):
1227 tp = descr.get_normalized_result_type()
1228 if tp == 'i':
1229 return rop.CALL_MAY_FORCE_I
1230 elif tp == 'r':
1231 return rop.CALL_MAY_FORCE_R
1232 elif tp == 'f':
1233 return rop.CALL_MAY_FORCE_F
1234 assert tp == 'v'
1235 return rop.CALL_MAY_FORCE_N
1236
1237 @staticmethod
1238 def call_release_gil_for_descr(descr):
1239 tp = descr.get_normalized_result_type()
1240 if tp == 'i':
1241 return rop.CALL_RELEASE_GIL_I
1242 # no such thing
1243 #elif tp == 'r':
1244 # return rop.CALL_RELEASE_GIL_R
1245 elif tp == 'f':
1246 return rop.CALL_RELEASE_GIL_F
1247 assert tp == 'v'
1248 return rop.CALL_RELEASE_GIL_N
1249
1250 @staticmethod
1251 def call_assembler_for_descr(descr):
1252 tp = descr.get_normalized_result_type()
1253 if tp == 'i':
1254 return rop.CALL_ASSEMBLER_I
1255 elif tp == 'r':
1256 return rop.CALL_ASSEMBLER_R
1257 elif tp == 'f':
1258 return rop.CALL_ASSEMBLER_F
1259 assert tp == 'v'
1260 return rop.CALL_ASSEMBLER_N
1261
1262 @staticmethod
1263 def call_loopinvariant_for_descr(descr):
1264 tp = descr.get_normalized_result_type()
1265 if tp == 'i':
1266 return rop.CALL_LOOPINVARIANT_I
1267 elif tp == 'r':
1268 return rop.CALL_LOOPINVARIANT_R
1269 elif tp == 'f':
1270 return rop.CALL_LOOPINVARIANT_F
1271 assert tp == 'v'
1272 return rop.CALL_LOOPINVARIANT_N
1273
1274 @staticmethod
1275 def cond_call_value_for_descr(descr):
1276 tp = descr.get_normalized_result_type()
1277 if tp == 'i':
1278 return rop.COND_CALL_VALUE_I
1279 elif tp == 'r':
1280 return rop.COND_CALL_VALUE_R
1281 assert False, tp
1282
1283 @staticmethod
1284 def getfield_pure_for_descr(descr):
1285 if descr.is_pointer_field():
1286 return rop.GETFIELD_GC_PURE_R
1287 elif descr.is_float_field():
1288 return rop.GETFIELD_GC_PURE_F
1289 return rop.GETFIELD_GC_PURE_I
1290
1291 @staticmethod
1292 def getfield_for_descr(descr):
1293 if descr.is_pointer_field():
1294 return rop.GETFIELD_GC_R
1295 elif descr.is_float_field():
1296 return rop.GETFIELD_GC_F
1297 return rop.GETFIELD_GC_I
1298
1299 @staticmethod
1300 def getarrayitem_pure_for_descr(descr):
1301 if descr.is_array_of_pointers():
1302 return rop.GETARRAYITEM_GC_PURE_R
1303 elif descr.is_array_of_floats():
1304 return rop.GETARRAYITEM_GC_PURE_F
1305 return rop.GETARRAYITEM_GC_PURE_I
1306
1307 @staticmethod
1308 def getarrayitem_for_descr(descr):
1309 if descr.is_array_of_pointers():
1310 return rop.GETARRAYITEM_GC_R
1311 elif descr.is_array_of_floats():
1312 return rop.GETARRAYITEM_GC_F
1313 return rop.GETARRAYITEM_GC_I
1314
1315 @staticmethod
1316 def same_as_for_type(tp):
1317 if tp == 'i':
1318 return rop.SAME_AS_I
1319 elif tp == 'r':
1320 return rop.SAME_AS_R
1321 else:
1322 assert tp == 'f'
1323 return rop.SAME_AS_F
1324
1325 @staticmethod
1326 def call_for_type(tp):
1327 if tp == 'i':
1328 return rop.CALL_I
1329 elif tp == 'r':
1330 return rop.CALL_R
1331 elif tp == 'f':
1332 return rop.CALL_F
1333 return rop.CALL_N
1334
1335 @staticmethod
1336 def call_pure_for_type(tp):
1337 if tp == 'i':
1338 return rop.CALL_PURE_I
1339 elif tp == 'r':
1340 return rop.CALL_PURE_R
1341 elif tp == 'f':
1342 return rop.CALL_PURE_F
1343 return rop.CALL_PURE_N
1344
1345 @staticmethod
1346 def is_guard(opnum):
1347 return rop._GUARD_FIRST <= opnum <= rop._GUARD_LAST
1348
1349 @staticmethod
1350 def is_comparison(opnum):
1351 return rop.is_always_pure(opnum) and rop.returns_bool_result(opnum)
1352
1353 @staticmethod
1354 def is_foldable_guard(opnum):
1355 return rop._GUARD_FOLDABLE_FIRST <= opnum <= rop._GUARD_FOLDABLE_LAST
1356
1357 @staticmethod
1358 def is_guard_exception(opnum):
1359 return (opnum == rop.GUARD_EXCEPTION or
1360 opnum == rop.GUARD_NO_EXCEPTION)
1361
1362 @staticmethod
1363 def is_guard_overflow(opnum):
1364 return (opnum == rop.GUARD_OVERFLOW or
1365 opnum == rop.GUARD_NO_OVERFLOW)
1366
1367 @staticmethod
1368 def is_jit_debug(opnum):
1369 return rop._JIT_DEBUG_FIRST <= opnum <= rop._JIT_DEBUG_LAST
1370
1371 @staticmethod
1372 @specialize.arg_or_var(0)
1373 def is_always_pure(opnum):
1374 return rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST
1375
1376 @staticmethod
1377 @specialize.arg_or_var(0)
1378 def is_pure_with_descr(opnum, descr):
1379 if rop.is_always_pure(opnum):
1380 return True
1381 if (opnum == rop.GETFIELD_RAW_I or
1382 opnum == rop.GETFIELD_RAW_R or
1383 opnum == rop.GETFIELD_RAW_F or
1384 opnum == rop.GETFIELD_GC_I or
1385 opnum == rop.GETFIELD_GC_R or
1386 opnum == rop.GETFIELD_GC_F or
1387 opnum == rop.GETARRAYITEM_RAW_I or
1388 opnum == rop.GETARRAYITEM_RAW_F):
1389 return descr.is_always_pure()
1390 return False
1391
1392 @staticmethod
1393 def is_pure_getfield(opnum, descr):
1394 if (opnum == rop.GETFIELD_GC_I or
1395 opnum == rop.GETFIELD_GC_F or
1396 opnum == rop.GETFIELD_GC_R):
1397 return descr is not None and descr.is_always_pure()
1398 return False
1399
1400 @staticmethod
1401 def has_no_side_effect(opnum):
1402 return rop._NOSIDEEFFECT_FIRST <= opnum <= rop._NOSIDEEFFECT_LAST
1403
1404 @staticmethod
1405 def can_raise(opnum):
1406 return rop._CANRAISE_FIRST <= opnum <= rop._CANRAISE_LAST
1407
1408 @staticmethod
1409 def is_malloc(opnum):
1410 # a slightly different meaning from can_malloc
1411 return rop._MALLOC_FIRST <= opnum <= rop._MALLOC_LAST
1412
1413 @staticmethod
1414 def can_malloc(opnum):
1415 return rop.is_call(opnum) or rop.is_malloc(opnum)
1416
1417 @staticmethod
1418 def is_same_as(opnum):
1419 return opnum in (rop.SAME_AS_I, rop.SAME_AS_F, rop.SAME_AS_R)
1420
1421 @staticmethod
1422 def is_getfield(opnum):
1423 return opnum in (rop.GETFIELD_GC_I, rop.GETFIELD_GC_F,
1424 rop.GETFIELD_GC_R)
1425
1426 @staticmethod
1427 def is_getarrayitem(opnum):
1428 return opnum in (rop.GETARRAYITEM_GC_I, rop.GETARRAYITEM_GC_F,
1429 rop.GETARRAYITEM_GC_R, rop.GETARRAYITEM_GC_PURE_I,
1430 rop.GETARRAYITEM_GC_PURE_F,
1431 rop.GETARRAYITEM_GC_PURE_R)
1432
1433 @staticmethod
1434 def is_real_call(opnum):
1435 return (opnum == rop.CALL_I or
1436 opnum == rop.CALL_R or
1437 opnum == rop.CALL_F or
1438 opnum == rop.CALL_N)
1439
1440 @staticmethod
1441 def is_call_assembler(opnum):
1442 return (opnum == rop.CALL_ASSEMBLER_I or
1443 opnum == rop.CALL_ASSEMBLER_R or
1444 opnum == rop.CALL_ASSEMBLER_N or
1445 opnum == rop.CALL_ASSEMBLER_F)
1446
1447 @staticmethod
1448 def is_call_may_force(opnum):
1449 return (opnum == rop.CALL_MAY_FORCE_I or
1450 opnum == rop.CALL_MAY_FORCE_R or
1451 opnum == rop.CALL_MAY_FORCE_N or
1452 opnum == rop.CALL_MAY_FORCE_F)
1453
1454 @staticmethod
1455 def is_call_pure(opnum):
1456 return (opnum == rop.CALL_PURE_I or
1457 opnum == rop.CALL_PURE_R or
1458 opnum == rop.CALL_PURE_N or
1459 opnum == rop.CALL_PURE_F)
1460
1461 @staticmethod
1462 def is_call_release_gil(opnum):
1463 # no R returning call_release_gil
1464 return (opnum == rop.CALL_RELEASE_GIL_I or
1465 opnum == rop.CALL_RELEASE_GIL_F or
1466 opnum == rop.CALL_RELEASE_GIL_N)
1467
1468 @staticmethod
1469 def is_cond_call_value(opnum):
1470 return (opnum == rop.COND_CALL_VALUE_I or
1471 opnum == rop.COND_CALL_VALUE_R)
1472
1473 @staticmethod
1474 def is_ovf(opnum):
1475 return rop._OVF_FIRST <= opnum <= rop._OVF_LAST
1476
1477 @staticmethod
1478 def is_vector_arithmetic(opnum):
1479 return rop._VEC_ARITHMETIC_FIRST <= opnum <= rop._VEC_ARITHMETIC_LAST
1480
1481 @staticmethod
1482 def is_raw_array_access(opnum):
1483 return rop.is_raw_load(opnum) or rop.is_raw_store(opnum)
1484
1485 @staticmethod
1486 def is_primitive_load(opnum):
1487 return rop._RAW_LOAD_FIRST < opnum < rop._RAW_LOAD_LAST
1488
1489 @staticmethod
1490 def is_primitive_store(opnum):
1491 return rop._RAW_STORE_FIRST < opnum < rop._RAW_STORE_LAST
1492
1493 @staticmethod
1494 def is_final(opnum):
1495 return rop._FINAL_FIRST <= opnum <= rop._FINAL_LAST
1496
1497 @staticmethod
1498 def returns_bool_result(opnum):
1499 return opclasses[opnum]._cls_has_bool_result
1500
1501 @staticmethod
1502 def is_label(opnum):
1503 return opnum == rop.LABEL
1504
1505 @staticmethod
1506 def is_call(opnum):
1507 return rop._CALL_FIRST <= opnum <= rop._CALL_LAST
1508
1509 @staticmethod
1510 def is_plain_call(opnum):
1511 return (opnum == rop.CALL_I or
1512 opnum == rop.CALL_R or
1513 opnum == rop.CALL_F or
1514 opnum == rop.CALL_N)
1515
1516 @staticmethod
1517 def is_call_loopinvariant(opnum):
1518 return (opnum == rop.CALL_LOOPINVARIANT_I or
1519 opnum == rop.CALL_LOOPINVARIANT_R or
1520 opnum == rop.CALL_LOOPINVARIANT_F or
1521 opnum == rop.CALL_LOOPINVARIANT_N)
1522
1523 @staticmethod
1524 def get_gc_load(tp):
1525 if tp == 'i':
1526 return rop.GC_LOAD_I
1527 elif tp == 'f':
1528 return rop.GC_LOAD_F
1529 else:
1530 assert tp == 'r'
1531 return rop.GC_LOAD_R
1532
1533 @staticmethod
1534 def get_gc_load_indexed(tp):
1535 if tp == 'i':
1536 return rop.GC_LOAD_INDEXED_I
1537 elif tp == 'f':
1538 return rop.GC_LOAD_INDEXED_F
1539 else:
1540 assert tp == 'r'
1541 return rop.GC_LOAD_INDEXED_R
1542
1543 @staticmethod
1544 def inputarg_from_tp(tp):
1545 if tp == 'i':
1546 return InputArgInt()
1547 elif tp == 'r' or tp == 'p':
1548 return InputArgRef()
1549 elif tp == 'v':
1550 return InputArgVector()
1551 else:
1552 assert tp == 'f'
1553 return InputArgFloat()
1554
1555 @staticmethod
1556 def create_vec_expand(arg, bytesize, signed, count):
1557 if arg.type == 'i':
1558 opnum = rop.VEC_EXPAND_I
1559 else:
1560 assert arg.type == 'f'
1561 opnum = rop.VEC_EXPAND_F
1562 return VecOperationNew(opnum, [arg], arg.type, bytesize, signed, count)
1563
1564 @staticmethod
1565 def create_vec(datatype, bytesize, signed, count):
1566 if datatype == 'i':
1567 opnum = rop.VEC_I
1568 else:
1569 assert datatype == 'f'
1570 opnum = rop.VEC_F
1571 return VecOperationNew(opnum, [], datatype, bytesize, signed, count)
1572
1573 @staticmethod
1574 def create_vec_pack(datatype, args, bytesize, signed, count):
1575 if datatype == 'i':
1576 opnum = rop.VEC_PACK_I
1577 else:
1578 assert datatype == 'f'
1579 opnum = rop.VEC_PACK_F
1580 return VecOperationNew(opnum, args, datatype, bytesize, signed, count)
1581
1582 @staticmethod
1583 def create_vec_unpack(datatype, args, bytesize, signed, count):
1584 if datatype == 'i':
1585 opnum = rop.VEC_UNPACK_I
1586 else:
1587 assert datatype == 'f'
1588 opnum = rop.VEC_UNPACK_F
1589 return VecOperationNew(opnum, args, datatype, bytesize, signed, count)
1590
1591
1592
1593 opclasses = [] # mapping numbers to the concrete ResOp class
1594 opname = {} # mapping numbers to the original names, for debugging
1595 oparity = [] # mapping numbers to the arity of the operation or -1
1596 opwithdescr = [] # mapping numbers to a flag "takes a descr"
1597 optypes = [] # mapping numbers to type of return
1598
1599 def setup(debug_print=False):
1600 i = 0
1601 for name in _oplist:
1602 if '/' in name:
1603 name, arity, result = name.split('/')
1604 withdescr = 'd' in arity
1605 boolresult = 'b' in arity
1606 arity = arity.rstrip('db')
1607 if arity == '*':
1608 arity = -1
1609 else:
1610 arity = int(arity)
1611 else:
1612 arity, withdescr, boolresult, result = -1, True, False, None # default
1613 if not name.startswith('_'):
1614 for r in result:
1615 if len(result) == 1:
1616 cls_name = name
1617 else:
1618 cls_name = name + '_' + r.upper()
1619 setattr(rop, cls_name, i)
1620 opname[i] = cls_name
1621 cls = create_class_for_op(cls_name, i, arity, withdescr, r)
1622 cls._cls_has_bool_result = boolresult
1623 opclasses.append(cls)
1624 oparity.append(arity)
1625 opwithdescr.append(withdescr)
1626 optypes.append(r)
1627 if debug_print:
1628 print('%30s = %d' % (cls_name, i))
1629 i += 1
1630 else:
1631 setattr(rop, name, i)
1632 opclasses.append(None)
1633 oparity.append(-1)
1634 opwithdescr.append(False)
1635 optypes.append(' ')
1636 if debug_print:
1637 print('%30s = %d' % (name, i))
1638 i += 1
1639 # for optimizeopt/pure.py's getrecentops()
1640 assert (rop.INT_ADD_OVF - rop._OVF_FIRST ==
1641 rop.INT_ADD - rop._ALWAYS_PURE_FIRST)
1642 assert (rop.INT_SUB_OVF - rop._OVF_FIRST ==
1643 rop.INT_SUB - rop._ALWAYS_PURE_FIRST)
1644 assert (rop.INT_MUL_OVF - rop._OVF_FIRST ==
1645 rop.INT_MUL - rop._ALWAYS_PURE_FIRST)
1646
1647 def get_base_class(mixins, base):
1648 try:
1649 return get_base_class.cache[(base,) + mixins]
1650 except KeyError:
1651 arity_name = mixins[0].__name__[:-2] # remove the trailing "Op"
1652 name = arity_name + base.__name__ # something like BinaryPlainResOp
1653 bases = mixins + (base,)
1654 cls = type(name, bases, {})
1655 get_base_class.cache[(base,) + mixins] = cls
1656 return cls
1657 get_base_class.cache = {}
1658
1659 def create_class_for_op(name, opnum, arity, withdescr, result_type):
1660 arity2mixin = {
1661 0: NullaryOp,
1662 1: UnaryOp,
1663 2: BinaryOp,
1664 3: TernaryOp
1665 }
1666
1667 is_guard = name.startswith('GUARD')
1668 if name.startswith('VEC'):
1669 if name.startswith('VEC_GUARD'):
1670 baseclass = VectorGuardOp
1671 else:
1672 baseclass = VectorOp
1673 elif is_guard:
1674 assert withdescr
1675 baseclass = GuardResOp
1676 elif withdescr:
1677 baseclass = ResOpWithDescr
1678 else:
1679 baseclass = PlainResOp
1680
1681 mixins = [arity2mixin.get(arity, N_aryOp)]
1682 if name in _cast_ops:
1683 if "INT_SIGNEXT" in name:
1684 mixins.append(SignExtOp)
1685 mixins.append(CastOp)
1686
1687 cls_name = '%s_OP' % name
1688 bases = (get_base_class(tuple(mixins), baseclass),)
1689 dic = {'opnum': opnum}
1690 res = type(cls_name, bases, dic)
1691 if result_type == 'n':
1692 result_type = 'v' # why?
1693 res.type = result_type
1694 return res
1695
1696 setup(__name__ == '__main__') # print out the table when run directly
1697 del _oplist
1698
1699 _opboolinverse = {
1700 rop.INT_EQ: rop.INT_NE,
1701 rop.INT_NE: rop.INT_EQ,
1702 rop.INT_LT: rop.INT_GE,
1703 rop.INT_GE: rop.INT_LT,
1704 rop.INT_GT: rop.INT_LE,
1705 rop.INT_LE: rop.INT_GT,
1706
1707 rop.UINT_LT: rop.UINT_GE,
1708 rop.UINT_GE: rop.UINT_LT,
1709 rop.UINT_GT: rop.UINT_LE,
1710 rop.UINT_LE: rop.UINT_GT,
1711
1712 rop.FLOAT_EQ: rop.FLOAT_NE,
1713 rop.FLOAT_NE: rop.FLOAT_EQ,
1714 rop.FLOAT_LT: rop.FLOAT_GE,
1715 rop.FLOAT_GE: rop.FLOAT_LT,
1716 rop.FLOAT_GT: rop.FLOAT_LE,
1717 rop.FLOAT_LE: rop.FLOAT_GT,
1718
1719 rop.PTR_EQ: rop.PTR_NE,
1720 rop.PTR_NE: rop.PTR_EQ,
1721 }
1722
1723 _opboolreflex = {
1724 rop.INT_EQ: rop.INT_EQ,
1725 rop.INT_NE: rop.INT_NE,
1726 rop.INT_LT: rop.INT_GT,
1727 rop.INT_GE: rop.INT_LE,
1728 rop.INT_GT: rop.INT_LT,
1729 rop.INT_LE: rop.INT_GE,
1730
1731 rop.UINT_LT: rop.UINT_GT,
1732 rop.UINT_GE: rop.UINT_LE,
1733 rop.UINT_GT: rop.UINT_LT,
1734 rop.UINT_LE: rop.UINT_GE,
1735
1736 rop.FLOAT_EQ: rop.FLOAT_EQ,
1737 rop.FLOAT_NE: rop.FLOAT_NE,
1738 rop.FLOAT_LT: rop.FLOAT_GT,
1739 rop.FLOAT_GE: rop.FLOAT_LE,
1740 rop.FLOAT_GT: rop.FLOAT_LT,
1741 rop.FLOAT_LE: rop.FLOAT_GE,
1742
1743 rop.PTR_EQ: rop.PTR_EQ,
1744 rop.PTR_NE: rop.PTR_NE,
1745 }
1746 _opvector = {
1747 rop.RAW_LOAD_I: rop.VEC_LOAD_I,
1748 rop.RAW_LOAD_F: rop.VEC_LOAD_F,
1749 rop.GETARRAYITEM_RAW_I: rop.VEC_LOAD_I,
1750 rop.GETARRAYITEM_RAW_F: rop.VEC_LOAD_F,
1751 rop.GETARRAYITEM_GC_I: rop.VEC_LOAD_I,
1752 rop.GETARRAYITEM_GC_F: rop.VEC_LOAD_F,
1753 # note that there is no _PURE operation for vector operations.
1754 # reason: currently we do not care if it is pure or not!
1755 rop.GETARRAYITEM_GC_PURE_I: rop.VEC_LOAD_I,
1756 rop.GETARRAYITEM_GC_PURE_F: rop.VEC_LOAD_F,
1757 rop.RAW_STORE: rop.VEC_STORE,
1758 rop.SETARRAYITEM_RAW: rop.VEC_STORE,
1759 rop.SETARRAYITEM_GC: rop.VEC_STORE,
1760
1761 rop.INT_ADD: rop.VEC_INT_ADD,
1762 rop.INT_SUB: rop.VEC_INT_SUB,
1763 rop.INT_MUL: rop.VEC_INT_MUL,
1764 rop.INT_AND: rop.VEC_INT_AND,
1765 rop.INT_OR: rop.VEC_INT_OR,
1766 rop.INT_XOR: rop.VEC_INT_XOR,
1767 rop.FLOAT_ADD: rop.VEC_FLOAT_ADD,
1768 rop.FLOAT_SUB: rop.VEC_FLOAT_SUB,
1769 rop.FLOAT_MUL: rop.VEC_FLOAT_MUL,
1770 rop.FLOAT_TRUEDIV: rop.VEC_FLOAT_TRUEDIV,
1771 rop.FLOAT_ABS: rop.VEC_FLOAT_ABS,
1772 rop.FLOAT_NEG: rop.VEC_FLOAT_NEG,
1773 rop.FLOAT_EQ: rop.VEC_FLOAT_EQ,
1774 rop.FLOAT_NE: rop.VEC_FLOAT_NE,
1775 rop.INT_IS_TRUE: rop.VEC_INT_IS_TRUE,
1776 rop.INT_EQ: rop.VEC_INT_EQ,
1777 rop.INT_NE: rop.VEC_INT_NE,
1778
1779 # casts
1780 rop.INT_SIGNEXT: rop.VEC_INT_SIGNEXT,
1781 rop.CAST_FLOAT_TO_SINGLEFLOAT: rop.VEC_CAST_FLOAT_TO_SINGLEFLOAT,
1782 rop.CAST_SINGLEFLOAT_TO_FLOAT: rop.VEC_CAST_SINGLEFLOAT_TO_FLOAT,
1783 rop.CAST_INT_TO_FLOAT: rop.VEC_CAST_INT_TO_FLOAT,
1784 rop.CAST_FLOAT_TO_INT: rop.VEC_CAST_FLOAT_TO_INT,
1785
1786 # guard
1787 rop.GUARD_TRUE: rop.VEC_GUARD_TRUE,
1788 rop.GUARD_FALSE: rop.VEC_GUARD_FALSE,
1789 }
1790
1791 def setup2():
1792 for cls in opclasses:
1793 if cls is None:
1794 continue
1795 opnum = cls.opnum
1796 name = opname[opnum]
1797 if opnum in _opboolreflex:
1798 cls.boolreflex = _opboolreflex[opnum]
1799 if opnum in _opboolinverse:
1800 cls.boolinverse = _opboolinverse[opnum]
1801 if opnum in _opvector:
1802 cls.vector = _opvector[opnum]
1803 if name in _cast_ops:
1804 cls.cls_casts = _cast_ops[name]
1805 if name.startswith('VEC'):
1806 cls.vector = -2
1807 setup2()
1808 del _opboolinverse
1809 del _opboolreflex
1810 del _opvector
1811 del _cast_ops
1812
1813 def get_deep_immutable_oplist(operations):
1814 """
1815 When not we_are_translated(), turns ``operations`` into a frozenlist and
1816 monkey-patch its items to make sure they are not mutated.
1817
1818 When we_are_translated(), do nothing and just return the old list.
1819 """
1820 from rpython.tool.frozenlist import frozenlist
1821 if we_are_translated():
1822 return operations
1823 #
1824 def setarg(*args):
1825 assert False, "operations cannot change at this point"
1826 def setdescr(*args):
1827 assert False, "operations cannot change at this point"
1828 newops = frozenlist(operations)
1829 for op in newops:
1830 op.setarg = setarg
1831 op.setdescr = setdescr
1832 return newops
1833
1834 OpHelpers = rop