-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathas_jit.cpp
4454 lines (3917 loc) · 116 KB
/
as_jit.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 "as_jit.h"
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <map>
#include <functional>
#include <cstdint>
#include "../source/as_scriptfunction.h"
#include "../source/as_objecttype.h"
#include "../source/as_callfunc.h"
#include "../source/as_scriptengine.h"
#include "../source/as_scriptobject.h"
#include "../source/as_texts.h"
#include "../source/as_context.h"
#include "virtual_asm.h"
using namespace assembler;
#ifdef __amd64__
#define stdcall
#define JIT_64
#endif
#ifdef _M_AMD64
#define JIT_64
#endif
#ifdef JIT_64
#define stdcall
#else
#ifdef _MSC_VER
#define stdcall __stdcall
#else
#define stdcall __attribute__((stdcall))
#endif
#endif
//#define JIT_PRINT_UNHANDLED_CALLS
#ifdef JIT_PRINT_UNHANDLED_CALLS
#include <string>
#include <set>
static std::set<asCScriptFunction*> unhandledCalls;
#endif
const unsigned codePageSize = 65535 * 4;
static const void* JUMP_DESTINATION = (void*)(size_t)0x1;
#define offset0 (asBC_SWORDARG0(pOp)*sizeof(asDWORD))
#define offset1 (asBC_SWORDARG1(pOp)*sizeof(asDWORD))
#define offset2 (asBC_SWORDARG2(pOp)*sizeof(asDWORD))
//#define JIT_DEBUG
#ifdef JIT_DEBUG
static asEBCInstr DBG_CurrentOP;
static asEBCInstr DBG_LastOP;
static void* DBG_Entry = 0;
static void* DBG_Instr = 0;
static void* DBG_LastInstr = 0;
static void* DBG_LastCall = 0;
static void* DBG_FuncEntry = 0;
static asCScriptFunction* DBG_CurrentFunction;
#endif
short offset(asDWORD* op, unsigned n) {
return *(((short*)op) + (n+1)) * sizeof(asDWORD);
}
//Returns true if the op will clear the temporary var
// Used to determine if we need to perform a full test in a Test-Jump pair
bool clearsTemporary(asEBCInstr op) {
switch(op) {
case asBC_TZ:
case asBC_TNZ:
case asBC_TS:
case asBC_TNS:
case asBC_TP:
case asBC_TNP:
case asBC_CMPd:
case asBC_CMPu:
case asBC_CMPf:
case asBC_CMPi:
case asBC_CMPIi:
case asBC_CMPIf:
case asBC_CMPIu:
case asBC_CmpPtr:
case asBC_CpyVtoR4:
case asBC_CpyVtoR8:
case asBC_CMPi64:
case asBC_CMPu64:
return true;
}
return false;
}
//Wrappers so we can deal with complex pointers/calling conventions
void stdcall allocScriptObject(asCObjectType* type, asCScriptFunction* constructor, asIScriptEngine* engine, asSVMRegisters* registers);
void* stdcall allocArray(asDWORD bytes);
void* stdcall engineAlloc(asCScriptEngine* engine, asCObjectType* type);
void stdcall engineRelease(asCScriptEngine* engine, void* memory, asCScriptFunction* release);
void stdcall engineListFree(asCScriptEngine* engine, asCObjectType* objType, void* memory);
void stdcall engineDestroyFree(asCScriptEngine* engine, void* memory, asCScriptFunction* destruct);
void stdcall engineFree(asCScriptEngine* engine, void* memory);
void stdcall engineCallMethod(asCScriptEngine* engine, void* object, asCScriptFunction* method);
void stdcall callScriptFunction(asIScriptContext* ctx, asCScriptFunction* func);
asCScriptFunction* stdcall callInterfaceMethod(asIScriptContext* ctx, asCScriptFunction* func);
asCScriptFunction* stdcall callBoundFunction(asIScriptContext* ctx, unsigned short fid);
void stdcall receiveAutoObjectHandle(asIScriptContext* ctx, asCScriptObject* obj);
asCScriptObject* stdcall castObject(asCScriptObject* obj, asCObjectType* to);
bool stdcall doSuspend(asIScriptContext* ctx);
void stdcall returnScriptFunction(asCContext* ctx);
//Wrapper functions to cast between types, or perform math on large types, where doing so is overly complicated in the ASM
#ifdef _MSC_VER
template<class F, class T>
void stdcall directConvert(F* from, T* to) {
*to = (T)*from;
}
#else
//stdcall doesn't work with templates on GCC
template<class F, class T>
void directConvert(F* from, T* to) {
*to = (T)*from;
}
#endif
void fpow_wrapper(float* base, float* exponent, bool* overflow, float* ret) {
float r = pow(*base, *exponent);
bool over = (r == float(HUGE_VAL));
*overflow = over;
if(!over)
*ret = r;
}
void dpow_wrapper(double* base, double* exponent, bool* overflow, double* ret) {
double r = pow(*base, *exponent);
bool over = (r == HUGE_VAL);
*overflow = over;
if(!over)
*ret = r;
}
void dipow_wrapper(double* base, int exponent, bool* overflow, double* ret) {
double r = pow(*base, exponent);
bool over = (r == HUGE_VAL);
*overflow = over;
if(!over)
*ret = r;
}
void i64pow_wrapper(asINT64* base, asINT64* exponent, bool* overflow, asINT64* ret) {
auto r = as_powi64(*base, *exponent, *overflow);
if(!*overflow)
*ret = r;
}
void u64pow_wrapper(asQWORD* base, asQWORD* exponent, bool* overflow, asQWORD* ret) {
auto r = as_powu64(*base, *exponent, *overflow);
if(!*overflow)
*ret = r;
}
float stdcall fmod_wrapper_f(float* div, float* mod) {
return fmod(*div, *mod);
}
double stdcall fmod_wrapper(double* div, double* mod) {
return fmod(*div, *mod);
}
void stdcall i64_add(long long* a, long long* b, long long* r) {
*r = *a + *b;
}
void stdcall i64_sub(long long* a, long long* b, long long* r) {
*r = *a - *b;
}
void stdcall i64_mul(long long* a, long long* b, long long* r) {
*r = *a * *b;
}
void stdcall i64_div(long long* a, long long* b, long long* r) {
*r = *a / *b;
}
void stdcall i64_mod(long long* a, long long* b, long long* r) {
*r = *a % *b;
}
void stdcall i64_sll(unsigned long long* a, asDWORD* b, unsigned long long* r) {
*r = *a << *b;
}
void stdcall i64_srl(unsigned long long* a, asDWORD* b, unsigned long long* r) {
*r = *a >> *b;
}
void stdcall i64_sra(long long* a, asDWORD* b, long long* r) {
*r = *a >> *b;
}
int stdcall cmp_int64(long long* a, long long* b) {
if(*a == *b )
return 0;
else if(*a < *b)
return -1;
else
return 1;
}
int stdcall cmp_uint64(unsigned long long* a, unsigned long long* b) {
if(*a == *b )
return 0;
else if(*a < *b)
return -1;
else
return 1;
}
size_t stdcall div_ull(unsigned long long* div, unsigned long long* by, unsigned long long* result) {
if(*by == 0)
return 1;
*result = *div / *by;
return 0;
}
size_t stdcall mod_ull(unsigned long long* div, unsigned long long* by, unsigned long long* result) {
if(*by == 0)
return 1;
*result = *div % *by;
return 0;
}
enum ObjectPosition {
OP_This,
OP_First,
OP_Last,
OP_None
};
enum EAXContains {
EAX_Unknown,
EAX_Stack,
EAX_Offset,
};
enum SysCallFlags {
SC_Safe = 0x01,
SC_ValidObj = 0x02,
SC_NoSuspend = 0x04,
SC_FastFPU = 0x08,
SC_NoReturn = 0x10,
SC_Simple = 0x20,
};
struct SystemCall {
Processor& cpu;
FloatingPointUnit& fpu;
asDWORD* const & pOp;
unsigned flags;
bool callIsSafe;
bool checkNullObj;
bool handleSuspend;
bool acceptReturn;
bool isSimple;
std::function<void(JumpType,bool)> returnHandler;
SystemCall(Processor& CPU, FloatingPointUnit& FPU,
std::function<void(JumpType,bool)> ConditionalReturn, asDWORD* const & bytecode, unsigned JitFlags)
: cpu(CPU), fpu(FPU), returnHandler(ConditionalReturn), pOp(bytecode), flags(0)
{
if((JitFlags & JIT_SYSCALL_NO_ERRORS) != 0)
flags |= SC_Safe;
if((JitFlags & JIT_NO_SUSPEND) != 0)
flags |= SC_NoSuspend;
if((JitFlags & JIT_SYSCALL_FPU_NORESET) != 0)
flags |= SC_FastFPU;
}
void callSystemFunction(asCScriptFunction* func, Register* objPointer = 0, unsigned callFlags = 0);
private:
void call_viaAS(asCScriptFunction* func, Register* objPointer);
void call_generic(asCScriptFunction* func, Register* objPointer);
void call_stdcall(asSSystemFunctionInterface* func, asCScriptFunction* sFunc);
void call_cdecl(asSSystemFunctionInterface* func, asCScriptFunction* sFunc);
void call_cdecl_obj(asSSystemFunctionInterface* func, asCScriptFunction* sFunc, Register* objPointer, bool last);
void call_thiscall(asSSystemFunctionInterface* func, asCScriptFunction* sFunc, Register* objPointer);
void call_simple(Register& objPointer, asCScriptFunction* func);
void call_64conv(asSSystemFunctionInterface* func, asCScriptFunction* sFunc, Register* objPointer, ObjectPosition pos);
void call_getReturn(asSSystemFunctionInterface* func, asCScriptFunction* sFunc);
//Handles error handling
void call_entry(asSSystemFunctionInterface* func, asCScriptFunction* sFunc);
void call_error();
void call_exit(asSSystemFunctionInterface* func);
};
struct SwitchRegion {
unsigned char** buffer;
unsigned count, remaining;
SwitchRegion() : buffer(0), count(0), remaining(0) {}
};
struct FutureJump {
void* jump;
FutureJump* next;
FutureJump() : jump(0), next(0) {}
FutureJump* advance() {
FutureJump* n = next;
delete this;
return n;
}
};
unsigned toSize(asEBCInstr instr) {
return asBCTypeSize[asBCInfo[instr].type];
}
asCJITCompiler::asCJITCompiler(unsigned Flags)
: activePage(0), lock(new assembler::CriticalSection()), flags(Flags), activeJumpTable(0), currentTableSize(0)
{
}
asCJITCompiler::~asCJITCompiler() {
if(activeJumpTable)
delete[] activeJumpTable;
delete lock;
}
//Returns the total number of bytes that will be pushed, until the next op that doesn't push
unsigned findTotalPushBatchSize(asDWORD* firstPush, asDWORD* endOfBytecode);
//Offsets on the stack for function local variables
namespace local {
//Used in alloc
const unsigned allocMem = 2 * sizeof(void*);
//Used in function calls
const unsigned pIsSystem = 3 * sizeof(void*);
const unsigned retPointer = 4 * sizeof(void*);
//Copy of value register in 32 bit mode when returns are being ignored, not used alongside retPointer
const unsigned regCopy = 4 * sizeof(void*);
//Used in REFCPY
const unsigned object1 = 0;
const unsigned object2 = sizeof(void*);
//Used in power calls to check for overflows
const unsigned overflowRet = 0;
};
const unsigned functionReserveSpace = 5 * sizeof(void*);
int asCJITCompiler::CompileFunction(asIScriptFunction *function, asJITFunction *output) {
asUINT length;
asDWORD *pOp = function->GetByteCode(&length);
//No bytecode for this function, don't bother making any jit for it
if(pOp == 0 || length == 0) {
output = 0;
return 1;
}
asDWORD *end = pOp + length, *start = pOp;
std::vector<SwitchRegion> switches;
SwitchRegion* activeSwitch = 0;
lock->enter();
//Get the jump table, or make a new one if necessary, and then zero it out
unsigned char** jumpTable = 0;
if(activeJumpTable) {
if(length <= currentTableSize) {
jumpTable = activeJumpTable;
}
else {
delete[] activeJumpTable;
jumpTable = new unsigned char*[length];
activeJumpTable = jumpTable;
}
}
else {
jumpTable = new unsigned char*[length];
activeJumpTable = jumpTable;
}
memset(jumpTable, 0, length * sizeof(void*));
//Do a first pass through the bytecode to mark all locations we are going to be jumping to,
//that way we can prevent running multi-op optimizations on them.
asDWORD* passOp = pOp;
while(passOp < end) {
asEBCInstr op = asEBCInstr(*(asBYTE*)passOp);
switch(op) {
case asBC_JMP:
case asBC_JLowZ:
case asBC_JZ:
case asBC_JLowNZ:
case asBC_JNZ:
case asBC_JS:
case asBC_JNS:
case asBC_JP:
case asBC_JNP: {
asDWORD* target = passOp + asBC_INTARG(passOp) + 2;
jumpTable[target - start] = (unsigned char*)JUMP_DESTINATION;
} break;
}
passOp += toSize(op);
}
//Get the active page, or create a new one if the current one is missing or too small (256 bytes for the entry and a few ops)
if(activePage == 0 || activePage->final || activePage->getFreeSize() < 256)
activePage = new CodePage(codePageSize, reinterpret_cast<void*>(&toSize));
activePage->grab();
void* curJitFunction = activePage->getFunctionPointer<void*>();
void* firstJitEntry = 0;
*output = activePage->getFunctionPointer<asJITFunction>();
pages.insert(std::pair<asJITFunction,assembler::CodePage*>(*output,activePage));
//If we are outside of opcodes we can execute, ignore all ops until a new JIT entry is found
bool waitingForEntry = true;
//Special case for a common op-pairing (*esi = eax; eax = *esi;)
unsigned currentEAX = EAX_Unknown, nextEAX = EAX_Unknown;
//Setup the processor as a 32 bit processor, as most angelscript ops work on integers
Processor cpu(*activePage, 32);
byte* byteStart = (byte*)cpu.op;
FloatingPointUnit fpu(cpu);
unsigned pBits = sizeof(void*) * 8;
#ifdef JIT_64
//32-bit registers
Register eax(cpu,EAX), ebx(cpu,EBX), ecx(cpu,ECX), edx(cpu,EDX), ebp(cpu,EBP,pBits), edi(cpu,R12);
//8-bit registers
Register al(cpu,EAX,8), bl(cpu,EBX,8), cl(cpu,ECX,8), dl(cpu,EDX,8);
//Pointer-sized registers
Register pax(cpu,EAX,pBits), pbx(cpu,EBX,pBits), pcx(cpu,ECX,pBits), pdx(cpu,EDX,pBits), esp(cpu,ESP,pBits),
pdi(cpu, R12, pBits), esi(cpu, R13, pBits);
Register rarg(cpu, R10, pBits);
//Don't use EDI and ESI, they're used for integer
//arguments to functions, despite being nonvolatile
#else
//32-bit registers
Register eax(cpu,EAX), ebx(cpu,EBX), ecx(cpu,ECX), edx(cpu,EDX), ebp(cpu,EBP,pBits), edi(cpu,EDI);
//8-bit registers
Register al(cpu,EAX,8), bl(cpu,EBX,8), cl(cpu,ECX,8), dl(cpu,EDX,8);
//Pointer-sized registers
Register pax(cpu,EAX,pBits), pbx(cpu,EBX,pBits), pcx(cpu,ECX,pBits), pdx(cpu,EDX,pBits), esp(cpu,ESP,pBits),
pdi(cpu, EDI, pBits), esi(cpu, ESI, pBits);
Register rarg(cpu, EDX, pBits);
#endif
//JIT FUNCTION ENTRY
//==================
//Push unmutable registers (these registers must retain their value after we leave our function)
cpu.push(esi);
cpu.push(edi);
cpu.push(ebx);
cpu.push(ebp);
//Reserve two pointers for various things
esp -= functionReserveSpace;
cpu.stackDepth += (cpu.pushSize() * 4) + functionReserveSpace;
#ifdef JIT_DEBUG
pbx = (void*)&DBG_FuncEntry;
as<void*>(*pbx) = pax;
#endif
//Function initialization {
#ifdef JIT_64
ebp = cpu.intArg64(0, 0);
pax = cpu.intArg64(1, 1);
#else
ebp = as<void*>(*esp+cpu.stackDepth); //Register pointer
pax = as<void*>(*esp+cpu.stackDepth+cpu.pushSize()); //Entry jump pointer
#endif
#ifdef JIT_DEBUG
pbx = (void*)&DBG_CurrentFunction;
as<void*>(*pbx) = (void*)function;
pbx = (void*)&DBG_Entry;
as<void*>(*pbx) = pax;
#endif
pdi = as<void*>(*ebp+offsetof(asSVMRegisters,stackFramePointer)); //VM Frame pointer
esi = as<void*>(*ebp+offsetof(asSVMRegisters,stackPointer)); //VM Stack pointer
pbx = as<void*>(*ebp+offsetof(asSVMRegisters,valueRegister)); //VM Temporary
//}
//Jump to the section of the function we'll actually be executing this time
cpu.jump(pax);
//Function return {
volatile byte* ret_pos = cpu.op;
as<void*>(*ebp+offsetof(asSVMRegisters,programPointer)) = rarg; //Set the bytecode pointer based on our exit
as<void*>(*ebp+offsetof(asSVMRegisters,stackFramePointer)) = pdi; //Return the frame pointer
as<void*>(*ebp+offsetof(asSVMRegisters,stackPointer)) = esi; //Return the stack pointer
as<void*>(*ebp+offsetof(asSVMRegisters,valueRegister)) = pbx; //Return the temporary
//Pop reserved pointers and saved pointers
esp += functionReserveSpace;
cpu.pop(ebp);
cpu.pop(ebx);
cpu.pop(edi);
cpu.pop(esi);
cpu.ret();
//}
auto Return = [&](bool expected) {
//Set EDX to the bytecode pointer so the vm can be returned to the correct state
rarg = (void*)pOp;
cpu.jump(Jump,ret_pos);
waitingForEntry = expected;
};
auto ReturnCondition = [&](JumpType condition) {
if(condition != Zero) {
rarg = (void*)pOp;
cpu.jump(condition,ret_pos);
}
else {
auto* j = cpu.prep_short_jump(NotZero);
rarg = (void*)pOp;
cpu.jump(Jump,ret_pos);
cpu.end_short_jump(j);
}
};
auto ReturnPosition = [&](JumpType condition, bool nextOp) {
auto retBC = pOp;
if(nextOp) {
asEBCInstr op = (asEBCInstr)*(asBYTE*)pOp;
retBC += toSize(op);
}
if(condition != Zero) {
rarg = (void*)retBC;
cpu.jump(condition,ret_pos);
}
else {
auto* j = cpu.prep_short_jump(NotZero);
rarg = (void*)retBC;
cpu.jump(Jump,ret_pos);
cpu.end_short_jump(j);
}
};
SystemCall sysCall(cpu, fpu, ReturnPosition, pOp, flags);
volatile byte* script_ret = 0;
auto ReturnFromScriptCall = [&]() {
if(script_ret) {
cpu.jump(Jump,script_ret);
}
else {
script_ret = cpu.op;
//The VM Registers are already in the correct state, so just do a simple return here
esp += functionReserveSpace;
cpu.pop(ebp);
cpu.pop(ebx);
cpu.pop(edi);
cpu.pop(esi);
cpu.ret();
}
waitingForEntry = true;
};
auto PrepareJitScriptCall = [&](asCScriptFunction* func) -> bool {
asDWORD* bc = func->scriptData->byteCode.AddressOf();
#ifdef JIT_64
Register arg0 = cpu.intArg64(0, 0, pax);
#else
Register arg0 = pax;
#endif
arg0 = as<void*>(*ebp + offsetof(asSVMRegisters,ctx));
//Prepare the vm state
cpu.call_stdcall((void*)callScriptFunction,"rp", &arg0, func);
if(flags & JIT_NO_SCRIPT_CALLS)
return false;
return *(asBYTE*)bc == asBC_JitEntry;
};
auto JitScriptCall = [&](asCScriptFunction* func) {
//Call the first jit entry in the target function
asDWORD* bc = func->scriptData->byteCode.AddressOf();
#ifdef JIT_64
Register arg0 = as<void*>(cpu.intArg64(0, 0));
Register arg1 = as<void*>(cpu.intArg64(1, 1));
Register ptr = pax;
#else
Register arg0 = ecx;
Register arg1 = ebx;
Register ptr = pax;
#endif
arg0 = as<void*>(ebp);
asPWORD entryPoint = asBC_PTRARG(bc);
if(entryPoint && func->scriptData->jitFunction) {
arg1 = (void*)entryPoint;
ptr = (void*)func->scriptData->jitFunction;
}
else {
DeferredCodePointer def;
def.jitEntry = (void**)arg1.setDeferred();
def.jitFunction = (void**)ptr.setDeferred();
deferredPointers.insert(std::pair<asIScriptFunction*,DeferredCodePointer>(func,def));
}
unsigned sb = cpu.call_cdecl_args("rr", &arg0, &arg1);
cpu.call(ptr);
cpu.call_cdecl_end(sb);
};
auto DynamicJitScriptCall = [&]() {
//Expects the asCScriptFunction* to be in eax
#ifdef JIT_64
Register arg0 = as<void*>(cpu.intArg64(0, 0));
Register arg1 = as<void*>(cpu.intArg64(1, 1));
Register ptr = pax;
#else
Register arg0 = ecx;
Register arg1 = ebx;
Register ptr = pax;
#endif
arg0 = as<void*>(ebp);
//Read the first pointer from where byteCode is, which is the
//array pointer from asCArray, skip the asBC_JitEntry byte and
//then read the first entry pointer
pax = as<void*>(*pax + offsetof(asCScriptFunction, scriptData));
arg1 = as<void*>(*pax + offsetof(asCScriptFunction::ScriptFunctionData, byteCode));
arg1 = as<void*>(*arg1 + sizeof(asDWORD));
//Read the jit function pointer from the asCScriptFunction
ptr = as<void*>(*pax + offsetof(asCScriptFunction::ScriptFunctionData, jitFunction));
unsigned sb = cpu.call_cdecl_args("rr", &arg0, &arg1);
cpu.call(ptr);
cpu.call_cdecl_end(sb);
};
auto JitScriptCallIntf = [&](asCScriptFunction* func) {
#ifdef JIT_64
Register arg0 = as<void*>(cpu.intArg64(0, 0));
#else
Register arg0 = ecx;
#endif
arg0 = as<void*>(*ebp + offsetof(asSVMRegisters,ctx));
//Prepare the vm state
cpu.call_stdcall((void*)callInterfaceMethod,"rp", &arg0, func);
//This returns the asCScriptFunction* in pax
pax &= pax;
auto okay = cpu.prep_short_jump(NotZero);
ReturnFromScriptCall();
cpu.end_short_jump(okay);
DynamicJitScriptCall();
};
auto JitScriptCallBnd = [&](int fid) {
#ifdef JIT_64
Register arg0 = as<void*>(cpu.intArg64(0, 0));
#else
Register arg0 = ecx;
#endif
arg0 = as<void*>(*ebp + offsetof(asSVMRegisters,ctx));
//Prepare the vm state
cpu.call_stdcall((void*)callBoundFunction,"rc", &arg0, (unsigned)fid);
//This returns the asCScriptFunction* in pax
pax &= pax;
auto okay = cpu.prep_short_jump(NotZero);
ReturnFromScriptCall();
cpu.end_short_jump(okay);
DynamicJitScriptCall();
};
auto ReturnFromJittedScriptCall = [&](void* expectedPC) {
//Check if we need to return to the vm
// If the program pointer is what we expect, we don't need to return
pcx = (void*)(expectedPC == 0 ? pOp+2 : expectedPC);
pcx == as<void*>(*ebp + offsetof(asSVMRegisters,programPointer));
auto skip_ret = cpu.prep_short_jump(Equal);
ReturnFromScriptCall();
cpu.end_short_jump(skip_ret);
// If execution is finished, return to the vm as well so it can clean up
as<asEContextState>(ecx) = asEXECUTION_FINISHED;
pax = as<void*>(*ebp + offsetof(asSVMRegisters,ctx));
as<asEContextState>(ecx) == as<asEContextState>(*pax + offsetof(asCContext, m_status));
auto skip_finish = cpu.prep_short_jump(NotEqual);
ReturnFromScriptCall();
cpu.end_short_jump(skip_finish);
esi = as<void*>(*ebp+offsetof(asSVMRegisters,stackPointer)); //update stack pointer
pbx = as<void*>(*ebp+offsetof(asSVMRegisters,valueRegister)); //update value register
};
auto do_jump = [&](JumpType type) {
asDWORD* bc = pOp + asBC_INTARG(pOp) + 2;
auto& jmp = jumpTable[bc - start];
if(bc > pOp) {
//Prep the jump for a future instruction
auto* jumpData = new FutureJump;
jumpData->jump = cpu.prep_long_jump(type);
jumpData->next = jmp ? (FutureJump*)jmp : 0;
jmp = (byte*)jumpData;
}
else if(jmp != 0 && jmp != JUMP_DESTINATION) {
//Jump to code that already exists
cpu.jump(type, jmp);
}
else {
//We can't handle this address, so generate a special return that does the jump ahead of time
rarg = bc;
cpu.jump(type, ret_pos);
}
};
auto do_jump_from = [&](JumpType type, asDWORD* op) {
asDWORD* bc = op + asBC_INTARG(op) + 2;
auto& jmp = jumpTable[bc - start];
if(bc > op) {
//Prep the jump for a future instruction
auto* jumpData = new FutureJump;
jumpData->jump = cpu.prep_long_jump(type);
jumpData->next = jmp ? (FutureJump*)jmp : 0;
jmp = (byte*)jumpData;
}
else if(jmp != 0 && jmp != JUMP_DESTINATION) {
//Jump to code that already exists
cpu.jump(type, jmp);
}
else {
//We can't handle this address, so generate a special return that does the jump ahead of time
rarg = bc;
cpu.jump(type, ret_pos);
}
};
auto check_space = [&](unsigned bytes) {
unsigned remaining = activePage->getFreeSize() - (unsigned)(cpu.op - byteStart);
if(remaining < bytes + cpu.jumpSpace) {
CodePage* newPage = new CodePage(codePageSize, ((char*)activePage->page + activePage->size));
cpu.migrate(*activePage, *newPage);
activePage->drop();
activePage = newPage;
activePage->grab();
pages.insert(std::pair<asJITFunction,assembler::CodePage*>(*output,activePage));
byteStart = (byte*)cpu.op;
}
};
unsigned reservedPushBytes = 0;
asEBCInstr op;
#ifdef JIT_DEBUG
volatile void* lastop = 0;
#endif
while(pOp < end) {
currentEAX = nextEAX;
nextEAX = EAX_Unknown;
if(cpu.op > activePage->getActivePage() + activePage->getFreeSize())
throw "Page exceeded...";
op = asEBCInstr(*(asBYTE*)pOp);
auto* futureJump = (FutureJump*)jumpTable[pOp - start];
//Handle jumps from earlier ops
if(futureJump) {
if(waitingForEntry && op != asBC_JitEntry) {
check_space(48);
jumpTable[pOp - start] = (unsigned char*)cpu.op;
while(futureJump && futureJump != JUMP_DESTINATION) {
cpu.end_long_jump(futureJump->jump);
futureJump = futureJump->advance();
}
Return(true);
pOp += toSize(op);
continue;
}
}
//Check for remaining space of at least 64 bytes (roughly 3 max-sized ops)
// Do so before building jumps to save a jump when crossing pages
#ifdef JIT_DEBUG
check_space(128);
#else
check_space(64);
#endif
//Deal with the most recent switch
if(activeSwitch) {
activeSwitch->buffer[int(activeSwitch->count) - int(activeSwitch->remaining)] = (unsigned char*)cpu.op;
if(--activeSwitch->remaining == 0)
activeSwitch = 0;
}
jumpTable[pOp - start] = (unsigned char*)cpu.op;
#ifdef JIT_DEBUG
void* beg = (void*)cpu.op;
pdx = (void*)&DBG_CurrentOP;
as<asEBCInstr>(*pdx) = op;
pdx = (void*)&DBG_LastInstr;
*pdx = (void*)lastop;
pdx = (void*)&DBG_Instr;
*pdx = (void*)beg;
lastop = beg;
#endif
//Handle jumps to code we hadn't made yet
while(futureJump && futureJump != JUMP_DESTINATION) {
cpu.end_long_jump(futureJump->jump);
futureJump = futureJump->advance();
}
//Multi-op optimization - special cases where specific sets of ops serve a common purpose
auto pNextOp = pOp + toSize(op);
if(pNextOp < end && jumpTable[pNextOp - start] == nullptr) {
auto nextOp = asEBCInstr(*(asBYTE*)pNextOp);
auto pThirdOp = pNextOp + toSize(nextOp);
auto thirdOp = asBC_MAXBYTECODE;
if(pThirdOp < end && jumpTable[pThirdOp - start] == nullptr) {
thirdOp = asEBCInstr(*(asBYTE*)pThirdOp);
switch(op) {
case asBC_SetV8:
if(thirdOp == asBC_CpyVtoV8 &&
(nextOp == asBC_ADDd || nextOp == asBC_DIVd ||
nextOp == asBC_SUBd || nextOp == asBC_MULd)) {
if(asBC_SWORDARG0(pOp) != asBC_SWORDARG2(pNextOp) || asBC_SWORDARG0(pOp) != asBC_SWORDARG0(pNextOp))
break;
//Optimize <Variable Double> <op>= <Constant Double>
fpu.load_double(*edi-offset(pNextOp,1));
MemAddress doubleConstant(cpu, &asBC_QWORDARG(pOp));
switch(nextOp) {
case asBC_ADDd:
fpu.add_double(doubleConstant); break;
case asBC_SUBd:
fpu.sub_double(doubleConstant); break;
case asBC_MULd:
fpu.mult_double(doubleConstant); break;
case asBC_DIVd:
fpu.div_double(doubleConstant); break;
}
if(asBC_SWORDARG0(pOp) == asBC_SWORDARG1(pThirdOp)) {
fpu.store_double(*edi-offset(pOp,0),false);
fpu.store_double(*edi-offset(pThirdOp,0));
pOp = pThirdOp + toSize(thirdOp);
}
else {
fpu.store_double(*edi-offset(pOp,0));
pOp = pThirdOp;
}
continue;
}
break;
case asBC_SetV4:
if(nextOp == asBC_SetV4 && thirdOp == asBC_SetV4 && asBC_DWORDARG(pOp) == asBC_DWORDARG(pNextOp) && asBC_DWORDARG(pNextOp) == asBC_DWORDARG(pThirdOp)) {
//Optimize intializing 3 variables to the same value (often 0)
if(asBC_DWORDARG(pOp) == 0)
eax ^= eax;
else
eax = asBC_DWORDARG(pOp);
*edi-offset(pOp,0) = eax;
*edi-offset(pNextOp,0) = eax;
*edi-offset(pThirdOp,0) = eax;
pOp = pThirdOp + toSize(thirdOp);
continue;
}
break;
case asBC_PshVPtr:
//Optimize PshVPtr, ADDSi, RDSPtr to avoid many interim ops
if(nextOp == asBC_ADDSi && thirdOp == asBC_RDSPtr) {
pax = as<void*>(*edi-offset0);
if(reservedPushBytes != 0)
reservedPushBytes = 0;
else
esi -= sizeof(void*);
pax &= pax;
auto notNull = cpu.prep_short_jump(NotZero);
as<void*>(*esi) = pax;
Return(false);
cpu.end_short_jump(notNull);
pax = as<void*>(*pax+asBC_SWORDARG0(pNextOp));
as<void*>(*esi) = pax;
nextEAX = EAX_Stack;
pOp = pThirdOp + toSize(thirdOp);
continue;
}
break;
}
}
switch(op) {
case asBC_SetV4:
if(nextOp == asBC_SetV4 && asBC_DWORDARG(pOp) == asBC_DWORDARG(pNextOp)) {
//Optimize intializing 2 variables to the same value (often 0)
if(asBC_DWORDARG(pOp) == 0)
eax ^= eax;
else
eax = asBC_DWORDARG(pOp);
*edi-offset(pOp,0) = eax;
*edi-offset(pNextOp,0) = eax;
pOp = pThirdOp;
continue;
}
break;
case asBC_RDR4:
if(nextOp == asBC_PshV4 && asBC_SWORDARG0(pOp) == asBC_SWORDARG0(pNextOp)) {
//Optimize:
//Store temporary int
//Push stored temporary
eax = *ebx;
*edi-offset0 = eax;
reservedPushBytes = findTotalPushBatchSize(pNextOp, end);
esi -= reservedPushBytes;
reservedPushBytes -= sizeof(asDWORD);
*esi + reservedPushBytes = eax;
if(reservedPushBytes == 0)
nextEAX = EAX_Stack;
pOp = pThirdOp;
continue;
}
break;
//TODO: Update this to use inline memcpy improvement
/*case asBC_PSF:
case asBC_PshVPtr:
if(reservedPushBytes == 0 && nextOp == asBC_COPY) {
//Optimize:
//Push Pointer
//Copy Pointer
//To:
//Copy Pointer