forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.cpp
More file actions
10802 lines (9705 loc) · 408 KB
/
compiler.cpp
File metadata and controls
10802 lines (9705 loc) · 408 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "gcinfoencoder.h"
#include "interpreter.h"
#include "stackmap.h"
#include <inttypes.h>
#include <new> // for std::bad_alloc
static const StackType g_stackTypeFromInterpType[] =
{
StackTypeI4, // I1
StackTypeI4, // U1
StackTypeI4, // I2
StackTypeI4, // U2
StackTypeI4, // I4
StackTypeI8, // I8
StackTypeR4, // R4
StackTypeR8, // R8
StackTypeO, // O
StackTypeVT, // VT
StackTypeByRef, // ByRef
};
static const InterpType g_interpTypeFromStackType[] =
{
InterpTypeI4, // I4,
InterpTypeI8, // I8,
InterpTypeR4, // R4,
InterpTypeR8, // R8,
InterpTypeO, // O,
InterpTypeVT, // VT,
InterpTypeByRef, // MP,
InterpTypeI, // F
InterpTypeByRef, // LocalVariableAddress, The result of ldloca or ldarga is a byref per spec, but is also permitted to be treated as a nint in some cases. Keep track of that here.
};
// Used by assertAbort
thread_local ICorJitInfo* t_InterpJitInfoTls = nullptr;
static const char *g_stackTypeString[] = { "I4", "I8", "R4", "R8", "O ", "VT", "MP", "F ", "TP" };
const char* CorInfoHelperToName(CorInfoHelpFunc helper);
/*****************************************************************************/
#ifdef DEBUG
thread_local bool t_interpDump;
#endif // DEBUG
bool IsInterpDumpActive()
{
#ifdef DEBUG
return t_interpDump;
#else // !DEBUG
return false;
#endif // DEBUG
}
void AssertOpCodeNotImplemented(const uint8_t *ip, size_t offset)
{
#ifdef DEBUG
fprintf(stderr, "IL_%04x %-10s - opcode not supported yet\n",
(int32_t)(offset),
CEEOpName(CEEDecodeOpcode(&ip)));
#endif // DEBUG
BADCODE("opcode not implemented");
}
// GCInfoEncoder needs an IAllocator implementation. This is a simple one that forwards to the Compiler.
class InterpIAllocator : public IAllocator
{
InterpCompiler *m_pCompiler;
public:
InterpIAllocator(InterpCompiler *compiler)
: m_pCompiler(compiler)
{
}
// Allocates a block of memory at least `sz` in size.
virtual void* Alloc(size_t sz) override
{
return m_pCompiler->AllocMethodData(sz);
}
// Allocates a block of memory at least `elems * elemSize` in size.
virtual void* ArrayAlloc(size_t elems, size_t elemSize) override
{
// Ensure that elems * elemSize does not overflow.
if (elems > (SIZE_MAX / elemSize))
{
NOMEM();
}
return m_pCompiler->AllocMethodData(elems * elemSize);
}
// Frees the block of memory pointed to by p.
virtual void Free(void* p) override
{
// Interpreter-FIXME: m_pCompiler->FreeMethodData
free(p);
}
};
void* MemPoolAllocator::Alloc(size_t sz) const { return m_compiler->AllocMemPool(sz); }
void MemPoolAllocator::Free(void* ptr) const { /* no-op */ }
void* MallocAllocator::Alloc(size_t sz) const
{
void* mem = malloc(sz);
if (mem == nullptr)
NOMEM();
return mem;
}
void MallocAllocator::Free(void* ptr) const
{
free(ptr);
}
size_t GetGenericLookupOffset(const CORINFO_RUNTIME_LOOKUP *pLookup, uint32_t index)
{
if (pLookup->indirections == CORINFO_USEHELPER)
return 0;
else if (index < pLookup->indirections)
return pLookup->offsets[index];
else
return 0;
}
void InterpCompiler::CopyToInterpGenericLookup(InterpGenericLookup* dst, const CORINFO_RUNTIME_LOOKUP *src)
{
if (src->testForNull || src->indirections == CORINFO_USEHELPER)
{
dst->signature = src->signature;
}
else
{
dst->signature = nullptr;
}
if (src->indirections == CORINFO_USEHELPER)
dst->indirections = InterpGenericLookup_UseHelper;
else
dst->indirections = src->indirections;
assert(CORINFO_MAXINDIRECTIONS == sizeof(dst->offsets)/sizeof(dst->offsets[0]));
if (GetGenericLookupOffset(src, 0) > UINT16_MAX || GetGenericLookupOffset(src, 1) > UINT16_MAX ||
GetGenericLookupOffset(src, 2) > UINT16_MAX || GetGenericLookupOffset(src, 3) > UINT16_MAX)
{
#ifdef DEBUG
if (IsInterpDumpActive())
{
printf("CopyToInterpGenericLookup: Offsets too large for generic lookup, unable to compile\n");
printf(" Indirections: %d\n", (int)src->indirections);
printf(" Offsets: %zu %zu %zu %zu\n",
src->offsets[0], src->offsets[1], src->offsets[2], src->offsets[3]);
}
#endif // DEBUG
NO_WAY("CopyToInterpGenericLookup: Offsets too large for generic lookup");
}
if (dst->indirections == InterpGenericLookup_UseHelper)
{
if (dst->signature == NULL)
{
NO_WAY("CopyToInterpGenericLookup: Helper lookup must have a signature");
}
dst->sizeOffset = 0;
dst->offsets[0] = 0;
dst->offsets[1] = 0;
dst->offsets[2] = 0;
dst->offsets[3] = 0;
}
else
{
dst->sizeOffset = src->sizeOffset;
dst->offsets[0] = (uint16_t)GetGenericLookupOffset(src, 0);
dst->offsets[1] = (uint16_t)GetGenericLookupOffset(src, 1);
dst->offsets[2] = (uint16_t)GetGenericLookupOffset(src, 2);
dst->offsets[3] = (uint16_t)GetGenericLookupOffset(src, 3);
}
assert(!src->indirectFirstOffset);
assert(!src->indirectSecondOffset);
}
// Interpreter-FIXME Use specific allocators for their intended purpose
// Allocator for data that is kept alive throughout application execution,
// being freed only if the associated method gets freed.
void* InterpCompiler::AllocMethodData(size_t numBytes)
{
return malloc(numBytes);
}
// Fast allocator for small chunks of memory that can be freed together when the
// method compilation is finished.
void* InterpCompiler::AllocMemPool(size_t numBytes)
{
return malloc(numBytes);
}
void* InterpCompiler::AllocMemPool0(size_t numBytes)
{
void *ptr = AllocMemPool(numBytes);
memset(ptr, 0, numBytes);
return ptr;
}
// Allocator for potentially larger chunks of data, that we might want to free
// eagerly, before method is finished compiling, to prevent excessive memory usage.
void* InterpCompiler::AllocTemporary(size_t numBytes)
{
return malloc(numBytes);
}
void* InterpCompiler::AllocTemporary0(size_t numBytes)
{
void *ptr = AllocTemporary(numBytes);
memset(ptr, 0, numBytes);
return ptr;
}
void* InterpCompiler::ReallocTemporary(void* ptr, size_t numBytes)
{
return realloc(ptr, numBytes);
}
void InterpCompiler::FreeTemporary(void* ptr)
{
free(ptr);
}
static int GetDataLen(int opcode)
{
int length = g_interpOpLen[opcode];
int numSVars = g_interpOpSVars[opcode];
int numDVars = g_interpOpDVars[opcode];
return length - 1 - numSVars - numDVars;
}
InterpInst* InterpCompiler::AddIns(int opcode)
{
return AddInsExplicit(opcode, GetDataLen(opcode));
}
InterpInst* InterpCompiler::AddInsExplicit(int opcode, int dataLen)
{
InterpInst *ins = NewIns(opcode, dataLen);
ins->pPrev = m_pCBB->pLastIns;
if (m_pCBB->pLastIns)
m_pCBB->pLastIns->pNext = ins;
else
m_pCBB->pFirstIns = ins;
m_pCBB->pLastIns = ins;
return ins;
}
InterpInst* InterpCompiler::NewIns(int opcode, int dataLen)
{
int insSize = sizeof(InterpInst) + sizeof(uint32_t) * dataLen;
InterpInst *ins = (InterpInst*)AllocMemPool(insSize);
memset(ins, 0, insSize);
ins->opcode = opcode;
ins->ilOffset = m_currentILOffset;
m_pLastNewIns = ins;
return ins;
}
InterpInst* InterpCompiler::InsertInsBB(InterpBasicBlock *pBB, InterpInst *pPrevIns, int opcode)
{
InterpInst *ins = NewIns(opcode, GetDataLen(opcode));
ins->pPrev = pPrevIns;
if (pPrevIns)
{
ins->pNext = pPrevIns->pNext;
pPrevIns->pNext = ins;
}
else
{
ins->pNext = pBB->pFirstIns;
pBB->pFirstIns = ins;
}
if (ins->pNext == NULL)
{
pBB->pLastIns = ins;
}
else
{
ins->pNext->pPrev = ins;
}
return ins;
}
// Inserts a new instruction after prevIns. prevIns must be in cbb
InterpInst* InterpCompiler::InsertIns(InterpInst *pPrevIns, int opcode)
{
return InsertInsBB(m_pCBB, pPrevIns, opcode);
}
InterpInst* InterpCompiler::FirstRealIns(InterpBasicBlock *pBB)
{
InterpInst *ins = pBB->pFirstIns;
if (!ins || !InsIsNop(ins))
return ins;
while (ins && InsIsNop(ins))
ins = ins->pNext;
return ins;
}
InterpInst* InterpCompiler::NextRealIns(InterpInst *ins)
{
ins = ins->pNext;
while (ins && InsIsNop(ins))
ins = ins->pNext;
return ins;
}
InterpInst* InterpCompiler::PrevRealIns(InterpInst *ins)
{
ins = ins->pPrev;
while (ins && InsIsNop(ins))
ins = ins->pPrev;
return ins;
}
void InterpCompiler::ClearIns(InterpInst *ins)
{
ins->opcode = INTOP_NOP;
}
bool InterpCompiler::InsIsNop(InterpInst *ins)
{
return ins->opcode == INTOP_NOP;
}
int32_t InterpCompiler::GetInsLength(InterpInst *ins)
{
int len = g_interpOpLen[ins->opcode];
if (len == 0)
{
assert(ins->opcode == INTOP_SWITCH);
len = 3 + ins->data[0];
}
return len;
}
void InterpCompiler::ForEachInsSVar(InterpInst *ins, void *pData, void (InterpCompiler::*callback)(int*, void*))
{
int numSVars = g_interpOpSVars[ins->opcode];
if (numSVars)
{
for (int i = 0; i < numSVars; i++)
{
if (ins->sVars [i] == CALL_ARGS_SVAR)
{
if (ins->info.pCallInfo && ins->info.pCallInfo->pCallArgs) {
int *callArgs = ins->info.pCallInfo->pCallArgs;
while (*callArgs != CALL_ARGS_TERMINATOR)
{
(this->*callback) (callArgs, pData);
callArgs++;
}
}
}
else
{
(this->*callback) (&ins->sVars[i], pData);
}
}
}
}
void InterpCompiler::ForEachInsVar(InterpInst *ins, void *pData, void (InterpCompiler::*callback)(int*, void*))
{
ForEachInsSVar(ins, pData, callback);
if (g_interpOpDVars [ins->opcode])
(this->*callback) (&ins->dVar, pData);
}
InterpBasicBlock* InterpCompiler::AllocBB(int32_t ilOffset)
{
InterpBasicBlock *bb = (InterpBasicBlock*)AllocMemPool(sizeof(InterpBasicBlock));
new (bb) InterpBasicBlock (m_BBCount, ilOffset);
m_BBCount++;
return bb;
}
InterpBasicBlock* InterpCompiler::GetBB(int32_t ilOffset)
{
InterpBasicBlock *bb = m_ppOffsetToBB [ilOffset];
if (!bb)
{
bb = AllocBB(ilOffset);
m_ppOffsetToBB[ilOffset] = bb;
}
return bb;
}
// Same implementation as JIT
static inline uint32_t LeadingZeroCount(uint32_t value)
{
if (value == 0)
{
return 32;
}
#if defined(_MSC_VER)
unsigned long result;
::_BitScanReverse(&result, value);
return 31 ^ static_cast<uint32_t>(result);
#else
int32_t result = __builtin_clz(value);
return static_cast<uint32_t>(result);
#endif
}
int GetBBLinksCapacity(int links)
{
if (links <= 2)
return links;
// Return the next power of 2 bigger or equal to links
uint32_t leadingZeroes = LeadingZeroCount(links - 1);
return 1 << (32 - leadingZeroes);
}
void InterpCompiler::LinkBBs(InterpBasicBlock *from, InterpBasicBlock *to)
{
int i;
bool found = false;
for (i = 0; i < from->outCount; i++)
{
if (to == from->ppOutBBs[i])
{
found = true;
break;
}
}
if (!found)
{
int prevCapacity = GetBBLinksCapacity(from->outCount);
int newCapacity = GetBBLinksCapacity(from->outCount + 1);
if (newCapacity > prevCapacity)
{
InterpBasicBlock **newa = (InterpBasicBlock**)AllocMemPool(newCapacity * sizeof(InterpBasicBlock*));
if (from->outCount != 0)
{
memcpy(newa, from->ppOutBBs, from->outCount * sizeof(InterpBasicBlock*));
}
from->ppOutBBs = newa;
}
from->ppOutBBs [from->outCount] = to;
from->outCount++;
}
found = false;
for (i = 0; i < to->inCount; i++)
{
if (from == to->ppInBBs [i])
{
found = true;
break;
}
}
if (!found) {
int prevCapacity = GetBBLinksCapacity(to->inCount);
int newCapacity = GetBBLinksCapacity(to->inCount + 1);
if (newCapacity > prevCapacity) {
InterpBasicBlock **newa = (InterpBasicBlock**)AllocMemPool(newCapacity * sizeof(InterpBasicBlock*));
if (to->inCount != 0) {
memcpy(newa, to->ppInBBs, to->inCount * sizeof(InterpBasicBlock*));
}
to->ppInBBs = newa;
}
to->ppInBBs [to->inCount] = from;
to->inCount++;
}
}
// array must contain ref
static void RemoveBBRef(InterpBasicBlock **array, InterpBasicBlock *ref, int len)
{
int i = 0;
while (array[i] != ref)
{
i++;
}
i++;
while (i < len)
{
array[i - 1] = array[i];
i++;
}
}
void InterpCompiler::UnlinkBBs(InterpBasicBlock *from, InterpBasicBlock *to)
{
RemoveBBRef(from->ppOutBBs, to, from->outCount);
from->outCount--;
RemoveBBRef(to->ppInBBs, from, to->inCount);
to->inCount--;
}
// These are moves between vars, operating only on the interpreter stack
int32_t InterpCompiler::InterpGetMovForType(InterpType interpType, bool signExtend)
{
switch (interpType)
{
case InterpTypeI1:
case InterpTypeU1:
case InterpTypeI2:
case InterpTypeU2:
if (signExtend)
return INTOP_MOV_I4_I1 + interpType;
else
return INTOP_MOV_4;
case InterpTypeI4:
case InterpTypeR4:
return INTOP_MOV_4;
case InterpTypeI8:
case InterpTypeR8:
return INTOP_MOV_8;
case InterpTypeO:
case InterpTypeByRef:
return INTOP_MOV_P;
case InterpTypeVT:
return INTOP_MOV_VT;
default:
assert(0);
}
return -1;
}
// This method needs to be called when the current basic blocks ends and execution can
// continue into pTargetBB. When the stack state of a basic block is initialized, the vars
// associated with the stack state are set. When another bblock will continue execution
// into this bblock, it will first have to emit moves from the vars in its stack state
// to the vars of the target bblock stack state.
void InterpCompiler::EmitBBEndVarMoves(InterpBasicBlock *pTargetBB)
{
if (pTargetBB->stackHeight <= 0)
return;
for (int i = 0; i < pTargetBB->stackHeight; i++)
{
int sVar = m_pStackBase[i].var;
int dVar = pTargetBB->pStackState[i].var;
if (sVar != dVar)
{
InterpType interpType = g_interpTypeFromStackType[m_pStackBase[i].GetStackType()];
InterpType interpDestType = g_interpTypeFromStackType[pTargetBB->pStackState[i].GetStackType()];
int32_t movOp;
if (interpType != interpDestType)
{
if (interpType == InterpTypeR4 && interpDestType == InterpTypeR8)
{
movOp = INTOP_CONV_R8_R4;
}
else if (interpType == InterpTypeR8 && interpDestType == InterpTypeR4)
{
movOp = INTOP_CONV_R4_R8;
}
else if (interpType == InterpTypeI && interpDestType == InterpTypeByRef)
{
movOp = InterpGetMovForType(interpDestType, false);
}
#ifdef TARGET_64BIT
// nint and int32 can be used interchangeably. Add implicit conversions.
else if (interpType == InterpTypeI4 && ((interpDestType == InterpTypeI8) || (interpDestType == InterpTypeByRef)))
{
movOp = INTOP_CONV_I8_I4;
}
else if (interpType == InterpTypeI8 && interpDestType == InterpTypeI4)
{
movOp = InterpGetMovForType(interpDestType, false);
}
#endif // TARGET_64BIT
else
{
BADCODE("Incompatible types on stack between basic blocks");
}
}
else
{
movOp = InterpGetMovForType(interpType, false);
}
AddIns(movOp);
m_pLastNewIns->SetSVar(sVar);
m_pLastNewIns->SetDVar(dVar);
if (interpType == InterpTypeVT)
{
assert(m_pVars[sVar].size == m_pVars[dVar].size);
m_pLastNewIns->data[0] = m_pVars[sVar].size;
}
}
}
}
static void MergeStackTypeInfo(StackInfo *pState1, StackInfo *pState2, int len)
{
// Discard type information if we have type conflicts for stack contents
for (int i = 0; i < len; i++)
{
if (pState1[i].clsHnd != pState2[i].clsHnd)
{
pState1[i].clsHnd = NULL;
pState2[i].clsHnd = NULL;
}
}
}
// Initializes stack state at entry to bb, based on the current stack state
void InterpCompiler::InitBBStackState(InterpBasicBlock *pBB)
{
if (pBB->stackHeight >= 0)
{
// Already initialized, update stack information
MergeStackTypeInfo(m_pStackBase, pBB->pStackState, pBB->stackHeight);
}
else
{
pBB->stackHeight = (int32_t)(m_pStackPointer - m_pStackBase);
if (pBB->stackHeight > 0)
{
int size = pBB->stackHeight * sizeof (StackInfo);
pBB->pStackState = (StackInfo*)AllocMemPool(size);
memcpy (pBB->pStackState, m_pStackBase, size);
}
}
}
int32_t InterpCompiler::CreateVarExplicit(InterpType interpType, CORINFO_CLASS_HANDLE clsHnd, int size)
{
if (interpType == InterpTypeVT)
{
assert(clsHnd != NULL);
}
if (m_varsSize == m_varsCapacity) {
m_varsCapacity *= 2;
if (m_varsCapacity == 0)
m_varsCapacity = 16;
m_pVars = (InterpVar*) ReallocTemporary(m_pVars, m_varsCapacity * sizeof(InterpVar));
}
InterpVar *var = &m_pVars[m_varsSize];
new (var) InterpVar(interpType, clsHnd, size);
m_varsSize++;
return m_varsSize - 1;
}
void InterpCompiler::EnsureStack(int additional)
{
int32_t currentSize = (int32_t)(m_pStackPointer - m_pStackBase);
if ((additional + currentSize) > m_stackCapacity) {
m_stackCapacity *= 2;
m_pStackBase = (StackInfo*)ReallocTemporary (m_pStackBase, m_stackCapacity * sizeof(StackInfo));
m_pStackPointer = m_pStackBase + currentSize;
}
}
#define CHECK_STACK(n) CheckStackHelper(n)
#define INVALID_CODE_RET_VOID BADCODE("Invalid code detected")
void InterpCompiler::CheckStackHelper(int n)
{
int32_t currentSize = (int32_t)(m_pStackPointer - m_pStackBase);
if (currentSize < n)
{
BADCODE("Stack underflow");
}
}
void InterpCompiler::CheckStackExact(int n)
{
int32_t currentSize = (int32_t)(m_pStackPointer - m_pStackBase);
if (currentSize < n)
{
BADCODE("Stack underflow");
}
else if (currentSize > n)
{
BADCODE("Stack contains extra data");
}
}
void InterpCompiler::PushTypeExplicit(StackType stackType, CORINFO_CLASS_HANDLE clsHnd, int size)
{
EnsureStack(1);
int32_t var = CreateVarExplicit(g_interpTypeFromStackType[stackType], clsHnd, size);
new (m_pStackPointer) StackInfo(stackType, clsHnd, var);
m_pStackPointer++;
}
void InterpCompiler::PushStackType(StackType stackType, CORINFO_CLASS_HANDLE clsHnd)
{
if (stackType == StackTypeVT)
{
assert(clsHnd != NULL);
int size = m_compHnd->getClassSize(clsHnd);
PushTypeExplicit(stackType, clsHnd, size);
}
else
{
// We don't really care about the exact size for non-valuetypes
PushTypeExplicit(stackType, clsHnd, INTERP_STACK_SLOT_SIZE);
}
}
void InterpCompiler::PushInterpType(InterpType interpType, CORINFO_CLASS_HANDLE clsHnd)
{
PushStackType(g_stackTypeFromInterpType[interpType], clsHnd);
}
void InterpCompiler::PushTypeVT(CORINFO_CLASS_HANDLE clsHnd, int size)
{
PushTypeExplicit(StackTypeVT, clsHnd, size);
}
int32_t InterpCompiler::ComputeCodeSize()
{
int32_t codeSize = 0;
for (InterpBasicBlock *bb = m_pEntryBB; bb != NULL; bb = bb->pNextBB)
{
for (InterpInst *ins = bb->pFirstIns; ins != NULL; ins = ins->pNext)
{
codeSize += GetInsLength(ins);
}
}
return codeSize;
}
int32_t InterpCompiler::GetLiveStartOffset(int var)
{
if (m_pVars[var].global)
{
return 0;
}
else
{
assert(m_pVars[var].liveStart != NULL);
return m_pVars[var].liveStart->nativeOffset;
}
}
int32_t InterpCompiler::GetLiveEndOffset(int var)
{
if (m_pVars[var].global)
{
return m_methodCodeSize;
}
else
{
assert(m_pVars[var].liveEnd != NULL);
return m_pVars[var].liveEnd->nativeOffset + GetInsLength(m_pVars[var].liveEnd);
}
}
uint32_t InterpCompiler::ConvertOffset(int32_t offset)
{
// FIXME Once the VM moved the InterpMethod* to code header, we don't need to add a pointer size to the offset
return offset * sizeof(int32_t) + sizeof(void*);
}
int32_t* InterpCompiler::EmitCodeIns(int32_t *ip, InterpInst *ins, TArray<Reloc*, MemPoolAllocator> *relocs)
{
ins->nativeOffset = (int32_t)(ip - m_pMethodCode);
int32_t opcode = ins->opcode;
int32_t *startIp = ip;
*ip++ = opcode;
// Set to true if the instruction was completely reverted.
bool isReverted = false;
if (opcode == INTOP_HANDLE_CONTINUATION_SUSPEND)
{
// Capture meaningful start IP for async suspend diagnostics
((InterpAsyncSuspendData*)GetDataItemAtIndex(ins->data[0]))->resumeInfo.DiagnosticIP = (size_t)startIp;
}
if (opcode == INTOP_SWITCH)
{
int32_t numLabels = ins->data [0];
*ip++ = m_pVars[ins->sVars[0]].offset;
*ip++ = numLabels;
// Add relocation for each label
for (int32_t i = 0; i < numLabels; i++)
{
Reloc *reloc = (Reloc*)AllocMemPool(sizeof(Reloc));
new (reloc) Reloc(RelocSwitch, (int32_t)(ip - m_pMethodCode), ins->info.ppTargetBBTable[i], 0);
relocs->Add(reloc);
*ip++ = (int32_t)0xdeadbeef;
}
}
else if (InterpOpIsUncondBranch(opcode) || InterpOpIsCondBranch(opcode) || (opcode == INTOP_LEAVE_CATCH) || (opcode == INTOP_CALL_FINALLY))
{
int32_t brBaseOffset = (int32_t)(startIp - m_pMethodCode);
for (int i = 0; i < g_interpOpSVars[opcode]; i++)
*ip++ = m_pVars[ins->sVars[i]].offset;
if (ins->info.pTargetBB->nativeOffset >= 0)
{
*ip++ = ins->info.pTargetBB->nativeOffset - brBaseOffset;
}
else if (opcode == INTOP_BR && ins->info.pTargetBB == m_pCBB->pNextBB && ins->info.pTargetBB->overlappingEHClauseCount == m_pCBB->overlappingEHClauseCount)
{
// Ignore branch to the next basic block if it is on the same clause depth. Revert the added INTOP_BR.
isReverted = true;
ip--;
}
else
{
// We don't know yet the IR offset of the target, add a reloc instead
Reloc *reloc = (Reloc*)AllocMemPool(sizeof(Reloc));
new (reloc) Reloc(RelocLongBranch, brBaseOffset, ins->info.pTargetBB, g_interpOpSVars[opcode]);
relocs->Add(reloc);
*ip++ = (int32_t)0xdeadbeef;
}
}
else if (opcode == INTOP_MOV_SRC_OFF)
{
// This opcode reuses the MOV opcodes, which are normally used to copy the
// contents of one var to the other, in order to copy a containing field
// of the source var (which is a vt) to another var.
int32_t fOffset = ins->data[0];
InterpType fType = (InterpType)ins->data[1];
int32_t fSize = ins->data[2];
// Revert opcode emit
ip--;
int destOffset = m_pVars[ins->dVar].offset;
int srcOffset = m_pVars[ins->sVars[0]].offset;
srcOffset += fOffset;
if (fSize)
opcode = INTOP_MOV_VT;
else
opcode = InterpGetMovForType(fType, true);
*ip++ = opcode;
*ip++ = destOffset;
*ip++ = srcOffset;
if (opcode == INTOP_MOV_VT)
*ip++ = fSize;
// NOTE: It is important to patch the opcode of the insn so that live end offsets are computed correctly.
// Otherwise the live end offset will be computed using the size of mov_src_off instead of the actual move,
// which will break gc live range computations.
ins->opcode = opcode;
ins->data[0] = fSize;
}
else if (opcode == INTOP_LDLOCA)
{
// This opcode references a var, int sVars[0], but it is not registered as a source for it
// aka g_interpOpSVars[INTOP_LDLOCA] is 0.
*ip++ = m_pVars[ins->dVar].offset;
*ip++ = m_pVars[ins->sVars[0]].offset;
}
else
{
// Default code emit for an instruction. The opcode was already emitted above.
// We emit the offset for the instruction destination, then for every single source
// variable we emit another offset. Finally, we will emit any additional data needed
// by the instruction.
if (g_interpOpDVars[opcode])
*ip++ = m_pVars[ins->dVar].offset;
if (g_interpOpSVars[opcode])
{
for (int i = 0; i < g_interpOpSVars[opcode]; i++)
{
if (ins->sVars[i] == CALL_ARGS_SVAR)
{
*ip++ = m_paramAreaOffset + ins->info.pCallInfo->callOffset;
}
else
{
*ip++ = m_pVars[ins->sVars[i]].offset;
}
}
}
int left = GetInsLength(ins) - (int32_t)(ip - startIp);
// Emit the rest of the data
for (int i = 0; i < left; i++)
*ip++ = ins->data[i];
}
if ((ins->ilOffset != -1) && !isReverted)
{
assert(ins->ilOffset >= 0);
assert(ins->nativeOffset >= 0);
uint32_t ilOffset = ins->ilOffset;
// For synchronized methods, we inject "IL" instructions after the end of the method. We can't report these to the diagnostic infra in any real way, so just don't report them.
if (ilOffset < (uint32_t)m_ILCodeSizeFromILHeader)
{
uint32_t nativeOffset = ConvertOffset(ins->nativeOffset);
if ((m_ILToNativeMapSize == 0) || (m_pILToNativeMap[m_ILToNativeMapSize - 1].ilOffset != ilOffset))
{
// This code assumes that instructions for the same IL offset are emitted in a single run without
// any other IL offsets in between and that they don't repeat again after the run ends.
#ifdef DEBUG
// Use a side table for fast checking of whether or not we've emitted this IL offset before.
// Walking the m_pILToNativeMap can be slow for excessively large functions
if (m_pNativeMapIndexToILOffset == NULL)
{
m_pNativeMapIndexToILOffset = new (this) int32_t[m_ILCodeSize];
memset(m_pNativeMapIndexToILOffset, 0, sizeof(int32_t) * m_ILCodeSize);
}
assert(m_pNativeMapIndexToILOffset[ilOffset] == 0);
m_pNativeMapIndexToILOffset[ilOffset] = m_ILToNativeMapSize;
#endif // DEBUG
// Since we can have at most one entry per IL offset,
// this map cannot possibly use more entries than the size of the IL code
assert(m_ILToNativeMapSize < m_ILCodeSize);
m_pILToNativeMap[m_ILToNativeMapSize].ilOffset = ilOffset;
m_pILToNativeMap[m_ILToNativeMapSize].nativeOffset = nativeOffset;
m_pILToNativeMap[m_ILToNativeMapSize].source = ICorDebugInfo::SOURCE_TYPE_INVALID;
m_ILToNativeMapSize++;
}
}
}
return ip;
}
void InterpCompiler::PatchRelocations(TArray<Reloc*, MemPoolAllocator> *relocs)
{
int32_t size = relocs->GetSize();
for (int32_t i = 0; i < size; i++)
{
Reloc *reloc = relocs->Get(i);
if (reloc->pTargetBB->nativeOffset < 0)
BADCODE("jump with invalid offset");
int32_t offset = reloc->pTargetBB->nativeOffset - reloc->offset;
int32_t *pSlot = NULL;
if (reloc->type == RelocLongBranch)
pSlot = m_pMethodCode + reloc->offset + reloc->skip + 1;
else if (reloc->type == RelocSwitch)
pSlot = m_pMethodCode + reloc->offset;
else
assert(0);
assert(*pSlot == (int32_t)0xdeadbeef);
*pSlot = offset;
}
}
int32_t *InterpCompiler::EmitBBCode(int32_t *ip, InterpBasicBlock *bb, TArray<Reloc*, MemPoolAllocator> *relocs)
{
m_pCBB = bb;
m_pCBB->nativeOffset = (int32_t)(ip - m_pMethodCode);
for (InterpInst *ins = bb->pFirstIns; ins != NULL; ins = ins->pNext)
{
if (InterpOpIsEmitNop(ins->opcode))
{
ins->nativeOffset = (int32_t)(ip - m_pMethodCode);
continue;
}
ip = EmitCodeIns(ip, ins, relocs);
}
m_pCBB->nativeEndOffset = (int32_t)(ip - m_pMethodCode);