Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork34.2k
Expand file tree
/
Copy pathjit.c
More file actions
823 lines (754 loc) · 28 KB
/
jit.c
File metadata and controls
823 lines (754 loc) · 28 KB
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
#ifdef_Py_JIT
#include"Python.h"
#include"pycore_abstract.h"
#include"pycore_bitutils.h"
#include"pycore_call.h"
#include"pycore_ceval.h"
#include"pycore_critical_section.h"
#include"pycore_dict.h"
#include"pycore_floatobject.h"
#include"pycore_frame.h"
#include"pycore_function.h"
#include"pycore_import.h"
#include"pycore_interpframe.h"
#include"pycore_interpolation.h"
#include"pycore_intrinsics.h"
#include"pycore_lazyimportobject.h"
#include"pycore_list.h"
#include"pycore_long.h"
#include"pycore_mmap.h"
#include"pycore_opcode_metadata.h"
#include"pycore_opcode_utils.h"
#include"pycore_optimizer.h"
#include"pycore_pyerrors.h"
#include"pycore_setobject.h"
#include"pycore_sliceobject.h"
#include"pycore_template.h"
#include"pycore_tuple.h"
#include"pycore_unicodeobject.h"
#include"pycore_jit.h"
// Memory management stuff: ////////////////////////////////////////////////////
#ifndefMS_WINDOWS
#include<sys/mman.h>
#endif
staticsize_t
get_page_size(void)
{
#ifdefMS_WINDOWS
SYSTEM_INFOsi;
GetSystemInfo(&si);
returnsi.dwPageSize;
#else
returnsysconf(_SC_PAGESIZE);
#endif
}
staticvoid
jit_error(constchar*message)
{
#ifdefMS_WINDOWS
inthint=GetLastError();
#else
inthint=errno;
#endif
PyErr_Format(PyExc_RuntimeWarning,"JIT %s (%d)",message,hint);
}
staticsize_t_Py_jit_shim_size=0;
staticint
address_in_executor_list(_PyExecutorObject*head,uintptr_taddr)
{
for (_PyExecutorObject*exec=head;
exec!=NULL;
exec=exec->vm_data.links.next)
{
if (exec->jit_code==NULL||exec->jit_size==0) {
continue;
}
uintptr_tstart= (uintptr_t)exec->jit_code;
uintptr_tend=start+exec->jit_size;
if (addr >=start&&addr<end) {
return1;
}
}
return0;
}
PyAPI_FUNC(int)
_PyJIT_AddressInJitCode(PyInterpreterState*interp,uintptr_taddr)
{
if (interp==NULL) {
return0;
}
if (_Py_jit_entry!=_Py_LazyJitShim&&_Py_jit_shim_size!=0) {
uintptr_tstart= (uintptr_t)_Py_jit_entry;
uintptr_tend=start+_Py_jit_shim_size;
if (addr >=start&&addr<end) {
return1;
}
}
if (address_in_executor_list(interp->executor_list_head,addr)) {
return1;
}
if (address_in_executor_list(interp->executor_deletion_list_head,addr)) {
return1;
}
return0;
}
staticunsignedchar*
jit_alloc(size_tsize)
{
if (size>PY_MAX_JIT_CODE_SIZE) {
jit_error("code too big; refactor bytecodes.c to keep uop size down, or reduce maximum trace length.");
returnNULL;
}
assert(size);
assert(size %get_page_size()==0);
#ifdefMS_WINDOWS
intflags=MEM_COMMIT |MEM_RESERVE;
unsignedchar*memory=VirtualAlloc(NULL,size,flags,PAGE_READWRITE);
intfailed=memory==NULL;
#else
intflags=MAP_ANONYMOUS |MAP_PRIVATE;
intprot=PROT_READ |PROT_WRITE;
unsignedchar*memory=mmap(NULL,size,prot,flags,-1,0);
intfailed=memory==MAP_FAILED;
if (!failed) {
(void)_PyAnnotateMemoryMap(memory,size,"cpython:jit");
}
#endif
if (failed) {
jit_error("unable to allocate memory");
returnNULL;
}
returnmemory;
}
staticint
jit_free(unsignedchar*memory,size_tsize)
{
assert(size);
assert(size %get_page_size()==0);
#ifdefMS_WINDOWS
intfailed= !VirtualFree(memory,0,MEM_RELEASE);
#else
intfailed=munmap(memory,size);
#endif
if (failed) {
jit_error("unable to free memory");
return-1;
}
OPT_STAT_ADD(jit_freed_memory_size,size);
return0;
}
staticint
mark_executable(unsignedchar*memory,size_tsize)
{
if (size==0) {
return0;
}
assert(size %get_page_size()==0);
// Do NOT ever leave the memory writable! Also, don't forget to flush the
// i-cache (I cannot begin to tell you how horrible that is to debug):
#ifdefMS_WINDOWS
if (!FlushInstructionCache(GetCurrentProcess(),memory,size)) {
jit_error("unable to flush instruction cache");
return-1;
}
DWORDold;
intfailed= !VirtualProtect(memory,size,PAGE_EXECUTE_READ,&old);
#else
__builtin___clear_cache((char*)memory, (char*)memory+size);
intfailed=mprotect(memory,size,PROT_EXEC |PROT_READ);
#endif
if (failed) {
jit_error("unable to protect executable memory");
return-1;
}
return0;
}
// JIT compiler stuff: /////////////////////////////////////////////////////////
#defineGOT_SLOT_SIZE sizeof(uintptr_t)
#defineSYMBOL_MASK_WORDS 8
typedefuint32_tsymbol_mask[SYMBOL_MASK_WORDS];
typedefstruct {
unsignedchar*mem;
symbol_maskmask;
size_tsize;
}symbol_state;
typedefstruct {
symbol_statetrampolines;
symbol_stategot_symbols;
uintptr_tinstruction_starts[UOP_MAX_TRACE_LENGTH];
}jit_state;
// Warning! AArch64 requires you to get your hands dirty. These are your gloves:
// value[value_start : value_start + len]
staticuint32_t
get_bits(uint64_tvalue,uint8_tvalue_start,uint8_twidth)
{
assert(width <=32);
return (value >>value_start)& ((1ULL <<width)-1);
}
// *loc[loc_start : loc_start + width] = value[value_start : value_start + width]
staticvoid
set_bits(uint32_t*loc,uint8_tloc_start,uint64_tvalue,uint8_tvalue_start,
uint8_twidth)
{
assert(loc_start+width <=32);
uint32_ttemp_val;
// Use memcpy to safely read the value, avoiding potential alignment
// issues and strict aliasing violations.
memcpy(&temp_val,loc,sizeof(temp_val));
// Clear the bits we're about to patch:
temp_val &= ~(((1ULL <<width)-1) <<loc_start);
assert(get_bits(temp_val,loc_start,width)==0);
// Patch the bits:
temp_val |=get_bits(value,value_start,width) <<loc_start;
assert(get_bits(temp_val,loc_start,width)==get_bits(value,value_start,width));
// Safely write the modified value back to memory.
memcpy(loc,&temp_val,sizeof(temp_val));
}
// See https://developer.arm.com/documentation/ddi0602/2023-09/Base-Instructions
// for instruction encodings:
#defineIS_AARCH64_ADD_OR_SUB(I) (((I) & 0x11C00000) == 0x11000000)
#defineIS_AARCH64_ADRP(I) (((I) & 0x9F000000) == 0x90000000)
#defineIS_AARCH64_BRANCH(I) (((I) & 0x7C000000) == 0x14000000)
#defineIS_AARCH64_BRANCH_COND(I) (((I) & 0x7C000000) == 0x54000000)
#defineIS_AARCH64_BRANCH_ZERO(I) (((I) & 0x7E000000) == 0x34000000)
#defineIS_AARCH64_TEST_AND_BRANCH(I) (((I) & 0x7E000000) == 0x36000000)
#defineIS_AARCH64_LDR_OR_STR(I) (((I) & 0x3B000000) == 0x39000000)
#defineIS_AARCH64_MOV(I) (((I) & 0x9F800000) == 0x92800000)
// LLD is a great reference for performing relocations... just keep in
// mind that Tools/jit/build.py does filtering and preprocessing for us!
// Here's a good place to start for each platform:
// - aarch64-apple-darwin:
// - https://github.com/llvm/llvm-project/blob/main/lld/MachO/Arch/ARM64.cpp
// - https://github.com/llvm/llvm-project/blob/main/lld/MachO/Arch/ARM64Common.cpp
// - https://github.com/llvm/llvm-project/blob/main/lld/MachO/Arch/ARM64Common.h
// - aarch64-pc-windows-msvc:
// - https://github.com/llvm/llvm-project/blob/main/lld/COFF/Chunks.cpp
// - aarch64-unknown-linux-gnu:
// - https://github.com/llvm/llvm-project/blob/main/lld/ELF/Arch/AArch64.cpp
// - i686-pc-windows-msvc:
// - https://github.com/llvm/llvm-project/blob/main/lld/COFF/Chunks.cpp
// - x86_64-apple-darwin:
// - https://github.com/llvm/llvm-project/blob/main/lld/MachO/Arch/X86_64.cpp
// - x86_64-pc-windows-msvc:
// - https://github.com/llvm/llvm-project/blob/main/lld/COFF/Chunks.cpp
// - x86_64-unknown-linux-gnu:
// - https://github.com/llvm/llvm-project/blob/main/lld/ELF/Arch/X86_64.cpp
// Get the symbol slot memory location for a given symbol ordinal.
staticunsignedchar*
get_symbol_slot(intordinal,symbol_state*state,intsize)
{
constuint32_tsymbol_mask=1U << (ordinal %32);
constuint32_tstate_mask=state->mask[ordinal /32];
assert(symbol_mask&state_mask);
// Count the number of set bits in the symbol mask lower than ordinal
size_tindex=_Py_popcount32(state_mask& (symbol_mask-1));
for (inti=0;i<ordinal /32;i++) {
index+=_Py_popcount32(state->mask[i]);
}
unsignedchar*slot=state->mem+index*size;
assert((size_t)(index+1)*size <=state->size);
returnslot;
}
// Return the address of the GOT slot for the requested symbol ordinal.
staticuintptr_t
got_symbol_address(intordinal,jit_state*state)
{
return (uintptr_t)get_symbol_slot(ordinal,&state->got_symbols,GOT_SLOT_SIZE);
}
// Many of these patches are "relaxing", meaning that they can rewrite the
// code they're patching to be more efficient (like turning a 64-bit memory
// load into a 32-bit immediate load). These patches have an "x" in their name.
// Relative patches have an "r" in their name.
// 32-bit absolute address.
void
patch_32(unsignedchar*location,uint64_tvalue)
{
// Check that we're not out of range of 32 unsigned bits:
assert(value< (1ULL <<32));
uint32_tfinal_value= (uint32_t)value;
memcpy(location,&final_value,sizeof(final_value));
}
// 32-bit relative address.
void
patch_32r(unsignedchar*location,uint64_tvalue)
{
value-= (uintptr_t)location;
// Check that we're not out of range of 32 signed bits:
assert((int64_t)value >=-(1LL <<31));
assert((int64_t)value< (1LL <<31));
uint32_tfinal_value= (uint32_t)value;
memcpy(location,&final_value,sizeof(final_value));
}
// 64-bit absolute address.
void
patch_64(unsignedchar*location,uint64_tvalue)
{
memcpy(location,&value,sizeof(value));
}
// 12-bit low part of an absolute address. Pairs nicely with patch_aarch64_21r
// (below).
void
patch_aarch64_12(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
assert(IS_AARCH64_LDR_OR_STR(*loc32)||IS_AARCH64_ADD_OR_SUB(*loc32));
// There might be an implicit shift encoded in the instruction:
uint8_tshift=0;
if (IS_AARCH64_LDR_OR_STR(*loc32)) {
shift= (uint8_t)get_bits(*loc32,30,2);
// If both of these are set, the shift is supposed to be 4.
// That's pretty weird, and it's never actually been observed...
assert(get_bits(*loc32,23,1)==0||get_bits(*loc32,26,1)==0);
}
value=get_bits(value,0,12);
assert(get_bits(value,0,shift)==0);
set_bits(loc32,10,value,shift,12);
}
// Relaxable 12-bit low part of an absolute address. Pairs nicely with
// patch_aarch64_21rx (below).
void
patch_aarch64_12x(unsignedchar*location,uint64_tvalue)
{
// This can *only* be relaxed if it occurs immediately before a matching
// patch_aarch64_21rx. If that happens, the JIT build step will replace both
// calls with a single call to patch_aarch64_33rx. Otherwise, we end up
// here, and the instruction is patched normally:
patch_aarch64_12(location,value);
}
// 16-bit low part of an absolute address.
void
patch_aarch64_16a(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
assert(IS_AARCH64_MOV(*loc32));
// Check the implicit shift (this is "part 0 of 3"):
assert(get_bits(*loc32,21,2)==0);
set_bits(loc32,5,value,0,16);
}
// 16-bit middle-low part of an absolute address.
void
patch_aarch64_16b(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
assert(IS_AARCH64_MOV(*loc32));
// Check the implicit shift (this is "part 1 of 3"):
assert(get_bits(*loc32,21,2)==1);
set_bits(loc32,5,value,16,16);
}
// 16-bit middle-high part of an absolute address.
void
patch_aarch64_16c(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
assert(IS_AARCH64_MOV(*loc32));
// Check the implicit shift (this is "part 2 of 3"):
assert(get_bits(*loc32,21,2)==2);
set_bits(loc32,5,value,32,16);
}
// 16-bit high part of an absolute address.
void
patch_aarch64_16d(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
assert(IS_AARCH64_MOV(*loc32));
// Check the implicit shift (this is "part 3 of 3"):
assert(get_bits(*loc32,21,2)==3);
set_bits(loc32,5,value,48,16);
}
// 21-bit count of pages between this page and an absolute address's page... I
// know, I know, it's weird. Pairs nicely with patch_aarch64_12 (above).
void
patch_aarch64_21r(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
value= (value >>12)- ((uintptr_t)location >>12);
// Check that we're not out of range of 21 signed bits:
assert((int64_t)value >=-(1 <<20));
assert((int64_t)value< (1 <<20));
// value[0:2] goes in loc[29:31]:
set_bits(loc32,29,value,0,2);
// value[2:21] goes in loc[5:26]:
set_bits(loc32,5,value,2,19);
}
// Relaxable 21-bit count of pages between this page and an absolute address's
// page. Pairs nicely with patch_aarch64_12x (above).
void
patch_aarch64_21rx(unsignedchar*location,uint64_tvalue)
{
// This can *only* be relaxed if it occurs immediately before a matching
// patch_aarch64_12x. If that happens, the JIT build step will replace both
// calls with a single call to patch_aarch64_33rx. Otherwise, we end up
// here, and the instruction is patched normally:
patch_aarch64_21r(location,value);
}
// 21-bit relative branch.
void
patch_aarch64_19r(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
assert(IS_AARCH64_BRANCH_COND(*loc32)||IS_AARCH64_BRANCH_ZERO(*loc32));
value-= (uintptr_t)location;
// Check that we're not out of range of 21 signed bits:
assert((int64_t)value >=-(1 <<20));
assert((int64_t)value< (1 <<20));
// Since instructions are 4-byte aligned, only use 19 bits:
assert(get_bits(value,0,2)==0);
set_bits(loc32,5,value,2,19);
}
// 28-bit relative branch.
void
patch_aarch64_26r(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
assert(IS_AARCH64_BRANCH(*loc32));
value-= (uintptr_t)location;
// Check that we're not out of range of 28 signed bits:
assert((int64_t)value >=-(1 <<27));
assert((int64_t)value< (1 <<27));
// Since instructions are 4-byte aligned, only use 26 bits:
assert(get_bits(value,0,2)==0);
set_bits(loc32,0,value,2,26);
}
// A pair of patch_aarch64_21rx and patch_aarch64_12x.
void
patch_aarch64_33rx(unsignedchar*location,uint64_tvalue)
{
uint32_t*loc32= (uint32_t*)location;
// Try to relax the pair of GOT loads into an immediate value:
assert(IS_AARCH64_ADRP(*loc32));
unsignedcharreg=get_bits(loc32[0],0,5);
assert(IS_AARCH64_LDR_OR_STR(loc32[1]));
// There should be only one register involved:
assert(reg==get_bits(loc32[1],0,5));// ldr's output register.
assert(reg==get_bits(loc32[1],5,5));// ldr's input register.
uint64_trelaxed=*(uint64_t*)value;
if (relaxed< (1UL <<16)) {
// adrp reg, AAA; ldr reg, [reg + BBB] -> movz reg, XXX; nop
loc32[0]=0xD2800000 | (get_bits(relaxed,0,16) <<5) |reg;
loc32[1]=0xD503201F;
return;
}
if (relaxed< (1ULL <<32)) {
// adrp reg, AAA; ldr reg, [reg + BBB] -> movz reg, XXX; movk reg, YYY
loc32[0]=0xD2800000 | (get_bits(relaxed,0,16) <<5) |reg;
loc32[1]=0xF2A00000 | (get_bits(relaxed,16,16) <<5) |reg;
return;
}
int64_tpage_delta= (relaxed >>12)- ((uintptr_t)location >>12);
if (page_delta >=-(1L <<20)&&
page_delta< (1L <<20))
{
// adrp reg, AAA; ldr reg, [reg + BBB] -> adrp reg, AAA; add reg, reg, BBB
patch_aarch64_21rx(location,relaxed);
loc32[1]=0x91000000 |get_bits(relaxed,0,12) <<10 |reg <<5 |reg;
return;
}
relaxed=value- (uintptr_t)location;
if ((relaxed&0x3)==0&&
(int64_t)relaxed >=-(1L <<19)&&
(int64_t)relaxed< (1L <<19))
{
// adrp reg, AAA; ldr reg, [reg + BBB] -> ldr reg, XXX; nop
loc32[0]=0x58000000 | (get_bits(relaxed,2,19) <<5) |reg;
loc32[1]=0xD503201F;
return;
}
// Couldn't do it. Just patch the two instructions normally:
patch_aarch64_21rx(location,value);
patch_aarch64_12x(location+4,value);
}
// Relaxable 32-bit relative address.
void
patch_x86_64_32rx(unsignedchar*location,uint64_tvalue)
{
uint8_t*loc8= (uint8_t*)location;
// Try to relax the GOT load into an immediate value:
uint64_trelaxed;
memcpy(&relaxed, (void*)(value+4),sizeof(relaxed));
relaxed-=4;
if ((int64_t)relaxed- (int64_t)location >=-(1LL <<31)&&
(int64_t)relaxed- (int64_t)location+1< (1LL <<31))
{
if (loc8[-2]==0x8B) {
// mov reg, dword ptr [rip + AAA] -> lea reg, [rip + XXX]
loc8[-2]=0x8D;
value=relaxed;
}
elseif (loc8[-2]==0xFF&&loc8[-1]==0x15) {
// call qword ptr [rip + AAA] -> nop; call XXX
loc8[-2]=0x90;
loc8[-1]=0xE8;
value=relaxed;
}
elseif (loc8[-2]==0xFF&&loc8[-1]==0x25) {
// jmp qword ptr [rip + AAA] -> nop; jmp XXX
loc8[-2]=0x90;
loc8[-1]=0xE9;
value=relaxed;
}
}
patch_32r(location,value);
}
voidpatch_got_symbol(jit_state*state,intordinal);
voidpatch_aarch64_trampoline(unsignedchar*location,intordinal,jit_state*state);
voidpatch_x86_64_trampoline(unsignedchar*location,intordinal,jit_state*state);
#include"jit_stencils.h"
#if defined(__aarch64__)|| defined(_M_ARM64)
#defineTRAMPOLINE_SIZE 16
#defineDATA_ALIGN 8
#elif defined(__x86_64__)&& defined(__APPLE__)
// LLVM 20 on macOS x86_64 debug builds: GOT entries may exceed ±2GB PC-relative
// range.
#defineTRAMPOLINE_SIZE 16 // 14 bytes + 2 bytes padding for alignment
#defineDATA_ALIGN 8
#else
#defineTRAMPOLINE_SIZE 0
#defineDATA_ALIGN 1
#endif
// Populate the GOT entry for the given symbol ordinal with its resolved address.
void
patch_got_symbol(jit_state*state,intordinal)
{
uint64_tvalue= (uintptr_t)symbols_map[ordinal];
unsignedchar*location= (unsignedchar*)get_symbol_slot(ordinal,&state->got_symbols,GOT_SLOT_SIZE);
patch_64(location,value);
}
// Generate and patch AArch64 trampolines. The symbols to jump to are stored
// in the jit_stencils.h in the symbols_map.
void
patch_aarch64_trampoline(unsignedchar*location,intordinal,jit_state*state)
{
uint64_tvalue= (uintptr_t)symbols_map[ordinal];
int64_trange=value- (uintptr_t)location;
// If we are in range of 28 signed bits, we patch the instruction with
// the address of the symbol.
if (range >=-(1 <<27)&&range< (1 <<27)) {
patch_aarch64_26r(location, (uintptr_t)value);
return;
}
// Out of range - need a trampoline
uint32_t*p= (uint32_t*)get_symbol_slot(ordinal,&state->trampolines,TRAMPOLINE_SIZE);
/* Generate the trampoline
0: 58000048 ldr x8, 8
4: d61f0100 br x8
8: 00000000 // The next two words contain the 64-bit address to jump to.
c: 00000000
*/
p[0]=0x58000048;
p[1]=0xD61F0100;
p[2]=value&0xffffffff;
p[3]=value >>32;
patch_aarch64_26r(location, (uintptr_t)p);
}
// Generate and patch x86_64 trampolines.
void
patch_x86_64_trampoline(unsignedchar*location,intordinal,jit_state*state)
{
uint64_tvalue= (uintptr_t)symbols_map[ordinal];
int64_trange= (int64_t)value-4- (int64_t)location;
// If we are in range of 32 signed bits, we can patch directly
if (range >=-(1LL <<31)&&range< (1LL <<31)) {
patch_32r(location,value-4);
return;
}
// Out of range - need a trampoline
unsignedchar*trampoline=get_symbol_slot(ordinal,&state->trampolines,TRAMPOLINE_SIZE);
/* Generate the trampoline (14 bytes, padded to 16):
0: ff 25 00 00 00 00 jmp *(%rip)
6: XX XX XX XX XX XX XX XX (64-bit target address)
Reference: https://wiki.osdev.org/X86-64_Instruction_Encoding#FF (JMP r/m64)
*/
trampoline[0]=0xFF;
trampoline[1]=0x25;
memset(trampoline+2,0,4);
memcpy(trampoline+6,&value,8);
// Patch the call site to call the trampoline instead
patch_32r(location, (uintptr_t)trampoline-4);
}
staticvoid
combine_symbol_mask(constsymbol_masksrc,symbol_maskdest)
{
// Calculate the union of the trampolines required by each StencilGroup
for (size_ti=0;i<SYMBOL_MASK_WORDS;i++) {
dest[i] |=src[i];
}
}
// Compiles executor in-place. Don't forget to call _PyJIT_Free later!
int
_PyJIT_Compile(_PyExecutorObject*executor,const_PyUOpInstructiontrace[],size_tlength)
{
constStencilGroup*group;
// Loop once to find the total compiled size:
size_tcode_size=0;
size_tdata_size=0;
jit_statestate= {0};
for (size_ti=0;i<length;i++) {
const_PyUOpInstruction*instruction=&trace[i];
group=&stencil_groups[instruction->opcode];
state.instruction_starts[i]=code_size;
code_size+=group->code_size;
data_size+=group->data_size;
combine_symbol_mask(group->trampoline_mask,state.trampolines.mask);
combine_symbol_mask(group->got_mask,state.got_symbols.mask);
}
group=&stencil_groups[_FATAL_ERROR_r00];
code_size+=group->code_size;
data_size+=group->data_size;
combine_symbol_mask(group->trampoline_mask,state.trampolines.mask);
combine_symbol_mask(group->got_mask,state.got_symbols.mask);
// Calculate the size of the trampolines required by the whole trace
for (size_ti=0;i<Py_ARRAY_LENGTH(state.trampolines.mask);i++) {
state.trampolines.size+=_Py_popcount32(state.trampolines.mask[i])*TRAMPOLINE_SIZE;
}
for (size_ti=0;i<Py_ARRAY_LENGTH(state.got_symbols.mask);i++) {
state.got_symbols.size+=_Py_popcount32(state.got_symbols.mask[i])*GOT_SLOT_SIZE;
}
// Round up to the nearest page:
size_tpage_size=get_page_size();
assert((page_size& (page_size-1))==0);
size_tcode_padding=DATA_ALIGN- ((code_size+state.trampolines.size)& (DATA_ALIGN-1));
size_tpadding=page_size- ((code_size+state.trampolines.size+code_padding+data_size+state.got_symbols.size)& (page_size-1));
size_ttotal_size=code_size+state.trampolines.size+code_padding+data_size+state.got_symbols.size+padding;
unsignedchar*memory=jit_alloc(total_size);
if (memory==NULL) {
return-1;
}
// Collect memory stats
OPT_STAT_ADD(jit_total_memory_size,total_size);
OPT_STAT_ADD(jit_code_size,code_size);
OPT_STAT_ADD(jit_trampoline_size,state.trampolines.size);
OPT_STAT_ADD(jit_data_size,data_size);
OPT_STAT_ADD(jit_got_size,state.got_symbols.size);
OPT_STAT_ADD(jit_padding_size,padding);
OPT_HIST(total_size,trace_total_memory_hist);
// Update the offsets of each instruction:
for (size_ti=0;i<length;i++) {
state.instruction_starts[i]+= (uintptr_t)memory;
}
// Loop again to emit the code:
unsignedchar*code=memory;
state.trampolines.mem=memory+code_size;
unsignedchar*data=memory+code_size+state.trampolines.size+code_padding;
assert(trace[0].opcode==_START_EXECUTOR_r00||trace[0].opcode==_COLD_EXIT_r00||trace[0].opcode==_COLD_DYNAMIC_EXIT_r00);
state.got_symbols.mem=data+data_size;
for (size_ti=0;i<length;i++) {
const_PyUOpInstruction*instruction=&trace[i];
group=&stencil_groups[instruction->opcode];
group->emit(code,data,executor,instruction,&state);
code+=group->code_size;
data+=group->data_size;
}
// Protect against accidental buffer overrun into data:
group=&stencil_groups[_FATAL_ERROR_r00];
group->emit(code,data,executor,NULL,&state);
code+=group->code_size;
data+=group->data_size;
assert(code==memory+code_size);
assert(data==memory+code_size+state.trampolines.size+code_padding+data_size);
if (mark_executable(memory,total_size)) {
jit_free(memory,total_size);
return-1;
}
executor->jit_code=memory;
executor->jit_size=total_size;
return0;
}
/* One-off compilation of the jit entry shim
* We compile this once only as it effectively a normal
* function, but we need to use the JIT because it needs
* to understand the jit-specific calling convention.
* Don't forget to call _PyJIT_Fini later!
*/
static_PyJitEntryFuncPtr
compile_shim(void)
{
_PyExecutorObjectdummy;
constStencilGroup*group;
size_tcode_size=0;
size_tdata_size=0;
jit_statestate= {0};
group=&shim;
code_size+=group->code_size;
data_size+=group->data_size;
combine_symbol_mask(group->trampoline_mask,state.trampolines.mask);
combine_symbol_mask(group->got_mask,state.got_symbols.mask);
// Round up to the nearest page:
size_tpage_size=get_page_size();
assert((page_size& (page_size-1))==0);
size_tcode_padding=DATA_ALIGN- ((code_size+state.trampolines.size)& (DATA_ALIGN-1));
size_tpadding=page_size- ((code_size+state.trampolines.size+code_padding+data_size+state.got_symbols.size)& (page_size-1));
size_ttotal_size=code_size+state.trampolines.size+code_padding+data_size+state.got_symbols.size+padding;
unsignedchar*memory=jit_alloc(total_size);
if (memory==NULL) {
returnNULL;
}
unsignedchar*code=memory;
state.trampolines.mem=memory+code_size;
unsignedchar*data=memory+code_size+state.trampolines.size+code_padding;
state.got_symbols.mem=data+data_size;
// Compile the shim, which handles converting between the native
// calling convention and the calling convention used by jitted code
// (which may be different for efficiency reasons).
group=&shim;
group->emit(code,data,&dummy,NULL,&state);
code+=group->code_size;
data+=group->data_size;
assert(code==memory+code_size);
assert(data==memory+code_size+state.trampolines.size+code_padding+data_size);
if (mark_executable(memory,total_size)) {
jit_free(memory,total_size);
returnNULL;
}
_Py_jit_shim_size=total_size;
return (_PyJitEntryFuncPtr)memory;
}
staticPyMutexlazy_jit_mutex= {0 };
_Py_CODEUNIT*
_Py_LazyJitShim(
_PyExecutorObject*executor,_PyInterpreterFrame*frame,_PyStackRef*stack_pointer,PyThreadState*tstate
) {
PyMutex_Lock(&lazy_jit_mutex);
if (_Py_jit_entry==_Py_LazyJitShim) {
_PyJitEntryFuncPtrshim=compile_shim();
if (shim==NULL) {
PyMutex_Unlock(&lazy_jit_mutex);
Py_FatalError("Cannot allocate core JIT code");
}
_Py_jit_entry=shim;
}
PyMutex_Unlock(&lazy_jit_mutex);
return_Py_jit_entry(executor,frame,stack_pointer,tstate);
}
// Free executor's memory allocated with _PyJIT_Compile
void
_PyJIT_Free(_PyExecutorObject*executor)
{
unsignedchar*memory= (unsignedchar*)executor->jit_code;
size_tsize=executor->jit_size;
if (memory) {
executor->jit_code=NULL;
executor->jit_size=0;
if (jit_free(memory,size)) {
PyErr_FormatUnraisable("Exception ignored while "
"freeing JIT memory");
}
}
}
// Free shim memory allocated with compile_shim
void
_PyJIT_Fini(void)
{
PyMutex_Lock(&lazy_jit_mutex);
unsignedchar*memory= (unsignedchar*)_Py_jit_entry;
size_tsize=_Py_jit_shim_size;
if (size) {
_Py_jit_entry=_Py_LazyJitShim;
_Py_jit_shim_size=0;
if (jit_free(memory,size)) {
PyErr_FormatUnraisable("Exception ignored while "
"freeing JIT entry code");
}
}
PyMutex_Unlock(&lazy_jit_mutex);
}
#endif// _Py_JIT