/
_dispatcher.cpp
1281 lines (1167 loc) · 42.9 KB
/
_dispatcher.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "_pymodule.h"
#include <cstring>
#include <ctime>
#include <cassert>
#include <vector>
#include "_typeof.h"
#include "frameobject.h"
#include "traceback.h"
#include "core/typeconv/typeconv.hpp"
#include "_devicearray.h"
/*
* Notes on the C_TRACE macro:
*
* The original C_TRACE macro (from ceval.c) would call
* PyTrace_C_CALL et al., for which the frame argument wouldn't
* be usable. Since we explicitly synthesize a frame using the
* original Python code object, we call PyTrace_CALL instead so
* the profiler can report the correct source location.
*
* Likewise, while ceval.c would call PyTrace_C_EXCEPTION in case
* of error, the profiler would simply expect a RETURN in case of
* a Python function, so we generate that here (making sure the
* exception state is preserved correctly).
*
*/
#if (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 12)
/* empty */
#elif (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 11)
#ifndef Py_BUILD_CORE
#define Py_BUILD_CORE 1
#endif
#include "internal/pycore_frame.h"
#include "internal/pycore_pyerrors.h"
/*
* Code originally from:
* https://github.com/python/cpython/blob/deaf509e8fc6e0363bd6f26d52ad42f976ec42f2/Python/ceval.c#L6804
*/
static int
call_trace(Py_tracefunc func, PyObject *obj,
PyThreadState *tstate, PyFrameObject *frame,
int what, PyObject *arg)
{
int result;
if (tstate->tracing) {
return 0;
}
if (frame == NULL) {
return -1;
}
int old_what = tstate->tracing_what;
tstate->tracing_what = what;
PyThreadState_EnterTracing(tstate);
result = func(obj, frame, what, NULL);
PyThreadState_LeaveTracing(tstate);
tstate->tracing_what = old_what;
return result;
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/d5650a1738fe34f6e1db4af5f4c4edb7cae90a36/Python/ceval.c#L4220-L4240
*/
static int
call_trace_protected(Py_tracefunc func, PyObject *obj,
PyThreadState *tstate, PyFrameObject *frame,
int what, PyObject *arg)
{
PyObject *type, *value, *traceback;
int err;
_PyErr_Fetch(tstate, &type, &value, &traceback);
err = call_trace(func, obj, tstate, frame, what, arg);
if (err == 0)
{
_PyErr_Restore(tstate, type, value, traceback);
return 0;
}
else {
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
return -1;
}
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/deaf509e8fc6e0363bd6f26d52ad42f976ec42f2/Python/ceval.c#L7245
* NOTE: The state test https://github.com/python/cpython/blob/d5650a1738fe34f6e1db4af5f4c4edb7cae90a36/Python/ceval.c#L4521
* has been removed, it's dealt with in call_cfunc.
*/
#define C_TRACE(x, call, frame) \
if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
tstate, frame, \
PyTrace_CALL, cfunc)) { \
x = NULL; \
} \
else { \
x = call; \
if (tstate->c_profilefunc != NULL) { \
if (x == NULL) { \
call_trace_protected(tstate->c_profilefunc, \
tstate->c_profileobj, \
tstate, frame, \
PyTrace_RETURN, cfunc); \
/* XXX should pass (type, value, tb) */ \
} else { \
if (call_trace(tstate->c_profilefunc, \
tstate->c_profileobj, \
tstate, frame, \
PyTrace_RETURN, cfunc)) { \
Py_DECREF(x); \
x = NULL; \
} \
} \
} \
} \
#elif (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 10 || PY_MINOR_VERSION == 11)
/*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Python/ceval.c#L36-L40
*/
typedef struct {
PyCodeObject *code; // The code object for the bounds. May be NULL.
PyCodeAddressRange bounds; // Only valid if code != NULL.
CFrame cframe;
} PyTraceInfo;
/*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Objects/codeobject.c#L1257-L1266
* NOTE: The function is renamed.
*/
static void
_nb_PyLineTable_InitAddressRange(const char *linetable, Py_ssize_t length, int firstlineno, PyCodeAddressRange *range)
{
range->opaque.lo_next = linetable;
range->opaque.limit = range->opaque.lo_next + length;
range->ar_start = -1;
range->ar_end = 0;
range->opaque.computed_line = firstlineno;
range->ar_line = -1;
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Objects/codeobject.c#L1269-L1275
* NOTE: The function is renamed.
*/
static int
_nb_PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds)
{
const char *linetable = PyBytes_AS_STRING(co->co_linetable);
Py_ssize_t length = PyBytes_GET_SIZE(co->co_linetable);
_nb_PyLineTable_InitAddressRange(linetable, length, co->co_firstlineno, bounds);
return bounds->ar_line;
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Python/ceval.c#L5468-L5475
* NOTE: The call to _PyCode_InitAddressRange is renamed.
*/
static void
initialize_trace_info(PyTraceInfo *trace_info, PyFrameObject *frame)
{
if (trace_info->code != frame->f_code) {
trace_info->code = frame->f_code;
_nb_PyCode_InitAddressRange(frame->f_code, &trace_info->bounds);
}
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Python/ceval.c#L5477-L5501
*/
static int
call_trace(Py_tracefunc func, PyObject *obj,
PyThreadState *tstate, PyFrameObject *frame,
PyTraceInfo *trace_info,
int what, PyObject *arg)
{
int result;
if (tstate->tracing)
return 0;
tstate->tracing++;
tstate->cframe->use_tracing = 0;
if (frame->f_lasti < 0) {
frame->f_lineno = frame->f_code->co_firstlineno;
}
else {
initialize_trace_info(trace_info, frame);
frame->f_lineno = _PyCode_CheckLineNumber(frame->f_lasti*sizeof(_Py_CODEUNIT), &trace_info->bounds);
}
result = func(obj, frame, what, arg);
frame->f_lineno = 0;
tstate->cframe->use_tracing = ((tstate->c_tracefunc != NULL)
|| (tstate->c_profilefunc != NULL));
tstate->tracing--;
return result;
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Python/ceval.c#L5445-L5466
*/
static int
call_trace_protected(Py_tracefunc func, PyObject *obj,
PyThreadState *tstate, PyFrameObject *frame,
PyTraceInfo *trace_info,
int what, PyObject *arg)
{
PyObject *type, *value, *traceback;
int err;
PyErr_Fetch(&type, &value, &traceback);
err = call_trace(func, obj, tstate, frame, trace_info, what, arg);
if (err == 0)
{
PyErr_Restore(type, value, traceback);
return 0;
}
else
{
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
return -1;
}
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Python/ceval.c#L5810-L5839
* NOTE: The state test https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Python/ceval.c#L5811
* has been removed, it's dealt with in call_cfunc.
*/
#define C_TRACE(x, call) \
if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
tstate, tstate->frame, &trace_info, PyTrace_CALL,\
cfunc)) \
x = NULL; \
else \
{ \
x = call; \
if (tstate->c_profilefunc != NULL) \
{ \
if (x == NULL) \
{ \
call_trace_protected(tstate->c_profilefunc, \
tstate->c_profileobj, \
tstate, tstate->frame, \
&trace_info, \
PyTrace_RETURN, cfunc); \
/* XXX should pass (type, value, tb) */ \
} \
else \
{ \
if (call_trace(tstate->c_profilefunc, \
tstate->c_profileobj, \
tstate, tstate->frame, \
&trace_info, \
PyTrace_RETURN, cfunc)) \
{ \
Py_DECREF(x); \
x = NULL; \
} \
} \
} \
}
#else // Python <3.10
/*
* Code originally from:
* https://github.com/python/cpython/blob/d5650a1738fe34f6e1db4af5f4c4edb7cae90a36/Python/ceval.c#L4242-L4257
*/
static int
call_trace(Py_tracefunc func, PyObject *obj,
PyThreadState *tstate, PyFrameObject *frame,
int what, PyObject *arg)
{
int result;
if (tstate->tracing)
return 0;
tstate->tracing++;
tstate->use_tracing = 0;
result = func(obj, frame, what, arg);
tstate->use_tracing = ((tstate->c_tracefunc != NULL)
|| (tstate->c_profilefunc != NULL));
tstate->tracing--;
return result;
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/d5650a1738fe34f6e1db4af5f4c4edb7cae90a36/Python/ceval.c#L4220-L4240
*/
static int
call_trace_protected(Py_tracefunc func, PyObject *obj,
PyThreadState *tstate, PyFrameObject *frame,
int what, PyObject *arg)
{
PyObject *type, *value, *traceback;
int err;
PyErr_Fetch(&type, &value, &traceback);
err = call_trace(func, obj, tstate, frame, what, arg);
if (err == 0)
{
PyErr_Restore(type, value, traceback);
return 0;
}
else
{
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
return -1;
}
}
/*
* Code originally from:
* https://github.com/python/cpython/blob/d5650a1738fe34f6e1db4af5f4c4edb7cae90a36/Python/ceval.c#L4520-L4549
* NOTE: The state test https://github.com/python/cpython/blob/d5650a1738fe34f6e1db4af5f4c4edb7cae90a36/Python/ceval.c#L4521
* has been removed, it's dealt with in call_cfunc.
*/
#define C_TRACE(x, call) \
if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, \
tstate, tstate->frame, PyTrace_CALL, cfunc)) \
x = NULL; \
else \
{ \
x = call; \
if (tstate->c_profilefunc != NULL) \
{ \
if (x == NULL) \
{ \
call_trace_protected(tstate->c_profilefunc, \
tstate->c_profileobj, \
tstate, tstate->frame, \
PyTrace_RETURN, cfunc); \
/* XXX should pass (type, value, tb) */ \
} \
else \
{ \
if (call_trace(tstate->c_profilefunc, \
tstate->c_profileobj, \
tstate, tstate->frame, \
PyTrace_RETURN, cfunc)) \
{ \
Py_DECREF(x); \
x = NULL; \
} \
} \
} \
}
#endif
typedef std::vector<Type> TypeTable;
typedef std::vector<PyObject*> Functions;
/* The Dispatcher class is the base class of all dispatchers in the CPU and
CUDA targets. Its main responsibilities are:
- Resolving the best overload to call for a given set of arguments, and
- Calling the resolved overload.
This logic is implemented within this class for efficiency (lookup of the
appropriate overload needs to be fast) and ease of implementation (calling
directly into a compiled function using a function pointer is easier within
the C++ code where the overload has been resolved). */
class Dispatcher {
public:
PyObject_HEAD
/* Whether compilation of new overloads is permitted */
char can_compile;
/* Whether fallback to object mode is permitted */
char can_fallback;
/* Whether types must match exactly when resolving overloads.
If not, conversions (e.g. float32 -> float64) are permitted when
searching for a match. */
char exact_match_required;
/* Borrowed reference */
PyObject *fallbackdef;
/* Whether to fold named arguments and default values
(false for lifted loops) */
int fold_args;
/* Whether the last positional argument is a stararg */
int has_stararg;
/* Tuple of argument names */
PyObject *argnames;
/* Tuple of default values */
PyObject *defargs;
/* Number of arguments to function */
int argct;
/* Used for selecting overloaded function implementations */
TypeManager *tm;
/* An array of overloads */
Functions functions;
/* A flattened array of argument types to all overloads
* (invariant: sizeof(overloads) == argct * sizeof(functions)) */
TypeTable overloads;
/* Add a new overload. Parameters:
- args: An array of Type objects, one for each parameter
- callable: The callable implementing this overload. */
void addDefinition(Type args[], PyObject *callable) {
overloads.reserve(argct + overloads.size());
for (int i=0; i<argct; ++i) {
overloads.push_back(args[i]);
}
functions.push_back(callable);
}
/* Given a list of types, find the overloads that have a matching signature.
Returns the best match, as well as the number of matches found.
Parameters:
- sig: an array of Type objects, one for each parameter.
- matches: the number of matches found (mutated by this function).
- allow_unsafe: whether to match overloads that would require an unsafe
cast.
- exact_match_required: Whether all arguments types must match the
overload's types exactly. When false,
overloads that would require a type conversion
can also be matched. */
PyObject* resolve(Type sig[], int &matches, bool allow_unsafe,
bool exact_match_required) const {
const int ovct = functions.size();
int selected;
matches = 0;
if (0 == ovct) {
// No overloads registered
return NULL;
}
if (argct == 0) {
// Nullary function: trivial match on first overload
matches = 1;
selected = 0;
}
else {
matches = tm->selectOverload(sig, &overloads[0], selected, argct,
ovct, allow_unsafe,
exact_match_required);
}
if (matches == 1) {
return functions[selected];
}
return NULL;
}
/* Remove all overloads */
void clear() {
functions.clear();
overloads.clear();
}
};
static int
Dispatcher_traverse(Dispatcher *self, visitproc visit, void *arg)
{
Py_VISIT(self->defargs);
return 0;
}
static void
Dispatcher_dealloc(Dispatcher *self)
{
Py_XDECREF(self->argnames);
Py_XDECREF(self->defargs);
self->clear();
Py_TYPE(self)->tp_free((PyObject*)self);
}
static int
Dispatcher_init(Dispatcher *self, PyObject *args, PyObject *kwds)
{
PyObject *tmaddrobj;
void *tmaddr;
int argct;
int can_fallback;
int has_stararg = 0;
int exact_match_required = 0;
if (!PyArg_ParseTuple(args, "OiiO!O!i|ii", &tmaddrobj, &argct,
&self->fold_args,
&PyTuple_Type, &self->argnames,
&PyTuple_Type, &self->defargs,
&can_fallback,
&has_stararg,
&exact_match_required
)) {
return -1;
}
Py_INCREF(self->argnames);
Py_INCREF(self->defargs);
tmaddr = PyLong_AsVoidPtr(tmaddrobj);
self->tm = static_cast<TypeManager*>(tmaddr);
self->argct = argct;
self->can_compile = 1;
self->can_fallback = can_fallback;
self->fallbackdef = NULL;
self->has_stararg = has_stararg;
self->exact_match_required = exact_match_required;
return 0;
}
static PyObject *
Dispatcher_clear(Dispatcher *self, PyObject *args)
{
self->clear();
Py_RETURN_NONE;
}
static
PyObject*
Dispatcher_Insert(Dispatcher *self, PyObject *args, PyObject *kwds)
{
/* The cuda kwarg is a temporary addition until CUDA overloads are compiled
* functions. Once they are compiled functions, kwargs can be removed from
* this function. */
static char *keywords[] = {
(char*)"sig",
(char*)"func",
(char*)"objectmode",
(char*)"cuda",
NULL
};
PyObject *sigtup, *cfunc;
int i, sigsz;
int *sig;
int objectmode = 0;
int cuda = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|ip", keywords, &sigtup,
&cfunc, &objectmode, &cuda)) {
return NULL;
}
if (!cuda && !PyObject_TypeCheck(cfunc, &PyCFunction_Type) ) {
PyErr_SetString(PyExc_TypeError, "must be builtin_function_or_method");
return NULL;
}
sigsz = PySequence_Fast_GET_SIZE(sigtup);
sig = new int[sigsz];
for (i = 0; i < sigsz; ++i) {
sig[i] = PyLong_AsLong(PySequence_Fast_GET_ITEM(sigtup, i));
}
/* The reference to cfunc is borrowed; this only works because the
derived Python class also stores an (owned) reference to cfunc. */
self->addDefinition(sig, cfunc);
/* Add pure python fallback */
if (!self->fallbackdef && objectmode){
self->fallbackdef = cfunc;
}
delete[] sig;
Py_RETURN_NONE;
}
static
void explain_issue(PyObject *dispatcher, PyObject *args, PyObject *kws,
const char *method_name, const char *default_msg)
{
PyObject *callback, *result;
callback = PyObject_GetAttrString(dispatcher, method_name);
if (!callback) {
PyErr_SetString(PyExc_TypeError, default_msg);
return;
}
result = PyObject_Call(callback, args, kws);
Py_DECREF(callback);
if (result != NULL) {
PyErr_Format(PyExc_RuntimeError, "%s must raise an exception",
method_name);
Py_DECREF(result);
}
}
static
void explain_ambiguous(PyObject *dispatcher, PyObject *args, PyObject *kws)
{
explain_issue(dispatcher, args, kws, "_explain_ambiguous",
"Ambiguous overloading");
}
static
void explain_matching_error(PyObject *dispatcher, PyObject *args, PyObject *kws)
{
explain_issue(dispatcher, args, kws, "_explain_matching_error",
"No matching definition");
}
static
int search_new_conversions(PyObject *dispatcher, PyObject *args, PyObject *kws)
{
PyObject *callback, *result;
int res;
callback = PyObject_GetAttrString(dispatcher,
"_search_new_conversions");
if (!callback) {
return -1;
}
result = PyObject_Call(callback, args, kws);
Py_DECREF(callback);
if (result == NULL) {
return -1;
}
if (!PyBool_Check(result)) {
Py_DECREF(result);
PyErr_SetString(PyExc_TypeError,
"_search_new_conversions() should return a boolean");
return -1;
}
res = (result == Py_True) ? 1 : 0;
Py_DECREF(result);
return res;
}
/* A custom, fast, inlinable version of PyCFunction_Call() */
static PyObject *
call_cfunc(Dispatcher *self, PyObject *cfunc, PyObject *args, PyObject *kws, PyObject *locals)
{
PyCFunctionWithKeywords fn;
PyThreadState *tstate;
assert(PyCFunction_Check(cfunc));
assert(PyCFunction_GET_FLAGS(cfunc) == (METH_VARARGS | METH_KEYWORDS));
fn = (PyCFunctionWithKeywords) PyCFunction_GET_FUNCTION(cfunc);
tstate = PyThreadState_GET();
#if (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 12)
/* FIXME: as per the changes from PEP 669 Numba does not support profiling
* (yet?). Just skip frame injection entirely. JIT compiled functions will
* NOT show up in cProfile profiler.
*/
if (0)
#elif (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 11)
/*
* On Python 3.11, _PyEval_EvalFrameDefault stops using PyTraceInfo since
* it's now baked into ThreadState.
* https://github.com/python/cpython/pull/26623
*/
if (tstate->cframe->use_tracing && tstate->c_profilefunc)
#elif (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 10)
/*
* On Python 3.10+ trace_info comes from somewhere up in PyFrameEval et al,
* Numba doesn't have access to that so creates an equivalent struct and
* wires it up against the cframes. This is passed into the tracing
* functions.
*
* Code originally from:
* https://github.com/python/cpython/blob/c5bfb88eb6f82111bb1603ae9d78d0476b552d66/Python/ceval.c#L1611-L1622
*/
PyTraceInfo trace_info;
trace_info.code = NULL; // not initialized
CFrame *prev_cframe = tstate->cframe;
trace_info.cframe.use_tracing = prev_cframe->use_tracing;
trace_info.cframe.previous = prev_cframe;
if (trace_info.cframe.use_tracing && tstate->c_profilefunc)
#else
/*
* On Python prior to 3.10, tracing state is a member of the threadstate
*/
if (tstate->use_tracing && tstate->c_profilefunc)
#endif
{
/*
* The following code requires some explaining:
*
* We want the jit-compiled function to be visible to the profiler, so we
* need to synthesize a frame for it.
* The PyFrame_New() constructor doesn't do anything with the 'locals' value if the 'code's
* 'CO_NEWLOCALS' flag is set (which is always the case nowadays).
* So, to get local variables into the frame, we have to manually set the 'f_locals'
* member, then call `PyFrame_LocalsToFast`, where a subsequent call to the `frame.f_locals`
* property (by virtue of the `frame_getlocals` function in frameobject.c) will find them.
*/
PyCodeObject *code = (PyCodeObject*)PyObject_GetAttrString((PyObject*)self, "__code__");
PyObject *globals = PyDict_New();
PyObject *builtins = PyEval_GetBuiltins();
PyFrameObject *frame = NULL;
PyObject *result = NULL;
if (!code) {
PyErr_Format(PyExc_RuntimeError, "No __code__ attribute found.");
goto error;
}
/* Populate builtins, which is required by some JITted functions */
if (PyDict_SetItemString(globals, "__builtins__", builtins)) {
goto error;
}
/* unset the CO_OPTIMIZED flag, make the frame get a new locals dict */
code->co_flags &= 0xFFFE;
frame = PyFrame_New(tstate, code, globals, locals);
if (frame == NULL) {
goto error;
}
/* Populate the 'fast locals' in `frame` */
PyFrame_LocalsToFast(frame, 0);
#if (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 12)
/* empty */
#elif (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION == 11)
C_TRACE(result, fn(PyCFunction_GET_SELF(cfunc), args, kws), frame);
#else
tstate->frame = frame;
C_TRACE(result, fn(PyCFunction_GET_SELF(cfunc), args, kws));
/* write changes back to locals? */
PyFrame_FastToLocals(frame);
tstate->frame = frame->f_back;
#endif
error:
Py_XDECREF(frame);
Py_XDECREF(globals);
Py_XDECREF(code);
return result;
}
else
{
return fn(PyCFunction_GET_SELF(cfunc), args, kws);
}
}
static
PyObject*
compile_and_invoke(Dispatcher *self, PyObject *args, PyObject *kws, PyObject *locals)
{
/* Compile a new one */
PyObject *cfa, *cfunc, *retval;
cfa = PyObject_GetAttrString((PyObject*)self, "_compile_for_args");
if (cfa == NULL)
return NULL;
/* NOTE: we call the compiled function ourselves instead of
letting the Python derived class do it. This is for proper
behaviour of globals() in jitted functions (issue #476). */
cfunc = PyObject_Call(cfa, args, kws);
Py_DECREF(cfa);
if (cfunc == NULL)
return NULL;
if (PyObject_TypeCheck(cfunc, &PyCFunction_Type)) {
retval = call_cfunc(self, cfunc, args, kws, locals);
} else {
/* Re-enter interpreter */
retval = PyObject_Call(cfunc, args, kws);
}
Py_DECREF(cfunc);
return retval;
}
/* A copy of compile_and_invoke, that only compiles. This is needed for CUDA
* kernels, because its overloads are Python instances of the _Kernel class,
* rather than compiled functions. Once CUDA overloads are compiled functions,
* cuda_compile_only can be removed. */
static
PyObject*
cuda_compile_only(Dispatcher *self, PyObject *args, PyObject *kws, PyObject *locals)
{
/* Compile a new one */
PyObject *cfa, *cfunc;
cfa = PyObject_GetAttrString((PyObject*)self, "_compile_for_args");
if (cfa == NULL)
return NULL;
cfunc = PyObject_Call(cfa, args, kws);
Py_DECREF(cfa);
return cfunc;
}
static int
find_named_args(Dispatcher *self, PyObject **pargs, PyObject **pkws)
{
PyObject *oldargs = *pargs, *newargs;
PyObject *kws = *pkws;
Py_ssize_t pos_args = PyTuple_GET_SIZE(oldargs);
Py_ssize_t named_args, total_args, i;
Py_ssize_t func_args = PyTuple_GET_SIZE(self->argnames);
Py_ssize_t defaults = PyTuple_GET_SIZE(self->defargs);
/* Last parameter with a default value */
Py_ssize_t last_def = (self->has_stararg)
? func_args - 2
: func_args - 1;
/* First parameter with a default value */
Py_ssize_t first_def = last_def - defaults + 1;
/* Minimum number of required arguments */
Py_ssize_t minargs = first_def;
if (kws != NULL)
named_args = PyDict_Size(kws);
else
named_args = 0;
total_args = pos_args + named_args;
if (!self->has_stararg && total_args > func_args) {
PyErr_Format(PyExc_TypeError,
"too many arguments: expected %d, got %d",
(int) func_args, (int) total_args);
return -1;
}
else if (total_args < minargs) {
if (minargs == func_args)
PyErr_Format(PyExc_TypeError,
"not enough arguments: expected %d, got %d",
(int) minargs, (int) total_args);
else
PyErr_Format(PyExc_TypeError,
"not enough arguments: expected at least %d, got %d",
(int) minargs, (int) total_args);
return -1;
}
newargs = PyTuple_New(func_args);
if (!newargs)
return -1;
/* First pack the stararg */
if (self->has_stararg) {
Py_ssize_t stararg_size = Py_MAX(0, pos_args - func_args + 1);
PyObject *stararg = PyTuple_New(stararg_size);
if (!stararg) {
Py_DECREF(newargs);
return -1;
}
for (i = 0; i < stararg_size; i++) {
PyObject *value = PyTuple_GET_ITEM(oldargs, func_args - 1 + i);
Py_INCREF(value);
PyTuple_SET_ITEM(stararg, i, value);
}
/* Put it in last position */
PyTuple_SET_ITEM(newargs, func_args - 1, stararg);
}
for (i = 0; i < pos_args; i++) {
PyObject *value = PyTuple_GET_ITEM(oldargs, i);
if (self->has_stararg && i >= func_args - 1) {
/* Skip stararg */
break;
}
Py_INCREF(value);
PyTuple_SET_ITEM(newargs, i, value);
}
/* Iterate over missing positional arguments, try to find them in
named arguments or default values. */
for (i = pos_args; i < func_args; i++) {
PyObject *name = PyTuple_GET_ITEM(self->argnames, i);
if (self->has_stararg && i >= func_args - 1) {
/* Skip stararg */
break;
}
if (kws != NULL) {
/* Named argument? */
PyObject *value = PyDict_GetItem(kws, name);
if (value != NULL) {
Py_INCREF(value);
PyTuple_SET_ITEM(newargs, i, value);
named_args--;
continue;
}
}
if (i >= first_def && i <= last_def) {
/* Argument has a default value? */
PyObject *value = PyTuple_GET_ITEM(self->defargs, i - first_def);
Py_INCREF(value);
PyTuple_SET_ITEM(newargs, i, value);
continue;
}
else if (i < func_args - 1 || !self->has_stararg) {
PyErr_Format(PyExc_TypeError,
"missing argument '%s'",
PyString_AsString(name));
Py_DECREF(newargs);
return -1;
}
}
if (named_args) {
PyErr_Format(PyExc_TypeError,
"some keyword arguments unexpected");
Py_DECREF(newargs);
return -1;
}
*pargs = newargs;
*pkws = NULL;
return 0;
}
static PyObject*
Dispatcher_call(Dispatcher *self, PyObject *args, PyObject *kws)
{
PyObject *tmptype, *retval = NULL;
int *tys = NULL;
int argct;
int i;
int prealloc[24];
int matches;
PyObject *cfunc;
PyThreadState *ts = PyThreadState_Get();
PyObject *locals = NULL;
/* If compilation is enabled, ensure that an exact match is found and if
* not compile one */
int exact_match_required = self->can_compile ? 1 : self->exact_match_required;
#if (PY_MAJOR_VERSION >= 3) && (PY_MINOR_VERSION >= 10)
if (ts->tracing && ts->c_profilefunc) {
#else
if (ts->use_tracing && ts->c_profilefunc) {
#endif
locals = PyEval_GetLocals();
if (locals == NULL) {
goto CLEANUP;
}
}
if (self->fold_args) {
if (find_named_args(self, &args, &kws))
return NULL;
}
else
Py_INCREF(args);
/* Now we own a reference to args */
argct = PySequence_Fast_GET_SIZE(args);
if (argct < (Py_ssize_t) (sizeof(prealloc) / sizeof(int)))
tys = prealloc;
else
tys = new int[argct];
for (i = 0; i < argct; ++i) {
tmptype = PySequence_Fast_GET_ITEM(args, i);
tys[i] = typeof_typecode((PyObject *) self, tmptype);
if (tys[i] == -1) {
if (self->can_fallback){
/* We will clear the exception if fallback is allowed. */
PyErr_Clear();
} else {
goto CLEANUP;
}
}
}
/* We only allow unsafe conversions if compilation of new specializations
has been disabled.
Note that the number of matches is returned in matches by resolve, which
accepts it as a reference. */
cfunc = self->resolve(tys, matches, !self->can_compile,
exact_match_required);
if (matches == 0 && !self->can_compile) {
/*
* If we can't compile a new specialization, look for
* matching signatures for which conversions haven't been
* registered on the C++ TypeManager.
*/
int res = search_new_conversions((PyObject *) self, args, kws);
if (res < 0) {
retval = NULL;
goto CLEANUP;
}
if (res > 0) {
/* Retry with the newly registered conversions */
cfunc = self->resolve(tys, matches, !self->can_compile,
exact_match_required);
}
}
if (matches == 1) {
/* Definition is found */
retval = call_cfunc(self, cfunc, args, kws, locals);
} else if (matches == 0) {
/* No matching definition */
if (self->can_compile) {
retval = compile_and_invoke(self, args, kws, locals);
} else if (self->fallbackdef) {