peephole.c 27.1 KB
Newer Older
1
/* Peephole optimizations for bytecode compiler. */
2 3 4 5 6 7 8 9 10

#include "Python.h"

#include "Python-ast.h"
#include "node.h"
#include "ast.h"
#include "code.h"
#include "symtable.h"
#include "opcode.h"
11
#include "wordcode_helpers.h"
12

13
#define UNCONDITIONAL_JUMP(op)  (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
14
#define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
15
    || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
16
#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \
17 18
    || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
    || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
19
#define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP)
20 21
#define GETJUMPTGT(arr, i) (get_arg(arr, i) / sizeof(_Py_CODEUNIT) + \
        (ABSOLUTE_JUMP(_Py_OPCODE(arr[i])) ? 0 : i+1))
22 23
#define ISBASICBLOCK(blocks, start, end) \
    (blocks[start]==blocks[end])
24

25 26 27 28

#define CONST_STACK_CREATE() { \
    const_stack_size = 256; \
    const_stack = PyMem_New(PyObject *, const_stack_size); \
29
    if (!const_stack) { \
30 31 32 33 34 35 36 37 38 39
        PyErr_NoMemory(); \
        goto exitError; \
    } \
    }

#define CONST_STACK_DELETE() do { \
    if (const_stack) \
        PyMem_Free(const_stack); \
    } while(0)

40
#define CONST_STACK_LEN() ((unsigned)(const_stack_top + 1))
41 42 43

#define CONST_STACK_PUSH_OP(i) do { \
    PyObject *_x; \
44
    assert(_Py_OPCODE(codestr[i]) == LOAD_CONST); \
45 46
    assert(PyList_GET_SIZE(consts) > (Py_ssize_t)get_arg(codestr, i)); \
    _x = PyList_GET_ITEM(consts, get_arg(codestr, i)); \
47 48 49
    if (++const_stack_top >= const_stack_size) { \
        const_stack_size *= 2; \
        PyMem_Resize(const_stack, PyObject *, const_stack_size); \
50
        if (!const_stack) { \
51 52 53 54 55 56 57 58 59 60 61 62 63
            PyErr_NoMemory(); \
            goto exitError; \
        } \
    } \
    const_stack[const_stack_top] = _x; \
    in_consts = 1; \
    } while(0)

#define CONST_STACK_RESET() do { \
    const_stack_top = -1; \
    } while(0)

#define CONST_STACK_LASTN(i) \
64
    &const_stack[CONST_STACK_LEN() - i]
65 66

#define CONST_STACK_POP(i) do { \
67
    assert(CONST_STACK_LEN() >= i); \
68 69 70
    const_stack_top -= i; \
    } while(0)

71 72 73 74 75
/* Scans back N consecutive LOAD_CONST instructions, skipping NOPs,
   returns index of the Nth last's LOAD_CONST's EXTENDED_ARG prefix.
   Callers are responsible to check CONST_STACK_LEN beforehand.
*/
static Py_ssize_t
76
lastn_const_start(const _Py_CODEUNIT *codestr, Py_ssize_t i, Py_ssize_t n)
77
{
78
    assert(n > 0);
79
    for (;;) {
80
        i--;
81
        assert(i >= 0);
82
        if (_Py_OPCODE(codestr[i]) == LOAD_CONST) {
83
            if (!--n) {
84 85
                while (i > 0 && _Py_OPCODE(codestr[i-1]) == EXTENDED_ARG) {
                    i--;
86 87 88 89 90
                }
                return i;
            }
        }
        else {
91 92
            assert(_Py_OPCODE(codestr[i]) == NOP ||
                   _Py_OPCODE(codestr[i]) == EXTENDED_ARG);
93 94 95 96 97 98
        }
    }
}

/* Scans through EXTENDED ARGs, seeking the index of the effective opcode */
static Py_ssize_t
99
find_op(const _Py_CODEUNIT *codestr, Py_ssize_t i)
100
{
101 102
    while (_Py_OPCODE(codestr[i]) == EXTENDED_ARG) {
        i++;
103 104 105 106 107 108 109
    }
    return i;
}

/* Given the index of the effective opcode,
   scan back to construct the oparg with EXTENDED_ARG */
static unsigned int
110
get_arg(const _Py_CODEUNIT *codestr, Py_ssize_t i)
111
{
112 113 114 115 116 117 118 119
    _Py_CODEUNIT word;
    unsigned int oparg = _Py_OPARG(codestr[i]);
    if (i >= 1 && _Py_OPCODE(word = codestr[i-1]) == EXTENDED_ARG) {
        oparg |= _Py_OPARG(word) << 8;
        if (i >= 2 && _Py_OPCODE(word = codestr[i-2]) == EXTENDED_ARG) {
            oparg |= _Py_OPARG(word) << 16;
            if (i >= 3 && _Py_OPCODE(word = codestr[i-3]) == EXTENDED_ARG) {
                oparg |= _Py_OPARG(word) << 24;
120 121 122 123 124 125
            }
        }
    }
    return oparg;
}

126 127 128 129 130 131 132
/* Fill the region with NOPs. */
static void
fill_nops(_Py_CODEUNIT *codestr, Py_ssize_t start, Py_ssize_t end)
{
    memset(codestr + start, NOP, (end - start) * sizeof(_Py_CODEUNIT));
}

133 134 135 136
/* Given the index of the effective opcode,
   attempt to replace the argument, taking into account EXTENDED_ARG.
   Returns -1 on failure, or the new op index on success */
static Py_ssize_t
137
set_arg(_Py_CODEUNIT *codestr, Py_ssize_t i, unsigned int oparg)
138 139 140 141 142 143 144 145 146 147
{
    unsigned int curarg = get_arg(codestr, i);
    int curilen, newilen;
    if (curarg == oparg)
        return i;
    curilen = instrsize(curarg);
    newilen = instrsize(oparg);
    if (curilen < newilen) {
        return -1;
    }
148

149 150
    write_op_arg(codestr + i + 1 - curilen, _Py_OPCODE(codestr[i]), oparg, newilen);
    fill_nops(codestr, i + 1 - curilen + newilen, i + 1);
151 152 153 154 155 156 157
    return i-curilen+newilen;
}

/* Attempt to write op/arg at end of specified region of memory.
   Preceding memory in the region is overwritten with NOPs.
   Returns -1 on failure, op index on success */
static Py_ssize_t
158
copy_op_arg(_Py_CODEUNIT *codestr, Py_ssize_t i, unsigned char op,
159 160 161 162 163 164 165
            unsigned int oparg, Py_ssize_t maxi)
{
    int ilen = instrsize(oparg);
    if (i + ilen > maxi) {
        return -1;
    }
    write_op_arg(codestr + maxi - ilen, op, oparg, ilen);
166 167
    fill_nops(codestr, i, maxi - ilen);
    return maxi - 1;
168
}
169

170
/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
171
   with    LOAD_CONST (c1, c2, ... cn).
172 173 174
   The consts table must still be in list form so that the
   new constant (c1, c2, ... cn) can be appended.
   Called with codestr pointing to the first LOAD_CONST.
175
   Bails out with no change if one or more of the LOAD_CONSTs is missing.
176 177
   Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in"
   test; for BUILD_SET it assembles a frozenset rather than a tuple.
178
*/
179
static Py_ssize_t
180
fold_tuple_on_constants(_Py_CODEUNIT *codestr, Py_ssize_t c_start,
181 182
                        Py_ssize_t opcode_end, unsigned char opcode,
                        PyObject *consts, PyObject **objs, int n)
183
{
184
    PyObject *newconst, *constant;
185
    Py_ssize_t i, len_consts;
186 187 188 189 190 191

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));

    /* Buildup new tuple of constants */
    newconst = PyTuple_New(n);
192 193 194
    if (newconst == NULL) {
        return -1;
    }
195
    for (i=0 ; i<n ; i++) {
196
        constant = objs[i];
197 198 199 200 201
        Py_INCREF(constant);
        PyTuple_SET_ITEM(newconst, i, constant);
    }

    /* If it's a BUILD_SET, use the PyTuple we just built to create a
202 203 204 205 206 207
       PyFrozenSet, and use that as the constant instead: */
    if (opcode == BUILD_SET) {
        Py_SETREF(newconst, PyFrozenSet_New(newconst));
        if (newconst == NULL) {
            return -1;
        }
208 209 210
    }

    /* Append folded constant onto consts */
211
    len_consts = PyList_GET_SIZE(consts);
212 213
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
214
        return -1;
215 216 217
    }
    Py_DECREF(newconst);

218
    return copy_op_arg(codestr, c_start, LOAD_CONST, len_consts, opcode_end);
219 220
}

221
/* Replace LOAD_CONST c1, LOAD_CONST c2, BINOP
222
   with    LOAD_CONST binop(c1,c2)
223 224
   The consts table must still be in list form so that the
   new constant can be appended.
225
   Called with codestr pointing to the BINOP.
226
   Abandons the transformation if the folding fails (i.e.  1+'a').
227
   If the new constant is a sequence, only folds when the size
228 229
   is below a threshold value.  That keeps pyc files from
   becoming large in the presence of code like:  (None,)*1000.
230
*/
231
static Py_ssize_t
232
fold_binops_on_constants(_Py_CODEUNIT *codestr, Py_ssize_t c_start,
233 234
                         Py_ssize_t opcode_end, unsigned char opcode,
                         PyObject *consts, PyObject **objs)
235
{
236 237 238 239 240
    PyObject *newconst, *v, *w;
    Py_ssize_t len_consts, size;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
241
    len_consts = PyList_GET_SIZE(consts);
242 243

    /* Create new constant */
244 245
    v = objs[0];
    w = objs[1];
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
    switch (opcode) {
        case BINARY_POWER:
            newconst = PyNumber_Power(v, w, Py_None);
            break;
        case BINARY_MULTIPLY:
            newconst = PyNumber_Multiply(v, w);
            break;
        case BINARY_TRUE_DIVIDE:
            newconst = PyNumber_TrueDivide(v, w);
            break;
        case BINARY_FLOOR_DIVIDE:
            newconst = PyNumber_FloorDivide(v, w);
            break;
        case BINARY_MODULO:
            newconst = PyNumber_Remainder(v, w);
            break;
        case BINARY_ADD:
            newconst = PyNumber_Add(v, w);
            break;
        case BINARY_SUBTRACT:
            newconst = PyNumber_Subtract(v, w);
            break;
        case BINARY_SUBSCR:
            newconst = PyObject_GetItem(v, w);
            break;
        case BINARY_LSHIFT:
            newconst = PyNumber_Lshift(v, w);
            break;
        case BINARY_RSHIFT:
            newconst = PyNumber_Rshift(v, w);
            break;
        case BINARY_AND:
            newconst = PyNumber_And(v, w);
            break;
        case BINARY_XOR:
            newconst = PyNumber_Xor(v, w);
            break;
        case BINARY_OR:
            newconst = PyNumber_Or(v, w);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected binary operation %d on a constant",
                     opcode);
291
            return -1;
292 293
    }
    if (newconst == NULL) {
294
        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
295
            PyErr_Clear();
296 297
        }
        return -1;
298 299
    }
    size = PyObject_Size(newconst);
300
    if (size == -1) {
301 302 303
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
            return -1;
        }
304
        PyErr_Clear();
305
    } else if (size > 20) {
306
        Py_DECREF(newconst);
307
        return -1;
308 309 310 311 312
    }

    /* Append folded constant into consts table */
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
313
        return -1;
314 315 316
    }
    Py_DECREF(newconst);

317
    return copy_op_arg(codestr, c_start, LOAD_CONST, len_consts, opcode_end);
318 319
}

320
static Py_ssize_t
321
fold_unaryops_on_constants(_Py_CODEUNIT *codestr, Py_ssize_t c_start,
322 323
                           Py_ssize_t opcode_end, unsigned char opcode,
                           PyObject *consts, PyObject *v)
324
{
325
    PyObject *newconst;
326 327 328 329
    Py_ssize_t len_consts;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
330
    len_consts = PyList_GET_SIZE(consts);
331 332 333 334

    /* Create new constant */
    switch (opcode) {
        case UNARY_NEGATIVE:
335
            newconst = PyNumber_Negative(v);
336 337 338 339 340 341 342 343 344 345 346 347
            break;
        case UNARY_INVERT:
            newconst = PyNumber_Invert(v);
            break;
        case UNARY_POSITIVE:
            newconst = PyNumber_Positive(v);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected unary operation %d on a constant",
                     opcode);
348
            return -1;
349 350
    }
    if (newconst == NULL) {
351
        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
352
            PyErr_Clear();
353 354
        }
        return -1;
355 356 357 358 359
    }

    /* Append folded constant into consts table */
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
360
        PyErr_Clear();
361
        return -1;
362 363 364
    }
    Py_DECREF(newconst);

365
    return copy_op_arg(codestr, c_start, LOAD_CONST, len_consts, opcode_end);
366 367 368
}

static unsigned int *
369
markblocks(_Py_CODEUNIT *code, Py_ssize_t len)
370
{
371
    unsigned int *blocks = PyMem_New(unsigned int, len);
372
    int i, j, opcode, blockcnt = 0;
373 374 375 376 377 378 379 380

    if (blocks == NULL) {
        PyErr_NoMemory();
        return NULL;
    }
    memset(blocks, 0, len*sizeof(int));

    /* Mark labels in the first pass */
381 382
    for (i = 0; i < len; i++) {
        opcode = _Py_OPCODE(code[i]);
383 384 385 386 387 388 389 390 391 392 393 394 395
        switch (opcode) {
            case FOR_ITER:
            case JUMP_FORWARD:
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
396
            case SETUP_ASYNC_WITH:
397
                j = GETJUMPTGT(code, i);
398
                assert(j < len);
399 400 401 402 403
                blocks[j] = 1;
                break;
        }
    }
    /* Build block numbers in the second pass */
404
    for (i = 0; i < len; i++) {
405 406 407 408
        blockcnt += blocks[i];          /* increment blockcnt over labels */
        blocks[i] = blockcnt;
    }
    return blocks;
409 410 411
}

/* Perform basic peephole optimizations to components of a code object.
412
   The consts object should still be in list form to allow new constants
413 414
   to be appended.

415 416
   To keep the optimizer simple, it bails when the lineno table has complex
   encoding for gaps >= 255.
417

418
   Optimizations are restricted to simple transformations occurring within a
419 420 421
   single basic block.  All transformations keep the code size the same or
   smaller.  For those that reduce size, the gaps are initially filled with
   NOPs.  Later those NOPs are removed and the jump addresses retargeted in
422
   a single pass. */
423 424 425

PyObject *
PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
426
                PyObject *lnotab_obj)
427
{
428 429 430
    Py_ssize_t h, i, nexti, op_start, codelen, tgt;
    unsigned int j, nops;
    unsigned char opcode, nextop;
431
    _Py_CODEUNIT *codestr = NULL;
432
    unsigned char *lnotab;
433
    unsigned int cum_orig_offset, last_offset;
434
    Py_ssize_t tabsiz;
435 436 437 438
    PyObject **const_stack = NULL;
    Py_ssize_t const_stack_top = -1;
    Py_ssize_t const_stack_size = 0;
    int in_consts = 0;  /* whether we are in a LOAD_CONST sequence */
439 440 441 442 443 444
    unsigned int *blocks = NULL;

    /* Bail out if an exception is set */
    if (PyErr_Occurred())
        goto exitError;

445 446 447 448 449 450 451
    /* Bypass optimization when the lnotab table is too complex */
    assert(PyBytes_Check(lnotab_obj));
    lnotab = (unsigned char*)PyBytes_AS_STRING(lnotab_obj);
    tabsiz = PyBytes_GET_SIZE(lnotab_obj);
    assert(tabsiz == 0 || Py_REFCNT(lnotab_obj) == 1);
    if (memchr(lnotab, 255, tabsiz) != NULL) {
        /* 255 value are used for multibyte bytecode instructions */
452
        goto exitUnchanged;
453 454 455
    }
    /* Note: -128 and 127 special values for line number delta are ok,
       the peephole optimizer doesn't modify line numbers. */
456 457 458

    assert(PyBytes_Check(code));
    codelen = PyBytes_GET_SIZE(code);
459
    assert(codelen % sizeof(_Py_CODEUNIT) == 0);
460 461

    /* Make a modifiable copy of the code string */
462
    codestr = (_Py_CODEUNIT *)PyMem_Malloc(codelen);
463 464
    if (codestr == NULL) {
        PyErr_NoMemory();
465
        goto exitError;
466
    }
467 468
    memcpy(codestr, PyBytes_AS_STRING(code), codelen);
    codelen /= sizeof(_Py_CODEUNIT);
469 470 471 472 473 474

    blocks = markblocks(codestr, codelen);
    if (blocks == NULL)
        goto exitError;
    assert(PyList_Check(consts));

475 476
    CONST_STACK_CREATE();

477
    for (i=find_op(codestr, 0) ; i<codelen ; i=nexti) {
478
        opcode = _Py_OPCODE(codestr[i]);
479
        op_start = i;
480 481
        while (op_start >= 1 && _Py_OPCODE(codestr[op_start-1]) == EXTENDED_ARG) {
            op_start--;
482 483
        }

484 485 486 487
        nexti = i + 1;
        while (nexti < codelen && _Py_OPCODE(codestr[nexti]) == EXTENDED_ARG)
            nexti++;
        nextop = nexti < codelen ? _Py_OPCODE(codestr[nexti]) : 0;
488

489 490 491 492
        if (!in_consts) {
            CONST_STACK_RESET();
        }
        in_consts = 0;
493 494 495 496 497

        switch (opcode) {
            /* Replace UNARY_NOT POP_JUMP_IF_FALSE
               with    POP_JUMP_IF_TRUE */
            case UNARY_NOT:
498
                if (nextop != POP_JUMP_IF_FALSE
499
                    || !ISBASICBLOCK(blocks, op_start, i + 1))
500
                    break;
501 502
                fill_nops(codestr, op_start, i + 1);
                codestr[nexti] = PACKOPARG(POP_JUMP_IF_TRUE, _Py_OPARG(codestr[nexti]));
503
                break;
504 505 506 507 508 509 510

                /* not a is b -->  a is not b
                   not a in b -->  a not in b
                   not a is not b -->  a is b
                   not a not in b -->  a in b
                */
            case COMPARE_OP:
511 512 513
                j = get_arg(codestr, i);
                if (j < 6 || j > 9 ||
                    nextop != UNARY_NOT ||
514
                    !ISBASICBLOCK(blocks, op_start, i + 1))
515
                    break;
516 517
                codestr[i] = PACKOPARG(opcode, j^1);
                fill_nops(codestr, i + 1, nexti + 1);
518 519 520
                break;

                /* Skip over LOAD_CONST trueconst
521 522
                   POP_JUMP_IF_FALSE xx.  This improves
                   "while 1" performance.  */
523
            case LOAD_CONST:
524
                CONST_STACK_PUSH_OP(i);
525
                if (nextop != POP_JUMP_IF_FALSE  ||
526
                    !ISBASICBLOCK(blocks, op_start, i + 1)  ||
527 528
                    !PyObject_IsTrue(PyList_GET_ITEM(consts, get_arg(codestr, i))))
                    break;
529
                fill_nops(codestr, op_start, nexti + 1);
530
                CONST_STACK_POP(1);
531 532
                break;

533 534
                /* Try to fold tuples of constants (includes a case for lists
                   and sets which are only used for "in" and "not in" tests).
535 536 537 538 539 540
                   Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
                   Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
                   Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
            case BUILD_TUPLE:
            case BUILD_LIST:
            case BUILD_SET:
541 542 543 544 545 546 547
                j = get_arg(codestr, i);
                if (j > 0 && CONST_STACK_LEN() >= j) {
                    h = lastn_const_start(codestr, op_start, j);
                    if ((opcode == BUILD_TUPLE &&
                          ISBASICBLOCK(blocks, h, op_start)) ||
                         ((opcode == BUILD_LIST || opcode == BUILD_SET) &&
                          ((nextop==COMPARE_OP &&
548 549 550 551
                          (_Py_OPARG(codestr[nexti]) == PyCmp_IN ||
                           _Py_OPARG(codestr[nexti]) == PyCmp_NOT_IN)) ||
                          nextop == GET_ITER) && ISBASICBLOCK(blocks, h, i + 1))) {
                        h = fold_tuple_on_constants(codestr, h, i + 1, opcode,
552 553 554 555 556 557 558
                                                    consts, CONST_STACK_LASTN(j), j);
                        if (h >= 0) {
                            CONST_STACK_POP(j);
                            CONST_STACK_PUSH_OP(h);
                        }
                        break;
                    }
559
                }
560
                if (nextop != UNPACK_SEQUENCE  ||
561
                    !ISBASICBLOCK(blocks, op_start, i + 1) ||
562
                    j != get_arg(codestr, nexti) ||
563
                    opcode == BUILD_SET)
564 565
                    break;
                if (j < 2) {
566
                    fill_nops(codestr, op_start, nexti + 1);
567
                } else if (j == 2) {
568 569
                    codestr[op_start] = PACKOPARG(ROT_TWO, 0);
                    fill_nops(codestr, op_start + 1, nexti + 1);
570
                    CONST_STACK_RESET();
571
                } else if (j == 3) {
572 573 574
                    codestr[op_start] = PACKOPARG(ROT_THREE, 0);
                    codestr[op_start + 1] = PACKOPARG(ROT_TWO, 0);
                    fill_nops(codestr, op_start + 2, nexti + 1);
575
                    CONST_STACK_RESET();
576 577 578 579
                }
                break;

                /* Fold binary ops on constants.
580
                   LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
581 582 583 584 585 586 587 588 589 590 591 592 593
            case BINARY_POWER:
            case BINARY_MULTIPLY:
            case BINARY_TRUE_DIVIDE:
            case BINARY_FLOOR_DIVIDE:
            case BINARY_MODULO:
            case BINARY_ADD:
            case BINARY_SUBTRACT:
            case BINARY_SUBSCR:
            case BINARY_LSHIFT:
            case BINARY_RSHIFT:
            case BINARY_AND:
            case BINARY_XOR:
            case BINARY_OR:
594 595 596 597
                if (CONST_STACK_LEN() < 2)
                    break;
                h = lastn_const_start(codestr, op_start, 2);
                if (ISBASICBLOCK(blocks, h, op_start)) {
598
                    h = fold_binops_on_constants(codestr, h, i + 1, opcode,
599 600 601 602 603
                                                 consts, CONST_STACK_LASTN(2));
                    if (h >= 0) {
                        CONST_STACK_POP(2);
                        CONST_STACK_PUSH_OP(h);
                    }
604 605 606 607
                }
                break;

                /* Fold unary ops on constants.
608
                   LOAD_CONST c1  UNARY_OP --> LOAD_CONST unary_op(c) */
609 610 611
            case UNARY_NEGATIVE:
            case UNARY_INVERT:
            case UNARY_POSITIVE:
612 613 614 615
                if (CONST_STACK_LEN() < 1)
                    break;
                h = lastn_const_start(codestr, op_start, 1);
                if (ISBASICBLOCK(blocks, h, op_start)) {
616
                    h = fold_unaryops_on_constants(codestr, h, i + 1, opcode,
617 618 619 620 621
                                                   consts, *CONST_STACK_LASTN(1));
                    if (h >= 0) {
                        CONST_STACK_POP(1);
                        CONST_STACK_PUSH_OP(h);
                    }
622 623 624 625 626 627 628 629 630 631 632 633 634 635
                }
                break;

                /* Simplify conditional jump to conditional jump where the
                   result of the first test implies the success of a similar
                   test or the failure of the opposite test.
                   Arises in code like:
                   "if a and b:"
                   "if a or b:"
                   "a and b or c"
                   "(a and b) and c"
                   x:JUMP_IF_FALSE_OR_POP y   y:JUMP_IF_FALSE_OR_POP z
                      -->  x:JUMP_IF_FALSE_OR_POP z
                   x:JUMP_IF_FALSE_OR_POP y   y:JUMP_IF_TRUE_OR_POP z
636 637
                      -->  x:POP_JUMP_IF_FALSE y+1
                   where y+1 is the instruction following the second test.
638 639 640
                */
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
641
                h = get_arg(codestr, i) / sizeof(_Py_CODEUNIT);
642 643
                tgt = find_op(codestr, h);

644
                j = _Py_OPCODE(codestr[tgt]);
645
                if (CONDITIONAL_JUMP(j)) {
646
                    /* NOTE: all possible jumps here are absolute. */
647
                    if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
648 649 650
                        /* The second jump will be taken iff the first is.
                           The current opcode inherits its target's
                           stack effect */
651
                        h = set_arg(codestr, i, get_arg(codestr, tgt));
652
                    } else {
653 654 655 656
                        /* The second jump is not taken if the first is (so
                           jump past it), and all conditional jumps pop their
                           argument when they're not taken (so change the
                           first jump to pop its argument when it's taken). */
657
                        h = set_arg(codestr, i, (tgt + 1) * sizeof(_Py_CODEUNIT));
658 659 660 661 662 663
                        j = opcode == JUMP_IF_TRUE_OR_POP ?
                            POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE;
                    }

                    if (h >= 0) {
                        nexti = h;
664
                        codestr[nexti] = PACKOPARG(j, _Py_OPARG(codestr[nexti]));
665
                        break;
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
                    }
                }
                /* Intentional fallthrough */

                /* Replace jumps to unconditional jumps */
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case FOR_ITER:
            case JUMP_FORWARD:
            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
681
            case SETUP_ASYNC_WITH:
682 683
                h = GETJUMPTGT(codestr, i);
                tgt = find_op(codestr, h);
684 685
                /* Replace JUMP_* to a RETURN into just a RETURN */
                if (UNCONDITIONAL_JUMP(opcode) &&
686 687 688 689
                    _Py_OPCODE(codestr[tgt]) == RETURN_VALUE) {
                    codestr[op_start] = PACKOPARG(RETURN_VALUE, 0);
                    fill_nops(codestr, op_start + 1, i + 1);
                } else if (UNCONDITIONAL_JUMP(_Py_OPCODE(codestr[tgt]))) {
690 691 692 693
                    j = GETJUMPTGT(codestr, tgt);
                    if (opcode == JUMP_FORWARD) { /* JMP_ABS can go backwards */
                        opcode = JUMP_ABSOLUTE;
                    } else if (!ABSOLUTE_JUMP(opcode)) {
694
                        if ((Py_ssize_t)j < i + 1) {
695 696
                            break;           /* No backward relative jumps */
                        }
697
                        j -= i + 1;          /* Calc relative jump addr */
698
                    }
699 700
                    j *= sizeof(_Py_CODEUNIT);
                    copy_op_arg(codestr, op_start, opcode, j, i + 1);
701 702 703
                }
                break;

704
                /* Remove unreachable ops after RETURN */
705
            case RETURN_VALUE:
706 707 708
                h = i + 1;
                while (h + 1 < codelen && ISBASICBLOCK(blocks, i, h + 1)) {
                    h++;
709
                }
710 711
                if (h > i + 1) {
                    fill_nops(codestr, i + 1, h + 1);
712 713
                    nexti = find_op(codestr, h);
                }
714 715 716 717
                break;
        }
    }

718
    /* Fixup lnotab */
719
    for (i = 0, nops = 0; i < codelen; i++) {
720
        assert(i - nops <= INT_MAX);
721
        /* original code offset => new code offset */
722
        blocks[i] = i - nops;
723 724
        if (_Py_OPCODE(codestr[i]) == NOP)
            nops++;
725
    }
726 727
    cum_orig_offset = 0;
    last_offset = 0;
728
    for (i=0 ; i < tabsiz ; i+=2) {
729
        unsigned int offset_delta, new_offset;
730
        cum_orig_offset += lnotab[i];
731 732 733
        assert(cum_orig_offset % sizeof(_Py_CODEUNIT) == 0);
        new_offset = blocks[cum_orig_offset / sizeof(_Py_CODEUNIT)] *
                sizeof(_Py_CODEUNIT);
734
        offset_delta = new_offset - last_offset;
735
        assert(offset_delta <= 255);
736 737
        lnotab[i] = (unsigned char)offset_delta;
        last_offset = new_offset;
738 739 740
    }

    /* Remove NOPs and fixup jump targets */
741 742 743 744 745
    for (op_start = i = h = 0; i < codelen; i++, op_start = i) {
        j = _Py_OPARG(codestr[i]);
        while (_Py_OPCODE(codestr[i]) == EXTENDED_ARG) {
            i++;
            j = j<<8 | _Py_OPARG(codestr[i]);
746
        }
747
        opcode = _Py_OPCODE(codestr[i]);
748
        switch (opcode) {
749
            case NOP:continue;
750 751 752 753 754 755 756

            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
757
                j = blocks[j / sizeof(_Py_CODEUNIT)] * sizeof(_Py_CODEUNIT);
758 759 760 761 762 763 764 765
                break;

            case FOR_ITER:
            case JUMP_FORWARD:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
766
            case SETUP_ASYNC_WITH:
767 768
                j = blocks[j / sizeof(_Py_CODEUNIT) + i + 1] - blocks[i] - 1;
                j *= sizeof(_Py_CODEUNIT);
769 770
                break;
        }
771
        nexti = i - op_start + 1;
772 773 774 775 776
        if (instrsize(j) > nexti)
            goto exitUnchanged;
        /* If instrsize(j) < nexti, we'll emit EXTENDED_ARG 0 */
        write_op_arg(codestr + h, opcode, j, nexti);
        h += nexti;
777
    }
778
    assert(h + (Py_ssize_t)nops == codelen);
779

780
    CONST_STACK_DELETE();
781
    PyMem_Free(blocks);
782
    code = PyBytes_FromStringAndSize((char *)codestr, h * sizeof(_Py_CODEUNIT));
783
    PyMem_Free(codestr);
784
    return code;
785

786
 exitError:
787
    code = NULL;
788

789
 exitUnchanged:
790
    Py_XINCREF(code);
791
    CONST_STACK_DELETE();
792 793
    PyMem_Free(blocks);
    PyMem_Free(codestr);
794
    return code;
795
}