Source

pypy-arp11 / pypy / jit / metainterp / optimizeopt / rewrite.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
from pypy.jit.metainterp.optimizeopt.optimizer import *
from pypy.jit.metainterp.resoperation import opboolinvers, opboolreflex
from pypy.jit.metainterp.history import ConstInt
from pypy.jit.metainterp.optimizeutil import _findall
from pypy.jit.metainterp.resoperation import rop, ResOperation
from pypy.jit.codewriter.effectinfo import EffectInfo
from pypy.jit.metainterp.optimizeopt.intutils import IntBound
from pypy.rlib.rarithmetic import highest_bit


class OptRewrite(Optimization):
    """Rewrite operations into equivalent, cheaper operations.
       This includes already executed operations and constants.
    """

    def reconstruct_for_next_iteration(self, optimizer, valuemap):
        return self
    
    def propagate_forward(self, op):
        args = self.optimizer.make_args_key(op)
        if self.find_rewritable_bool(op, args):
            return

        opnum = op.getopnum()
        for value, func in optimize_ops:
            if opnum == value:
                func(self, op)
                break
        else:
            self.emit_operation(op)

    def test_emittable(self, op):
        opnum = op.getopnum()
        for value, func in optimize_guards:
            if opnum == value:
                try:
                    func(self, op, dryrun=True)
                    return self.is_emittable(op)
                except InvalidLoop:
                    return False
        return self.is_emittable(op)

        
    def try_boolinvers(self, op, targs):
        oldop = self.optimizer.pure_operations.get(targs, None)
        if oldop is not None and oldop.getdescr() is op.getdescr():
            value = self.getvalue(oldop.result)
            if value.is_constant():
                if value.box.same_constant(CONST_1):
                    self.make_constant(op.result, CONST_0)
                    return True
                elif value.box.same_constant(CONST_0):
                    self.make_constant(op.result, CONST_1)
                    return True

        return False


    def find_rewritable_bool(self, op, args):
        try:
            oldopnum = opboolinvers[op.getopnum()]
            targs = [args[0], args[1], ConstInt(oldopnum)]
            if self.try_boolinvers(op, targs):
                return True
        except KeyError:
            pass

        try:
            oldopnum = opboolreflex[op.getopnum()] # FIXME: add INT_ADD, INT_MUL
            targs = [args[1], args[0], ConstInt(oldopnum)]
            oldop = self.optimizer.pure_operations.get(targs, None)
            if oldop is not None and oldop.getdescr() is op.getdescr():
                self.make_equal_to(op.result, self.getvalue(oldop.result))
                return True
        except KeyError:
            pass

        try:
            oldopnum = opboolinvers[opboolreflex[op.getopnum()]]
            targs = [args[1], args[0], ConstInt(oldopnum)]
            if self.try_boolinvers(op, targs):
                return True
        except KeyError:
            pass

        return False

    def optimize_INT_AND(self, op):
        v1 = self.getvalue(op.getarg(0))
        v2 = self.getvalue(op.getarg(1))
        if v1.is_null() or v2.is_null():
            self.make_constant_int(op.result, 0)
        else:
            self.emit_operation(op)

    def optimize_INT_OR(self, op):
        v1 = self.getvalue(op.getarg(0))
        v2 = self.getvalue(op.getarg(1))
        if v1.is_null():
            self.make_equal_to(op.result, v2)
        elif v2.is_null():
            self.make_equal_to(op.result, v1)
        else:
            self.emit_operation(op)

    def optimize_INT_SUB(self, op):
        v1 = self.getvalue(op.getarg(0))
        v2 = self.getvalue(op.getarg(1))
        if v2.is_constant() and v2.box.getint() == 0:
            self.make_equal_to(op.result, v1)
        else:
            self.emit_operation(op)

        # Synthesize the reverse ops for optimize_default to reuse
        self.pure(rop.INT_ADD, [op.result, op.getarg(1)], op.getarg(0))
        self.pure(rop.INT_SUB, [op.getarg(0), op.result], op.getarg(1))

    def optimize_INT_ADD(self, op):
        v1 = self.getvalue(op.getarg(0))
        v2 = self.getvalue(op.getarg(1))

        # If one side of the op is 0 the result is the other side.
        if v1.is_constant() and v1.box.getint() == 0:
            self.make_equal_to(op.result, v2)
        elif v2.is_constant() and v2.box.getint() == 0:
            self.make_equal_to(op.result, v1)
        else:
            self.emit_operation(op)

        # Synthesize the reverse op for optimize_default to reuse
        self.pure(rop.INT_SUB, [op.result, op.getarg(1)], op.getarg(0))
        self.pure(rop.INT_SUB, [op.result, op.getarg(0)], op.getarg(1))

    def optimize_INT_MUL(self, op):
        v1 = self.getvalue(op.getarg(0))
        v2 = self.getvalue(op.getarg(1))

        # If one side of the op is 1 the result is the other side.
        if v1.is_constant() and v1.box.getint() == 1:
            self.make_equal_to(op.result, v2)
        elif v2.is_constant() and v2.box.getint() == 1:
            self.make_equal_to(op.result, v1)
        elif (v1.is_constant() and v1.box.getint() == 0) or \
             (v2.is_constant() and v2.box.getint() == 0):
            self.make_constant_int(op.result, 0)
        else:
            for lhs, rhs in [(v1, v2), (v2, v1)]:
                # x & (x -1) == 0 is a quick test for power of 2
                if (lhs.is_constant() and
                    (lhs.box.getint() & (lhs.box.getint() - 1)) == 0):
                    new_rhs = ConstInt(highest_bit(lhs.box.getint()))
                    op = op.copy_and_change(rop.INT_LSHIFT, args=[rhs.box, new_rhs])
                    break

            self.emit_operation(op)

    def optimize_CALL_PURE(self, op):
        for i in range(op.numargs()):
            arg = op.getarg(i)
            if self.get_constant_box(arg) is None:
                break
        else:
            # all constant arguments: constant-fold away
            self.make_constant(op.result, op.getarg(0))
            return
        # replace CALL_PURE with just CALL
        args = op.getarglist()[1:]
        self.emit_operation(ResOperation(rop.CALL, args, op.result,
                                         op.getdescr()))

    def optimize_guard(self, op, constbox, emit_operation=True, dryrun=False):
        value = self.getvalue(op.getarg(0))
        if value.is_constant():
            box = value.box
            assert isinstance(box, Const)
            if not box.same_constant(constbox):
                raise InvalidLoop
            return
        if dryrun: return
        if emit_operation:
            self.emit_operation(op)
        value.make_constant(constbox)
        self.optimizer.turned_constant(value)

    def optimize_GUARD_ISNULL(self, op, dryrun=False):
        value = self.getvalue(op.getarg(0))
        if value.is_null():
            return
        elif value.is_nonnull():
            raise InvalidLoop
        if dryrun: return
        self.emit_operation(op)
        value.make_constant(self.optimizer.cpu.ts.CONST_NULL)

    def optimize_GUARD_NONNULL(self, op, dryrun=False):
        value = self.getvalue(op.getarg(0))
        if value.is_nonnull():
            return
        elif value.is_null():
            raise InvalidLoop
        if dryrun: return
        self.emit_operation(op)
        value.make_nonnull(len(self.optimizer.newoperations) - 1)

    def optimize_GUARD_VALUE(self, op, dryrun=False):
        value = self.getvalue(op.getarg(0))
        emit_operation = True
        if not dryrun and value.last_guard_index != -1:
            # there already has been a guard_nonnull or guard_class or
            # guard_nonnull_class on this value, which is rather silly.
            # replace the original guard with a guard_value
            old_guard_op = self.optimizer.newoperations[value.last_guard_index]
            new_guard_op = old_guard_op.copy_and_change(rop.GUARD_VALUE,
                                             args = [old_guard_op.getarg(0), op.getarg(1)])
            self.optimizer.newoperations[value.last_guard_index] = new_guard_op
            # hack hack hack.  Change the guard_opnum on
            # new_guard_op.getdescr() so that when resuming,
            # the operation is not skipped by pyjitpl.py.
            descr = new_guard_op.getdescr()
            assert isinstance(descr, compile.ResumeGuardDescr)
            descr.guard_opnum = rop.GUARD_VALUE
            descr.make_a_counter_per_value(new_guard_op)
            emit_operation = False
        constbox = op.getarg(1)
        assert isinstance(constbox, Const)
        self.optimize_guard(op, constbox, emit_operation, dryrun)

    def optimize_GUARD_TRUE(self, op, dryrun=False):
        value = self.getvalue(op.getarg(0))
        v = self.optimizer.int_to_bool_nullity.get(value)
        if v:
            v, int_is_true = v
            if int_is_true:
                if not v.is_nonnull():
                    v.make_nonnull(len(self.optimizer.newoperations) - 1)
            else:
                v.make_constant(CONST_0)
        self.optimize_guard(op, CONST_1, dryrun=dryrun)

    def optimize_GUARD_FALSE(self, op, dryrun=False):
        value = self.getvalue(op.getarg(0))
        v = self.optimizer.int_to_bool_nullity.get(value)
        if v:
            v, int_is_true = v
            if int_is_true:
                v.make_constant(ConstInt(0))
            elif not v.is_nonnull():
                v.make_nonnull(len(self.optimizer.newoperations) - 1)
        self.optimize_guard(op, CONST_0, dryrun=dryrun)

    def optimize_GUARD_CLASS(self, op, dryrun=False):
        value = self.getvalue(op.getarg(0))
        expectedclassbox = op.getarg(1)
        assert isinstance(expectedclassbox, Const)
        realclassbox = value.get_constant_class(self.optimizer.cpu)
        if realclassbox is not None:
            if realclassbox.same_constant(expectedclassbox):
                return
            raise InvalidLoop
        if dryrun: return
        emit_operation = True
        if value.last_guard_index != -1:
            # there already has been a guard_nonnull or guard_class or
            # guard_nonnull_class on this value.
            old_guard_op = self.optimizer.newoperations[value.last_guard_index]
            if old_guard_op.getopnum() == rop.GUARD_NONNULL:
                # it was a guard_nonnull, which we replace with a
                # guard_nonnull_class.
                new_guard_op = old_guard_op.copy_and_change (rop.GUARD_NONNULL_CLASS,
                                         args = [old_guard_op.getarg(0), op.getarg(1)])
                self.optimizer.newoperations[value.last_guard_index] = new_guard_op
                # hack hack hack.  Change the guard_opnum on
                # new_guard_op.getdescr() so that when resuming,
                # the operation is not skipped by pyjitpl.py.
                descr = new_guard_op.getdescr()
                assert isinstance(descr, compile.ResumeGuardDescr)
                descr.guard_opnum = rop.GUARD_NONNULL_CLASS
                emit_operation = False
        if emit_operation:
            self.emit_operation(op)
            last_guard_index = len(self.optimizer.newoperations) - 1
        else:
            last_guard_index = value.last_guard_index
        value.make_constant_class(expectedclassbox, last_guard_index)

    def optimize_GUARD_NONNULL_CLASS(self, op, dryrun=False):
        self.optimize_GUARD_NONNULL(op, True)
        self.optimize_GUARD_CLASS(op, dryrun)

    def optimize_GUARD_NO_EXCEPTION(self, op, dryrun=False):
        if dryrun: return
        if not self.optimizer.exception_might_have_happened:
            return
        self.emit_operation(op)
        self.optimizer.exception_might_have_happened = False

    def optimize_CALL_LOOPINVARIANT(self, op):
        arg = op.getarg(0)
        # 'arg' must be a Const, because residual_call in codewriter
        # expects a compile-time constant
        assert isinstance(arg, Const)
        key = make_hashable_int(arg.getint())
        resvalue = self.optimizer.loop_invariant_results.get(key, None)
        if resvalue is not None:
            self.make_equal_to(op.result, resvalue)
            return
        # change the op to be a normal call, from the backend's point of view
        # there is no reason to have a separate operation for this
        op = op.copy_and_change(rop.CALL)
        self.emit_operation(op)
        resvalue = self.getvalue(op.result)
        self.optimizer.loop_invariant_results[key] = resvalue
    
    def _optimize_nullness(self, op, box, expect_nonnull):
        value = self.getvalue(box)
        if value.is_nonnull():
            self.make_constant_int(op.result, expect_nonnull)
        elif value.is_null():
            self.make_constant_int(op.result, not expect_nonnull)
        else:
            self.emit_operation(op)

    def optimize_INT_IS_TRUE(self, op):
        v = self.getvalue(op.getarg(0))
        if v in self.optimizer.bool_boxes:
            self.make_equal_to(op.result, v)
            return
        self._optimize_nullness(op, op.getarg(0), True)
        self.optimizer.int_to_bool_nullity[self.getvalue(op.result)] = (v, True)

    def optimize_INT_IS_ZERO(self, op):
        v = self.getvalue(op.getarg(0))
        self._optimize_nullness(op, op.getarg(0), False)
        self.optimizer.int_to_bool_nullity[self.getvalue(op.result)] = (v,
                                                                        False)

    def _optimize_oois_ooisnot(self, op, expect_isnot):
        value0 = self.getvalue(op.getarg(0))
        value1 = self.getvalue(op.getarg(1))
        if value0.is_virtual():
            if value1.is_virtual():
                intres = (value0 is value1) ^ expect_isnot
                self.make_constant_int(op.result, intres)
            else:
                self.make_constant_int(op.result, expect_isnot)
        elif value1.is_virtual():
            self.make_constant_int(op.result, expect_isnot)
        elif value1.is_null():
            self._optimize_nullness(op, op.getarg(0), expect_isnot)
        elif value0.is_null():
            self._optimize_nullness(op, op.getarg(1), expect_isnot)
        elif value0 is value1:
            self.make_constant_int(op.result, not expect_isnot)
        else:
            cls0 = value0.get_constant_class(self.optimizer.cpu)
            if cls0 is not None:
                cls1 = value1.get_constant_class(self.optimizer.cpu)
                if cls1 is not None and not cls0.same_constant(cls1):
                    # cannot be the same object, as we know that their
                    # class is different
                    self.make_constant_int(op.result, expect_isnot)
                    return
            self.emit_operation(op)

    def optimize_PTR_NE(self, op):
        self._optimize_oois_ooisnot(op, True)

    def optimize_PTR_EQ(self, op):
        self._optimize_oois_ooisnot(op, False)

##    def optimize_INSTANCEOF(self, op):
##        value = self.getvalue(op.args[0])
##        realclassbox = value.get_constant_class(self.optimizer.cpu)
##        if realclassbox is not None:
##            checkclassbox = self.optimizer.cpu.typedescr2classbox(op.descr)
##            result = self.optimizer.cpu.ts.subclassOf(self.optimizer.cpu,
##                                                      realclassbox, 
##                                                      checkclassbox)
##            self.make_constant_int(op.result, result)
##            return
##        self.emit_operation(op)

    def optimize_CALL(self, op):
        # dispatch based on 'oopspecindex' to a method that handles
        # specifically the given oopspec call.  For non-oopspec calls,
        # oopspecindex is just zero.
        effectinfo = op.getdescr().get_extra_info()
        if effectinfo is not None:
            oopspecindex = effectinfo.oopspecindex
            if oopspecindex == EffectInfo.OS_ARRAYCOPY:
                if self._optimize_CALL_ARRAYCOPY(op):
                    return
        self.emit_operation(op)

    def _optimize_CALL_ARRAYCOPY(self, op):
        source_value = self.getvalue(op.getarg(1))
        dest_value = self.getvalue(op.getarg(2))
        source_start_box = self.get_constant_box(op.getarg(3))
        dest_start_box = self.get_constant_box(op.getarg(4))
        length = self.get_constant_box(op.getarg(5))
        if (source_value.is_virtual() and source_start_box and dest_start_box
            and length and dest_value.is_virtual()):
            # XXX optimize the case where dest value is not virtual,
            #     but we still can avoid a mess
            source_start = source_start_box.getint()
            dest_start = dest_start_box.getint()
            for index in range(length.getint()):
                val = source_value.getitem(index + source_start)
                dest_value.setitem(index + dest_start, val)
            return True
        if length and length.getint() == 0:
            return True # 0-length arraycopy
        return False

    def optimize_INT_FLOORDIV(self, op):
        v1 = self.getvalue(op.getarg(0))
        v2 = self.getvalue(op.getarg(1))

        if v1.intbound.known_ge(IntBound(0, 0)) and v2.is_constant():
            val = v2.box.getint()
            if val & (val - 1) == 0 and val > 0: # val == 2**shift
                op = op.copy_and_change(rop.INT_RSHIFT,
                                        args = [op.getarg(0), ConstInt(highest_bit(val))])
        self.emit_operation(op)


optimize_ops = _findall(OptRewrite, 'optimize_')
optimize_guards = _findall(OptRewrite, 'optimize_', 'GUARD')