forked from dotnet/runtimelab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
llvm.cpp
1701 lines (1512 loc) · 63.6 KB
/
llvm.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifdef TARGET_WASM
#include <string.h>
#include "alloc.h"
#include "compiler.h"
#include "block.h"
#include "gentree.h"
#pragma warning (disable: 4702)
#include "llvm.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/BinaryFormat/Dwarf.h"
#pragma warning (error: 4702)
using llvm::Function;
using llvm::FunctionType;
using llvm::LLVMContext;
using llvm::ArrayRef;
using llvm::Module;
static Module* _module = nullptr;
static llvm::DIBuilder* _diBuilder = nullptr;
static LLVMContext _llvmContext;
static void* _thisPtr; // TODO: workaround for not changing the JIT/EE interface. As this is static, it will probably fail if multithreaded compilation is attempted
static const char* (*_getMangledMethodName)(void*, CORINFO_METHOD_STRUCT_*);
static const char* (*_getMangledSymbolName)(void*, void*);
static const char* (*_addCodeReloc)(void*, void*);
static const uint32_t (*_isRuntimeImport)(void*, CORINFO_METHOD_STRUCT_*);
static const char* (*_getDocumentFileName)(void*);
static const uint32_t (*_firstSequencePointLineNumber)(void*);
static const uint32_t (*_getOffsetLineNumber)(void*, unsigned int ilOffset);
static const uint32_t(*_structIsWrappedPrimitive)(void*, CORINFO_CLASS_STRUCT_*, CorInfoType);
static char* _outputFileName;
static Function* _doNothingFunction;
static std::unordered_map<CORINFO_CLASS_HANDLE, Type*>* _llvmStructs = new std::unordered_map<CORINFO_CLASS_HANDLE, Type*>();
extern "C" DLLEXPORT void registerLlvmCallbacks(void* thisPtr,
const char* outputFileName,
const char* triple,
const char* dataLayout,
const char* (*getMangledMethodNamePtr)(void*, CORINFO_METHOD_STRUCT_*),
const char* (*getMangledSymbolNamePtr)(void*, void*),
const char* (*addCodeRelocPtr)(void*, void*),
const uint32_t (*isRuntimeImport)(void*, CORINFO_METHOD_STRUCT_*),
const char* (*getDocumentFileName)(void*),
const uint32_t (*firstSequencePointLineNumber)(void*),
const uint32_t (*getOffsetLineNumber)(void*, unsigned int),
const uint32_t(*structIsWrappedPrimitive)(void*, CORINFO_CLASS_STRUCT_*, CorInfoType))
{
_thisPtr = thisPtr;
_getMangledMethodName = getMangledMethodNamePtr;
_getMangledSymbolName = getMangledSymbolNamePtr;
_addCodeReloc = addCodeRelocPtr;
_isRuntimeImport = isRuntimeImport;
_getDocumentFileName = getDocumentFileName;
_firstSequencePointLineNumber = firstSequencePointLineNumber;
_getOffsetLineNumber = getOffsetLineNumber;
_structIsWrappedPrimitive = structIsWrappedPrimitive;
if (_module == nullptr) // registerLlvmCallbacks is called for each method to compile, but must only created the module once. Better perhaps to split this into 2 calls.
{
_module = new Module(llvm::StringRef("netscripten-clrjit"), _llvmContext);
_module->setTargetTriple(triple);
_module->setDataLayout(dataLayout);
_outputFileName = (char*)malloc(strlen(outputFileName) + 7);
strcpy(_outputFileName, "1.txt"); // ??? without this _outputFileName is corrupted
strcpy(_outputFileName, outputFileName);
strcpy(_outputFileName + strlen(_outputFileName) - 3, "clrjit"); // use different module output name for now, TODO: delete if old LLVM gen does not create a module
strcat(_outputFileName, ".bc");
}
}
void emitDebugMetadata(LLVMContext& context)
{
_module->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 4);
_module->addModuleFlag(llvm::Module::Warning, "Debug Info Version", 3);
_diBuilder->finalize();
}
[[noreturn]] void Llvm::failFunctionCompilation()
{
if (_function != nullptr)
{
_function->deleteBody();
}
fatal(CORJIT_SKIPPED);
}
Value* Llvm::mapGenTreeToValue(GenTree* genTree, Value* valueRef)
{
if (_sdsuMap->find(genTree) != _sdsuMap->end())
{
fatal(CorJitResult::CORJIT_INTERNALERROR);
}
_sdsuMap->insert({genTree, valueRef});
return valueRef;
}
Value* Llvm::getGenTreeValue(GenTree* op)
{
if (op->IsLocal())
{
unsigned lclNum = op->AsLclVar()->GetLclNum();
if (lclNum == _shadowStackLclNum)
{
return _function->getArg(0);
}
else if (lclNum == _retAddressLclNum)
{
return _function->getArg(1);
}
}
return _sdsuMap->at(op);
}
// maintains compatiblity with the IL->LLVM generation. TODO-LLVM, when IL generation is no more, see if we can remove this unwrapping
bool structIsWrappedPrimitive(CORINFO_CLASS_HANDLE classHnd, CorInfoType primitiveType)
{
return (*_structIsWrappedPrimitive)(_thisPtr, classHnd, primitiveType);
}
void addPaddingFields(unsigned paddingSize, std::vector<Type*> llvmFields)
{
unsigned numInts = paddingSize / 4;
unsigned numBytes = paddingSize - numInts * 4;
for (unsigned i = 0; i < numInts; i++)
{
llvmFields.push_back(Type::getInt32Ty(_llvmContext));
}
for (unsigned i = 0; i < numBytes; i++)
{
llvmFields.push_back(Type::getInt8Ty(_llvmContext));
}
}
unsigned getWellKnownTypeSize(CorInfoType corInfoType)
{
return genTypeSize(JITtype2varType(corInfoType));
}
unsigned Llvm::getElementSize(CORINFO_CLASS_HANDLE fieldClassHandle, CorInfoType corInfoType)
{
if (fieldClassHandle != NO_CLASS_HANDLE)
{
return _info.compCompHnd->getClassSize(fieldClassHandle);
}
return getWellKnownTypeSize(corInfoType);
}
llvm::Type* Llvm::getLlvmTypeForStruct(CORINFO_CLASS_HANDLE structHandle)
{
if (_llvmStructs->find(structHandle) == _llvmStructs->end())
{
llvm::Type* llvmType;
// LLVM thinks certain sizes of struct have a different calling convention than Clang does.
// Treating them as ints fixes that and is more efficient in general
unsigned structSize = _info.compCompHnd->getClassSize(structHandle);
unsigned structAlignment = _info.compCompHnd->getClassAlignmentRequirement(structHandle);
switch (structSize)
{
case 1:
llvmType = Type::getInt8Ty(_llvmContext);
break;
case 2:
if (structAlignment == 2)
{
llvmType = Type::getInt16Ty(_llvmContext);
break;
}
case 4:
if (structAlignment == 4)
{
if (structIsWrappedPrimitive(structHandle, CORINFO_TYPE_FLOAT))
{
llvmType = Type::getFloatTy(_llvmContext);
}
else
{
llvmType = Type::getInt32Ty(_llvmContext);
}
break;
}
case 8:
if (structAlignment == 8)
{
if (structIsWrappedPrimitive(structHandle, CORINFO_TYPE_DOUBLE))
{
llvmType = Type::getDoubleTy(_llvmContext);
}
else
{
llvmType = Type::getInt64Ty(_llvmContext);
}
break;
}
default:
// Forward-declare the struct in case there's a reference to it in the fields.
// This must be a named struct or LLVM hits a stack overflow
const char* name = _info.compCompHnd->getClassName(structHandle);
llvm::StructType* llvmStructType = llvm::StructType::create(_llvmContext, _info.compCompHnd->getClassName(structHandle));
llvmType = llvmStructType;
unsigned fieldCnt = _info.compCompHnd->getClassNumInstanceFields(structHandle);
std::vector<CORINFO_FIELD_HANDLE> sparseFields = std::vector<CORINFO_FIELD_HANDLE>(structSize);
std::vector<Type*> llvmFields = std::vector<Type*>();
for (unsigned i = 0; i < structSize; i++) sparseFields[i] = nullptr;
for (unsigned i = 0; i < fieldCnt; i++)
{
CORINFO_FIELD_HANDLE fieldHandle = _info.compCompHnd->getFieldInClass(structHandle, i);
unsigned fldOffset = _info.compCompHnd->getFieldOffset(fieldHandle);
assert(fldOffset < structSize);
// store the biggest field at the offset for unions
if (sparseFields[fldOffset] == nullptr ||
_info.compCompHnd->getClassSize(_info.compCompHnd->getFieldClass(fieldHandle)) > _info.compCompHnd->getClassSize(_info.compCompHnd->getFieldClass(sparseFields[fldOffset])))
{
sparseFields[fldOffset] = fieldHandle;
}
}
unsigned lastOffset = -1;
CORINFO_CLASS_HANDLE prevClass = nullptr;
CorInfoType prevCorInfoType = CorInfoType::CORINFO_TYPE_UNDEF;
unsigned totalSize = 0;
for (unsigned curOffset = 0; curOffset < structSize;)
{
CORINFO_FIELD_HANDLE fieldHandle = sparseFields[curOffset];
if (fieldHandle == nullptr)
{
curOffset++;
continue;
}
int prevElementSize;
if (prevCorInfoType == CorInfoType::CORINFO_TYPE_UNDEF)
{
lastOffset = 0;
prevElementSize = 0;
}
else
{
prevElementSize = getElementSize(prevClass, prevCorInfoType);
}
// Pad to this field if necessary
unsigned paddingSize = curOffset - lastOffset - prevElementSize;
if (paddingSize > 0)
{
addPaddingFields(paddingSize, llvmFields);
totalSize += paddingSize;
}
CORINFO_CLASS_HANDLE fieldClassHandle = NO_CLASS_HANDLE;
CorInfoType fieldCorType = _info.compCompHnd->getFieldType(fieldHandle, &fieldClassHandle);
int fieldSize = getElementSize(fieldClassHandle, fieldCorType);
llvmFields.push_back(getLlvmTypeForCorInfoType(fieldCorType, fieldClassHandle));
totalSize += fieldSize;
lastOffset = curOffset;
prevClass = fieldClassHandle;
prevCorInfoType = fieldCorType;
curOffset += fieldSize;
}
// If explicit layout is greater than the sum of fields, add padding
if (totalSize < structSize)
{
addPaddingFields(structSize - totalSize, llvmFields);
}
llvmStructType->setBody(llvmFields, true);
break;
}
_llvmStructs->insert({ structHandle, llvmType });
}
return _llvmStructs->at(structHandle);
}
// Copy of logic from ILImporter.GetLLVMTypeForTypeDesc
llvm::Type* Llvm::getLlvmTypeForCorInfoType(CorInfoType corInfoType, CORINFO_CLASS_HANDLE classHnd) {
switch (corInfoType)
{
case CorInfoType::CORINFO_TYPE_VOID:
return Type::getVoidTy(_llvmContext);
case CorInfoType::CORINFO_TYPE_BOOL:
case CorInfoType::CORINFO_TYPE_UBYTE:
case CorInfoType::CORINFO_TYPE_BYTE:
return Type::getInt8Ty(_llvmContext);
case CorInfoType::CORINFO_TYPE_INT:
case CorInfoType::CORINFO_TYPE_UINT:
case CorInfoType::CORINFO_TYPE_NATIVEINT: // TODO: Wasm64 - what does NativeInt mean for Wasm64
return Type::getInt32Ty(_llvmContext);
case CorInfoType::CORINFO_TYPE_LONG:
case CorInfoType::CORINFO_TYPE_ULONG:
return Type::getInt64Ty(_llvmContext);
case CorInfoType::CORINFO_TYPE_FLOAT:
return Type::getFloatTy(_llvmContext);
case CorInfoType::CORINFO_TYPE_DOUBLE:
return Type::getDoubleTy(_llvmContext);
case CorInfoType::CORINFO_TYPE_BYREF:
case CorInfoType::CORINFO_TYPE_CLASS:
return Type::getInt8PtrTy(_llvmContext);
case CorInfoType::CORINFO_TYPE_VALUECLASS:
return getLlvmTypeForStruct(classHnd);
default:
failFunctionCompilation();
}
}
// When looking at a sigInfo from eeGetMethodSig we have CorInfoType(s) but when looking at lclVars we have LclVarDsc or var_type(s), This method exists to allow both to map to LLVM types.
CorInfoType Llvm::toCorInfoType(var_types varType)
{
switch (varType)
{
case TYP_BOOL:
return CorInfoType::CORINFO_TYPE_BOOL;
case TYP_BYREF:
return CorInfoType::CORINFO_TYPE_BYREF;
case TYP_BYTE:
return CorInfoType::CORINFO_TYPE_BYTE;
case TYP_UBYTE:
return CorInfoType::CORINFO_TYPE_UBYTE;
case TYP_LCLBLK: // TODO: outgoing args space - need to get an example compiling, e.g. https://github.com/dotnet/runtimelab/blob/40f9ff64ae80596bcddcec16a7e1a8f57a0b2cff/src/tests/nativeaot/SmokeTests/HelloWasm/HelloWasm.cs#L3492 to see what's
// going on. CORINFO_TYPE_VALUECLASS is a better mapping but if that is mapped as of now, then canStoreTypeOnLlvmStack will fail compilation for most methods.
failFunctionCompilation();
case TYP_DOUBLE:
return CorInfoType::CORINFO_TYPE_DOUBLE;
case TYP_FLOAT:
return CorInfoType::CORINFO_TYPE_FLOAT;
case TYP_INT:
return CorInfoType::CORINFO_TYPE_INT;
case TYP_UINT:
return CorInfoType::CORINFO_TYPE_UINT;
case TYP_LONG:
return CorInfoType::CORINFO_TYPE_LONG;
case TYP_ULONG:
return CorInfoType::CORINFO_TYPE_ULONG;
case TYP_REF:
return CorInfoType::CORINFO_TYPE_REFANY;
case TYP_SHORT:
return CorInfoType::CORINFO_TYPE_SHORT;
case TYP_USHORT:
return CorInfoType::CORINFO_TYPE_USHORT;
case TYP_STRUCT:
return CorInfoType::CORINFO_TYPE_VALUECLASS;
case TYP_UNDEF:
return CorInfoType::CORINFO_TYPE_UNDEF;
default:
failFunctionCompilation();
}
}
unsigned int Llvm::padOffset(CorInfoType corInfoType, unsigned int atOffset)
{
unsigned int alignment;
if (corInfoType == CorInfoType::CORINFO_TYPE_BYREF || corInfoType == CorInfoType::CORINFO_TYPE_CLASS ||
corInfoType == CorInfoType::CORINFO_TYPE_REFANY)
{
// simplified for just pointers
alignment = TARGET_POINTER_SIZE; // TODO Wasm64 aligns pointers at 4 or 8?
}
else
{
// TODO: value type field alignment - this is the ILToLLVMImporter logic:
//var fieldAlignment = type is DefType && type.IsValueType ? ((DefType)type).InstanceFieldAlignment
// : type.Context.Target.LayoutPointerSize;
//var alignment = LayoutInt.Min(fieldAlignment, new LayoutInt(ComputePackingSize(type))).AsInt;
//var padding = (atOffset + (alignment - 1)) & ~(alignment - 1);
failFunctionCompilation();
}
return roundUp(atOffset, alignment);
}
unsigned int Llvm::padNextOffset(CorInfoType corInfoType, unsigned int atOffset)
{
unsigned int size;
if (corInfoType == CorInfoType::CORINFO_TYPE_BYREF || corInfoType == CorInfoType::CORINFO_TYPE_CLASS ||
corInfoType == CorInfoType::CORINFO_TYPE_REFANY)
{
size = TARGET_POINTER_SIZE;
}
else
{
// TODO: value type field size - this is the ILToLLVMImporter logic:
// var size = type is DefType && type.IsValueType ? ((DefType)type).InstanceFieldSize
// : type.Context.Target.LayoutPointerSize;
failFunctionCompilation(); // TODO value type sizes and alignment
}
return padOffset(corInfoType, atOffset) + size;
}
/// <summary>
/// Returns true if the type can be stored on the LLVM stack
/// instead of the shadow stack in this method. This is the case
/// if it is a non-ref primitive or a struct without GC fields.
/// </summary>
bool canStoreLocalOnLlvmStack(LclVarDsc* varDsc)
{
return !varDsc->HasGCPtr();
}
bool Llvm::canStoreArgOnLlvmStack(CorInfoType corInfoType, CORINFO_CLASS_HANDLE classHnd)
{
// structs with no GC pointers can go on LLVM stack.
if (corInfoType == CorInfoType::CORINFO_TYPE_VALUECLASS)
{
// Use getClassAtribs over typGetObjLayout because EETypePtr has CORINFO_FLG_GENERIC_TYPE_VARIABLE? which fails with typGetObjLayout
uint32_t classAttribs = _info.compCompHnd->getClassAttribs(classHnd);
return (classAttribs & CORINFO_FLG_CONTAINS_GC_PTR) == 0;
}
if (corInfoType == CorInfoType::CORINFO_TYPE_BYREF || corInfoType == CorInfoType::CORINFO_TYPE_CLASS ||
corInfoType == CorInfoType::CORINFO_TYPE_REFANY)
{
return false;
}
return true;
}
/// <summary>
/// Returns true if the method returns a type that must be kept
/// on the shadow stack
/// </summary>
bool Llvm::needsReturnStackSlot(CorInfoType corInfoType, CORINFO_CLASS_HANDLE classHnd)
{
return corInfoType != CorInfoType::CORINFO_TYPE_VOID && !canStoreArgOnLlvmStack(corInfoType, classHnd);
}
CorInfoType Llvm::getCorInfoTypeForArg(CORINFO_SIG_INFO& sigInfo, CORINFO_ARG_LIST_HANDLE& arg, CORINFO_CLASS_HANDLE* clsHnd)
{
CorInfoTypeWithMod corTypeWithMod = _info.compCompHnd->getArgType(&sigInfo, arg, clsHnd);
return strip(corTypeWithMod);
}
FunctionType* Llvm::getFunctionTypeForSigInfo(CORINFO_SIG_INFO& sigInfo)
{
if (sigInfo.hasExplicitThis() || sigInfo.hasTypeArg())
failFunctionCompilation();
// start vector with shadow stack arg, this might reduce the number of bitcasts as a i8**, TODO: try it and check LLVM bitcode size
std::vector<llvm::Type*> argVec{Type::getInt8PtrTy(_llvmContext)};
llvm::Type* retLlvmType;
if (needsReturnStackSlot(sigInfo.retType, sigInfo.retTypeClass))
{
argVec.push_back(Type::getInt8PtrTy(_llvmContext));
retLlvmType = Type::getVoidTy(_llvmContext);
}
else
{
retLlvmType = getLlvmTypeForCorInfoType(sigInfo.retType, sigInfo.retTypeClass);
}
CORINFO_ARG_LIST_HANDLE sigArgs = sigInfo.args;
//TODO: not attempting to compile generic signatures with context arg via clrjit yet
if (sigInfo.hasTypeArg())
{
failFunctionCompilation();
//signatureTypes.Add(LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0)); // *MethodTable
}
for (unsigned int i = 0; i < sigInfo.numArgs; i++, sigArgs = _info.compCompHnd->getArgNext(sigArgs))
{
CORINFO_CLASS_HANDLE classHnd;
CorInfoType corInfoType = getCorInfoTypeForArg(sigInfo, sigArgs, &classHnd);
if (canStoreArgOnLlvmStack(corInfoType, classHnd))
{
argVec.push_back(getLlvmTypeForCorInfoType(corInfoType, classHnd));
}
}
return FunctionType::get(retLlvmType, ArrayRef<Type*>(argVec), false);
}
Value* getOrCreateExternalSymbol(const char* symbolName)
{
Value* symbol = _module->getGlobalVariable(symbolName);
if (symbol == nullptr)
{
symbol = new llvm::GlobalVariable(*_module, Type::getInt32PtrTy(_llvmContext), true, llvm::GlobalValue::LinkageTypes::ExternalLinkage, (llvm::Constant*)nullptr, symbolName);
}
return symbol;
}
Function* getOrCreateRhpAssignRef()
{
Function* llvmFunc = _module->getFunction("RhpAssignRef");
if (llvmFunc == nullptr)
{
llvmFunc = Function::Create(FunctionType::get(Type::getVoidTy(_llvmContext), ArrayRef<Type*>{Type::getInt8PtrTy(_llvmContext), Type::getInt8PtrTy(_llvmContext)}, false), Function::ExternalLinkage, 0U, "RhpAssignRef", _module); // TODO: ExternalLinkage forced as linked from old module
}
return llvmFunc;
}
Type* Llvm::getLLVMTypeForVarType(var_types type)
{
// TODO: Fill out with missing type mappings and when all code done via clrjit, default should fail with useful
// message
switch (type)
{
case TYP_BOOL:
case TYP_BYTE:
case TYP_UBYTE:
return Type::getInt8Ty(_llvmContext);
case TYP_SHORT:
case TYP_USHORT:
return Type::getInt16Ty(_llvmContext);
case TYP_INT:
return Type::getInt32Ty(_llvmContext);
case var_types::TYP_FLOAT:
return Type::getFloatTy(_llvmContext);
case var_types::TYP_DOUBLE:
return Type::getDoubleTy(_llvmContext);
case TYP_REF:
return Type::getInt8PtrTy(_llvmContext);
default:
failFunctionCompilation();
}
}
llvm::Instruction* Llvm::getCast(llvm::Value* source, Type* targetType)
{
Type* sourceType = source->getType();
if (sourceType == targetType)
return nullptr;
Type::TypeID sourceTypeID = sourceType->getTypeID();
Type::TypeID targetTypeId = targetType->getTypeID();
if (targetTypeId == Type::TypeID::PointerTyID)
{
switch (sourceTypeID)
{
case Type::TypeID::PointerTyID:
return new llvm::BitCastInst(source, targetType, "CastPtrToPtr");
case Type::TypeID::IntegerTyID:
return new llvm::IntToPtrInst(source, targetType, "CastPtrToInt");
default:
failFunctionCompilation();
}
}
if (targetTypeId == Type::TypeID::IntegerTyID)
{
switch (sourceTypeID)
{
case Type::TypeID::IntegerTyID:
if (sourceType->getPrimitiveSizeInBits() > targetType->getPrimitiveSizeInBits())
{
return new llvm::TruncInst(source, targetType, "TruncInt");
}
default:
failFunctionCompilation();
}
}
failFunctionCompilation();
}
Value* Llvm::castIfNecessary(Value* source, Type* targetType)
{
llvm::Instruction* castInst = getCast(source, targetType);
if (castInst == nullptr)
return source;
return _builder.Insert(castInst);
}
Value* Llvm::castToPointerToLlvmType(Value* address, llvm::Type* llvmType)
{
return castIfNecessary(address, llvmType->getPointerTo());
}
void Llvm::castingStore(Value* toStore, Value* address, llvm::Type* llvmType)
{
_builder.CreateStore(castIfNecessary(toStore, llvmType),
castToPointerToLlvmType(address, llvmType));
}
void Llvm::castingStore(Value* toStore, Value* address, var_types type)
{
castingStore(toStore, address, getLLVMTypeForVarType(type));
}
/// <summary>
/// Returns the llvm arg number or shadow stack offset for the corresponding local which must be loaded from an argument
/// </summary>
LlvmArgInfo Llvm::getLlvmArgInfoForArgIx(CORINFO_SIG_INFO& sigInfo, unsigned int lclNum)
{
if (sigInfo.hasExplicitThis() || sigInfo.hasTypeArg())
failFunctionCompilation();
unsigned int llvmArgNum = 1; // skip shadow stack arg
bool returnOnStack = false;
LlvmArgInfo llvmArgInfo = {
-1 /* default to not an LLVM arg*/, sigInfo.hasThis() ? TARGET_POINTER_SIZE : 0 /* this is the first pointer on
the shadow stack */
};
if (needsReturnStackSlot(sigInfo.retType, sigInfo.retTypeClass))
{
if (lclNum == 0)
{
// the first IR arg is the return address, but its not in sigInfo so handle here
llvmArgInfo.m_argIx = llvmArgNum;
return llvmArgInfo;
}
lclNum--; // line up with sigArgs
llvmArgNum++;
}
CORINFO_ARG_LIST_HANDLE sigArgs = sigInfo.args;
unsigned int shadowStackOffset = llvmArgInfo.m_shadowStackOffset;
unsigned int i = 0;
for (; i < sigInfo.numArgs; i++, sigArgs = _info.compCompHnd->getArgNext(sigArgs))
{
CORINFO_CLASS_HANDLE clsHnd;
CorInfoType corInfoType = getCorInfoTypeForArg(sigInfo, sigArgs, &clsHnd);
if (canStoreArgOnLlvmStack(corInfoType, clsHnd))
{
if (lclNum == i)
{
llvmArgInfo.m_argIx = llvmArgNum;
break;
}
llvmArgNum++;
}
else
{
if (lclNum == i)
{
llvmArgInfo.m_shadowStackOffset = shadowStackOffset;
break;
}
shadowStackOffset += TARGET_POINTER_SIZE; // TODO size of arg, for now only handles byrefs and class types
}
}
assert(lclNum == i); // lclNum not an argument
return llvmArgInfo;
}
void Llvm::emitDoNothingCall()
{
if (_doNothingFunction == nullptr)
{
_doNothingFunction = Function::Create(FunctionType::get(Type::getVoidTy(_llvmContext), ArrayRef<Type*>(), false), Function::ExternalLinkage, 0U, "llvm.donothing", _module);
}
_builder.CreateCall(_doNothingFunction);
}
void Llvm::buildAdd(GenTree* node, Value* op1, Value* op2)
{
if (op1->getType()->isPointerTy() && op2->getType()->isIntegerTy())
{
mapGenTreeToValue(node, _builder.CreateGEP(op1, op2));
}
else if (op1->getType()->isIntegerTy() && op2->getType() == op1->getType())
{
mapGenTreeToValue(node, _builder.CreateAdd(op1, op2));
}
else
{
// unsupported add type combination
failFunctionCompilation();
}
}
Value* Llvm::genTreeAsLlvmType(GenTree* tree, Type* type)
{
Value* v = getGenTreeValue(tree);
if (v->getType() == type)
return v;
if (tree->IsIntegralConst() && tree->TypeIs(TYP_INT))
{
if (type->isPointerTy())
{
return _builder.CreateIntToPtr(v, type);
}
return _builder.getInt({(unsigned int)type->getPrimitiveSizeInBits().getFixedSize(), (uint64_t)tree->AsIntCon()->IconValue(), true});
}
failFunctionCompilation();
}
unsigned int Llvm::getTotalRealLocalOffset()
{
return _shadowStackLocalsSize;
}
unsigned int Llvm::getTotalLocalOffset()
{
unsigned int offset = getTotalRealLocalOffset();
for (unsigned int i = 0; i < _spilledExpressions.size(); i++)
{
offset = padNextOffset(_spilledExpressions[i].m_CorInfoType, offset);
}
return AlignUp(offset, TARGET_POINTER_SIZE);
}
unsigned int Llvm::getSpillOffsetAtIndex(unsigned int index, unsigned int offset)
{
SpilledExpressionEntry spill = _spilledExpressions[index];
for (unsigned int i = 0; i < index; i++)
{
offset = padNextOffset(_spilledExpressions[i].m_CorInfoType, offset);
}
offset = padOffset(spill.m_CorInfoType, offset);
return offset;
}
llvm::Value* Llvm::getShadowStackOffest(Value* shadowStack, unsigned int offset)
{
if (offset == 0)
{
return shadowStack;
}
return _builder.CreateGEP(shadowStack, _builder.getInt32(offset));
}
llvm::BasicBlock* Llvm::getLLVMBasicBlockForBlock(BasicBlock* block)
{
llvm::BasicBlock* llvmBlock;
if (_blkToLlvmBlkVectorMap->Lookup(block, &llvmBlock))
return llvmBlock;
llvmBlock = llvm::BasicBlock::Create(_llvmContext, "", _function);
_blkToLlvmBlkVectorMap->Set(block, llvmBlock);
return llvmBlock;
}
bool Llvm::isThisArg(GenTreeCall* call, GenTree* operand)
{
if (call->gtCallThisArg == nullptr)
{
return false;
}
return _compiler->gtGetThisArg(call) == operand;
}
void Llvm::storeOnShadowStack(GenTree* operand, Value* shadowStackForCallee, unsigned int offset)
{
castingStore(genTreeAsLlvmType(operand, Type::getInt8PtrTy(_llvmContext)),
getShadowStackOffest(shadowStackForCallee, offset), Type::getInt8PtrTy(_llvmContext));
}
// shadow stack moved up to avoid overwriting anything on the stack in the compiling method
llvm::Value* Llvm::getShadowStackForCallee()
{
unsigned int offset = getTotalLocalOffset();
return offset == 0 ? _function->getArg(0) : _builder.CreateGEP(_function->getArg(0), _builder.getInt32(offset));
}
llvm::Value* Llvm::buildUserFuncCall(GenTreeCall* call)
{
const char* symbolName = (*_getMangledSymbolName)(_thisPtr, call->gtEntryPoint.handle);
if (_isRuntimeImport(_thisPtr, call->gtCallMethHnd))
{
failFunctionCompilation();
}
(*_addCodeReloc)(_thisPtr, call->gtEntryPoint.handle);
Function* llvmFunc = _module->getFunction(symbolName);
CORINFO_SIG_INFO sigInfo;
_compiler->eeGetMethodSig(call->gtCallMethHnd, &sigInfo);
if (llvmFunc == nullptr)
{
CORINFO_ARG_LIST_HANDLE sigArgs = sigInfo.args;
// assume ExternalLinkage, if the function is defined in the clrjit module, then it is replaced and an extern
// added to the Ilc module
llvmFunc = Function::Create(getFunctionTypeForSigInfo(sigInfo), Function::ExternalLinkage,
0U, symbolName, _module);
}
std::vector<llvm::Value*> argVec;
// shadowstack arg first
Value* shadowStackForCallee = getShadowStackForCallee(); // TODO: store this in the prolog and calculate once.
argVec.push_back(shadowStackForCallee); // TODO-LLVM: we are not moving this past any return address args, so the return address is clobbering the first slot in the shadow stack.
// As the return is the last thing executed this seems ok, but then the question becomes why do we need the return address arg at all
// apart from compatibility with IL->LLVM?
unsigned int shadowStackUseOffest = 0;
int argIx = 0;
GenTree* thisArg = nullptr;
fgArgInfo* argInfo = call->fgArgInfo;
unsigned int argCount = argInfo->ArgCount();
fgArgTabEntry** argTable = argInfo->ArgTable();
std::vector<OperandArgNum> sortedArgs = std::vector<OperandArgNum>(argCount);
OperandArgNum* sortedData = sortedArgs.data();
for (unsigned i = 0; i < argCount; i++)
{
fgArgTabEntry* curArgTabEntry = argTable[i];
unsigned int argNum = curArgTabEntry->argNum;
OperandArgNum opAndArg = {argNum, curArgTabEntry->GetNode()};
sortedData[argNum] = opAndArg;
}
for (OperandArgNum opAndArg : sortedArgs)
{
if (opAndArg.operand->IsArgPlaceHolderNode())
{
continue;
}
LlvmArgInfo llvmArgInfo = getLlvmArgInfoForArgIx(sigInfo, argIx);
if (llvmArgInfo.m_argIx >= 0)
{
// pass the parameter on the LLVM stack
argVec.push_back(genTreeAsLlvmType(opAndArg.operand, llvmFunc->getArg(llvmArgInfo.m_argIx)->getType()));
}
else
{
// pass on shadow stack
storeOnShadowStack(opAndArg.operand, shadowStackForCallee, shadowStackUseOffest);
shadowStackUseOffest += TARGET_POINTER_SIZE;
}
argIx++;
}
Value* llvmCall = _builder.CreateCall(llvmFunc, ArrayRef<Value*>(argVec));
return mapGenTreeToValue(call, llvmCall);
}
void Llvm::buildCall(GenTree* node)
{
GenTreeCall* call = node->AsCall();
if (call->gtCallType == CT_HELPER)
{
if (call->gtCallMethHnd == _compiler->eeFindHelper(CORINFO_HELP_READYTORUN_STATIC_BASE))
{
const char* symbolName = (*_getMangledSymbolName)(_thisPtr, call->gtEntryPoint.handle);
Function* llvmFunc = _module->getFunction(symbolName);
if (llvmFunc == nullptr)
{
llvmFunc = Function::Create(FunctionType::get(Type::getInt8PtrTy(_llvmContext), ArrayRef<Type*>(Type::getInt8PtrTy(_llvmContext)), false), Function::ExternalLinkage, 0U, symbolName, _module); // TODO: ExternalLinkage forced as defined in ILC module
}
// replacement for _info.compCompHnd->recordRelocation(nullptr, gtCall->gtEntryPoint.handle, IMAGE_REL_BASED_REL32);
(*_addCodeReloc)(_thisPtr, call->gtEntryPoint.handle);
mapGenTreeToValue(node, _builder.CreateCall(llvmFunc, getShadowStackForCallee()));
return;
}
}
else if (call->gtCallType == CT_USER_FUNC && !call->IsVirtualStub() /* TODO: Virtual stub not implemented */)
{
buildUserFuncCall(call);
return;
}
failFunctionCompilation();
}
void Llvm::buildCast(GenTreeCast* cast)
{
if (cast->CastToType() == TYP_BOOL && cast->TypeIs(TYP_INT) && cast->CastOp()->TypeIs(TYP_INT))
{
Value* intValue = _builder.CreateZExt(getGenTreeValue(cast->CastOp()), getLLVMTypeForVarType(TYP_INT));
mapGenTreeToValue(cast, intValue); // nothing to do except map the source value to the destination GenTree
}
else if (cast->CastToType() == TYP_DOUBLE && cast->CastOp()->TypeIs(TYP_FLOAT))
{
mapGenTreeToValue(cast, _builder.CreateFPCast(getGenTreeValue(cast->CastOp()), getLLVMTypeForVarType(TYP_DOUBLE)));
}
else if (cast->CastToType() == TYP_INT && cast->CastOp()->TypeIs(TYP_FLOAT, TYP_DOUBLE))
{
mapGenTreeToValue(cast,
cast->IsUnsigned()
? _builder.CreateFPToUI(getGenTreeValue(cast->CastOp()), getLLVMTypeForVarType(TYP_INT))
: _builder.CreateFPToSI(getGenTreeValue(cast->CastOp()), getLLVMTypeForVarType(TYP_INT)));
}
else
{
// TODO: other casts
failFunctionCompilation();
}
}
void Llvm::buildCnsDouble(GenTreeDblCon* node)
{
if (node->TypeIs(TYP_DOUBLE))
{
mapGenTreeToValue(node, llvm::ConstantFP::get(Type::getDoubleTy(_llvmContext), node->gtDconVal));
}
else
{
assert(node->TypeIs(TYP_FLOAT));
mapGenTreeToValue(node, llvm::ConstantFP::get(Type::getFloatTy(_llvmContext), node->gtDconVal));
}
}
void Llvm::buildCnsInt(GenTree* node)
{
if (node->gtType == TYP_INT)
{
mapGenTreeToValue(node, _builder.getInt32(node->AsIntCon()->IconValue()));
return;
}
if (node->gtType == TYP_REF)
{
ssize_t intCon = node->AsIntCon()->gtIconVal;
if (node->IsIconHandle(GTF_ICON_STR_HDL))
{
const char* symbolName = (*_getMangledSymbolName)(_thisPtr, (void *)(node->AsIntCon()->IconValue()));
(*_addCodeReloc)(_thisPtr, (void*)node->AsIntCon()->IconValue());
mapGenTreeToValue(node, _builder.CreateLoad(getOrCreateExternalSymbol(symbolName)));
return;
}
// TODO: delete this check, just handling string constants and null ptr stores for now, other TYP_REFs not implemented yet
if (intCon != 0)
{
failFunctionCompilation();
}
mapGenTreeToValue(node, _builder.CreateIntToPtr(_builder.getInt32(intCon), Type::getInt8PtrTy(_llvmContext))); // TODO: wasm64
return;
}
failFunctionCompilation();
}
void Llvm::buildInd(GenTree* node, Value* ptr)
{
// first cast the pointer to create the correct load instructions, then cast the result incase we are loading a small int into an int32
mapGenTreeToValue(node, castIfNecessary(_builder.CreateLoad(
castIfNecessary(ptr,
getLLVMTypeForVarType(node->TypeGet())->getPointerTo())), getLLVMTypeForVarType(genActualType(node))));
}
Value* Llvm::buildJTrue(GenTree* node, Value* opValue)
{
return _builder.CreateCondBr(opValue, getLLVMBasicBlockForBlock(_currentBlock->bbJumpDest), getLLVMBasicBlockForBlock(_currentBlock->bbNext));
}
void Llvm::buildCmp(genTreeOps op, GenTree* node, Value* op1, Value* op2)
{
llvm::CmpInst::Predicate llvmPredicate;
bool isIntOrPtr = op1->getType()->isIntOrPtrTy();
switch (op)
{
case GT_EQ:
llvmPredicate = isIntOrPtr ? llvm::CmpInst::Predicate::ICMP_EQ : llvm::CmpInst::Predicate::FCMP_OEQ;
break;
case GT_NE:
llvmPredicate = isIntOrPtr ? llvm::CmpInst::Predicate::ICMP_NE : llvm::CmpInst::Predicate::FCMP_ONE;
break;
case GT_LE:
llvmPredicate = isIntOrPtr ? (node->IsUnsigned() ? llvm::CmpInst::Predicate::ICMP_ULE : llvm::CmpInst::Predicate::ICMP_SLE)
: llvm::CmpInst::Predicate::FCMP_OLE;
break;
case GT_LT:
llvmPredicate = isIntOrPtr ? (node->IsUnsigned() ? llvm::CmpInst::Predicate::ICMP_ULT : llvm::CmpInst::Predicate::ICMP_SLT)
: llvm::CmpInst::Predicate::FCMP_OLT;
break;
case GT_GE:
llvmPredicate = isIntOrPtr ? (node->IsUnsigned() ? llvm::CmpInst::Predicate::ICMP_UGE : llvm::CmpInst::Predicate::ICMP_SGE)
: llvm::CmpInst::Predicate::FCMP_OGE;
break;
case GT_GT:
llvmPredicate = isIntOrPtr ? (node->IsUnsigned() ? llvm::CmpInst::Predicate::ICMP_UGT : llvm::CmpInst::Predicate::ICMP_SGT)
: llvm::CmpInst::Predicate::FCMP_OGT;
break;
default:
failFunctionCompilation(); // TODO all genTreeOps values
}