Coverage Report

Created: 2026-01-17 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/optimizer.c
Line
Count
Source
1
#include "Python.h"
2
3
#ifdef _Py_TIER2
4
5
#include "opcode.h"
6
#include "pycore_interp.h"
7
#include "pycore_backoff.h"
8
#include "pycore_bitutils.h"        // _Py_popcount32()
9
#include "pycore_ceval.h"       // _Py_set_eval_breaker_bit
10
#include "pycore_code.h"            // _Py_GetBaseCodeUnit
11
#include "pycore_function.h"        // _PyFunction_LookupByVersion()
12
#include "pycore_interpframe.h"
13
#include "pycore_object.h"          // _PyObject_GC_UNTRACK()
14
#include "pycore_opcode_metadata.h" // _PyOpcode_OpName[]
15
#include "pycore_opcode_utils.h"  // MAX_REAL_OPCODE
16
#include "pycore_optimizer.h"     // _Py_uop_analyze_and_optimize()
17
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
18
#include "pycore_tuple.h"         // _PyTuple_FromArraySteal
19
#include "pycore_unicodeobject.h" // _PyUnicode_FromASCII
20
#include "pycore_uop_ids.h"
21
#include "pycore_jit.h"
22
#include <stdbool.h>
23
#include <stdint.h>
24
#include <stddef.h>
25
26
#define NEED_OPCODE_METADATA
27
#include "pycore_uop_metadata.h" // Uop tables
28
#undef NEED_OPCODE_METADATA
29
30
#define MAX_EXECUTORS_SIZE 256
31
32
// Trace too short, no progress:
33
// _START_EXECUTOR
34
// _MAKE_WARM
35
// _CHECK_VALIDITY
36
// _SET_IP
37
// is 4-5 instructions.
38
#define CODE_SIZE_NO_PROGRESS 5
39
// We start with _START_EXECUTOR, _MAKE_WARM
40
#define CODE_SIZE_EMPTY 2
41
42
#define _PyExecutorObject_CAST(op)  ((_PyExecutorObject *)(op))
43
44
static bool
45
has_space_for_executor(PyCodeObject *code, _Py_CODEUNIT *instr)
46
{
47
    if (code == (PyCodeObject *)&_Py_InitCleanup) {
48
        return false;
49
    }
50
    if (instr->op.code == ENTER_EXECUTOR) {
51
        return true;
52
    }
53
    if (code->co_executors == NULL) {
54
        return true;
55
    }
56
    return code->co_executors->size < MAX_EXECUTORS_SIZE;
57
}
58
59
static int32_t
60
get_index_for_executor(PyCodeObject *code, _Py_CODEUNIT *instr)
61
{
62
    if (instr->op.code == ENTER_EXECUTOR) {
63
        return instr->op.arg;
64
    }
65
    _PyExecutorArray *old = code->co_executors;
66
    int size = 0;
67
    int capacity = 0;
68
    if (old != NULL) {
69
        size = old->size;
70
        capacity = old->capacity;
71
        assert(size < MAX_EXECUTORS_SIZE);
72
    }
73
    assert(size <= capacity);
74
    if (size == capacity) {
75
        /* Array is full. Grow array */
76
        int new_capacity = capacity ? capacity * 2 : 4;
77
        _PyExecutorArray *new = PyMem_Realloc(
78
            old,
79
            offsetof(_PyExecutorArray, executors) +
80
            new_capacity * sizeof(_PyExecutorObject *));
81
        if (new == NULL) {
82
            return -1;
83
        }
84
        new->capacity = new_capacity;
85
        new->size = size;
86
        code->co_executors = new;
87
    }
88
    assert(size < code->co_executors->capacity);
89
    return size;
90
}
91
92
static void
93
insert_executor(PyCodeObject *code, _Py_CODEUNIT *instr, int index, _PyExecutorObject *executor)
94
{
95
    Py_INCREF(executor);
96
    if (instr->op.code == ENTER_EXECUTOR) {
97
        assert(index == instr->op.arg);
98
        _Py_ExecutorDetach(code->co_executors->executors[index]);
99
    }
100
    else {
101
        assert(code->co_executors->size == index);
102
        assert(code->co_executors->capacity > index);
103
        code->co_executors->size++;
104
    }
105
    executor->vm_data.opcode = instr->op.code;
106
    executor->vm_data.oparg = instr->op.arg;
107
    executor->vm_data.code = code;
108
    executor->vm_data.index = (int)(instr - _PyCode_CODE(code));
109
    code->co_executors->executors[index] = executor;
110
    assert(index < MAX_EXECUTORS_SIZE);
111
    instr->op.code = ENTER_EXECUTOR;
112
    instr->op.arg = index;
113
}
114
115
static _PyExecutorObject *
116
make_executor_from_uops(_PyThreadStateImpl *tstate, _PyUOpInstruction *buffer, int length, const _PyBloomFilter *dependencies);
117
118
static int
119
uop_optimize(_PyInterpreterFrame *frame, PyThreadState *tstate,
120
             _PyExecutorObject **exec_ptr,
121
             bool progress_needed);
122
123
/* Returns 1 if optimized, 0 if not optimized, and -1 for an error.
124
 * If optimized, *executor_ptr contains a new reference to the executor
125
 */
126
// gh-137573: inlining this function causes stack overflows
127
Py_NO_INLINE int
128
_PyOptimizer_Optimize(
129
    _PyInterpreterFrame *frame, PyThreadState *tstate)
130
{
131
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
132
    int chain_depth = _tstate->jit_tracer_state->initial_state.chain_depth;
133
    PyInterpreterState *interp = _PyInterpreterState_GET();
134
    if (!interp->jit) {
135
        // gh-140936: It is possible that interp->jit will become false during
136
        // interpreter finalization. However, the specialized JUMP_BACKWARD_JIT
137
        // instruction may still be present. In this case, we should
138
        // return immediately without optimization.
139
        return 0;
140
    }
141
    _PyExecutorObject *prev_executor = _tstate->jit_tracer_state->initial_state.executor;
142
    if (prev_executor != NULL && !prev_executor->vm_data.valid) {
143
        // gh-143604: If we are a side exit executor and the original executor is no
144
        // longer valid, don't compile to prevent a reference leak.
145
        return 0;
146
    }
147
    assert(!interp->compiling);
148
    assert(_tstate->jit_tracer_state->initial_state.stack_depth >= 0);
149
#ifndef Py_GIL_DISABLED
150
    assert(_tstate->jit_tracer_state->initial_state.func != NULL);
151
    interp->compiling = true;
152
    // The first executor in a chain and the MAX_CHAIN_DEPTH'th executor *must*
153
    // make progress in order to avoid infinite loops or excessively-long
154
    // side-exit chains. We can only insert the executor into the bytecode if
155
    // this is true, since a deopt won't infinitely re-enter the executor:
156
    chain_depth %= MAX_CHAIN_DEPTH;
157
    bool progress_needed = chain_depth == 0;
158
    PyCodeObject *code = (PyCodeObject *)_tstate->jit_tracer_state->initial_state.code;
159
    _Py_CODEUNIT *start = _tstate->jit_tracer_state->initial_state.start_instr;
160
    if (progress_needed && !has_space_for_executor(code, start)) {
161
        interp->compiling = false;
162
        return 0;
163
    }
164
    // One of our dependencies while tracing was invalidated. Not worth compiling.
165
    if (!_tstate->jit_tracer_state->prev_state.dependencies_still_valid) {
166
        interp->compiling = false;
167
        return 0;
168
    }
169
    _PyExecutorObject *executor;
170
    int err = uop_optimize(frame, tstate, &executor, progress_needed);
171
    if (err <= 0) {
172
        interp->compiling = false;
173
        return err;
174
    }
175
    assert(executor != NULL);
176
    if (progress_needed) {
177
        int index = get_index_for_executor(code, start);
178
        if (index < 0) {
179
            /* Out of memory. Don't raise and assume that the
180
             * error will show up elsewhere.
181
             *
182
             * If an optimizer has already produced an executor,
183
             * it might get confused by the executor disappearing,
184
             * but there is not much we can do about that here. */
185
            Py_DECREF(executor);
186
            interp->compiling = false;
187
            return 0;
188
        }
189
        insert_executor(code, start, index, executor);
190
    }
191
    else {
192
        executor->vm_data.code = NULL;
193
    }
194
    executor->vm_data.chain_depth = chain_depth;
195
    assert(executor->vm_data.valid);
196
    _PyExitData *exit = _tstate->jit_tracer_state->initial_state.exit;
197
    if (exit != NULL && !progress_needed) {
198
        exit->executor = executor;
199
    }
200
    else {
201
        // An executor inserted into the code object now has a strong reference
202
        // to it from the code object. Thus, we don't need this reference anymore.
203
        Py_DECREF(executor);
204
    }
205
    interp->compiling = false;
206
    return 1;
207
#else
208
    return 0;
209
#endif
210
}
211
212
static _PyExecutorObject *
213
get_executor_lock_held(PyCodeObject *code, int offset)
214
{
215
    int code_len = (int)Py_SIZE(code);
216
    for (int i = 0 ; i < code_len;) {
217
        if (_PyCode_CODE(code)[i].op.code == ENTER_EXECUTOR && i*2 == offset) {
218
            int oparg = _PyCode_CODE(code)[i].op.arg;
219
            _PyExecutorObject *res = code->co_executors->executors[oparg];
220
            Py_INCREF(res);
221
            return res;
222
        }
223
        i += _PyInstruction_GetLength(code, i);
224
    }
225
    PyErr_SetString(PyExc_ValueError, "no executor at given byte offset");
226
    return NULL;
227
}
228
229
_PyExecutorObject *
230
_Py_GetExecutor(PyCodeObject *code, int offset)
231
{
232
    _PyExecutorObject *executor;
233
    Py_BEGIN_CRITICAL_SECTION(code);
234
    executor = get_executor_lock_held(code, offset);
235
    Py_END_CRITICAL_SECTION();
236
    return executor;
237
}
238
239
static PyObject *
240
is_valid(PyObject *self, PyObject *Py_UNUSED(ignored))
241
{
242
    return PyBool_FromLong(((_PyExecutorObject *)self)->vm_data.valid);
243
}
244
245
static PyObject *
246
get_opcode(PyObject *self, PyObject *Py_UNUSED(ignored))
247
{
248
    return PyLong_FromUnsignedLong(((_PyExecutorObject *)self)->vm_data.opcode);
249
}
250
251
static PyObject *
252
get_oparg(PyObject *self, PyObject *Py_UNUSED(ignored))
253
{
254
    return PyLong_FromUnsignedLong(((_PyExecutorObject *)self)->vm_data.oparg);
255
}
256
257
///////////////////// Experimental UOp Optimizer /////////////////////
258
259
static int executor_clear(PyObject *executor);
260
261
void
262
_PyExecutor_Free(_PyExecutorObject *self)
263
{
264
#ifdef _Py_JIT
265
    _PyJIT_Free(self);
266
#endif
267
    PyObject_GC_Del(self);
268
}
269
270
static void executor_invalidate(PyObject *op);
271
272
static void
273
executor_clear_exits(_PyExecutorObject *executor)
274
{
275
    _PyExecutorObject *cold = _PyExecutor_GetColdExecutor();
276
    _PyExecutorObject *cold_dynamic = _PyExecutor_GetColdDynamicExecutor();
277
    for (uint32_t i = 0; i < executor->exit_count; i++) {
278
        _PyExitData *exit = &executor->exits[i];
279
        exit->temperature = initial_unreachable_backoff_counter();
280
        _PyExecutorObject *old = executor->exits[i].executor;
281
        exit->executor = exit->is_dynamic ? cold_dynamic : cold;
282
        Py_DECREF(old);
283
    }
284
}
285
286
287
void
288
_Py_ClearExecutorDeletionList(PyInterpreterState *interp)
289
{
290
    if (interp->executor_deletion_list_head == NULL) {
291
        return;
292
    }
293
    _PyRuntimeState *runtime = &_PyRuntime;
294
    HEAD_LOCK(runtime);
295
    PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
296
    while (ts) {
297
        _PyExecutorObject *current = (_PyExecutorObject *)ts->current_executor;
298
        Py_XINCREF(current);
299
        ts = ts->next;
300
    }
301
    HEAD_UNLOCK(runtime);
302
    _PyExecutorObject *keep_list = NULL;
303
    do {
304
        _PyExecutorObject *exec = interp->executor_deletion_list_head;
305
        interp->executor_deletion_list_head = exec->vm_data.links.next;
306
        if (Py_REFCNT(exec) == 0) {
307
            _PyExecutor_Free(exec);
308
        } else {
309
            exec->vm_data.links.next = keep_list;
310
            keep_list = exec;
311
        }
312
    } while (interp->executor_deletion_list_head != NULL);
313
    interp->executor_deletion_list_head = keep_list;
314
    HEAD_LOCK(runtime);
315
    ts = PyInterpreterState_ThreadHead(interp);
316
    while (ts) {
317
        _PyExecutorObject *current = (_PyExecutorObject *)ts->current_executor;
318
        if (current != NULL) {
319
            Py_DECREF((PyObject *)current);
320
        }
321
        ts = ts->next;
322
    }
323
    HEAD_UNLOCK(runtime);
324
}
325
326
static void
327
add_to_pending_deletion_list(_PyExecutorObject *self)
328
{
329
    if (self->vm_data.pending_deletion) {
330
        return;
331
    }
332
    self->vm_data.pending_deletion = 1;
333
    PyInterpreterState *interp = PyInterpreterState_Get();
334
    self->vm_data.links.previous = NULL;
335
    self->vm_data.links.next = interp->executor_deletion_list_head;
336
    interp->executor_deletion_list_head = self;
337
}
338
339
static void
340
uop_dealloc(PyObject *op) {
341
    _PyExecutorObject *self = _PyExecutorObject_CAST(op);
342
    executor_invalidate(op);
343
    assert(self->vm_data.code == NULL);
344
    add_to_pending_deletion_list(self);
345
}
346
347
const char *
348
_PyUOpName(int index)
349
{
350
    if (index < 0 || index > MAX_UOP_REGS_ID) {
351
        return NULL;
352
    }
353
    return _PyOpcode_uop_name[index];
354
}
355
356
#ifdef Py_DEBUG
357
void
358
_PyUOpPrint(const _PyUOpInstruction *uop)
359
{
360
    const char *name = _PyUOpName(uop->opcode);
361
    if (name == NULL) {
362
        printf("<uop %d>", uop->opcode);
363
    }
364
    else {
365
        printf("%s", name);
366
    }
367
    switch(uop->format) {
368
        case UOP_FORMAT_TARGET:
369
            printf(" (%d, target=%d, operand0=%#" PRIx64 ", operand1=%#" PRIx64,
370
                uop->oparg,
371
                uop->target,
372
                (uint64_t)uop->operand0,
373
                (uint64_t)uop->operand1);
374
            break;
375
        case UOP_FORMAT_JUMP:
376
            printf(" (%d, jump_target=%d, operand0=%#" PRIx64 ", operand1=%#" PRIx64,
377
                uop->oparg,
378
                uop->jump_target,
379
                (uint64_t)uop->operand0,
380
                (uint64_t)uop->operand1);
381
            break;
382
        default:
383
            printf(" (%d, Unknown format)", uop->oparg);
384
    }
385
    if (_PyUop_Flags[_PyUop_Uncached[uop->opcode]] & HAS_ERROR_FLAG) {
386
        printf(", error_target=%d", uop->error_target);
387
    }
388
389
    printf(")");
390
}
391
#endif
392
393
static Py_ssize_t
394
uop_len(PyObject *op)
395
{
396
    _PyExecutorObject *self = _PyExecutorObject_CAST(op);
397
    return self->code_size;
398
}
399
400
static PyObject *
401
uop_item(PyObject *op, Py_ssize_t index)
402
{
403
    _PyExecutorObject *self = _PyExecutorObject_CAST(op);
404
    Py_ssize_t len = uop_len(op);
405
    if (index < 0 || index >= len) {
406
        PyErr_SetNone(PyExc_IndexError);
407
        return NULL;
408
    }
409
    int opcode = self->trace[index].opcode;
410
    int base_opcode = _PyUop_Uncached[opcode];
411
    const char *name = _PyUOpName(base_opcode);
412
    if (name == NULL) {
413
        name = "<nil>";
414
    }
415
    PyObject *oname = _PyUnicode_FromASCII(name, strlen(name));
416
    if (oname == NULL) {
417
        return NULL;
418
    }
419
    PyObject *oparg = PyLong_FromUnsignedLong(self->trace[index].oparg);
420
    if (oparg == NULL) {
421
        Py_DECREF(oname);
422
        return NULL;
423
    }
424
    PyObject *target = PyLong_FromUnsignedLong(self->trace[index].target);
425
    if (target == NULL) {
426
        Py_DECREF(oparg);
427
        Py_DECREF(oname);
428
        return NULL;
429
    }
430
    PyObject *operand = PyLong_FromUnsignedLongLong(self->trace[index].operand0);
431
    if (operand == NULL) {
432
        Py_DECREF(target);
433
        Py_DECREF(oparg);
434
        Py_DECREF(oname);
435
        return NULL;
436
    }
437
    PyObject *args[4] = { oname, oparg, target, operand };
438
    return _PyTuple_FromArraySteal(args, 4);
439
}
440
441
PySequenceMethods uop_as_sequence = {
442
    .sq_length = uop_len,
443
    .sq_item = uop_item,
444
};
445
446
static int
447
executor_traverse(PyObject *o, visitproc visit, void *arg)
448
{
449
    _PyExecutorObject *executor = _PyExecutorObject_CAST(o);
450
    for (uint32_t i = 0; i < executor->exit_count; i++) {
451
        Py_VISIT(executor->exits[i].executor);
452
    }
453
    return 0;
454
}
455
456
static PyObject *
457
get_jit_code(PyObject *self, PyObject *Py_UNUSED(ignored))
458
{
459
#ifndef _Py_JIT
460
    PyErr_SetString(PyExc_RuntimeError, "JIT support not enabled.");
461
    return NULL;
462
#else
463
    _PyExecutorObject *executor = _PyExecutorObject_CAST(self);
464
    if (executor->jit_code == NULL || executor->jit_size == 0) {
465
        Py_RETURN_NONE;
466
    }
467
    return PyBytes_FromStringAndSize(executor->jit_code, executor->jit_size);
468
#endif
469
}
470
471
static PyMethodDef uop_executor_methods[] = {
472
    { "is_valid", is_valid, METH_NOARGS, NULL },
473
    { "get_jit_code", get_jit_code, METH_NOARGS, NULL},
474
    { "get_opcode", get_opcode, METH_NOARGS, NULL },
475
    { "get_oparg", get_oparg, METH_NOARGS, NULL },
476
    { NULL, NULL },
477
};
478
479
static int
480
executor_is_gc(PyObject *o)
481
{
482
    return !_Py_IsImmortal(o);
483
}
484
485
PyTypeObject _PyUOpExecutor_Type = {
486
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
487
    .tp_name = "uop_executor",
488
    .tp_basicsize = offsetof(_PyExecutorObject, exits),
489
    .tp_itemsize = 1,
490
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC,
491
    .tp_dealloc = uop_dealloc,
492
    .tp_as_sequence = &uop_as_sequence,
493
    .tp_methods = uop_executor_methods,
494
    .tp_traverse = executor_traverse,
495
    .tp_clear = executor_clear,
496
    .tp_is_gc = executor_is_gc,
497
};
498
499
/* TO DO -- Generate these tables */
500
static const uint16_t
501
_PyUOp_Replacements[MAX_UOP_ID + 1] = {
502
    [_ITER_JUMP_RANGE] = _GUARD_NOT_EXHAUSTED_RANGE,
503
    [_ITER_JUMP_LIST] = _GUARD_NOT_EXHAUSTED_LIST,
504
    [_ITER_JUMP_TUPLE] = _GUARD_NOT_EXHAUSTED_TUPLE,
505
    [_FOR_ITER] = _FOR_ITER_TIER_TWO,
506
    [_ITER_NEXT_LIST] = _ITER_NEXT_LIST_TIER_TWO,
507
    [_CHECK_PERIODIC_AT_END] = _TIER2_RESUME_CHECK,
508
};
509
510
static const uint8_t
511
is_for_iter_test[MAX_UOP_ID + 1] = {
512
    [_GUARD_NOT_EXHAUSTED_RANGE] = 1,
513
    [_GUARD_NOT_EXHAUSTED_LIST] = 1,
514
    [_GUARD_NOT_EXHAUSTED_TUPLE] = 1,
515
    [_FOR_ITER_TIER_TWO] = 1,
516
};
517
518
static const uint16_t
519
BRANCH_TO_GUARD[4][2] = {
520
    [POP_JUMP_IF_FALSE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_TRUE_POP,
521
    [POP_JUMP_IF_FALSE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_FALSE_POP,
522
    [POP_JUMP_IF_TRUE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_FALSE_POP,
523
    [POP_JUMP_IF_TRUE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_TRUE_POP,
524
    [POP_JUMP_IF_NONE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_NOT_NONE_POP,
525
    [POP_JUMP_IF_NONE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_NONE_POP,
526
    [POP_JUMP_IF_NOT_NONE - POP_JUMP_IF_FALSE][0] = _GUARD_IS_NONE_POP,
527
    [POP_JUMP_IF_NOT_NONE - POP_JUMP_IF_FALSE][1] = _GUARD_IS_NOT_NONE_POP,
528
};
529
530
static const uint16_t
531
guard_ip_uop[MAX_UOP_ID + 1] = {
532
    [_PUSH_FRAME] = _GUARD_IP__PUSH_FRAME,
533
    [_RETURN_GENERATOR] = _GUARD_IP_RETURN_GENERATOR,
534
    [_RETURN_VALUE] = _GUARD_IP_RETURN_VALUE,
535
    [_YIELD_VALUE] = _GUARD_IP_YIELD_VALUE,
536
};
537
538
539
#define CONFIDENCE_RANGE 1000
540
#define CONFIDENCE_CUTOFF 333
541
542
#ifdef Py_DEBUG
543
#define DPRINTF(level, ...) \
544
    if (lltrace >= (level)) { printf(__VA_ARGS__); }
545
#else
546
#define DPRINTF(level, ...)
547
#endif
548
549
550
static inline int
551
add_to_trace(
552
    _PyUOpInstruction *trace,
553
    int trace_length,
554
    uint16_t opcode,
555
    uint16_t oparg,
556
    uint64_t operand,
557
    uint32_t target)
558
{
559
    trace[trace_length].opcode = opcode;
560
    trace[trace_length].format = UOP_FORMAT_TARGET;
561
    trace[trace_length].target = target;
562
    trace[trace_length].oparg = oparg;
563
    trace[trace_length].operand0 = operand;
564
#ifdef Py_STATS
565
    trace[trace_length].execution_count = 0;
566
#endif
567
    return trace_length + 1;
568
}
569
570
#ifdef Py_DEBUG
571
#define ADD_TO_TRACE(OPCODE, OPARG, OPERAND, TARGET) \
572
    assert(trace_length < max_length); \
573
    trace_length = add_to_trace(trace, trace_length, (OPCODE), (OPARG), (OPERAND), (TARGET)); \
574
    if (lltrace >= 2) { \
575
        printf("%4d ADD_TO_TRACE: ", trace_length); \
576
        _PyUOpPrint(&trace[trace_length-1]); \
577
        printf("\n"); \
578
    }
579
#else
580
#define ADD_TO_TRACE(OPCODE, OPARG, OPERAND, TARGET) \
581
    assert(trace_length < max_length); \
582
    trace_length = add_to_trace(trace, trace_length, (OPCODE), (OPARG), (OPERAND), (TARGET));
583
#endif
584
585
#define INSTR_IP(INSTR, CODE) \
586
    ((uint32_t)((INSTR) - ((_Py_CODEUNIT *)(CODE)->co_code_adaptive)))
587
588
// Reserve space for n uops
589
#define RESERVE_RAW(n, opname) \
590
    if (trace_length + (n) > max_length) { \
591
        DPRINTF(2, "No room for %s (need %d, got %d)\n", \
592
                (opname), (n), max_length - trace_length); \
593
        OPT_STAT_INC(trace_too_long); \
594
        goto full; \
595
    }
596
597
static int
598
is_terminator(const _PyUOpInstruction *uop)
599
{
600
    int opcode = _PyUop_Uncached[uop->opcode];
601
    return (
602
        opcode == _EXIT_TRACE ||
603
        opcode == _DEOPT ||
604
        opcode == _JUMP_TO_TOP ||
605
        opcode == _DYNAMIC_EXIT
606
    );
607
}
608
609
/* Returns 1 on success (added to trace), 0 on trace end.
610
 */
611
// gh-142543: inlining this function causes stack overflows
612
Py_NO_INLINE int
613
_PyJit_translate_single_bytecode_to_trace(
614
    PyThreadState *tstate,
615
    _PyInterpreterFrame *frame,
616
    _Py_CODEUNIT *next_instr,
617
    int stop_tracing_opcode)
618
{
619
620
#ifdef Py_DEBUG
621
    char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
622
    int lltrace = 0;
623
    if (python_lltrace != NULL && *python_lltrace >= '0') {
624
        lltrace = *python_lltrace - '0';  // TODO: Parse an int and all that
625
    }
626
#endif
627
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
628
    _PyJitTracerState *tracer = _tstate->jit_tracer_state;
629
    PyCodeObject *old_code = tracer->prev_state.instr_code;
630
    bool progress_needed = (tracer->initial_state.chain_depth % MAX_CHAIN_DEPTH) == 0;
631
    _PyBloomFilter *dependencies = &tracer->prev_state.dependencies;
632
    int trace_length = tracer->prev_state.code_curr_size;
633
    _PyUOpInstruction *trace = tracer->code_buffer;
634
    int max_length = tracer->prev_state.code_max_size;
635
636
    _Py_CODEUNIT *this_instr =  tracer->prev_state.instr;
637
    _Py_CODEUNIT *target_instr = this_instr;
638
    uint32_t target = 0;
639
640
    target = Py_IsNone((PyObject *)old_code)
641
        ? (uint32_t)(target_instr - _Py_INTERPRETER_TRAMPOLINE_INSTRUCTIONS_PTR)
642
        : INSTR_IP(target_instr, old_code);
643
644
    // Rewind EXTENDED_ARG so that we see the whole thing.
645
    // We must point to the first EXTENDED_ARG when deopting.
646
    int oparg = tracer->prev_state.instr_oparg;
647
    int opcode = this_instr->op.code;
648
    int rewind_oparg = oparg;
649
    while (rewind_oparg > 255) {
650
        rewind_oparg >>= 8;
651
        target--;
652
    }
653
654
    if (_PyOpcode_Caches[_PyOpcode_Deopt[opcode]] > 0) {
655
        uint16_t backoff = (this_instr + 1)->counter.value_and_backoff;
656
        // adaptive_counter_cooldown is a fresh specialization.
657
        // trigger_backoff_counter is what we set during tracing.
658
        // All tracing backoffs should be freshly specialized or untouched.
659
        // If not, that indicates a deopt during tracing, and
660
        // thus the "actual" instruction executed is not the one that is
661
        // in the instruction stream, but rather the deopt.
662
        // It's important we check for this, as some specializations might make
663
        // no progress (they can immediately deopt after specializing).
664
        // We do this to improve performance, as otherwise a compiled trace
665
        // will just deopt immediately.
666
        if (backoff != adaptive_counter_cooldown().value_and_backoff &&
667
            backoff != trigger_backoff_counter().value_and_backoff) {
668
            OPT_STAT_INC(trace_immediately_deopts);
669
            opcode = _PyOpcode_Deopt[opcode];
670
        }
671
    }
672
673
    int old_stack_level = tracer->prev_state.instr_stacklevel;
674
675
    // Strange control-flow
676
    bool has_dynamic_jump_taken = OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) &&
677
        (next_instr != this_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]]);
678
679
    /* Special case the first instruction,
680
    * so that we can guarantee forward progress */
681
    if (progress_needed && tracer->prev_state.code_curr_size < CODE_SIZE_NO_PROGRESS) {
682
        if (OPCODE_HAS_EXIT(opcode) || OPCODE_HAS_DEOPT(opcode)) {
683
            opcode = _PyOpcode_Deopt[opcode];
684
        }
685
        assert(!OPCODE_HAS_EXIT(opcode));
686
        assert(!OPCODE_HAS_DEOPT(opcode));
687
    }
688
689
    bool needs_guard_ip = OPCODE_HAS_NEEDS_GUARD_IP(opcode);
690
    if (has_dynamic_jump_taken && !needs_guard_ip) {
691
        DPRINTF(2, "Unsupported: dynamic jump taken %s\n", _PyOpcode_OpName[opcode]);
692
        goto unsupported;
693
    }
694
695
    int is_sys_tracing = (tstate->c_tracefunc != NULL) || (tstate->c_profilefunc != NULL);
696
    if (is_sys_tracing) {
697
        goto full;
698
    }
699
700
    if (stop_tracing_opcode == _DEOPT) {
701
        // gh-143183: It's important we rewind to the last known proper target.
702
        // The current target might be garbage as stop tracing usually indicates
703
        // we are in something that we can't trace.
704
        DPRINTF(2, "Told to stop tracing\n");
705
        goto unsupported;
706
    }
707
    else if (stop_tracing_opcode != 0) {
708
        assert(stop_tracing_opcode == _EXIT_TRACE);
709
        ADD_TO_TRACE(stop_tracing_opcode, 0, 0, target);
710
        goto done;
711
    }
712
713
    DPRINTF(2, "%p %d: %s(%d) %d %d\n", old_code, target, _PyOpcode_OpName[opcode], oparg, needs_guard_ip, old_stack_level);
714
715
#ifdef Py_DEBUG
716
    if (oparg > 255) {
717
        assert(_Py_GetBaseCodeUnit(old_code, target).op.code == EXTENDED_ARG);
718
    }
719
#endif
720
721
    if (!tracer->prev_state.dependencies_still_valid) {
722
        goto full;
723
    }
724
725
    // This happens when a recursive call happens that we can't trace. Such as Python -> C -> Python calls
726
    // If we haven't guarded the IP, then it's untraceable.
727
    if (frame != tracer->prev_state.instr_frame && !needs_guard_ip) {
728
        DPRINTF(2, "Unsupported: unguardable jump taken\n");
729
        goto unsupported;
730
    }
731
732
    if (oparg > 0xFFFF) {
733
        DPRINTF(2, "Unsupported: oparg too large\n");
734
        unsupported:
735
        {
736
            // Rewind to previous instruction and replace with _EXIT_TRACE.
737
            _PyUOpInstruction *curr = &trace[trace_length-1];
738
            while (curr->opcode != _SET_IP && trace_length > 2) {
739
                trace_length--;
740
                curr = &trace[trace_length-1];
741
            }
742
            assert(curr->opcode == _SET_IP || trace_length == 2);
743
            if (curr->opcode == _SET_IP) {
744
                int32_t old_target = (int32_t)uop_get_target(curr);
745
                curr++;
746
                trace_length++;
747
                curr->opcode = _DEOPT;
748
                curr->format = UOP_FORMAT_TARGET;
749
                curr->target = old_target;
750
            }
751
            goto done;
752
        }
753
    }
754
755
756
    if (opcode == NOP) {
757
        return 1;
758
    }
759
760
    if (opcode == JUMP_FORWARD) {
761
        return 1;
762
    }
763
764
    if (opcode == EXTENDED_ARG) {
765
        return 1;
766
    }
767
768
    // One for possible _DEOPT, one because _CHECK_VALIDITY itself might _DEOPT
769
    max_length -= 2;
770
771
    const struct opcode_macro_expansion *expansion = &_PyOpcode_macro_expansion[opcode];
772
773
    assert(opcode != ENTER_EXECUTOR && opcode != EXTENDED_ARG);
774
    assert(!_PyErr_Occurred(tstate));
775
776
777
    if (OPCODE_HAS_EXIT(opcode)) {
778
        // Make space for side exit and final _EXIT_TRACE:
779
        max_length--;
780
    }
781
    if (OPCODE_HAS_ERROR(opcode)) {
782
        // Make space for error stub and final _EXIT_TRACE:
783
        max_length--;
784
    }
785
786
    // _GUARD_IP leads to an exit.
787
    max_length -= needs_guard_ip;
788
789
    RESERVE_RAW(expansion->nuops + needs_guard_ip + 2 + (!OPCODE_HAS_NO_SAVE_IP(opcode)), "uop and various checks");
790
791
    ADD_TO_TRACE(_CHECK_VALIDITY, 0, 0, target);
792
793
    if (!OPCODE_HAS_NO_SAVE_IP(opcode)) {
794
        ADD_TO_TRACE(_SET_IP, 0, (uintptr_t)target_instr, target);
795
    }
796
797
    // Can be NULL for the entry frame.
798
    if (old_code != NULL) {
799
        _Py_BloomFilter_Add(dependencies, old_code);
800
    }
801
802
    switch (opcode) {
803
        case POP_JUMP_IF_NONE:
804
        case POP_JUMP_IF_NOT_NONE:
805
        case POP_JUMP_IF_FALSE:
806
        case POP_JUMP_IF_TRUE:
807
        {
808
            _Py_CODEUNIT *computed_next_instr_without_modifiers = target_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]];
809
            _Py_CODEUNIT *computed_next_instr = computed_next_instr_without_modifiers + (computed_next_instr_without_modifiers->op.code == NOT_TAKEN);
810
            _Py_CODEUNIT *computed_jump_instr = computed_next_instr_without_modifiers + oparg;
811
            assert(next_instr == computed_next_instr || next_instr == computed_jump_instr);
812
            int jump_happened = computed_jump_instr == next_instr;
813
            assert(jump_happened == (target_instr[1].cache & 1));
814
            uint32_t uopcode = BRANCH_TO_GUARD[opcode - POP_JUMP_IF_FALSE][jump_happened];
815
            ADD_TO_TRACE(uopcode, 0, 0, INSTR_IP(jump_happened ? computed_next_instr : computed_jump_instr, old_code));
816
            break;
817
        }
818
        case JUMP_BACKWARD_JIT:
819
            // This is possible as the JIT might have re-activated after it was disabled
820
        case JUMP_BACKWARD_NO_JIT:
821
        case JUMP_BACKWARD:
822
            ADD_TO_TRACE(_CHECK_PERIODIC, 0, 0, target);
823
            _Py_FALLTHROUGH;
824
        case JUMP_BACKWARD_NO_INTERRUPT:
825
        {
826
            if ((next_instr != tracer->initial_state.close_loop_instr) &&
827
                (next_instr != tracer->initial_state.start_instr) &&
828
                tracer->prev_state.code_curr_size > CODE_SIZE_NO_PROGRESS &&
829
                // For side exits, we don't want to terminate them early.
830
                tracer->initial_state.exit == NULL &&
831
                // These are coroutines, and we want to unroll those usually.
832
                opcode != JUMP_BACKWARD_NO_INTERRUPT) {
833
                // We encountered a JUMP_BACKWARD but not to the top of our own loop.
834
                // We don't want to continue tracing as we might get stuck in the
835
                // inner loop. Instead, end the trace where the executor of the
836
                // inner loop might start and let the traces rejoin.
837
                OPT_STAT_INC(inner_loop);
838
                ADD_TO_TRACE(_EXIT_TRACE, 0, 0, target);
839
                trace[trace_length-1].operand1 = true; // is_control_flow
840
                DPRINTF(2, "JUMP_BACKWARD not to top ends trace %p %p %p\n", next_instr,
841
                    tracer->initial_state.close_loop_instr, tracer->initial_state.start_instr);
842
                goto done;
843
            }
844
            break;
845
        }
846
847
        case RESUME:
848
        case RESUME_CHECK:
849
            /* Use a special tier 2 version of RESUME_CHECK to allow traces to
850
             *  start with RESUME_CHECK */
851
            ADD_TO_TRACE(_TIER2_RESUME_CHECK, 0, 0, target);
852
            break;
853
        default:
854
        {
855
            const struct opcode_macro_expansion *expansion = &_PyOpcode_macro_expansion[opcode];
856
            // Reserve space for nuops (+ _SET_IP + _EXIT_TRACE)
857
            int nuops = expansion->nuops;
858
            if (nuops == 0) {
859
                DPRINTF(2, "Unsupported opcode %s\n", _PyOpcode_OpName[opcode]);
860
                goto unsupported;
861
            }
862
            assert(nuops > 0);
863
            uint32_t orig_oparg = oparg;  // For OPARG_TOP/BOTTOM
864
            uint32_t orig_target = target;
865
            for (int i = 0; i < nuops; i++) {
866
                oparg = orig_oparg;
867
                target = orig_target;
868
                uint32_t uop = expansion->uops[i].uop;
869
                uint64_t operand = 0;
870
                // Add one to account for the actual opcode/oparg pair:
871
                int offset = expansion->uops[i].offset + 1;
872
                switch (expansion->uops[i].size) {
873
                    case OPARG_SIMPLE:
874
                        assert(opcode != _JUMP_BACKWARD_NO_INTERRUPT && opcode != JUMP_BACKWARD);
875
                        break;
876
                    case OPARG_CACHE_1:
877
                        operand = read_u16(&this_instr[offset].cache);
878
                        break;
879
                    case OPARG_CACHE_2:
880
                        operand = read_u32(&this_instr[offset].cache);
881
                        break;
882
                    case OPARG_CACHE_4:
883
                        operand = read_u64(&this_instr[offset].cache);
884
                        break;
885
                    case OPARG_TOP:  // First half of super-instr
886
                        assert(orig_oparg <= 255);
887
                        oparg = orig_oparg >> 4;
888
                        break;
889
                    case OPARG_BOTTOM:  // Second half of super-instr
890
                        assert(orig_oparg <= 255);
891
                        oparg = orig_oparg & 0xF;
892
                        break;
893
                    case OPARG_SAVE_RETURN_OFFSET:  // op=_SAVE_RETURN_OFFSET; oparg=return_offset
894
                        oparg = offset;
895
                        assert(uop == _SAVE_RETURN_OFFSET);
896
                        break;
897
                    case OPARG_REPLACED:
898
                        uop = _PyUOp_Replacements[uop];
899
                        assert(uop != 0);
900
901
                        uint32_t next_inst = target + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]];
902
                        if (uop == _TIER2_RESUME_CHECK) {
903
                            target = next_inst;
904
                        }
905
                        else {
906
                            int extended_arg = orig_oparg > 255;
907
                            uint32_t jump_target = next_inst + orig_oparg + extended_arg;
908
                            assert(_Py_GetBaseCodeUnit(old_code, jump_target).op.code == END_FOR);
909
                            assert(_Py_GetBaseCodeUnit(old_code, jump_target+1).op.code == POP_ITER);
910
                            if (is_for_iter_test[uop]) {
911
                                target = jump_target + 1;
912
                            }
913
                        }
914
                        break;
915
                    case OPERAND1_1:
916
                        assert(trace[trace_length-1].opcode == uop);
917
                        operand = read_u16(&this_instr[offset].cache);
918
                        trace[trace_length-1].operand1 = operand;
919
                        continue;
920
                    case OPERAND1_2:
921
                        assert(trace[trace_length-1].opcode == uop);
922
                        operand = read_u32(&this_instr[offset].cache);
923
                        trace[trace_length-1].operand1 = operand;
924
                        continue;
925
                    case OPERAND1_4:
926
                        assert(trace[trace_length-1].opcode == uop);
927
                        operand = read_u64(&this_instr[offset].cache);
928
                        trace[trace_length-1].operand1 = operand;
929
                        continue;
930
                    default:
931
                        fprintf(stderr,
932
                                "opcode=%d, oparg=%d; nuops=%d, i=%d; size=%d, offset=%d\n",
933
                                opcode, oparg, nuops, i,
934
                                expansion->uops[i].size,
935
                                expansion->uops[i].offset);
936
                        Py_FatalError("garbled expansion");
937
                }
938
                if (uop == _PUSH_FRAME || uop == _RETURN_VALUE || uop == _RETURN_GENERATOR || uop == _YIELD_VALUE) {
939
                    PyCodeObject *new_code = (PyCodeObject *)PyStackRef_AsPyObjectBorrow(frame->f_executable);
940
                    PyFunctionObject *new_func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj);
941
942
                    operand = 0;
943
                    if (frame->owner < FRAME_OWNED_BY_INTERPRETER) {
944
                        // Don't add nested code objects to the dependency.
945
                        // It causes endless re-traces.
946
                        if (new_func != NULL && !Py_IsNone((PyObject*)new_func) && !(new_code->co_flags & CO_NESTED)) {
947
                            operand = (uintptr_t)new_func;
948
                            DPRINTF(2, "Adding %p func to op\n", (void *)operand);
949
                            _Py_BloomFilter_Add(dependencies, new_func);
950
                        }
951
                        else if (new_code != NULL && !Py_IsNone((PyObject*)new_code)) {
952
                            operand = (uintptr_t)new_code | 1;
953
                            DPRINTF(2, "Adding %p code to op\n", (void *)operand);
954
                            _Py_BloomFilter_Add(dependencies, new_code);
955
                        }
956
                    }
957
                    ADD_TO_TRACE(uop, oparg, operand, target);
958
                    trace[trace_length - 1].operand1 = PyStackRef_IsNone(frame->f_executable) ? 2 : ((int)(frame->stackpointer - _PyFrame_Stackbase(frame)));
959
                    break;
960
                }
961
                if (uop == _BINARY_OP_INPLACE_ADD_UNICODE) {
962
                    assert(i + 1 == nuops);
963
                    _Py_CODEUNIT *next = target_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]];
964
                    assert(next->op.code == STORE_FAST);
965
                    operand = next->op.arg;
966
                }
967
                // All other instructions
968
                ADD_TO_TRACE(uop, oparg, operand, target);
969
            }
970
            break;
971
        }  // End default
972
973
    }  // End switch (opcode)
974
975
    if (needs_guard_ip) {
976
        uint16_t guard_ip = guard_ip_uop[trace[trace_length-1].opcode];
977
        if (guard_ip == 0) {
978
            DPRINTF(1, "Unknown uop needing guard ip %s\n", _PyOpcode_uop_name[trace[trace_length-1].opcode]);
979
            Py_UNREACHABLE();
980
        }
981
        ADD_TO_TRACE(guard_ip, 0, (uintptr_t)next_instr, 0);
982
    }
983
    // Loop back to the start
984
    int is_first_instr = tracer->initial_state.close_loop_instr == next_instr ||
985
        tracer->initial_state.start_instr == next_instr;
986
    if (is_first_instr && tracer->prev_state.code_curr_size > CODE_SIZE_NO_PROGRESS) {
987
        if (needs_guard_ip) {
988
            ADD_TO_TRACE(_SET_IP, 0, (uintptr_t)next_instr, 0);
989
        }
990
        ADD_TO_TRACE(_JUMP_TO_TOP, 0, 0, 0);
991
        goto done;
992
    }
993
    DPRINTF(2, "Trace continuing\n");
994
    tracer->prev_state.code_curr_size = trace_length;
995
    tracer->prev_state.code_max_size = max_length;
996
    return 1;
997
done:
998
    DPRINTF(2, "Trace done\n");
999
    tracer->prev_state.code_curr_size = trace_length;
1000
    tracer->prev_state.code_max_size = max_length;
1001
    return 0;
1002
full:
1003
    DPRINTF(2, "Trace full\n");
1004
    if (!is_terminator(&tracer->code_buffer[trace_length-1])) {
1005
        // Undo the last few instructions.
1006
        trace_length = tracer->prev_state.code_curr_size;
1007
        max_length = tracer->prev_state.code_max_size;
1008
        // We previously reversed one.
1009
        max_length += 1;
1010
        ADD_TO_TRACE(_EXIT_TRACE, 0, 0, target);
1011
        trace[trace_length-1].operand1 = true; // is_control_flow
1012
    }
1013
    tracer->prev_state.code_curr_size = trace_length;
1014
    tracer->prev_state.code_max_size = max_length;
1015
    return 0;
1016
}
1017
1018
// Returns 0 for do not enter tracing, 1 on enter tracing.
1019
// gh-142543: inlining this function causes stack overflows
1020
Py_NO_INLINE int
1021
_PyJit_TryInitializeTracing(
1022
    PyThreadState *tstate, _PyInterpreterFrame *frame, _Py_CODEUNIT *curr_instr,
1023
    _Py_CODEUNIT *start_instr, _Py_CODEUNIT *close_loop_instr, int curr_stackdepth, int chain_depth,
1024
    _PyExitData *exit, int oparg, _PyExecutorObject *current_executor)
1025
{
1026
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
1027
    if (_tstate->jit_tracer_state == NULL) {
1028
        _tstate->jit_tracer_state = (_PyJitTracerState *)_PyObject_VirtualAlloc(sizeof(_PyJitTracerState));
1029
        if (_tstate->jit_tracer_state == NULL) {
1030
            // Don't error, just go to next instruction.
1031
            return 0;
1032
        }
1033
        _tstate->jit_tracer_state->is_tracing = false;
1034
    }
1035
    _PyJitTracerState *tracer = _tstate->jit_tracer_state;
1036
    // A recursive trace.
1037
    if (tracer->is_tracing) {
1038
        return 0;
1039
    }
1040
    if (oparg > 0xFFFF) {
1041
        return 0;
1042
    }
1043
    PyObject *func = PyStackRef_AsPyObjectBorrow(frame->f_funcobj);
1044
    if (func == NULL) {
1045
        return 0;
1046
    }
1047
    PyCodeObject *code = _PyFrame_GetCode(frame);
1048
#ifdef Py_DEBUG
1049
    char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
1050
    int lltrace = 0;
1051
    if (python_lltrace != NULL && *python_lltrace >= '0') {
1052
        lltrace = *python_lltrace - '0';  // TODO: Parse an int and all that
1053
    }
1054
    DPRINTF(2,
1055
        "Tracing %s (%s:%d) at byte offset %d at chain depth %d\n",
1056
        PyUnicode_AsUTF8(code->co_qualname),
1057
        PyUnicode_AsUTF8(code->co_filename),
1058
        code->co_firstlineno,
1059
        2 * INSTR_IP(close_loop_instr, code),
1060
        chain_depth);
1061
#endif
1062
    add_to_trace(tracer->code_buffer, 0, _START_EXECUTOR, 0, (uintptr_t)start_instr, INSTR_IP(start_instr, code));
1063
    add_to_trace(tracer->code_buffer, 1, _MAKE_WARM, 0, 0, 0);
1064
    tracer->prev_state.code_curr_size = CODE_SIZE_EMPTY;
1065
1066
    tracer->prev_state.code_max_size = UOP_MAX_TRACE_LENGTH/2;
1067
    tracer->initial_state.start_instr = start_instr;
1068
    tracer->initial_state.close_loop_instr = close_loop_instr;
1069
    tracer->initial_state.code = (PyCodeObject *)Py_NewRef(code);
1070
    tracer->initial_state.func = (PyFunctionObject *)Py_NewRef(func);
1071
    tracer->initial_state.executor = (_PyExecutorObject *)Py_XNewRef(current_executor);
1072
    tracer->initial_state.exit = exit;
1073
    tracer->initial_state.stack_depth = curr_stackdepth;
1074
    tracer->initial_state.chain_depth = chain_depth;
1075
    tracer->prev_state.instr_frame = frame;
1076
    tracer->prev_state.dependencies_still_valid = true;
1077
    tracer->prev_state.instr_code = (PyCodeObject *)Py_NewRef(_PyFrame_GetCode(frame));
1078
    tracer->prev_state.instr = curr_instr;
1079
    tracer->prev_state.instr_frame = frame;
1080
    tracer->prev_state.instr_oparg = oparg;
1081
    tracer->prev_state.instr_stacklevel = curr_stackdepth;
1082
    assert(curr_instr->op.code == JUMP_BACKWARD_JIT || (exit != NULL));
1083
    tracer->initial_state.jump_backward_instr = curr_instr;
1084
1085
    if (_PyOpcode_Caches[_PyOpcode_Deopt[close_loop_instr->op.code]]) {
1086
        close_loop_instr[1].counter = trigger_backoff_counter();
1087
    }
1088
    _Py_BloomFilter_Init(&tracer->prev_state.dependencies);
1089
    tracer->is_tracing = true;
1090
    return 1;
1091
}
1092
1093
Py_NO_INLINE void
1094
_PyJit_FinalizeTracing(PyThreadState *tstate, int err)
1095
{
1096
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
1097
    _PyJitTracerState *tracer = _tstate->jit_tracer_state;
1098
    // Deal with backoffs
1099
    assert(tracer != NULL);
1100
    _PyExitData *exit = tracer->initial_state.exit;
1101
    if (exit == NULL) {
1102
        // We hold a strong reference to the code object, so the instruction won't be freed.
1103
        if (err <= 0) {
1104
            _Py_BackoffCounter counter = tracer->initial_state.jump_backward_instr[1].counter;
1105
            tracer->initial_state.jump_backward_instr[1].counter = restart_backoff_counter(counter);
1106
        }
1107
        else {
1108
            tracer->initial_state.jump_backward_instr[1].counter = initial_jump_backoff_counter(&tstate->interp->opt_config);
1109
        }
1110
    }
1111
    else if (tracer->initial_state.executor->vm_data.valid) {
1112
        // Likewise, we hold a strong reference to the executor containing this exit, so the exit is guaranteed
1113
        // to be valid to access.
1114
        if (err <= 0) {
1115
            exit->temperature = restart_backoff_counter(exit->temperature);
1116
        }
1117
        else {
1118
            exit->temperature = initial_temperature_backoff_counter(&tstate->interp->opt_config);
1119
        }
1120
    }
1121
    Py_CLEAR(tracer->initial_state.code);
1122
    Py_CLEAR(tracer->initial_state.func);
1123
    Py_CLEAR(tracer->initial_state.executor);
1124
    Py_CLEAR(tracer->prev_state.instr_code);
1125
    tracer->prev_state.code_curr_size = CODE_SIZE_EMPTY;
1126
    tracer->prev_state.code_max_size = UOP_MAX_TRACE_LENGTH/2 - 1;
1127
    tracer->is_tracing = false;
1128
}
1129
1130
void
1131
_PyJit_TracerFree(_PyThreadStateImpl *_tstate)
1132
{
1133
    if (_tstate->jit_tracer_state != NULL) {
1134
        _PyObject_VirtualFree(_tstate->jit_tracer_state, sizeof(_PyJitTracerState));
1135
        _tstate->jit_tracer_state = NULL;
1136
    }
1137
}
1138
1139
#undef RESERVE
1140
#undef RESERVE_RAW
1141
#undef INSTR_IP
1142
#undef ADD_TO_TRACE
1143
#undef DPRINTF
1144
1145
#define UNSET_BIT(array, bit) (array[(bit)>>5] &= ~(1<<((bit)&31)))
1146
#define SET_BIT(array, bit) (array[(bit)>>5] |= (1<<((bit)&31)))
1147
#define BIT_IS_SET(array, bit) (array[(bit)>>5] & (1<<((bit)&31)))
1148
1149
/* Count the number of unused uops and exits
1150
*/
1151
static int
1152
count_exits(_PyUOpInstruction *buffer, int length)
1153
{
1154
    int exit_count = 0;
1155
    for (int i = 0; i < length; i++) {
1156
        uint16_t base_opcode = _PyUop_Uncached[buffer[i].opcode];
1157
        if (base_opcode == _EXIT_TRACE || base_opcode == _DYNAMIC_EXIT) {
1158
            exit_count++;
1159
        }
1160
    }
1161
    return exit_count;
1162
}
1163
1164
/* The number of cached registers at any exit (`EXIT_IF` or `DEOPT_IF`)
1165
 * This is the number of cached at entries at start, unless the uop is
1166
 * marked as `exit_depth_is_output` in which case it is the number of
1167
 * cached entries at the end */
1168
static int
1169
get_cached_entries_for_side_exit(_PyUOpInstruction *inst)
1170
{
1171
    // Maybe add another generated table for this?
1172
    int base_opcode = _PyUop_Uncached[inst->opcode];
1173
    assert(base_opcode != 0);
1174
    for (int i = 0; i <= MAX_CACHED_REGISTER; i++) {
1175
        const _PyUopTOSentry *entry = &_PyUop_Caching[base_opcode].entries[i];
1176
        if (entry->opcode == inst->opcode) {
1177
            return entry->exit;
1178
        }
1179
    }
1180
    Py_UNREACHABLE();
1181
}
1182
1183
static void make_exit(_PyUOpInstruction *inst, int opcode, int target, bool is_control_flow)
1184
{
1185
    assert(opcode > MAX_UOP_ID && opcode <= MAX_UOP_REGS_ID);
1186
    inst->opcode = opcode;
1187
    inst->oparg = 0;
1188
    inst->operand0 = 0;
1189
    inst->format = UOP_FORMAT_TARGET;
1190
    inst->target = target;
1191
    inst->operand1 = is_control_flow;
1192
#ifdef Py_STATS
1193
    inst->execution_count = 0;
1194
#endif
1195
}
1196
1197
/* Convert implicit exits, errors and deopts
1198
 * into explicit ones. */
1199
static int
1200
prepare_for_execution(_PyUOpInstruction *buffer, int length)
1201
{
1202
    int32_t current_jump = -1;
1203
    int32_t current_jump_target = -1;
1204
    int32_t current_error = -1;
1205
    int32_t current_error_target = -1;
1206
    int32_t current_popped = -1;
1207
    int32_t current_exit_op = -1;
1208
    /* Leaving in NOPs slows down the interpreter and messes up the stats */
1209
    _PyUOpInstruction *copy_to = &buffer[0];
1210
    for (int i = 0; i < length; i++) {
1211
        _PyUOpInstruction *inst = &buffer[i];
1212
        if (inst->opcode != _NOP) {
1213
            if (copy_to != inst) {
1214
                *copy_to = *inst;
1215
            }
1216
            copy_to++;
1217
        }
1218
    }
1219
    length = (int)(copy_to - buffer);
1220
    int next_spare = length;
1221
    for (int i = 0; i < length; i++) {
1222
        _PyUOpInstruction *inst = &buffer[i];
1223
        int base_opcode = _PyUop_Uncached[inst->opcode];
1224
        assert(inst->opcode != _NOP);
1225
        int32_t target = (int32_t)uop_get_target(inst);
1226
        uint16_t exit_flags = _PyUop_Flags[base_opcode] & (HAS_EXIT_FLAG | HAS_DEOPT_FLAG | HAS_PERIODIC_FLAG);
1227
        if (exit_flags) {
1228
            uint16_t base_exit_op = _EXIT_TRACE;
1229
            if (exit_flags & HAS_DEOPT_FLAG) {
1230
                base_exit_op = _DEOPT;
1231
            }
1232
            else if (exit_flags & HAS_PERIODIC_FLAG) {
1233
                base_exit_op = _HANDLE_PENDING_AND_DEOPT;
1234
            }
1235
            int32_t jump_target = target;
1236
            if (
1237
                base_opcode == _GUARD_IP__PUSH_FRAME ||
1238
                base_opcode == _GUARD_IP_RETURN_VALUE ||
1239
                base_opcode == _GUARD_IP_YIELD_VALUE ||
1240
                base_opcode == _GUARD_IP_RETURN_GENERATOR
1241
            ) {
1242
                base_exit_op = _DYNAMIC_EXIT;
1243
            }
1244
            int exit_depth = get_cached_entries_for_side_exit(inst);
1245
            assert(_PyUop_Caching[base_exit_op].entries[exit_depth].opcode > 0);
1246
            int16_t exit_op = _PyUop_Caching[base_exit_op].entries[exit_depth].opcode;
1247
            bool is_control_flow = (base_opcode == _GUARD_IS_FALSE_POP || base_opcode == _GUARD_IS_TRUE_POP || is_for_iter_test[base_opcode]);
1248
            if (jump_target != current_jump_target || current_exit_op != exit_op) {
1249
                make_exit(&buffer[next_spare], exit_op, jump_target, is_control_flow);
1250
                current_exit_op = exit_op;
1251
                current_jump_target = jump_target;
1252
                current_jump = next_spare;
1253
                next_spare++;
1254
            }
1255
            buffer[i].jump_target = current_jump;
1256
            buffer[i].format = UOP_FORMAT_JUMP;
1257
        }
1258
        if (_PyUop_Flags[base_opcode] & HAS_ERROR_FLAG) {
1259
            int popped = (_PyUop_Flags[base_opcode] & HAS_ERROR_NO_POP_FLAG) ?
1260
                0 : _PyUop_num_popped(base_opcode, inst->oparg);
1261
            if (target != current_error_target || popped != current_popped) {
1262
                current_popped = popped;
1263
                current_error = next_spare;
1264
                current_error_target = target;
1265
                make_exit(&buffer[next_spare], _ERROR_POP_N_r00, 0, false);
1266
                buffer[next_spare].operand0 = target;
1267
                next_spare++;
1268
            }
1269
            buffer[i].error_target = current_error;
1270
            if (buffer[i].format == UOP_FORMAT_TARGET) {
1271
                buffer[i].format = UOP_FORMAT_JUMP;
1272
                buffer[i].jump_target = 0;
1273
            }
1274
        }
1275
        if (base_opcode == _JUMP_TO_TOP) {
1276
            assert(_PyUop_Uncached[buffer[0].opcode] == _START_EXECUTOR);
1277
            buffer[i].format = UOP_FORMAT_JUMP;
1278
            buffer[i].jump_target = 1;
1279
        }
1280
    }
1281
    return next_spare;
1282
}
1283
1284
/* Executor side exits */
1285
1286
static _PyExecutorObject *
1287
allocate_executor(int exit_count, int length)
1288
{
1289
    int size = exit_count*sizeof(_PyExitData) + length*sizeof(_PyUOpInstruction);
1290
    _PyExecutorObject *res = PyObject_GC_NewVar(_PyExecutorObject, &_PyUOpExecutor_Type, size);
1291
    if (res == NULL) {
1292
        return NULL;
1293
    }
1294
    res->trace = (_PyUOpInstruction *)(res->exits + exit_count);
1295
    res->code_size = length;
1296
    res->exit_count = exit_count;
1297
    return res;
1298
}
1299
1300
#ifdef Py_DEBUG
1301
1302
#define CHECK(PRED) \
1303
if (!(PRED)) { \
1304
    printf(#PRED " at %d\n", i); \
1305
    assert(0); \
1306
}
1307
1308
static int
1309
target_unused(int opcode)
1310
{
1311
    return (_PyUop_Flags[opcode] & (HAS_ERROR_FLAG | HAS_EXIT_FLAG | HAS_DEOPT_FLAG)) == 0;
1312
}
1313
1314
static void
1315
sanity_check(_PyExecutorObject *executor)
1316
{
1317
    for (uint32_t i = 0; i < executor->exit_count; i++) {
1318
        _PyExitData *exit = &executor->exits[i];
1319
        CHECK(exit->target < (1 << 25));
1320
    }
1321
    bool ended = false;
1322
    uint32_t i = 0;
1323
    CHECK(_PyUop_Uncached[executor->trace[0].opcode] == _START_EXECUTOR ||
1324
        _PyUop_Uncached[executor->trace[0].opcode] == _COLD_EXIT ||
1325
        _PyUop_Uncached[executor->trace[0].opcode] == _COLD_DYNAMIC_EXIT);
1326
    for (; i < executor->code_size; i++) {
1327
        const _PyUOpInstruction *inst = &executor->trace[i];
1328
        uint16_t opcode = inst->opcode;
1329
        uint16_t base_opcode = _PyUop_Uncached[opcode];
1330
        CHECK(opcode > MAX_UOP_ID);
1331
        CHECK(opcode <= MAX_UOP_REGS_ID);
1332
        CHECK(base_opcode <= MAX_UOP_ID);
1333
        CHECK(base_opcode != 0);
1334
        switch(inst->format) {
1335
            case UOP_FORMAT_TARGET:
1336
                CHECK(target_unused(base_opcode));
1337
                break;
1338
            case UOP_FORMAT_JUMP:
1339
                CHECK(inst->jump_target < executor->code_size);
1340
                break;
1341
        }
1342
        if (_PyUop_Flags[base_opcode] & HAS_ERROR_FLAG) {
1343
            CHECK(inst->format == UOP_FORMAT_JUMP);
1344
            CHECK(inst->error_target < executor->code_size);
1345
        }
1346
        if (is_terminator(inst)) {
1347
            ended = true;
1348
            i++;
1349
            break;
1350
        }
1351
    }
1352
    CHECK(ended);
1353
    for (; i < executor->code_size; i++) {
1354
        const _PyUOpInstruction *inst = &executor->trace[i];
1355
        uint16_t base_opcode = _PyUop_Uncached[inst->opcode];
1356
        CHECK(
1357
            base_opcode == _DEOPT ||
1358
            base_opcode == _HANDLE_PENDING_AND_DEOPT ||
1359
            base_opcode == _EXIT_TRACE ||
1360
            base_opcode == _ERROR_POP_N ||
1361
            base_opcode == _DYNAMIC_EXIT);
1362
    }
1363
}
1364
1365
#undef CHECK
1366
#endif
1367
1368
/* Makes an executor from a buffer of uops.
1369
 * Account for the buffer having gaps and NOPs by computing a "used"
1370
 * bit vector and only copying the used uops. Here "used" means reachable
1371
 * and not a NOP.
1372
 */
1373
static _PyExecutorObject *
1374
make_executor_from_uops(_PyThreadStateImpl *tstate, _PyUOpInstruction *buffer, int length, const _PyBloomFilter *dependencies)
1375
{
1376
    int exit_count = count_exits(buffer, length);
1377
    _PyExecutorObject *executor = allocate_executor(exit_count, length);
1378
    if (executor == NULL) {
1379
        return NULL;
1380
    }
1381
1382
    /* Initialize exits */
1383
    int chain_depth = tstate->jit_tracer_state->initial_state.chain_depth;
1384
    _PyExecutorObject *cold = _PyExecutor_GetColdExecutor();
1385
    _PyExecutorObject *cold_dynamic = _PyExecutor_GetColdDynamicExecutor();
1386
    cold->vm_data.chain_depth = chain_depth;
1387
    PyInterpreterState *interp = tstate->base.interp;
1388
    for (int i = 0; i < exit_count; i++) {
1389
        executor->exits[i].index = i;
1390
        executor->exits[i].temperature = initial_temperature_backoff_counter(&interp->opt_config);
1391
    }
1392
    int next_exit = exit_count-1;
1393
    _PyUOpInstruction *dest = (_PyUOpInstruction *)&executor->trace[length];
1394
    assert(_PyUop_Uncached[buffer[0].opcode] == _START_EXECUTOR);
1395
    buffer[0].operand0 = (uint64_t)executor;
1396
    for (int i = length-1; i >= 0; i--) {
1397
        uint16_t base_opcode = _PyUop_Uncached[buffer[i].opcode];
1398
        dest--;
1399
        *dest = buffer[i];
1400
        if (base_opcode == _EXIT_TRACE || base_opcode == _DYNAMIC_EXIT) {
1401
            _PyExitData *exit = &executor->exits[next_exit];
1402
            exit->target = buffer[i].target;
1403
            dest->operand0 = (uint64_t)exit;
1404
            exit->executor = base_opcode == _EXIT_TRACE ? cold : cold_dynamic;
1405
            exit->is_dynamic = (char)(base_opcode == _DYNAMIC_EXIT);
1406
            exit->is_control_flow = (char)buffer[i].operand1;
1407
            next_exit--;
1408
        }
1409
    }
1410
    assert(next_exit == -1);
1411
    assert(dest == executor->trace);
1412
    assert(_PyUop_Uncached[dest->opcode] == _START_EXECUTOR);
1413
    // Note: we MUST track it here before any Py_DECREF(executor) or
1414
    // linking of executor. Otherwise, the GC tries to untrack a
1415
    // still untracked object during dealloc.
1416
    _PyObject_GC_TRACK(executor);
1417
    _Py_ExecutorInit(executor, dependencies);
1418
#ifdef Py_DEBUG
1419
    char *python_lltrace = Py_GETENV("PYTHON_LLTRACE");
1420
    int lltrace = 0;
1421
    if (python_lltrace != NULL && *python_lltrace >= '0') {
1422
        lltrace = *python_lltrace - '0';  // TODO: Parse an int and all that
1423
    }
1424
    if (lltrace >= 2) {
1425
        printf("Optimized trace (length %d):\n", length);
1426
        for (int i = 0; i < length; i++) {
1427
            printf("%4d OPTIMIZED: ", i);
1428
            _PyUOpPrint(&executor->trace[i]);
1429
            printf("\n");
1430
        }
1431
    }
1432
    sanity_check(executor);
1433
#endif
1434
#ifdef _Py_JIT
1435
    executor->jit_code = NULL;
1436
    executor->jit_size = 0;
1437
    // This is initialized to false so we can prevent the executor
1438
    // from being immediately detected as cold and invalidated.
1439
    executor->vm_data.cold = false;
1440
    if (_PyJIT_Compile(executor, executor->trace, length)) {
1441
        Py_DECREF(executor);
1442
        return NULL;
1443
    }
1444
#endif
1445
    return executor;
1446
}
1447
1448
#ifdef Py_STATS
1449
/* Returns the effective trace length.
1450
 * Ignores NOPs and trailing exit and error handling.*/
1451
int effective_trace_length(_PyUOpInstruction *buffer, int length)
1452
{
1453
    int nop_count = 0;
1454
    for (int i = 0; i < length; i++) {
1455
        int opcode = buffer[i].opcode;
1456
        if (opcode == _NOP) {
1457
            nop_count++;
1458
        }
1459
        if (is_terminator(&buffer[i])) {
1460
            return i+1-nop_count;
1461
        }
1462
    }
1463
    Py_FatalError("No terminating instruction");
1464
    Py_UNREACHABLE();
1465
}
1466
#endif
1467
1468
1469
static int
1470
stack_allocate(_PyUOpInstruction *buffer, int length)
1471
{
1472
    assert(buffer[0].opcode == _START_EXECUTOR);
1473
    for (int i = length-1; i >= 0; i--) {
1474
        buffer[i*2+1] = buffer[i];
1475
        buffer[i*2].format = UOP_FORMAT_TARGET;
1476
        buffer[i*2].oparg = 0;
1477
        buffer[i*2].target = 0;
1478
    }
1479
    int depth = 0;
1480
    for (int i = 0; i < length; i++) {
1481
        _PyUOpInstruction *spill_or_reload = &buffer[i*2];
1482
        int uop = buffer[i*2+1].opcode;
1483
        if (uop == _NOP) {
1484
            // leave _NOPs to be cleaned up later
1485
            spill_or_reload->opcode = _NOP;
1486
            continue;
1487
        }
1488
        int new_depth = _PyUop_Caching[uop].best[depth];
1489
        if (new_depth == depth) {
1490
            spill_or_reload->opcode = _NOP;
1491
        }
1492
        else {
1493
            spill_or_reload->opcode = _PyUop_SpillsAndReloads[depth][new_depth];
1494
            depth = new_depth;
1495
        }
1496
        uint16_t new_opcode = _PyUop_Caching[uop].entries[depth].opcode;
1497
        assert(new_opcode != 0);
1498
        assert(spill_or_reload->opcode != 0);
1499
        buffer[i*2+1].opcode = new_opcode;
1500
        depth = _PyUop_Caching[uop].entries[depth].output;
1501
    }
1502
    return length*2;
1503
}
1504
1505
static int
1506
uop_optimize(
1507
    _PyInterpreterFrame *frame,
1508
    PyThreadState *tstate,
1509
    _PyExecutorObject **exec_ptr,
1510
    bool progress_needed)
1511
{
1512
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
1513
    assert(_tstate->jit_tracer_state != NULL);
1514
    _PyBloomFilter *dependencies = &_tstate->jit_tracer_state->prev_state.dependencies;
1515
    _PyUOpInstruction *buffer = _tstate->jit_tracer_state->code_buffer;
1516
    OPT_STAT_INC(attempts);
1517
    char *env_var = Py_GETENV("PYTHON_UOPS_OPTIMIZE");
1518
    bool is_noopt = true;
1519
    if (env_var == NULL || *env_var == '\0' || *env_var > '0') {
1520
        is_noopt = false;
1521
    }
1522
    int curr_stackentries = _tstate->jit_tracer_state->initial_state.stack_depth;
1523
    int length = _tstate->jit_tracer_state->prev_state.code_curr_size;
1524
    if (length <= CODE_SIZE_NO_PROGRESS) {
1525
        return 0;
1526
    }
1527
    assert(length > 0);
1528
    assert(length < UOP_MAX_TRACE_LENGTH/2);
1529
    OPT_STAT_INC(traces_created);
1530
    if (!is_noopt) {
1531
        length = _Py_uop_analyze_and_optimize(
1532
            _tstate,
1533
            buffer, length,
1534
            curr_stackentries, dependencies);
1535
        if (length <= 0) {
1536
            return length;
1537
        }
1538
    }
1539
    assert(length < UOP_MAX_TRACE_LENGTH/2);
1540
    assert(length >= 1);
1541
    /* Fix up */
1542
    for (int pc = 0; pc < length; pc++) {
1543
        int opcode = buffer[pc].opcode;
1544
        int oparg = buffer[pc].oparg;
1545
        if (oparg < _PyUop_Replication[opcode].stop && oparg >= _PyUop_Replication[opcode].start) {
1546
            buffer[pc].opcode = opcode + oparg + 1 - _PyUop_Replication[opcode].start;
1547
            assert(strncmp(_PyOpcode_uop_name[buffer[pc].opcode], _PyOpcode_uop_name[opcode], strlen(_PyOpcode_uop_name[opcode])) == 0);
1548
        }
1549
        else if (is_terminator(&buffer[pc])) {
1550
            break;
1551
        }
1552
        assert(_PyOpcode_uop_name[buffer[pc].opcode]);
1553
    }
1554
    OPT_HIST(effective_trace_length(buffer, length), optimized_trace_length_hist);
1555
    length = stack_allocate(buffer, length);
1556
    length = prepare_for_execution(buffer, length);
1557
    assert(length <= UOP_MAX_TRACE_LENGTH);
1558
    _PyExecutorObject *executor = make_executor_from_uops(
1559
        _tstate, buffer, length, dependencies);
1560
    if (executor == NULL) {
1561
        return -1;
1562
    }
1563
    assert(length <= UOP_MAX_TRACE_LENGTH);
1564
1565
    // Check executor coldness
1566
    // It's okay if this ends up going negative.
1567
    if (--tstate->interp->executor_creation_counter == 0) {
1568
        _Py_set_eval_breaker_bit(tstate, _PY_EVAL_JIT_INVALIDATE_COLD_BIT);
1569
    }
1570
1571
    *exec_ptr = executor;
1572
    return 1;
1573
}
1574
1575
1576
/*****************************************
1577
 *        Executor management
1578
 ****************************************/
1579
1580
/* We use a bloomfilter with k = 6, m = 256
1581
 * The choice of k and the following constants
1582
 * could do with a more rigorous analysis,
1583
 * but here is a simple analysis:
1584
 *
1585
 * We want to keep the false positive rate low.
1586
 * For n = 5 (a trace depends on 5 objects),
1587
 * we expect 30 bits set, giving a false positive
1588
 * rate of (30/256)**6 == 2.5e-6 which is plenty
1589
 * good enough.
1590
 *
1591
 * However with n = 10 we expect 60 bits set (worst case),
1592
 * giving a false positive of (60/256)**6 == 0.0001
1593
 *
1594
 * We choose k = 6, rather than a higher number as
1595
 * it means the false positive rate grows slower for high n.
1596
 *
1597
 * n = 5, k = 6 => fp = 2.6e-6
1598
 * n = 5, k = 8 => fp = 3.5e-7
1599
 * n = 10, k = 6 => fp = 1.6e-4
1600
 * n = 10, k = 8 => fp = 0.9e-4
1601
 * n = 15, k = 6 => fp = 0.18%
1602
 * n = 15, k = 8 => fp = 0.23%
1603
 * n = 20, k = 6 => fp = 1.1%
1604
 * n = 20, k = 8 => fp = 2.3%
1605
 *
1606
 * The above analysis assumes perfect hash functions,
1607
 * but those don't exist, so the real false positive
1608
 * rates may be worse.
1609
 */
1610
1611
#define K 6
1612
1613
#define SEED 20221211
1614
1615
/* TO DO -- Use more modern hash functions with better distribution of bits */
1616
static uint64_t
1617
address_to_hash(void *ptr) {
1618
    assert(ptr != NULL);
1619
    uint64_t uhash = SEED;
1620
    uintptr_t addr = (uintptr_t)ptr;
1621
    for (int i = 0; i < SIZEOF_VOID_P; i++) {
1622
        uhash ^= addr & 255;
1623
        uhash *= (uint64_t)PyHASH_MULTIPLIER;
1624
        addr >>= 8;
1625
    }
1626
    return uhash;
1627
}
1628
1629
void
1630
_Py_BloomFilter_Init(_PyBloomFilter *bloom)
1631
{
1632
    for (int i = 0; i < _Py_BLOOM_FILTER_WORDS; i++) {
1633
        bloom->bits[i] = 0;
1634
    }
1635
}
1636
1637
/* We want K hash functions that each set 1 bit.
1638
 * A hash function that sets 1 bit in M bits can be trivially
1639
 * derived from a log2(M) bit hash function.
1640
 * So we extract 8 (log2(256)) bits at a time from
1641
 * the 64bit hash. */
1642
void
1643
_Py_BloomFilter_Add(_PyBloomFilter *bloom, void *ptr)
1644
{
1645
    uint64_t hash = address_to_hash(ptr);
1646
    assert(K <= 8);
1647
    for (int i = 0; i < K; i++) {
1648
        uint8_t bits = hash & 255;
1649
        bloom->bits[bits >> 5] |= (1 << (bits&31));
1650
        hash >>= 8;
1651
    }
1652
}
1653
1654
static bool
1655
bloom_filter_may_contain(_PyBloomFilter *bloom, _PyBloomFilter *hashes)
1656
{
1657
    for (int i = 0; i < _Py_BLOOM_FILTER_WORDS; i++) {
1658
        if ((bloom->bits[i] & hashes->bits[i]) != hashes->bits[i]) {
1659
            return false;
1660
        }
1661
    }
1662
    return true;
1663
}
1664
1665
static void
1666
link_executor(_PyExecutorObject *executor)
1667
{
1668
    PyInterpreterState *interp = _PyInterpreterState_GET();
1669
    _PyExecutorLinkListNode *links = &executor->vm_data.links;
1670
    _PyExecutorObject *head = interp->executor_list_head;
1671
    if (head == NULL) {
1672
        interp->executor_list_head = executor;
1673
        links->previous = NULL;
1674
        links->next = NULL;
1675
    }
1676
    else {
1677
        assert(head->vm_data.links.previous == NULL);
1678
        links->previous = NULL;
1679
        links->next = head;
1680
        head->vm_data.links.previous = executor;
1681
        interp->executor_list_head = executor;
1682
    }
1683
    /* executor_list_head must be first in list */
1684
    assert(interp->executor_list_head->vm_data.links.previous == NULL);
1685
}
1686
1687
static void
1688
unlink_executor(_PyExecutorObject *executor)
1689
{
1690
    _PyExecutorLinkListNode *links = &executor->vm_data.links;
1691
    _PyExecutorObject *next = links->next;
1692
    _PyExecutorObject *prev = links->previous;
1693
    if (next != NULL) {
1694
        next->vm_data.links.previous = prev;
1695
    }
1696
    if (prev != NULL) {
1697
        prev->vm_data.links.next = next;
1698
    }
1699
    else {
1700
        // prev == NULL implies that executor is the list head
1701
        PyInterpreterState *interp = PyInterpreterState_Get();
1702
        assert(interp->executor_list_head == executor);
1703
        interp->executor_list_head = next;
1704
    }
1705
}
1706
1707
/* This must be called by optimizers before using the executor */
1708
void
1709
_Py_ExecutorInit(_PyExecutorObject *executor, const _PyBloomFilter *dependency_set)
1710
{
1711
    executor->vm_data.valid = true;
1712
    executor->vm_data.pending_deletion = 0;
1713
    for (int i = 0; i < _Py_BLOOM_FILTER_WORDS; i++) {
1714
        executor->vm_data.bloom.bits[i] = dependency_set->bits[i];
1715
    }
1716
    link_executor(executor);
1717
}
1718
1719
static _PyExecutorObject *
1720
make_cold_executor(uint16_t opcode)
1721
{
1722
    _PyExecutorObject *cold = allocate_executor(0, 1);
1723
    if (cold == NULL) {
1724
        Py_FatalError("Cannot allocate core JIT code");
1725
    }
1726
    ((_PyUOpInstruction *)cold->trace)->opcode = opcode;
1727
    // This is initialized to false so we can prevent the executor
1728
    // from being immediately detected as cold and invalidated.
1729
    cold->vm_data.cold = false;
1730
#ifdef _Py_JIT
1731
    cold->jit_code = NULL;
1732
    cold->jit_size = 0;
1733
    if (_PyJIT_Compile(cold, cold->trace, 1)) {
1734
        Py_DECREF(cold);
1735
        Py_FatalError("Cannot allocate core JIT code");
1736
    }
1737
#endif
1738
    _Py_SetImmortal((PyObject *)cold);
1739
    return cold;
1740
}
1741
1742
_PyExecutorObject *
1743
_PyExecutor_GetColdExecutor(void)
1744
{
1745
    PyInterpreterState *interp = _PyInterpreterState_GET();
1746
    if (interp->cold_executor == NULL) {
1747
        return interp->cold_executor = make_cold_executor(_COLD_EXIT_r00);;
1748
    }
1749
    return interp->cold_executor;
1750
}
1751
1752
_PyExecutorObject *
1753
_PyExecutor_GetColdDynamicExecutor(void)
1754
{
1755
    PyInterpreterState *interp = _PyInterpreterState_GET();
1756
    if (interp->cold_dynamic_executor == NULL) {
1757
        interp->cold_dynamic_executor = make_cold_executor(_COLD_DYNAMIC_EXIT_r00);
1758
    }
1759
    return interp->cold_dynamic_executor;
1760
}
1761
1762
void
1763
_PyExecutor_ClearExit(_PyExitData *exit)
1764
{
1765
    if (exit == NULL) {
1766
        return;
1767
    }
1768
    _PyExecutorObject *old = exit->executor;
1769
    if (exit->is_dynamic) {
1770
        exit->executor = _PyExecutor_GetColdDynamicExecutor();
1771
    }
1772
    else {
1773
        exit->executor = _PyExecutor_GetColdExecutor();
1774
    }
1775
    Py_DECREF(old);
1776
}
1777
1778
/* Detaches the executor from the code object (if any) that
1779
 * holds a reference to it */
1780
void
1781
_Py_ExecutorDetach(_PyExecutorObject *executor)
1782
{
1783
    PyCodeObject *code = executor->vm_data.code;
1784
    if (code == NULL) {
1785
        return;
1786
    }
1787
    _Py_CODEUNIT *instruction = &_PyCode_CODE(code)[executor->vm_data.index];
1788
    assert(instruction->op.code == ENTER_EXECUTOR);
1789
    int index = instruction->op.arg;
1790
    assert(code->co_executors->executors[index] == executor);
1791
    instruction->op.code = executor->vm_data.opcode;
1792
    instruction->op.arg = executor->vm_data.oparg;
1793
    executor->vm_data.code = NULL;
1794
    code->co_executors->executors[index] = NULL;
1795
    Py_DECREF(executor);
1796
}
1797
1798
/* Executors can be invalidated at any time,
1799
   even with a stop-the-world lock held.
1800
   Consequently it must not run arbitrary code,
1801
   including Py_DECREF with a non-executor. */
1802
static void
1803
executor_invalidate(PyObject *op)
1804
{
1805
    _PyExecutorObject *executor = _PyExecutorObject_CAST(op);
1806
    if (!executor->vm_data.valid) {
1807
        return;
1808
    }
1809
    executor->vm_data.valid = 0;
1810
    unlink_executor(executor);
1811
    executor_clear_exits(executor);
1812
    _Py_ExecutorDetach(executor);
1813
    _PyObject_GC_UNTRACK(op);
1814
}
1815
1816
static int
1817
executor_clear(PyObject *op)
1818
{
1819
    executor_invalidate(op);
1820
    return 0;
1821
}
1822
1823
void
1824
_Py_Executor_DependsOn(_PyExecutorObject *executor, void *obj)
1825
{
1826
    assert(executor->vm_data.valid);
1827
    _Py_BloomFilter_Add(&executor->vm_data.bloom, obj);
1828
}
1829
1830
/* Invalidate all executors that depend on `obj`
1831
 * May cause other executors to be invalidated as well
1832
 */
1833
void
1834
_Py_Executors_InvalidateDependency(PyInterpreterState *interp, void *obj, int is_invalidation)
1835
{
1836
    _PyBloomFilter obj_filter;
1837
    _Py_BloomFilter_Init(&obj_filter);
1838
    _Py_BloomFilter_Add(&obj_filter, obj);
1839
    /* Walk the list of executors */
1840
    /* TO DO -- Use a tree to avoid traversing as many objects */
1841
    PyObject *invalidate = PyList_New(0);
1842
    if (invalidate == NULL) {
1843
        goto error;
1844
    }
1845
    /* Clearing an executor can clear others, so we need to make a list of
1846
     * executors to invalidate first */
1847
    for (_PyExecutorObject *exec = interp->executor_list_head; exec != NULL;) {
1848
        assert(exec->vm_data.valid);
1849
        _PyExecutorObject *next = exec->vm_data.links.next;
1850
        if (bloom_filter_may_contain(&exec->vm_data.bloom, &obj_filter) &&
1851
            PyList_Append(invalidate, (PyObject *)exec))
1852
        {
1853
            goto error;
1854
        }
1855
        exec = next;
1856
    }
1857
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(invalidate); i++) {
1858
        PyObject *exec = PyList_GET_ITEM(invalidate, i);
1859
        executor_invalidate(exec);
1860
        if (is_invalidation) {
1861
            OPT_STAT_INC(executors_invalidated);
1862
        }
1863
    }
1864
    Py_DECREF(invalidate);
1865
    return;
1866
error:
1867
    PyErr_Clear();
1868
    Py_XDECREF(invalidate);
1869
    // If we're truly out of memory, wiping out everything is a fine fallback:
1870
    _Py_Executors_InvalidateAll(interp, is_invalidation);
1871
}
1872
1873
void
1874
_PyJit_Tracer_InvalidateDependency(PyThreadState *tstate, void *obj)
1875
{
1876
    _PyBloomFilter obj_filter;
1877
    _Py_BloomFilter_Init(&obj_filter);
1878
    _Py_BloomFilter_Add(&obj_filter, obj);
1879
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
1880
    if (_tstate->jit_tracer_state == NULL) {
1881
        return;
1882
    }
1883
    if (bloom_filter_may_contain(&_tstate->jit_tracer_state->prev_state.dependencies, &obj_filter))
1884
    {
1885
        _tstate->jit_tracer_state->prev_state.dependencies_still_valid = false;
1886
    }
1887
}
1888
/* Invalidate all executors */
1889
void
1890
_Py_Executors_InvalidateAll(PyInterpreterState *interp, int is_invalidation)
1891
{
1892
    while (interp->executor_list_head) {
1893
        _PyExecutorObject *executor = interp->executor_list_head;
1894
        assert(executor->vm_data.valid);
1895
        if (executor->vm_data.code) {
1896
            // Clear the entire code object so its co_executors array be freed:
1897
            _PyCode_Clear_Executors(executor->vm_data.code);
1898
        }
1899
        else {
1900
            executor_invalidate((PyObject *)executor);
1901
        }
1902
        if (is_invalidation) {
1903
            OPT_STAT_INC(executors_invalidated);
1904
        }
1905
    }
1906
}
1907
1908
void
1909
_Py_Executors_InvalidateCold(PyInterpreterState *interp)
1910
{
1911
    /* Walk the list of executors */
1912
    /* TO DO -- Use a tree to avoid traversing as many objects */
1913
    PyObject *invalidate = PyList_New(0);
1914
    if (invalidate == NULL) {
1915
        goto error;
1916
    }
1917
1918
    /* Clearing an executor can deallocate others, so we need to make a list of
1919
     * executors to invalidate first */
1920
    for (_PyExecutorObject *exec = interp->executor_list_head; exec != NULL;) {
1921
        assert(exec->vm_data.valid);
1922
        _PyExecutorObject *next = exec->vm_data.links.next;
1923
1924
        if (exec->vm_data.cold && PyList_Append(invalidate, (PyObject *)exec) < 0) {
1925
            goto error;
1926
        }
1927
        else {
1928
            exec->vm_data.cold = true;
1929
        }
1930
1931
        exec = next;
1932
    }
1933
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(invalidate); i++) {
1934
        PyObject *exec = PyList_GET_ITEM(invalidate, i);
1935
        executor_invalidate(exec);
1936
    }
1937
    Py_DECREF(invalidate);
1938
    return;
1939
error:
1940
    PyErr_Clear();
1941
    Py_XDECREF(invalidate);
1942
    // If we're truly out of memory, wiping out everything is a fine fallback
1943
    _Py_Executors_InvalidateAll(interp, 0);
1944
}
1945
1946
static int
1947
escape_angles(const char *input, Py_ssize_t size, char *buffer) {
1948
    int written = 0;
1949
    for (Py_ssize_t i = 0; i < size; i++) {
1950
        char c = input[i];
1951
        if (c == '<' || c == '>') {
1952
            buffer[written++] = '&';
1953
            buffer[written++] = c == '>' ? 'g' : 'l';
1954
            buffer[written++] = 't';
1955
            buffer[written++] = ';';
1956
        }
1957
        else {
1958
            buffer[written++] = c;
1959
        }
1960
    }
1961
    return written;
1962
}
1963
1964
static void
1965
write_str(PyObject *str, FILE *out)
1966
{
1967
    // Encode the Unicode object to the specified encoding
1968
    PyObject *encoded_obj = PyUnicode_AsEncodedString(str, "utf8", "strict");
1969
    if (encoded_obj == NULL) {
1970
        PyErr_Clear();
1971
        return;
1972
    }
1973
    const char *encoded_str = PyBytes_AsString(encoded_obj);
1974
    Py_ssize_t encoded_size = PyBytes_Size(encoded_obj);
1975
    char buffer[120];
1976
    bool truncated = false;
1977
    if (encoded_size > 24) {
1978
        encoded_size = 24;
1979
        truncated = true;
1980
    }
1981
    int size = escape_angles(encoded_str, encoded_size, buffer);
1982
    fwrite(buffer, 1, size, out);
1983
    if (truncated) {
1984
        fwrite("...", 1, 3, out);
1985
    }
1986
    Py_DECREF(encoded_obj);
1987
}
1988
1989
static int
1990
find_line_number(PyCodeObject *code, _PyExecutorObject *executor)
1991
{
1992
    int code_len = (int)Py_SIZE(code);
1993
    for (int i = 0; i < code_len; i++) {
1994
        _Py_CODEUNIT *instr = &_PyCode_CODE(code)[i];
1995
        int opcode = instr->op.code;
1996
        if (opcode == ENTER_EXECUTOR) {
1997
            _PyExecutorObject *exec = code->co_executors->executors[instr->op.arg];
1998
            if (exec == executor) {
1999
                return PyCode_Addr2Line(code, i*2);
2000
            }
2001
        }
2002
        i += _PyOpcode_Caches[_Py_GetBaseCodeUnit(code, i).op.code];
2003
    }
2004
    return -1;
2005
}
2006
2007
#define RED "#ff0000"
2008
#define WHITE "#ffffff"
2009
#define BLUE "#0000ff"
2010
#define BLACK "#000000"
2011
#define LOOP "#00c000"
2012
2013
static const char *COLORS[10] = {
2014
    "9",
2015
    "8",
2016
    "7",
2017
    "6",
2018
    "5",
2019
    "4",
2020
    "3",
2021
    "2",
2022
    "1",
2023
    WHITE,
2024
};
2025
2026
#ifdef Py_STATS
2027
const char *
2028
get_background_color(_PyUOpInstruction const *inst, uint64_t max_hotness)
2029
{
2030
    uint64_t hotness = inst->execution_count;
2031
    int index = (hotness * 10)/max_hotness;
2032
    if (index > 9) {
2033
        index = 9;
2034
    }
2035
    if (index < 0) {
2036
        index = 0;
2037
    }
2038
    return COLORS[index];
2039
}
2040
2041
const char *
2042
get_foreground_color(_PyUOpInstruction const *inst, uint64_t max_hotness)
2043
{
2044
    if(_PyUop_Uncached[inst->opcode] == _DEOPT) {
2045
        return RED;
2046
    }
2047
    uint64_t hotness = inst->execution_count;
2048
    int index = (hotness * 10)/max_hotness;
2049
    if (index > 3) {
2050
        return BLACK;
2051
    }
2052
    return WHITE;
2053
}
2054
#endif
2055
2056
static void
2057
write_row_for_uop(_PyExecutorObject *executor, uint32_t i, FILE *out)
2058
{
2059
    /* Write row for uop.
2060
        * The `port` is a marker so that outgoing edges can
2061
        * be placed correctly. If a row is marked `port=17`,
2062
        * then the outgoing edge is `{EXEC_NAME}:17 -> {TARGET}`
2063
        * https://graphviz.readthedocs.io/en/stable/manual.html#node-ports-compass
2064
        */
2065
    _PyUOpInstruction const *inst = &executor->trace[i];
2066
    const char *opname = _PyOpcode_uop_name[inst->opcode];
2067
#ifdef Py_STATS
2068
    const char *bg_color = get_background_color(inst, executor->trace[0].execution_count);
2069
    const char *color = get_foreground_color(inst, executor->trace[0].execution_count);
2070
    fprintf(out, "        <tr><td port=\"i%d\" border=\"1\" color=\"%s\" bgcolor=\"%s\" ><font color=\"%s\"> %s &nbsp;--&nbsp; %" PRIu64 "</font></td></tr>\n",
2071
        i, color, bg_color, color, opname, inst->execution_count);
2072
#else
2073
    const char *color = (_PyUop_Uncached[inst->opcode] == _DEOPT) ? RED : BLACK;
2074
    fprintf(out, "        <tr><td port=\"i%d\" border=\"1\" color=\"%s\" >%s op0=%" PRIu64 "</td></tr>\n", i, color, opname, inst->operand0);
2075
#endif
2076
}
2077
2078
static bool
2079
is_stop(_PyUOpInstruction const *inst)
2080
{
2081
    uint16_t base_opcode = _PyUop_Uncached[inst->opcode];
2082
    return (base_opcode == _EXIT_TRACE || base_opcode == _DEOPT || base_opcode == _JUMP_TO_TOP);
2083
}
2084
2085
2086
/* Writes the node and outgoing edges for a single tracelet in graphviz format.
2087
 * Each tracelet is presented as a table of the uops it contains.
2088
 * If Py_STATS is enabled, execution counts are included.
2089
 *
2090
 * https://graphviz.readthedocs.io/en/stable/manual.html
2091
 * https://graphviz.org/gallery/
2092
 */
2093
static void
2094
executor_to_gv(_PyExecutorObject *executor, FILE *out)
2095
{
2096
    PyCodeObject *code = executor->vm_data.code;
2097
    fprintf(out, "executor_%p [\n", executor);
2098
    fprintf(out, "    shape = none\n");
2099
2100
    /* Write the HTML table for the uops */
2101
    fprintf(out, "    label = <<table border=\"0\" cellspacing=\"0\">\n");
2102
    fprintf(out, "        <tr><td port=\"start\" border=\"1\" ><b>Executor</b></td></tr>\n");
2103
    if (code == NULL) {
2104
        fprintf(out, "        <tr><td border=\"1\" >No code object</td></tr>\n");
2105
    }
2106
    else {
2107
        fprintf(out, "        <tr><td  border=\"1\" >");
2108
        write_str(code->co_qualname, out);
2109
        int line = find_line_number(code, executor);
2110
        fprintf(out, ": %d</td></tr>\n", line);
2111
    }
2112
    for (uint32_t i = 0; i < executor->code_size; i++) {
2113
        write_row_for_uop(executor, i, out);
2114
        if (is_stop(&executor->trace[i])) {
2115
            break;
2116
        }
2117
    }
2118
    fprintf(out, "    </table>>\n");
2119
    fprintf(out, "]\n\n");
2120
2121
    /* Write all the outgoing edges */
2122
    _PyExecutorObject *cold = _PyExecutor_GetColdExecutor();
2123
    _PyExecutorObject *cold_dynamic = _PyExecutor_GetColdDynamicExecutor();
2124
    for (uint32_t i = 0; i < executor->code_size; i++) {
2125
        _PyUOpInstruction const *inst = &executor->trace[i];
2126
        uint16_t base_opcode = _PyUop_Uncached[inst->opcode];
2127
        uint16_t flags = _PyUop_Flags[base_opcode];
2128
        _PyExitData *exit = NULL;
2129
        if (base_opcode == _JUMP_TO_TOP) {
2130
            fprintf(out, "executor_%p:i%d -> executor_%p:i%d [color = \"" LOOP "\"]\n", executor, i, executor, inst->jump_target);
2131
            break;
2132
        }
2133
        if (base_opcode == _EXIT_TRACE) {
2134
            exit = (_PyExitData *)inst->operand0;
2135
        }
2136
        else if (flags & HAS_EXIT_FLAG) {
2137
            assert(inst->format == UOP_FORMAT_JUMP);
2138
            _PyUOpInstruction const *exit_inst = &executor->trace[inst->jump_target];
2139
            uint16_t base_exit_opcode = _PyUop_Uncached[exit_inst->opcode];
2140
            assert(base_exit_opcode == _EXIT_TRACE || base_exit_opcode == _DYNAMIC_EXIT);
2141
            exit = (_PyExitData *)exit_inst->operand0;
2142
        }
2143
        if (exit != NULL) {
2144
            if (exit->executor == cold || exit->executor == cold_dynamic) {
2145
#ifdef Py_STATS
2146
                /* Only mark as have cold exit if it has actually exited */
2147
                uint64_t diff = inst->execution_count - executor->trace[i+1].execution_count;
2148
                if (diff) {
2149
                    fprintf(out, "cold_%p%d [ label = \"%"  PRIu64  "\" shape = ellipse color=\"" BLUE "\" ]\n", executor, i, diff);
2150
                    fprintf(out, "executor_%p:i%d -> cold_%p%d\n", executor, i, executor, i);
2151
                }
2152
#endif
2153
            }
2154
            else {
2155
                fprintf(out, "executor_%p:i%d -> executor_%p:start\n", executor, i, exit->executor);
2156
            }
2157
        }
2158
        if (is_stop(inst)) {
2159
            break;
2160
        }
2161
    }
2162
}
2163
2164
/* Write the graph of all the live tracelets in graphviz format. */
2165
int
2166
_PyDumpExecutors(FILE *out)
2167
{
2168
    fprintf(out, "digraph ideal {\n\n");
2169
    fprintf(out, "    rankdir = \"LR\"\n\n");
2170
    fprintf(out, "    node [colorscheme=greys9]\n");
2171
    PyInterpreterState *interp = PyInterpreterState_Get();
2172
    for (_PyExecutorObject *exec = interp->executor_list_head; exec != NULL;) {
2173
        executor_to_gv(exec, out);
2174
        exec = exec->vm_data.links.next;
2175
    }
2176
    fprintf(out, "}\n\n");
2177
    return 0;
2178
}
2179
2180
#else
2181
2182
int
2183
_PyDumpExecutors(FILE *out)
2184
0
{
2185
0
    PyErr_SetString(PyExc_NotImplementedError, "No JIT available");
2186
0
    return -1;
2187
0
}
2188
2189
void
2190
_PyExecutor_Free(struct _PyExecutorObject *self)
2191
0
{
2192
    /* This should never be called */
2193
0
    Py_UNREACHABLE();
2194
0
}
2195
2196
#endif /* _Py_TIER2 */