Coverage Report

Created: 2025-11-02 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/flowgraph.c
Line
Count
Source
1
#include "Python.h"
2
#include "opcode.h"
3
#include "pycore_c_array.h"       // _Py_CArray_EnsureCapacity
4
#include "pycore_flowgraph.h"
5
#include "pycore_compile.h"
6
#include "pycore_intrinsics.h"
7
#include "pycore_pymem.h"         // _PyMem_IsPtrFreed()
8
#include "pycore_long.h"          // _PY_IS_SMALL_INT()
9
10
#include "pycore_opcode_utils.h"
11
#include "pycore_opcode_metadata.h" // OPCODE_HAS_ARG, etc
12
13
#include <stdbool.h>
14
15
16
#undef SUCCESS
17
#undef ERROR
18
1.23M
#define SUCCESS 0
19
6.99k
#define ERROR -1
20
21
#define RETURN_IF_ERROR(X)  \
22
1.94M
    if ((X) == -1) {        \
23
0
        return ERROR;       \
24
0
    }
25
26
414k
#define DEFAULT_BLOCK_SIZE 16
27
28
typedef _Py_SourceLocation location;
29
typedef _PyJumpTargetLabel jump_target_label;
30
31
typedef struct _PyCfgInstruction {
32
    int i_opcode;
33
    int i_oparg;
34
    _Py_SourceLocation i_loc;
35
    struct _PyCfgBasicblock *i_target; /* target block (if jump instruction) */
36
    struct _PyCfgBasicblock *i_except; /* target block when exception is raised */
37
} cfg_instr;
38
39
typedef struct _PyCfgBasicblock {
40
    /* Each basicblock in a compilation unit is linked via b_list in the
41
       reverse order that the block are allocated.  b_list points to the next
42
       block in this list, not to be confused with b_next, which is next by
43
       control flow. */
44
    struct _PyCfgBasicblock *b_list;
45
    /* The label of this block if it is a jump target, -1 otherwise */
46
    _PyJumpTargetLabel b_label;
47
    /* Exception stack at start of block, used by assembler to create the exception handling table */
48
    struct _PyCfgExceptStack *b_exceptstack;
49
    /* pointer to an array of instructions, initially NULL */
50
    cfg_instr *b_instr;
51
    /* If b_next is non-NULL, it is a pointer to the next
52
       block reached by normal control flow. */
53
    struct _PyCfgBasicblock *b_next;
54
    /* number of instructions used */
55
    int b_iused;
56
    /* length of instruction array (b_instr) */
57
    int b_ialloc;
58
    /* Used by add_checks_for_loads_of_unknown_variables */
59
    uint64_t b_unsafe_locals_mask;
60
    /* Number of predecessors that a block has. */
61
    int b_predecessors;
62
    /* depth of stack upon entry of block, computed by stackdepth() */
63
    int b_startdepth;
64
    /* Basic block is an exception handler that preserves lasti */
65
    unsigned b_preserve_lasti : 1;
66
    /* Used by compiler passes to mark whether they have visited a basic block. */
67
    unsigned b_visited : 1;
68
    /* b_except_handler is used by the cold-detection algorithm to mark exception targets */
69
    unsigned b_except_handler : 1;
70
    /* b_cold is true if this block is not perf critical (like an exception handler) */
71
    unsigned b_cold : 1;
72
    /* b_warm is used by the cold-detection algorithm to mark blocks which are definitely not cold */
73
    unsigned b_warm : 1;
74
} basicblock;
75
76
77
struct _PyCfgBuilder {
78
    /* The entryblock, at which control flow begins. All blocks of the
79
       CFG are reachable through the b_next links */
80
    struct _PyCfgBasicblock *g_entryblock;
81
    /* Pointer to the most recently allocated block.  By following
82
       b_list links, you can reach all allocated blocks. */
83
    struct _PyCfgBasicblock *g_block_list;
84
    /* pointer to the block currently being constructed */
85
    struct _PyCfgBasicblock *g_curblock;
86
    /* label for the next instruction to be placed */
87
    _PyJumpTargetLabel g_current_label;
88
};
89
90
typedef struct _PyCfgBuilder cfg_builder;
91
92
425k
#define SAME_LABEL(L1, L2) ((L1).id == (L2).id)
93
425k
#define IS_LABEL(L) (!SAME_LABEL((L), (NO_LABEL)))
94
95
#define LOCATION(LNO, END_LNO, COL, END_COL) \
96
385
    ((const _Py_SourceLocation){(LNO), (END_LNO), (COL), (END_COL)})
97
98
static inline int
99
is_block_push(cfg_instr *i)
100
1.80M
{
101
1.80M
    assert(OPCODE_HAS_ARG(i->i_opcode) || !IS_BLOCK_PUSH_OPCODE(i->i_opcode));
102
1.80M
    return IS_BLOCK_PUSH_OPCODE(i->i_opcode);
103
1.80M
}
104
105
static inline int
106
is_jump(cfg_instr *i)
107
1.66M
{
108
1.66M
    return OPCODE_HAS_JUMP(i->i_opcode);
109
1.66M
}
110
111
/* One arg*/
112
#define INSTR_SET_OP1(I, OP, ARG) \
113
42.5k
    do { \
114
42.5k
        assert(OPCODE_HAS_ARG(OP)); \
115
42.5k
        cfg_instr *_instr__ptr_ = (I); \
116
42.5k
        _instr__ptr_->i_opcode = (OP); \
117
42.5k
        _instr__ptr_->i_oparg = (ARG); \
118
42.5k
    } while (0);
119
120
/* No args*/
121
#define INSTR_SET_OP0(I, OP) \
122
88.4k
    do { \
123
88.4k
        assert(!OPCODE_HAS_ARG(OP)); \
124
88.4k
        cfg_instr *_instr__ptr_ = (I); \
125
88.4k
        _instr__ptr_->i_opcode = (OP); \
126
88.4k
        _instr__ptr_->i_oparg = 0; \
127
88.4k
    } while (0);
128
129
#define INSTR_SET_LOC(I, LOC) \
130
5.06k
    do { \
131
5.06k
        cfg_instr *_instr__ptr_ = (I); \
132
5.06k
        _instr__ptr_->i_loc = (LOC); \
133
5.06k
    } while (0);
134
135
/***** Blocks *****/
136
137
/* Returns the offset of the next instruction in the current block's
138
   b_instr array.  Resizes the b_instr as necessary.
139
   Returns -1 on failure.
140
*/
141
static int
142
basicblock_next_instr(basicblock *b)
143
414k
{
144
414k
    assert(b != NULL);
145
414k
    _Py_c_array_t array = {
146
414k
        .array = (void*)b->b_instr,
147
414k
        .allocated_entries = b->b_ialloc,
148
414k
        .item_size = sizeof(cfg_instr),
149
414k
        .initial_num_entries = DEFAULT_BLOCK_SIZE,
150
414k
    };
151
152
414k
    RETURN_IF_ERROR(_Py_CArray_EnsureCapacity(&array, b->b_iused + 1));
153
414k
    b->b_instr = array.array;
154
414k
    b->b_ialloc = array.allocated_entries;
155
414k
    return b->b_iused++;
156
414k
}
157
158
static cfg_instr *
159
1.56M
basicblock_last_instr(const basicblock *b) {
160
1.56M
    assert(b->b_iused >= 0);
161
1.56M
    if (b->b_iused > 0) {
162
1.43M
        assert(b->b_instr != NULL);
163
1.43M
        return &b->b_instr[b->b_iused - 1];
164
1.43M
    }
165
121k
    return NULL;
166
1.56M
}
167
168
/* Allocate a new block and return a pointer to it.
169
   Returns NULL on error.
170
*/
171
172
static basicblock *
173
cfg_builder_new_block(cfg_builder *g)
174
49.1k
{
175
49.1k
    basicblock *b = (basicblock *)PyMem_Calloc(1, sizeof(basicblock));
176
49.1k
    if (b == NULL) {
177
0
        PyErr_NoMemory();
178
0
        return NULL;
179
0
    }
180
    /* Extend the singly linked list of blocks with new block. */
181
49.1k
    b->b_list = g->g_block_list;
182
49.1k
    g->g_block_list = b;
183
49.1k
    b->b_label = NO_LABEL;
184
49.1k
    return b;
185
49.1k
}
186
187
static int
188
basicblock_addop(basicblock *b, int opcode, int oparg, location loc)
189
405k
{
190
405k
    assert(IS_WITHIN_OPCODE_RANGE(opcode));
191
405k
    assert(!IS_ASSEMBLER_OPCODE(opcode));
192
405k
    assert(OPCODE_HAS_ARG(opcode) || HAS_TARGET(opcode) || oparg == 0);
193
405k
    assert(0 <= oparg && oparg < (1 << 30));
194
195
405k
    int off = basicblock_next_instr(b);
196
405k
    if (off < 0) {
197
0
        return ERROR;
198
0
    }
199
405k
    cfg_instr *i = &b->b_instr[off];
200
405k
    i->i_opcode = opcode;
201
405k
    i->i_oparg = oparg;
202
405k
    i->i_loc = loc;
203
    // memory is already zero initialized
204
405k
    assert(i->i_target == NULL);
205
405k
    assert(i->i_except == NULL);
206
207
405k
    return SUCCESS;
208
405k
}
209
210
static int
211
basicblock_add_jump(basicblock *b, int opcode, basicblock *target, location loc)
212
1.59k
{
213
1.59k
    cfg_instr *last = basicblock_last_instr(b);
214
1.59k
    if (last && is_jump(last)) {
215
0
        return ERROR;
216
0
    }
217
218
1.59k
    RETURN_IF_ERROR(
219
1.59k
        basicblock_addop(b, opcode, target->b_label.id, loc));
220
1.59k
    last = basicblock_last_instr(b);
221
1.59k
    assert(last && last->i_opcode == opcode);
222
1.59k
    last->i_target = target;
223
1.59k
    return SUCCESS;
224
1.59k
}
225
226
static inline int
227
basicblock_append_instructions(basicblock *to, basicblock *from)
228
3.38k
{
229
8.84k
    for (int i = 0; i < from->b_iused; i++) {
230
5.45k
        int n = basicblock_next_instr(to);
231
5.45k
        if (n < 0) {
232
0
            return ERROR;
233
0
        }
234
5.45k
        to->b_instr[n] = from->b_instr[i];
235
5.45k
    }
236
3.38k
    return SUCCESS;
237
3.38k
}
238
239
static inline int
240
489k
basicblock_nofallthrough(const basicblock *b) {
241
489k
    cfg_instr *last = basicblock_last_instr(b);
242
489k
    return (last &&
243
464k
            (IS_SCOPE_EXIT_OPCODE(last->i_opcode) ||
244
305k
             IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)));
245
489k
}
246
247
#define BB_NO_FALLTHROUGH(B) (basicblock_nofallthrough(B))
248
789k
#define BB_HAS_FALLTHROUGH(B) (!basicblock_nofallthrough(B))
249
250
static basicblock *
251
copy_basicblock(cfg_builder *g, basicblock *block)
252
651
{
253
    /* Cannot copy a block if it has a fallthrough, since
254
     * a block can only have one fallthrough predecessor.
255
     */
256
651
    assert(BB_NO_FALLTHROUGH(block));
257
651
    basicblock *result = cfg_builder_new_block(g);
258
651
    if (result == NULL) {
259
0
        return NULL;
260
0
    }
261
651
    if (basicblock_append_instructions(result, block) < 0) {
262
0
        return NULL;
263
0
    }
264
651
    return result;
265
651
}
266
267
static int
268
3.97k
basicblock_insert_instruction(basicblock *block, int pos, cfg_instr *instr) {
269
3.97k
    RETURN_IF_ERROR(basicblock_next_instr(block));
270
74.3k
    for (int i = block->b_iused - 1; i > pos; i--) {
271
70.3k
        block->b_instr[i] = block->b_instr[i-1];
272
70.3k
    }
273
3.97k
    block->b_instr[pos] = *instr;
274
3.97k
    return SUCCESS;
275
3.97k
}
276
277
/* For debugging purposes only */
278
#if 0
279
static void
280
dump_instr(cfg_instr *i)
281
{
282
    const char *jump = is_jump(i) ? "jump " : "";
283
284
    char arg[128];
285
286
    *arg = '\0';
287
    if (OPCODE_HAS_ARG(i->i_opcode)) {
288
        sprintf(arg, "arg: %d ", i->i_oparg);
289
    }
290
    if (HAS_TARGET(i->i_opcode)) {
291
        sprintf(arg, "target: %p [%d] ", i->i_target, i->i_oparg);
292
    }
293
    fprintf(stderr, "line: %d, %s (%d)  %s%s\n",
294
                    i->i_loc.lineno, _PyOpcode_OpName[i->i_opcode], i->i_opcode, arg, jump);
295
}
296
297
static inline int
298
basicblock_returns(const basicblock *b) {
299
    cfg_instr *last = basicblock_last_instr(b);
300
    return last && IS_RETURN_OPCODE(last->i_opcode);
301
}
302
303
static void
304
dump_basicblock(const basicblock *b, bool highlight)
305
{
306
    const char *b_return = basicblock_returns(b) ? "return " : "";
307
    if (highlight) {
308
        fprintf(stderr, ">>> ");
309
    }
310
    fprintf(stderr, "%d: [EH=%d CLD=%d WRM=%d NO_FT=%d %p] used: %d, depth: %d, preds: %d %s\n",
311
        b->b_label.id, b->b_except_handler, b->b_cold, b->b_warm, BB_NO_FALLTHROUGH(b), b, b->b_iused,
312
        b->b_startdepth, b->b_predecessors, b_return);
313
    int depth = b->b_startdepth;
314
    if (b->b_instr) {
315
        int i;
316
        for (i = 0; i < b->b_iused; i++) {
317
            fprintf(stderr, "  [%02d] depth: %d ", i, depth);
318
            dump_instr(b->b_instr + i);
319
320
            int popped = _PyOpcode_num_popped(b->b_instr[i].i_opcode, b->b_instr[i].i_oparg);
321
            int pushed = _PyOpcode_num_pushed(b->b_instr[i].i_opcode, b->b_instr[i].i_oparg);
322
            depth += (pushed - popped);
323
        }
324
    }
325
}
326
327
void
328
_PyCfgBuilder_DumpGraph(const basicblock *entryblock, const basicblock *mark)
329
{
330
    for (const basicblock *b = entryblock; b != NULL; b = b->b_next) {
331
        dump_basicblock(b, b == mark);
332
    }
333
}
334
335
#endif
336
337
338
/***** CFG construction and modification *****/
339
340
static basicblock *
341
cfg_builder_use_next_block(cfg_builder *g, basicblock *block)
342
40.6k
{
343
40.6k
    assert(block != NULL);
344
40.6k
    g->g_curblock->b_next = block;
345
40.6k
    g->g_curblock = block;
346
40.6k
    return block;
347
40.6k
}
348
349
static inline int
350
94.4k
basicblock_exits_scope(const basicblock *b) {
351
94.4k
    cfg_instr *last = basicblock_last_instr(b);
352
94.4k
    return last && IS_SCOPE_EXIT_OPCODE(last->i_opcode);
353
94.4k
}
354
355
static inline int
356
60.1k
basicblock_has_eval_break(const basicblock *b) {
357
294k
    for (int i = 0; i < b->b_iused; i++) {
358
258k
        if (OPCODE_HAS_EVAL_BREAK(b->b_instr[i].i_opcode)) {
359
24.2k
            return true;
360
24.2k
        }
361
258k
    }
362
35.9k
    return false;
363
60.1k
}
364
365
static bool
366
cfg_builder_current_block_is_terminated(cfg_builder *g)
367
411k
{
368
411k
    cfg_instr *last = basicblock_last_instr(g->g_curblock);
369
411k
    if (last && IS_TERMINATOR_OPCODE(last->i_opcode)) {
370
34.6k
        return true;
371
34.6k
    }
372
376k
    if (IS_LABEL(g->g_current_label)) {
373
6.03k
        if (last || IS_LABEL(g->g_curblock->b_label)) {
374
6.03k
            return true;
375
6.03k
        }
376
0
        else {
377
            /* current block is empty, label it */
378
0
            g->g_curblock->b_label = g->g_current_label;
379
0
            g->g_current_label = NO_LABEL;
380
0
        }
381
6.03k
    }
382
370k
    return false;
383
376k
}
384
385
static int
386
cfg_builder_maybe_start_new_block(cfg_builder *g)
387
411k
{
388
411k
    if (cfg_builder_current_block_is_terminated(g)) {
389
40.6k
        basicblock *b = cfg_builder_new_block(g);
390
40.6k
        if (b == NULL) {
391
0
            return ERROR;
392
0
        }
393
40.6k
        b->b_label = g->g_current_label;
394
40.6k
        g->g_current_label = NO_LABEL;
395
40.6k
        cfg_builder_use_next_block(g, b);
396
40.6k
    }
397
411k
    return SUCCESS;
398
411k
}
399
400
#ifndef NDEBUG
401
static bool
402
cfg_builder_check(cfg_builder *g)
403
{
404
    assert(g->g_entryblock->b_iused > 0);
405
    for (basicblock *block = g->g_block_list; block != NULL; block = block->b_list) {
406
        assert(!_PyMem_IsPtrFreed(block));
407
        if (block->b_instr != NULL) {
408
            assert(block->b_ialloc > 0);
409
            assert(block->b_iused >= 0);
410
            assert(block->b_ialloc >= block->b_iused);
411
        }
412
        else {
413
            assert (block->b_iused == 0);
414
            assert (block->b_ialloc == 0);
415
        }
416
    }
417
    return true;
418
}
419
#endif
420
421
static int
422
init_cfg_builder(cfg_builder *g)
423
6.99k
{
424
6.99k
    g->g_block_list = NULL;
425
6.99k
    basicblock *block = cfg_builder_new_block(g);
426
6.99k
    if (block == NULL) {
427
0
        return ERROR;
428
0
    }
429
6.99k
    g->g_curblock = g->g_entryblock = block;
430
6.99k
    g->g_current_label = NO_LABEL;
431
6.99k
    return SUCCESS;
432
6.99k
}
433
434
cfg_builder *
435
_PyCfgBuilder_New(void)
436
6.99k
{
437
6.99k
    cfg_builder *g = PyMem_Malloc(sizeof(cfg_builder));
438
6.99k
    if (g == NULL) {
439
0
        PyErr_NoMemory();
440
0
        return NULL;
441
0
    }
442
6.99k
    memset(g, 0, sizeof(cfg_builder));
443
6.99k
    if (init_cfg_builder(g) < 0) {
444
0
        PyMem_Free(g);
445
0
        return NULL;
446
0
    }
447
6.99k
    return g;
448
6.99k
}
449
450
void
451
_PyCfgBuilder_Free(cfg_builder *g)
452
6.99k
{
453
6.99k
    if (g == NULL) {
454
0
        return;
455
0
    }
456
6.99k
    assert(cfg_builder_check(g));
457
6.99k
    basicblock *b = g->g_block_list;
458
56.1k
    while (b != NULL) {
459
49.1k
        if (b->b_instr) {
460
49.1k
            PyMem_Free((void *)b->b_instr);
461
49.1k
        }
462
49.1k
        basicblock *next = b->b_list;
463
49.1k
        PyMem_Free((void *)b);
464
49.1k
        b = next;
465
49.1k
    }
466
6.99k
    PyMem_Free(g);
467
6.99k
}
468
469
int
470
_PyCfgBuilder_CheckSize(cfg_builder *g)
471
6.99k
{
472
6.99k
    int nblocks = 0;
473
54.6k
    for (basicblock *b = g->g_block_list; b != NULL; b = b->b_list) {
474
47.6k
        nblocks++;
475
47.6k
    }
476
6.99k
    if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
477
0
        PyErr_NoMemory();
478
0
        return ERROR;
479
0
    }
480
6.99k
    return SUCCESS;
481
6.99k
}
482
483
int
484
_PyCfgBuilder_UseLabel(cfg_builder *g, jump_target_label lbl)
485
20.3k
{
486
20.3k
    g->g_current_label = lbl;
487
20.3k
    return cfg_builder_maybe_start_new_block(g);
488
20.3k
}
489
490
int
491
_PyCfgBuilder_Addop(cfg_builder *g, int opcode, int oparg, location loc)
492
391k
{
493
391k
    RETURN_IF_ERROR(cfg_builder_maybe_start_new_block(g));
494
391k
    return basicblock_addop(g->g_curblock, opcode, oparg, loc);
495
391k
}
496
497
498
static basicblock *
499
next_nonempty_block(basicblock *b)
500
82.9k
{
501
86.5k
    while (b && b->b_iused == 0) {
502
3.62k
        b = b->b_next;
503
3.62k
    }
504
82.9k
    return b;
505
82.9k
}
506
507
/***** debugging helpers *****/
508
509
#ifndef NDEBUG
510
static int remove_redundant_nops(cfg_builder *g);
511
512
static bool
513
no_redundant_nops(cfg_builder *g) {
514
    if (remove_redundant_nops(g) != 0) {
515
        return false;
516
    }
517
    return true;
518
}
519
520
static bool
521
no_redundant_jumps(cfg_builder *g) {
522
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
523
        cfg_instr *last = basicblock_last_instr(b);
524
        if (last != NULL) {
525
            if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
526
                basicblock *next = next_nonempty_block(b->b_next);
527
                basicblock *jump_target = next_nonempty_block(last->i_target);
528
                if (jump_target == next) {
529
                    assert(next);
530
                    if (last->i_loc.lineno == next->b_instr[0].i_loc.lineno) {
531
                        assert(0);
532
                        return false;
533
                    }
534
                }
535
            }
536
        }
537
    }
538
    return true;
539
}
540
#endif
541
542
/***** CFG preprocessing (jump targets and exceptions) *****/
543
544
static int
545
49.1k
normalize_jumps_in_block(cfg_builder *g, basicblock *b) {
546
49.1k
    cfg_instr *last = basicblock_last_instr(b);
547
49.1k
    if (last == NULL || !IS_CONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
548
36.7k
        return SUCCESS;
549
36.7k
    }
550
49.1k
    assert(!IS_ASSEMBLER_OPCODE(last->i_opcode));
551
552
12.3k
    bool is_forward = last->i_target->b_visited == 0;
553
12.3k
    if (is_forward) {
554
11.5k
        RETURN_IF_ERROR(
555
11.5k
            basicblock_addop(b, NOT_TAKEN, 0, last->i_loc));
556
11.5k
        return SUCCESS;
557
11.5k
    }
558
559
824
    int reversed_opcode = 0;
560
824
    switch(last->i_opcode) {
561
30
        case POP_JUMP_IF_NOT_NONE:
562
30
            reversed_opcode = POP_JUMP_IF_NONE;
563
30
            break;
564
36
        case POP_JUMP_IF_NONE:
565
36
            reversed_opcode = POP_JUMP_IF_NOT_NONE;
566
36
            break;
567
681
        case POP_JUMP_IF_FALSE:
568
681
            reversed_opcode = POP_JUMP_IF_TRUE;
569
681
            break;
570
77
        case POP_JUMP_IF_TRUE:
571
77
            reversed_opcode = POP_JUMP_IF_FALSE;
572
77
            break;
573
824
    }
574
    /* transform 'conditional jump T' to
575
     * 'reversed_jump b_next' followed by 'jump_backwards T'
576
     */
577
578
824
    basicblock *target = last->i_target;
579
824
    basicblock *backwards_jump = cfg_builder_new_block(g);
580
824
    if (backwards_jump == NULL) {
581
0
        return ERROR;
582
0
    }
583
824
    RETURN_IF_ERROR(
584
824
        basicblock_addop(backwards_jump, NOT_TAKEN, 0, last->i_loc));
585
824
    RETURN_IF_ERROR(
586
824
        basicblock_add_jump(backwards_jump, JUMP, target, last->i_loc));
587
824
    backwards_jump->b_startdepth = target->b_startdepth;
588
824
    last->i_opcode = reversed_opcode;
589
824
    last->i_target = b->b_next;
590
591
824
    backwards_jump->b_cold = b->b_cold;
592
824
    backwards_jump->b_next = b->b_next;
593
824
    b->b_next = backwards_jump;
594
824
    return SUCCESS;
595
824
}
596
597
598
static int
599
normalize_jumps(cfg_builder *g)
600
6.99k
{
601
6.99k
    basicblock *entryblock = g->g_entryblock;
602
55.3k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
603
48.3k
        b->b_visited = 0;
604
48.3k
    }
605
56.1k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
606
49.1k
        b->b_visited = 1;
607
49.1k
        RETURN_IF_ERROR(normalize_jumps_in_block(g, b));
608
49.1k
    }
609
6.99k
    return SUCCESS;
610
6.99k
}
611
612
static int
613
6.99k
check_cfg(cfg_builder *g) {
614
54.6k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
615
        /* Raise SystemError if jump or exit is not last instruction in the block. */
616
438k
        for (int i = 0; i < b->b_iused; i++) {
617
391k
            int opcode = b->b_instr[i].i_opcode;
618
391k
            assert(!IS_ASSEMBLER_OPCODE(opcode));
619
391k
            if (IS_TERMINATOR_OPCODE(opcode)) {
620
41.6k
                if (i != b->b_iused - 1) {
621
0
                    PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
622
0
                    return ERROR;
623
0
                }
624
41.6k
            }
625
391k
        }
626
47.6k
    }
627
6.99k
    return SUCCESS;
628
6.99k
}
629
630
static int
631
get_max_label(basicblock *entryblock)
632
27.2k
{
633
27.2k
    int lbl = -1;
634
218k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
635
191k
        if (b->b_label.id > lbl) {
636
73.9k
            lbl = b->b_label.id;
637
73.9k
        }
638
191k
    }
639
27.2k
    return lbl;
640
27.2k
}
641
642
/* Calculate the actual jump target from the target_label */
643
static int
644
translate_jump_labels_to_targets(basicblock *entryblock)
645
6.99k
{
646
6.99k
    int max_label = get_max_label(entryblock);
647
6.99k
    size_t mapsize = sizeof(basicblock *) * (max_label + 1);
648
6.99k
    basicblock **label2block = (basicblock **)PyMem_Malloc(mapsize);
649
6.99k
    if (!label2block) {
650
0
        PyErr_NoMemory();
651
0
        return ERROR;
652
0
    }
653
6.99k
    memset(label2block, 0, mapsize);
654
54.6k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
655
47.6k
        if (b->b_label.id >= 0) {
656
20.3k
            label2block[b->b_label.id] = b;
657
20.3k
        }
658
47.6k
    }
659
54.6k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
660
438k
        for (int i = 0; i < b->b_iused; i++) {
661
391k
            cfg_instr *instr = &b->b_instr[i];
662
391k
            assert(instr->i_target == NULL);
663
391k
            if (HAS_TARGET(instr->i_opcode)) {
664
25.1k
                int lbl = instr->i_oparg;
665
25.1k
                assert(lbl >= 0 && lbl <= max_label);
666
25.1k
                instr->i_target = label2block[lbl];
667
25.1k
                assert(instr->i_target != NULL);
668
25.1k
                assert(instr->i_target->b_label.id == lbl);
669
25.1k
            }
670
391k
        }
671
47.6k
    }
672
6.99k
    PyMem_Free(label2block);
673
6.99k
    return SUCCESS;
674
6.99k
}
675
676
static int
677
6.99k
mark_except_handlers(basicblock *entryblock) {
678
#ifndef NDEBUG
679
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
680
        assert(!b->b_except_handler);
681
    }
682
#endif
683
54.6k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
684
438k
        for (int i=0; i < b->b_iused; i++) {
685
391k
            cfg_instr *instr = &b->b_instr[i];
686
391k
            if (is_block_push(instr)) {
687
2.85k
                instr->i_target->b_except_handler = 1;
688
2.85k
            }
689
391k
        }
690
47.6k
    }
691
6.99k
    return SUCCESS;
692
6.99k
}
693
694
695
struct _PyCfgExceptStack {
696
    basicblock *handlers[CO_MAXBLOCKS+2];
697
    int depth;
698
};
699
700
701
static basicblock *
702
2.84k
push_except_block(struct _PyCfgExceptStack *stack, cfg_instr *setup) {
703
2.84k
    assert(is_block_push(setup));
704
2.84k
    int opcode = setup->i_opcode;
705
2.84k
    basicblock * target = setup->i_target;
706
2.84k
    if (opcode == SETUP_WITH || opcode == SETUP_CLEANUP) {
707
1.64k
        target->b_preserve_lasti = 1;
708
1.64k
    }
709
2.84k
    assert(stack->depth <= CO_MAXBLOCKS);
710
2.84k
    stack->handlers[++stack->depth] = target;
711
2.84k
    return target;
712
2.84k
}
713
714
static basicblock *
715
2.30k
pop_except_block(struct _PyCfgExceptStack *stack) {
716
2.30k
    assert(stack->depth > 0);
717
2.30k
    return stack->handlers[--stack->depth];
718
2.30k
}
719
720
static basicblock *
721
40.8k
except_stack_top(struct _PyCfgExceptStack *stack) {
722
40.8k
    return stack->handlers[stack->depth];
723
40.8k
}
724
725
static struct _PyCfgExceptStack *
726
6.99k
make_except_stack(void) {
727
6.99k
    struct _PyCfgExceptStack *new = PyMem_Malloc(sizeof(struct _PyCfgExceptStack));
728
6.99k
    if (new == NULL) {
729
0
        PyErr_NoMemory();
730
0
        return NULL;
731
0
    }
732
6.99k
    new->depth = 0;
733
6.99k
    new->handlers[0] = NULL;
734
6.99k
    return new;
735
6.99k
}
736
737
static struct _PyCfgExceptStack *
738
15.2k
copy_except_stack(struct _PyCfgExceptStack *stack) {
739
15.2k
    struct _PyCfgExceptStack *copy = PyMem_Malloc(sizeof(struct _PyCfgExceptStack));
740
15.2k
    if (copy == NULL) {
741
0
        PyErr_NoMemory();
742
0
        return NULL;
743
0
    }
744
15.2k
    memcpy(copy, stack, sizeof(struct _PyCfgExceptStack));
745
15.2k
    return copy;
746
15.2k
}
747
748
static basicblock**
749
52.8k
make_cfg_traversal_stack(basicblock *entryblock) {
750
52.8k
    int nblocks = 0;
751
433k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
752
380k
        b->b_visited = 0;
753
380k
        nblocks++;
754
380k
    }
755
52.8k
    basicblock **stack = (basicblock **)PyMem_Malloc(sizeof(basicblock *) * nblocks);
756
52.8k
    if (!stack) {
757
0
        PyErr_NoMemory();
758
0
    }
759
52.8k
    return stack;
760
52.8k
}
761
762
/* Compute the stack effects of opcode with argument oparg.
763
764
   Some opcodes have different stack effect when jump to the target and
765
   when not jump. The 'jump' parameter specifies the case:
766
767
   * 0 -- when not jump
768
   * 1 -- when jump
769
   * -1 -- maximal
770
 */
771
typedef struct {
772
    /* The stack effect of the instruction. */
773
    int net;
774
} stack_effects;
775
776
Py_LOCAL(int)
777
get_stack_effects(int opcode, int oparg, int jump, stack_effects *effects)
778
364k
{
779
364k
    if (opcode < 0) {
780
0
        return -1;
781
0
    }
782
364k
    if ((opcode <= MAX_REAL_OPCODE) && (_PyOpcode_Deopt[opcode] != opcode)) {
783
        // Specialized instructions are not supported.
784
0
        return -1;
785
0
    }
786
364k
    int popped = _PyOpcode_num_popped(opcode, oparg);
787
364k
    int pushed = _PyOpcode_num_pushed(opcode, oparg);
788
364k
    if (popped < 0 || pushed < 0) {
789
0
        return -1;
790
0
    }
791
364k
    if (IS_BLOCK_PUSH_OPCODE(opcode) && !jump) {
792
2.84k
        effects->net = 0;
793
2.84k
        return 0;
794
2.84k
    }
795
361k
    effects->net = pushed - popped;
796
361k
    return 0;
797
364k
}
798
799
Py_LOCAL_INLINE(int)
800
stackdepth_push(basicblock ***sp, basicblock *b, int depth)
801
50.2k
{
802
50.2k
    if (!(b->b_startdepth < 0 || b->b_startdepth == depth)) {
803
0
        PyErr_Format(PyExc_ValueError, "Invalid CFG, inconsistent stackdepth");
804
0
        return ERROR;
805
0
    }
806
50.2k
    if (b->b_startdepth < depth && b->b_startdepth < 100) {
807
40.6k
        assert(b->b_startdepth < 0);
808
40.6k
        b->b_startdepth = depth;
809
40.6k
        *(*sp)++ = b;
810
40.6k
    }
811
50.2k
    return SUCCESS;
812
50.2k
}
813
814
/* Find the flow path that needs the largest stack.  We assume that
815
 * cycles in the flow graph have no net effect on the stack depth.
816
 */
817
static int
818
calculate_stackdepth(cfg_builder *g)
819
6.99k
{
820
6.99k
    basicblock *entryblock = g->g_entryblock;
821
55.3k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
822
48.3k
        b->b_startdepth = INT_MIN;
823
48.3k
    }
824
6.99k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
825
6.99k
    if (!stack) {
826
0
        return ERROR;
827
0
    }
828
829
830
6.99k
    int stackdepth = -1;
831
6.99k
    int maxdepth = 0;
832
6.99k
    basicblock **sp = stack;
833
6.99k
    if (stackdepth_push(&sp, entryblock, 0) < 0) {
834
0
        goto error;
835
0
    }
836
47.6k
    while (sp != stack) {
837
40.6k
        basicblock *b = *--sp;
838
40.6k
        int depth = b->b_startdepth;
839
40.6k
        assert(depth >= 0);
840
40.6k
        basicblock *next = b->b_next;
841
363k
        for (int i = 0; i < b->b_iused; i++) {
842
342k
            cfg_instr *instr = &b->b_instr[i];
843
342k
            stack_effects effects;
844
342k
            if (get_stack_effects(instr->i_opcode, instr->i_oparg, 0, &effects) < 0) {
845
0
                PyErr_Format(PyExc_SystemError,
846
0
                             "Invalid stack effect for opcode=%d, arg=%i",
847
0
                             instr->i_opcode, instr->i_oparg);
848
0
                goto error;
849
0
            }
850
342k
            int new_depth = depth + effects.net;
851
342k
            if (new_depth < 0) {
852
0
                PyErr_Format(PyExc_ValueError,
853
0
                             "Invalid CFG, stack underflow");
854
0
                goto error;
855
0
            }
856
342k
            maxdepth = Py_MAX(maxdepth, depth);
857
342k
            if (HAS_TARGET(instr->i_opcode) && instr->i_opcode != END_ASYNC_FOR) {
858
21.9k
                if (get_stack_effects(instr->i_opcode, instr->i_oparg, 1, &effects) < 0) {
859
0
                    PyErr_Format(PyExc_SystemError,
860
0
                                 "Invalid stack effect for opcode=%d, arg=%i",
861
0
                                 instr->i_opcode, instr->i_oparg);
862
0
                    goto error;
863
0
                }
864
21.9k
                int target_depth = depth + effects.net;
865
21.9k
                assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
866
21.9k
                maxdepth = Py_MAX(maxdepth, depth);
867
21.9k
                if (stackdepth_push(&sp, instr->i_target, target_depth) < 0) {
868
0
                    goto error;
869
0
                }
870
21.9k
            }
871
342k
            depth = new_depth;
872
342k
            assert(!IS_ASSEMBLER_OPCODE(instr->i_opcode));
873
342k
            if (IS_UNCONDITIONAL_JUMP_OPCODE(instr->i_opcode) ||
874
337k
                IS_SCOPE_EXIT_OPCODE(instr->i_opcode))
875
19.3k
            {
876
                /* remaining code is dead */
877
19.3k
                next = NULL;
878
19.3k
                break;
879
19.3k
            }
880
342k
        }
881
40.6k
        if (next != NULL) {
882
21.3k
            assert(BB_HAS_FALLTHROUGH(b));
883
21.3k
            if (stackdepth_push(&sp, next, depth) < 0) {
884
0
                goto error;
885
0
            }
886
21.3k
        }
887
40.6k
    }
888
6.99k
    stackdepth = maxdepth;
889
6.99k
error:
890
6.99k
    PyMem_Free(stack);
891
6.99k
    return stackdepth;
892
6.99k
}
893
894
static int
895
6.99k
label_exception_targets(basicblock *entryblock) {
896
6.99k
    basicblock **todo_stack = make_cfg_traversal_stack(entryblock);
897
6.99k
    if (todo_stack == NULL) {
898
0
        return ERROR;
899
0
    }
900
6.99k
    struct _PyCfgExceptStack *except_stack = make_except_stack();
901
6.99k
    if (except_stack == NULL) {
902
0
        PyMem_Free(todo_stack);
903
0
        PyErr_NoMemory();
904
0
        return ERROR;
905
0
    }
906
6.99k
    except_stack->depth = 0;
907
6.99k
    todo_stack[0] = entryblock;
908
6.99k
    entryblock->b_visited = 1;
909
6.99k
    entryblock->b_exceptstack = except_stack;
910
6.99k
    basicblock **todo = &todo_stack[1];
911
6.99k
    basicblock *handler = NULL;
912
47.8k
    while (todo > todo_stack) {
913
40.8k
        todo--;
914
40.8k
        basicblock *b = todo[0];
915
40.8k
        assert(b->b_visited == 1);
916
40.8k
        except_stack = b->b_exceptstack;
917
40.8k
        assert(except_stack != NULL);
918
40.8k
        b->b_exceptstack = NULL;
919
40.8k
        handler = except_stack_top(except_stack);
920
40.8k
        int last_yield_except_depth = -1;
921
418k
        for (int i = 0; i < b->b_iused; i++) {
922
377k
            cfg_instr *instr = &b->b_instr[i];
923
377k
            if (is_block_push(instr)) {
924
2.84k
                if (!instr->i_target->b_visited) {
925
2.84k
                    struct _PyCfgExceptStack *copy = copy_except_stack(except_stack);
926
2.84k
                    if (copy == NULL) {
927
0
                        goto error;
928
0
                    }
929
2.84k
                    instr->i_target->b_exceptstack = copy;
930
2.84k
                    todo[0] = instr->i_target;
931
2.84k
                    instr->i_target->b_visited = 1;
932
2.84k
                    todo++;
933
2.84k
                }
934
2.84k
                handler = push_except_block(except_stack, instr);
935
2.84k
            }
936
374k
            else if (instr->i_opcode == POP_BLOCK) {
937
2.30k
                handler = pop_except_block(except_stack);
938
2.30k
                INSTR_SET_OP0(instr, NOP);
939
2.30k
            }
940
372k
            else if (is_jump(instr)) {
941
21.1k
                instr->i_except = handler;
942
21.1k
                assert(i == b->b_iused -1);
943
21.1k
                if (!instr->i_target->b_visited) {
944
15.0k
                    if (BB_HAS_FALLTHROUGH(b)) {
945
12.4k
                        struct _PyCfgExceptStack *copy = copy_except_stack(except_stack);
946
12.4k
                        if (copy == NULL) {
947
0
                            goto error;
948
0
                        }
949
12.4k
                        instr->i_target->b_exceptstack = copy;
950
12.4k
                    }
951
2.68k
                    else {
952
2.68k
                        instr->i_target->b_exceptstack = except_stack;
953
2.68k
                        except_stack = NULL;
954
2.68k
                    }
955
15.0k
                    todo[0] = instr->i_target;
956
15.0k
                    instr->i_target->b_visited = 1;
957
15.0k
                    todo++;
958
15.0k
                }
959
21.1k
            }
960
350k
            else if (instr->i_opcode == YIELD_VALUE) {
961
505
                instr->i_except = handler;
962
505
                last_yield_except_depth = except_stack->depth;
963
505
            }
964
350k
            else if (instr->i_opcode == RESUME) {
965
7.49k
                instr->i_except = handler;
966
7.49k
                if (instr->i_oparg != RESUME_AT_FUNC_START) {
967
505
                    assert(last_yield_except_depth >= 0);
968
505
                    if (last_yield_except_depth == 1) {
969
440
                        instr->i_oparg |= RESUME_OPARG_DEPTH1_MASK;
970
440
                    }
971
505
                    last_yield_except_depth = -1;
972
505
                }
973
7.49k
            }
974
342k
            else {
975
342k
                instr->i_except = handler;
976
342k
            }
977
377k
        }
978
40.8k
        if (BB_HAS_FALLTHROUGH(b) && !b->b_next->b_visited) {
979
15.9k
            assert(except_stack != NULL);
980
15.9k
            b->b_next->b_exceptstack = except_stack;
981
15.9k
            todo[0] = b->b_next;
982
15.9k
            b->b_next->b_visited = 1;
983
15.9k
            todo++;
984
15.9k
        }
985
24.9k
        else if (except_stack != NULL) {
986
22.2k
           PyMem_Free(except_stack);
987
22.2k
        }
988
40.8k
    }
989
#ifdef Py_DEBUG
990
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
991
        assert(b->b_exceptstack == NULL);
992
    }
993
#endif
994
6.99k
    PyMem_Free(todo_stack);
995
6.99k
    return SUCCESS;
996
0
error:
997
0
    PyMem_Free(todo_stack);
998
0
    PyMem_Free(except_stack);
999
0
    return ERROR;
1000
6.99k
}
1001
1002
/***** CFG optimizations *****/
1003
1004
static int
1005
13.9k
remove_unreachable(basicblock *entryblock) {
1006
109k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1007
95.9k
        b->b_predecessors = 0;
1008
95.9k
    }
1009
13.9k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
1010
13.9k
    if (stack == NULL) {
1011
0
        return ERROR;
1012
0
    }
1013
13.9k
    basicblock **sp = stack;
1014
13.9k
    entryblock->b_predecessors = 1;
1015
13.9k
    *sp++ = entryblock;
1016
13.9k
    entryblock->b_visited = 1;
1017
94.7k
    while (sp > stack) {
1018
80.7k
        basicblock *b = *(--sp);
1019
80.7k
        if (b->b_next && BB_HAS_FALLTHROUGH(b)) {
1020
40.6k
            if (!b->b_next->b_visited) {
1021
34.9k
                assert(b->b_next->b_predecessors == 0);
1022
34.9k
                *sp++ = b->b_next;
1023
34.9k
                b->b_next->b_visited = 1;
1024
34.9k
            }
1025
40.6k
            b->b_next->b_predecessors++;
1026
40.6k
        }
1027
809k
        for (int i = 0; i < b->b_iused; i++) {
1028
728k
            basicblock *target;
1029
728k
            cfg_instr *instr = &b->b_instr[i];
1030
728k
            if (is_jump(instr) || is_block_push(instr)) {
1031
45.6k
                target = instr->i_target;
1032
45.6k
                if (!target->b_visited) {
1033
31.8k
                    *sp++ = target;
1034
31.8k
                    target->b_visited = 1;
1035
31.8k
                }
1036
45.6k
                target->b_predecessors++;
1037
45.6k
            }
1038
728k
        }
1039
80.7k
    }
1040
13.9k
    PyMem_Free(stack);
1041
1042
    /* Delete unreachable instructions */
1043
109k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1044
95.9k
       if (b->b_predecessors == 0) {
1045
15.1k
            b->b_iused = 0;
1046
15.1k
            b->b_except_handler = 0;
1047
15.1k
       }
1048
95.9k
    }
1049
13.9k
    return SUCCESS;
1050
13.9k
}
1051
1052
static int
1053
266k
basicblock_remove_redundant_nops(basicblock *bb) {
1054
    /* Remove NOPs when legal to do so. */
1055
266k
    int dest = 0;
1056
266k
    int prev_lineno = -1;
1057
2.10M
    for (int src = 0; src < bb->b_iused; src++) {
1058
1.83M
        int lineno = bb->b_instr[src].i_loc.lineno;
1059
1.83M
        if (bb->b_instr[src].i_opcode == NOP) {
1060
            /* Eliminate no-op if it doesn't have a line number */
1061
44.4k
            if (lineno < 0) {
1062
6.10k
                continue;
1063
6.10k
            }
1064
            /* or, if the previous instruction had the same line number. */
1065
38.3k
            if (prev_lineno == lineno) {
1066
30.9k
                continue;
1067
30.9k
            }
1068
            /* or, if the next instruction has same line number or no line number */
1069
7.36k
            if (src < bb->b_iused - 1) {
1070
6.29k
                int next_lineno = bb->b_instr[src+1].i_loc.lineno;
1071
6.29k
                if (next_lineno == lineno) {
1072
4.21k
                    continue;
1073
4.21k
                }
1074
2.08k
                if (next_lineno < 0) {
1075
0
                    bb->b_instr[src+1].i_loc = bb->b_instr[src].i_loc;
1076
0
                    continue;
1077
0
                }
1078
2.08k
            }
1079
1.06k
            else {
1080
1.06k
                basicblock *next = next_nonempty_block(bb->b_next);
1081
                /* or if last instruction in BB and next BB has same line number */
1082
1.06k
                if (next) {
1083
1.06k
                    location next_loc = NO_LOCATION;
1084
1.06k
                    for (int next_i=0; next_i < next->b_iused; next_i++) {
1085
1.06k
                        cfg_instr *instr = &next->b_instr[next_i];
1086
1.06k
                        if (instr->i_opcode == NOP && instr->i_loc.lineno < 0) {
1087
                            /* Skip over NOPs without a location, they will be removed */
1088
0
                            continue;
1089
0
                        }
1090
1.06k
                        next_loc = instr->i_loc;
1091
1.06k
                        break;
1092
1.06k
                    }
1093
1.06k
                    if (lineno == next_loc.lineno) {
1094
7
                        continue;
1095
7
                    }
1096
1.06k
                }
1097
1.06k
            }
1098
1099
7.36k
        }
1100
1.79M
        if (dest != src) {
1101
170k
            bb->b_instr[dest] = bb->b_instr[src];
1102
170k
        }
1103
1.79M
        dest++;
1104
1.79M
        prev_lineno = lineno;
1105
1.79M
    }
1106
266k
    assert(dest <= bb->b_iused);
1107
266k
    int num_removed = bb->b_iused - dest;
1108
266k
    bb->b_iused = dest;
1109
266k
    memset(&bb->b_instr[dest], 0, sizeof(cfg_instr) * num_removed);
1110
266k
    return num_removed;
1111
266k
}
1112
1113
static int
1114
24.2k
remove_redundant_nops(cfg_builder *g) {
1115
24.2k
    int changes = 0;
1116
242k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
1117
218k
        int change = basicblock_remove_redundant_nops(b);
1118
218k
        RETURN_IF_ERROR(change);
1119
218k
        changes += change;
1120
218k
    }
1121
24.2k
    return changes;
1122
24.2k
}
1123
1124
static int
1125
remove_redundant_nops_and_pairs(basicblock *entryblock)
1126
6.99k
{
1127
6.99k
    bool done = false;
1128
1129
13.9k
    while (! done) {
1130
6.99k
        done = true;
1131
6.99k
        cfg_instr *prev_instr = NULL;
1132
6.99k
        cfg_instr *instr = NULL;
1133
55.2k
        for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1134
48.2k
            RETURN_IF_ERROR(basicblock_remove_redundant_nops(b));
1135
48.2k
            if (IS_LABEL(b->b_label)) {
1136
                /* this block is a jump target, forget instr */
1137
20.9k
                instr = NULL;
1138
20.9k
            }
1139
398k
            for (int i = 0; i < b->b_iused; i++) {
1140
349k
                prev_instr = instr;
1141
349k
                instr = &b->b_instr[i];
1142
349k
                int prev_opcode = prev_instr ? prev_instr->i_opcode : 0;
1143
349k
                int prev_oparg = prev_instr ? prev_instr->i_oparg : 0;
1144
349k
                int opcode = instr->i_opcode;
1145
349k
                bool is_redundant_pair = false;
1146
349k
                if (opcode == POP_TOP) {
1147
8.25k
                   if (prev_opcode == LOAD_CONST || prev_opcode == LOAD_SMALL_INT) {
1148
0
                       is_redundant_pair = true;
1149
0
                   }
1150
8.25k
                   else if (prev_opcode == COPY && prev_oparg == 1) {
1151
0
                       is_redundant_pair = true;
1152
0
                   }
1153
8.25k
                }
1154
349k
                if (is_redundant_pair) {
1155
0
                    INSTR_SET_OP0(prev_instr, NOP);
1156
0
                    INSTR_SET_OP0(instr, NOP);
1157
0
                    done = false;
1158
0
                }
1159
349k
            }
1160
48.2k
            if ((instr && is_jump(instr)) || !BB_HAS_FALLTHROUGH(b)) {
1161
34.9k
                instr = NULL;
1162
34.9k
            }
1163
48.2k
        }
1164
6.99k
    }
1165
6.99k
    return SUCCESS;
1166
6.99k
}
1167
1168
static int
1169
17.2k
remove_redundant_jumps(cfg_builder *g) {
1170
    /* If a non-empty block ends with a jump instruction, check if the next
1171
     * non-empty block reached through normal flow control is the target
1172
     * of that jump. If it is, then the jump instruction is redundant and
1173
     * can be deleted.
1174
     *
1175
     * Return the number of changes applied, or -1 on error.
1176
     */
1177
1178
17.2k
    int changes = 0;
1179
187k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
1180
170k
        cfg_instr *last = basicblock_last_instr(b);
1181
170k
        if (last == NULL) {
1182
23.6k
            continue;
1183
23.6k
        }
1184
170k
        assert(!IS_ASSEMBLER_OPCODE(last->i_opcode));
1185
146k
        if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
1186
21.0k
            basicblock* jump_target = next_nonempty_block(last->i_target);
1187
21.0k
            if (jump_target == NULL) {
1188
0
                PyErr_SetString(PyExc_SystemError, "jump with NULL target");
1189
0
                return ERROR;
1190
0
            }
1191
21.0k
            basicblock *next = next_nonempty_block(b->b_next);
1192
21.0k
            if (jump_target == next) {
1193
703
                changes++;
1194
703
                INSTR_SET_OP0(last, NOP);
1195
703
            }
1196
21.0k
        }
1197
146k
    }
1198
1199
17.2k
    return changes;
1200
17.2k
}
1201
1202
static inline bool
1203
58.5k
basicblock_has_no_lineno(basicblock *b) {
1204
69.7k
    for (int i = 0; i < b->b_iused; i++) {
1205
64.1k
        if (b->b_instr[i].i_loc.lineno >= 0) {
1206
52.9k
            return false;
1207
52.9k
        }
1208
64.1k
    }
1209
5.55k
    return true;
1210
58.5k
}
1211
1212
/* Maximum size of basic block that should be copied in optimizer */
1213
2.38k
#define MAX_COPY_SIZE 4
1214
1215
/* If this block ends with an unconditional jump to a small exit block or
1216
 * a block that has no line numbers (and no fallthrough), then
1217
 * remove the jump and extend this block with the target.
1218
 * Returns 1 if extended, 0 if no change, and -1 on error.
1219
 */
1220
static int
1221
74.8k
basicblock_inline_small_or_no_lineno_blocks(basicblock *bb) {
1222
74.8k
    cfg_instr *last = basicblock_last_instr(bb);
1223
74.8k
    if (last == NULL) {
1224
0
        return 0;
1225
0
    }
1226
74.8k
    if (!IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
1227
61.3k
        return 0;
1228
61.3k
    }
1229
13.4k
    basicblock *target = last->i_target;
1230
13.4k
    bool small_exit_block = (basicblock_exits_scope(target) &&
1231
2.38k
                             target->b_iused <= MAX_COPY_SIZE);
1232
13.4k
    bool no_lineno_no_fallthrough = (basicblock_has_no_lineno(target) &&
1233
2.31k
                                     !BB_HAS_FALLTHROUGH(target));
1234
13.4k
    if (small_exit_block || no_lineno_no_fallthrough) {
1235
2.73k
        assert(is_jump(last));
1236
2.73k
        int removed_jump_opcode = last->i_opcode;
1237
2.73k
        INSTR_SET_OP0(last, NOP);
1238
2.73k
        RETURN_IF_ERROR(basicblock_append_instructions(bb, target));
1239
2.73k
        if (no_lineno_no_fallthrough) {
1240
2.31k
            last = basicblock_last_instr(bb);
1241
2.31k
            if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode) &&
1242
1.43k
                removed_jump_opcode == JUMP)
1243
59
            {
1244
                /* Make sure we don't lose eval breaker checks */
1245
59
                last->i_opcode = JUMP;
1246
59
            }
1247
2.31k
        }
1248
2.73k
        target->b_predecessors--;
1249
2.73k
        return 1;
1250
2.73k
    }
1251
10.6k
    return 0;
1252
13.4k
}
1253
1254
static int
1255
6.99k
inline_small_or_no_lineno_blocks(basicblock *entryblock) {
1256
6.99k
    bool changes;
1257
8.14k
    do {
1258
8.14k
        changes = false;
1259
82.9k
        for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
1260
74.8k
            int res = basicblock_inline_small_or_no_lineno_blocks(b);
1261
74.8k
            RETURN_IF_ERROR(res);
1262
74.8k
            if (res) {
1263
2.73k
                changes = true;
1264
2.73k
            }
1265
74.8k
        }
1266
8.14k
    } while(changes); /* every change removes a jump, ensuring convergence */
1267
6.99k
    return changes;
1268
6.99k
}
1269
1270
// Attempt to eliminate jumps to jumps by updating inst to jump to
1271
// target->i_target using the provided opcode. Return whether or not the
1272
// optimization was successful.
1273
static bool
1274
jump_thread(basicblock *bb, cfg_instr *inst, cfg_instr *target, int opcode)
1275
773
{
1276
773
    assert(is_jump(inst));
1277
773
    assert(is_jump(target));
1278
773
    assert(inst == basicblock_last_instr(bb));
1279
    // bpo-45773: If inst->i_target == target->i_target, then nothing actually
1280
    // changes (and we fall into an infinite loop):
1281
773
    if (inst->i_target != target->i_target) {
1282
        /* Change inst to NOP and append a jump to target->i_target. The
1283
         * NOP will be removed later if it's not needed for the lineno.
1284
         */
1285
773
        INSTR_SET_OP0(inst, NOP);
1286
1287
773
        RETURN_IF_ERROR(
1288
773
            basicblock_add_jump(
1289
773
                bb, opcode, target->i_target, target->i_loc));
1290
1291
773
        return true;
1292
773
    }
1293
0
    return false;
1294
773
}
1295
1296
static int
1297
loads_const(int opcode)
1298
19.2k
{
1299
19.2k
    return OPCODE_HAS_CONST(opcode) || opcode == LOAD_SMALL_INT;
1300
19.2k
}
1301
1302
/* Returns new reference */
1303
static PyObject*
1304
get_const_value(int opcode, int oparg, PyObject *co_consts)
1305
74.2k
{
1306
74.2k
    PyObject *constant = NULL;
1307
74.2k
    assert(loads_const(opcode));
1308
74.2k
    if (opcode == LOAD_CONST) {
1309
73.4k
        constant = PyList_GET_ITEM(co_consts, oparg);
1310
73.4k
    }
1311
74.2k
    if (opcode == LOAD_SMALL_INT) {
1312
824
        return PyLong_FromLong(oparg);
1313
824
    }
1314
1315
73.4k
    if (constant == NULL) {
1316
0
        PyErr_SetString(PyExc_SystemError,
1317
0
                        "Internal error: failed to get value of a constant");
1318
0
        return NULL;
1319
0
    }
1320
73.4k
    return Py_NewRef(constant);
1321
73.4k
}
1322
1323
// Steals a reference to newconst.
1324
static int
1325
add_const(PyObject *newconst, PyObject *consts, PyObject *const_cache)
1326
2.40k
{
1327
2.40k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &newconst) < 0) {
1328
0
        Py_DECREF(newconst);
1329
0
        return -1;
1330
0
    }
1331
1332
2.40k
    Py_ssize_t index;
1333
105k
    for (index = 0; index < PyList_GET_SIZE(consts); index++) {
1334
104k
        if (PyList_GET_ITEM(consts, index) == newconst) {
1335
689
            break;
1336
689
        }
1337
104k
    }
1338
2.40k
    if (index == PyList_GET_SIZE(consts)) {
1339
1.71k
        if ((size_t)index >= (size_t)INT_MAX - 1) {
1340
0
            PyErr_SetString(PyExc_OverflowError, "too many constants");
1341
0
            Py_DECREF(newconst);
1342
0
            return -1;
1343
0
        }
1344
1.71k
        if (PyList_Append(consts, newconst)) {
1345
0
            Py_DECREF(newconst);
1346
0
            return -1;
1347
0
        }
1348
1.71k
    }
1349
2.40k
    Py_DECREF(newconst);
1350
2.40k
    return (int)index;
1351
2.40k
}
1352
1353
/*
1354
  Traverse the instructions of the basic block backwards from index "start", skipping over NOPs.
1355
  Try to collect "size" number of consecutive instructions that load constants into the array "instrs".
1356
  Caller must make sure that length of "instrs" is sufficient to fit in at least "size" instructions.
1357
1358
  Return boolean indicating whether "size" such instructions were found.
1359
*/
1360
static bool
1361
get_const_loading_instrs(basicblock *bb, int start, cfg_instr **instrs, int size)
1362
12.7k
{
1363
12.7k
    assert(start < bb->b_iused);
1364
12.7k
    assert(size >= 0);
1365
12.7k
    assert(size <= _PY_STACK_USE_GUIDELINE);
1366
1367
21.4k
    for (; start >= 0 && size > 0; start--) {
1368
19.1k
        cfg_instr *instr = &bb->b_instr[start];
1369
19.1k
        if (instr->i_opcode == NOP) {
1370
274
            continue;
1371
274
        }
1372
18.8k
        if (!loads_const(instr->i_opcode)) {
1373
10.4k
            return false;
1374
10.4k
        }
1375
8.44k
        instrs[--size] = instr;
1376
8.44k
    }
1377
1378
2.32k
    return size == 0;
1379
12.7k
}
1380
1381
/*
1382
  Change every instruction in "instrs" NOP and set its location to NO_LOCATION.
1383
  Caller must make sure "instrs" has at least "size" elements.
1384
*/
1385
static void
1386
nop_out(cfg_instr **instrs, int size)
1387
2.55k
{
1388
7.49k
    for (int i = 0; i < size; i++) {
1389
4.94k
        cfg_instr *instr = instrs[i];
1390
4.94k
        assert(instr->i_opcode != NOP);
1391
4.94k
        INSTR_SET_OP0(instr, NOP);
1392
4.94k
        INSTR_SET_LOC(instr, NO_LOCATION);
1393
4.94k
    }
1394
2.55k
}
1395
1396
/* Does not steal reference to "newconst".
1397
   Return 1 if changed instruction to LOAD_SMALL_INT.
1398
   Return 0 if could not change instruction to LOAD_SMALL_INT.
1399
   Return -1 on error.
1400
*/
1401
static int
1402
maybe_instr_make_load_smallint(cfg_instr *instr, PyObject *newconst,
1403
                               PyObject *consts, PyObject *const_cache)
1404
69.7k
{
1405
69.7k
    if (PyLong_CheckExact(newconst)) {
1406
24.5k
        int overflow;
1407
24.5k
        long val = PyLong_AsLongAndOverflow(newconst, &overflow);
1408
24.5k
        if (val == -1 && PyErr_Occurred()) {
1409
0
            return -1;
1410
0
        }
1411
24.5k
        if (!overflow && _PY_IS_SMALL_INT(val)) {
1412
19.0k
            assert(_Py_IsImmortal(newconst));
1413
19.0k
            INSTR_SET_OP1(instr, LOAD_SMALL_INT, (int)val);
1414
19.0k
            return 1;
1415
19.0k
        }
1416
24.5k
    }
1417
50.7k
    return 0;
1418
69.7k
}
1419
1420
1421
/* Steals reference to "newconst" */
1422
static int
1423
instr_make_load_const(cfg_instr *instr, PyObject *newconst,
1424
                      PyObject *consts, PyObject *const_cache)
1425
2.10k
{
1426
2.10k
    int res = maybe_instr_make_load_smallint(instr, newconst, consts, const_cache);
1427
2.10k
    if (res < 0) {
1428
0
        Py_DECREF(newconst);
1429
0
        return ERROR;
1430
0
    }
1431
2.10k
    if (res > 0) {
1432
9
        return SUCCESS;
1433
9
    }
1434
2.09k
    int oparg = add_const(newconst, consts, const_cache);
1435
2.09k
    RETURN_IF_ERROR(oparg);
1436
2.09k
    INSTR_SET_OP1(instr, LOAD_CONST, oparg);
1437
2.09k
    return SUCCESS;
1438
2.09k
}
1439
1440
/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
1441
   with    LOAD_CONST (c1, c2, ... cn).
1442
   The consts table must still be in list form so that the
1443
   new constant (c1, c2, ... cn) can be appended.
1444
   Called with codestr pointing to the first LOAD_CONST.
1445
*/
1446
static int
1447
fold_tuple_of_constants(basicblock *bb, int i, PyObject *consts, PyObject *const_cache)
1448
4.17k
{
1449
    /* Pre-conditions */
1450
4.17k
    assert(PyDict_CheckExact(const_cache));
1451
4.17k
    assert(PyList_CheckExact(consts));
1452
1453
4.17k
    cfg_instr *instr = &bb->b_instr[i];
1454
4.17k
    assert(instr->i_opcode == BUILD_TUPLE);
1455
1456
4.17k
    int seq_size = instr->i_oparg;
1457
4.17k
    if (seq_size > _PY_STACK_USE_GUIDELINE) {
1458
0
        return SUCCESS;
1459
0
    }
1460
1461
4.17k
    cfg_instr *const_instrs[_PY_STACK_USE_GUIDELINE];
1462
4.17k
    if (!get_const_loading_instrs(bb, i-1, const_instrs, seq_size)) {
1463
        /* not a const sequence */
1464
2.67k
        return SUCCESS;
1465
2.67k
    }
1466
1467
1.50k
    PyObject *const_tuple = PyTuple_New((Py_ssize_t)seq_size);
1468
1.50k
    if (const_tuple == NULL) {
1469
0
        return ERROR;
1470
0
    }
1471
1472
4.06k
    for (int i = 0; i < seq_size; i++) {
1473
2.56k
        cfg_instr *inst = const_instrs[i];
1474
2.56k
        assert(loads_const(inst->i_opcode));
1475
2.56k
        PyObject *element = get_const_value(inst->i_opcode, inst->i_oparg, consts);
1476
2.56k
        if (element == NULL) {
1477
0
            Py_DECREF(const_tuple);
1478
0
            return ERROR;
1479
0
        }
1480
2.56k
        PyTuple_SET_ITEM(const_tuple, i, element);
1481
2.56k
    }
1482
1483
1.50k
    nop_out(const_instrs, seq_size);
1484
1.50k
    return instr_make_load_const(instr, const_tuple, consts, const_cache);
1485
1.50k
}
1486
1487
/* Replace:
1488
    BUILD_LIST 0
1489
    LOAD_CONST c1
1490
    LIST_APPEND 1
1491
    LOAD_CONST c2
1492
    LIST_APPEND 1
1493
    ...
1494
    LOAD_CONST cN
1495
    LIST_APPEND 1
1496
    CALL_INTRINSIC_1 INTRINSIC_LIST_TO_TUPLE
1497
   with:
1498
    LOAD_CONST (c1, c2, ... cN)
1499
*/
1500
static int
1501
fold_constant_intrinsic_list_to_tuple(basicblock *bb, int i,
1502
                                      PyObject *consts, PyObject *const_cache)
1503
118
{
1504
118
    assert(PyDict_CheckExact(const_cache));
1505
118
    assert(PyList_CheckExact(consts));
1506
118
    assert(i >= 0);
1507
118
    assert(i < bb->b_iused);
1508
1509
118
    cfg_instr *intrinsic = &bb->b_instr[i];
1510
118
    assert(intrinsic->i_opcode == CALL_INTRINSIC_1);
1511
118
    assert(intrinsic->i_oparg == INTRINSIC_LIST_TO_TUPLE);
1512
1513
118
    int consts_found = 0;
1514
118
    bool expect_append = true;
1515
1516
391
    for (int pos = i - 1; pos >= 0; pos--) {
1517
391
        cfg_instr *instr = &bb->b_instr[pos];
1518
391
        int opcode = instr->i_opcode;
1519
391
        int oparg = instr->i_oparg;
1520
1521
391
        if (opcode == NOP) {
1522
0
            continue;
1523
0
        }
1524
1525
391
        if (opcode == BUILD_LIST && oparg == 0) {
1526
3
            if (!expect_append) {
1527
                /* Not a sequence start. */
1528
0
                return SUCCESS;
1529
0
            }
1530
1531
            /* Sequence start, we are done. */
1532
3
            PyObject *newconst = PyTuple_New((Py_ssize_t)consts_found);
1533
3
            if (newconst == NULL) {
1534
0
                return ERROR;
1535
0
            }
1536
1537
276
            for (int newpos = i - 1; newpos >= pos; newpos--) {
1538
273
                instr = &bb->b_instr[newpos];
1539
273
                if (instr->i_opcode == NOP) {
1540
0
                    continue;
1541
0
                }
1542
273
                if (loads_const(instr->i_opcode)) {
1543
135
                    PyObject *constant = get_const_value(instr->i_opcode, instr->i_oparg, consts);
1544
135
                    if (constant == NULL) {
1545
0
                        Py_DECREF(newconst);
1546
0
                        return ERROR;
1547
0
                    }
1548
135
                    assert(consts_found > 0);
1549
135
                    PyTuple_SET_ITEM(newconst, --consts_found, constant);
1550
135
                }
1551
273
                nop_out(&instr, 1);
1552
273
            }
1553
3
            assert(consts_found == 0);
1554
3
            return instr_make_load_const(intrinsic, newconst, consts, const_cache);
1555
3
        }
1556
1557
388
        if (expect_append) {
1558
251
            if (opcode != LIST_APPEND || oparg != 1) {
1559
114
                return SUCCESS;
1560
114
            }
1561
251
        }
1562
137
        else {
1563
137
            if (!loads_const(opcode)) {
1564
1
                return SUCCESS;
1565
1
            }
1566
136
            consts_found++;
1567
136
        }
1568
1569
273
        expect_append = !expect_append;
1570
273
    }
1571
1572
    /* Did not find sequence start. */
1573
0
    return SUCCESS;
1574
118
}
1575
1576
2.90k
#define MIN_CONST_SEQUENCE_SIZE 3
1577
/*
1578
Optimize lists and sets for:
1579
    1. "for" loop, comprehension or "in"/"not in" tests:
1580
           Change literal list or set of constants into constant
1581
           tuple or frozenset respectively. Change list of
1582
           non-constants into tuple.
1583
    2. Constant literal lists/set with length >= MIN_CONST_SEQUENCE_SIZE:
1584
           Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cN, BUILD_LIST N
1585
           with BUILD_LIST 0, LOAD_CONST (c1, c2, ... cN), LIST_EXTEND 1,
1586
           or BUILD_SET & SET_UPDATE respectively.
1587
*/
1588
static int
1589
optimize_lists_and_sets(basicblock *bb, int i, int nextop,
1590
                        PyObject *consts, PyObject *const_cache)
1591
1.45k
{
1592
1.45k
    assert(PyDict_CheckExact(const_cache));
1593
1.45k
    assert(PyList_CheckExact(consts));
1594
1595
1.45k
    cfg_instr *instr = &bb->b_instr[i];
1596
1.45k
    assert(instr->i_opcode == BUILD_LIST || instr->i_opcode == BUILD_SET);
1597
1598
1.45k
    bool contains_or_iter = nextop == GET_ITER || nextop == CONTAINS_OP;
1599
1.45k
    int seq_size = instr->i_oparg;
1600
1.45k
    if (seq_size > _PY_STACK_USE_GUIDELINE ||
1601
1.45k
        (seq_size < MIN_CONST_SEQUENCE_SIZE && !contains_or_iter))
1602
1.18k
    {
1603
1.18k
        return SUCCESS;
1604
1.18k
    }
1605
1606
266
    cfg_instr *const_instrs[_PY_STACK_USE_GUIDELINE];
1607
266
    if (!get_const_loading_instrs(bb, i-1, const_instrs, seq_size)) {  /* not a const sequence */
1608
88
        if (contains_or_iter && instr->i_opcode == BUILD_LIST) {
1609
            /* iterate over a tuple instead of list */
1610
0
            INSTR_SET_OP1(instr, BUILD_TUPLE, instr->i_oparg);
1611
0
        }
1612
88
        return SUCCESS;
1613
88
    }
1614
1615
178
    PyObject *const_result = PyTuple_New((Py_ssize_t)seq_size);
1616
178
    if (const_result == NULL) {
1617
0
        return ERROR;
1618
0
    }
1619
1620
1.64k
    for (int i = 0; i < seq_size; i++) {
1621
1.46k
        cfg_instr *inst = const_instrs[i];
1622
1.46k
        assert(loads_const(inst->i_opcode));
1623
1.46k
        PyObject *element = get_const_value(inst->i_opcode, inst->i_oparg, consts);
1624
1.46k
        if (element == NULL) {
1625
0
            Py_DECREF(const_result);
1626
0
            return ERROR;
1627
0
        }
1628
1.46k
        PyTuple_SET_ITEM(const_result, i, element);
1629
1.46k
    }
1630
1631
178
    if (instr->i_opcode == BUILD_SET) {
1632
55
        PyObject *frozenset = PyFrozenSet_New(const_result);
1633
55
        if (frozenset == NULL) {
1634
0
            Py_DECREF(const_result);
1635
0
            return ERROR;
1636
0
        }
1637
55
        Py_SETREF(const_result, frozenset);
1638
55
    }
1639
1640
178
    int index = add_const(const_result, consts, const_cache);
1641
178
    RETURN_IF_ERROR(index);
1642
178
    nop_out(const_instrs, seq_size);
1643
1644
178
    if (contains_or_iter) {
1645
55
        INSTR_SET_OP1(instr, LOAD_CONST, index);
1646
55
    }
1647
123
    else {
1648
123
        assert(i >= 2);
1649
123
        assert(instr->i_opcode == BUILD_LIST || instr->i_opcode == BUILD_SET);
1650
1651
123
        INSTR_SET_LOC(&bb->b_instr[i-2], instr->i_loc);
1652
1653
123
        INSTR_SET_OP1(&bb->b_instr[i-2], instr->i_opcode, 0);
1654
123
        INSTR_SET_OP1(&bb->b_instr[i-1], LOAD_CONST, index);
1655
123
        INSTR_SET_OP1(&bb->b_instr[i], instr->i_opcode == BUILD_LIST ? LIST_EXTEND : SET_UPDATE, 1);
1656
123
    }
1657
178
    return SUCCESS;
1658
178
}
1659
1660
/* Check whether the total number of items in the (possibly nested) collection obj exceeds
1661
 * limit. Return a negative number if it does, and a non-negative number otherwise.
1662
 * Used to avoid creating constants which are slow to hash.
1663
 */
1664
static Py_ssize_t
1665
const_folding_check_complexity(PyObject *obj, Py_ssize_t limit)
1666
0
{
1667
0
    if (PyTuple_Check(obj)) {
1668
0
        Py_ssize_t i;
1669
0
        limit -= PyTuple_GET_SIZE(obj);
1670
0
        for (i = 0; limit >= 0 && i < PyTuple_GET_SIZE(obj); i++) {
1671
0
            limit = const_folding_check_complexity(PyTuple_GET_ITEM(obj, i), limit);
1672
0
            if (limit < 0) {
1673
0
                return limit;
1674
0
            }
1675
0
        }
1676
0
    }
1677
0
    return limit;
1678
0
}
1679
1680
38
#define MAX_INT_SIZE           128  /* bits */
1681
0
#define MAX_COLLECTION_SIZE    256  /* items */
1682
12
#define MAX_STR_SIZE          4096  /* characters */
1683
0
#define MAX_TOTAL_ITEMS       1024  /* including nested collections */
1684
1685
static PyObject *
1686
const_folding_safe_multiply(PyObject *v, PyObject *w)
1687
27
{
1688
27
    if (PyLong_Check(v) && PyLong_Check(w) &&
1689
3
        !_PyLong_IsZero((PyLongObject *)v) && !_PyLong_IsZero((PyLongObject *)w)
1690
27
    ) {
1691
3
        int64_t vbits = _PyLong_NumBits(v);
1692
3
        int64_t wbits = _PyLong_NumBits(w);
1693
3
        assert(vbits >= 0);
1694
3
        assert(wbits >= 0);
1695
3
        if (vbits + wbits > MAX_INT_SIZE) {
1696
0
            return NULL;
1697
0
        }
1698
3
    }
1699
24
    else if (PyLong_Check(v) && PyTuple_Check(w)) {
1700
0
        Py_ssize_t size = PyTuple_GET_SIZE(w);
1701
0
        if (size) {
1702
0
            long n = PyLong_AsLong(v);
1703
0
            if (n < 0 || n > MAX_COLLECTION_SIZE / size) {
1704
0
                return NULL;
1705
0
            }
1706
0
            if (n && const_folding_check_complexity(w, MAX_TOTAL_ITEMS / n) < 0) {
1707
0
                return NULL;
1708
0
            }
1709
0
        }
1710
0
    }
1711
24
    else if (PyLong_Check(v) && (PyUnicode_Check(w) || PyBytes_Check(w))) {
1712
12
        Py_ssize_t size = PyUnicode_Check(w) ? PyUnicode_GET_LENGTH(w) :
1713
12
                                               PyBytes_GET_SIZE(w);
1714
12
        if (size) {
1715
12
            long n = PyLong_AsLong(v);
1716
12
            if (n < 0 || n > MAX_STR_SIZE / size) {
1717
4
                return NULL;
1718
4
            }
1719
12
        }
1720
12
    }
1721
12
    else if (PyLong_Check(w) &&
1722
12
             (PyTuple_Check(v) || PyUnicode_Check(v) || PyBytes_Check(v)))
1723
12
    {
1724
12
        return const_folding_safe_multiply(w, v);
1725
12
    }
1726
1727
11
    return PyNumber_Multiply(v, w);
1728
27
}
1729
1730
static PyObject *
1731
const_folding_safe_power(PyObject *v, PyObject *w)
1732
8
{
1733
8
    if (PyLong_Check(v) && PyLong_Check(w) &&
1734
8
        !_PyLong_IsZero((PyLongObject *)v) && _PyLong_IsPositive((PyLongObject *)w)
1735
8
    ) {
1736
8
        int64_t vbits = _PyLong_NumBits(v);
1737
8
        size_t wbits = PyLong_AsSize_t(w);
1738
8
        assert(vbits >= 0);
1739
8
        if (wbits == (size_t)-1) {
1740
0
            return NULL;
1741
0
        }
1742
8
        if ((uint64_t)vbits > MAX_INT_SIZE / wbits) {
1743
0
            return NULL;
1744
0
        }
1745
8
    }
1746
1747
8
    return PyNumber_Power(v, w, Py_None);
1748
8
}
1749
1750
static PyObject *
1751
const_folding_safe_lshift(PyObject *v, PyObject *w)
1752
9
{
1753
9
    if (PyLong_Check(v) && PyLong_Check(w) &&
1754
9
        !_PyLong_IsZero((PyLongObject *)v) && !_PyLong_IsZero((PyLongObject *)w)
1755
9
    ) {
1756
9
        int64_t vbits = _PyLong_NumBits(v);
1757
9
        size_t wbits = PyLong_AsSize_t(w);
1758
9
        assert(vbits >= 0);
1759
9
        if (wbits == (size_t)-1) {
1760
0
            return NULL;
1761
0
        }
1762
9
        if (wbits > MAX_INT_SIZE || (uint64_t)vbits > MAX_INT_SIZE - wbits) {
1763
0
            return NULL;
1764
0
        }
1765
9
    }
1766
1767
9
    return PyNumber_Lshift(v, w);
1768
9
}
1769
1770
static PyObject *
1771
const_folding_safe_mod(PyObject *v, PyObject *w)
1772
0
{
1773
0
    if (PyUnicode_Check(v) || PyBytes_Check(v)) {
1774
0
        return NULL;
1775
0
    }
1776
1777
0
    return PyNumber_Remainder(v, w);
1778
0
}
1779
1780
static PyObject *
1781
eval_const_binop(PyObject *left, int op, PyObject *right)
1782
47
{
1783
47
    assert(left != NULL && right != NULL);
1784
47
    assert(op >= 0 && op <= NB_OPARG_LAST);
1785
1786
47
    PyObject *result = NULL;
1787
47
    switch (op) {
1788
5
        case NB_ADD:
1789
5
            result = PyNumber_Add(left, right);
1790
5
            break;
1791
0
        case NB_SUBTRACT:
1792
0
            result = PyNumber_Subtract(left, right);
1793
0
            break;
1794
15
        case NB_MULTIPLY:
1795
15
            result = const_folding_safe_multiply(left, right);
1796
15
            break;
1797
1
        case NB_TRUE_DIVIDE:
1798
1
            result = PyNumber_TrueDivide(left, right);
1799
1
            break;
1800
0
        case NB_FLOOR_DIVIDE:
1801
0
            result = PyNumber_FloorDivide(left, right);
1802
0
            break;
1803
0
        case NB_REMAINDER:
1804
0
            result = const_folding_safe_mod(left, right);
1805
0
            break;
1806
8
        case NB_POWER:
1807
8
            result = const_folding_safe_power(left, right);
1808
8
            break;
1809
9
        case NB_LSHIFT:
1810
9
            result = const_folding_safe_lshift(left, right);
1811
9
            break;
1812
0
        case NB_RSHIFT:
1813
0
            result = PyNumber_Rshift(left, right);
1814
0
            break;
1815
0
        case NB_OR:
1816
0
            result = PyNumber_Or(left, right);
1817
0
            break;
1818
0
        case NB_XOR:
1819
0
            result = PyNumber_Xor(left, right);
1820
0
            break;
1821
0
        case NB_AND:
1822
0
            result = PyNumber_And(left, right);
1823
0
            break;
1824
9
        case NB_SUBSCR:
1825
9
            result = PyObject_GetItem(left, right);
1826
9
            break;
1827
0
        case NB_MATRIX_MULTIPLY:
1828
            // No builtin constants implement matrix multiplication
1829
0
            break;
1830
0
        default:
1831
0
            Py_UNREACHABLE();
1832
47
    }
1833
47
    return result;
1834
47
}
1835
1836
static int
1837
fold_const_binop(basicblock *bb, int i, PyObject *consts, PyObject *const_cache)
1838
7.58k
{
1839
7.62k
    #define BINOP_OPERAND_COUNT 2
1840
7.58k
    assert(PyDict_CheckExact(const_cache));
1841
7.58k
    assert(PyList_CheckExact(consts));
1842
1843
7.58k
    cfg_instr *binop = &bb->b_instr[i];
1844
7.58k
    assert(binop->i_opcode == BINARY_OP);
1845
1846
7.58k
    cfg_instr *operands_instrs[BINOP_OPERAND_COUNT];
1847
7.58k
    if (!get_const_loading_instrs(bb, i-1, operands_instrs, BINOP_OPERAND_COUNT)) {
1848
        /* not a const sequence */
1849
7.53k
        return SUCCESS;
1850
7.53k
    }
1851
1852
47
    cfg_instr *lhs_instr = operands_instrs[0];
1853
47
    assert(loads_const(lhs_instr->i_opcode));
1854
47
    PyObject *lhs = get_const_value(lhs_instr->i_opcode, lhs_instr->i_oparg, consts);
1855
47
    if (lhs == NULL) {
1856
0
        return ERROR;
1857
0
    }
1858
1859
47
    cfg_instr *rhs_instr = operands_instrs[1];
1860
47
    assert(loads_const(rhs_instr->i_opcode));
1861
47
    PyObject *rhs = get_const_value(rhs_instr->i_opcode, rhs_instr->i_oparg, consts);
1862
47
    if (rhs == NULL) {
1863
0
        Py_DECREF(lhs);
1864
0
        return ERROR;
1865
0
    }
1866
1867
47
    PyObject *newconst = eval_const_binop(lhs, binop->i_oparg, rhs);
1868
47
    Py_DECREF(lhs);
1869
47
    Py_DECREF(rhs);
1870
47
    if (newconst == NULL) {
1871
4
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
1872
0
            return ERROR;
1873
0
        }
1874
4
        PyErr_Clear();
1875
4
        return SUCCESS;
1876
4
    }
1877
1878
43
    nop_out(operands_instrs, BINOP_OPERAND_COUNT);
1879
43
    return instr_make_load_const(binop, newconst, consts, const_cache);
1880
47
}
1881
1882
static PyObject *
1883
eval_const_unaryop(PyObject *operand, int opcode, int oparg)
1884
560
{
1885
560
    assert(operand != NULL);
1886
560
    assert(
1887
560
        opcode == UNARY_NEGATIVE ||
1888
560
        opcode == UNARY_INVERT ||
1889
560
        opcode == UNARY_NOT ||
1890
560
        (opcode == CALL_INTRINSIC_1 && oparg == INTRINSIC_UNARY_POSITIVE)
1891
560
    );
1892
560
    PyObject *result;
1893
560
    switch (opcode) {
1894
560
        case UNARY_NEGATIVE:
1895
560
            result = PyNumber_Negative(operand);
1896
560
            break;
1897
0
        case UNARY_INVERT:
1898
            // XXX: This should be removed once the ~bool depreciation expires.
1899
0
            if (PyBool_Check(operand)) {
1900
0
                return NULL;
1901
0
            }
1902
0
            result = PyNumber_Invert(operand);
1903
0
            break;
1904
0
        case UNARY_NOT: {
1905
0
            int r = PyObject_IsTrue(operand);
1906
0
            if (r < 0) {
1907
0
                return NULL;
1908
0
            }
1909
0
            result = PyBool_FromLong(!r);
1910
0
            break;
1911
0
        }
1912
0
        case CALL_INTRINSIC_1:
1913
0
            if (oparg != INTRINSIC_UNARY_POSITIVE) {
1914
0
                Py_UNREACHABLE();
1915
0
            }
1916
0
            result = PyNumber_Positive(operand);
1917
0
            break;
1918
0
        default:
1919
0
            Py_UNREACHABLE();
1920
560
    }
1921
560
    return result;
1922
560
}
1923
1924
static int
1925
fold_const_unaryop(basicblock *bb, int i, PyObject *consts, PyObject *const_cache)
1926
752
{
1927
1.31k
    #define UNARYOP_OPERAND_COUNT 1
1928
752
    assert(PyDict_CheckExact(const_cache));
1929
752
    assert(PyList_CheckExact(consts));
1930
752
    cfg_instr *unaryop = &bb->b_instr[i];
1931
1932
752
    cfg_instr *operand_instr;
1933
752
    if (!get_const_loading_instrs(bb, i-1, &operand_instr, UNARYOP_OPERAND_COUNT)) {
1934
        /* not a const */
1935
192
        return SUCCESS;
1936
192
    }
1937
1938
752
    assert(loads_const(operand_instr->i_opcode));
1939
560
    PyObject *operand = get_const_value(
1940
560
        operand_instr->i_opcode,
1941
560
        operand_instr->i_oparg,
1942
560
        consts
1943
560
    );
1944
560
    if (operand == NULL) {
1945
0
        return ERROR;
1946
0
    }
1947
1948
560
    PyObject *newconst = eval_const_unaryop(operand, unaryop->i_opcode, unaryop->i_oparg);
1949
560
    Py_DECREF(operand);
1950
560
    if (newconst == NULL) {
1951
0
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
1952
0
            return ERROR;
1953
0
        }
1954
0
        PyErr_Clear();
1955
0
        return SUCCESS;
1956
0
    }
1957
1958
560
    if (unaryop->i_opcode == UNARY_NOT) {
1959
0
        assert(PyBool_Check(newconst));
1960
0
    }
1961
560
    nop_out(&operand_instr, UNARYOP_OPERAND_COUNT);
1962
560
    return instr_make_load_const(unaryop, newconst, consts, const_cache);
1963
560
}
1964
1965
1.98k
#define VISITED (-1)
1966
1967
// Replace an arbitrary run of SWAPs and NOPs with an optimal one that has the
1968
// same effect.
1969
static int
1970
swaptimize(basicblock *block, int *ix)
1971
1.87k
{
1972
    // NOTE: "./python -m test test_patma" serves as a good, quick stress test
1973
    // for this function. Make sure to blow away cached *.pyc files first!
1974
1.87k
    assert(*ix < block->b_iused);
1975
1.87k
    cfg_instr *instructions = &block->b_instr[*ix];
1976
    // Find the length of the current sequence of SWAPs and NOPs, and record the
1977
    // maximum depth of the stack manipulations:
1978
1.87k
    assert(instructions[0].i_opcode == SWAP);
1979
1.87k
    int depth = instructions[0].i_oparg;
1980
1.87k
    int len = 0;
1981
1.87k
    int more = false;
1982
1.87k
    int limit = block->b_iused - *ix;
1983
2.10k
    while (++len < limit) {
1984
2.10k
        int opcode = instructions[len].i_opcode;
1985
2.10k
        if (opcode == SWAP) {
1986
153
            depth = Py_MAX(depth, instructions[len].i_oparg);
1987
153
            more = true;
1988
153
        }
1989
1.94k
        else if (opcode != NOP) {
1990
1.87k
            break;
1991
1.87k
        }
1992
2.10k
    }
1993
    // It's already optimal if there's only one SWAP:
1994
1.87k
    if (!more) {
1995
1.71k
        return SUCCESS;
1996
1.71k
    }
1997
    // Create an array with elements {0, 1, 2, ..., depth - 1}:
1998
153
    int *stack = PyMem_Malloc(depth * sizeof(int));
1999
153
    if (stack == NULL) {
2000
0
        PyErr_NoMemory();
2001
0
        return ERROR;
2002
0
    }
2003
612
    for (int i = 0; i < depth; i++) {
2004
459
        stack[i] = i;
2005
459
    }
2006
    // Simulate the combined effect of these instructions by "running" them on
2007
    // our "stack":
2008
459
    for (int i = 0; i < len; i++) {
2009
306
        if (instructions[i].i_opcode == SWAP) {
2010
306
            int oparg = instructions[i].i_oparg;
2011
306
            int top = stack[0];
2012
            // SWAPs are 1-indexed:
2013
306
            stack[0] = stack[oparg - 1];
2014
306
            stack[oparg - 1] = top;
2015
306
        }
2016
306
    }
2017
    // Now we can begin! Our approach here is based on a solution to a closely
2018
    // related problem (https://cs.stackexchange.com/a/13938). It's easiest to
2019
    // think of this algorithm as determining the steps needed to efficiently
2020
    // "un-shuffle" our stack. By performing the moves in *reverse* order,
2021
    // though, we can efficiently *shuffle* it! For this reason, we will be
2022
    // replacing instructions starting from the *end* of the run. Since the
2023
    // solution is optimal, we don't need to worry about running out of space:
2024
153
    int current = len - 1;
2025
612
    for (int i = 0; i < depth; i++) {
2026
        // Skip items that have already been visited, or just happen to be in
2027
        // the correct location:
2028
459
        if (stack[i] == VISITED || stack[i] == i) {
2029
306
            continue;
2030
306
        }
2031
        // Okay, we've found an item that hasn't been visited. It forms a cycle
2032
        // with other items; traversing the cycle and swapping each item with
2033
        // the next will put them all in the correct place. The weird
2034
        // loop-and-a-half is necessary to insert 0 into every cycle, since we
2035
        // can only swap from that position:
2036
153
        int j = i;
2037
612
        while (true) {
2038
            // Skip the actual swap if our item is zero, since swapping the top
2039
            // item with itself is pointless:
2040
612
            if (j) {
2041
306
                assert(0 <= current);
2042
                // SWAPs are 1-indexed:
2043
306
                instructions[current].i_opcode = SWAP;
2044
306
                instructions[current--].i_oparg = j + 1;
2045
306
            }
2046
612
            if (stack[j] == VISITED) {
2047
                // Completed the cycle:
2048
153
                assert(j == i);
2049
153
                break;
2050
153
            }
2051
459
            int next_j = stack[j];
2052
459
            stack[j] = VISITED;
2053
459
            j = next_j;
2054
459
        }
2055
153
    }
2056
    // NOP out any unused instructions:
2057
153
    while (0 <= current) {
2058
0
        INSTR_SET_OP0(&instructions[current--], NOP);
2059
0
    }
2060
153
    PyMem_Free(stack);
2061
153
    *ix += len - 1;
2062
153
    return SUCCESS;
2063
153
}
2064
2065
2066
// This list is pretty small, since it's only okay to reorder opcodes that:
2067
// - can't affect control flow (like jumping or raising exceptions)
2068
// - can't invoke arbitrary code (besides finalizers)
2069
// - only touch the TOS (and pop it when finished)
2070
#define SWAPPABLE(opcode) \
2071
3.13k
    ((opcode) == STORE_FAST || \
2072
3.13k
     (opcode) == STORE_FAST_MAYBE_NULL || \
2073
3.13k
     (opcode) == POP_TOP)
2074
2075
#define STORES_TO(instr) \
2076
450
    (((instr).i_opcode == STORE_FAST || \
2077
450
      (instr).i_opcode == STORE_FAST_MAYBE_NULL) \
2078
450
     ? (instr).i_oparg : -1)
2079
2080
static int
2081
next_swappable_instruction(basicblock *block, int i, int lineno)
2082
3.07k
{
2083
3.15k
    while (++i < block->b_iused) {
2084
3.13k
        cfg_instr *instruction = &block->b_instr[i];
2085
3.13k
        if (0 <= lineno && instruction->i_loc.lineno != lineno) {
2086
            // Optimizing across this instruction could cause user-visible
2087
            // changes in the names bound between line tracing events!
2088
12
            return -1;
2089
12
        }
2090
3.12k
        if (instruction->i_opcode == NOP) {
2091
79
            continue;
2092
79
        }
2093
3.04k
        if (SWAPPABLE(instruction->i_opcode)) {
2094
1.41k
            return i;
2095
1.41k
        }
2096
1.63k
        return -1;
2097
3.04k
    }
2098
20
    return -1;
2099
3.07k
}
2100
2101
// Attempt to apply SWAPs statically by swapping *instructions* rather than
2102
// stack items. For example, we can replace SWAP(2), POP_TOP, STORE_FAST(42)
2103
// with the more efficient NOP, STORE_FAST(42), POP_TOP.
2104
static void
2105
apply_static_swaps(basicblock *block, int i)
2106
1.87k
{
2107
    // SWAPs are to our left, and potential swaperands are to our right:
2108
2.16k
    for (; 0 <= i; i--) {
2109
2.04k
        assert(i < block->b_iused);
2110
2.04k
        cfg_instr *swap = &block->b_instr[i];
2111
2.04k
        if (swap->i_opcode != SWAP) {
2112
176
            if (swap->i_opcode == NOP || SWAPPABLE(swap->i_opcode)) {
2113
                // Nope, but we know how to handle these. Keep looking:
2114
88
                continue;
2115
88
            }
2116
            // We can't reason about what this instruction does. Bail:
2117
88
            return;
2118
176
        }
2119
1.87k
        int j = next_swappable_instruction(block, i, -1);
2120
1.87k
        if (j < 0) {
2121
903
            return;
2122
903
        }
2123
967
        int k = j;
2124
967
        int lineno = block->b_instr[j].i_loc.lineno;
2125
1.41k
        for (int count = swap->i_oparg - 1; 0 < count; count--) {
2126
1.20k
            k = next_swappable_instruction(block, k, lineno);
2127
1.20k
            if (k < 0) {
2128
760
                return;
2129
760
            }
2130
1.20k
        }
2131
        // The reordering is not safe if the two instructions to be swapped
2132
        // store to the same location, or if any intervening instruction stores
2133
        // to the same location as either of them.
2134
207
        int store_j = STORES_TO(block->b_instr[j]);
2135
207
        int store_k = STORES_TO(block->b_instr[k]);
2136
207
        if (store_j >= 0 || store_k >= 0) {
2137
207
            if (store_j == store_k) {
2138
0
                return;
2139
0
            }
2140
243
            for (int idx = j + 1; idx < k; idx++) {
2141
36
                int store_idx = STORES_TO(block->b_instr[idx]);
2142
36
                if (store_idx >= 0 && (store_idx == store_j || store_idx == store_k)) {
2143
0
                    return;
2144
0
                }
2145
36
            }
2146
207
        }
2147
2148
        // Success!
2149
207
        INSTR_SET_OP0(swap, NOP);
2150
207
        cfg_instr temp = block->b_instr[j];
2151
207
        block->b_instr[j] = block->b_instr[k];
2152
207
        block->b_instr[k] = temp;
2153
207
    }
2154
1.87k
}
2155
2156
static int
2157
basicblock_optimize_load_const(PyObject *const_cache, basicblock *bb, PyObject *consts)
2158
48.2k
{
2159
48.2k
    assert(PyDict_CheckExact(const_cache));
2160
48.2k
    assert(PyList_CheckExact(consts));
2161
48.2k
    int opcode = 0;
2162
48.2k
    int oparg = 0;
2163
428k
    for (int i = 0; i < bb->b_iused; i++) {
2164
380k
        cfg_instr *inst = &bb->b_instr[i];
2165
380k
        if (inst->i_opcode == LOAD_CONST) {
2166
67.6k
            PyObject *constant = get_const_value(inst->i_opcode, inst->i_oparg, consts);
2167
67.6k
            int res = maybe_instr_make_load_smallint(inst, constant, consts, const_cache);
2168
67.6k
            Py_DECREF(constant);
2169
67.6k
            if (res < 0) {
2170
0
                return ERROR;
2171
0
            }
2172
67.6k
        }
2173
380k
        bool is_copy_of_load_const = (opcode == LOAD_CONST &&
2174
48.4k
                                      inst->i_opcode == COPY &&
2175
41
                                      inst->i_oparg == 1);
2176
380k
        if (! is_copy_of_load_const) {
2177
380k
            opcode = inst->i_opcode;
2178
380k
            oparg = inst->i_oparg;
2179
380k
        }
2180
380k
        assert(!IS_ASSEMBLER_OPCODE(opcode));
2181
380k
        if (opcode != LOAD_CONST && opcode != LOAD_SMALL_INT) {
2182
312k
            continue;
2183
312k
        }
2184
67.7k
        int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
2185
67.7k
        switch(nextop) {
2186
129
            case POP_JUMP_IF_FALSE:
2187
132
            case POP_JUMP_IF_TRUE:
2188
132
            case JUMP_IF_FALSE:
2189
132
            case JUMP_IF_TRUE:
2190
132
            {
2191
                /* Remove LOAD_CONST const; conditional jump */
2192
132
                PyObject* cnt = get_const_value(opcode, oparg, consts);
2193
132
                if (cnt == NULL) {
2194
0
                    return ERROR;
2195
0
                }
2196
132
                int is_true = PyObject_IsTrue(cnt);
2197
132
                Py_DECREF(cnt);
2198
132
                if (is_true == -1) {
2199
0
                    return ERROR;
2200
0
                }
2201
132
                if (PyCompile_OpcodeStackEffect(nextop, 0) == -1) {
2202
                    /* POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE */
2203
132
                    INSTR_SET_OP0(inst, NOP);
2204
132
                }
2205
132
                int jump_if_true = (nextop == POP_JUMP_IF_TRUE || nextop == JUMP_IF_TRUE);
2206
132
                if (is_true == jump_if_true) {
2207
1
                    bb->b_instr[i+1].i_opcode = JUMP;
2208
1
                }
2209
131
                else {
2210
131
                    INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2211
131
                }
2212
132
                break;
2213
132
            }
2214
1.49k
            case IS_OP:
2215
1.49k
            {
2216
                // Fold to POP_JUMP_IF_NONE:
2217
                // - LOAD_CONST(None) IS_OP(0) POP_JUMP_IF_TRUE
2218
                // - LOAD_CONST(None) IS_OP(1) POP_JUMP_IF_FALSE
2219
                // - LOAD_CONST(None) IS_OP(0) TO_BOOL POP_JUMP_IF_TRUE
2220
                // - LOAD_CONST(None) IS_OP(1) TO_BOOL POP_JUMP_IF_FALSE
2221
                // Fold to POP_JUMP_IF_NOT_NONE:
2222
                // - LOAD_CONST(None) IS_OP(0) POP_JUMP_IF_FALSE
2223
                // - LOAD_CONST(None) IS_OP(1) POP_JUMP_IF_TRUE
2224
                // - LOAD_CONST(None) IS_OP(0) TO_BOOL POP_JUMP_IF_FALSE
2225
                // - LOAD_CONST(None) IS_OP(1) TO_BOOL POP_JUMP_IF_TRUE
2226
1.49k
                PyObject *cnt = get_const_value(opcode, oparg, consts);
2227
1.49k
                if (cnt == NULL) {
2228
0
                    return ERROR;
2229
0
                }
2230
1.49k
                if (!Py_IsNone(cnt)) {
2231
18
                    Py_DECREF(cnt);
2232
18
                    break;
2233
18
                }
2234
1.47k
                if (bb->b_iused <= i + 2) {
2235
8
                    break;
2236
8
                }
2237
1.47k
                cfg_instr *is_instr = &bb->b_instr[i + 1];
2238
1.47k
                cfg_instr *jump_instr = &bb->b_instr[i + 2];
2239
                // Get rid of TO_BOOL regardless:
2240
1.47k
                if (jump_instr->i_opcode == TO_BOOL) {
2241
1.43k
                    INSTR_SET_OP0(jump_instr, NOP);
2242
1.43k
                    if (bb->b_iused <= i + 3) {
2243
0
                        break;
2244
0
                    }
2245
1.43k
                    jump_instr = &bb->b_instr[i + 3];
2246
1.43k
                }
2247
1.47k
                bool invert = is_instr->i_oparg;
2248
1.47k
                if (jump_instr->i_opcode == POP_JUMP_IF_FALSE) {
2249
1.38k
                    invert = !invert;
2250
1.38k
                }
2251
82
                else if (jump_instr->i_opcode != POP_JUMP_IF_TRUE) {
2252
31
                    break;
2253
31
                }
2254
1.44k
                INSTR_SET_OP0(inst, NOP);
2255
1.44k
                INSTR_SET_OP0(is_instr, NOP);
2256
1.44k
                jump_instr->i_opcode = invert ? POP_JUMP_IF_NOT_NONE
2257
1.44k
                                              : POP_JUMP_IF_NONE;
2258
1.44k
                break;
2259
1.47k
            }
2260
132
            case TO_BOOL:
2261
132
            {
2262
132
                PyObject *cnt = get_const_value(opcode, oparg, consts);
2263
132
                if (cnt == NULL) {
2264
0
                    return ERROR;
2265
0
                }
2266
132
                int is_true = PyObject_IsTrue(cnt);
2267
132
                Py_DECREF(cnt);
2268
132
                if (is_true == -1) {
2269
0
                    return ERROR;
2270
0
                }
2271
132
                cnt = PyBool_FromLong(is_true);
2272
132
                int index = add_const(cnt, consts, const_cache);
2273
132
                if (index < 0) {
2274
0
                    return ERROR;
2275
0
                }
2276
132
                INSTR_SET_OP0(inst, NOP);
2277
132
                INSTR_SET_OP1(&bb->b_instr[i + 1], LOAD_CONST, index);
2278
132
                break;
2279
132
            }
2280
67.7k
        }
2281
67.7k
    }
2282
48.2k
    return SUCCESS;
2283
48.2k
}
2284
2285
static int
2286
6.99k
optimize_load_const(PyObject *const_cache, cfg_builder *g, PyObject *consts) {
2287
55.2k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
2288
48.2k
        RETURN_IF_ERROR(basicblock_optimize_load_const(const_cache, b, consts));
2289
48.2k
    }
2290
6.99k
    return SUCCESS;
2291
6.99k
}
2292
2293
static int
2294
optimize_basic_block(PyObject *const_cache, basicblock *bb, PyObject *consts)
2295
48.2k
{
2296
48.2k
    assert(PyDict_CheckExact(const_cache));
2297
48.2k
    assert(PyList_CheckExact(consts));
2298
48.2k
    cfg_instr nop;
2299
48.2k
    INSTR_SET_OP0(&nop, NOP);
2300
430k
    for (int i = 0; i < bb->b_iused; i++) {
2301
381k
        cfg_instr *inst = &bb->b_instr[i];
2302
381k
        cfg_instr *target;
2303
381k
        int opcode = inst->i_opcode;
2304
381k
        int oparg = inst->i_oparg;
2305
381k
        if (HAS_TARGET(opcode)) {
2306
24.0k
            assert(inst->i_target->b_iused > 0);
2307
24.0k
            target = &inst->i_target->b_instr[0];
2308
24.0k
            assert(!IS_ASSEMBLER_OPCODE(target->i_opcode));
2309
24.0k
        }
2310
357k
        else {
2311
357k
            target = &nop;
2312
357k
        }
2313
381k
        int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
2314
381k
        assert(!IS_ASSEMBLER_OPCODE(opcode));
2315
381k
        switch (opcode) {
2316
            /* Try to fold tuples of constants.
2317
               Skip over BUILD_TUPLE(1) UNPACK_SEQUENCE(1).
2318
               Replace BUILD_TUPLE(2) UNPACK_SEQUENCE(2) with SWAP(2).
2319
               Replace BUILD_TUPLE(3) UNPACK_SEQUENCE(3) with SWAP(3). */
2320
4.26k
            case BUILD_TUPLE:
2321
4.26k
                if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
2322
106
                    switch(oparg) {
2323
0
                        case 1:
2324
0
                            INSTR_SET_OP0(inst, NOP);
2325
0
                            INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2326
0
                            continue;
2327
89
                        case 2:
2328
99
                        case 3:
2329
99
                            INSTR_SET_OP0(inst, NOP);
2330
99
                            bb->b_instr[i+1].i_opcode = SWAP;
2331
99
                            continue;
2332
106
                    }
2333
106
                }
2334
4.17k
                RETURN_IF_ERROR(fold_tuple_of_constants(bb, i, consts, const_cache));
2335
4.17k
                break;
2336
1.33k
            case BUILD_LIST:
2337
1.45k
            case BUILD_SET:
2338
1.45k
                RETURN_IF_ERROR(optimize_lists_and_sets(bb, i, nextop, consts, const_cache));
2339
1.45k
                break;
2340
771
            case POP_JUMP_IF_NOT_NONE:
2341
1.50k
            case POP_JUMP_IF_NONE:
2342
1.50k
                switch (target->i_opcode) {
2343
69
                    case JUMP:
2344
69
                        i -= jump_thread(bb, inst, target, inst->i_opcode);
2345
1.50k
                }
2346
1.50k
                break;
2347
9.27k
            case POP_JUMP_IF_FALSE:
2348
9.27k
                switch (target->i_opcode) {
2349
646
                    case JUMP:
2350
646
                        i -= jump_thread(bb, inst, target, POP_JUMP_IF_FALSE);
2351
9.27k
                }
2352
9.27k
                break;
2353
9.27k
            case POP_JUMP_IF_TRUE:
2354
1.79k
                switch (target->i_opcode) {
2355
58
                    case JUMP:
2356
58
                        i -= jump_thread(bb, inst, target, POP_JUMP_IF_TRUE);
2357
1.79k
                }
2358
1.79k
                break;
2359
1.79k
            case JUMP_IF_FALSE:
2360
318
                switch (target->i_opcode) {
2361
0
                    case JUMP:
2362
0
                    case JUMP_IF_FALSE:
2363
0
                        i -= jump_thread(bb, inst, target, JUMP_IF_FALSE);
2364
0
                        continue;
2365
3
                    case JUMP_IF_TRUE:
2366
                        // No need to check for loops here, a block's b_next
2367
                        // cannot point to itself.
2368
3
                        assert(inst->i_target != inst->i_target->b_next);
2369
3
                        inst->i_target = inst->i_target->b_next;
2370
3
                        i--;
2371
3
                        continue;
2372
318
                }
2373
315
                break;
2374
315
            case JUMP_IF_TRUE:
2375
280
                switch (target->i_opcode) {
2376
0
                    case JUMP:
2377
0
                    case JUMP_IF_TRUE:
2378
0
                        i -= jump_thread(bb, inst, target, JUMP_IF_TRUE);
2379
0
                        continue;
2380
6
                    case JUMP_IF_FALSE:
2381
                        // No need to check for loops here, a block's b_next
2382
                        // cannot point to itself.
2383
6
                        assert(inst->i_target != inst->i_target->b_next);
2384
6
                        inst->i_target = inst->i_target->b_next;
2385
6
                        i--;
2386
6
                        continue;
2387
280
                }
2388
274
                break;
2389
3.80k
            case JUMP:
2390
6.29k
            case JUMP_NO_INTERRUPT:
2391
6.29k
                switch (target->i_opcode) {
2392
0
                    case JUMP:
2393
0
                        i -= jump_thread(bb, inst, target, JUMP);
2394
0
                        continue;
2395
0
                    case JUMP_NO_INTERRUPT:
2396
0
                        i -= jump_thread(bb, inst, target, opcode);
2397
0
                        continue;
2398
6.29k
                }
2399
6.29k
                break;
2400
6.29k
            case FOR_ITER:
2401
1.71k
                if (target->i_opcode == JUMP) {
2402
                    /* This will not work now because the jump (at target) could
2403
                     * be forward or backward and FOR_ITER only jumps forward. We
2404
                     * can re-enable this if ever we implement a backward version
2405
                     * of FOR_ITER.
2406
                     */
2407
                    /*
2408
                    i -= jump_thread(bb, inst, target, FOR_ITER);
2409
                    */
2410
0
                }
2411
1.71k
                break;
2412
13.8k
            case STORE_FAST:
2413
13.8k
                if (opcode == nextop &&
2414
1.62k
                    oparg == bb->b_instr[i+1].i_oparg &&
2415
27
                    bb->b_instr[i].i_loc.lineno == bb->b_instr[i+1].i_loc.lineno) {
2416
27
                    bb->b_instr[i].i_opcode = POP_TOP;
2417
27
                    bb->b_instr[i].i_oparg = 0;
2418
27
                }
2419
13.8k
                break;
2420
2.02k
            case SWAP:
2421
2.02k
                if (oparg == 1) {
2422
0
                    INSTR_SET_OP0(inst, NOP);
2423
0
                }
2424
2.02k
                break;
2425
17.2k
            case LOAD_GLOBAL:
2426
17.2k
                if (nextop == PUSH_NULL && (oparg & 1) == 0) {
2427
8.65k
                    INSTR_SET_OP1(inst, LOAD_GLOBAL, oparg | 1);
2428
8.65k
                    INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2429
8.65k
                }
2430
17.2k
                break;
2431
5.99k
            case COMPARE_OP:
2432
5.99k
                if (nextop == TO_BOOL) {
2433
2.74k
                    INSTR_SET_OP0(inst, NOP);
2434
2.74k
                    INSTR_SET_OP1(&bb->b_instr[i + 1], COMPARE_OP, oparg | 16);
2435
2.74k
                    continue;
2436
2.74k
                }
2437
3.25k
                break;
2438
3.25k
            case CONTAINS_OP:
2439
4.22k
            case IS_OP:
2440
4.22k
                if (nextop == TO_BOOL) {
2441
1.96k
                    INSTR_SET_OP0(inst, NOP);
2442
1.96k
                    INSTR_SET_OP1(&bb->b_instr[i + 1], opcode, oparg);
2443
1.96k
                    continue;
2444
1.96k
                }
2445
2.26k
                if (nextop == UNARY_NOT) {
2446
0
                    INSTR_SET_OP0(inst, NOP);
2447
0
                    int inverted = oparg ^ 1;
2448
0
                    assert(inverted == 0 || inverted == 1);
2449
0
                    INSTR_SET_OP1(&bb->b_instr[i + 1], opcode, inverted);
2450
0
                    continue;
2451
0
                }
2452
2.26k
                break;
2453
4.75k
            case TO_BOOL:
2454
4.75k
                if (nextop == TO_BOOL) {
2455
0
                    INSTR_SET_OP0(inst, NOP);
2456
0
                    continue;
2457
0
                }
2458
4.75k
                break;
2459
4.75k
            case UNARY_NOT:
2460
98
                if (nextop == TO_BOOL) {
2461
0
                    INSTR_SET_OP0(inst, NOP);
2462
0
                    INSTR_SET_OP0(&bb->b_instr[i + 1], UNARY_NOT);
2463
0
                    continue;
2464
0
                }
2465
98
                if (nextop == UNARY_NOT) {
2466
0
                    INSTR_SET_OP0(inst, NOP);
2467
0
                    INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
2468
0
                    continue;
2469
0
                }
2470
98
                _Py_FALLTHROUGH;
2471
141
            case UNARY_INVERT:
2472
749
            case UNARY_NEGATIVE:
2473
749
                RETURN_IF_ERROR(fold_const_unaryop(bb, i, consts, const_cache));
2474
749
                break;
2475
530
            case CALL_INTRINSIC_1:
2476
530
                if (oparg == INTRINSIC_LIST_TO_TUPLE) {
2477
118
                    if (nextop == GET_ITER) {
2478
0
                        INSTR_SET_OP0(inst, NOP);
2479
0
                    }
2480
118
                    else {
2481
118
                        RETURN_IF_ERROR(fold_constant_intrinsic_list_to_tuple(bb, i, consts, const_cache));
2482
118
                    }
2483
118
                }
2484
412
                else if (oparg == INTRINSIC_UNARY_POSITIVE) {
2485
3
                    RETURN_IF_ERROR(fold_const_unaryop(bb, i, consts, const_cache));
2486
3
                }
2487
530
                break;
2488
7.58k
            case BINARY_OP:
2489
7.58k
                RETURN_IF_ERROR(fold_const_binop(bb, i, consts, const_cache));
2490
7.58k
                break;
2491
381k
        }
2492
381k
    }
2493
2494
429k
    for (int i = 0; i < bb->b_iused; i++) {
2495
380k
        cfg_instr *inst = &bb->b_instr[i];
2496
380k
        if (inst->i_opcode == SWAP) {
2497
1.87k
            if (swaptimize(bb, &i) < 0) {
2498
0
                goto error;
2499
0
            }
2500
1.87k
            apply_static_swaps(bb, i);
2501
1.87k
        }
2502
380k
    }
2503
48.2k
    return SUCCESS;
2504
0
error:
2505
0
    return ERROR;
2506
48.2k
}
2507
2508
static int resolve_line_numbers(cfg_builder *g, int firstlineno);
2509
2510
static int
2511
remove_redundant_nops_and_jumps(cfg_builder *g)
2512
15.1k
{
2513
15.1k
    int removed_nops, removed_jumps;
2514
17.2k
    do {
2515
        /* Convergence is guaranteed because the number of
2516
         * redundant jumps and nops only decreases.
2517
         */
2518
17.2k
        removed_nops = remove_redundant_nops(g);
2519
17.2k
        RETURN_IF_ERROR(removed_nops);
2520
17.2k
        removed_jumps = remove_redundant_jumps(g);
2521
17.2k
        RETURN_IF_ERROR(removed_jumps);
2522
17.2k
    } while(removed_nops + removed_jumps > 0);
2523
15.1k
    return SUCCESS;
2524
15.1k
}
2525
2526
/* Perform optimizations on a control flow graph.
2527
   The consts object should still be in list form to allow new constants
2528
   to be appended.
2529
2530
   Code trasnformations that reduce code size initially fill the gaps with
2531
   NOPs.  Later those NOPs are removed.
2532
*/
2533
static int
2534
optimize_cfg(cfg_builder *g, PyObject *consts, PyObject *const_cache, int firstlineno)
2535
6.99k
{
2536
6.99k
    assert(PyDict_CheckExact(const_cache));
2537
6.99k
    RETURN_IF_ERROR(check_cfg(g));
2538
6.99k
    RETURN_IF_ERROR(inline_small_or_no_lineno_blocks(g->g_entryblock));
2539
6.99k
    RETURN_IF_ERROR(remove_unreachable(g->g_entryblock));
2540
6.99k
    RETURN_IF_ERROR(resolve_line_numbers(g, firstlineno));
2541
6.99k
    RETURN_IF_ERROR(optimize_load_const(const_cache, g, consts));
2542
55.2k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
2543
48.2k
        RETURN_IF_ERROR(optimize_basic_block(const_cache, b, consts));
2544
48.2k
    }
2545
6.99k
    RETURN_IF_ERROR(remove_redundant_nops_and_pairs(g->g_entryblock));
2546
6.99k
    RETURN_IF_ERROR(remove_unreachable(g->g_entryblock));
2547
6.99k
    RETURN_IF_ERROR(remove_redundant_nops_and_jumps(g));
2548
6.99k
    assert(no_redundant_jumps(g));
2549
6.99k
    return SUCCESS;
2550
6.99k
}
2551
2552
static void
2553
make_super_instruction(cfg_instr *inst1, cfg_instr *inst2, int super_op)
2554
13.0k
{
2555
13.0k
    int32_t line1 = inst1->i_loc.lineno;
2556
13.0k
    int32_t line2 = inst2->i_loc.lineno;
2557
    /* Skip if instructions are on different lines */
2558
13.0k
    if (line1 >= 0 && line2 >= 0 && line1 != line2) {
2559
4.75k
        return;
2560
4.75k
    }
2561
8.30k
    if (inst1->i_oparg >= 16 || inst2->i_oparg >= 16) {
2562
823
        return;
2563
823
    }
2564
7.48k
    INSTR_SET_OP1(inst1, super_op, (inst1->i_oparg << 4) | inst2->i_oparg);
2565
7.48k
    INSTR_SET_OP0(inst2, NOP);
2566
7.48k
}
2567
2568
static int
2569
insert_superinstructions(cfg_builder *g)
2570
6.99k
{
2571
55.2k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
2572
2573
397k
        for (int i = 0; i < b->b_iused; i++) {
2574
349k
            cfg_instr *inst = &b->b_instr[i];
2575
349k
            int nextop = i+1 < b->b_iused ? b->b_instr[i+1].i_opcode : 0;
2576
349k
            switch(inst->i_opcode) {
2577
45.0k
                case LOAD_FAST:
2578
45.0k
                    if (nextop == LOAD_FAST) {
2579
6.91k
                        make_super_instruction(inst, &b->b_instr[i + 1], LOAD_FAST_LOAD_FAST);
2580
6.91k
                    }
2581
45.0k
                    break;
2582
12.6k
                case STORE_FAST:
2583
12.6k
                    switch (nextop) {
2584
4.81k
                        case LOAD_FAST:
2585
4.81k
                            make_super_instruction(inst, &b->b_instr[i + 1], STORE_FAST_LOAD_FAST);
2586
4.81k
                            break;
2587
1.33k
                        case STORE_FAST:
2588
1.33k
                            make_super_instruction(inst, &b->b_instr[i + 1], STORE_FAST_STORE_FAST);
2589
1.33k
                            break;
2590
12.6k
                    }
2591
12.6k
                    break;
2592
349k
            }
2593
349k
        }
2594
48.2k
    }
2595
6.99k
    int res = remove_redundant_nops(g);
2596
6.99k
    assert(no_redundant_nops(g));
2597
6.99k
    return res;
2598
6.99k
}
2599
2600
#define NOT_LOCAL -1
2601
13.4k
#define DUMMY_INSTR -1
2602
2603
typedef struct {
2604
    // Index of instruction that produced the reference or DUMMY_INSTR.
2605
    int instr;
2606
2607
    // The local to which the reference refers or NOT_LOCAL.
2608
    int local;
2609
} ref;
2610
2611
typedef struct {
2612
    ref *refs;
2613
    Py_ssize_t size;
2614
    Py_ssize_t capacity;
2615
} ref_stack;
2616
2617
static int
2618
ref_stack_push(ref_stack *stack, ref r)
2619
293k
{
2620
293k
    if (stack->size == stack->capacity) {
2621
6.99k
        Py_ssize_t new_cap = Py_MAX(32, stack->capacity * 2);
2622
6.99k
        ref *refs = PyMem_Realloc(stack->refs, sizeof(*stack->refs) * new_cap);
2623
6.99k
        if (refs == NULL) {
2624
0
            PyErr_NoMemory();
2625
0
            return -1;
2626
0
        }
2627
6.99k
        stack->refs = refs;
2628
6.99k
        stack->capacity = new_cap;
2629
6.99k
    }
2630
293k
    stack->refs[stack->size] = r;
2631
293k
    stack->size++;
2632
293k
    return 0;
2633
293k
}
2634
2635
static ref
2636
ref_stack_pop(ref_stack *stack)
2637
251k
{
2638
251k
    assert(stack->size > 0);
2639
251k
    stack->size--;
2640
251k
    ref r = stack->refs[stack->size];
2641
251k
    return r;
2642
251k
}
2643
2644
static void
2645
ref_stack_swap_top(ref_stack *stack, Py_ssize_t off)
2646
1.21k
{
2647
1.21k
    Py_ssize_t idx = stack->size - off;
2648
1.21k
    assert(idx >= 0 && idx < stack->size);
2649
1.21k
    ref tmp = stack->refs[idx];
2650
1.21k
    stack->refs[idx] = stack->refs[stack->size - 1];
2651
1.21k
    stack->refs[stack->size - 1] = tmp;
2652
1.21k
}
2653
2654
static ref
2655
ref_stack_at(ref_stack *stack, Py_ssize_t idx)
2656
55.9k
{
2657
55.9k
    assert(idx >= 0 && idx < stack->size);
2658
55.9k
    return stack->refs[idx];
2659
55.9k
}
2660
2661
static void
2662
ref_stack_clear(ref_stack *stack)
2663
35.8k
{
2664
35.8k
    stack->size = 0;
2665
35.8k
}
2666
2667
static void
2668
ref_stack_fini(ref_stack *stack)
2669
6.99k
{
2670
6.99k
    if (stack->refs != NULL) {
2671
6.99k
        PyMem_Free(stack->refs);
2672
6.99k
    }
2673
6.99k
    stack->refs = NULL;
2674
6.99k
    stack->capacity = 0;
2675
6.99k
    stack->size = 0;
2676
6.99k
}
2677
2678
typedef enum {
2679
    // The loaded reference is still on the stack when the local is killed
2680
    SUPPORT_KILLED  = 1,
2681
    // The loaded reference is stored into a local
2682
    STORED_AS_LOCAL = 2,
2683
    // The loaded reference is still on the stack at the end of the basic block
2684
    REF_UNCONSUMED  = 4,
2685
} LoadFastInstrFlag;
2686
2687
static void
2688
kill_local(uint8_t *instr_flags, ref_stack *refs, int local)
2689
13.7k
{
2690
27.0k
    for (Py_ssize_t i = 0; i < refs->size; i++) {
2691
13.3k
        ref r = ref_stack_at(refs, i);
2692
13.3k
        if (r.local == local) {
2693
13
            assert(r.instr >= 0);
2694
13
            instr_flags[r.instr] |= SUPPORT_KILLED;
2695
13
        }
2696
13.3k
    }
2697
13.7k
}
2698
2699
static void
2700
store_local(uint8_t *instr_flags, ref_stack *refs, int local, ref r)
2701
13.4k
{
2702
13.4k
    kill_local(instr_flags, refs, local);
2703
13.4k
    if (r.instr != DUMMY_INSTR) {
2704
11.5k
        instr_flags[r.instr] |= STORED_AS_LOCAL;
2705
11.5k
    }
2706
13.4k
}
2707
2708
static void
2709
load_fast_push_block(basicblock ***sp, basicblock *target,
2710
                     Py_ssize_t start_depth)
2711
37.7k
{
2712
37.7k
    assert(target->b_startdepth >= 0 && target->b_startdepth == start_depth);
2713
37.7k
    if (!target->b_visited) {
2714
28.8k
        target->b_visited = 1;
2715
28.8k
        *(*sp)++ = target;
2716
28.8k
    }
2717
37.7k
}
2718
2719
/*
2720
 * Strength reduce LOAD_FAST{_LOAD_FAST} instructions into faster variants that
2721
 * load borrowed references onto the operand stack.
2722
 *
2723
 * This is only safe when we can prove that the reference in the frame outlives
2724
 * the borrowed reference produced by the instruction. We make this tractable
2725
 * by enforcing the following lifetimes:
2726
 *
2727
 * 1. Borrowed references loaded onto the operand stack live until the end of
2728
 *    the instruction that consumes them from the stack. Any borrowed
2729
 *    references that would escape into the heap (e.g. into frame objects or
2730
 *    generators) are converted into new, strong references.
2731
 *
2732
 * 2. Locals live until they are either killed by an instruction
2733
 *    (e.g. STORE_FAST) or the frame is unwound. Any local that is overwritten
2734
 *    via `f_locals` is added to a tuple owned by the frame object.
2735
 *
2736
 * To simplify the problem of detecting which supporting references in the
2737
 * frame are killed by instructions that overwrite locals, we only allow
2738
 * borrowed references to be stored as a local in the frame if they were passed
2739
 * as an argument. {RETURN,YIELD}_VALUE convert borrowed references into new,
2740
 * strong references.
2741
 *
2742
 * Using the above, we can optimize any LOAD_FAST{_LOAD_FAST} instructions
2743
 * that meet the following criteria:
2744
 *
2745
 * 1. The produced reference must be consumed from the stack before the
2746
 *    supporting reference in the frame is killed.
2747
 *
2748
 * 2. The produced reference cannot be stored as a local.
2749
 *
2750
 * We use abstract interpretation to identify instructions that meet these
2751
 * criteria. For each basic block, we simulate the effect the bytecode has on a
2752
 * stack of abstract references and note any instructions that violate the
2753
 * criteria above. Once we've processed all the instructions in a block, any
2754
 * non-violating LOAD_FAST{_LOAD_FAST} can be optimized.
2755
 */
2756
static int
2757
optimize_load_fast(cfg_builder *g)
2758
6.99k
{
2759
6.99k
    int status;
2760
6.99k
    ref_stack refs = {0};
2761
6.99k
    int max_instrs = 0;
2762
6.99k
    basicblock *entryblock = g->g_entryblock;
2763
56.1k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
2764
49.1k
        max_instrs = Py_MAX(max_instrs, b->b_iused);
2765
49.1k
    }
2766
6.99k
    size_t instr_flags_size = max_instrs * sizeof(uint8_t);
2767
6.99k
    uint8_t *instr_flags = PyMem_Malloc(instr_flags_size);
2768
6.99k
    if (instr_flags == NULL) {
2769
0
        PyErr_NoMemory();
2770
0
        return ERROR;
2771
0
    }
2772
6.99k
    basicblock **blocks = make_cfg_traversal_stack(entryblock);
2773
6.99k
    if (blocks == NULL) {
2774
0
        status = ERROR;
2775
0
        goto done;
2776
0
    }
2777
6.99k
    basicblock **sp = blocks;
2778
6.99k
    *sp = entryblock;
2779
6.99k
    sp++;
2780
6.99k
    entryblock->b_startdepth = 0;
2781
6.99k
    entryblock->b_visited = 1;
2782
2783
6.99k
    #define PUSH_REF(instr, local)                \
2784
293k
        do {                                      \
2785
293k
            if (ref_stack_push(&refs, (ref){(instr), (local)}) < 0) { \
2786
0
                status = ERROR;                   \
2787
0
                goto done;                        \
2788
0
            }                                     \
2789
293k
        } while(0)
2790
2791
42.8k
    while (sp != blocks) {
2792
35.8k
        basicblock *block = *--sp;
2793
35.8k
        assert(block->b_startdepth > -1);
2794
2795
        // Reset per-block state.
2796
35.8k
        memset(instr_flags, 0, block->b_iused * sizeof(*instr_flags));
2797
2798
        // Reset the stack of refs. We don't track references on the stack
2799
        // across basic blocks, but the bytecode will expect their
2800
        // presence. Add dummy references as necessary.
2801
35.8k
        ref_stack_clear(&refs);
2802
70.3k
        for (int i = 0; i < block->b_startdepth; i++) {
2803
34.4k
            PUSH_REF(DUMMY_INSTR, NOT_LOCAL);
2804
34.4k
        }
2805
2806
367k
        for (int i = 0; i < block->b_iused; i++) {
2807
331k
            cfg_instr *instr = &block->b_instr[i];
2808
331k
            int opcode = instr->i_opcode;
2809
331k
            int oparg = instr->i_oparg;
2810
331k
            assert(opcode != EXTENDED_ARG);
2811
331k
            switch (opcode) {
2812
                // Opcodes that load and store locals
2813
2
                case DELETE_FAST: {
2814
2
                    kill_local(instr_flags, &refs, oparg);
2815
2
                    break;
2816
0
                }
2817
2818
39.3k
                case LOAD_FAST: {
2819
39.3k
                    PUSH_REF(i, oparg);
2820
39.3k
                    break;
2821
39.3k
                }
2822
2823
39.3k
                case LOAD_FAST_AND_CLEAR: {
2824
321
                    kill_local(instr_flags, &refs, oparg);
2825
321
                    PUSH_REF(i, oparg);
2826
321
                    break;
2827
321
                }
2828
2829
5.95k
                case LOAD_FAST_LOAD_FAST: {
2830
5.95k
                    PUSH_REF(i, oparg >> 4);
2831
5.95k
                    PUSH_REF(i, oparg & 15);
2832
5.95k
                    break;
2833
5.95k
                }
2834
2835
10.9k
                case STORE_FAST: {
2836
10.9k
                    ref r = ref_stack_pop(&refs);
2837
10.9k
                    store_local(instr_flags, &refs, oparg, r);
2838
10.9k
                    break;
2839
5.95k
                }
2840
2841
225
                case STORE_FAST_LOAD_FAST: {
2842
                    // STORE_FAST
2843
225
                    ref r = ref_stack_pop(&refs);
2844
225
                    store_local(instr_flags, &refs, oparg >> 4, r);
2845
                    // LOAD_FAST
2846
225
                    PUSH_REF(i, oparg & 15);
2847
225
                    break;
2848
225
                }
2849
2850
1.12k
                case STORE_FAST_STORE_FAST: {
2851
                    // STORE_FAST
2852
1.12k
                    ref r = ref_stack_pop(&refs);
2853
1.12k
                    store_local(instr_flags, &refs, oparg >> 4, r);
2854
                    // STORE_FAST
2855
1.12k
                    r = ref_stack_pop(&refs);
2856
1.12k
                    store_local(instr_flags, &refs, oparg & 15, r);
2857
1.12k
                    break;
2858
225
                }
2859
2860
                // Opcodes that shuffle values on the stack
2861
1.35k
                case COPY: {
2862
1.35k
                    assert(oparg > 0);
2863
1.35k
                    Py_ssize_t idx = refs.size - oparg;
2864
1.35k
                    ref r = ref_stack_at(&refs, idx);
2865
1.35k
                    PUSH_REF(r.instr, r.local);
2866
1.35k
                    break;
2867
1.35k
                }
2868
2869
1.35k
                case SWAP: {
2870
1.21k
                    assert(oparg >= 2);
2871
1.21k
                    ref_stack_swap_top(&refs, oparg);
2872
1.21k
                    break;
2873
1.35k
                }
2874
2875
                // We treat opcodes that do not consume all of their inputs on
2876
                // a case by case basis, as we have no generic way of knowing
2877
                // how many inputs should be left on the stack.
2878
2879
                // Opcodes that consume no inputs
2880
1.39k
                case FORMAT_SIMPLE:
2881
1.39k
                case GET_ANEXT:
2882
2.99k
                case GET_ITER:
2883
2.99k
                case GET_LEN:
2884
3.02k
                case GET_YIELD_FROM_ITER:
2885
3.64k
                case IMPORT_FROM:
2886
3.64k
                case MATCH_KEYS:
2887
3.64k
                case MATCH_MAPPING:
2888
3.64k
                case MATCH_SEQUENCE:
2889
3.64k
                case WITH_EXCEPT_START: {
2890
3.64k
                    int num_popped = _PyOpcode_num_popped(opcode, oparg);
2891
3.64k
                    int num_pushed = _PyOpcode_num_pushed(opcode, oparg);
2892
3.64k
                    int net_pushed = num_pushed - num_popped;
2893
3.64k
                    assert(net_pushed >= 0);
2894
5.86k
                    for (int j = 0; j < net_pushed; j++) {
2895
2.22k
                        PUSH_REF(i, NOT_LOCAL);
2896
2.22k
                    }
2897
3.64k
                    break;
2898
3.64k
                }
2899
2900
                // Opcodes that consume some inputs and push no new values
2901
3.64k
                case DICT_MERGE:
2902
814
                case DICT_UPDATE:
2903
1.54k
                case LIST_APPEND:
2904
1.75k
                case LIST_EXTEND:
2905
12.5k
                case MAP_ADD:
2906
12.5k
                case RERAISE:
2907
12.7k
                case SET_ADD:
2908
12.7k
                case SET_UPDATE: {
2909
12.7k
                    int num_popped = _PyOpcode_num_popped(opcode, oparg);
2910
12.7k
                    int num_pushed = _PyOpcode_num_pushed(opcode, oparg);
2911
12.7k
                    int net_popped = num_popped - num_pushed;
2912
12.7k
                    assert(net_popped > 0);
2913
36.2k
                    for (int i = 0; i < net_popped; i++) {
2914
23.5k
                        ref_stack_pop(&refs);
2915
23.5k
                    }
2916
12.7k
                    break;
2917
12.7k
                }
2918
2919
44
                case END_SEND:
2920
1.91k
                case SET_FUNCTION_ATTRIBUTE: {
2921
1.91k
                    assert(_PyOpcode_num_popped(opcode, oparg) == 2);
2922
1.91k
                    assert(_PyOpcode_num_pushed(opcode, oparg) == 1);
2923
1.91k
                    ref tos = ref_stack_pop(&refs);
2924
1.91k
                    ref_stack_pop(&refs);
2925
1.91k
                    PUSH_REF(tos.instr, tos.local);
2926
1.91k
                    break;
2927
1.91k
                }
2928
2929
                // Opcodes that consume some inputs and push new values
2930
1.91k
                case CHECK_EXC_MATCH: {
2931
0
                    ref_stack_pop(&refs);
2932
0
                    PUSH_REF(i, NOT_LOCAL);
2933
0
                    break;
2934
0
                }
2935
2936
1.68k
                case FOR_ITER: {
2937
1.68k
                    load_fast_push_block(&sp, instr->i_target, refs.size + 1);
2938
1.68k
                    PUSH_REF(i, NOT_LOCAL);
2939
1.68k
                    break;
2940
1.68k
                }
2941
2942
19.9k
                case LOAD_ATTR:
2943
20.1k
                case LOAD_SUPER_ATTR: {
2944
20.1k
                    ref self = ref_stack_pop(&refs);
2945
20.1k
                    if (opcode == LOAD_SUPER_ATTR) {
2946
210
                        ref_stack_pop(&refs);
2947
210
                        ref_stack_pop(&refs);
2948
210
                    }
2949
20.1k
                    PUSH_REF(i, NOT_LOCAL);
2950
20.1k
                    if (oparg & 1) {
2951
                        // A method call; conservatively assume that self is pushed
2952
                        // back onto the stack
2953
7.87k
                        PUSH_REF(self.instr, self.local);
2954
7.87k
                    }
2955
20.1k
                    break;
2956
20.1k
                }
2957
2958
20.1k
                case LOAD_SPECIAL:
2959
224
                case PUSH_EXC_INFO: {
2960
224
                    ref tos = ref_stack_pop(&refs);
2961
224
                    PUSH_REF(i, NOT_LOCAL);
2962
224
                    PUSH_REF(tos.instr, tos.local);
2963
224
                    break;
2964
224
                }
2965
2966
224
                case SEND: {
2967
44
                    load_fast_push_block(&sp, instr->i_target, refs.size);
2968
44
                    ref_stack_pop(&refs);
2969
44
                    PUSH_REF(i, NOT_LOCAL);
2970
44
                    break;
2971
44
                }
2972
2973
                // Opcodes that consume all of their inputs
2974
230k
                default: {
2975
230k
                    int num_popped = _PyOpcode_num_popped(opcode, oparg);
2976
230k
                    int num_pushed = _PyOpcode_num_pushed(opcode, oparg);
2977
230k
                    if (HAS_TARGET(instr->i_opcode)) {
2978
16.2k
                        load_fast_push_block(&sp, instr->i_target, refs.size - num_popped + num_pushed);
2979
16.2k
                    }
2980
230k
                    if (!IS_BLOCK_PUSH_OPCODE(instr->i_opcode)) {
2981
                        // Block push opcodes only affect the stack when jumping
2982
                        // to the target.
2983
421k
                        for (int j = 0; j < num_popped; j++) {
2984
190k
                            ref_stack_pop(&refs);
2985
190k
                        }
2986
402k
                        for (int j = 0; j < num_pushed; j++) {
2987
171k
                            PUSH_REF(i, NOT_LOCAL);
2988
171k
                        }
2989
230k
                    }
2990
230k
                    break;
2991
230k
                }
2992
331k
            }
2993
331k
        }
2994
2995
        // Push fallthrough block
2996
35.8k
        if (BB_HAS_FALLTHROUGH(block)) {
2997
19.8k
            assert(block->b_next != NULL);
2998
19.8k
            load_fast_push_block(&sp, block->b_next, refs.size);
2999
19.8k
        }
3000
3001
        // Mark instructions that produce values that are on the stack at the
3002
        // end of the basic block
3003
77.1k
        for (Py_ssize_t i = 0; i < refs.size; i++) {
3004
41.2k
            ref r = ref_stack_at(&refs, i);
3005
41.2k
            if (r.instr != -1) {
3006
17.3k
                instr_flags[r.instr] |= REF_UNCONSUMED;
3007
17.3k
            }
3008
41.2k
        }
3009
3010
        // Optimize instructions
3011
367k
        for (int i = 0; i < block->b_iused; i++) {
3012
331k
            if (!instr_flags[i]) {
3013
304k
                cfg_instr *instr = &block->b_instr[i];
3014
304k
                switch (instr->i_opcode) {
3015
37.9k
                    case LOAD_FAST:
3016
37.9k
                        instr->i_opcode = LOAD_FAST_BORROW;
3017
37.9k
                        break;
3018
5.87k
                    case LOAD_FAST_LOAD_FAST:
3019
5.87k
                        instr->i_opcode = LOAD_FAST_BORROW_LOAD_FAST_BORROW;
3020
5.87k
                        break;
3021
260k
                    default:
3022
260k
                        break;
3023
304k
                }
3024
304k
            }
3025
331k
        }
3026
35.8k
    }
3027
3028
6.99k
    #undef PUSH_REF
3029
3030
6.99k
    status = SUCCESS;
3031
3032
6.99k
done:
3033
6.99k
    ref_stack_fini(&refs);
3034
6.99k
    PyMem_Free(instr_flags);
3035
6.99k
    PyMem_Free(blocks);
3036
6.99k
    return status;
3037
6.99k
}
3038
3039
// helper functions for add_checks_for_loads_of_unknown_variables
3040
static inline void
3041
maybe_push(basicblock *b, uint64_t unsafe_mask, basicblock ***sp)
3042
163k
{
3043
    // Push b if the unsafe mask is giving us any new information.
3044
    // To avoid overflowing the stack, only allow each block once.
3045
    // Use b->b_visited=1 to mean that b is currently on the stack.
3046
163k
    uint64_t both = b->b_unsafe_locals_mask | unsafe_mask;
3047
163k
    if (b->b_unsafe_locals_mask != both) {
3048
27.4k
        b->b_unsafe_locals_mask = both;
3049
        // More work left to do.
3050
27.4k
        if (!b->b_visited) {
3051
            // not on the stack, so push it.
3052
27.2k
            *(*sp)++ = b;
3053
27.2k
            b->b_visited = 1;
3054
27.2k
        }
3055
27.4k
    }
3056
163k
}
3057
3058
static void
3059
scan_block_for_locals(basicblock *b, basicblock ***sp)
3060
72.0k
{
3061
    // bit i is set if local i is potentially uninitialized
3062
72.0k
    uint64_t unsafe_mask = b->b_unsafe_locals_mask;
3063
500k
    for (int i = 0; i < b->b_iused; i++) {
3064
428k
        cfg_instr *instr = &b->b_instr[i];
3065
428k
        assert(instr->i_opcode != EXTENDED_ARG);
3066
428k
        if (instr->i_except != NULL) {
3067
84.6k
            maybe_push(instr->i_except, unsafe_mask, sp);
3068
84.6k
        }
3069
428k
        if (instr->i_oparg >= 64) {
3070
29.3k
            continue;
3071
29.3k
        }
3072
428k
        assert(instr->i_oparg >= 0);
3073
398k
        uint64_t bit = (uint64_t)1 << instr->i_oparg;
3074
398k
        switch (instr->i_opcode) {
3075
345
            case DELETE_FAST:
3076
997
            case LOAD_FAST_AND_CLEAR:
3077
2.30k
            case STORE_FAST_MAYBE_NULL:
3078
2.30k
                unsafe_mask |= bit;
3079
2.30k
                break;
3080
26.8k
            case STORE_FAST:
3081
26.8k
                unsafe_mask &= ~bit;
3082
26.8k
                break;
3083
125
            case LOAD_FAST_CHECK:
3084
                // If this doesn't raise, then the local is defined.
3085
125
                unsafe_mask &= ~bit;
3086
125
                break;
3087
87.9k
            case LOAD_FAST:
3088
87.9k
                if (unsafe_mask & bit) {
3089
125
                    instr->i_opcode = LOAD_FAST_CHECK;
3090
125
                }
3091
87.9k
                unsafe_mask &= ~bit;
3092
87.9k
                break;
3093
398k
        }
3094
398k
    }
3095
72.0k
    if (b->b_next && BB_HAS_FALLTHROUGH(b)) {
3096
38.3k
        maybe_push(b->b_next, unsafe_mask, sp);
3097
38.3k
    }
3098
72.0k
    cfg_instr *last = basicblock_last_instr(b);
3099
72.0k
    if (last && is_jump(last)) {
3100
35.1k
        assert(last->i_target != NULL);
3101
35.1k
        maybe_push(last->i_target, unsafe_mask, sp);
3102
35.1k
    }
3103
72.0k
}
3104
3105
static int
3106
fast_scan_many_locals(basicblock *entryblock, int nlocals)
3107
0
{
3108
0
    assert(nlocals > 64);
3109
0
    Py_ssize_t *states = PyMem_Calloc(nlocals - 64, sizeof(Py_ssize_t));
3110
0
    if (states == NULL) {
3111
0
        PyErr_NoMemory();
3112
0
        return ERROR;
3113
0
    }
3114
0
    Py_ssize_t blocknum = 0;
3115
    // state[i - 64] == blocknum if local i is guaranteed to
3116
    // be initialized, i.e., if it has had a previous LOAD_FAST or
3117
    // STORE_FAST within that basicblock (not followed by
3118
    // DELETE_FAST/LOAD_FAST_AND_CLEAR/STORE_FAST_MAYBE_NULL).
3119
0
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3120
0
        blocknum++;
3121
0
        for (int i = 0; i < b->b_iused; i++) {
3122
0
            cfg_instr *instr = &b->b_instr[i];
3123
0
            assert(instr->i_opcode != EXTENDED_ARG);
3124
0
            int arg = instr->i_oparg;
3125
0
            if (arg < 64) {
3126
0
                continue;
3127
0
            }
3128
0
            assert(arg >= 0);
3129
0
            switch (instr->i_opcode) {
3130
0
                case DELETE_FAST:
3131
0
                case LOAD_FAST_AND_CLEAR:
3132
0
                case STORE_FAST_MAYBE_NULL:
3133
0
                    states[arg - 64] = blocknum - 1;
3134
0
                    break;
3135
0
                case STORE_FAST:
3136
0
                    states[arg - 64] = blocknum;
3137
0
                    break;
3138
0
                case LOAD_FAST:
3139
0
                    if (states[arg - 64] != blocknum) {
3140
0
                        instr->i_opcode = LOAD_FAST_CHECK;
3141
0
                    }
3142
0
                    states[arg - 64] = blocknum;
3143
0
                    break;
3144
0
                    Py_UNREACHABLE();
3145
0
            }
3146
0
        }
3147
0
    }
3148
0
    PyMem_Free(states);
3149
0
    return SUCCESS;
3150
0
}
3151
3152
static int
3153
remove_unused_consts(basicblock *entryblock, PyObject *consts)
3154
6.99k
{
3155
6.99k
    assert(PyList_CheckExact(consts));
3156
6.99k
    Py_ssize_t nconsts = PyList_GET_SIZE(consts);
3157
6.99k
    if (nconsts == 0) {
3158
0
        return SUCCESS;  /* nothing to do */
3159
0
    }
3160
3161
6.99k
    Py_ssize_t *index_map = NULL;
3162
6.99k
    Py_ssize_t *reverse_index_map = NULL;
3163
6.99k
    int err = ERROR;
3164
3165
6.99k
    index_map = PyMem_Malloc(nconsts * sizeof(Py_ssize_t));
3166
6.99k
    if (index_map == NULL) {
3167
0
        goto end;
3168
0
    }
3169
52.5k
    for (Py_ssize_t i = 1; i < nconsts; i++) {
3170
45.5k
        index_map[i] = -1;
3171
45.5k
    }
3172
    // The first constant may be docstring; keep it always.
3173
6.99k
    index_map[0] = 0;
3174
3175
    /* mark used consts */
3176
55.2k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3177
397k
        for (int i = 0; i < b->b_iused; i++) {
3178
349k
            int opcode = b->b_instr[i].i_opcode;
3179
349k
            if (OPCODE_HAS_CONST(opcode)) {
3180
45.2k
                int index = b->b_instr[i].i_oparg;
3181
45.2k
                index_map[index] = index;
3182
45.2k
            }
3183
349k
        }
3184
48.2k
    }
3185
    /* now index_map[i] == i if consts[i] is used, -1 otherwise */
3186
    /* condense consts */
3187
6.99k
    Py_ssize_t n_used_consts = 0;
3188
59.5k
    for (Py_ssize_t i = 0; i < nconsts; i++) {
3189
52.5k
        if (index_map[i] != -1) {
3190
39.0k
            assert(index_map[i] == i);
3191
39.0k
            index_map[n_used_consts++] = index_map[i];
3192
39.0k
        }
3193
52.5k
    }
3194
6.99k
    if (n_used_consts == nconsts) {
3195
        /* nothing to do */
3196
2.78k
        err = SUCCESS;
3197
2.78k
        goto end;
3198
2.78k
    }
3199
3200
    /* move all used consts to the beginning of the consts list */
3201
6.99k
    assert(n_used_consts < nconsts);
3202
35.5k
    for (Py_ssize_t i = 0; i < n_used_consts; i++) {
3203
31.3k
        Py_ssize_t old_index = index_map[i];
3204
31.3k
        assert(i <= old_index && old_index < nconsts);
3205
31.3k
        if (i != old_index) {
3206
22.9k
            PyObject *value = PyList_GET_ITEM(consts, index_map[i]);
3207
22.9k
            assert(value != NULL);
3208
22.9k
            PyList_SetItem(consts, i, Py_NewRef(value));
3209
22.9k
        }
3210
31.3k
    }
3211
3212
    /* truncate the consts list at its new size */
3213
4.20k
    if (PyList_SetSlice(consts, n_used_consts, nconsts, NULL) < 0) {
3214
0
        goto end;
3215
0
    }
3216
    /* adjust const indices in the bytecode */
3217
4.20k
    reverse_index_map = PyMem_Malloc(nconsts * sizeof(Py_ssize_t));
3218
4.20k
    if (reverse_index_map == NULL) {
3219
0
        goto end;
3220
0
    }
3221
48.9k
    for (Py_ssize_t i = 0; i < nconsts; i++) {
3222
44.7k
        reverse_index_map[i] = -1;
3223
44.7k
    }
3224
35.5k
    for (Py_ssize_t i = 0; i < n_used_consts; i++) {
3225
31.3k
        assert(index_map[i] != -1);
3226
31.3k
        assert(reverse_index_map[index_map[i]] == -1);
3227
31.3k
        reverse_index_map[index_map[i]] = i;
3228
31.3k
    }
3229
3230
39.1k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3231
308k
        for (int i = 0; i < b->b_iused; i++) {
3232
273k
            int opcode = b->b_instr[i].i_opcode;
3233
273k
            if (OPCODE_HAS_CONST(opcode)) {
3234
37.1k
                int index = b->b_instr[i].i_oparg;
3235
37.1k
                assert(reverse_index_map[index] >= 0);
3236
37.1k
                assert(reverse_index_map[index] < n_used_consts);
3237
37.1k
                b->b_instr[i].i_oparg = (int)reverse_index_map[index];
3238
37.1k
            }
3239
273k
        }
3240
34.9k
    }
3241
3242
4.20k
    err = SUCCESS;
3243
6.99k
end:
3244
6.99k
    PyMem_Free(index_map);
3245
6.99k
    PyMem_Free(reverse_index_map);
3246
6.99k
    return err;
3247
4.20k
}
3248
3249
3250
3251
static int
3252
add_checks_for_loads_of_uninitialized_variables(basicblock *entryblock,
3253
                                                int nlocals,
3254
                                                int nparams)
3255
6.99k
{
3256
6.99k
    if (nlocals == 0) {
3257
1.66k
        return SUCCESS;
3258
1.66k
    }
3259
5.32k
    if (nlocals > 64) {
3260
        // To avoid O(nlocals**2) compilation, locals beyond the first
3261
        // 64 are only analyzed one basicblock at a time: initialization
3262
        // info is not passed between basicblocks.
3263
0
        if (fast_scan_many_locals(entryblock, nlocals) < 0) {
3264
0
            return ERROR;
3265
0
        }
3266
0
        nlocals = 64;
3267
0
    }
3268
5.32k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
3269
5.32k
    if (stack == NULL) {
3270
0
        return ERROR;
3271
0
    }
3272
5.32k
    basicblock **sp = stack;
3273
3274
    // First origin of being uninitialized:
3275
    // The non-parameter locals in the entry block.
3276
5.32k
    uint64_t start_mask = 0;
3277
13.5k
    for (int i = nparams; i < nlocals; i++) {
3278
8.24k
        start_mask |= (uint64_t)1 << i;
3279
8.24k
    }
3280
5.32k
    maybe_push(entryblock, start_mask, &sp);
3281
3282
    // Second origin of being uninitialized:
3283
    // There could be DELETE_FAST somewhere, so
3284
    // be sure to scan each basicblock at least once.
3285
50.0k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3286
44.7k
        scan_block_for_locals(b, &sp);
3287
44.7k
    }
3288
    // Now propagate the uncertainty from the origins we found: Use
3289
    // LOAD_FAST_CHECK for any LOAD_FAST where the local could be undefined.
3290
32.5k
    while (sp > stack) {
3291
27.2k
        basicblock *b = *--sp;
3292
        // mark as no longer on stack
3293
27.2k
        b->b_visited = 0;
3294
27.2k
        scan_block_for_locals(b, &sp);
3295
27.2k
    }
3296
5.32k
    PyMem_Free(stack);
3297
5.32k
    return SUCCESS;
3298
5.32k
}
3299
3300
3301
static int
3302
6.25k
mark_warm(basicblock *entryblock) {
3303
6.25k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
3304
6.25k
    if (stack == NULL) {
3305
0
        return ERROR;
3306
0
    }
3307
6.25k
    basicblock **sp = stack;
3308
3309
6.25k
    *sp++ = entryblock;
3310
6.25k
    entryblock->b_visited = 1;
3311
40.3k
    while (sp > stack) {
3312
34.0k
        basicblock *b = *(--sp);
3313
34.0k
        assert(!b->b_except_handler);
3314
34.0k
        b->b_warm = 1;
3315
34.0k
        basicblock *next = b->b_next;
3316
34.0k
        if (next && BB_HAS_FALLTHROUGH(b) && !next->b_visited) {
3317
16.3k
            *sp++ = next;
3318
16.3k
            next->b_visited = 1;
3319
16.3k
        }
3320
301k
        for (int i=0; i < b->b_iused; i++) {
3321
267k
            cfg_instr *instr = &b->b_instr[i];
3322
267k
            if (is_jump(instr) && !instr->i_target->b_visited) {
3323
11.4k
                *sp++ = instr->i_target;
3324
11.4k
                instr->i_target->b_visited = 1;
3325
11.4k
            }
3326
267k
        }
3327
34.0k
    }
3328
6.25k
    PyMem_Free(stack);
3329
6.25k
    return SUCCESS;
3330
6.25k
}
3331
3332
static int
3333
6.25k
mark_cold(basicblock *entryblock) {
3334
53.8k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3335
47.5k
        assert(!b->b_cold && !b->b_warm);
3336
47.5k
    }
3337
6.25k
    if (mark_warm(entryblock) < 0) {
3338
0
        return ERROR;
3339
0
    }
3340
3341
6.25k
    basicblock **stack = make_cfg_traversal_stack(entryblock);
3342
6.25k
    if (stack == NULL) {
3343
0
        return ERROR;
3344
0
    }
3345
3346
6.25k
    basicblock **sp = stack;
3347
53.8k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3348
47.5k
        if (b->b_except_handler) {
3349
2.84k
            assert(!b->b_warm);
3350
2.84k
            *sp++ = b;
3351
2.84k
            b->b_visited = 1;
3352
2.84k
        }
3353
47.5k
    }
3354
3355
11.8k
    while (sp > stack) {
3356
5.57k
        basicblock *b = *(--sp);
3357
5.57k
        b->b_cold = 1;
3358
5.57k
        basicblock *next = b->b_next;
3359
5.57k
        if (next && BB_HAS_FALLTHROUGH(b)) {
3360
1.50k
            if (!next->b_warm && !next->b_visited) {
3361
1.40k
                *sp++ = next;
3362
1.40k
                next->b_visited = 1;
3363
1.40k
            }
3364
1.50k
        }
3365
29.8k
        for (int i = 0; i < b->b_iused; i++) {
3366
24.2k
            cfg_instr *instr = &b->b_instr[i];
3367
24.2k
            if (is_jump(instr)) {
3368
1.91k
                assert(i == b->b_iused - 1);
3369
1.91k
                basicblock *target = b->b_instr[i].i_target;
3370
1.91k
                if (!target->b_warm && !target->b_visited) {
3371
1.32k
                    *sp++ = target;
3372
1.32k
                    target->b_visited = 1;
3373
1.32k
                }
3374
1.91k
            }
3375
24.2k
        }
3376
5.57k
    }
3377
6.25k
    PyMem_Free(stack);
3378
6.25k
    return SUCCESS;
3379
6.25k
}
3380
3381
3382
static int
3383
6.99k
push_cold_blocks_to_end(cfg_builder *g) {
3384
6.99k
    basicblock *entryblock = g->g_entryblock;
3385
6.99k
    if (entryblock->b_next == NULL) {
3386
        /* single basicblock, no need to reorder */
3387
739
        return SUCCESS;
3388
739
    }
3389
6.25k
    RETURN_IF_ERROR(mark_cold(entryblock));
3390
3391
6.25k
    int next_lbl = get_max_label(g->g_entryblock) + 1;
3392
3393
    /* If we have a cold block with fallthrough to a warm block, add */
3394
    /* an explicit jump instead of fallthrough */
3395
53.8k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3396
47.6k
        if (b->b_cold && BB_HAS_FALLTHROUGH(b) && b->b_next && b->b_next->b_warm) {
3397
44
            basicblock *explicit_jump = cfg_builder_new_block(g);
3398
44
            if (explicit_jump == NULL) {
3399
0
                return ERROR;
3400
0
            }
3401
44
            if (!IS_LABEL(b->b_next->b_label)) {
3402
0
                b->b_next->b_label.id = next_lbl++;
3403
0
            }
3404
44
            basicblock_addop(explicit_jump, JUMP_NO_INTERRUPT, b->b_next->b_label.id,
3405
44
                             NO_LOCATION);
3406
44
            explicit_jump->b_cold = 1;
3407
44
            explicit_jump->b_next = b->b_next;
3408
44
            explicit_jump->b_predecessors = 1;
3409
44
            b->b_next = explicit_jump;
3410
3411
            /* set target */
3412
44
            cfg_instr *last = basicblock_last_instr(explicit_jump);
3413
44
            last->i_target = explicit_jump->b_next;
3414
44
        }
3415
47.6k
    }
3416
3417
6.25k
    assert(!entryblock->b_cold);  /* First block can't be cold */
3418
6.25k
    basicblock *cold_blocks = NULL;
3419
6.25k
    basicblock *cold_blocks_tail = NULL;
3420
3421
6.25k
    basicblock *b = entryblock;
3422
8.40k
    while(b->b_next) {
3423
8.40k
        assert(!b->b_cold);
3424
44.1k
        while (b->b_next && !b->b_next->b_cold) {
3425
35.7k
            b = b->b_next;
3426
35.7k
        }
3427
8.40k
        if (b->b_next == NULL) {
3428
            /* no more cold blocks */
3429
6.25k
            break;
3430
6.25k
        }
3431
3432
        /* b->b_next is the beginning of a cold streak */
3433
8.40k
        assert(!b->b_cold && b->b_next->b_cold);
3434
3435
2.14k
        basicblock *b_end = b->b_next;
3436
5.61k
        while (b_end->b_next && b_end->b_next->b_cold) {
3437
3.46k
            b_end = b_end->b_next;
3438
3.46k
        }
3439
3440
        /* b_end is the end of the cold streak */
3441
2.14k
        assert(b_end && b_end->b_cold);
3442
2.14k
        assert(b_end->b_next == NULL || !b_end->b_next->b_cold);
3443
3444
2.14k
        if (cold_blocks == NULL) {
3445
1.15k
            cold_blocks = b->b_next;
3446
1.15k
        }
3447
990
        else {
3448
990
            cold_blocks_tail->b_next = b->b_next;
3449
990
        }
3450
2.14k
        cold_blocks_tail = b_end;
3451
2.14k
        b->b_next = b_end->b_next;
3452
2.14k
        b_end->b_next = NULL;
3453
2.14k
    }
3454
6.25k
    assert(b != NULL && b->b_next == NULL);
3455
6.25k
    b->b_next = cold_blocks;
3456
3457
6.25k
    if (cold_blocks != NULL) {
3458
1.15k
        RETURN_IF_ERROR(remove_redundant_nops_and_jumps(g));
3459
1.15k
    }
3460
6.25k
    return SUCCESS;
3461
6.25k
}
3462
3463
static int
3464
convert_pseudo_conditional_jumps(cfg_builder *g)
3465
6.99k
{
3466
6.99k
    basicblock *entryblock = g->g_entryblock;
3467
55.3k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3468
389k
        for (int i = 0; i < b->b_iused; i++) {
3469
341k
            cfg_instr *instr = &b->b_instr[i];
3470
341k
            if (instr->i_opcode == JUMP_IF_FALSE || instr->i_opcode == JUMP_IF_TRUE) {
3471
589
                assert(i == b->b_iused - 1);
3472
589
                instr->i_opcode = instr->i_opcode == JUMP_IF_FALSE ?
3473
315
                                          POP_JUMP_IF_FALSE : POP_JUMP_IF_TRUE;
3474
589
                location loc = instr->i_loc;
3475
589
                basicblock *except = instr->i_except;
3476
589
                cfg_instr copy = {
3477
589
                            .i_opcode = COPY,
3478
589
                            .i_oparg = 1,
3479
589
                            .i_loc = loc,
3480
589
                            .i_target = NULL,
3481
589
                            .i_except = except,
3482
589
                };
3483
589
                RETURN_IF_ERROR(basicblock_insert_instruction(b, i++, &copy));
3484
589
                cfg_instr to_bool = {
3485
589
                            .i_opcode = TO_BOOL,
3486
589
                            .i_oparg = 0,
3487
589
                            .i_loc = loc,
3488
589
                            .i_target = NULL,
3489
589
                            .i_except = except,
3490
589
                };
3491
589
                RETURN_IF_ERROR(basicblock_insert_instruction(b, i++, &to_bool));
3492
589
            }
3493
341k
        }
3494
48.3k
    }
3495
6.99k
    return SUCCESS;
3496
6.99k
}
3497
3498
static int
3499
convert_pseudo_ops(cfg_builder *g)
3500
6.99k
{
3501
6.99k
    basicblock *entryblock = g->g_entryblock;
3502
55.3k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3503
393k
        for (int i = 0; i < b->b_iused; i++) {
3504
345k
            cfg_instr *instr = &b->b_instr[i];
3505
345k
            if (is_block_push(instr)) {
3506
2.84k
                INSTR_SET_OP0(instr, NOP);
3507
2.84k
            }
3508
342k
            else if (instr->i_opcode == LOAD_CLOSURE) {
3509
1.95k
                assert(is_pseudo_target(LOAD_CLOSURE, LOAD_FAST));
3510
1.95k
                instr->i_opcode = LOAD_FAST;
3511
1.95k
            }
3512
340k
            else if (instr->i_opcode == STORE_FAST_MAYBE_NULL) {
3513
652
                assert(is_pseudo_target(STORE_FAST_MAYBE_NULL, STORE_FAST));
3514
652
                instr->i_opcode = STORE_FAST;
3515
652
            }
3516
345k
        }
3517
48.3k
    }
3518
6.99k
    return remove_redundant_nops_and_jumps(g);
3519
6.99k
}
3520
3521
static inline bool
3522
81.0k
is_exit_or_eval_check_without_lineno(basicblock *b) {
3523
81.0k
    if (basicblock_exits_scope(b) || basicblock_has_eval_break(b)) {
3524
45.0k
        return basicblock_has_no_lineno(b);
3525
45.0k
    }
3526
35.9k
    else {
3527
35.9k
        return false;
3528
35.9k
    }
3529
81.0k
}
3530
3531
3532
/* PEP 626 mandates that the f_lineno of a frame is correct
3533
 * after a frame terminates. It would be prohibitively expensive
3534
 * to continuously update the f_lineno field at runtime,
3535
 * so we make sure that all exiting instruction (raises and returns)
3536
 * have a valid line number, allowing us to compute f_lineno lazily.
3537
 * We can do this by duplicating the exit blocks without line number
3538
 * so that none have more than one predecessor. We can then safely
3539
 * copy the line number from the sole predecessor block.
3540
 */
3541
static int
3542
duplicate_exits_without_lineno(cfg_builder *g)
3543
13.9k
{
3544
13.9k
    int next_lbl = get_max_label(g->g_entryblock) + 1;
3545
3546
    /* Copy all exit blocks without line number that are targets of a jump.
3547
     */
3548
13.9k
    basicblock *entryblock = g->g_entryblock;
3549
110k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3550
96.6k
        cfg_instr *last = basicblock_last_instr(b);
3551
96.6k
        if (last == NULL) {
3552
15.1k
            continue;
3553
15.1k
        }
3554
81.4k
        if (is_jump(last)) {
3555
39.7k
            basicblock *target = next_nonempty_block(last->i_target);
3556
39.7k
            if (is_exit_or_eval_check_without_lineno(target) && target->b_predecessors > 1) {
3557
651
                basicblock *new_target = copy_basicblock(g, target);
3558
651
                if (new_target == NULL) {
3559
0
                    return ERROR;
3560
0
                }
3561
651
                new_target->b_instr[0].i_loc = last->i_loc;
3562
651
                last->i_target = new_target;
3563
651
                target->b_predecessors--;
3564
651
                new_target->b_predecessors = 1;
3565
651
                new_target->b_next = target->b_next;
3566
651
                new_target->b_label.id = next_lbl++;
3567
651
                target->b_next = new_target;
3568
651
            }
3569
39.7k
        }
3570
81.4k
    }
3571
3572
    /* Any remaining reachable exit blocks without line number can only be reached by
3573
     * fall through, and thus can only have a single predecessor */
3574
110k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3575
96.6k
        if (BB_HAS_FALLTHROUGH(b) && b->b_next && b->b_iused > 0) {
3576
41.3k
            if (is_exit_or_eval_check_without_lineno(b->b_next)) {
3577
833
                cfg_instr *last = basicblock_last_instr(b);
3578
833
                assert(last != NULL);
3579
833
                b->b_next->b_instr[0].i_loc = last->i_loc;
3580
833
            }
3581
41.3k
        }
3582
96.6k
    }
3583
13.9k
    return SUCCESS;
3584
13.9k
}
3585
3586
3587
/* If an instruction has no line number, but it's predecessor in the BB does,
3588
 * then copy the line number. If a successor block has no line number, and only
3589
 * one predecessor, then inherit the line number.
3590
 * This ensures that all exit blocks (with one predecessor) receive a line number.
3591
 * Also reduces the size of the line number table,
3592
 * but has no impact on the generated line number events.
3593
 */
3594
3595
static inline void
3596
maybe_propagate_location(basicblock *b, int i, location loc)
3597
769k
{
3598
769k
    assert(b->b_iused > i);
3599
769k
    if (b->b_instr[i].i_loc.lineno == NO_LOCATION.lineno) {
3600
44.6k
         b->b_instr[i].i_loc = loc;
3601
44.6k
    }
3602
769k
}
3603
3604
static void
3605
propagate_line_numbers(basicblock *entryblock)
3606
13.9k
{
3607
110k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3608
96.6k
        cfg_instr *last = basicblock_last_instr(b);
3609
96.6k
        if (last == NULL) {
3610
15.1k
            continue;
3611
15.1k
        }
3612
3613
81.4k
        location prev_location = NO_LOCATION;
3614
802k
        for (int i = 0; i < b->b_iused; i++) {
3615
721k
            maybe_propagate_location(b, i, prev_location);
3616
721k
            prev_location = b->b_instr[i].i_loc;
3617
721k
        }
3618
81.4k
        if (BB_HAS_FALLTHROUGH(b) && b->b_next->b_predecessors == 1) {
3619
29.7k
            if (b->b_next->b_iused > 0) {
3620
29.7k
                maybe_propagate_location(b->b_next, 0, prev_location);
3621
29.7k
            }
3622
29.7k
        }
3623
81.4k
        if (is_jump(last)) {
3624
39.7k
            basicblock *target = last->i_target;
3625
39.7k
            while (target->b_iused == 0 && target->b_predecessors == 1) {
3626
2
                target = target->b_next;
3627
2
            }
3628
39.7k
            if (target->b_predecessors == 1) {
3629
18.3k
                maybe_propagate_location(target, 0, prev_location);
3630
18.3k
            }
3631
39.7k
        }
3632
81.4k
    }
3633
13.9k
}
3634
3635
static int
3636
resolve_line_numbers(cfg_builder *g, int firstlineno)
3637
13.9k
{
3638
13.9k
    RETURN_IF_ERROR(duplicate_exits_without_lineno(g));
3639
13.9k
    propagate_line_numbers(g->g_entryblock);
3640
13.9k
    return SUCCESS;
3641
13.9k
}
3642
3643
int
3644
_PyCfg_OptimizeCodeUnit(cfg_builder *g, PyObject *consts, PyObject *const_cache,
3645
                        int nlocals, int nparams, int firstlineno)
3646
6.99k
{
3647
6.99k
    assert(cfg_builder_check(g));
3648
    /** Preprocessing **/
3649
    /* Map labels to targets and mark exception handlers */
3650
6.99k
    RETURN_IF_ERROR(translate_jump_labels_to_targets(g->g_entryblock));
3651
6.99k
    RETURN_IF_ERROR(mark_except_handlers(g->g_entryblock));
3652
6.99k
    RETURN_IF_ERROR(label_exception_targets(g->g_entryblock));
3653
3654
    /** Optimization **/
3655
6.99k
    RETURN_IF_ERROR(optimize_cfg(g, consts, const_cache, firstlineno));
3656
6.99k
    RETURN_IF_ERROR(remove_unused_consts(g->g_entryblock, consts));
3657
6.99k
    RETURN_IF_ERROR(
3658
6.99k
        add_checks_for_loads_of_uninitialized_variables(
3659
6.99k
            g->g_entryblock, nlocals, nparams));
3660
6.99k
    RETURN_IF_ERROR(insert_superinstructions(g));
3661
3662
6.99k
    RETURN_IF_ERROR(push_cold_blocks_to_end(g));
3663
6.99k
    RETURN_IF_ERROR(resolve_line_numbers(g, firstlineno));
3664
    // temporarily remove assert. See https://github.com/python/cpython/issues/125845
3665
    // assert(all_exits_have_lineno(g->g_entryblock));
3666
6.99k
    return SUCCESS;
3667
6.99k
}
3668
3669
static int *
3670
build_cellfixedoffsets(_PyCompile_CodeUnitMetadata *umd)
3671
6.99k
{
3672
6.99k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
3673
6.99k
    int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
3674
6.99k
    int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
3675
3676
6.99k
    int noffsets = ncellvars + nfreevars;
3677
6.99k
    int *fixed = PyMem_New(int, noffsets);
3678
6.99k
    if (fixed == NULL) {
3679
0
        PyErr_NoMemory();
3680
0
        return NULL;
3681
0
    }
3682
9.61k
    for (int i = 0; i < noffsets; i++) {
3683
2.62k
        fixed[i] = nlocals + i;
3684
2.62k
    }
3685
3686
6.99k
    PyObject *varname, *cellindex;
3687
6.99k
    Py_ssize_t pos = 0;
3688
8.39k
    while (PyDict_Next(umd->u_cellvars, &pos, &varname, &cellindex)) {
3689
1.40k
        PyObject *varindex;
3690
1.40k
        if (PyDict_GetItemRef(umd->u_varnames, varname, &varindex) < 0) {
3691
0
            goto error;
3692
0
        }
3693
1.40k
        if (varindex == NULL) {
3694
983
            continue;
3695
983
        }
3696
3697
423
        int argoffset = PyLong_AsInt(varindex);
3698
423
        Py_DECREF(varindex);
3699
423
        if (argoffset == -1 && PyErr_Occurred()) {
3700
0
            goto error;
3701
0
        }
3702
3703
423
        int oldindex = PyLong_AsInt(cellindex);
3704
423
        if (oldindex == -1 && PyErr_Occurred()) {
3705
0
            goto error;
3706
0
        }
3707
423
        fixed[oldindex] = argoffset;
3708
423
    }
3709
6.99k
    return fixed;
3710
3711
0
error:
3712
0
    PyMem_Free(fixed);
3713
0
    return NULL;
3714
6.99k
}
3715
3716
#define IS_GENERATOR(CF) \
3717
6.99k
    ((CF) & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR))
3718
3719
static int
3720
insert_prefix_instructions(_PyCompile_CodeUnitMetadata *umd, basicblock *entryblock,
3721
                           int *fixed, int nfreevars, int code_flags)
3722
6.99k
{
3723
6.99k
    assert(umd->u_firstlineno > 0);
3724
3725
    /* Add the generator prefix instructions. */
3726
6.99k
    if (IS_GENERATOR(code_flags)) {
3727
        /* Note that RETURN_GENERATOR + POP_TOP have a net stack effect
3728
         * of 0. This is because RETURN_GENERATOR pushes an element
3729
         * with _PyFrame_StackPush before switching stacks.
3730
         */
3731
3732
385
        location loc = LOCATION(umd->u_firstlineno, umd->u_firstlineno, -1, -1);
3733
385
        cfg_instr make_gen = {
3734
385
            .i_opcode = RETURN_GENERATOR,
3735
385
            .i_oparg = 0,
3736
385
            .i_loc = loc,
3737
385
            .i_target = NULL,
3738
385
            .i_except = NULL,
3739
385
        };
3740
385
        RETURN_IF_ERROR(basicblock_insert_instruction(entryblock, 0, &make_gen));
3741
385
        cfg_instr pop_top = {
3742
385
            .i_opcode = POP_TOP,
3743
385
            .i_oparg = 0,
3744
385
            .i_loc = loc,
3745
385
            .i_target = NULL,
3746
385
            .i_except = NULL,
3747
385
        };
3748
385
        RETURN_IF_ERROR(basicblock_insert_instruction(entryblock, 1, &pop_top));
3749
385
    }
3750
3751
    /* Set up cells for any variable that escapes, to be put in a closure. */
3752
6.99k
    const int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
3753
6.99k
    if (ncellvars) {
3754
        // umd->u_cellvars has the cells out of order so we sort them
3755
        // before adding the MAKE_CELL instructions.  Note that we
3756
        // adjust for arg cells, which come first.
3757
875
        const int nvars = ncellvars + (int)PyDict_GET_SIZE(umd->u_varnames);
3758
875
        int *sorted = PyMem_RawCalloc(nvars, sizeof(int));
3759
875
        if (sorted == NULL) {
3760
0
            PyErr_NoMemory();
3761
0
            return ERROR;
3762
0
        }
3763
2.28k
        for (int i = 0; i < ncellvars; i++) {
3764
1.40k
            sorted[fixed[i]] = i + 1;
3765
1.40k
        }
3766
2.97k
        for (int i = 0, ncellsused = 0; ncellsused < ncellvars; i++) {
3767
2.10k
            int oldindex = sorted[i] - 1;
3768
2.10k
            if (oldindex == -1) {
3769
696
                continue;
3770
696
            }
3771
1.40k
            cfg_instr make_cell = {
3772
1.40k
                .i_opcode = MAKE_CELL,
3773
                // This will get fixed in offset_derefs().
3774
1.40k
                .i_oparg = oldindex,
3775
1.40k
                .i_loc = NO_LOCATION,
3776
1.40k
                .i_target = NULL,
3777
1.40k
                .i_except = NULL,
3778
1.40k
            };
3779
1.40k
            if (basicblock_insert_instruction(entryblock, ncellsused, &make_cell) < 0) {
3780
0
                PyMem_RawFree(sorted);
3781
0
                return ERROR;
3782
0
            }
3783
1.40k
            ncellsused += 1;
3784
1.40k
        }
3785
875
        PyMem_RawFree(sorted);
3786
875
    }
3787
3788
6.99k
    if (nfreevars) {
3789
621
        cfg_instr copy_frees = {
3790
621
            .i_opcode = COPY_FREE_VARS,
3791
621
            .i_oparg = nfreevars,
3792
621
            .i_loc = NO_LOCATION,
3793
621
            .i_target = NULL,
3794
621
            .i_except = NULL,
3795
621
        };
3796
621
        RETURN_IF_ERROR(basicblock_insert_instruction(entryblock, 0, &copy_frees));
3797
621
    }
3798
3799
6.99k
    return SUCCESS;
3800
6.99k
}
3801
3802
static int
3803
fix_cell_offsets(_PyCompile_CodeUnitMetadata *umd, basicblock *entryblock, int *fixedmap)
3804
6.99k
{
3805
6.99k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
3806
6.99k
    int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
3807
6.99k
    int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
3808
6.99k
    int noffsets = ncellvars + nfreevars;
3809
3810
    // First deal with duplicates (arg cells).
3811
6.99k
    int numdropped = 0;
3812
9.61k
    for (int i = 0; i < noffsets ; i++) {
3813
2.62k
        if (fixedmap[i] == i + nlocals) {
3814
2.20k
            fixedmap[i] -= numdropped;
3815
2.20k
        }
3816
423
        else {
3817
            // It was a duplicate (cell/arg).
3818
423
            numdropped += 1;
3819
423
        }
3820
2.62k
    }
3821
3822
    // Then update offsets, either relative to locals or by cell2arg.
3823
55.3k
    for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
3824
393k
        for (int i = 0; i < b->b_iused; i++) {
3825
345k
            cfg_instr *inst = &b->b_instr[i];
3826
            // This is called before extended args are generated.
3827
345k
            assert(inst->i_opcode != EXTENDED_ARG);
3828
345k
            int oldoffset = inst->i_oparg;
3829
345k
            switch(inst->i_opcode) {
3830
1.40k
                case MAKE_CELL:
3831
3.36k
                case LOAD_CLOSURE:
3832
6.01k
                case LOAD_DEREF:
3833
7.11k
                case STORE_DEREF:
3834
7.11k
                case DELETE_DEREF:
3835
7.11k
                case LOAD_FROM_DICT_OR_DEREF:
3836
7.11k
                    assert(oldoffset >= 0);
3837
7.11k
                    assert(oldoffset < noffsets);
3838
7.11k
                    assert(fixedmap[oldoffset] >= 0);
3839
7.11k
                    inst->i_oparg = fixedmap[oldoffset];
3840
345k
            }
3841
345k
        }
3842
48.3k
    }
3843
3844
6.99k
    return numdropped;
3845
6.99k
}
3846
3847
static int
3848
prepare_localsplus(_PyCompile_CodeUnitMetadata *umd, cfg_builder *g, int code_flags)
3849
6.99k
{
3850
6.99k
    assert(PyDict_GET_SIZE(umd->u_varnames) < INT_MAX);
3851
6.99k
    assert(PyDict_GET_SIZE(umd->u_cellvars) < INT_MAX);
3852
6.99k
    assert(PyDict_GET_SIZE(umd->u_freevars) < INT_MAX);
3853
6.99k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
3854
6.99k
    int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
3855
6.99k
    int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
3856
6.99k
    assert(INT_MAX - nlocals - ncellvars > 0);
3857
6.99k
    assert(INT_MAX - nlocals - ncellvars - nfreevars > 0);
3858
6.99k
    int nlocalsplus = nlocals + ncellvars + nfreevars;
3859
6.99k
    int* cellfixedoffsets = build_cellfixedoffsets(umd);
3860
6.99k
    if (cellfixedoffsets == NULL) {
3861
0
        return ERROR;
3862
0
    }
3863
3864
    // This must be called before fix_cell_offsets().
3865
6.99k
    if (insert_prefix_instructions(umd, g->g_entryblock, cellfixedoffsets, nfreevars, code_flags)) {
3866
0
        PyMem_Free(cellfixedoffsets);
3867
0
        return ERROR;
3868
0
    }
3869
3870
6.99k
    int numdropped = fix_cell_offsets(umd, g->g_entryblock, cellfixedoffsets);
3871
6.99k
    PyMem_Free(cellfixedoffsets);  // At this point we're done with it.
3872
6.99k
    cellfixedoffsets = NULL;
3873
6.99k
    if (numdropped < 0) {
3874
0
        return ERROR;
3875
0
    }
3876
3877
6.99k
    nlocalsplus -= numdropped;
3878
6.99k
    return nlocalsplus;
3879
6.99k
}
3880
3881
cfg_builder *
3882
_PyCfg_FromInstructionSequence(_PyInstructionSequence *seq)
3883
6.99k
{
3884
6.99k
    if (_PyInstructionSequence_ApplyLabelMap(seq) < 0) {
3885
0
        return NULL;
3886
0
    }
3887
6.99k
    cfg_builder *g = _PyCfgBuilder_New();
3888
6.99k
    if (g == NULL) {
3889
0
        return NULL;
3890
0
    }
3891
398k
    for (int i = 0; i < seq->s_used; i++) {
3892
391k
        seq->s_instrs[i].i_target = 0;
3893
391k
    }
3894
398k
    for (int i = 0; i < seq->s_used; i++) {
3895
391k
        _PyInstruction *instr = &seq->s_instrs[i];
3896
391k
        if (HAS_TARGET(instr->i_opcode)) {
3897
25.1k
            assert(instr->i_oparg >= 0 && instr->i_oparg < seq->s_used);
3898
25.1k
            seq->s_instrs[instr->i_oparg].i_target = 1;
3899
25.1k
        }
3900
391k
    }
3901
6.99k
    int offset = 0;
3902
398k
    for (int i = 0; i < seq->s_used; i++) {
3903
391k
        _PyInstruction *instr = &seq->s_instrs[i];
3904
391k
        if (instr->i_opcode == ANNOTATIONS_PLACEHOLDER) {
3905
367
            if (seq->s_annotations_code != NULL) {
3906
1
                assert(seq->s_annotations_code->s_labelmap_size == 0
3907
1
                    && seq->s_annotations_code->s_nested == NULL);
3908
4
                for (int j = 0; j < seq->s_annotations_code->s_used; j++) {
3909
3
                    _PyInstruction *ann_instr = &seq->s_annotations_code->s_instrs[j];
3910
3
                    assert(!HAS_TARGET(ann_instr->i_opcode));
3911
3
                    if (_PyCfgBuilder_Addop(g, ann_instr->i_opcode, ann_instr->i_oparg, ann_instr->i_loc) < 0) {
3912
0
                        goto error;
3913
0
                    }
3914
3
                }
3915
1
                offset += seq->s_annotations_code->s_used - 1;
3916
1
            }
3917
366
            else {
3918
366
                offset -= 1;
3919
366
            }
3920
367
            continue;
3921
367
        }
3922
390k
        if (instr->i_target) {
3923
20.3k
            jump_target_label lbl_ = {i + offset};
3924
20.3k
            if (_PyCfgBuilder_UseLabel(g, lbl_) < 0) {
3925
0
                goto error;
3926
0
            }
3927
20.3k
        }
3928
390k
        int opcode = instr->i_opcode;
3929
390k
        int oparg = instr->i_oparg;
3930
390k
        if (HAS_TARGET(opcode)) {
3931
25.1k
            oparg += offset;
3932
25.1k
        }
3933
390k
        if (_PyCfgBuilder_Addop(g, opcode, oparg, instr->i_loc) < 0) {
3934
0
            goto error;
3935
0
        }
3936
390k
    }
3937
6.99k
    if (_PyCfgBuilder_CheckSize(g) < 0) {
3938
0
        goto error;
3939
0
    }
3940
6.99k
    return g;
3941
0
error:
3942
0
    _PyCfgBuilder_Free(g);
3943
0
    return NULL;
3944
6.99k
}
3945
3946
int
3947
_PyCfg_ToInstructionSequence(cfg_builder *g, _PyInstructionSequence *seq)
3948
6.99k
{
3949
6.99k
    int lbl = 0;
3950
56.1k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
3951
49.1k
        b->b_label = (jump_target_label){lbl};
3952
49.1k
        lbl += 1;
3953
49.1k
    }
3954
56.1k
    for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
3955
49.1k
        RETURN_IF_ERROR(_PyInstructionSequence_UseLabel(seq, b->b_label.id));
3956
405k
        for (int i = 0; i < b->b_iused; i++) {
3957
356k
            cfg_instr *instr = &b->b_instr[i];
3958
356k
            if (HAS_TARGET(instr->i_opcode)) {
3959
                /* Set oparg to the label id (it will later be mapped to an offset) */
3960
19.9k
                instr->i_oparg = instr->i_target->b_label.id;
3961
19.9k
            }
3962
356k
            RETURN_IF_ERROR(
3963
356k
                _PyInstructionSequence_Addop(
3964
356k
                    seq, instr->i_opcode, instr->i_oparg, instr->i_loc));
3965
3966
356k
            _PyExceptHandlerInfo *hi = &seq->s_instrs[seq->s_used-1].i_except_handler_info;
3967
356k
            if (instr->i_except != NULL) {
3968
45.3k
                hi->h_label = instr->i_except->b_label.id;
3969
45.3k
                hi->h_startdepth = instr->i_except->b_startdepth;
3970
45.3k
                hi->h_preserve_lasti = instr->i_except->b_preserve_lasti;
3971
45.3k
            }
3972
310k
            else {
3973
310k
                hi->h_label = -1;
3974
310k
            }
3975
356k
        }
3976
49.1k
    }
3977
6.99k
    if (_PyInstructionSequence_ApplyLabelMap(seq) < 0) {
3978
0
        return ERROR;
3979
0
    }
3980
6.99k
    return SUCCESS;
3981
6.99k
}
3982
3983
3984
int
3985
_PyCfg_OptimizedCfgToInstructionSequence(cfg_builder *g,
3986
                                     _PyCompile_CodeUnitMetadata *umd, int code_flags,
3987
                                     int *stackdepth, int *nlocalsplus,
3988
                                     _PyInstructionSequence *seq)
3989
6.99k
{
3990
6.99k
    RETURN_IF_ERROR(convert_pseudo_conditional_jumps(g));
3991
3992
6.99k
    *stackdepth = calculate_stackdepth(g);
3993
6.99k
    if (*stackdepth < 0) {
3994
0
        return ERROR;
3995
0
    }
3996
3997
    /* prepare_localsplus adds instructions for generators that push
3998
     * and pop an item on the stack. This assertion makes sure there
3999
     * is space on the stack for that.
4000
     * It should always be true, because a generator must have at
4001
     * least one expression or call to INTRINSIC_STOPITERATION_ERROR,
4002
     * which requires stackspace.
4003
     */
4004
6.99k
    assert(!(IS_GENERATOR(code_flags) && *stackdepth == 0));
4005
4006
6.99k
    *nlocalsplus = prepare_localsplus(umd, g, code_flags);
4007
6.99k
    if (*nlocalsplus < 0) {
4008
0
        return ERROR;
4009
0
    }
4010
4011
6.99k
    RETURN_IF_ERROR(convert_pseudo_ops(g));
4012
4013
    /* Order of basic blocks must have been determined by now */
4014
4015
6.99k
    RETURN_IF_ERROR(normalize_jumps(g));
4016
6.99k
    assert(no_redundant_jumps(g));
4017
4018
    /* Can't modify the bytecode after inserting instructions that produce
4019
     * borrowed references.
4020
     */
4021
6.99k
    RETURN_IF_ERROR(optimize_load_fast(g));
4022
4023
    /* Can't modify the bytecode after computing jump offsets. */
4024
6.99k
    if (_PyCfg_ToInstructionSequence(g, seq) < 0) {
4025
0
        return ERROR;
4026
0
    }
4027
4028
6.99k
    return SUCCESS;
4029
6.99k
}
4030
4031
/* This is used by _PyCompile_Assemble to fill in the jump and exception
4032
 * targets in a synthetic CFG (which is not the output of the builtin compiler).
4033
 */
4034
int
4035
_PyCfg_JumpLabelsToTargets(cfg_builder *g)
4036
0
{
4037
0
    RETURN_IF_ERROR(translate_jump_labels_to_targets(g->g_entryblock));
4038
0
    RETURN_IF_ERROR(label_exception_targets(g->g_entryblock));
4039
0
    return SUCCESS;
4040
0
}
4041
4042
/* Exported API functions */
4043
4044
int
4045
PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
4046
0
{
4047
0
    stack_effects effs;
4048
0
    if (get_stack_effects(opcode, oparg, jump, &effs) < 0) {
4049
0
        return PY_INVALID_STACK_EFFECT;
4050
0
    }
4051
0
    return effs.net;
4052
0
}
4053
4054
int
4055
PyCompile_OpcodeStackEffect(int opcode, int oparg)
4056
132
{
4057
132
    stack_effects effs;
4058
132
    if (get_stack_effects(opcode, oparg, -1, &effs) < 0) {
4059
0
        return PY_INVALID_STACK_EFFECT;
4060
0
    }
4061
132
    return effs.net;
4062
132
}
4063
4064
/* Access to compiler optimizations for unit tests.
4065
4066
 * _PyCompile_OptimizeCfg takes an instruction list, constructs
4067
 * a CFG, optimizes it and converts back to an instruction list.
4068
 */
4069
4070
static PyObject *
4071
cfg_to_instruction_sequence(cfg_builder *g)
4072
0
{
4073
0
    _PyInstructionSequence *seq = (_PyInstructionSequence *)_PyInstructionSequence_New();
4074
0
    if (seq == NULL) {
4075
0
        return NULL;
4076
0
    }
4077
0
    if (_PyCfg_ToInstructionSequence(g, seq) < 0) {
4078
0
        PyInstructionSequence_Fini(seq);
4079
0
        return NULL;
4080
0
    }
4081
0
    return (PyObject*)seq;
4082
0
}
4083
4084
PyObject *
4085
_PyCompile_OptimizeCfg(PyObject *seq, PyObject *consts, int nlocals)
4086
0
{
4087
0
    if (!_PyInstructionSequence_Check(seq)) {
4088
0
        PyErr_SetString(PyExc_ValueError, "expected an instruction sequence");
4089
0
        return NULL;
4090
0
    }
4091
0
    PyObject *const_cache = PyDict_New();
4092
0
    if (const_cache == NULL) {
4093
0
        return NULL;
4094
0
    }
4095
4096
0
    PyObject *res = NULL;
4097
0
    cfg_builder *g = _PyCfg_FromInstructionSequence((_PyInstructionSequence*)seq);
4098
0
    if (g == NULL) {
4099
0
        goto error;
4100
0
    }
4101
0
    int nparams = 0, firstlineno = 1;
4102
0
    if (_PyCfg_OptimizeCodeUnit(g, consts, const_cache, nlocals,
4103
0
                                nparams, firstlineno) < 0) {
4104
0
        goto error;
4105
0
    }
4106
4107
0
    if (calculate_stackdepth(g) == ERROR) {
4108
0
        goto error;
4109
0
    }
4110
4111
0
    if (optimize_load_fast(g) != SUCCESS) {
4112
0
        goto error;
4113
0
    }
4114
4115
0
    res = cfg_to_instruction_sequence(g);
4116
0
error:
4117
0
    Py_DECREF(const_cache);
4118
0
    _PyCfgBuilder_Free(g);
4119
0
    return res;
4120
0
}