forked from terralang/terra
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tcompiler.cpp
4054 lines (3805 loc) · 152 KB
/
tcompiler.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
/* See Copyright Notice in ../LICENSE.txt */
#include "tcompiler.h"
#include "tkind.h"
#include "terrastate.h"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include <assert.h>
#include <stdio.h>
#include <inttypes.h>
#include <cmath>
#include <sstream>
#include "llvmheaders.h"
#include "tcompilerstate.h" //definition of terra_CompilerState which contains LLVM state
#include "tobj.h"
#if LLVM_VERSION < 170
// FIXME (Elliott): need to restore the manual inliner in LLVM 17
#include "tinline.h"
#endif
#include "llvm/Support/ManagedStatic.h"
#if LLVM_VERSION < 120
#include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
#endif
#include "llvm/Support/Atomic.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "tllvmutil.h"
#ifdef _WIN32
#include <io.h>
#include <time.h>
#include "twindows.h"
#undef interface
#else
#include <unistd.h>
#include <sys/time.h>
#endif
using namespace llvm;
#define TERRALIB_FUNCTIONS(_) \
_(inittarget, 1) \
_(freetarget, 0) \
_(initcompilationunit, 1) \
_(compilationunitaddvalue, \
1) /*entry point from lua into compiler to generate LLVM for a function, other \
functions it calls may not yet exist*/ \
_(freecompilationunit, 0) \
_(jit, 1) /*entry point from lua into compiler to actually invoke the JIT by calling \
getPointerToFunction*/ \
_(llvmsizeof, 1) \
_(disassemble, 1) \
_(pointertolightuserdata, 0) /*because luajit ffi doesn't do this...*/ \
_(bindtoluaapi, 0) \
_(gcdebug, 0) \
_(saveobjimpl, 1) \
_(linklibraryimpl, 1) \
_(linkllvmimpl, 1) \
_(currenttimeinseconds, 0) \
_(isintegral, 0) \
_(dumpmodule, 1)
#define DEF_LIBFUNCTION(nm, isclo) static int terra_##nm(lua_State *L);
TERRALIB_FUNCTIONS(DEF_LIBFUNCTION)
#undef DEF_LIBFUNCTION
#ifdef PRINT_LLVM_TIMING_STATS
static llvm_shutdown_obj llvmshutdownobj;
#endif
#define TERRA_DUMP_FUNCTION(t) (t)->print(llvm::errs(), nullptr)
#define TERRA_DUMP_TYPE(t) (t)->print(llvm::errs(), true)
#define TERRA_DUMP_MODULE(t) (t)->print(llvm::errs(), nullptr)
#define MEM_ARRAY_THRESHOLD 64
struct DisassembleFunctionListener : public JITEventListener {
TerraCompilationUnit *CU;
terra_State *T;
DisassembleFunctionListener(TerraCompilationUnit *CU_) : CU(CU_), T(CU_->T) {}
void InitializeDebugData(StringRef name, object::SymbolRef::Type type, uint64_t sz) {
if (type == object::SymbolRef::ST_Function) {
#if !defined(__arm__) && !defined(__linux__) && !defined(__FreeBSD__)
name = name.substr(1);
#endif
void *addr = (void *)CU->ee->getFunctionAddress(name.str());
if (addr) {
assert(addr);
TerraFunctionInfo &fi = T->C->functioninfo[addr];
fi.ctx = CU->TT->ctx;
fi.name = name.str();
fi.addr = addr;
fi.size = sz;
}
}
}
virtual void NotifyObjectEmitted(const object::ObjectFile &Obj,
const RuntimeDyld::LoadedObjectInfo &L) {
auto size_map = llvm::object::computeSymbolSizes(Obj);
for (auto &S : size_map) {
object::SymbolRef sym = S.first;
auto name = sym.getName();
auto type = sym.getType();
if (name && type) InitializeDebugData(name.get(), type.get(), S.second);
}
}
};
class TerraSectionMemoryManager : public SectionMemoryManager {
public:
TerraSectionMemoryManager(TerraCompilationUnit *CU_in, MemoryMapper *MM = nullptr)
: SectionMemoryManager(MM) {
CU = CU_in;
}
TerraSectionMemoryManager(const TerraSectionMemoryManager &) = delete;
void operator=(const TerraSectionMemoryManager &) = delete;
void notifyObjectLoaded(ExecutionEngine *EE, const object::ObjectFile &obj) override {
auto size_map = llvm::object::computeSymbolSizes(obj);
for (auto &S : size_map) {
object::SymbolRef sym = S.first;
auto name = sym.getName();
auto type = sym.getType();
// printf("notify: %s %d %#010llx\n", cantFail(std::move(name)).data(),
// cantFail(std::move(type)), S.second);
if (name && type)
static_cast<DisassembleFunctionListener *>(CU->jiteventlistener)
->InitializeDebugData(name.get(), type.get(), S.second);
}
}
private:
TerraCompilationUnit *CU;
};
static double CurrentTimeInSeconds() {
#ifdef _WIN32
static uint64_t freq = 0;
if (freq == 0) {
LARGE_INTEGER i;
QueryPerformanceFrequency(&i);
freq = i.QuadPart;
}
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return t.QuadPart / (double)freq;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec / 1000000.0;
#endif
}
static int terra_currenttimeinseconds(lua_State *L) {
lua_pushnumber(L, CurrentTimeInSeconds());
return 1;
}
static void AddLLVMOptions(int N, ...) {
va_list ap;
va_start(ap, N);
std::vector<const char *> ops;
ops.push_back("terra");
for (int i = 0; i < N; i++) {
const char *arg = va_arg(ap, const char *);
ops.push_back(arg);
}
cl::ParseCommandLineOptions(N + 1, &ops[0]);
}
// useful for debugging GC problems. You can attach it to
static int terra_gcdebug(lua_State *L) {
lua_newuserdata(L, sizeof(void *));
lua_getfield(L, LUA_GLOBALSINDEX, "terra");
lua_getfield(L, -1, "llvm_gcdebugmetatable");
lua_setmetatable(L, -3);
lua_pop(L, 1); // the 'terra' table
lua_setfield(L, -2, "llvm_gcdebughandle");
return 0;
}
static void RegisterFunction(struct terra_State *T, const char *name, int isclo,
lua_CFunction fn) {
if (isclo) {
lua_pushlightuserdata(T->L, (void *)T);
lua_pushcclosure(T->L, fn, 1);
} else {
lua_pushcfunction(T->L, fn);
}
lua_setfield(T->L, -2, name);
}
static llvm::sys::Mutex terrainitlock;
static int terrainitcount;
bool OneTimeInit(struct terra_State *T) {
bool success = true;
terrainitlock.lock();
terrainitcount++;
if (terrainitcount == 1) {
#ifdef PRINT_LLVM_TIMING_STATS
AddLLVMOptions(1, "-time-passes");
#endif
#if !defined(__arm__) && !defined(__aarch64__) && !defined(__PPC__)
AddLLVMOptions(1, "-x86-asm-syntax=intel");
#endif
InitializeAllTargets();
InitializeAllTargetInfos();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
InitializeAllTargetMCs();
}
terrainitlock.unlock();
return success;
}
// LLVM 3.1 doesn't enable avx even if it is present, we detect and force it here
bool HostHasAVX() {
StringMap<bool> Features;
sys::getHostCPUFeatures(Features);
return Features["avx"];
}
int terra_inittarget(lua_State *L) {
terra_State *T = terra_getstate(L, 1);
TerraTarget *TT = new TerraTarget();
TT->id = T->targets.size();
T->targets.push_back(TT);
TT->nreferences = 2;
if (!lua_isnil(L, 1)) {
TT->Triple = lua_tostring(L, 1);
} else {
TT->Triple = llvm::sys::getProcessTriple();
}
if (!lua_isnil(L, 2))
TT->CPU = lua_tostring(L, 2);
else
TT->CPU = llvm::sys::getHostCPUName().str();
#if defined(__x86_64__) || defined(_WIN32)
if (TT->CPU == "generic") {
TT->CPU = "x86-64";
}
#endif
if (!lua_isnil(L, 3))
TT->Features = lua_tostring(L, 3);
else {
#ifdef DISABLE_AVX
TT->Features = "-avx";
#else
TT->Features = HostHasAVX() ? "+avx" : "";
#endif
}
TargetOptions options;
if (lua_toboolean(L, 4)) { // FloatABIHard boolean
options.FloatABIType = FloatABI::Hard;
} else {
#ifdef __arm__
// force hard float since we currently onlly work on platforms that have it
options.FloatABIType = FloatABI::Hard;
#endif
}
TT->next_unused_id = 0;
TT->ctx = new LLVMContext();
#if LLVM_VERSION >= 150 && LLVM_VERSION < 170
// Hack: This is a workaround to avoid the opaque pointer
// transition, but we will need to deal with it eventually.
// FIXME: https://github.com/terralang/terra/issues/553
TT->ctx->setOpaquePointers(false);
#endif
std::string err;
const Target *TheTarget = TargetRegistry::lookupTarget(TT->Triple, err);
if (!TheTarget) {
luaL_error(L, "failed to initialize target for LLVM Triple: %s (%s)",
TT->Triple.c_str(), err.c_str());
}
TT->tm = TheTarget->createTargetMachine(
TT->Triple, TT->CPU, TT->Features, options,
#if defined(__linux__) || defined(__unix__)
Reloc::PIC_,
#else
#if LLVM_VERSION < 160
Optional<Reloc::Model>(),
#else
std::optional<Reloc::Model>(),
#endif
#endif
#if defined(__powerpc64__)
// On PPC the small model is limited to 16bit offsets
CodeModel::Medium,
#else
// Use small model so that we can use signed 32bits offset in the function and
// GV tables
CodeModel::Small,
#endif
#if LLVM_VERSION < 180
CodeGenOpt::Aggressive
#else
CodeGenOptLevel::Aggressive
#endif
);
TT->external = new Module("external", *TT->ctx);
TT->external->setTargetTriple(TT->Triple);
lua_pushlightuserdata(L, TT);
return 1;
}
int terra_initcompilationunit(lua_State *L) {
terra_State *T = terra_getstate(L, 1);
TerraCompilationUnit *CU = new TerraCompilationUnit();
TerraTarget *TT = (TerraTarget *)terra_tocdatapointer(L, 1);
CU->TT = TT;
CU->TT->nreferences++;
CU->nreferences = 1;
CU->T = T;
CU->C = T->C;
CU->C->nreferences++;
CU->optimize = lua_toboolean(L, 2);
int ref_table = lobj_newreftable(L);
{
Obj profile;
lua_pushvalue(L, 3);
profile.initFromStack(L, ref_table);
assert(profile.hasfield("fastmath"));
Obj mathflags;
bool ok = profile.obj("fastmath", &mathflags);
assert(ok);
llvm::FastMathFlags fastmath;
for (int i = 1; mathflags.hasfield(i); i++) {
const char *flag = mathflags.string(i);
// Thanks to LLVM's lack of support for parsing these values,
// we have to do this by hand.
if (strcmp(flag, "nnan") == 0) {
fastmath.setNoNaNs();
} else if (strcmp(flag, "ninf") == 0) {
fastmath.setNoInfs();
} else if (strcmp(flag, "nsz") == 0) {
fastmath.setNoSignedZeros();
} else if (strcmp(flag, "arcp") == 0) {
fastmath.setAllowReciprocal();
} else if (strcmp(flag, "contract") == 0) {
fastmath.setAllowContract();
} else if (strcmp(flag, "afn") == 0) {
fastmath.setApproxFunc();
} else if (strcmp(flag, "reassoc") == 0) {
fastmath.setAllowReassoc();
} else if (strcmp(flag, "fast") == 0) {
fastmath.setFast();
} else {
assert(false && "unrecognized fast math flag");
}
}
CU->fastmath = fastmath;
}
lobj_removereftable(L, ref_table);
CU->M = new Module("terra", *TT->ctx);
CU->M->setTargetTriple(TT->Triple);
CU->M->setDataLayout(TT->tm->createDataLayout());
#if LLVM_VERSION < 170
// FIXME (Elliott): need to restore the manual inliner in LLVM 17
CU->mi = new ManualInliner(TT->tm, CU->M);
CU->fpm = new FunctionPassManagerT(CU->M);
llvmutil_addtargetspecificpasses(CU->fpm, TT->tm);
llvmutil_addoptimizationpasses(CU->fpm);
CU->fpm->doInitialization();
#else
CU->fpm = new FunctionPassManager(llvmutil_createoptimizationpasses(
TT->tm, CU->lam, CU->fam, CU->cgam, CU->mam));
#endif
lua_pushlightuserdata(L, CU);
return 1;
}
static void InitializeJIT(TerraCompilationUnit *CU) {
if (CU->ee) return; // already initialized
Module *topeemodule = new Module("terra", *CU->TT->ctx);
#ifdef _WIN32
std::string MCJITTriple = CU->TT->Triple;
MCJITTriple.append("-elf"); // on windows we need to use an elf container because
// coff is not supported yet
topeemodule->setTargetTriple(MCJITTriple);
#else
topeemodule->setTargetTriple(CU->TT->Triple);
#endif
std::string err;
std::vector<std::string> mattrs;
if (!CU->TT->Features.empty()) mattrs.push_back(CU->TT->Features);
EngineBuilder eb(UNIQUEIFY(Module, topeemodule));
eb.setErrorStr(&err)
.setMCPU(CU->TT->CPU)
.setMAttrs(mattrs)
.setEngineKind(EngineKind::JIT)
.setTargetOptions(CU->TT->tm->Options)
.setOptLevel(
#if LLVM_VERSION < 180
CodeGenOpt::Aggressive
#else
CodeGenOptLevel::Aggressive
#endif
)
.setMCJITMemoryManager(std::make_unique<TerraSectionMemoryManager>(CU))
#if LLVM_VERSION < 120
.setUseOrcMCJITReplacement(true)
#endif
;
CU->ee = eb.create();
if (!CU->ee) terra_reporterror(CU->T, "llvm: %s\n", err.c_str());
CU->jiteventlistener = new DisassembleFunctionListener(CU);
}
int terra_compilerinit(struct terra_State *T) {
if (!OneTimeInit(T)) return LUA_ERRRUN;
lua_getfield(T->L, LUA_GLOBALSINDEX, "terra");
#define REGISTER_FN(name, isclo) RegisterFunction(T, #name, isclo, terra_##name);
TERRALIB_FUNCTIONS(REGISTER_FN)
#undef REGISTER_FN
lua_pushnumber(T->L, LLVM_VERSION);
lua_setfield(T->L, -2, "llvmversion");
lua_pop(T->L, 1); // remove terra from stack
T->C = new terra_CompilerState();
memset(T->C, 0, sizeof(terra_CompilerState));
T->C->nreferences = 1;
return 0;
}
void freetarget(TerraTarget *TT) {
assert(TT->nreferences > 0);
if (0 == --TT->nreferences) {
delete TT->external;
delete TT->tm;
delete TT->ctx;
delete TT;
}
}
int terra_freetarget(lua_State *L) {
freetarget((TerraTarget *)terra_tocdatapointer(L, 1));
return 0;
}
static void freecompilationunit(TerraCompilationUnit *CU) {
assert(CU->nreferences > 0);
if (0 == --CU->nreferences) {
#if LLVM_VERSION < 170
// FIXME (Elliott): need to restore the manual inliner in LLVM 17
delete CU->mi;
#endif
delete CU->fpm;
if (CU->ee) {
CU->ee->UnregisterJITEventListener(CU->jiteventlistener);
delete CU->jiteventlistener;
delete CU->ee;
}
delete CU->M; // we own the module so we delete it
freetarget(CU->TT);
terra_compilerfree(CU->C); // decrement reference count to compiler
delete CU;
}
}
int terra_freecompilationunit(lua_State *L) {
freecompilationunit((TerraCompilationUnit *)terra_tocdatapointer(L, 1));
return 0;
}
int terra_compilerfree(struct terra_CompilerState *C) {
assert(C->nreferences > 0);
if (0 == --C->nreferences) {
if (C->MB.base() != NULL) {
llvm::sys::Memory::releaseMappedMemory(C->MB);
}
C->functioninfo.clear();
delete C;
}
return 0;
}
static void GetStructEntries(Obj *typ, Obj *entries) {
Obj layout;
if (!typ->obj("cachedlayout", &layout)) {
assert(!"typechecked failed to complete type needed by the compiler, this is a bug.");
}
layout.obj("entries", entries);
}
struct TType { // contains llvm raw type pointer and any metadata about it we need
Type *type;
bool issigned;
bool islogical;
bool incomplete; // does this aggregate type or its children include an incomplete
// struct
};
class Types {
TerraCompilationUnit *CU;
terra_State *T;
TType *GetIncomplete(Obj *typ) {
TType *t = NULL;
if (!LookupTypeCache(typ, &t)) {
assert(t);
switch (typ->kind("kind")) {
case T_pointer: {
Obj base;
typ->obj("type", &base);
Type *baset = (base.kind("kind") == T_functype)
? Type::getInt8Ty(*CU->TT->ctx)
: GetIncomplete(&base)->type;
t->type = PointerType::get(baset, typ->number("addressspace"));
} break;
case T_array: {
Obj base;
typ->obj("type", &base);
int N = typ->number("N");
TType *baset = GetIncomplete(&base);
t->type = ArrayType::get(baset->type, N);
t->incomplete = baset->incomplete;
} break;
case T_struct: {
StructType *st = CreateStruct(typ);
t->type = st;
t->incomplete = st->isOpaque();
} break;
case T_vector: {
Obj base;
typ->obj("type", &base);
int N = typ->number("N");
TType *ttype =
GetIncomplete(&base); // vectors can only contain primitives,
// so the type must be complete
Type *baseType = ttype->type;
t->issigned = ttype->issigned;
t->islogical = ttype->islogical;
t->type = VectorType::get(baseType, N, false);
} break;
case T_primitive: {
CreatePrimitiveType(typ, t);
} break;
case T_niltype: {
#if LLVM_VERSION < 170
t->type = Type::getInt8PtrTy(*CU->TT->ctx);
#else
t->type = PointerType::get(*CU->TT->ctx, 0);
#endif
} break;
case T_opaque: {
t->type = Type::getInt8Ty(*CU->TT->ctx);
} break;
default: {
printf("kind = %d, %s\n", typ->kind("kind"),
tkindtostr(typ->kind("kind")));
terra_reporterror(T, "type not understood or not primitive\n");
} break;
}
}
assert(t && t->type);
return t;
}
void CreatePrimitiveType(Obj *typ, TType *t) {
int bytes = typ->number("bytes");
switch (typ->kind("type")) {
case T_float: {
if (bytes == 4) {
t->type = Type::getFloatTy(*CU->TT->ctx);
} else {
assert(bytes == 8);
t->type = Type::getDoubleTy(*CU->TT->ctx);
}
} break;
case T_integer: {
t->issigned = typ->boolean("signed");
t->type = Type::getIntNTy(*CU->TT->ctx, bytes * 8);
} break;
case T_logical: {
t->type = Type::getInt8Ty(*CU->TT->ctx);
t->islogical = true;
} break;
default: {
printf("kind = %d, %s\n", typ->kind("kind"),
tkindtostr(typ->kind("type")));
terra_reporterror(T, "type not understood");
} break;
}
}
Type *FunctionPointerType() {
#if LLVM_VERSION < 170
return Type::getInt8PtrTy(*CU->TT->ctx);
#else
return PointerType::get(*CU->TT->ctx, 0);
#endif
}
bool LookupTypeCache(Obj *typ, TType **t) {
*t = (TType *)CU->symbols->getud(typ); // try to look up the cached type
if (*t == NULL) {
CU->symbols->push();
typ->push();
*t = (TType *)lua_newuserdata(T->L, sizeof(TType));
lua_settable(T->L, -3);
lua_pop(T->L, 1);
memset(*t, 0, sizeof(TType));
assert(*t != NULL);
return false;
}
return true;
}
StructType *CreateStruct(Obj *typ) {
// Note: historically, Terra tried to reuse the types generated by Clang when
// importing C headers. This is why we maintain an `llvm_definingfunction` and
// `llvm_definingtarget`. As of the opaque pointer migration (circa LLVM 15-17),
// this approach no longer works. But it turns out that we don't need it: we can
// just define the structs below, as we've always been doing (and found was
// required for external targets).
std::string name = typ->asstring("name");
bool isreserved = beginsWith(name, "struct.") || beginsWith(name, "union.");
name = (isreserved) ? std::string("$") + name : name;
if (isreserved)
return StructType::create(*CU->TT->ctx, name);
else
return StructType::create(*CU->TT->ctx);
}
bool beginsWith(const std::string &s, const std::string &prefix) {
return s.substr(0, prefix.size()) == prefix;
}
void LayoutStruct(StructType *st, Obj *typ) {
Obj layout;
GetStructEntries(typ, &layout);
int N = layout.size();
std::vector<Type *> entry_types;
MaybeAlign unionAlign; // minimum union alignment
Type *unionType = NULL; // type with the largest alignment constraint
size_t unionAlignSz = 0; // size of type with largest alignment contraint
size_t unionSz = 0; // allocation size of the largest member
for (int i = 0; i < N; i++) {
Obj v;
layout.objAt(i, &v);
Obj vt;
v.obj("type", &vt);
Type *fieldtype = Get(&vt)->type;
bool inunion = v.boolean("inunion");
if (inunion) {
Align align = CU->getDataLayout().getABITypeAlign(fieldtype);
// orequal is to make sure we have a non-null
// type even if it is a 0-sized struct
if (encode(MaybeAlign(align)) >= encode(unionAlign)) {
unionAlign = align;
unionType = fieldtype;
unionAlignSz = CU->getDataLayout().getTypeAllocSize(fieldtype);
}
size_t allocSize = CU->getDataLayout().getTypeAllocSize(fieldtype);
if (allocSize > unionSz) unionSz = allocSize;
// check if this is the last member of the union, and if it is, add it to
// our struct
Obj nextObj;
if (i + 1 < N) layout.objAt(i + 1, &nextObj);
if (i + 1 == N ||
nextObj.number("allocation") != v.number("allocation")) {
std::vector<Type *> union_types;
assert(unionType);
union_types.push_back(unionType);
if (unionAlignSz <
unionSz) { // the type with the largest alignment requirement is
// not the type with the largest size, pad this struct
// so that it will fit the largest type
size_t diff = unionSz - unionAlignSz;
union_types.push_back(
ArrayType::get(Type::getInt8Ty(*CU->TT->ctx), diff));
}
entry_types.push_back(StructType::get(*CU->TT->ctx, union_types));
unionAlign = MaybeAlign();
unionType = NULL;
unionAlignSz = 0;
unionSz = 0;
}
} else {
entry_types.push_back(fieldtype);
}
}
st->setBody(entry_types);
VERBOSE_ONLY(T) {
printf("Struct Layout Is:\n");
TERRA_DUMP_TYPE(st);
printf("\nEnd Layout\n");
}
}
public:
Types(TerraCompilationUnit *CU_) : CU(CU_), T(CU_->T) {}
TType *Get(Obj *typ) {
assert(typ->kind("kind") != T_functype); // Get should not be called on function
// directly, only function pointers
TType *t = GetIncomplete(typ);
if (t->incomplete) {
assert(t->type->isAggregateType());
switch (typ->kind("kind")) {
case T_struct: {
LayoutStruct(cast<StructType>(t->type), typ);
} break;
case T_array: {
Obj base;
typ->obj("type", &base);
Get(&base); // force base type to be completed
} break;
default:
terra_reporterror(
T, "type marked incomplete is not an array or struct\n");
}
}
t->incomplete = false;
return t;
}
bool IsUnitType(Obj *t) {
t->pushfield("isunit");
t->push();
lua_call(T->L, 1, 1);
bool result = lua_toboolean(T->L, -1);
lua_pop(T->L, 1);
return result;
}
void EnsureTypeIsComplete(Obj *typ) { Get(typ); }
void EnsurePointsToCompleteType(Obj *ptrTy) {
if (ptrTy->kind("kind") == T_pointer) {
Obj objTy;
ptrTy->obj("type", &objTy);
EnsureTypeIsComplete(&objTy);
} // otherwise it is niltype and already complete
}
static void PointsToType(Obj *ptrTy, Obj *result) {
if (ptrTy->kind("kind") == T_pointer) {
ptrTy->obj("type", result);
} else {
printf("unexpected kind = %d, %s\n", ptrTy->kind("kind"),
tkindtostr(ptrTy->kind("kind")));
assert(false);
}
}
};
// helper function to alloca at the beginning of function
static AllocaInst *CreateAlloca(IRBuilder<> *B, Type *Ty, Value *ArraySize = 0,
const Twine &Name = "") {
BasicBlock *entry = &B->GetInsertBlock()->getParent()->getEntryBlock();
IRBuilder<> TmpB(entry,
entry->begin()); // make sure alloca are at the beginning of the
// function this is needed because alloca's that do
// not dominate the function do weird things
return TmpB.CreateAlloca(Ty, ArraySize, Name);
}
static Value *CreateConstGEP2_32(IRBuilder<> *B, Value *Ptr, Type *ValueType,
unsigned Idx0, unsigned Idx1) {
return B->CreateConstGEP2_32(ValueType, Ptr, Idx0, Idx1);
}
// functions that handle the details of the x86_64 ABI (this really should be handled by
// LLVM...)
struct CCallingConv {
TerraCompilationUnit *CU;
terra_State *T;
lua_State *L;
terra_CompilerState *C;
Types *Ty;
bool return_empty_struct_as_void;
bool aarch64_cconv;
bool amdgpu_cconv;
bool ppc64_cconv;
int ppc64_float_limit;
int ppc64_int_limit;
bool ppc64_count_used;
bool spirv_cconv;
bool wasm_cconv;
CCallingConv(TerraCompilationUnit *CU_, Types *Ty_)
: CU(CU_),
T(CU_->T),
L(CU_->T->L),
C(CU_->T->C),
Ty(Ty_),
return_empty_struct_as_void(false),
aarch64_cconv(false),
amdgpu_cconv(false),
ppc64_cconv(false),
ppc64_float_limit(0),
ppc64_int_limit(0),
ppc64_count_used(false),
spirv_cconv(false),
wasm_cconv(false) {
auto Triple = CU->TT->tm->getTargetTriple();
switch (Triple.getArch()) {
case Triple::ArchType::amdgcn: {
return_empty_struct_as_void = true;
amdgpu_cconv = true;
} break;
case Triple::ArchType::aarch64:
case Triple::ArchType::aarch64_be: {
aarch64_cconv = true;
// Hack: we share code with the PPC64 cconv, so configure here.
ppc64_float_limit = 4;
ppc64_int_limit = 2;
ppc64_count_used = false;
} break;
case Triple::ArchType::ppc64:
case Triple::ArchType::ppc64le: {
ppc64_cconv = true;
ppc64_float_limit = 8;
ppc64_int_limit = 8;
ppc64_count_used = true;
} break;
#if LLVM_VERSION >= 150
case Triple::ArchType::spirv32:
case Triple::ArchType::spirv64: {
return_empty_struct_as_void = true;
spirv_cconv = true;
} break;
#endif
case Triple::ArchType::wasm32:
case Triple::ArchType::wasm64: {
wasm_cconv = true;
} break;
default:
break;
}
switch (Triple.getOS()) {
case Triple::OSType::Win32: {
return_empty_struct_as_void = true;
} break;
default:
break;
}
}
enum RegisterClass {
C_NO_CLASS = 0,
C_SSE_FLOAT = 1,
C_SSE_DOUBLE = 2,
C_INTEGER = 3,
C_MEMORY = 4
};
enum ArgumentKind {
C_PRIMITIVE, // passed without modifcation (i.e. any non-aggregate type)
C_AGGREGATE_REG, // aggregate passed through registers
C_AGGREGATE_MEM, // aggregate passed through memory
C_ARRAY_REG, // aggregate passed through registers as an array
};
struct Argument {
ArgumentKind kind;
TType *type; // orignal type for the object
Type *cctype; // if type == C_AGGREGATE_REG, this is a struct that holds a list
// of the values that goes into the registers
// if type == CC_PRIMITIVE, this is the struct that this type
// appear in the argument list and the type should be coerced to
Argument() {}
Argument(ArgumentKind kind, TType *type, Type *cctype = NULL) {
this->kind = kind;
this->type = type;
this->cctype = cctype ? cctype : type->type;
}
int GetNumberOfTypesInParamList(Type *type) {
StructType *st = dyn_cast<StructType>(type);
if (st) {
size_t total = 0;
for (auto elt_type : st->elements()) {
total += GetNumberOfTypesInParamList(elt_type);
}
return total;
}
return 1;
}
int GetNumberOfTypesInParamList() {
if (this->kind == C_AGGREGATE_REG)
return GetNumberOfTypesInParamList(this->cctype);
return 1;
}
};
struct Classification {
Argument returntype;
std::vector<Argument> paramtypes;
FunctionType *fntype;
};
RegisterClass Meet(RegisterClass a, RegisterClass b) { return (a > b) ? a : b; }
void MergeValue(RegisterClass *classes, size_t offset, Obj *type) {
Type *t = Ty->Get(type)->type;
int entry = offset / 8;
if (t->isVectorTy()) // we don't handle structures with vectors in them yet
classes[entry] = C_MEMORY;
else if (t->isFloatTy())
classes[entry] = Meet(classes[entry], C_SSE_FLOAT);
else if (t->isDoubleTy())
classes[entry] = Meet(classes[entry], C_SSE_DOUBLE);
else if (t->isIntegerTy() || t->isPointerTy())
classes[entry] = Meet(classes[entry], C_INTEGER);
else if (t->isStructTy()) {
StructType *st = cast<StructType>(Ty->Get(type)->type);
assert(!st->isOpaque());
const StructLayout *sl = CU->getDataLayout().getStructLayout(st);
Obj layout;
GetStructEntries(type, &layout);
int N = layout.size();
for (int i = 0; i < N; i++) {
Obj entry;
layout.objAt(i, &entry);
int allocation = entry.number("allocation");
size_t structoffset = sl->getElementOffset(allocation);
Obj entrytype;
entry.obj("type", &entrytype);
MergeValue(classes, offset + structoffset, &entrytype);
}
} else if (t->isArrayTy()) {
ArrayType *at = cast<ArrayType>(Ty->Get(type)->type);
size_t elemsize = CU->getDataLayout().getTypeAllocSize(at->getElementType());
size_t sz = at->getNumElements();
Obj elemtype;
type->obj("type", &elemtype);
for (size_t i = 0; i < sz; i++)
MergeValue(classes, offset + i * elemsize, &elemtype);
} else
assert(!"unexpected value in classification");
}
#ifndef _WIN32
Type *TypeForClass(size_t size, RegisterClass clz) {
switch (clz) {
case C_SSE_FLOAT:
case C_SSE_DOUBLE:
switch (size) {
case 4:
return Type::getFloatTy(*CU->TT->ctx);
case 8:
return (C_SSE_DOUBLE == clz)
? Type::getDoubleTy(*CU->TT->ctx)
: VectorType::get(Type::getFloatTy(*CU->TT->ctx),
2, false);
default:
assert(!"unexpected size for floating point class");
}
case C_INTEGER:
assert(size <= 8);
return Type::getIntNTy(*CU->TT->ctx, size * 8);
default:
assert(!"unexpected class");
}
}
bool ValidAggregateSize(size_t sz) { return sz <= 16; }
#else
Type *TypeForClass(size_t size, RegisterClass clz) {
assert(size <= 8);
return Type::getIntNTy(*CU->TT->ctx, size * 8);
}
bool ValidAggregateSize(size_t sz) {
bool isPow2 = sz && !(sz & (sz - 1));
return sz <= 8 && isPow2;
}
#endif
void CountValuesPPC64(Type *t, bool &all_float, bool &all_double, int &n_elts,
int64_t &align) {
StructType *st = dyn_cast<StructType>(t);
if (st) {
for (auto elt : st->elements()) {
CountValuesPPC64(elt, all_float, all_double, n_elts, align);
}
return;
}
ArrayType *at = dyn_cast<ArrayType>(t);
if (at) {
Type *elt = at->getElementType();
uint64_t sz = at->getNumElements();
for (uint64_t i = 0; i < sz; ++i) {
CountValuesPPC64(elt, all_float, all_double, n_elts, align);
}
return;