Coverage Report

Created: 2025-11-16 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Python/specialize.c
Line
Count
Source
1
#include "Python.h"
2
3
#include "opcode.h"
4
5
#include "pycore_code.h"
6
#include "pycore_critical_section.h"
7
#include "pycore_descrobject.h"   // _PyMethodWrapper_Type
8
#include "pycore_dict.h"          // DICT_KEYS_UNICODE
9
#include "pycore_function.h"      // _PyFunction_GetVersionForCurrentState()
10
#include "pycore_interpframe.h"   // FRAME_SPECIALS_SIZE
11
#include "pycore_list.h"          // _PyListIterObject
12
#include "pycore_long.h"          // _PyLong_IsNonNegativeCompact()
13
#include "pycore_moduleobject.h"
14
#include "pycore_object.h"
15
#include "pycore_opcode_metadata.h" // _PyOpcode_Caches
16
#include "pycore_uop_metadata.h"    // _PyOpcode_uop_name
17
#include "pycore_uop_ids.h"       // MAX_UOP_ID
18
#include "pycore_opcode_utils.h"  // RESUME_AT_FUNC_START
19
#include "pycore_pylifecycle.h"   // _PyOS_URandomNonblock()
20
#include "pycore_runtime.h"       // _Py_ID()
21
#include "pycore_unicodeobject.h" // _PyUnicodeASCIIIter_Type
22
23
#include <stdlib.h> // rand()
24
25
/* For guidance on adding or extending families of instructions see
26
 * InternalDocs/interpreter.md `Specialization` section.
27
 */
28
29
#if Py_STATS
30
#define SPECIALIZATION_FAIL(opcode, kind) \
31
do { \
32
    PyStats *s = _PyStats_GET(); \
33
    if (s) { \
34
        int _kind = (kind); \
35
        assert(_kind < SPECIALIZATION_FAILURE_KINDS); \
36
        s->opcode_stats[opcode].specialization.failure_kinds[_kind]++; \
37
    } \
38
} while (0)
39
#else
40
72.4k
#  define SPECIALIZATION_FAIL(opcode, kind) ((void)0)
41
#endif  // Py_STATS
42
43
// Initialize warmup counters and optimize instructions. This cannot fail.
44
void
45
_PyCode_Quicken(_Py_CODEUNIT *instructions, Py_ssize_t size, int enable_counters)
46
60.5k
{
47
60.5k
    #if ENABLE_SPECIALIZATION_FT
48
60.5k
    _Py_BackoffCounter jump_counter, adaptive_counter;
49
60.5k
    if (enable_counters) {
50
60.5k
        jump_counter = initial_jump_backoff_counter();
51
60.5k
        adaptive_counter = adaptive_counter_warmup();
52
60.5k
    }
53
0
    else {
54
0
        jump_counter = initial_unreachable_backoff_counter();
55
0
        adaptive_counter = initial_unreachable_backoff_counter();
56
0
    }
57
60.5k
    int opcode = 0;
58
60.5k
    int oparg = 0;
59
    /* The last code unit cannot have a cache, so we don't need to check it */
60
3.57M
    for (Py_ssize_t i = 0; i < size-1; i++) {
61
3.51M
        opcode = instructions[i].op.code;
62
3.51M
        int caches = _PyOpcode_Caches[opcode];
63
3.51M
        oparg = (oparg << 8) | instructions[i].op.arg;
64
3.51M
        if (caches) {
65
            // The initial value depends on the opcode
66
897k
            switch (opcode) {
67
16.9k
                case JUMP_BACKWARD:
68
16.9k
                    instructions[i + 1].counter = jump_counter;
69
16.9k
                    break;
70
95.9k
                case POP_JUMP_IF_FALSE:
71
115k
                case POP_JUMP_IF_TRUE:
72
118k
                case POP_JUMP_IF_NONE:
73
123k
                case POP_JUMP_IF_NOT_NONE:
74
123k
                    instructions[i + 1].cache = 0x5555;  // Alternating 0, 1 bits
75
123k
                    break;
76
757k
                default:
77
757k
                    instructions[i + 1].counter = adaptive_counter;
78
757k
                    break;
79
897k
            }
80
897k
            i += caches;
81
897k
        }
82
3.51M
        if (opcode != EXTENDED_ARG) {
83
3.42M
            oparg = 0;
84
3.42M
        }
85
3.51M
    }
86
60.5k
    #endif /* ENABLE_SPECIALIZATION_FT */
87
60.5k
}
88
89
32.9k
#define SIMPLE_FUNCTION 0
90
91
/* Common */
92
93
#define SPEC_FAIL_OTHER 0
94
#define SPEC_FAIL_NO_DICT 1
95
#define SPEC_FAIL_OVERRIDDEN 2
96
#define SPEC_FAIL_OUT_OF_VERSIONS 3
97
#define SPEC_FAIL_OUT_OF_RANGE 4
98
#define SPEC_FAIL_EXPECTED_ERROR 5
99
#define SPEC_FAIL_WRONG_NUMBER_ARGUMENTS 6
100
619
#define SPEC_FAIL_CODE_COMPLEX_PARAMETERS 7
101
12.2k
#define SPEC_FAIL_CODE_NOT_OPTIMIZED 8
102
103
104
#define SPEC_FAIL_LOAD_GLOBAL_NON_DICT 17
105
#define SPEC_FAIL_LOAD_GLOBAL_NON_STRING_OR_SPLIT 18
106
107
/* Super */
108
109
#define SPEC_FAIL_SUPER_BAD_CLASS 9
110
#define SPEC_FAIL_SUPER_SHADOWED 10
111
112
/* Attributes */
113
114
#define SPEC_FAIL_ATTR_OVERRIDING_DESCRIPTOR 9
115
#define SPEC_FAIL_ATTR_NON_OVERRIDING_DESCRIPTOR 10
116
#define SPEC_FAIL_ATTR_NOT_DESCRIPTOR 11
117
#define SPEC_FAIL_ATTR_METHOD 12
118
#define SPEC_FAIL_ATTR_MUTABLE_CLASS 13
119
#define SPEC_FAIL_ATTR_PROPERTY 14
120
#define SPEC_FAIL_ATTR_NON_OBJECT_SLOT 15
121
#define SPEC_FAIL_ATTR_READ_ONLY 16
122
#define SPEC_FAIL_ATTR_AUDITED_SLOT 17
123
#define SPEC_FAIL_ATTR_NOT_MANAGED_DICT 18
124
#define SPEC_FAIL_ATTR_NON_STRING 19
125
#define SPEC_FAIL_ATTR_MODULE_ATTR_NOT_FOUND 20
126
#define SPEC_FAIL_ATTR_SHADOWED 21
127
#define SPEC_FAIL_ATTR_BUILTIN_CLASS_METHOD 22
128
#define SPEC_FAIL_ATTR_CLASS_METHOD_OBJ 23
129
#define SPEC_FAIL_ATTR_OBJECT_SLOT 24
130
131
#define SPEC_FAIL_ATTR_INSTANCE_ATTRIBUTE 26
132
#define SPEC_FAIL_ATTR_METACLASS_ATTRIBUTE 27
133
#define SPEC_FAIL_ATTR_PROPERTY_NOT_PY_FUNCTION 28
134
#define SPEC_FAIL_ATTR_NOT_IN_KEYS 29
135
#define SPEC_FAIL_ATTR_NOT_IN_DICT 30
136
#define SPEC_FAIL_ATTR_CLASS_ATTR_SIMPLE 31
137
#define SPEC_FAIL_ATTR_CLASS_ATTR_DESCRIPTOR 32
138
#define SPEC_FAIL_ATTR_BUILTIN_CLASS_METHOD_OBJ 33
139
#define SPEC_FAIL_ATTR_METACLASS_OVERRIDDEN 34
140
#define SPEC_FAIL_ATTR_SPLIT_DICT 35
141
#define SPEC_FAIL_ATTR_DESCR_NOT_DEFERRED 36
142
143
/* Binary subscr and store subscr */
144
145
#define SPEC_FAIL_SUBSCR_ARRAY_INT 9
146
#define SPEC_FAIL_SUBSCR_ARRAY_SLICE 10
147
#define SPEC_FAIL_SUBSCR_LIST_SLICE 11
148
#define SPEC_FAIL_SUBSCR_BUFFER_INT 12
149
#define SPEC_FAIL_SUBSCR_BUFFER_SLICE 13
150
151
/* Store subscr */
152
#define SPEC_FAIL_SUBSCR_BYTEARRAY_INT 18
153
#define SPEC_FAIL_SUBSCR_BYTEARRAY_SLICE 19
154
#define SPEC_FAIL_SUBSCR_PY_SIMPLE 20
155
#define SPEC_FAIL_SUBSCR_PY_OTHER 21
156
#define SPEC_FAIL_SUBSCR_DICT_SUBCLASS_NO_OVERRIDE 22
157
#define SPEC_FAIL_SUBSCR_NOT_HEAP_TYPE 23
158
159
/* Binary op */
160
161
#define SPEC_FAIL_BINARY_OP_ADD_DIFFERENT_TYPES          9
162
#define SPEC_FAIL_BINARY_OP_ADD_OTHER                   10
163
#define SPEC_FAIL_BINARY_OP_AND_DIFFERENT_TYPES         11
164
#define SPEC_FAIL_BINARY_OP_AND_INT                     12
165
#define SPEC_FAIL_BINARY_OP_AND_OTHER                   13
166
#define SPEC_FAIL_BINARY_OP_FLOOR_DIVIDE                14
167
#define SPEC_FAIL_BINARY_OP_LSHIFT                      15
168
#define SPEC_FAIL_BINARY_OP_MATRIX_MULTIPLY             16
169
#define SPEC_FAIL_BINARY_OP_MULTIPLY_DIFFERENT_TYPES    17
170
#define SPEC_FAIL_BINARY_OP_MULTIPLY_OTHER              18
171
#define SPEC_FAIL_BINARY_OP_OR                          19
172
#define SPEC_FAIL_BINARY_OP_POWER                       20
173
#define SPEC_FAIL_BINARY_OP_REMAINDER                   21
174
#define SPEC_FAIL_BINARY_OP_RSHIFT                      22
175
#define SPEC_FAIL_BINARY_OP_SUBTRACT_DIFFERENT_TYPES    23
176
#define SPEC_FAIL_BINARY_OP_SUBTRACT_OTHER              24
177
#define SPEC_FAIL_BINARY_OP_TRUE_DIVIDE_DIFFERENT_TYPES 25
178
#define SPEC_FAIL_BINARY_OP_TRUE_DIVIDE_FLOAT           26
179
#define SPEC_FAIL_BINARY_OP_TRUE_DIVIDE_OTHER           27
180
#define SPEC_FAIL_BINARY_OP_XOR                         28
181
#define SPEC_FAIL_BINARY_OP_OR_INT                      29
182
#define SPEC_FAIL_BINARY_OP_OR_DIFFERENT_TYPES          30
183
#define SPEC_FAIL_BINARY_OP_XOR_INT                     31
184
#define SPEC_FAIL_BINARY_OP_XOR_DIFFERENT_TYPES         32
185
#define SPEC_FAIL_BINARY_OP_SUBSCR                      33
186
#define SPEC_FAIL_BINARY_OP_SUBSCR_LIST_SLICE           34
187
#define SPEC_FAIL_BINARY_OP_SUBSCR_TUPLE_SLICE          35
188
#define SPEC_FAIL_BINARY_OP_SUBSCR_STRING_SLICE         36
189
#define SPEC_FAIL_BINARY_OP_SUBSCR_NOT_HEAP_TYPE        37
190
#define SPEC_FAIL_BINARY_OP_SUBSCR_OTHER_SLICE          38
191
#define SPEC_FAIL_BINARY_OP_SUBSCR_MAPPINGPROXY         39
192
#define SPEC_FAIL_BINARY_OP_SUBSCR_RE_MATCH             40
193
#define SPEC_FAIL_BINARY_OP_SUBSCR_ARRAY                41
194
#define SPEC_FAIL_BINARY_OP_SUBSCR_DEQUE                42
195
#define SPEC_FAIL_BINARY_OP_SUBSCR_ENUMDICT             43
196
#define SPEC_FAIL_BINARY_OP_SUBSCR_STACKSUMMARY         44
197
#define SPEC_FAIL_BINARY_OP_SUBSCR_DEFAULTDICT          45
198
#define SPEC_FAIL_BINARY_OP_SUBSCR_COUNTER              46
199
#define SPEC_FAIL_BINARY_OP_SUBSCR_ORDEREDDICT          47
200
#define SPEC_FAIL_BINARY_OP_SUBSCR_BYTES                48
201
#define SPEC_FAIL_BINARY_OP_SUBSCR_STRUCTTIME           49
202
#define SPEC_FAIL_BINARY_OP_SUBSCR_RANGE                50
203
204
/* Calls */
205
206
#define SPEC_FAIL_CALL_INSTANCE_METHOD 11
207
#define SPEC_FAIL_CALL_CMETHOD 12
208
#define SPEC_FAIL_CALL_CFUNC_VARARGS 13
209
#define SPEC_FAIL_CALL_CFUNC_VARARGS_KEYWORDS 14
210
#define SPEC_FAIL_CALL_CFUNC_NOARGS 15
211
#define SPEC_FAIL_CALL_CFUNC_METHOD_FASTCALL_KEYWORDS 16
212
#define SPEC_FAIL_CALL_METH_DESCR_VARARGS 17
213
#define SPEC_FAIL_CALL_METH_DESCR_VARARGS_KEYWORDS 18
214
#define SPEC_FAIL_CALL_METH_DESCR_METHOD_FASTCALL_KEYWORDS 19
215
#define SPEC_FAIL_CALL_BAD_CALL_FLAGS 20
216
#define SPEC_FAIL_CALL_INIT_NOT_PYTHON 21
217
#define SPEC_FAIL_CALL_PEP_523 22
218
#define SPEC_FAIL_CALL_BOUND_METHOD 23
219
#define SPEC_FAIL_CALL_VECTORCALL 24
220
#define SPEC_FAIL_CALL_CLASS_MUTABLE 26
221
#define SPEC_FAIL_CALL_METHOD_WRAPPER 28
222
#define SPEC_FAIL_CALL_OPERATOR_WRAPPER 29
223
#define SPEC_FAIL_CALL_INIT_NOT_SIMPLE 30
224
#define SPEC_FAIL_CALL_METACLASS 31
225
#define SPEC_FAIL_CALL_INIT_NOT_INLINE_VALUES 32
226
227
/* COMPARE_OP */
228
#define SPEC_FAIL_COMPARE_OP_DIFFERENT_TYPES 12
229
#define SPEC_FAIL_COMPARE_OP_STRING 13
230
#define SPEC_FAIL_COMPARE_OP_BIG_INT 14
231
#define SPEC_FAIL_COMPARE_OP_BYTES 15
232
#define SPEC_FAIL_COMPARE_OP_TUPLE 16
233
#define SPEC_FAIL_COMPARE_OP_LIST 17
234
#define SPEC_FAIL_COMPARE_OP_SET 18
235
#define SPEC_FAIL_COMPARE_OP_BOOL 19
236
#define SPEC_FAIL_COMPARE_OP_BASEOBJECT 20
237
#define SPEC_FAIL_COMPARE_OP_FLOAT_LONG 21
238
#define SPEC_FAIL_COMPARE_OP_LONG_FLOAT 22
239
240
/* FOR_ITER and SEND */
241
#define SPEC_FAIL_ITER_GENERATOR 10
242
#define SPEC_FAIL_ITER_COROUTINE 11
243
#define SPEC_FAIL_ITER_ASYNC_GENERATOR 12
244
#define SPEC_FAIL_ITER_LIST 13
245
#define SPEC_FAIL_ITER_TUPLE 14
246
#define SPEC_FAIL_ITER_SET 15
247
#define SPEC_FAIL_ITER_STRING 16
248
#define SPEC_FAIL_ITER_BYTES 17
249
#define SPEC_FAIL_ITER_RANGE 18
250
#define SPEC_FAIL_ITER_ITERTOOLS 19
251
#define SPEC_FAIL_ITER_DICT_KEYS 20
252
#define SPEC_FAIL_ITER_DICT_ITEMS 21
253
#define SPEC_FAIL_ITER_DICT_VALUES 22
254
#define SPEC_FAIL_ITER_ENUMERATE 23
255
#define SPEC_FAIL_ITER_MAP 24
256
#define SPEC_FAIL_ITER_ZIP 25
257
#define SPEC_FAIL_ITER_SEQ_ITER 26
258
#define SPEC_FAIL_ITER_REVERSED_LIST 27
259
#define SPEC_FAIL_ITER_CALLABLE 28
260
#define SPEC_FAIL_ITER_ASCII_STRING 29
261
#define SPEC_FAIL_ITER_ASYNC_GENERATOR_SEND 30
262
#define SPEC_FAIL_ITER_SELF 31
263
264
// UNPACK_SEQUENCE
265
266
#define SPEC_FAIL_UNPACK_SEQUENCE_ITERATOR 9
267
#define SPEC_FAIL_UNPACK_SEQUENCE_SEQUENCE 10
268
269
// TO_BOOL
270
#define SPEC_FAIL_TO_BOOL_BYTEARRAY    9
271
#define SPEC_FAIL_TO_BOOL_BYTES       10
272
#define SPEC_FAIL_TO_BOOL_DICT        11
273
#define SPEC_FAIL_TO_BOOL_FLOAT       12
274
1.04k
#define SPEC_FAIL_TO_BOOL_MAPPING     13
275
#define SPEC_FAIL_TO_BOOL_MEMORY_VIEW 14
276
19
#define SPEC_FAIL_TO_BOOL_NUMBER      15
277
0
#define SPEC_FAIL_TO_BOOL_SEQUENCE    16
278
#define SPEC_FAIL_TO_BOOL_SET         17
279
#define SPEC_FAIL_TO_BOOL_TUPLE       18
280
281
// CONTAINS_OP
282
#define SPEC_FAIL_CONTAINS_OP_STR        9
283
#define SPEC_FAIL_CONTAINS_OP_TUPLE      10
284
#define SPEC_FAIL_CONTAINS_OP_LIST       11
285
#define SPEC_FAIL_CONTAINS_OP_USER_CLASS 12
286
287
static inline int
288
set_opcode(_Py_CODEUNIT *instr, uint8_t opcode)
289
371k
{
290
#ifdef Py_GIL_DISABLED
291
    uint8_t old_op = _Py_atomic_load_uint8_relaxed(&instr->op.code);
292
    if (old_op >= MIN_INSTRUMENTED_OPCODE) {
293
        /* Lost race with instrumentation */
294
        return 0;
295
    }
296
    if (!_Py_atomic_compare_exchange_uint8(&instr->op.code, &old_op, opcode)) {
297
        /* Lost race with instrumentation */
298
        assert(old_op >= MIN_INSTRUMENTED_OPCODE);
299
        return 0;
300
    }
301
    return 1;
302
#else
303
371k
    instr->op.code = opcode;
304
371k
    return 1;
305
371k
#endif
306
371k
}
307
308
static inline void
309
set_counter(_Py_BackoffCounter *counter, _Py_BackoffCounter value)
310
371k
{
311
371k
    FT_ATOMIC_STORE_UINT16_RELAXED(counter->value_and_backoff,
312
371k
                                   value.value_and_backoff);
313
371k
}
314
315
static inline _Py_BackoffCounter
316
load_counter(_Py_BackoffCounter *counter)
317
72.5k
{
318
72.5k
    _Py_BackoffCounter result = {
319
72.5k
        .value_and_backoff =
320
72.5k
            FT_ATOMIC_LOAD_UINT16_RELAXED(counter->value_and_backoff)};
321
72.5k
    return result;
322
72.5k
}
323
324
static inline void
325
specialize(_Py_CODEUNIT *instr, uint8_t specialized_opcode)
326
299k
{
327
299k
    assert(!PyErr_Occurred());
328
299k
    if (!set_opcode(instr, specialized_opcode)) {
329
0
        STAT_INC(_PyOpcode_Deopt[specialized_opcode], failure);
330
0
        SPECIALIZATION_FAIL(_PyOpcode_Deopt[specialized_opcode],
331
0
                            SPEC_FAIL_OTHER);
332
0
        return;
333
0
    }
334
299k
    STAT_INC(_PyOpcode_Deopt[specialized_opcode], success);
335
299k
    set_counter((_Py_BackoffCounter *)instr + 1, adaptive_counter_cooldown());
336
299k
}
337
338
static inline void
339
unspecialize(_Py_CODEUNIT *instr)
340
72.5k
{
341
72.5k
    assert(!PyErr_Occurred());
342
72.5k
    uint8_t opcode = FT_ATOMIC_LOAD_UINT8_RELAXED(instr->op.code);
343
72.5k
    uint8_t generic_opcode = _PyOpcode_Deopt[opcode];
344
72.5k
    STAT_INC(generic_opcode, failure);
345
72.5k
    if (!set_opcode(instr, generic_opcode)) {
346
0
        SPECIALIZATION_FAIL(generic_opcode, SPEC_FAIL_OTHER);
347
0
        return;
348
0
    }
349
72.5k
    _Py_BackoffCounter *counter = (_Py_BackoffCounter *)instr + 1;
350
72.5k
    _Py_BackoffCounter cur = load_counter(counter);
351
72.5k
    set_counter(counter, adaptive_counter_backoff(cur));
352
72.5k
}
353
354
static int function_kind(PyCodeObject *code);
355
static bool function_check_args(PyObject *o, int expected_argcount, int opcode);
356
static uint32_t function_get_version(PyObject *o, int opcode);
357
358
static int
359
specialize_module_load_attr_lock_held(PyDictObject *dict, _Py_CODEUNIT *instr, PyObject *name)
360
2.46k
{
361
2.46k
    _PyAttrCache *cache = (_PyAttrCache *)(instr + 1);
362
2.46k
    if (dict->ma_keys->dk_kind != DICT_KEYS_UNICODE) {
363
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_NON_STRING);
364
0
        return -1;
365
0
    }
366
2.46k
    Py_ssize_t index = _PyDict_LookupIndex(dict, &_Py_ID(__getattr__));
367
2.46k
    assert(index != DKIX_ERROR);
368
2.46k
    if (index != DKIX_EMPTY) {
369
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_MODULE_ATTR_NOT_FOUND);
370
0
        return -1;
371
0
    }
372
2.46k
    index = _PyDict_LookupIndex(dict, name);
373
2.46k
    assert (index != DKIX_ERROR);
374
2.46k
    if (index != (uint16_t)index) {
375
171
        SPECIALIZATION_FAIL(LOAD_ATTR,
376
171
                            index == DKIX_EMPTY ?
377
171
                            SPEC_FAIL_ATTR_MODULE_ATTR_NOT_FOUND :
378
171
                            SPEC_FAIL_OUT_OF_RANGE);
379
171
        return -1;
380
171
    }
381
2.29k
    uint32_t keys_version = _PyDict_GetKeysVersionForCurrentState(
382
2.29k
            _PyInterpreterState_GET(), dict);
383
2.29k
    if (keys_version == 0) {
384
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OUT_OF_VERSIONS);
385
0
        return -1;
386
0
    }
387
2.29k
    write_u32(cache->version, keys_version);
388
2.29k
    cache->index = (uint16_t)index;
389
2.29k
    specialize(instr, LOAD_ATTR_MODULE);
390
2.29k
    return 0;
391
2.29k
}
392
393
static int
394
specialize_module_load_attr(
395
    PyObject *owner, _Py_CODEUNIT *instr, PyObject *name)
396
2.46k
{
397
2.46k
    PyModuleObject *m = (PyModuleObject *)owner;
398
2.46k
    assert((Py_TYPE(owner)->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
399
2.46k
    PyDictObject *dict = (PyDictObject *)m->md_dict;
400
2.46k
    if (dict == NULL) {
401
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_NO_DICT);
402
0
        return -1;
403
0
    }
404
2.46k
    int result;
405
2.46k
    Py_BEGIN_CRITICAL_SECTION(dict);
406
2.46k
    result = specialize_module_load_attr_lock_held(dict, instr, name);
407
2.46k
    Py_END_CRITICAL_SECTION();
408
2.46k
    return result;
409
2.46k
}
410
411
/* Attribute specialization */
412
413
Py_NO_INLINE void
414
116
_Py_Specialize_LoadSuperAttr(_PyStackRef global_super_st, _PyStackRef cls_st, _Py_CODEUNIT *instr, int load_method) {
415
116
    PyObject *global_super = PyStackRef_AsPyObjectBorrow(global_super_st);
416
116
    PyObject *cls = PyStackRef_AsPyObjectBorrow(cls_st);
417
418
116
    assert(ENABLE_SPECIALIZATION_FT);
419
116
    assert(_PyOpcode_Caches[LOAD_SUPER_ATTR] == INLINE_CACHE_ENTRIES_LOAD_SUPER_ATTR);
420
116
    if (global_super != (PyObject *)&PySuper_Type) {
421
0
        SPECIALIZATION_FAIL(LOAD_SUPER_ATTR, SPEC_FAIL_SUPER_SHADOWED);
422
0
        goto fail;
423
0
    }
424
116
    if (!PyType_Check(cls)) {
425
0
        SPECIALIZATION_FAIL(LOAD_SUPER_ATTR, SPEC_FAIL_SUPER_BAD_CLASS);
426
0
        goto fail;
427
0
    }
428
116
    uint8_t load_code = load_method ? LOAD_SUPER_ATTR_METHOD : LOAD_SUPER_ATTR_ATTR;
429
116
    specialize(instr, load_code);
430
116
    return;
431
0
fail:
432
0
    unspecialize(instr);
433
0
}
434
435
typedef enum {
436
    OVERRIDING, /* Is an overriding descriptor, and will remain so. */
437
    METHOD, /* Attribute has Py_TPFLAGS_METHOD_DESCRIPTOR set */
438
    PROPERTY, /* Is a property */
439
    OBJECT_SLOT, /* Is an object slot descriptor */
440
    OTHER_SLOT, /* Is a slot descriptor of another type */
441
    NON_OVERRIDING, /* Is another non-overriding descriptor, and is an instance of an immutable class*/
442
    BUILTIN_CLASSMETHOD, /* Builtin methods with METH_CLASS */
443
    PYTHON_CLASSMETHOD, /* Python classmethod(func) object */
444
    NON_DESCRIPTOR, /* Is not a descriptor, and is an instance of an immutable class */
445
    MUTABLE,   /* Instance of a mutable class; might, or might not, be a descriptor */
446
    ABSENT, /* Attribute is not present on the class */
447
    DUNDER_CLASS, /* __class__ attribute */
448
    GETSET_OVERRIDDEN, /* __getattribute__ or __setattr__ has been overridden */
449
    GETATTRIBUTE_IS_PYTHON_FUNCTION  /* Descriptor requires calling a Python __getattribute__ */
450
} DescriptorClassification;
451
452
453
static DescriptorClassification
454
classify_descriptor(PyObject *descriptor, bool has_getattr)
455
14.6k
{
456
14.6k
    if (descriptor == NULL) {
457
5.46k
        return ABSENT;
458
5.46k
    }
459
9.15k
    PyTypeObject *desc_cls = Py_TYPE(descriptor);
460
9.15k
    if (!(desc_cls->tp_flags & Py_TPFLAGS_IMMUTABLETYPE)) {
461
6
        return MUTABLE;
462
6
    }
463
9.14k
    if (desc_cls->tp_descr_set) {
464
1.42k
        if (desc_cls == &PyMemberDescr_Type) {
465
350
            PyMemberDescrObject *member = (PyMemberDescrObject *)descriptor;
466
350
            struct PyMemberDef *dmem = member->d_member;
467
350
            if (dmem->type == Py_T_OBJECT_EX || dmem->type == _Py_T_OBJECT) {
468
312
                return OBJECT_SLOT;
469
312
            }
470
38
            return OTHER_SLOT;
471
350
        }
472
1.07k
        if (desc_cls == &PyProperty_Type) {
473
            /* We can't detect at runtime whether an attribute exists
474
               with property. So that means we may have to call
475
               __getattr__. */
476
250
            return has_getattr ? GETSET_OVERRIDDEN : PROPERTY;
477
250
        }
478
826
        return OVERRIDING;
479
1.07k
    }
480
7.72k
    if (desc_cls->tp_descr_get) {
481
7.27k
        if (desc_cls->tp_flags & Py_TPFLAGS_METHOD_DESCRIPTOR) {
482
6.24k
            return METHOD;
483
6.24k
        }
484
1.02k
        if (Py_IS_TYPE(descriptor, &PyClassMethodDescr_Type)) {
485
150
            return BUILTIN_CLASSMETHOD;
486
150
        }
487
878
        if (Py_IS_TYPE(descriptor, &PyClassMethod_Type)) {
488
377
            return PYTHON_CLASSMETHOD;
489
377
        }
490
501
        return NON_OVERRIDING;
491
878
    }
492
449
    return NON_DESCRIPTOR;
493
7.72k
}
494
495
static bool
496
descriptor_is_class(PyObject *descriptor, PyObject *name)
497
12.6k
{
498
12.6k
    return ((PyUnicode_CompareWithASCIIString(name, "__class__") == 0) &&
499
24
            (descriptor == _PyType_Lookup(&PyBaseObject_Type, name)));
500
12.6k
}
501
502
static DescriptorClassification
503
10.5k
analyze_descriptor_load(PyTypeObject *type, PyObject *name, PyObject **descr, unsigned int *tp_version) {
504
10.5k
    bool has_getattr = false;
505
10.5k
    bool have_ga_version = false;
506
10.5k
    unsigned int ga_version;
507
10.5k
    getattrofunc getattro_slot = type->tp_getattro;
508
10.5k
    if (getattro_slot == PyObject_GenericGetAttr) {
509
        /* Normal attribute lookup; */
510
10.5k
        has_getattr = false;
511
10.5k
    }
512
91
    else if (getattro_slot == _Py_slot_tp_getattr_hook ||
513
91
        getattro_slot == _Py_slot_tp_getattro) {
514
        /* One or both of __getattribute__ or __getattr__ may have been
515
         overridden See typeobject.c for why these functions are special. */
516
0
        PyObject *getattribute = _PyType_LookupRefAndVersion(type,
517
0
                &_Py_ID(__getattribute__), &ga_version);
518
0
        have_ga_version = true;
519
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
520
0
        bool has_custom_getattribute = getattribute != NULL &&
521
0
            getattribute != interp->callable_cache.object__getattribute__;
522
0
        PyObject *getattr = _PyType_Lookup(type, &_Py_ID(__getattr__));
523
0
        has_getattr = getattr != NULL;
524
0
        if (has_custom_getattribute) {
525
0
            if (!has_getattr &&
526
0
                Py_IS_TYPE(getattribute, &PyFunction_Type)) {
527
0
                *descr = getattribute;
528
0
                *tp_version = ga_version;
529
0
                return GETATTRIBUTE_IS_PYTHON_FUNCTION;
530
0
            }
531
            /* Potentially both __getattr__ and __getattribute__ are set.
532
               Too complicated */
533
0
            Py_DECREF(getattribute);
534
0
            *descr = NULL;
535
0
            *tp_version = ga_version;
536
0
            return GETSET_OVERRIDDEN;
537
0
        }
538
        /* Potentially has __getattr__ but no custom __getattribute__.
539
           Fall through to usual descriptor analysis.
540
           Usual attribute lookup should only be allowed at runtime
541
           if we can guarantee that there is no way an exception can be
542
           raised. This means some specializations, e.g. specializing
543
           for property() isn't safe.
544
        */
545
0
        Py_XDECREF(getattribute);
546
0
    }
547
91
    else {
548
91
        *descr = NULL;
549
91
        *tp_version = FT_ATOMIC_LOAD_UINT_RELAXED(type->tp_version_tag);
550
91
        return GETSET_OVERRIDDEN;
551
91
    }
552
10.5k
    unsigned int descr_version;
553
10.5k
    PyObject *descriptor = _PyType_LookupRefAndVersion(type, name, &descr_version);
554
10.5k
    *descr = descriptor;
555
10.5k
    *tp_version = have_ga_version ? ga_version : descr_version;
556
10.5k
    if (descriptor_is_class(descriptor, name)) {
557
24
        return DUNDER_CLASS;
558
24
    }
559
10.4k
    return classify_descriptor(descriptor, has_getattr);
560
10.5k
}
561
562
static DescriptorClassification
563
analyze_descriptor_store(PyTypeObject *type, PyObject *name, PyObject **descr, unsigned int *tp_version)
564
2.21k
{
565
2.21k
    if (type->tp_setattro != PyObject_GenericSetAttr) {
566
100
        *descr = NULL;
567
100
        return GETSET_OVERRIDDEN;
568
100
    }
569
2.11k
    PyObject *descriptor = _PyType_LookupRefAndVersion(type, name, tp_version);
570
2.11k
    *descr = descriptor;
571
2.11k
    if (descriptor_is_class(descriptor, name)) {
572
0
        return DUNDER_CLASS;
573
0
    }
574
2.11k
    return classify_descriptor(descriptor, false);
575
2.11k
}
576
577
static int
578
specialize_dict_access_inline(
579
    PyObject *owner, _Py_CODEUNIT *instr, PyTypeObject *type,
580
    PyObject *name, unsigned int tp_version,
581
    int base_op, int values_op)
582
3.60k
{
583
3.60k
    _PyAttrCache *cache = (_PyAttrCache *)(instr + 1);
584
3.60k
    PyDictKeysObject *keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
585
3.60k
    assert(PyUnicode_CheckExact(name));
586
3.60k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(owner);
587
3.60k
    Py_ssize_t index = _PyDictKeys_StringLookupSplit(keys, name);
588
3.60k
    assert (index != DKIX_ERROR);
589
3.60k
    if (index == DKIX_EMPTY) {
590
0
        SPECIALIZATION_FAIL(base_op, SPEC_FAIL_ATTR_NOT_IN_KEYS);
591
0
        return 0;
592
0
    }
593
3.60k
    assert(index >= 0);
594
3.60k
    assert(_PyObject_InlineValues(owner)->valid);
595
3.60k
    char *value_addr = (char *)&_PyObject_InlineValues(owner)->values[index];
596
3.60k
    Py_ssize_t offset = value_addr - (char *)owner;
597
3.60k
    if (offset != (uint16_t)offset) {
598
0
        SPECIALIZATION_FAIL(base_op, SPEC_FAIL_OUT_OF_RANGE);
599
0
        return 0;
600
0
    }
601
3.60k
    cache->index = (uint16_t)offset;
602
3.60k
    write_u32(cache->version, tp_version);
603
3.60k
    specialize(instr, values_op);
604
3.60k
    return 1;
605
3.60k
}
606
607
static int
608
specialize_dict_access_hint(
609
    PyDictObject *dict, _Py_CODEUNIT *instr, PyTypeObject *type,
610
    PyObject *name, unsigned int tp_version,
611
    int base_op, int hint_op)
612
124
{
613
124
    _PyAttrCache *cache = (_PyAttrCache *)(instr + 1);
614
615
124
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(dict);
616
#ifdef Py_GIL_DISABLED
617
    _PyDict_EnsureSharedOnRead(dict);
618
#endif
619
620
    // We found an instance with a __dict__.
621
124
    if (_PyDict_HasSplitTable(dict)) {
622
124
        SPECIALIZATION_FAIL(base_op, SPEC_FAIL_ATTR_SPLIT_DICT);
623
124
        return 0;
624
124
    }
625
0
    Py_ssize_t index = _PyDict_LookupIndex(dict, name);
626
0
    if (index != (uint16_t)index) {
627
0
        SPECIALIZATION_FAIL(base_op,
628
0
                            index == DKIX_EMPTY ?
629
0
                            SPEC_FAIL_ATTR_NOT_IN_DICT :
630
0
                            SPEC_FAIL_OUT_OF_RANGE);
631
0
        return 0;
632
0
    }
633
0
    cache->index = (uint16_t)index;
634
0
    write_u32(cache->version, tp_version);
635
0
    specialize(instr, hint_op);
636
0
    return 1;
637
0
}
638
639
640
static int
641
specialize_dict_access(
642
    PyObject *owner, _Py_CODEUNIT *instr, PyTypeObject *type,
643
    DescriptorClassification kind, PyObject *name, unsigned int tp_version,
644
    int base_op, int values_op, int hint_op)
645
4.02k
{
646
4.02k
    assert(kind == NON_OVERRIDING || kind == NON_DESCRIPTOR || kind == ABSENT ||
647
4.02k
        kind == BUILTIN_CLASSMETHOD || kind == PYTHON_CLASSMETHOD ||
648
4.02k
        kind == METHOD);
649
    // No descriptor, or non overriding.
650
4.02k
    if ((type->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
651
219
        SPECIALIZATION_FAIL(base_op, SPEC_FAIL_ATTR_NOT_MANAGED_DICT);
652
219
        return 0;
653
219
    }
654
3.80k
    if (type->tp_flags & Py_TPFLAGS_INLINE_VALUES &&
655
3.60k
        FT_ATOMIC_LOAD_UINT8(_PyObject_InlineValues(owner)->valid) &&
656
3.60k
        !(base_op == STORE_ATTR && _PyObject_GetManagedDict(owner) != NULL))
657
3.60k
    {
658
3.60k
        int res;
659
3.60k
        Py_BEGIN_CRITICAL_SECTION(owner);
660
3.60k
        PyDictObject *dict = _PyObject_GetManagedDict(owner);
661
3.60k
        if (dict == NULL) {
662
            // managed dict, not materialized, inline values valid
663
3.60k
            res = specialize_dict_access_inline(owner, instr, type, name,
664
3.60k
                                                tp_version, base_op, values_op);
665
3.60k
        }
666
0
        else {
667
            // lost race and dict was created, fail specialization
668
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_OTHER);
669
0
            res = 0;
670
0
        }
671
3.60k
        Py_END_CRITICAL_SECTION();
672
3.60k
        return res;
673
3.60k
    }
674
197
    else {
675
197
        PyDictObject *dict = _PyObject_GetManagedDict(owner);
676
197
        if (dict == NULL || !PyDict_CheckExact(dict)) {
677
73
            SPECIALIZATION_FAIL(base_op, SPEC_FAIL_NO_DICT);
678
73
            return 0;
679
73
        }
680
124
        int res;
681
124
        Py_BEGIN_CRITICAL_SECTION(dict);
682
        // materialized managed dict
683
124
        res = specialize_dict_access_hint(dict, instr, type, name,
684
124
                                          tp_version, base_op, hint_op);
685
124
        Py_END_CRITICAL_SECTION();
686
124
        return res;
687
197
    }
688
3.80k
}
689
690
static int
691
specialize_attr_loadclassattr(PyObject *owner, _Py_CODEUNIT *instr,
692
                              PyObject *name, PyObject *descr,
693
                              unsigned int tp_version,
694
                              DescriptorClassification kind, bool is_method,
695
                              uint32_t shared_keys_version);
696
static int specialize_class_load_attr(PyObject* owner, _Py_CODEUNIT* instr, PyObject* name);
697
698
/* Returns true if instances of obj's class are
699
 * likely to have `name` in their __dict__.
700
 * For objects with inline values, we check in the shared keys.
701
 * For other objects, we check their actual dictionary.
702
 */
703
static bool
704
instance_has_key(PyObject *obj, PyObject *name, uint32_t *shared_keys_version)
705
9.20k
{
706
9.20k
    PyTypeObject *cls = Py_TYPE(obj);
707
9.20k
    if ((cls->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
708
3.74k
        return false;
709
3.74k
    }
710
5.45k
    if (cls->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
711
5.15k
        PyDictKeysObject *keys = ((PyHeapTypeObject *)cls)->ht_cached_keys;
712
5.15k
        Py_ssize_t index =
713
5.15k
            _PyDictKeys_StringLookupAndVersion(keys, name, shared_keys_version);
714
5.15k
        return index >= 0;
715
5.15k
    }
716
304
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
717
304
    if (dict == NULL || !PyDict_CheckExact(dict)) {
718
0
        return false;
719
0
    }
720
304
    bool result;
721
304
    Py_BEGIN_CRITICAL_SECTION(dict);
722
304
    if (dict->ma_values) {
723
304
        result = false;
724
304
    }
725
0
    else {
726
0
        result = (_PyDict_LookupIndex(dict, name) >= 0);
727
0
    }
728
304
    Py_END_CRITICAL_SECTION();
729
304
    return result;
730
304
}
731
732
static int
733
do_specialize_instance_load_attr(PyObject* owner, _Py_CODEUNIT* instr, PyObject* name,
734
                                 bool shadow, uint32_t shared_keys_version,
735
                                 DescriptorClassification kind, PyObject *descr, unsigned int tp_version)
736
9.20k
{
737
9.20k
    _PyAttrCache *cache = (_PyAttrCache *)(instr + 1);
738
9.20k
    PyTypeObject *type = Py_TYPE(owner);
739
9.20k
    if (tp_version == 0) {
740
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OUT_OF_VERSIONS);
741
0
        return -1;
742
0
    }
743
9.20k
    uint8_t oparg = FT_ATOMIC_LOAD_UINT8_RELAXED(instr->op.arg);
744
9.20k
    switch(kind) {
745
153
        case OVERRIDING:
746
153
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_OVERRIDING_DESCRIPTOR);
747
153
            return -1;
748
6.06k
        case METHOD:
749
6.06k
        {
750
6.06k
            if (shadow) {
751
0
                goto try_instance;
752
0
            }
753
6.06k
            if (oparg & 1) {
754
2.21k
                if (specialize_attr_loadclassattr(owner, instr, name, descr,
755
2.21k
                                                  tp_version, kind, true,
756
2.21k
                                                  shared_keys_version)) {
757
2.05k
                    return 0;
758
2.05k
                }
759
164
                else {
760
164
                    return -1;
761
164
                }
762
2.21k
            }
763
3.84k
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_METHOD);
764
3.84k
            return -1;
765
6.06k
        }
766
228
        case PROPERTY:
767
228
        {
768
228
            _PyLoadMethodCache *lm_cache = (_PyLoadMethodCache *)(instr + 1);
769
228
            assert(Py_TYPE(descr) == &PyProperty_Type);
770
228
            PyObject *fget = ((_PyPropertyObject *)descr)->prop_get;
771
228
            if (fget == NULL) {
772
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_EXPECTED_ERROR);
773
0
                return -1;
774
0
            }
775
228
            if (!Py_IS_TYPE(fget, &PyFunction_Type)) {
776
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_PROPERTY_NOT_PY_FUNCTION);
777
0
                return -1;
778
0
            }
779
228
            if (!function_check_args(fget, 1, LOAD_ATTR)) {
780
0
                return -1;
781
0
            }
782
228
            if (oparg & 1) {
783
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_METHOD);
784
0
                return -1;
785
0
            }
786
            /* Don't specialize if PEP 523 is active */
787
228
            if (_PyInterpreterState_GET()->eval_frame) {
788
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OTHER);
789
0
                return -1;
790
0
            }
791
            #ifdef Py_GIL_DISABLED
792
            if (!_PyObject_HasDeferredRefcount(fget)) {
793
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_DESCR_NOT_DEFERRED);
794
                return -1;
795
            }
796
            #endif
797
228
            assert(tp_version != 0);
798
228
            write_u32(lm_cache->type_version, tp_version);
799
            /* borrowed */
800
228
            write_ptr(lm_cache->descr, fget);
801
228
            specialize(instr, LOAD_ATTR_PROPERTY);
802
228
            return 0;
803
228
        }
804
229
        case OBJECT_SLOT:
805
229
        {
806
229
            PyMemberDescrObject *member = (PyMemberDescrObject *)descr;
807
229
            struct PyMemberDef *dmem = member->d_member;
808
229
            Py_ssize_t offset = dmem->offset;
809
229
            if (!PyObject_TypeCheck(owner, member->d_common.d_type)) {
810
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_EXPECTED_ERROR);
811
0
                return -1;
812
0
            }
813
229
            if (dmem->flags & Py_AUDIT_READ) {
814
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_AUDITED_SLOT);
815
0
                return -1;
816
0
            }
817
229
            if (offset != (uint16_t)offset) {
818
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OUT_OF_RANGE);
819
0
                return -1;
820
0
            }
821
229
            assert(dmem->type == Py_T_OBJECT_EX || dmem->type == _Py_T_OBJECT);
822
229
            assert(offset > 0);
823
229
            cache->index = (uint16_t)offset;
824
229
            write_u32(cache->version, tp_version);
825
229
            specialize(instr, LOAD_ATTR_SLOT);
826
229
            return 0;
827
229
        }
828
24
        case DUNDER_CLASS:
829
24
        {
830
24
            Py_ssize_t offset = offsetof(PyObject, ob_type);
831
24
            assert(offset == (uint16_t)offset);
832
24
            cache->index = (uint16_t)offset;
833
24
            write_u32(cache->version, tp_version);
834
24
            specialize(instr, LOAD_ATTR_SLOT);
835
24
            return 0;
836
24
        }
837
38
        case OTHER_SLOT:
838
38
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_NON_OBJECT_SLOT);
839
38
            return -1;
840
6
        case MUTABLE:
841
6
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_MUTABLE_CLASS);
842
6
            return -1;
843
0
        case GETSET_OVERRIDDEN:
844
0
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OVERRIDDEN);
845
0
            return -1;
846
0
        case GETATTRIBUTE_IS_PYTHON_FUNCTION:
847
0
        {
848
0
            assert(Py_IS_TYPE(descr, &PyFunction_Type));
849
0
            _PyLoadMethodCache *lm_cache = (_PyLoadMethodCache *)(instr + 1);
850
0
            if (!function_check_args(descr, 2, LOAD_ATTR)) {
851
0
                return -1;
852
0
            }
853
0
            if (oparg & 1) {
854
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_METHOD);
855
0
                return -1;
856
0
            }
857
0
            uint32_t version = function_get_version(descr, LOAD_ATTR);
858
0
            if (version == 0) {
859
0
                return -1;
860
0
            }
861
            /* Don't specialize if PEP 523 is active */
862
0
            if (_PyInterpreterState_GET()->eval_frame) {
863
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OTHER);
864
0
                return -1;
865
0
            }
866
            #ifdef Py_GIL_DISABLED
867
            if (!_PyObject_HasDeferredRefcount(descr)) {
868
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_DESCR_NOT_DEFERRED);
869
                return -1;
870
            }
871
            #endif
872
0
            write_u32(lm_cache->keys_version, version);
873
            /* borrowed */
874
0
            write_ptr(lm_cache->descr, descr);
875
0
            write_u32(lm_cache->type_version, tp_version);
876
0
            specialize(instr, LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN);
877
0
            return 0;
878
0
        }
879
0
        case BUILTIN_CLASSMETHOD:
880
0
        case PYTHON_CLASSMETHOD:
881
97
        case NON_OVERRIDING:
882
97
            if (shadow) {
883
0
                goto try_instance;
884
0
            }
885
97
            return -1;
886
77
        case NON_DESCRIPTOR:
887
77
            if (shadow) {
888
0
                goto try_instance;
889
0
            }
890
77
            if ((oparg & 1) == 0) {
891
77
                if (specialize_attr_loadclassattr(owner, instr, name, descr,
892
77
                                                  tp_version, kind, false,
893
77
                                                  shared_keys_version)) {
894
27
                    return 0;
895
27
                }
896
77
            }
897
50
            return -1;
898
2.28k
        case ABSENT:
899
2.28k
            if (shadow) {
900
2.07k
                goto try_instance;
901
2.07k
            }
902
216
            set_counter((_Py_BackoffCounter*)instr + 1, adaptive_counter_cooldown());
903
216
            return 0;
904
9.20k
    }
905
9.20k
    Py_UNREACHABLE();
906
2.07k
try_instance:
907
2.07k
    if (specialize_dict_access(owner, instr, type, kind, name, tp_version,
908
2.07k
                               LOAD_ATTR, LOAD_ATTR_INSTANCE_VALUE, LOAD_ATTR_WITH_HINT))
909
2.07k
    {
910
2.07k
        return 0;
911
2.07k
    }
912
0
    return -1;
913
2.07k
}
914
915
static int
916
specialize_instance_load_attr(PyObject* owner, _Py_CODEUNIT* instr, PyObject* name)
917
9.20k
{
918
    // 0 is not a valid version
919
9.20k
    uint32_t shared_keys_version = 0;
920
9.20k
    bool shadow = instance_has_key(owner, name, &shared_keys_version);
921
9.20k
    PyObject *descr = NULL;
922
9.20k
    unsigned int tp_version = 0;
923
9.20k
    PyTypeObject *type = Py_TYPE(owner);
924
9.20k
    DescriptorClassification kind = analyze_descriptor_load(type, name, &descr, &tp_version);
925
9.20k
    int result = do_specialize_instance_load_attr(owner, instr, name, shadow, shared_keys_version, kind, descr, tp_version);
926
9.20k
    Py_XDECREF(descr);
927
9.20k
    return result;
928
9.20k
}
929
930
Py_NO_INLINE void
931
_Py_Specialize_LoadAttr(_PyStackRef owner_st, _Py_CODEUNIT *instr, PyObject *name)
932
13.6k
{
933
13.6k
    PyObject *owner = PyStackRef_AsPyObjectBorrow(owner_st);
934
935
13.6k
    assert(ENABLE_SPECIALIZATION_FT);
936
13.6k
    assert(_PyOpcode_Caches[LOAD_ATTR] == INLINE_CACHE_ENTRIES_LOAD_ATTR);
937
13.6k
    PyTypeObject *type = Py_TYPE(owner);
938
13.6k
    bool fail;
939
13.6k
    if (!_PyType_IsReady(type)) {
940
        // We *might* not really need this check, but we inherited it from
941
        // PyObject_GenericGetAttr and friends... and this way we still do the
942
        // right thing if someone forgets to call PyType_Ready(type):
943
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OTHER);
944
0
        fail = true;
945
0
    }
946
13.6k
    else if (Py_TYPE(owner)->tp_getattro == PyModule_Type.tp_getattro) {
947
2.46k
        fail = specialize_module_load_attr(owner, instr, name);
948
2.46k
    }
949
11.2k
    else if (PyType_Check(owner)) {
950
2.01k
        fail = specialize_class_load_attr(owner, instr, name);
951
2.01k
    }
952
9.20k
    else {
953
9.20k
        fail = specialize_instance_load_attr(owner, instr, name);
954
9.20k
    }
955
956
13.6k
    if (fail) {
957
6.14k
        unspecialize(instr);
958
6.14k
    }
959
13.6k
}
960
961
Py_NO_INLINE void
962
_Py_Specialize_StoreAttr(_PyStackRef owner_st, _Py_CODEUNIT *instr, PyObject *name)
963
2.64k
{
964
2.64k
    PyObject *owner = PyStackRef_AsPyObjectBorrow(owner_st);
965
966
2.64k
    assert(ENABLE_SPECIALIZATION_FT);
967
2.64k
    assert(_PyOpcode_Caches[STORE_ATTR] == INLINE_CACHE_ENTRIES_STORE_ATTR);
968
2.64k
    PyObject *descr = NULL;
969
2.64k
    _PyAttrCache *cache = (_PyAttrCache *)(instr + 1);
970
2.64k
    PyTypeObject *type = Py_TYPE(owner);
971
2.64k
    if (!_PyType_IsReady(type)) {
972
        // We *might* not really need this check, but we inherited it from
973
        // PyObject_GenericSetAttr and friends... and this way we still do the
974
        // right thing if someone forgets to call PyType_Ready(type):
975
0
        SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_OTHER);
976
0
        goto fail;
977
0
    }
978
2.64k
    if (PyModule_CheckExact(owner)) {
979
432
        SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_OVERRIDDEN);
980
432
        goto fail;
981
432
    }
982
2.21k
    unsigned int tp_version = 0;
983
2.21k
    DescriptorClassification kind = analyze_descriptor_store(type, name, &descr, &tp_version);
984
2.21k
    if (tp_version == 0) {
985
100
        goto fail;
986
100
    }
987
2.21k
    assert(descr != NULL || kind == ABSENT || kind == GETSET_OVERRIDDEN);
988
2.11k
    switch(kind) {
989
52
        case OVERRIDING:
990
52
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_OVERRIDING_DESCRIPTOR);
991
52
            goto fail;
992
0
        case METHOD:
993
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_METHOD);
994
0
            goto fail;
995
22
        case PROPERTY:
996
22
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_PROPERTY);
997
22
            goto fail;
998
83
        case OBJECT_SLOT:
999
83
        {
1000
83
            PyMemberDescrObject *member = (PyMemberDescrObject *)descr;
1001
83
            struct PyMemberDef *dmem = member->d_member;
1002
83
            Py_ssize_t offset = dmem->offset;
1003
83
            if (!PyObject_TypeCheck(owner, member->d_common.d_type)) {
1004
0
                SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_EXPECTED_ERROR);
1005
0
                goto fail;
1006
0
            }
1007
83
            if (dmem->flags & Py_READONLY) {
1008
0
                SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_READ_ONLY);
1009
0
                goto fail;
1010
0
            }
1011
83
            if (offset != (uint16_t)offset) {
1012
0
                SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_OUT_OF_RANGE);
1013
0
                goto fail;
1014
0
            }
1015
83
            assert(dmem->type == Py_T_OBJECT_EX || dmem->type == _Py_T_OBJECT);
1016
83
            assert(offset > 0);
1017
83
            cache->index = (uint16_t)offset;
1018
83
            write_u32(cache->version, tp_version);
1019
83
            specialize(instr, STORE_ATTR_SLOT);
1020
83
            goto success;
1021
83
        }
1022
0
        case DUNDER_CLASS:
1023
0
        case OTHER_SLOT:
1024
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_NON_OBJECT_SLOT);
1025
0
            goto fail;
1026
0
        case MUTABLE:
1027
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_MUTABLE_CLASS);
1028
0
            goto fail;
1029
0
        case GETATTRIBUTE_IS_PYTHON_FUNCTION:
1030
0
        case GETSET_OVERRIDDEN:
1031
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_OVERRIDDEN);
1032
0
            goto fail;
1033
0
        case BUILTIN_CLASSMETHOD:
1034
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_BUILTIN_CLASS_METHOD_OBJ);
1035
0
            goto fail;
1036
0
        case PYTHON_CLASSMETHOD:
1037
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_CLASS_METHOD_OBJ);
1038
0
            goto fail;
1039
0
        case NON_OVERRIDING:
1040
0
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_CLASS_ATTR_DESCRIPTOR);
1041
0
            goto fail;
1042
8
        case NON_DESCRIPTOR:
1043
8
            SPECIALIZATION_FAIL(STORE_ATTR, SPEC_FAIL_ATTR_CLASS_ATTR_SIMPLE);
1044
8
            goto fail;
1045
1.95k
        case ABSENT:
1046
1.95k
            if (specialize_dict_access(owner, instr, type, kind, name, tp_version,
1047
1.95k
                                       STORE_ATTR, STORE_ATTR_INSTANCE_VALUE,
1048
1.95k
                                       STORE_ATTR_WITH_HINT)) {
1049
1.53k
                goto success;
1050
1.53k
            }
1051
2.11k
    }
1052
1.03k
fail:
1053
1.03k
    Py_XDECREF(descr);
1054
1.03k
    unspecialize(instr);
1055
1.03k
    return;
1056
1.61k
success:
1057
1.61k
    Py_XDECREF(descr);
1058
1.61k
    return;
1059
2.11k
}
1060
1061
#ifdef Py_STATS
1062
static int
1063
load_attr_fail_kind(DescriptorClassification kind)
1064
{
1065
    switch (kind) {
1066
        case OVERRIDING:
1067
            return SPEC_FAIL_ATTR_OVERRIDING_DESCRIPTOR;
1068
        case METHOD:
1069
            return SPEC_FAIL_ATTR_METHOD;
1070
        case PROPERTY:
1071
            return SPEC_FAIL_ATTR_PROPERTY;
1072
        case OBJECT_SLOT:
1073
            return SPEC_FAIL_ATTR_OBJECT_SLOT;
1074
        case OTHER_SLOT:
1075
            return SPEC_FAIL_ATTR_NON_OBJECT_SLOT;
1076
        case DUNDER_CLASS:
1077
            return SPEC_FAIL_OTHER;
1078
        case MUTABLE:
1079
            return SPEC_FAIL_ATTR_MUTABLE_CLASS;
1080
        case GETSET_OVERRIDDEN:
1081
        case GETATTRIBUTE_IS_PYTHON_FUNCTION:
1082
            return SPEC_FAIL_OVERRIDDEN;
1083
        case BUILTIN_CLASSMETHOD:
1084
            return SPEC_FAIL_ATTR_BUILTIN_CLASS_METHOD;
1085
        case PYTHON_CLASSMETHOD:
1086
            return SPEC_FAIL_ATTR_CLASS_METHOD_OBJ;
1087
        case NON_OVERRIDING:
1088
            return SPEC_FAIL_ATTR_NON_OVERRIDING_DESCRIPTOR;
1089
        case NON_DESCRIPTOR:
1090
            return SPEC_FAIL_ATTR_NOT_DESCRIPTOR;
1091
        case ABSENT:
1092
            return SPEC_FAIL_ATTR_INSTANCE_ATTRIBUTE;
1093
    }
1094
    Py_UNREACHABLE();
1095
}
1096
#endif   // Py_STATS
1097
1098
static int
1099
specialize_class_load_attr(PyObject *owner, _Py_CODEUNIT *instr,
1100
                             PyObject *name)
1101
2.01k
{
1102
2.01k
    assert(PyType_Check(owner));
1103
2.01k
    PyTypeObject *cls = (PyTypeObject *)owner;
1104
2.01k
    _PyLoadMethodCache *cache = (_PyLoadMethodCache *)(instr + 1);
1105
2.01k
    if (Py_TYPE(cls)->tp_getattro != _Py_type_getattro) {
1106
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_METACLASS_OVERRIDDEN);
1107
0
        return -1;
1108
0
    }
1109
2.01k
    unsigned int meta_version = 0;
1110
2.01k
    PyObject *metadescriptor = _PyType_LookupRefAndVersion(Py_TYPE(cls), name, &meta_version);
1111
2.01k
    DescriptorClassification metakind = classify_descriptor(metadescriptor, false);
1112
2.01k
    Py_XDECREF(metadescriptor);
1113
2.01k
    switch (metakind) {
1114
95
        case METHOD:
1115
146
        case NON_DESCRIPTOR:
1116
208
        case NON_OVERRIDING:
1117
208
        case BUILTIN_CLASSMETHOD:
1118
208
        case PYTHON_CLASSMETHOD:
1119
1.39k
        case ABSENT:
1120
1.39k
            break;
1121
621
        default:
1122
621
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_METACLASS_ATTRIBUTE);
1123
621
            return -1;
1124
2.01k
    }
1125
1.39k
    PyObject *descr = NULL;
1126
1.39k
    DescriptorClassification kind = 0;
1127
1.39k
    unsigned int tp_version = 0;
1128
1.39k
    kind = analyze_descriptor_load(cls, name, &descr, &tp_version);
1129
1.39k
    if (tp_version == 0) {
1130
0
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OUT_OF_VERSIONS);
1131
0
        Py_XDECREF(descr);
1132
0
        return -1;
1133
0
    }
1134
1.39k
    bool metaclass_check = false;
1135
1.39k
    if ((Py_TYPE(cls)->tp_flags & Py_TPFLAGS_IMMUTABLETYPE) == 0) {
1136
340
        metaclass_check = true;
1137
340
        if (meta_version == 0) {
1138
0
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OUT_OF_VERSIONS);
1139
0
            Py_XDECREF(descr);
1140
0
            return -1;
1141
0
        }
1142
340
    }
1143
1.39k
    switch (kind) {
1144
86
        case METHOD:
1145
399
        case NON_DESCRIPTOR:
1146
            #ifdef Py_GIL_DISABLED
1147
            if (!_PyObject_HasDeferredRefcount(descr)) {
1148
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_DESCR_NOT_DEFERRED);
1149
                Py_XDECREF(descr);
1150
                return -1;
1151
            }
1152
            #endif
1153
399
            write_u32(cache->type_version, tp_version);
1154
399
            write_ptr(cache->descr, descr);
1155
399
            if (metaclass_check) {
1156
229
                write_u32(cache->keys_version, meta_version);
1157
229
                specialize(instr, LOAD_ATTR_CLASS_WITH_METACLASS_CHECK);
1158
229
            }
1159
170
            else {
1160
170
                specialize(instr, LOAD_ATTR_CLASS);
1161
170
            }
1162
399
            Py_XDECREF(descr);
1163
399
            return 0;
1164
#ifdef Py_STATS
1165
        case ABSENT:
1166
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_EXPECTED_ERROR);
1167
            Py_XDECREF(descr);
1168
            return -1;
1169
#endif
1170
996
        default:
1171
996
            SPECIALIZATION_FAIL(LOAD_ATTR, load_attr_fail_kind(kind));
1172
996
            Py_XDECREF(descr);
1173
996
            return -1;
1174
1.39k
    }
1175
1.39k
}
1176
1177
// Please collect stats carefully before and after modifying. A subtle change
1178
// can cause a significant drop in cache hits. A possible test is
1179
// python.exe -m test_typing test_re test_dis test_zlib.
1180
static int
1181
specialize_attr_loadclassattr(PyObject *owner, _Py_CODEUNIT *instr,
1182
                              PyObject *name, PyObject *descr,
1183
                              unsigned int tp_version,
1184
                              DescriptorClassification kind, bool is_method,
1185
                              uint32_t shared_keys_version)
1186
2.29k
{
1187
2.29k
    _PyLoadMethodCache *cache = (_PyLoadMethodCache *)(instr + 1);
1188
2.29k
    PyTypeObject *owner_cls = Py_TYPE(owner);
1189
1190
2.29k
    assert(descr != NULL);
1191
2.29k
    assert((is_method && kind == METHOD) || (!is_method && kind == NON_DESCRIPTOR));
1192
1193
    #ifdef Py_GIL_DISABLED
1194
    if (!_PyObject_HasDeferredRefcount(descr)) {
1195
        SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_DESCR_NOT_DEFERRED);
1196
        return 0;
1197
    }
1198
    #endif
1199
1200
2.29k
    unsigned long tp_flags = PyType_GetFlags(owner_cls);
1201
2.29k
    if (tp_flags & Py_TPFLAGS_INLINE_VALUES) {
1202
570
        #ifndef Py_GIL_DISABLED
1203
570
        assert(_PyDictKeys_StringLookup(
1204
570
                   ((PyHeapTypeObject *)owner_cls)->ht_cached_keys, name) < 0);
1205
570
        #endif
1206
570
        if (shared_keys_version == 0) {
1207
0
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OUT_OF_VERSIONS);
1208
0
            return 0;
1209
0
        }
1210
570
        write_u32(cache->keys_version, shared_keys_version);
1211
570
        specialize(instr, is_method ? LOAD_ATTR_METHOD_WITH_VALUES : LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES);
1212
570
    }
1213
1.72k
    else {
1214
1.72k
        Py_ssize_t dictoffset;
1215
1.72k
        if (tp_flags & Py_TPFLAGS_MANAGED_DICT) {
1216
133
            dictoffset = MANAGED_DICT_OFFSET;
1217
133
        }
1218
1.59k
        else {
1219
1.59k
            dictoffset = owner_cls->tp_dictoffset;
1220
1.59k
            if (dictoffset < 0 || dictoffset > INT16_MAX + MANAGED_DICT_OFFSET) {
1221
0
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_OUT_OF_RANGE);
1222
0
                return 0;
1223
0
            }
1224
1.59k
        }
1225
1.72k
        if (dictoffset == 0) {
1226
1.49k
            specialize(instr, is_method ? LOAD_ATTR_METHOD_NO_DICT : LOAD_ATTR_NONDESCRIPTOR_NO_DICT);
1227
1.49k
        }
1228
236
        else if (is_method) {
1229
186
            PyObject **addr = (PyObject **)((char *)owner + dictoffset);
1230
186
            PyObject *dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*addr);
1231
186
            if (dict) {
1232
164
                SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_NOT_MANAGED_DICT);
1233
164
                return 0;
1234
164
            }
1235
            /* Cache entries must be unsigned values, so we offset the
1236
             * dictoffset by MANAGED_DICT_OFFSET.
1237
             * We do the reverse offset in LOAD_ATTR_METHOD_LAZY_DICT */
1238
22
            dictoffset -= MANAGED_DICT_OFFSET;
1239
22
            assert(((uint16_t)dictoffset) == dictoffset);
1240
22
            cache->dict_offset = (uint16_t)dictoffset;
1241
22
            specialize(instr, LOAD_ATTR_METHOD_LAZY_DICT);
1242
22
        }
1243
50
        else {
1244
50
            SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_CLASS_ATTR_SIMPLE);
1245
50
            return 0;
1246
50
        }
1247
1.72k
    }
1248
    /* `descr` is borrowed. This is safe for methods (even inherited ones from
1249
    *  super classes!) as long as tp_version_tag is validated for two main reasons:
1250
    *
1251
    *  1. The class will always hold a reference to the method so it will
1252
    *  usually not be GC-ed. Should it be deleted in Python, e.g.
1253
    *  `del obj.meth`, tp_version_tag will be invalidated, because of reason 2.
1254
    *
1255
    *  2. The pre-existing type method cache (MCACHE) uses the same principles
1256
    *  of caching a borrowed descriptor. The MCACHE infrastructure does all the
1257
    *  heavy lifting for us. E.g. it invalidates tp_version_tag on any MRO
1258
    *  modification, on any type object change along said MRO, etc. (see
1259
    *  PyType_Modified usages in typeobject.c). The MCACHE has been
1260
    *  working since Python 2.6 and it's battle-tested.
1261
    */
1262
2.08k
    write_u32(cache->type_version, tp_version);
1263
2.08k
    write_ptr(cache->descr, descr);
1264
2.08k
    return 1;
1265
2.29k
}
1266
1267
1268
static void
1269
specialize_load_global_lock_held(
1270
    PyObject *globals, PyObject *builtins,
1271
    _Py_CODEUNIT *instr, PyObject *name)
1272
10.0k
{
1273
10.0k
    assert(ENABLE_SPECIALIZATION_FT);
1274
10.0k
    assert(_PyOpcode_Caches[LOAD_GLOBAL] == INLINE_CACHE_ENTRIES_LOAD_GLOBAL);
1275
    /* Use inline cache */
1276
10.0k
    _PyLoadGlobalCache *cache = (_PyLoadGlobalCache *)(instr + 1);
1277
10.0k
    assert(PyUnicode_CheckExact(name));
1278
10.0k
    if (!PyDict_CheckExact(globals)) {
1279
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_LOAD_GLOBAL_NON_DICT);
1280
0
        goto fail;
1281
0
    }
1282
10.0k
    PyDictKeysObject * globals_keys = ((PyDictObject *)globals)->ma_keys;
1283
10.0k
    if (!DK_IS_UNICODE(globals_keys)) {
1284
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_LOAD_GLOBAL_NON_STRING_OR_SPLIT);
1285
0
        goto fail;
1286
0
    }
1287
10.0k
    Py_ssize_t index = _PyDictKeys_StringLookup(globals_keys, name);
1288
10.0k
    if (index == DKIX_ERROR) {
1289
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_EXPECTED_ERROR);
1290
0
        goto fail;
1291
0
    }
1292
10.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
1293
10.0k
    if (index != DKIX_EMPTY) {
1294
6.40k
        if (index != (uint16_t)index) {
1295
0
            SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_RANGE);
1296
0
            goto fail;
1297
0
        }
1298
6.40k
        uint32_t keys_version = _PyDict_GetKeysVersionForCurrentState(
1299
6.40k
                interp, (PyDictObject*) globals);
1300
6.40k
        if (keys_version == 0) {
1301
0
            SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_VERSIONS);
1302
0
            goto fail;
1303
0
        }
1304
6.40k
        if (keys_version != (uint16_t)keys_version) {
1305
0
            SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_RANGE);
1306
0
            goto fail;
1307
0
        }
1308
6.40k
        cache->index = (uint16_t)index;
1309
6.40k
        cache->module_keys_version = (uint16_t)keys_version;
1310
6.40k
        specialize(instr, LOAD_GLOBAL_MODULE);
1311
6.40k
        return;
1312
6.40k
    }
1313
3.66k
    if (!PyDict_CheckExact(builtins)) {
1314
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_LOAD_GLOBAL_NON_DICT);
1315
0
        goto fail;
1316
0
    }
1317
3.66k
    PyDictKeysObject * builtin_keys = ((PyDictObject *)builtins)->ma_keys;
1318
3.66k
    if (!DK_IS_UNICODE(builtin_keys)) {
1319
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_LOAD_GLOBAL_NON_STRING_OR_SPLIT);
1320
0
        goto fail;
1321
0
    }
1322
3.66k
    index = _PyDictKeys_StringLookup(builtin_keys, name);
1323
3.66k
    if (index == DKIX_ERROR) {
1324
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_EXPECTED_ERROR);
1325
0
        goto fail;
1326
0
    }
1327
3.66k
    if (index != (uint16_t)index) {
1328
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_RANGE);
1329
0
        goto fail;
1330
0
    }
1331
3.66k
    uint32_t globals_version = _PyDict_GetKeysVersionForCurrentState(
1332
3.66k
            interp, (PyDictObject*) globals);
1333
3.66k
    if (globals_version == 0) {
1334
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_VERSIONS);
1335
0
        goto fail;
1336
0
    }
1337
3.66k
    if (globals_version != (uint16_t)globals_version) {
1338
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_RANGE);
1339
0
        goto fail;
1340
0
    }
1341
3.66k
    uint32_t builtins_version = _PyDict_GetKeysVersionForCurrentState(
1342
3.66k
            interp, (PyDictObject*) builtins);
1343
3.66k
    if (builtins_version == 0) {
1344
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_VERSIONS);
1345
0
        goto fail;
1346
0
    }
1347
3.66k
    if (builtins_version > UINT16_MAX) {
1348
0
        SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_OUT_OF_RANGE);
1349
0
        goto fail;
1350
0
    }
1351
3.66k
    cache->index = (uint16_t)index;
1352
3.66k
    cache->module_keys_version = (uint16_t)globals_version;
1353
3.66k
    cache->builtin_keys_version = (uint16_t)builtins_version;
1354
3.66k
    specialize(instr, LOAD_GLOBAL_BUILTIN);
1355
3.66k
    return;
1356
0
fail:
1357
0
    unspecialize(instr);
1358
0
}
1359
1360
Py_NO_INLINE void
1361
_Py_Specialize_LoadGlobal(
1362
    PyObject *globals, PyObject *builtins,
1363
    _Py_CODEUNIT *instr, PyObject *name)
1364
10.0k
{
1365
10.0k
    Py_BEGIN_CRITICAL_SECTION2(globals, builtins);
1366
10.0k
    specialize_load_global_lock_held(globals, builtins, instr, name);
1367
10.0k
    Py_END_CRITICAL_SECTION2();
1368
10.0k
}
1369
1370
static int
1371
16.4k
function_kind(PyCodeObject *code) {
1372
16.4k
    int flags = code->co_flags;
1373
16.4k
    if ((flags & (CO_VARKEYWORDS | CO_VARARGS)) || code->co_kwonlyargcount) {
1374
619
        return SPEC_FAIL_CODE_COMPLEX_PARAMETERS;
1375
619
    }
1376
15.8k
    if ((flags & CO_OPTIMIZED) == 0) {
1377
0
        return SPEC_FAIL_CODE_NOT_OPTIMIZED;
1378
0
    }
1379
15.8k
    return SIMPLE_FUNCTION;
1380
15.8k
}
1381
1382
/* Returning false indicates a failure. */
1383
static bool
1384
function_check_args(PyObject *o, int expected_argcount, int opcode)
1385
228
{
1386
228
    assert(Py_IS_TYPE(o, &PyFunction_Type));
1387
228
    PyFunctionObject *func = (PyFunctionObject *)o;
1388
228
    PyCodeObject *fcode = (PyCodeObject *)func->func_code;
1389
228
    int kind = function_kind(fcode);
1390
228
    if (kind != SIMPLE_FUNCTION) {
1391
0
        SPECIALIZATION_FAIL(opcode, kind);
1392
0
        return false;
1393
0
    }
1394
228
    if (fcode->co_argcount != expected_argcount) {
1395
0
        SPECIALIZATION_FAIL(opcode, SPEC_FAIL_WRONG_NUMBER_ARGUMENTS);
1396
0
        return false;
1397
0
    }
1398
228
    return true;
1399
228
}
1400
1401
/* Returning 0 indicates a failure. */
1402
static uint32_t
1403
function_get_version(PyObject *o, int opcode)
1404
0
{
1405
0
    assert(Py_IS_TYPE(o, &PyFunction_Type));
1406
0
    PyFunctionObject *func = (PyFunctionObject *)o;
1407
0
    uint32_t version = _PyFunction_GetVersionForCurrentState(func);
1408
0
    if (!_PyFunction_IsVersionValid(version)) {
1409
0
        SPECIALIZATION_FAIL(opcode, SPEC_FAIL_OUT_OF_VERSIONS);
1410
0
        return 0;
1411
0
    }
1412
0
    return version;
1413
0
}
1414
1415
#ifdef Py_STATS
1416
static int
1417
store_subscr_fail_kind(PyObject *container, PyObject *sub)
1418
{
1419
    PyTypeObject *container_type = Py_TYPE(container);
1420
    PyMappingMethods *as_mapping = container_type->tp_as_mapping;
1421
    if (as_mapping && (as_mapping->mp_ass_subscript
1422
                       == PyDict_Type.tp_as_mapping->mp_ass_subscript)) {
1423
        return SPEC_FAIL_SUBSCR_DICT_SUBCLASS_NO_OVERRIDE;
1424
    }
1425
    if (PyObject_CheckBuffer(container)) {
1426
        if (PyLong_CheckExact(sub) && (!_PyLong_IsNonNegativeCompact((PyLongObject *)sub))) {
1427
            return SPEC_FAIL_OUT_OF_RANGE;
1428
        }
1429
        else if (strcmp(container_type->tp_name, "array.array") == 0) {
1430
            if (PyLong_CheckExact(sub)) {
1431
                return SPEC_FAIL_SUBSCR_ARRAY_INT;
1432
            }
1433
            else if (PySlice_Check(sub)) {
1434
                return SPEC_FAIL_SUBSCR_ARRAY_SLICE;
1435
            }
1436
            else {
1437
                return SPEC_FAIL_OTHER;
1438
            }
1439
        }
1440
        else if (PyByteArray_CheckExact(container)) {
1441
            if (PyLong_CheckExact(sub)) {
1442
                return SPEC_FAIL_SUBSCR_BYTEARRAY_INT;
1443
            }
1444
            else if (PySlice_Check(sub)) {
1445
                return SPEC_FAIL_SUBSCR_BYTEARRAY_SLICE;
1446
            }
1447
            else {
1448
                return SPEC_FAIL_OTHER;
1449
            }
1450
        }
1451
        else {
1452
            if (PyLong_CheckExact(sub)) {
1453
                return SPEC_FAIL_SUBSCR_BUFFER_INT;
1454
            }
1455
            else if (PySlice_Check(sub)) {
1456
                return SPEC_FAIL_SUBSCR_BUFFER_SLICE;
1457
            }
1458
            else {
1459
                return SPEC_FAIL_OTHER;
1460
            }
1461
        }
1462
        return SPEC_FAIL_OTHER;
1463
    }
1464
    PyObject *descriptor = _PyType_Lookup(container_type, &_Py_ID(__setitem__));
1465
    if (descriptor && Py_TYPE(descriptor) == &PyFunction_Type) {
1466
        PyFunctionObject *func = (PyFunctionObject *)descriptor;
1467
        PyCodeObject *code = (PyCodeObject *)func->func_code;
1468
        int kind = function_kind(code);
1469
        if (kind == SIMPLE_FUNCTION) {
1470
            return SPEC_FAIL_SUBSCR_PY_SIMPLE;
1471
        }
1472
        else {
1473
            return SPEC_FAIL_SUBSCR_PY_OTHER;
1474
        }
1475
    }
1476
    return SPEC_FAIL_OTHER;
1477
}
1478
#endif
1479
1480
Py_NO_INLINE void
1481
_Py_Specialize_StoreSubscr(_PyStackRef container_st, _PyStackRef sub_st, _Py_CODEUNIT *instr)
1482
3.04k
{
1483
3.04k
    PyObject *container = PyStackRef_AsPyObjectBorrow(container_st);
1484
3.04k
    PyObject *sub = PyStackRef_AsPyObjectBorrow(sub_st);
1485
1486
3.04k
    assert(ENABLE_SPECIALIZATION_FT);
1487
3.04k
    PyTypeObject *container_type = Py_TYPE(container);
1488
3.04k
    if (container_type == &PyList_Type) {
1489
433
        if (PyLong_CheckExact(sub)) {
1490
428
            if (_PyLong_IsNonNegativeCompact((PyLongObject *)sub)
1491
63
                && ((PyLongObject *)sub)->long_value.ob_digit[0] < (size_t)PyList_GET_SIZE(container))
1492
63
            {
1493
63
                specialize(instr, STORE_SUBSCR_LIST_INT);
1494
63
                return;
1495
63
            }
1496
365
            else {
1497
365
                SPECIALIZATION_FAIL(STORE_SUBSCR, SPEC_FAIL_OUT_OF_RANGE);
1498
365
                unspecialize(instr);
1499
365
                return;
1500
365
            }
1501
428
        }
1502
5
        else if (PySlice_Check(sub)) {
1503
5
            SPECIALIZATION_FAIL(STORE_SUBSCR, SPEC_FAIL_SUBSCR_LIST_SLICE);
1504
5
            unspecialize(instr);
1505
5
            return;
1506
5
        }
1507
0
        else {
1508
0
            SPECIALIZATION_FAIL(STORE_SUBSCR, SPEC_FAIL_OTHER);
1509
0
            unspecialize(instr);
1510
0
            return;
1511
0
        }
1512
433
    }
1513
2.61k
    if (container_type == &PyDict_Type) {
1514
443
        specialize(instr, STORE_SUBSCR_DICT);
1515
443
        return;
1516
443
    }
1517
2.17k
    SPECIALIZATION_FAIL(STORE_SUBSCR, store_subscr_fail_kind(container, sub));
1518
2.17k
    unspecialize(instr);
1519
2.17k
}
1520
1521
/* Returns a strong reference. */
1522
static PyObject *
1523
get_init_for_simple_managed_python_class(PyTypeObject *tp, unsigned int *tp_version)
1524
3.22k
{
1525
3.22k
    assert(tp->tp_new == PyBaseObject_Type.tp_new);
1526
3.22k
    if (tp->tp_alloc != PyType_GenericAlloc) {
1527
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_OVERRIDDEN);
1528
0
        return NULL;
1529
0
    }
1530
3.22k
    unsigned long tp_flags = PyType_GetFlags(tp);
1531
3.22k
    if (!(tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1532
        /* Is this possible? */
1533
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_EXPECTED_ERROR);
1534
0
        return NULL;
1535
0
    }
1536
3.22k
    PyObject *init = _PyType_LookupRefAndVersion(tp, &_Py_ID(__init__), tp_version);
1537
3.22k
    if (init == NULL || !PyFunction_Check(init)) {
1538
98
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CALL_INIT_NOT_PYTHON);
1539
98
        Py_XDECREF(init);
1540
98
        return NULL;
1541
98
    }
1542
3.12k
    int kind = function_kind((PyCodeObject *)PyFunction_GET_CODE(init));
1543
3.12k
    if (kind != SIMPLE_FUNCTION) {
1544
22
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CALL_INIT_NOT_SIMPLE);
1545
22
        Py_DECREF(init);
1546
22
        return NULL;
1547
22
    }
1548
3.10k
    return init;
1549
3.12k
}
1550
1551
static int
1552
specialize_class_call(PyObject *callable, _Py_CODEUNIT *instr, int nargs)
1553
3.93k
{
1554
3.93k
    assert(PyType_Check(callable));
1555
3.93k
    PyTypeObject *tp = _PyType_CAST(callable);
1556
3.93k
    if (tp->tp_flags & Py_TPFLAGS_IMMUTABLETYPE) {
1557
633
        int oparg = instr->op.arg;
1558
633
        if (nargs == 1 && oparg == 1) {
1559
421
            if (tp == &PyUnicode_Type) {
1560
53
                specialize(instr, CALL_STR_1);
1561
53
                return 0;
1562
53
            }
1563
368
            else if (tp == &PyType_Type) {
1564
83
                specialize(instr, CALL_TYPE_1);
1565
83
                return 0;
1566
83
            }
1567
285
            else if (tp == &PyTuple_Type) {
1568
39
                specialize(instr, CALL_TUPLE_1);
1569
39
                return 0;
1570
39
            }
1571
421
        }
1572
458
        if (tp->tp_vectorcall != NULL) {
1573
291
            specialize(instr, CALL_BUILTIN_CLASS);
1574
291
            return 0;
1575
291
        }
1576
167
        goto generic;
1577
458
    }
1578
3.29k
    if (Py_TYPE(tp) != &PyType_Type) {
1579
10
        goto generic;
1580
10
    }
1581
3.28k
    if (tp->tp_new == PyBaseObject_Type.tp_new) {
1582
3.22k
        unsigned int tp_version = 0;
1583
3.22k
        PyObject *init = get_init_for_simple_managed_python_class(tp, &tp_version);
1584
3.22k
        if (!tp_version) {
1585
0
            SPECIALIZATION_FAIL(CALL, SPEC_FAIL_OUT_OF_VERSIONS);
1586
0
            Py_XDECREF(init);
1587
0
            return -1;
1588
0
        }
1589
3.22k
        if (init != NULL && _PyType_CacheInitForSpecialization(
1590
3.10k
                                (PyHeapTypeObject *)tp, init, tp_version)) {
1591
3.10k
            _PyCallCache *cache = (_PyCallCache *)(instr + 1);
1592
3.10k
            write_u32(cache->func_version, tp_version);
1593
3.10k
            specialize(instr, CALL_ALLOC_AND_ENTER_INIT);
1594
3.10k
            Py_DECREF(init);
1595
3.10k
            return 0;
1596
3.10k
        }
1597
120
        Py_XDECREF(init);
1598
120
    }
1599
362
generic:
1600
362
    specialize(instr, CALL_NON_PY_GENERAL);
1601
362
    return 0;
1602
3.28k
}
1603
1604
static int
1605
specialize_method_descriptor(PyMethodDescrObject *descr, PyObject *self_or_null,
1606
                             _Py_CODEUNIT *instr, int nargs)
1607
1.70k
{
1608
1.70k
    switch (descr->d_method->ml_flags &
1609
1.70k
        (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O |
1610
1.70k
        METH_KEYWORDS | METH_METHOD)) {
1611
152
        case METH_NOARGS: {
1612
152
            if (nargs != 1) {
1613
0
                SPECIALIZATION_FAIL(CALL, SPEC_FAIL_WRONG_NUMBER_ARGUMENTS);
1614
0
                return -1;
1615
0
            }
1616
152
            specialize(instr, CALL_METHOD_DESCRIPTOR_NOARGS);
1617
152
            return 0;
1618
152
        }
1619
617
        case METH_O: {
1620
617
            if (nargs != 2) {
1621
0
                SPECIALIZATION_FAIL(CALL, SPEC_FAIL_WRONG_NUMBER_ARGUMENTS);
1622
0
                return -1;
1623
0
            }
1624
617
            PyInterpreterState *interp = _PyInterpreterState_GET();
1625
617
            PyObject *list_append = interp->callable_cache.list_append;
1626
617
            _Py_CODEUNIT next = instr[INLINE_CACHE_ENTRIES_CALL + 1];
1627
617
            bool pop = (next.op.code == POP_TOP);
1628
617
            int oparg = instr->op.arg;
1629
617
            if ((PyObject *)descr == list_append && oparg == 1 && pop) {
1630
245
                assert(self_or_null != NULL);
1631
245
                if (PyList_CheckExact(self_or_null)) {
1632
208
                    specialize(instr, CALL_LIST_APPEND);
1633
208
                    return 0;
1634
208
                }
1635
245
            }
1636
409
            specialize(instr, CALL_METHOD_DESCRIPTOR_O);
1637
409
            return 0;
1638
617
        }
1639
736
        case METH_FASTCALL: {
1640
736
            specialize(instr, CALL_METHOD_DESCRIPTOR_FAST);
1641
736
            return 0;
1642
617
        }
1643
102
        case METH_FASTCALL | METH_KEYWORDS: {
1644
102
            specialize(instr, CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS);
1645
102
            return 0;
1646
617
        }
1647
1.70k
    }
1648
100
    specialize(instr, CALL_NON_PY_GENERAL);
1649
100
    return 0;
1650
1.70k
}
1651
1652
static int
1653
specialize_py_call(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs,
1654
                   bool bound_method)
1655
12.1k
{
1656
12.1k
    _PyCallCache *cache = (_PyCallCache *)(instr + 1);
1657
12.1k
    PyCodeObject *code = (PyCodeObject *)func->func_code;
1658
12.1k
    int kind = function_kind(code);
1659
    /* Don't specialize if PEP 523 is active */
1660
12.1k
    if (_PyInterpreterState_GET()->eval_frame) {
1661
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CALL_PEP_523);
1662
0
        return -1;
1663
0
    }
1664
12.1k
    if (func->vectorcall != _PyFunction_Vectorcall) {
1665
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CALL_VECTORCALL);
1666
0
        return -1;
1667
0
    }
1668
12.1k
    int argcount = -1;
1669
12.1k
    if (kind == SPEC_FAIL_CODE_NOT_OPTIMIZED) {
1670
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CODE_NOT_OPTIMIZED);
1671
0
        return -1;
1672
0
    }
1673
12.1k
    if (kind == SIMPLE_FUNCTION) {
1674
11.6k
        argcount = code->co_argcount;
1675
11.6k
    }
1676
12.1k
    int version = _PyFunction_GetVersionForCurrentState(func);
1677
12.1k
    if (!_PyFunction_IsVersionValid(version)) {
1678
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_OUT_OF_VERSIONS);
1679
0
        return -1;
1680
0
    }
1681
12.1k
    write_u32(cache->func_version, version);
1682
12.1k
    uint8_t opcode;
1683
12.1k
    if (argcount == nargs + bound_method) {
1684
11.2k
        opcode =
1685
11.2k
            bound_method ? CALL_BOUND_METHOD_EXACT_ARGS : CALL_PY_EXACT_ARGS;
1686
11.2k
    }
1687
949
    else {
1688
949
        opcode = bound_method ? CALL_BOUND_METHOD_GENERAL : CALL_PY_GENERAL;
1689
949
    }
1690
12.1k
    specialize(instr, opcode);
1691
12.1k
    return 0;
1692
12.1k
}
1693
1694
1695
static int
1696
specialize_py_call_kw(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs,
1697
                   bool bound_method)
1698
112
{
1699
112
    _PyCallCache *cache = (_PyCallCache *)(instr + 1);
1700
112
    PyCodeObject *code = (PyCodeObject *)func->func_code;
1701
112
    int kind = function_kind(code);
1702
    /* Don't specialize if PEP 523 is active */
1703
112
    if (_PyInterpreterState_GET()->eval_frame) {
1704
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CALL_PEP_523);
1705
0
        return -1;
1706
0
    }
1707
112
    if (func->vectorcall != _PyFunction_Vectorcall) {
1708
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CALL_VECTORCALL);
1709
0
        return -1;
1710
0
    }
1711
112
    if (kind == SPEC_FAIL_CODE_NOT_OPTIMIZED) {
1712
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CODE_NOT_OPTIMIZED);
1713
0
        return -1;
1714
0
    }
1715
112
    int version = _PyFunction_GetVersionForCurrentState(func);
1716
112
    if (!_PyFunction_IsVersionValid(version)) {
1717
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_OUT_OF_VERSIONS);
1718
0
        return -1;
1719
0
    }
1720
112
    write_u32(cache->func_version, version);
1721
112
    specialize(instr, bound_method ? CALL_KW_BOUND_METHOD : CALL_KW_PY);
1722
112
    return 0;
1723
112
}
1724
1725
static int
1726
specialize_c_call(PyObject *callable, _Py_CODEUNIT *instr, int nargs)
1727
7.71k
{
1728
7.71k
    if (PyCFunction_GET_FUNCTION(callable) == NULL) {
1729
0
        SPECIALIZATION_FAIL(CALL, SPEC_FAIL_OTHER);
1730
0
        return 1;
1731
0
    }
1732
7.71k
    switch (PyCFunction_GET_FLAGS(callable) &
1733
7.71k
        (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O |
1734
7.71k
        METH_KEYWORDS | METH_METHOD)) {
1735
1.00k
        case METH_O: {
1736
1.00k
            if (nargs != 1) {
1737
0
                SPECIALIZATION_FAIL(CALL, SPEC_FAIL_WRONG_NUMBER_ARGUMENTS);
1738
0
                return 1;
1739
0
            }
1740
            /* len(o) */
1741
1.00k
            PyInterpreterState *interp = _PyInterpreterState_GET();
1742
1.00k
            if (callable == interp->callable_cache.len && instr->op.arg == 1) {
1743
525
                specialize(instr, CALL_LEN);
1744
525
                return 0;
1745
525
            }
1746
482
            specialize(instr, CALL_BUILTIN_O);
1747
482
            return 0;
1748
1.00k
        }
1749
5.90k
        case METH_FASTCALL: {
1750
5.90k
            if (nargs == 2) {
1751
                /* isinstance(o1, o2) */
1752
890
                PyInterpreterState *interp = _PyInterpreterState_GET();
1753
890
                if (callable == interp->callable_cache.isinstance && instr->op.arg == 2) {
1754
437
                    specialize(instr, CALL_ISINSTANCE);
1755
437
                    return 0;
1756
437
                }
1757
890
            }
1758
5.46k
            specialize(instr, CALL_BUILTIN_FAST);
1759
5.46k
            return 0;
1760
5.90k
        }
1761
445
        case METH_FASTCALL | METH_KEYWORDS: {
1762
445
            specialize(instr, CALL_BUILTIN_FAST_WITH_KEYWORDS);
1763
445
            return 0;
1764
5.90k
        }
1765
362
        default:
1766
362
            specialize(instr, CALL_NON_PY_GENERAL);
1767
362
            return 0;
1768
7.71k
    }
1769
7.71k
}
1770
1771
Py_NO_INLINE void
1772
_Py_Specialize_Call(_PyStackRef callable_st, _PyStackRef self_or_null_st, _Py_CODEUNIT *instr, int nargs)
1773
25.6k
{
1774
25.6k
    PyObject *callable = PyStackRef_AsPyObjectBorrow(callable_st);
1775
1776
25.6k
    assert(ENABLE_SPECIALIZATION_FT);
1777
25.6k
    assert(_PyOpcode_Caches[CALL] == INLINE_CACHE_ENTRIES_CALL);
1778
25.6k
    assert(_Py_OPCODE(*instr) != INSTRUMENTED_CALL);
1779
25.6k
    int fail;
1780
25.6k
    if (PyCFunction_CheckExact(callable)) {
1781
7.71k
        fail = specialize_c_call(callable, instr, nargs);
1782
7.71k
    }
1783
17.9k
    else if (PyFunction_Check(callable)) {
1784
10.9k
        fail = specialize_py_call((PyFunctionObject *)callable, instr, nargs, false);
1785
10.9k
    }
1786
6.96k
    else if (PyType_Check(callable)) {
1787
3.93k
        fail = specialize_class_call(callable, instr, nargs);
1788
3.93k
    }
1789
3.03k
    else if (Py_IS_TYPE(callable, &PyMethodDescr_Type)) {
1790
1.70k
        PyObject *self_or_null = PyStackRef_AsPyObjectBorrow(self_or_null_st);
1791
1.70k
        fail = specialize_method_descriptor((PyMethodDescrObject *)callable,
1792
1.70k
                                            self_or_null, instr, nargs);
1793
1.70k
    }
1794
1.32k
    else if (PyMethod_Check(callable)) {
1795
1.19k
        PyObject *func = ((PyMethodObject *)callable)->im_func;
1796
1.19k
        if (PyFunction_Check(func)) {
1797
1.19k
            fail = specialize_py_call((PyFunctionObject *)func, instr, nargs, true);
1798
1.19k
        }
1799
0
        else {
1800
0
            SPECIALIZATION_FAIL(CALL, SPEC_FAIL_CALL_BOUND_METHOD);
1801
0
            fail = -1;
1802
0
        }
1803
1.19k
    }
1804
133
    else {
1805
133
        specialize(instr, CALL_NON_PY_GENERAL);
1806
133
        fail = 0;
1807
133
    }
1808
25.6k
    if (fail) {
1809
0
        unspecialize(instr);
1810
0
    }
1811
25.6k
}
1812
1813
Py_NO_INLINE void
1814
_Py_Specialize_CallKw(_PyStackRef callable_st, _Py_CODEUNIT *instr, int nargs)
1815
314
{
1816
314
    PyObject *callable = PyStackRef_AsPyObjectBorrow(callable_st);
1817
1818
314
    assert(ENABLE_SPECIALIZATION_FT);
1819
314
    assert(_PyOpcode_Caches[CALL_KW] == INLINE_CACHE_ENTRIES_CALL_KW);
1820
314
    assert(_Py_OPCODE(*instr) != INSTRUMENTED_CALL_KW);
1821
314
    int fail;
1822
314
    if (PyFunction_Check(callable)) {
1823
112
        fail = specialize_py_call_kw((PyFunctionObject *)callable, instr, nargs, false);
1824
112
    }
1825
202
    else if (PyMethod_Check(callable)) {
1826
0
        PyObject *func = ((PyMethodObject *)callable)->im_func;
1827
0
        if (PyFunction_Check(func)) {
1828
0
            fail = specialize_py_call_kw((PyFunctionObject *)func, instr, nargs, true);
1829
0
        }
1830
0
        else {
1831
0
            SPECIALIZATION_FAIL(CALL_KW, SPEC_FAIL_CALL_BOUND_METHOD);
1832
0
            fail = -1;
1833
0
        }
1834
0
    }
1835
202
    else {
1836
202
        specialize(instr, CALL_KW_NON_PY);
1837
202
        fail = 0;
1838
202
    }
1839
314
    if (fail) {
1840
0
        unspecialize(instr);
1841
0
    }
1842
314
}
1843
1844
#ifdef Py_STATS
1845
static int
1846
binary_op_fail_kind(int oparg, PyObject *lhs, PyObject *rhs)
1847
{
1848
    switch (oparg) {
1849
        case NB_ADD:
1850
        case NB_INPLACE_ADD:
1851
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
1852
                return SPEC_FAIL_BINARY_OP_ADD_DIFFERENT_TYPES;
1853
            }
1854
            return SPEC_FAIL_BINARY_OP_ADD_OTHER;
1855
        case NB_AND:
1856
        case NB_INPLACE_AND:
1857
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
1858
                return SPEC_FAIL_BINARY_OP_AND_DIFFERENT_TYPES;
1859
            }
1860
            if (PyLong_CheckExact(lhs)) {
1861
                return SPEC_FAIL_BINARY_OP_AND_INT;
1862
            }
1863
            return SPEC_FAIL_BINARY_OP_AND_OTHER;
1864
        case NB_FLOOR_DIVIDE:
1865
        case NB_INPLACE_FLOOR_DIVIDE:
1866
            return SPEC_FAIL_BINARY_OP_FLOOR_DIVIDE;
1867
        case NB_LSHIFT:
1868
        case NB_INPLACE_LSHIFT:
1869
            return SPEC_FAIL_BINARY_OP_LSHIFT;
1870
        case NB_MATRIX_MULTIPLY:
1871
        case NB_INPLACE_MATRIX_MULTIPLY:
1872
            return SPEC_FAIL_BINARY_OP_MATRIX_MULTIPLY;
1873
        case NB_MULTIPLY:
1874
        case NB_INPLACE_MULTIPLY:
1875
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
1876
                return SPEC_FAIL_BINARY_OP_MULTIPLY_DIFFERENT_TYPES;
1877
            }
1878
            return SPEC_FAIL_BINARY_OP_MULTIPLY_OTHER;
1879
        case NB_OR:
1880
        case NB_INPLACE_OR:
1881
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
1882
                return SPEC_FAIL_BINARY_OP_OR_DIFFERENT_TYPES;
1883
            }
1884
            if (PyLong_CheckExact(lhs)) {
1885
                return SPEC_FAIL_BINARY_OP_OR_INT;
1886
            }
1887
            return SPEC_FAIL_BINARY_OP_OR;
1888
        case NB_POWER:
1889
        case NB_INPLACE_POWER:
1890
            return SPEC_FAIL_BINARY_OP_POWER;
1891
        case NB_REMAINDER:
1892
        case NB_INPLACE_REMAINDER:
1893
            return SPEC_FAIL_BINARY_OP_REMAINDER;
1894
        case NB_RSHIFT:
1895
        case NB_INPLACE_RSHIFT:
1896
            return SPEC_FAIL_BINARY_OP_RSHIFT;
1897
        case NB_SUBTRACT:
1898
        case NB_INPLACE_SUBTRACT:
1899
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
1900
                return SPEC_FAIL_BINARY_OP_SUBTRACT_DIFFERENT_TYPES;
1901
            }
1902
            return SPEC_FAIL_BINARY_OP_SUBTRACT_OTHER;
1903
        case NB_TRUE_DIVIDE:
1904
        case NB_INPLACE_TRUE_DIVIDE:
1905
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
1906
                return SPEC_FAIL_BINARY_OP_TRUE_DIVIDE_DIFFERENT_TYPES;
1907
            }
1908
            if (PyFloat_CheckExact(lhs)) {
1909
                return SPEC_FAIL_BINARY_OP_TRUE_DIVIDE_FLOAT;
1910
            }
1911
            return SPEC_FAIL_BINARY_OP_TRUE_DIVIDE_OTHER;
1912
        case NB_XOR:
1913
        case NB_INPLACE_XOR:
1914
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
1915
                return SPEC_FAIL_BINARY_OP_XOR_DIFFERENT_TYPES;
1916
            }
1917
            if (PyLong_CheckExact(lhs)) {
1918
                return SPEC_FAIL_BINARY_OP_XOR_INT;
1919
            }
1920
            return SPEC_FAIL_BINARY_OP_XOR;
1921
        case NB_SUBSCR:
1922
            if (PyList_CheckExact(lhs)) {
1923
                if (PyLong_CheckExact(rhs) && !_PyLong_IsNonNegativeCompact((PyLongObject *)rhs)) {
1924
                    return SPEC_FAIL_OUT_OF_RANGE;
1925
                }
1926
                if (PySlice_Check(rhs)) {
1927
                    return SPEC_FAIL_BINARY_OP_SUBSCR_LIST_SLICE;
1928
                }
1929
            }
1930
            if (PyTuple_CheckExact(lhs)) {
1931
                if (PyLong_CheckExact(rhs) && !_PyLong_IsNonNegativeCompact((PyLongObject *)rhs)) {
1932
                    return SPEC_FAIL_OUT_OF_RANGE;
1933
                }
1934
                if (PySlice_Check(rhs)) {
1935
                    return SPEC_FAIL_BINARY_OP_SUBSCR_TUPLE_SLICE;
1936
                }
1937
            }
1938
            if (PyUnicode_CheckExact(lhs)) {
1939
                if (PyLong_CheckExact(rhs) && !_PyLong_IsNonNegativeCompact((PyLongObject *)rhs)) {
1940
                    return SPEC_FAIL_OUT_OF_RANGE;
1941
                }
1942
                if (PySlice_Check(rhs)) {
1943
                    return SPEC_FAIL_BINARY_OP_SUBSCR_STRING_SLICE;
1944
                }
1945
            }
1946
            unsigned int tp_version;
1947
            PyTypeObject *container_type = Py_TYPE(lhs);
1948
            PyObject *descriptor = _PyType_LookupRefAndVersion(container_type, &_Py_ID(__getitem__), &tp_version);
1949
            if (descriptor && Py_TYPE(descriptor) == &PyFunction_Type) {
1950
                if (!(container_type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1951
                    Py_DECREF(descriptor);
1952
                    return SPEC_FAIL_BINARY_OP_SUBSCR_NOT_HEAP_TYPE;
1953
                }
1954
                PyFunctionObject *func = (PyFunctionObject *)descriptor;
1955
                PyCodeObject *fcode = (PyCodeObject *)func->func_code;
1956
                int kind = function_kind(fcode);
1957
                if (kind != SIMPLE_FUNCTION) {
1958
                    Py_DECREF(descriptor);
1959
                    return kind;
1960
                }
1961
                if (fcode->co_argcount != 2) {
1962
                    Py_DECREF(descriptor);
1963
                    return SPEC_FAIL_WRONG_NUMBER_ARGUMENTS;
1964
                }
1965
1966
                if (_PyInterpreterState_GET()->eval_frame) {
1967
                    /* Don't specialize if PEP 523 is active */
1968
                    Py_DECREF(descriptor);
1969
                    return SPEC_FAIL_OTHER;
1970
                }
1971
            }
1972
            Py_XDECREF(descriptor);
1973
1974
            if (PyObject_TypeCheck(lhs, &PyDictProxy_Type)) {
1975
                return SPEC_FAIL_BINARY_OP_SUBSCR_MAPPINGPROXY;
1976
            }
1977
1978
            if (PyObject_TypeCheck(lhs, &PyBytes_Type)) {
1979
                return SPEC_FAIL_BINARY_OP_SUBSCR_BYTES;
1980
            }
1981
1982
            if (PyObject_TypeCheck(lhs, &PyRange_Type)) {
1983
                return SPEC_FAIL_BINARY_OP_SUBSCR_RANGE;
1984
            }
1985
1986
            if (strcmp(container_type->tp_name, "array.array") == 0) {
1987
                return SPEC_FAIL_BINARY_OP_SUBSCR_ARRAY;
1988
            }
1989
1990
            if (strcmp(container_type->tp_name, "re.Match") == 0) {
1991
                return SPEC_FAIL_BINARY_OP_SUBSCR_RE_MATCH;
1992
            }
1993
1994
            if (strcmp(container_type->tp_name, "collections.deque") == 0) {
1995
                return SPEC_FAIL_BINARY_OP_SUBSCR_DEQUE;
1996
            }
1997
1998
            if (strcmp(_PyType_Name(container_type), "EnumDict") == 0) {
1999
                return SPEC_FAIL_BINARY_OP_SUBSCR_ENUMDICT;
2000
            }
2001
2002
            if (strcmp(container_type->tp_name, "StackSummary") == 0) {
2003
                return SPEC_FAIL_BINARY_OP_SUBSCR_STACKSUMMARY;
2004
            }
2005
2006
            if (strcmp(container_type->tp_name, "collections.defaultdict") == 0) {
2007
                return SPEC_FAIL_BINARY_OP_SUBSCR_DEFAULTDICT;
2008
            }
2009
2010
            if (strcmp(container_type->tp_name, "Counter") == 0) {
2011
                return SPEC_FAIL_BINARY_OP_SUBSCR_COUNTER;
2012
            }
2013
2014
            if (strcmp(container_type->tp_name, "collections.OrderedDict") == 0) {
2015
                return SPEC_FAIL_BINARY_OP_SUBSCR_ORDEREDDICT;
2016
            }
2017
2018
            if (strcmp(container_type->tp_name, "time.struct_time") == 0) {
2019
                return SPEC_FAIL_BINARY_OP_SUBSCR_STRUCTTIME;
2020
            }
2021
2022
            if (PySlice_Check(rhs)) {
2023
                return SPEC_FAIL_BINARY_OP_SUBSCR_OTHER_SLICE;
2024
            }
2025
            return SPEC_FAIL_BINARY_OP_SUBSCR;
2026
    }
2027
    Py_UNREACHABLE();
2028
}
2029
#endif
2030
2031
/** Binary Op Specialization Extensions */
2032
2033
/* long-long */
2034
2035
static inline int
2036
is_compactlong(PyObject *v)
2037
22.9M
{
2038
22.9M
    return PyLong_CheckExact(v) &&
2039
22.9M
           _PyLong_IsCompact((PyLongObject *)v);
2040
22.9M
}
2041
2042
static int
2043
compactlongs_guard(PyObject *lhs, PyObject *rhs)
2044
11.4M
{
2045
11.4M
    return (is_compactlong(lhs) && is_compactlong(rhs));
2046
11.4M
}
2047
2048
#define BITWISE_LONGS_ACTION(NAME, OP) \
2049
    static PyObject * \
2050
    (NAME)(PyObject *lhs, PyObject *rhs) \
2051
11.4M
    { \
2052
11.4M
        Py_ssize_t rhs_val = _PyLong_CompactValue((PyLongObject *)rhs); \
2053
11.4M
        Py_ssize_t lhs_val = _PyLong_CompactValue((PyLongObject *)lhs); \
2054
11.4M
        return PyLong_FromSsize_t(lhs_val OP rhs_val); \
2055
11.4M
    }
specialize.c:compactlongs_or
Line
Count
Source
2051
429k
    { \
2052
429k
        Py_ssize_t rhs_val = _PyLong_CompactValue((PyLongObject *)rhs); \
2053
429k
        Py_ssize_t lhs_val = _PyLong_CompactValue((PyLongObject *)lhs); \
2054
429k
        return PyLong_FromSsize_t(lhs_val OP rhs_val); \
2055
429k
    }
specialize.c:compactlongs_and
Line
Count
Source
2051
11.0M
    { \
2052
11.0M
        Py_ssize_t rhs_val = _PyLong_CompactValue((PyLongObject *)rhs); \
2053
11.0M
        Py_ssize_t lhs_val = _PyLong_CompactValue((PyLongObject *)lhs); \
2054
11.0M
        return PyLong_FromSsize_t(lhs_val OP rhs_val); \
2055
11.0M
    }
specialize.c:compactlongs_xor
Line
Count
Source
2051
32
    { \
2052
32
        Py_ssize_t rhs_val = _PyLong_CompactValue((PyLongObject *)rhs); \
2053
32
        Py_ssize_t lhs_val = _PyLong_CompactValue((PyLongObject *)lhs); \
2054
32
        return PyLong_FromSsize_t(lhs_val OP rhs_val); \
2055
32
    }
2056
BITWISE_LONGS_ACTION(compactlongs_or, |)
2057
BITWISE_LONGS_ACTION(compactlongs_and, &)
2058
BITWISE_LONGS_ACTION(compactlongs_xor, ^)
2059
#undef BITWISE_LONGS_ACTION
2060
2061
/* float-long */
2062
2063
static inline int
2064
float_compactlong_guard(PyObject *lhs, PyObject *rhs)
2065
21.4k
{
2066
21.4k
    return (
2067
21.4k
        PyFloat_CheckExact(lhs) &&
2068
0
        !isnan(PyFloat_AsDouble(lhs)) &&
2069
21.4k
        PyLong_CheckExact(rhs) &&
2070
0
        _PyLong_IsCompact((PyLongObject *)rhs)
2071
21.4k
    );
2072
21.4k
}
2073
2074
static inline int
2075
nonzero_float_compactlong_guard(PyObject *lhs, PyObject *rhs)
2076
0
{
2077
0
    return (
2078
0
        float_compactlong_guard(lhs, rhs) && !PyLong_IsZero(rhs)
2079
0
    );
2080
0
}
2081
2082
#define FLOAT_LONG_ACTION(NAME, OP) \
2083
    static PyObject * \
2084
    (NAME)(PyObject *lhs, PyObject *rhs) \
2085
0
    { \
2086
0
        double lhs_val = PyFloat_AsDouble(lhs); \
2087
0
        Py_ssize_t rhs_val = _PyLong_CompactValue((PyLongObject *)rhs); \
2088
0
        return PyFloat_FromDouble(lhs_val OP rhs_val); \
2089
0
    }
Unexecuted instantiation: specialize.c:float_compactlong_add
Unexecuted instantiation: specialize.c:float_compactlong_subtract
Unexecuted instantiation: specialize.c:float_compactlong_true_div
Unexecuted instantiation: specialize.c:float_compactlong_multiply
2090
FLOAT_LONG_ACTION(float_compactlong_add, +)
2091
FLOAT_LONG_ACTION(float_compactlong_subtract, -)
2092
FLOAT_LONG_ACTION(float_compactlong_multiply, *)
2093
FLOAT_LONG_ACTION(float_compactlong_true_div, /)
2094
#undef FLOAT_LONG_ACTION
2095
2096
/*  long-float */
2097
2098
static inline int
2099
compactlong_float_guard(PyObject *lhs, PyObject *rhs)
2100
21.4k
{
2101
21.4k
    return (
2102
21.4k
        PyLong_CheckExact(lhs) &&
2103
21.3k
        _PyLong_IsCompact((PyLongObject *)lhs) &&
2104
21.4k
        PyFloat_CheckExact(rhs) &&
2105
0
        !isnan(PyFloat_AsDouble(rhs))
2106
21.4k
    );
2107
21.4k
}
2108
2109
static inline int
2110
nonzero_compactlong_float_guard(PyObject *lhs, PyObject *rhs)
2111
0
{
2112
0
    return (
2113
0
        compactlong_float_guard(lhs, rhs) && PyFloat_AsDouble(rhs) != 0.0
2114
0
    );
2115
0
}
2116
2117
#define LONG_FLOAT_ACTION(NAME, OP) \
2118
    static PyObject * \
2119
    (NAME)(PyObject *lhs, PyObject *rhs) \
2120
0
    { \
2121
0
        double rhs_val = PyFloat_AsDouble(rhs); \
2122
0
        Py_ssize_t lhs_val = _PyLong_CompactValue((PyLongObject *)lhs); \
2123
0
        return PyFloat_FromDouble(lhs_val OP rhs_val); \
2124
0
    }
Unexecuted instantiation: specialize.c:compactlong_float_add
Unexecuted instantiation: specialize.c:compactlong_float_subtract
Unexecuted instantiation: specialize.c:compactlong_float_true_div
Unexecuted instantiation: specialize.c:compactlong_float_multiply
2125
LONG_FLOAT_ACTION(compactlong_float_add, +)
2126
LONG_FLOAT_ACTION(compactlong_float_subtract, -)
2127
LONG_FLOAT_ACTION(compactlong_float_multiply, *)
2128
LONG_FLOAT_ACTION(compactlong_float_true_div, /)
2129
#undef LONG_FLOAT_ACTION
2130
2131
static _PyBinaryOpSpecializationDescr binaryop_extend_descrs[] = {
2132
    /* long-long arithmetic */
2133
    {NB_OR, compactlongs_guard, compactlongs_or},
2134
    {NB_AND, compactlongs_guard, compactlongs_and},
2135
    {NB_XOR, compactlongs_guard, compactlongs_xor},
2136
    {NB_INPLACE_OR, compactlongs_guard, compactlongs_or},
2137
    {NB_INPLACE_AND, compactlongs_guard, compactlongs_and},
2138
    {NB_INPLACE_XOR, compactlongs_guard, compactlongs_xor},
2139
2140
    /* float-long arithemetic */
2141
    {NB_ADD, float_compactlong_guard, float_compactlong_add},
2142
    {NB_SUBTRACT, float_compactlong_guard, float_compactlong_subtract},
2143
    {NB_TRUE_DIVIDE, nonzero_float_compactlong_guard, float_compactlong_true_div},
2144
    {NB_MULTIPLY, float_compactlong_guard, float_compactlong_multiply},
2145
2146
    /* float-float arithmetic */
2147
    {NB_ADD, compactlong_float_guard, compactlong_float_add},
2148
    {NB_SUBTRACT, compactlong_float_guard, compactlong_float_subtract},
2149
    {NB_TRUE_DIVIDE, nonzero_compactlong_float_guard, compactlong_float_true_div},
2150
    {NB_MULTIPLY, compactlong_float_guard, compactlong_float_multiply},
2151
};
2152
2153
static int
2154
binary_op_extended_specialization(PyObject *lhs, PyObject *rhs, int oparg,
2155
                                  _PyBinaryOpSpecializationDescr **descr)
2156
25.2k
{
2157
25.2k
    size_t n = sizeof(binaryop_extend_descrs)/sizeof(_PyBinaryOpSpecializationDescr);
2158
374k
    for (size_t i = 0; i < n; i++) {
2159
349k
        _PyBinaryOpSpecializationDescr *d = &binaryop_extend_descrs[i];
2160
349k
        if (d->oparg == oparg && d->guard(lhs, rhs)) {
2161
353
            *descr = d;
2162
353
            return 1;
2163
353
        }
2164
349k
    }
2165
24.9k
    return 0;
2166
25.2k
}
2167
2168
Py_NO_INLINE void
2169
_Py_Specialize_BinaryOp(_PyStackRef lhs_st, _PyStackRef rhs_st, _Py_CODEUNIT *instr,
2170
                        int oparg, _PyStackRef *locals)
2171
262k
{
2172
262k
    PyObject *lhs = PyStackRef_AsPyObjectBorrow(lhs_st);
2173
262k
    PyObject *rhs = PyStackRef_AsPyObjectBorrow(rhs_st);
2174
262k
    assert(ENABLE_SPECIALIZATION_FT);
2175
262k
    assert(_PyOpcode_Caches[BINARY_OP] == INLINE_CACHE_ENTRIES_BINARY_OP);
2176
2177
262k
    _PyBinaryOpCache *cache = (_PyBinaryOpCache *)(instr + 1);
2178
262k
    if (instr->op.code == BINARY_OP_EXTEND) {
2179
0
        write_ptr(cache->external_cache, NULL);
2180
0
    }
2181
2182
262k
    switch (oparg) {
2183
25.1k
        case NB_ADD:
2184
25.5k
        case NB_INPLACE_ADD:
2185
25.5k
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
2186
3
                break;
2187
3
            }
2188
25.5k
            if (PyUnicode_CheckExact(lhs)) {
2189
239
                _Py_CODEUNIT next = instr[INLINE_CACHE_ENTRIES_BINARY_OP + 1];
2190
239
                bool to_store = (next.op.code == STORE_FAST);
2191
239
                if (to_store && PyStackRef_AsPyObjectBorrow(locals[next.op.arg]) == lhs) {
2192
46
                    specialize(instr, BINARY_OP_INPLACE_ADD_UNICODE);
2193
46
                    return;
2194
46
                }
2195
193
                specialize(instr, BINARY_OP_ADD_UNICODE);
2196
193
                return;
2197
239
            }
2198
25.3k
            if (_PyLong_CheckExactAndCompact(lhs) && _PyLong_CheckExactAndCompact(rhs)) {
2199
5.19k
                specialize(instr, BINARY_OP_ADD_INT);
2200
5.19k
                return;
2201
5.19k
            }
2202
20.1k
            if (PyFloat_CheckExact(lhs)) {
2203
0
                specialize(instr, BINARY_OP_ADD_FLOAT);
2204
0
                return;
2205
0
            }
2206
20.1k
            break;
2207
20.1k
        case NB_MULTIPLY:
2208
2.07k
        case NB_INPLACE_MULTIPLY:
2209
2.07k
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
2210
750
                break;
2211
750
            }
2212
1.32k
            if (_PyLong_CheckExactAndCompact(lhs) && _PyLong_CheckExactAndCompact(rhs)) {
2213
502
                specialize(instr, BINARY_OP_MULTIPLY_INT);
2214
502
                return;
2215
502
            }
2216
822
            if (PyFloat_CheckExact(lhs)) {
2217
0
                specialize(instr, BINARY_OP_MULTIPLY_FLOAT);
2218
0
                return;
2219
0
            }
2220
822
            break;
2221
822
        case NB_SUBTRACT:
2222
240
        case NB_INPLACE_SUBTRACT:
2223
240
            if (!Py_IS_TYPE(lhs, Py_TYPE(rhs))) {
2224
31
                break;
2225
31
            }
2226
209
            if (_PyLong_CheckExactAndCompact(lhs) && _PyLong_CheckExactAndCompact(rhs)) {
2227
186
                specialize(instr, BINARY_OP_SUBTRACT_INT);
2228
186
                return;
2229
186
            }
2230
23
            if (PyFloat_CheckExact(lhs)) {
2231
0
                specialize(instr, BINARY_OP_SUBTRACT_FLOAT);
2232
0
                return;
2233
0
            }
2234
23
            break;
2235
233k
        case NB_SUBSCR:
2236
233k
            if (PyLong_CheckExact(rhs) && _PyLong_IsNonNegativeCompact((PyLongObject *)rhs)) {
2237
231k
                if (PyList_CheckExact(lhs)) {
2238
37.8k
                    specialize(instr, BINARY_OP_SUBSCR_LIST_INT);
2239
37.8k
                    return;
2240
37.8k
                }
2241
193k
                if (PyTuple_CheckExact(lhs)) {
2242
302
                    specialize(instr, BINARY_OP_SUBSCR_TUPLE_INT);
2243
302
                    return;
2244
302
                }
2245
193k
                if (PyUnicode_CheckExact(lhs)) {
2246
192k
                    specialize(instr, BINARY_OP_SUBSCR_STR_INT);
2247
192k
                    return;
2248
192k
                }
2249
193k
            }
2250
2.76k
            if (PyDict_CheckExact(lhs)) {
2251
284
                specialize(instr, BINARY_OP_SUBSCR_DICT);
2252
284
                return;
2253
284
            }
2254
2.48k
            if (PyList_CheckExact(lhs) && PySlice_Check(rhs)) {
2255
14
                specialize(instr, BINARY_OP_SUBSCR_LIST_SLICE);
2256
14
                return;
2257
14
            }
2258
2.46k
            unsigned int tp_version;
2259
2.46k
            PyTypeObject *container_type = Py_TYPE(lhs);
2260
2.46k
            PyObject *descriptor = _PyType_LookupRefAndVersion(container_type, &_Py_ID(__getitem__), &tp_version);
2261
2.46k
            if (descriptor && Py_TYPE(descriptor) == &PyFunction_Type &&
2262
808
                container_type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2263
808
            {
2264
808
                PyFunctionObject *func = (PyFunctionObject *)descriptor;
2265
808
                PyCodeObject *fcode = (PyCodeObject *)func->func_code;
2266
808
                int kind = function_kind(fcode);
2267
808
                PyHeapTypeObject *ht = (PyHeapTypeObject *)container_type;
2268
808
                if (kind == SIMPLE_FUNCTION &&
2269
808
                    fcode->co_argcount == 2 &&
2270
808
                    !_PyInterpreterState_GET()->eval_frame && /* Don't specialize if PEP 523 is active */
2271
808
                    _PyType_CacheGetItemForSpecialization(ht, descriptor, (uint32_t)tp_version))
2272
808
                {
2273
808
                    specialize(instr, BINARY_OP_SUBSCR_GETITEM);
2274
808
                    Py_DECREF(descriptor);
2275
808
                    return;
2276
808
                }
2277
808
            }
2278
1.66k
            Py_XDECREF(descriptor);
2279
1.66k
            break;
2280
262k
    }
2281
2282
25.2k
    _PyBinaryOpSpecializationDescr *descr;
2283
25.2k
    if (binary_op_extended_specialization(lhs, rhs, oparg, &descr)) {
2284
353
        specialize(instr, BINARY_OP_EXTEND);
2285
353
        write_ptr(cache->external_cache, (void*)descr);
2286
353
        return;
2287
353
    }
2288
2289
24.9k
    SPECIALIZATION_FAIL(BINARY_OP, binary_op_fail_kind(oparg, lhs, rhs));
2290
24.9k
    unspecialize(instr);
2291
24.9k
    return;
2292
25.2k
}
2293
2294
2295
#ifdef Py_STATS
2296
static int
2297
compare_op_fail_kind(PyObject *lhs, PyObject *rhs)
2298
{
2299
    if (Py_TYPE(lhs) != Py_TYPE(rhs)) {
2300
        if (PyFloat_CheckExact(lhs) && PyLong_CheckExact(rhs)) {
2301
            return SPEC_FAIL_COMPARE_OP_FLOAT_LONG;
2302
        }
2303
        if (PyLong_CheckExact(lhs) && PyFloat_CheckExact(rhs)) {
2304
            return SPEC_FAIL_COMPARE_OP_LONG_FLOAT;
2305
        }
2306
        return SPEC_FAIL_COMPARE_OP_DIFFERENT_TYPES;
2307
    }
2308
    if (PyBytes_CheckExact(lhs)) {
2309
        return SPEC_FAIL_COMPARE_OP_BYTES;
2310
    }
2311
    if (PyTuple_CheckExact(lhs)) {
2312
        return SPEC_FAIL_COMPARE_OP_TUPLE;
2313
    }
2314
    if (PyList_CheckExact(lhs)) {
2315
        return SPEC_FAIL_COMPARE_OP_LIST;
2316
    }
2317
    if (PySet_CheckExact(lhs) || PyFrozenSet_CheckExact(lhs)) {
2318
        return SPEC_FAIL_COMPARE_OP_SET;
2319
    }
2320
    if (PyBool_Check(lhs)) {
2321
        return SPEC_FAIL_COMPARE_OP_BOOL;
2322
    }
2323
    if (Py_TYPE(lhs)->tp_richcompare == PyBaseObject_Type.tp_richcompare) {
2324
        return SPEC_FAIL_COMPARE_OP_BASEOBJECT;
2325
    }
2326
    return SPEC_FAIL_OTHER;
2327
}
2328
#endif   // Py_STATS
2329
2330
Py_NO_INLINE void
2331
_Py_Specialize_CompareOp(_PyStackRef lhs_st, _PyStackRef rhs_st, _Py_CODEUNIT *instr,
2332
                         int oparg)
2333
4.63k
{
2334
4.63k
    PyObject *lhs = PyStackRef_AsPyObjectBorrow(lhs_st);
2335
4.63k
    PyObject *rhs = PyStackRef_AsPyObjectBorrow(rhs_st);
2336
4.63k
    uint8_t specialized_op;
2337
2338
4.63k
    assert(ENABLE_SPECIALIZATION_FT);
2339
4.63k
    assert(_PyOpcode_Caches[COMPARE_OP] == INLINE_CACHE_ENTRIES_COMPARE_OP);
2340
    // All of these specializations compute boolean values, so they're all valid
2341
    // regardless of the fifth-lowest oparg bit.
2342
4.63k
    if (Py_TYPE(lhs) != Py_TYPE(rhs)) {
2343
449
        SPECIALIZATION_FAIL(COMPARE_OP, compare_op_fail_kind(lhs, rhs));
2344
449
        goto failure;
2345
449
    }
2346
4.18k
    if (PyFloat_CheckExact(lhs)) {
2347
9
        specialized_op = COMPARE_OP_FLOAT;
2348
9
        goto success;
2349
9
    }
2350
4.17k
    if (PyLong_CheckExact(lhs)) {
2351
1.34k
        if (_PyLong_IsCompact((PyLongObject *)lhs) && _PyLong_IsCompact((PyLongObject *)rhs)) {
2352
790
            specialized_op = COMPARE_OP_INT;
2353
790
            goto success;
2354
790
        }
2355
551
        else {
2356
551
            SPECIALIZATION_FAIL(COMPARE_OP, SPEC_FAIL_COMPARE_OP_BIG_INT);
2357
551
            goto failure;
2358
551
        }
2359
1.34k
    }
2360
2.83k
    if (PyUnicode_CheckExact(lhs)) {
2361
2.31k
        int cmp = oparg >> 5;
2362
2.31k
        if (cmp != Py_EQ && cmp != Py_NE) {
2363
1.67k
            SPECIALIZATION_FAIL(COMPARE_OP, SPEC_FAIL_COMPARE_OP_STRING);
2364
1.67k
            goto failure;
2365
1.67k
        }
2366
643
        else {
2367
643
            specialized_op = COMPARE_OP_STR;
2368
643
            goto success;
2369
643
        }
2370
2.31k
    }
2371
519
    SPECIALIZATION_FAIL(COMPARE_OP, compare_op_fail_kind(lhs, rhs));
2372
3.19k
failure:
2373
3.19k
    unspecialize(instr);
2374
3.19k
    return;
2375
1.44k
success:
2376
1.44k
    specialize(instr, specialized_op);
2377
1.44k
}
2378
2379
#ifdef Py_STATS
2380
static int
2381
unpack_sequence_fail_kind(PyObject *seq)
2382
{
2383
    if (PySequence_Check(seq)) {
2384
        return SPEC_FAIL_UNPACK_SEQUENCE_SEQUENCE;
2385
    }
2386
    if (PyIter_Check(seq)) {
2387
        return SPEC_FAIL_UNPACK_SEQUENCE_ITERATOR;
2388
    }
2389
    return SPEC_FAIL_OTHER;
2390
}
2391
#endif   // Py_STATS
2392
2393
Py_NO_INLINE void
2394
_Py_Specialize_UnpackSequence(_PyStackRef seq_st, _Py_CODEUNIT *instr, int oparg)
2395
421
{
2396
421
    PyObject *seq = PyStackRef_AsPyObjectBorrow(seq_st);
2397
2398
421
    assert(ENABLE_SPECIALIZATION_FT);
2399
421
    assert(_PyOpcode_Caches[UNPACK_SEQUENCE] ==
2400
421
           INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE);
2401
421
    if (PyTuple_CheckExact(seq)) {
2402
421
        if (PyTuple_GET_SIZE(seq) != oparg) {
2403
0
            SPECIALIZATION_FAIL(UNPACK_SEQUENCE, SPEC_FAIL_EXPECTED_ERROR);
2404
0
            unspecialize(instr);
2405
0
            return;
2406
0
        }
2407
421
        if (PyTuple_GET_SIZE(seq) == 2) {
2408
338
            specialize(instr, UNPACK_SEQUENCE_TWO_TUPLE);
2409
338
            return;
2410
338
        }
2411
83
        specialize(instr, UNPACK_SEQUENCE_TUPLE);
2412
83
        return;
2413
421
    }
2414
0
    if (PyList_CheckExact(seq)) {
2415
0
        if (PyList_GET_SIZE(seq) != oparg) {
2416
0
            SPECIALIZATION_FAIL(UNPACK_SEQUENCE, SPEC_FAIL_EXPECTED_ERROR);
2417
0
            unspecialize(instr);
2418
0
            return;
2419
0
        }
2420
0
        specialize(instr, UNPACK_SEQUENCE_LIST);
2421
0
        return;
2422
0
    }
2423
0
    SPECIALIZATION_FAIL(UNPACK_SEQUENCE, unpack_sequence_fail_kind(seq));
2424
0
    unspecialize(instr);
2425
0
}
2426
2427
#ifdef Py_STATS
2428
int
2429
 _PySpecialization_ClassifyIterator(PyObject *iter)
2430
{
2431
    if (PyGen_CheckExact(iter)) {
2432
        return SPEC_FAIL_ITER_GENERATOR;
2433
    }
2434
    if (PyCoro_CheckExact(iter)) {
2435
        return SPEC_FAIL_ITER_COROUTINE;
2436
    }
2437
    if (PyAsyncGen_CheckExact(iter)) {
2438
        return SPEC_FAIL_ITER_ASYNC_GENERATOR;
2439
    }
2440
    if (PyAsyncGenASend_CheckExact(iter)) {
2441
        return SPEC_FAIL_ITER_ASYNC_GENERATOR_SEND;
2442
    }
2443
    PyTypeObject *t = Py_TYPE(iter);
2444
    if (t == &PyListIter_Type) {
2445
        return SPEC_FAIL_ITER_LIST;
2446
    }
2447
    if (t == &PyTupleIter_Type) {
2448
        return SPEC_FAIL_ITER_TUPLE;
2449
    }
2450
    if (t == &PyDictIterKey_Type) {
2451
        return SPEC_FAIL_ITER_DICT_KEYS;
2452
    }
2453
    if (t == &PyDictIterValue_Type) {
2454
        return SPEC_FAIL_ITER_DICT_VALUES;
2455
    }
2456
    if (t == &PyDictIterItem_Type) {
2457
        return SPEC_FAIL_ITER_DICT_ITEMS;
2458
    }
2459
    if (t == &PySetIter_Type) {
2460
        return SPEC_FAIL_ITER_SET;
2461
    }
2462
    if (t == &PyUnicodeIter_Type) {
2463
        return SPEC_FAIL_ITER_STRING;
2464
    }
2465
    if (t == &PyBytesIter_Type) {
2466
        return SPEC_FAIL_ITER_BYTES;
2467
    }
2468
    if (t == &PyRangeIter_Type) {
2469
        return SPEC_FAIL_ITER_RANGE;
2470
    }
2471
    if (t == &PyEnum_Type) {
2472
        return SPEC_FAIL_ITER_ENUMERATE;
2473
    }
2474
    if (t == &PyMap_Type) {
2475
        return SPEC_FAIL_ITER_MAP;
2476
    }
2477
    if (t == &PyZip_Type) {
2478
        return SPEC_FAIL_ITER_ZIP;
2479
    }
2480
    if (t == &PySeqIter_Type) {
2481
        return SPEC_FAIL_ITER_SEQ_ITER;
2482
    }
2483
    if (t == &PyListRevIter_Type) {
2484
        return SPEC_FAIL_ITER_REVERSED_LIST;
2485
    }
2486
    if (t == &_PyUnicodeASCIIIter_Type) {
2487
        return SPEC_FAIL_ITER_ASCII_STRING;
2488
    }
2489
    const char *name = t->tp_name;
2490
    if (strncmp(name, "itertools", 9) == 0) {
2491
        return SPEC_FAIL_ITER_ITERTOOLS;
2492
    }
2493
    if (strncmp(name, "callable_iterator", 17) == 0) {
2494
        return SPEC_FAIL_ITER_CALLABLE;
2495
    }
2496
    return SPEC_FAIL_OTHER;
2497
}
2498
#endif   // Py_STATS
2499
2500
Py_NO_INLINE void
2501
_Py_Specialize_ForIter(_PyStackRef iter, _PyStackRef null_or_index, _Py_CODEUNIT *instr, int oparg)
2502
30.7k
{
2503
30.7k
    assert(ENABLE_SPECIALIZATION_FT);
2504
30.7k
    assert(_PyOpcode_Caches[FOR_ITER] == INLINE_CACHE_ENTRIES_FOR_ITER);
2505
30.7k
    PyObject *iter_o = PyStackRef_AsPyObjectBorrow(iter);
2506
30.7k
    PyTypeObject *tp = Py_TYPE(iter_o);
2507
2508
30.7k
    if (PyStackRef_IsNull(null_or_index)) {
2509
#ifdef Py_GIL_DISABLED
2510
        // Only specialize for uniquely referenced iterators, so that we know
2511
        // they're only referenced by this one thread. This is more limiting
2512
        // than we need (even `it = iter(mylist); for item in it:` won't get
2513
        // specialized) but we don't have a way to check whether we're the only
2514
        // _thread_ who has access to the object.
2515
        if (!_PyObject_IsUniquelyReferenced(iter_o)) {
2516
            goto failure;
2517
        }
2518
#endif
2519
23.7k
        if (tp == &PyRangeIter_Type) {
2520
25
            specialize(instr, FOR_ITER_RANGE);
2521
25
            return;
2522
25
        }
2523
23.7k
        else if (tp == &PyGen_Type && oparg <= SHRT_MAX) {
2524
            // Generators are very much not thread-safe, so don't worry about
2525
            // the specialization not being thread-safe.
2526
66
            assert(instr[oparg + INLINE_CACHE_ENTRIES_FOR_ITER + 1].op.code == END_FOR  ||
2527
66
                instr[oparg + INLINE_CACHE_ENTRIES_FOR_ITER + 1].op.code == INSTRUMENTED_END_FOR
2528
66
            );
2529
            /* Don't specialize if PEP 523 is active */
2530
66
            if (_PyInterpreterState_GET()->eval_frame) {
2531
0
                goto failure;
2532
0
            }
2533
66
            specialize(instr, FOR_ITER_GEN);
2534
66
            return;
2535
66
        }
2536
23.7k
    }
2537
6.96k
    else {
2538
6.96k
        if (tp == &PyList_Type) {
2539
#ifdef Py_GIL_DISABLED
2540
            // Only specialize for lists owned by this thread or shared
2541
            if (!_Py_IsOwnedByCurrentThread(iter_o) && !_PyObject_GC_IS_SHARED(iter_o)) {
2542
                goto failure;
2543
            }
2544
#endif
2545
6.51k
            specialize(instr, FOR_ITER_LIST);
2546
6.51k
            return;
2547
6.51k
        }
2548
446
        else if (tp == &PyTuple_Type) {
2549
446
            specialize(instr, FOR_ITER_TUPLE);
2550
446
            return;
2551
446
        }
2552
6.96k
    }
2553
23.6k
failure:
2554
23.6k
    SPECIALIZATION_FAIL(FOR_ITER,
2555
23.6k
                        _PySpecialization_ClassifyIterator(iter_o));
2556
23.6k
    unspecialize(instr);
2557
23.6k
}
2558
2559
Py_NO_INLINE void
2560
_Py_Specialize_Send(_PyStackRef receiver_st, _Py_CODEUNIT *instr)
2561
9
{
2562
9
    PyObject *receiver = PyStackRef_AsPyObjectBorrow(receiver_st);
2563
2564
9
    assert(ENABLE_SPECIALIZATION_FT);
2565
9
    assert(_PyOpcode_Caches[SEND] == INLINE_CACHE_ENTRIES_SEND);
2566
9
    PyTypeObject *tp = Py_TYPE(receiver);
2567
9
    if (tp == &PyGen_Type || tp == &PyCoro_Type) {
2568
        /* Don't specialize if PEP 523 is active */
2569
0
        if (_PyInterpreterState_GET()->eval_frame) {
2570
0
            SPECIALIZATION_FAIL(SEND, SPEC_FAIL_OTHER);
2571
0
            goto failure;
2572
0
        }
2573
0
        specialize(instr, SEND_GEN);
2574
0
        return;
2575
0
    }
2576
9
    SPECIALIZATION_FAIL(SEND,
2577
9
                        _PySpecialization_ClassifyIterator(receiver));
2578
9
failure:
2579
9
    unspecialize(instr);
2580
9
}
2581
2582
#ifdef Py_STATS
2583
static int
2584
to_bool_fail_kind(PyObject *value)
2585
{
2586
    if (PyByteArray_CheckExact(value)) {
2587
        return SPEC_FAIL_TO_BOOL_BYTEARRAY;
2588
    }
2589
    if (PyBytes_CheckExact(value)) {
2590
        return SPEC_FAIL_TO_BOOL_BYTES;
2591
    }
2592
    if (PyDict_CheckExact(value)) {
2593
        return SPEC_FAIL_TO_BOOL_DICT;
2594
    }
2595
    if (PyFloat_CheckExact(value)) {
2596
        return SPEC_FAIL_TO_BOOL_FLOAT;
2597
    }
2598
    if (PyMemoryView_Check(value)) {
2599
        return SPEC_FAIL_TO_BOOL_MEMORY_VIEW;
2600
    }
2601
    if (PyAnySet_CheckExact(value)) {
2602
        return SPEC_FAIL_TO_BOOL_SET;
2603
    }
2604
    if (PyTuple_CheckExact(value)) {
2605
        return SPEC_FAIL_TO_BOOL_TUPLE;
2606
    }
2607
    return SPEC_FAIL_OTHER;
2608
}
2609
#endif  // Py_STATS
2610
2611
static int
2612
check_type_always_true(PyTypeObject *ty)
2613
1.06k
{
2614
1.06k
    PyNumberMethods *nb = ty->tp_as_number;
2615
1.06k
    if (nb && nb->nb_bool) {
2616
19
        return SPEC_FAIL_TO_BOOL_NUMBER;
2617
19
    }
2618
1.04k
    PyMappingMethods *mp = ty->tp_as_mapping;
2619
1.04k
    if (mp && mp->mp_length) {
2620
1.04k
        return SPEC_FAIL_TO_BOOL_MAPPING;
2621
1.04k
    }
2622
4
    PySequenceMethods *sq = ty->tp_as_sequence;
2623
4
    if (sq && sq->sq_length) {
2624
0
      return SPEC_FAIL_TO_BOOL_SEQUENCE;
2625
0
    }
2626
4
    return 0;
2627
4
}
2628
2629
Py_NO_INLINE void
2630
_Py_Specialize_ToBool(_PyStackRef value_o, _Py_CODEUNIT *instr)
2631
11.1k
{
2632
11.1k
    assert(ENABLE_SPECIALIZATION_FT);
2633
11.1k
    assert(_PyOpcode_Caches[TO_BOOL] == INLINE_CACHE_ENTRIES_TO_BOOL);
2634
11.1k
    _PyToBoolCache *cache = (_PyToBoolCache *)(instr + 1);
2635
11.1k
    PyObject *value = PyStackRef_AsPyObjectBorrow(value_o);
2636
11.1k
    uint8_t specialized_op;
2637
11.1k
    if (PyBool_Check(value)) {
2638
2.75k
        specialized_op = TO_BOOL_BOOL;
2639
2.75k
        goto success;
2640
2.75k
    }
2641
8.36k
    if (PyLong_CheckExact(value)) {
2642
1.39k
        specialized_op = TO_BOOL_INT;
2643
1.39k
        goto success;
2644
1.39k
    }
2645
6.96k
    if (PyList_CheckExact(value)) {
2646
162
        specialized_op = TO_BOOL_LIST;
2647
162
        goto success;
2648
162
    }
2649
6.79k
    if (Py_IsNone(value)) {
2650
1.48k
        specialized_op = TO_BOOL_NONE;
2651
1.48k
        goto success;
2652
1.48k
    }
2653
5.31k
    if (PyUnicode_CheckExact(value)) {
2654
549
        specialized_op = TO_BOOL_STR;
2655
549
        goto success;
2656
549
    }
2657
4.76k
    if (PyType_HasFeature(Py_TYPE(value), Py_TPFLAGS_HEAPTYPE)) {
2658
1.06k
        unsigned int version = 0;
2659
1.06k
        int err = _PyType_Validate(Py_TYPE(value), check_type_always_true, &version);
2660
1.06k
        if (err < 0) {
2661
0
            SPECIALIZATION_FAIL(TO_BOOL, SPEC_FAIL_OUT_OF_VERSIONS);
2662
0
            goto failure;
2663
0
        }
2664
1.06k
        else if (err > 0) {
2665
1.06k
            SPECIALIZATION_FAIL(TO_BOOL, err);
2666
1.06k
            goto failure;
2667
1.06k
        }
2668
2669
1.06k
        assert(err == 0);
2670
4
        assert(version);
2671
4
        write_u32(cache->version, version);
2672
4
        specialized_op = TO_BOOL_ALWAYS_TRUE;
2673
4
        goto success;
2674
4
    }
2675
2676
3.69k
    SPECIALIZATION_FAIL(TO_BOOL, to_bool_fail_kind(value));
2677
4.75k
failure:
2678
4.75k
    unspecialize(instr);
2679
4.75k
    return;
2680
6.35k
success:
2681
6.35k
    specialize(instr, specialized_op);
2682
6.35k
}
2683
2684
#ifdef Py_STATS
2685
static int
2686
containsop_fail_kind(PyObject *value) {
2687
    if (PyUnicode_CheckExact(value)) {
2688
        return SPEC_FAIL_CONTAINS_OP_STR;
2689
    }
2690
    if (PyList_CheckExact(value)) {
2691
        return SPEC_FAIL_CONTAINS_OP_LIST;
2692
    }
2693
    if (PyTuple_CheckExact(value)) {
2694
        return SPEC_FAIL_CONTAINS_OP_TUPLE;
2695
    }
2696
    if (PyType_Check(value)) {
2697
        return SPEC_FAIL_CONTAINS_OP_USER_CLASS;
2698
    }
2699
    return SPEC_FAIL_OTHER;
2700
}
2701
#endif
2702
2703
Py_NO_INLINE void
2704
_Py_Specialize_ContainsOp(_PyStackRef value_st, _Py_CODEUNIT *instr)
2705
6.65k
{
2706
6.65k
    PyObject *value = PyStackRef_AsPyObjectBorrow(value_st);
2707
2708
6.65k
    assert(ENABLE_SPECIALIZATION_FT);
2709
6.65k
    assert(_PyOpcode_Caches[CONTAINS_OP] == INLINE_CACHE_ENTRIES_COMPARE_OP);
2710
6.65k
    if (PyDict_CheckExact(value)) {
2711
233
        specialize(instr, CONTAINS_OP_DICT);
2712
233
        return;
2713
233
    }
2714
6.41k
    if (PySet_CheckExact(value) || PyFrozenSet_CheckExact(value)) {
2715
194
        specialize(instr, CONTAINS_OP_SET);
2716
194
        return;
2717
194
    }
2718
2719
6.22k
    SPECIALIZATION_FAIL(CONTAINS_OP, containsop_fail_kind(value));
2720
6.22k
    unspecialize(instr);
2721
6.22k
    return;
2722
6.41k
}
2723
2724
#ifdef Py_STATS
2725
void
2726
_Py_GatherStats_GetIter(_PyStackRef iterable)
2727
{
2728
    PyTypeObject *tp = PyStackRef_TYPE(iterable);
2729
    int kind = SPEC_FAIL_OTHER;
2730
    if (tp == &PyTuple_Type) {
2731
        kind = SPEC_FAIL_ITER_TUPLE;
2732
    }
2733
    else if (tp == &PyList_Type) {
2734
        kind = SPEC_FAIL_ITER_LIST;
2735
    }
2736
    else if (tp == &PyDict_Type) {
2737
        kind = SPEC_FAIL_ITER_DICT_KEYS;
2738
    }
2739
    else if (tp == &PySet_Type) {
2740
        kind = SPEC_FAIL_ITER_SET;
2741
    }
2742
    else if (tp == &PyBytes_Type) {
2743
        kind = SPEC_FAIL_ITER_BYTES;
2744
    }
2745
    else if (tp == &PyEnum_Type) {
2746
        kind = SPEC_FAIL_ITER_ENUMERATE;
2747
    }
2748
    else if (tp == &PyUnicode_Type) {
2749
        kind = SPEC_FAIL_ITER_STRING;
2750
    }
2751
    else if (tp == &PyGen_Type) {
2752
        kind = SPEC_FAIL_ITER_GENERATOR;
2753
    }
2754
    else if (tp == &PyCoro_Type) {
2755
        kind = SPEC_FAIL_ITER_COROUTINE;
2756
    }
2757
    else if (tp == &PyAsyncGen_Type) {
2758
        kind = SPEC_FAIL_ITER_ASYNC_GENERATOR;
2759
    }
2760
    else if (tp == &_PyAsyncGenASend_Type) {
2761
        kind = SPEC_FAIL_ITER_ASYNC_GENERATOR_SEND;
2762
    }
2763
    else if (tp->tp_iter == PyObject_SelfIter) {
2764
        kind = SPEC_FAIL_ITER_SELF;
2765
    }
2766
    SPECIALIZATION_FAIL(GET_ITER, kind);
2767
}
2768
#endif
2769
2770
2771
/* Code init cleanup.
2772
 * CALL_ALLOC_AND_ENTER_INIT will set up
2773
 * the frame to execute the EXIT_INIT_CHECK
2774
 * instruction.
2775
 * Ends with a RESUME so that it is not traced.
2776
 * This is used as a plain code object, not a function,
2777
 * so must not access globals or builtins.
2778
 * There are a few other constraints imposed on the code
2779
 * by the free-threaded build:
2780
 *
2781
 * 1. The RESUME instruction must not be executed. Otherwise we may attempt to
2782
 *    free the statically allocated TLBC array.
2783
 * 2. It must contain no specializable instructions. Specializing multiple
2784
 *    copies of the same bytecode is not thread-safe in free-threaded builds.
2785
 *
2786
 * This should be dynamically allocated if either of those restrictions need to
2787
 * be lifted.
2788
 */
2789
2790
#define NO_LOC_4 (128 | (PY_CODE_LOCATION_INFO_NONE << 3) | 3)
2791
2792
static const PyBytesObject no_location = {
2793
    PyVarObject_HEAD_INIT(&PyBytes_Type, 1)
2794
    .ob_sval = { NO_LOC_4 }
2795
};
2796
2797
#ifdef Py_GIL_DISABLED
2798
static _PyCodeArray init_cleanup_tlbc = {
2799
    .size = 1,
2800
    .entries = {(char*) &_Py_InitCleanup.co_code_adaptive},
2801
};
2802
#endif
2803
2804
const struct _PyCode8 _Py_InitCleanup = {
2805
    _PyVarObject_HEAD_INIT(&PyCode_Type, 3),
2806
    .co_consts = (PyObject *)&_Py_SINGLETON(tuple_empty),
2807
    .co_names = (PyObject *)&_Py_SINGLETON(tuple_empty),
2808
    .co_exceptiontable = (PyObject *)&_Py_SINGLETON(bytes_empty),
2809
    .co_flags = CO_OPTIMIZED | CO_NO_MONITORING_EVENTS,
2810
    .co_localsplusnames = (PyObject *)&_Py_SINGLETON(tuple_empty),
2811
    .co_localspluskinds = (PyObject *)&_Py_SINGLETON(bytes_empty),
2812
    .co_filename = &_Py_ID(__init__),
2813
    .co_name = &_Py_ID(__init__),
2814
    .co_qualname = &_Py_ID(__init__),
2815
    .co_linetable = (PyObject *)&no_location,
2816
    ._co_firsttraceable = 4,
2817
    .co_stacksize = 2,
2818
    .co_framesize = 2 + FRAME_SPECIALS_SIZE,
2819
#ifdef Py_GIL_DISABLED
2820
    .co_tlbc = &init_cleanup_tlbc,
2821
#endif
2822
    .co_code_adaptive = {
2823
        EXIT_INIT_CHECK, 0,
2824
        RETURN_VALUE, 0,
2825
        RESUME, RESUME_AT_FUNC_START,
2826
    }
2827
};