This repository has been archived by the owner on Feb 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathllvm_engine.cpp
1195 lines (991 loc) · 45.2 KB
/
llvm_engine.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "execution/vm/llvm_engine.h"
#include <llvm/ADT/StringMap.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Bitcode/BitcodeReader.h>
#include <llvm/ExecutionEngine/RuntimeDyld.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Verifier.h>
#include <llvm/MC/MCContext.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/SmallVectorMemoryBuffer.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/AlwaysInliner.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <llvm/Transforms/InstCombine/InstCombine.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Scalar/GVN.h>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "execution/ast/type.h"
#include "execution/vm/bytecode_module.h"
#include "execution/vm/bytecode_traits.h"
#include "loggers/execution_logger.h"
extern void *__dso_handle __attribute__((__visibility__("hidden"))); // NOLINT
namespace noisepage::execution::vm {
namespace {
bool FunctionHasIndirectReturn(const ast::FunctionType *func_type) {
ast::Type *ret_type = func_type->GetReturnType();
return (!ret_type->IsNilType() && ret_type->GetSize() > sizeof(int64_t));
}
bool FunctionHasDirectReturn(const ast::FunctionType *func_type) {
ast::Type *ret_type = func_type->GetReturnType();
return (!ret_type->IsNilType() && ret_type->GetSize() <= sizeof(int64_t));
}
} // namespace
// ---------------------------------------------------------
// TPL's Jit Memory Manager
// ---------------------------------------------------------
class LLVMEngine::TPLMemoryManager : public llvm::SectionMemoryManager {
public:
llvm::JITSymbol findSymbol(const std::string &name) override {
EXECUTION_LOG_TRACE("Resolving symbol '{}' ...", name);
if (const auto iter = symbols_.find(name); iter != symbols_.end()) {
EXECUTION_LOG_TRACE("Symbol '{}' found in cache ...", name);
return llvm::JITSymbol(iter->second);
}
if (name == "__dso_handle") {
EXECUTION_LOG_DEBUG("'__dso_handle' resolved to {} ...", reinterpret_cast<uint64_t>(&__dso_handle));
return {reinterpret_cast<uint64_t>(&__dso_handle), {}};
}
EXECUTION_LOG_TRACE("Symbol '{}' not found in cache, checking process ...", name);
llvm::JITSymbol symbol = llvm::SectionMemoryManager::findSymbol(name);
// If you're here because you tripped the assertion, check that you have EXPORT'd symbol definitions.
// Symptoms may include your code working in interpreted, adaptive, and codegen, but not in JIT.
#ifndef NDEBUG
if (symbol.getAddress().get() == 0) {
EXECUTION_LOG_ERROR("Resolved symbol has no address, you may need to EXPORT: {}", name);
}
#endif // NDEBUG
NOISEPAGE_ASSERT(symbol.getAddress().get() != 0, "Resolved symbol has no address!");
symbols_[name] = {symbol.getAddress().get(), symbol.getFlags()};
return symbol;
}
private:
std::unordered_map<std::string, llvm::JITEvaluatedSymbol> symbols_;
};
// ---------------------------------------------------------
// TPL Type to LLVM Type
// ---------------------------------------------------------
/** A handy class that maps TPL types to LLVM types. */
class LLVMEngine::TypeMap {
public:
explicit TypeMap(llvm::Module *module) : module_(module) {
llvm::LLVMContext &ctx = module->getContext();
type_map_["nil"] = llvm::Type::getVoidTy(ctx);
type_map_["bool"] = llvm::Type::getInt8Ty(ctx);
type_map_["int8"] = llvm::Type::getInt8Ty(ctx);
type_map_["int16"] = llvm::Type::getInt16Ty(ctx);
type_map_["int32"] = llvm::Type::getInt32Ty(ctx);
type_map_["int64"] = llvm::Type::getInt64Ty(ctx);
type_map_["int128"] = llvm::Type::getInt128Ty(ctx);
type_map_["uint8"] = llvm::Type::getInt8Ty(ctx);
type_map_["uint16"] = llvm::Type::getInt16Ty(ctx);
type_map_["uint32"] = llvm::Type::getInt32Ty(ctx);
type_map_["uint64"] = llvm::Type::getInt64Ty(ctx);
type_map_["uint128"] = llvm::Type::getInt128Ty(ctx);
type_map_["float32"] = llvm::Type::getFloatTy(ctx);
type_map_["float64"] = llvm::Type::getDoubleTy(ctx);
type_map_["string"] = llvm::Type::getInt8PtrTy(ctx);
}
/** No copying or moving this class. */
DISALLOW_COPY_AND_MOVE(TypeMap);
llvm::Type *VoidType() { return type_map_["nil"]; }
llvm::Type *BoolType() { return type_map_["bool"]; }
llvm::Type *Int8Type() { return type_map_["int8"]; }
llvm::Type *Int16Type() { return type_map_["int16"]; }
llvm::Type *Int32Type() { return type_map_["int32"]; }
llvm::Type *Int64Type() { return type_map_["int64"]; }
llvm::Type *UInt8Type() { return type_map_["uint8"]; }
llvm::Type *UInt16Type() { return type_map_["uint16"]; }
llvm::Type *UInt32Type() { return type_map_["uint32"]; }
llvm::Type *UInt64Type() { return type_map_["uint64"]; }
llvm::Type *Float32Type() { return type_map_["float32"]; }
llvm::Type *Float64Type() { return type_map_["float64"]; }
llvm::Type *StringType() { return type_map_["string"]; }
llvm::Type *GetLLVMType(const ast::Type *type);
private:
// Given a non-primitive builtin type, convert it to an LLVM type
llvm::Type *GetLLVMTypeForBuiltin(const ast::BuiltinType *builtin_type);
// Given a struct type, convert it into an equivalent LLVM struct type
llvm::StructType *GetLLVMStructType(const ast::StructType *struct_type);
// Given a TPL function type, convert it into an equivalent LLVM function type
llvm::FunctionType *GetLLVMFunctionType(const ast::FunctionType *func_type);
private:
llvm::Module *module_;
std::unordered_map<std::string, llvm::Type *> type_map_;
};
llvm::Type *LLVMEngine::TypeMap::GetLLVMType(const ast::Type *type) {
//
// First, lookup the type in the cache. We do the lookup by performing a
// try_emplace() in order to save a second lookup in the case when the type
// does not exist in the cache. If the type is uncached, we can directly
// update the returned iterator rather than performing another lookup.
//
auto [iter, inserted] = type_map_.try_emplace(type->ToString(), nullptr);
if (!inserted) {
return iter->second;
}
//
// The type isn't cached, construct it now
//
llvm::Type *llvm_type = nullptr;
switch (type->GetTypeId()) {
case ast::Type::TypeId::StringType: {
// These should be pre-filled in type cache!
UNREACHABLE("Missing default type not found in cache");
}
case ast::Type::TypeId::BuiltinType: {
llvm_type = GetLLVMTypeForBuiltin(type->As<ast::BuiltinType>());
break;
}
case ast::Type::TypeId::PointerType: {
auto *ptr_type = type->As<ast::PointerType>();
llvm_type = llvm::PointerType::getUnqual(GetLLVMType(ptr_type->GetBase()));
break;
}
case ast::Type::TypeId::ArrayType: {
auto *arr_type = type->As<ast::ArrayType>();
llvm::Type *elem_type = GetLLVMType(arr_type->GetElementType());
if (arr_type->HasKnownLength()) {
llvm_type = llvm::ArrayType::get(elem_type, arr_type->GetLength());
} else {
llvm_type = llvm::PointerType::getUnqual(elem_type);
}
break;
}
case ast::Type::TypeId::MapType: {
// TODO(pmenon): me
break;
}
case ast::Type::TypeId::StructType: {
llvm_type = GetLLVMStructType(type->As<ast::StructType>());
break;
}
case ast::Type::TypeId::FunctionType: {
llvm_type = GetLLVMFunctionType(type->As<ast::FunctionType>());
break;
}
}
//
// Update the cache with the constructed type
//
NOISEPAGE_ASSERT(llvm_type != nullptr, "No LLVM type found!");
iter->second = llvm_type;
return llvm_type;
}
llvm::Type *LLVMEngine::TypeMap::GetLLVMTypeForBuiltin(const ast::BuiltinType *builtin_type) {
NOISEPAGE_ASSERT(!builtin_type->IsPrimitive(), "Primitive types should be cached!");
// For the builtins, we perform a lookup using the C++ name
const std::string name = builtin_type->GetCppName();
// Try "struct" prefix
if (llvm::Type *type = module_->getTypeByName("struct." + name)) {
return type;
}
// Try "class" prefix
if (llvm::Type *type = module_->getTypeByName("class." + name)) {
return type;
}
EXECUTION_LOG_ERROR("Could not find LLVM type for TPL type '{}'", name);
return nullptr;
}
llvm::StructType *LLVMEngine::TypeMap::GetLLVMStructType(const ast::StructType *struct_type) {
// Collect the fields here
llvm::SmallVector<llvm::Type *, 8> fields;
for (const auto &field : struct_type->GetAllFields()) {
fields.push_back(GetLLVMType(field.type_));
}
return llvm::StructType::create(fields);
}
llvm::FunctionType *LLVMEngine::TypeMap::GetLLVMFunctionType(const ast::FunctionType *func_type) {
// Collect parameter types here
llvm::SmallVector<llvm::Type *, 8> param_types;
//
// If the function has an indirect return value, insert it into the parameter
// list as the hidden first argument, and setup the function to return void.
// Otherwise, the return type of the LLVM function is the same as the TPL
// function.
//
llvm::Type *return_type = nullptr;
if (FunctionHasIndirectReturn(func_type)) {
llvm::Type *rv_param = GetLLVMType(func_type->GetReturnType()->PointerTo());
param_types.push_back(rv_param);
// Return type of the function is void
return_type = VoidType();
} else {
return_type = GetLLVMType(func_type->GetReturnType());
}
//
// Now the formal parameters
//
for (const auto ¶m_info : func_type->GetParams()) {
llvm::Type *param_type = GetLLVMType(param_info.type_);
param_types.push_back(param_type);
}
return llvm::FunctionType::get(return_type, param_types, false);
}
// ---------------------------------------------------------
// Function Locals Map
// ---------------------------------------------------------
/** This class provides access to a function's local variables. */
class LLVMEngine::FunctionLocalsMap {
public:
FunctionLocalsMap(const FunctionInfo &func_info, llvm::Function *func, TypeMap *type_map,
llvm::IRBuilder<> *ir_builder);
// Given a reference to a local variable in a function's local variable list,
// return the corresponding LLVM value.
llvm::Value *GetArgumentById(LocalVar var);
private:
llvm::IRBuilder<> *ir_builder_;
llvm::DenseMap<uint32_t, llvm::Value *> params_;
llvm::DenseMap<uint32_t, llvm::Value *> locals_;
};
LLVMEngine::FunctionLocalsMap::FunctionLocalsMap(const FunctionInfo &func_info, llvm::Function *func, TypeMap *type_map,
llvm::IRBuilder<> *ir_builder)
: ir_builder_(ir_builder) {
uint32_t local_idx = 0;
const auto &func_locals = func_info.GetLocals();
// Make an allocation for the return value, if it's direct.
if (const ast::FunctionType *func_type = func_info.GetFuncType(); FunctionHasDirectReturn(func_type)) {
llvm::Type *ret_type = type_map->GetLLVMType(func_type->GetReturnType());
llvm::Value *val = ir_builder_->CreateAlloca(ret_type);
params_[func_locals[0].GetOffset()] = val;
local_idx++;
}
// Cache parameters.
for (auto arg_iter = func->arg_begin(); local_idx < func_info.GetParamsCount(); ++local_idx, ++arg_iter) {
const LocalInfo ¶m = func_locals[local_idx];
params_[param.GetOffset()] = &*arg_iter;
}
// Allocate all local variables up front.
for (; local_idx < func_info.GetLocals().size(); local_idx++) {
const LocalInfo &local_info = func_locals[local_idx];
llvm::Type *llvm_type = type_map->GetLLVMType(local_info.GetType());
llvm::Value *val = ir_builder_->CreateAlloca(llvm_type);
locals_[local_info.GetOffset()] = val;
}
}
llvm::Value *LLVMEngine::FunctionLocalsMap::GetArgumentById(LocalVar var) {
if (auto iter = params_.find(var.GetOffset()); iter != params_.end()) {
return iter->second;
}
if (auto iter = locals_.find(var.GetOffset()); iter != locals_.end()) {
llvm::Value *val = iter->second;
if (var.GetAddressMode() == LocalVar::AddressMode::Value) {
val = ir_builder_->CreateLoad(val);
}
return val;
}
EXECUTION_LOG_ERROR("No variable found at offset {}", var.GetOffset());
return nullptr;
}
// ---------------------------------------------------------
// Compiled Module Builder
// ---------------------------------------------------------
/** A builder for compiled modules. We need this because compiled modules are immutable after creation. */
class LLVMEngine::CompiledModuleBuilder {
public:
CompiledModuleBuilder(const CompilerOptions &options, const BytecodeModule &tpl_module);
// No copying or moving this class
DISALLOW_COPY_AND_MOVE(CompiledModuleBuilder);
// Generate all static local data in the module
void DeclareStaticLocals();
// Generate function declarations for each function in the TPL bytecode module
void DeclareFunctions();
// Generate an LLVM function implementation for each function defined in the
// TPL bytecode module. DeclareFunctions() must be called to generate function
// declarations before they can be defined.
void DefineFunctions();
// Verify that all generated code is good
void Verify();
// Remove unused code to make optimizations quicker
void Simplify();
// Optimize the generate code
void Optimize();
// Perform finalization logic and create a compiled module
std::unique_ptr<CompiledModule> Finalize();
// Print the contents of the module to a string and return it
std::string DumpModuleIR();
// Print the contents of the module's assembly to a string and return it
std::string DumpModuleAsm();
private:
// Given a TPL function, build a simple CFG using 'blocks' as an output param
void BuildSimpleCFG(const FunctionInfo &func_info, std::map<std::size_t, llvm::BasicBlock *> *blocks);
// Convert one TPL function into an LLVM implementation
void DefineFunction(const FunctionInfo &func_info, llvm::IRBuilder<> *ir_builder);
// Given a bytecode, lookup it's LLVM function handler in the module
llvm::Function *LookupBytecodeHandler(Bytecode bytecode) const;
// Generate an in-memory shared object from this LLVM module. It iss assumed
// that all functions have been generated and verified.
std::unique_ptr<llvm::MemoryBuffer> EmitObject();
// Write the given object to the file system
void PersistObjectToFile(const llvm::MemoryBuffer &obj_buffer);
private:
const CompilerOptions &options_;
const BytecodeModule &tpl_module_;
std::unique_ptr<llvm::TargetMachine> target_machine_;
std::unique_ptr<llvm::LLVMContext> context_;
std::unique_ptr<llvm::Module> llvm_module_;
std::unique_ptr<TypeMap> type_map_;
llvm::DenseMap<std::size_t, llvm::Constant *> static_locals_;
};
// ---------------------------------------------------------
// Compiled Module Builder
// ---------------------------------------------------------
LLVMEngine::CompiledModuleBuilder::CompiledModuleBuilder(const CompilerOptions &options,
const BytecodeModule &tpl_module)
: options_(options),
tpl_module_(tpl_module),
target_machine_(nullptr),
context_(std::make_unique<llvm::LLVMContext>()),
llvm_module_(nullptr),
type_map_(nullptr) {
//
// We need to create a suitable TargetMachine for LLVM to before we can JIT
// TPL programs. At the moment, we rely on LLVM to discover all CPU features
// e.g., AVX2 or AVX512, and we make no assumptions about symbol relocations.
//
// TODO(pmenon): This may change with LLVM8 that comes with
// TargetMachineBuilders
// TODO(pmenon): Alter the flags as need be
//
const std::string target_triple = llvm::sys::getProcessTriple();
{
std::string error;
auto *target = llvm::TargetRegistry::lookupTarget(target_triple, error);
if (target == nullptr) {
EXECUTION_LOG_ERROR("LLVM: Unable to find target with target_triple {}", target_triple);
return;
}
// Collect CPU features
llvm::StringMap<bool> feature_map;
if (bool success = llvm::sys::getHostCPUFeatures(feature_map); !success) {
EXECUTION_LOG_ERROR("LLVM: Unable to find all CPU features");
return;
}
llvm::SubtargetFeatures target_features;
for (const auto &entry : feature_map) {
target_features.AddFeature(entry.getKey(), entry.getValue());
}
EXECUTION_LOG_TRACE("LLVM: Discovered CPU features: {}", target_features.getString());
// Both relocation=PIC or JIT=true work. Use the latter for now.
llvm::TargetOptions target_options;
llvm::Optional<llvm::Reloc::Model> reloc;
const llvm::CodeGenOpt::Level opt_level = llvm::CodeGenOpt::Aggressive;
target_machine_.reset(target->createTargetMachine(target_triple, llvm::sys::getHostCPUName(),
target_features.getString(), target_options, reloc, {}, opt_level,
true));
NOISEPAGE_ASSERT(target_machine_ != nullptr, "LLVM: Unable to find a suitable target machine!");
}
//
// We've built a TargetMachine we use to generate machine code. Now, we
// load the pre-compiled bytecode module containing all the TPL bytecode
// logic. We add the functions we're about to compile into this module. This
// module forms the unit of JIT.
//
{
auto memory_buffer = llvm::MemoryBuffer::getFile(GetEngineSettings()->GetBytecodeHandlersBcPath());
if (auto error = memory_buffer.getError()) {
EXECUTION_LOG_ERROR("There was an error loading the handler bytecode: {}", error.message());
}
auto module = llvm::parseBitcodeFile(*(memory_buffer.get()), *context_);
if (!module) {
auto error = llvm::toString(module.takeError());
EXECUTION_LOG_ERROR("{}", error);
throw std::runtime_error(error);
}
llvm_module_ = std::move(module.get());
llvm_module_->setModuleIdentifier(tpl_module.GetName());
llvm_module_->setSourceFileName(tpl_module.GetName() + ".tpl");
llvm_module_->setDataLayout(target_machine_->createDataLayout());
llvm_module_->setTargetTriple(target_triple);
}
type_map_ = std::make_unique<TypeMap>(llvm_module_.get());
}
void LLVMEngine::CompiledModuleBuilder::DeclareStaticLocals() {
for (const auto &local_info : tpl_module_.GetStaticLocalsInfo()) {
// The raw data wrapped in a string reference
llvm::StringRef data_ref(
reinterpret_cast<const char *>(tpl_module_.AccessStaticLocalDataRaw(local_info.GetOffset())),
local_info.GetSize());
// The constant
llvm::Constant *string_constant = llvm::ConstantDataArray::getString(*context_, data_ref);
// The global variable wrapping the constant. It's private to this module, so it does NOT
// participate in linking. It also not thread-local since it's shared across all threads. Don't
// be alarmed by 'new' here; the module will take care of deleting it.
auto *global_var =
new llvm::GlobalVariable(*llvm_module_, string_constant->getType(), true, llvm::GlobalValue::PrivateLinkage,
string_constant, local_info.GetName(), nullptr, llvm::GlobalVariable::NotThreadLocal);
global_var->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
global_var->setAlignment(1);
// Convert the global variable into an i8*
llvm::Constant *zero = llvm::ConstantInt::get(type_map_->Int32Type(), 0);
llvm::Constant *indices[] = {zero, zero};
auto result = llvm::ConstantExpr::getInBoundsGetElementPtr(global_var->getValueType(), global_var, indices);
// Cache
static_locals_[local_info.GetOffset()] = result;
}
}
void LLVMEngine::CompiledModuleBuilder::DeclareFunctions() {
for (const auto &func_info : tpl_module_.GetFunctionsInfo()) {
auto *func_type = llvm::cast<llvm::FunctionType>(type_map_->GetLLVMType(func_info.GetFuncType()));
llvm_module_->getOrInsertFunction(func_info.GetName(), func_type);
}
}
llvm::Function *LLVMEngine::CompiledModuleBuilder::LookupBytecodeHandler(Bytecode bytecode) const {
const char *handler_name = Bytecodes::GetBytecodeHandlerName(bytecode);
llvm::Function *func = llvm_module_->getFunction(handler_name);
#ifndef NDEBUG
if (func == nullptr) {
auto error =
fmt::format("No bytecode handler function '{}' for bytecode {}", handler_name, Bytecodes::ToString(bytecode));
EXECUTION_LOG_ERROR("{}", error);
throw std::runtime_error(error);
}
#endif
return func;
}
void LLVMEngine::CompiledModuleBuilder::BuildSimpleCFG(const FunctionInfo &func_info,
std::map<std::size_t, llvm::BasicBlock *> *blocks) {
// Before we can generate LLVM IR, we need to build a control-flow graph (CFG) for the function.
// We do this construction directly from the TPL bytecode using a vanilla DFS and produce an
// ordered map ('blocks') from bytecode position to an LLVM basic block. Each entry in the map
// indicates the start of a basic block.
// We use this vector as a stack for DFS traversal
llvm::SmallVector<std::size_t, 16> bb_begin_positions = {0};
for (auto iter = tpl_module_.GetBytecodeForFunction(func_info); !bb_begin_positions.empty();) {
std::size_t begin_pos = bb_begin_positions.back();
bb_begin_positions.pop_back();
// We're at what we think is the start of a new basic block. Scan it until we find a terminal
// instruction. Once we do,
for (iter.SetPosition(begin_pos); !iter.Done(); iter.Advance()) {
Bytecode bytecode = iter.CurrentBytecode();
// If the bytecode isn't a terminal for the block, continue until we reach one
if (!Bytecodes::IsTerminal(bytecode)) {
continue;
}
// Return?
if (Bytecodes::IsReturn(bytecode)) {
break;
}
// Unconditional branch?
if (Bytecodes::IsUnconditionalJump(bytecode)) {
std::size_t branch_target_pos =
iter.GetPosition() + Bytecodes::GetNthOperandOffset(bytecode, 0) + iter.GetJumpOffsetOperand(0);
if (blocks->find(branch_target_pos) == blocks->end()) {
(*blocks)[branch_target_pos] = nullptr;
bb_begin_positions.push_back(branch_target_pos);
}
break;
}
// Conditional branch?
if (Bytecodes::IsConditionalJump(bytecode)) {
std::size_t fallthrough_pos = iter.GetPosition() + iter.CurrentBytecodeSize();
if (blocks->find(fallthrough_pos) == blocks->end()) {
bb_begin_positions.push_back(fallthrough_pos);
(*blocks)[fallthrough_pos] = nullptr;
}
std::size_t branch_target_pos =
iter.GetPosition() + Bytecodes::GetNthOperandOffset(bytecode, 1) + iter.GetJumpOffsetOperand(1);
if (blocks->find(branch_target_pos) == blocks->end()) {
bb_begin_positions.push_back(branch_target_pos);
(*blocks)[branch_target_pos] = nullptr;
}
break;
}
}
}
}
void LLVMEngine::CompiledModuleBuilder::DefineFunction(const FunctionInfo &func_info, llvm::IRBuilder<> *ir_builder) {
llvm::LLVMContext &ctx = ir_builder->getContext();
llvm::Function *func = llvm_module_->getFunction(func_info.GetName());
llvm::BasicBlock *first_bb = llvm::BasicBlock::Create(ctx, "BB0", func);
llvm::BasicBlock *entry_bb = llvm::BasicBlock::Create(ctx, "EntryBB", func, first_bb);
// First, construct a simple CFG for the function. The CFG contains entries for the start of every
// basic block in the function, and the bytecode position of the first instruction in the block.
// The CFG is ordered by bytecode position in ascending order.
std::map<std::size_t, llvm::BasicBlock *> blocks = {{0, first_bb}};
BuildSimpleCFG(func_info, &blocks);
{
uint32_t block_num = 1;
for (auto &[_, block] : blocks) {
(void)_;
if (block == nullptr) {
block = llvm::BasicBlock::Create(ctx, "BB" + std::to_string(block_num++), func);
}
}
}
#ifndef NDEBUG
EXECUTION_LOG_TRACE("Found blocks:");
for (auto &[pos, block] : blocks) {
(void)pos;
(void)block;
EXECUTION_LOG_TRACE(" Block {} @ {:x}", block->getName().str(), pos);
}
#endif
// We can define the function now. LLVM IR generation happens by iterating over the function's
// bytecode simultaneously with the ordered list of basic block start positions ('blocks'). Each
// TPL bytecode is converted to a function call into a pre-compiled TPL bytecode handler. However,
// many of these calls will get inlined away during optimization. If the current bytecode position
// matches the position of a new basic block, a branch instruction is generated automatically
// (either conditional or not depending on context) into the new block, and the IR builder
// position shifts to the new block.
ir_builder->SetInsertPoint(entry_bb);
FunctionLocalsMap locals_map(func_info, func, type_map_.get(), ir_builder);
// Jump to the first block, after all local allocations have been made.
ir_builder->CreateBr(first_bb);
ir_builder->SetInsertPoint(first_bb);
for (auto iter = tpl_module_.GetBytecodeForFunction(func_info); !iter.Done(); iter.Advance()) {
Bytecode bytecode = iter.CurrentBytecode();
// Collect arguments
llvm::SmallVector<llvm::Value *, 8> args;
for (uint32_t i = 0; i < Bytecodes::NumOperands(bytecode); i++) {
switch (Bytecodes::GetNthOperandType(bytecode, i)) {
case OperandType::None: {
break;
}
case OperandType::Imm1: {
args.push_back(llvm::ConstantInt::get(type_map_->Int8Type(), iter.GetImmediateIntegerOperand(i), true));
break;
}
case OperandType::Imm2: {
args.push_back(llvm::ConstantInt::get(type_map_->Int16Type(), iter.GetImmediateIntegerOperand(i), true));
break;
}
case OperandType::Imm4: {
args.push_back(llvm::ConstantInt::get(type_map_->Int32Type(), iter.GetImmediateIntegerOperand(i), true));
break;
}
case OperandType::Imm8: {
args.push_back(llvm::ConstantInt::get(type_map_->Int64Type(), iter.GetImmediateIntegerOperand(i), true));
break;
}
case OperandType::Imm4F: {
args.push_back(llvm::ConstantFP::get(type_map_->Float32Type(), iter.GetImmediateFloatOperand(i)));
break;
}
case OperandType::Imm8F: {
args.push_back(llvm::ConstantFP::get(type_map_->Float64Type(), iter.GetImmediateFloatOperand(i)));
break;
}
case OperandType::UImm2: {
args.push_back(
llvm::ConstantInt::get(type_map_->UInt16Type(), iter.GetUnsignedImmediateIntegerOperand(i), false));
break;
}
case OperandType::UImm4: {
args.push_back(
llvm::ConstantInt::get(type_map_->UInt32Type(), iter.GetUnsignedImmediateIntegerOperand(i), false));
break;
}
case OperandType::FunctionId: {
const FunctionInfo *target_func_info = tpl_module_.GetFuncInfoById(iter.GetFunctionIdOperand(i));
llvm::Function *target_func = llvm_module_->getFunction(target_func_info->GetName());
NOISEPAGE_ASSERT(target_func != nullptr, "Function doesn't exist in LLVM module");
args.push_back(target_func);
break;
}
case OperandType::JumpOffset: {
// These are handled specially below
break;
}
case OperandType::Local: {
LocalVar local = iter.GetLocalOperand(i);
args.push_back(locals_map.GetArgumentById(local));
break;
}
case OperandType::StaticLocal: {
const uint32_t offset = iter.GetStaticLocalOperand(i).GetOffset();
const auto static_locals_iter = static_locals_.find(offset);
NOISEPAGE_ASSERT(static_locals_iter != static_locals_.end(), "Static local at offset does not exist");
args.push_back(static_locals_iter->second);
break;
}
case OperandType::LocalCount: {
std::vector<LocalVar> locals;
iter.GetLocalCountOperand(i, &locals);
for (const auto local : locals) {
args.push_back(locals_map.GetArgumentById(local));
}
break;
}
}
}
const auto issue_call = [&ir_builder](auto *func, auto &args) {
auto arg_iter = func->arg_begin();
for (uint32_t i = 0; i < args.size(); ++i, ++arg_iter) {
llvm::Type *expected_type = arg_iter->getType();
llvm::Type *provided_type = args[i]->getType();
if (provided_type == expected_type) {
continue;
}
if (expected_type->isIntegerTy()) {
if (provided_type->isPointerTy()) {
args[i] = ir_builder->CreatePtrToInt(args[i], expected_type);
} else {
args[i] = ir_builder->CreateIntCast(args[i], expected_type, true);
}
} else if (expected_type->isPointerTy()) {
NOISEPAGE_ASSERT(provided_type->isPointerTy(), "Mismatched types");
args[i] = ir_builder->CreateBitCast(args[i], expected_type);
}
}
return ir_builder->CreateCall(func, args);
};
// Handle bytecode
switch (bytecode) {
case Bytecode::Call: {
// For internal calls, the callee's function ID will be the first operand. We pull it out
// and lookup the function in the module and remove it from the arguments vector.
//
// If the function has a direct return, the second operand will be the value to store the
// result of the invocation into. We pop it off the argument vector, issue the call, then
// store the result. The remaining elements are legitimate arguments to the function.
const FunctionId callee_id = iter.GetFunctionIdOperand(0);
const auto *callee_func_info = tpl_module_.GetFuncInfoById(callee_id);
llvm::Function *callee = llvm_module_->getFunction(callee_func_info->GetName());
args.erase(args.begin());
if (FunctionHasDirectReturn(callee_func_info->GetFuncType())) {
llvm::Value *dest = args[0];
args.erase(args.begin());
llvm::Value *ret = issue_call(callee, args);
ir_builder->CreateStore(ret, dest);
} else {
issue_call(callee, args);
}
break;
}
case Bytecode::Jump: {
// Unconditional jumps work as follows: we read the relative target bytecode position from
// the iterator, calculate the absolute bytecode position, and create an unconditional
// branch to the basic block that starts at the given bytecode position, using the
// information in the CFG.
std::size_t branch_target_bb_pos =
iter.GetPosition() + Bytecodes::GetNthOperandOffset(bytecode, 0) + iter.GetJumpOffsetOperand(0);
NOISEPAGE_ASSERT(blocks[branch_target_bb_pos] != nullptr, "Branch target does not point to valid basic block");
ir_builder->CreateBr(blocks[branch_target_bb_pos]);
break;
}
case Bytecode::JumpIfFalse:
case Bytecode::JumpIfTrue: {
// Conditional jumps work almost exactly as unconditional jump except a second fallthrough
// position is calculated.
std::size_t fallthrough_bb_pos = iter.GetPosition() + iter.CurrentBytecodeSize();
std::size_t branch_target_bb_pos =
iter.GetPosition() + Bytecodes::GetNthOperandOffset(bytecode, 1) + iter.GetJumpOffsetOperand(1);
NOISEPAGE_ASSERT(blocks[fallthrough_bb_pos] != nullptr,
"Branch fallthrough does not point to valid basic block");
NOISEPAGE_ASSERT(blocks[branch_target_bb_pos] != nullptr, "Branch target does not point to valid basic block");
auto *check = llvm::ConstantInt::get(type_map_->Int8Type(), 1, false);
llvm::Value *cond = ir_builder->CreateICmpEQ(args[0], check);
if (bytecode == Bytecode::JumpIfTrue) {
ir_builder->CreateCondBr(cond, blocks[branch_target_bb_pos], blocks[fallthrough_bb_pos]);
} else {
ir_builder->CreateCondBr(cond, blocks[fallthrough_bb_pos], blocks[branch_target_bb_pos]);
}
break;
}
case Bytecode::Lea: {
NOISEPAGE_ASSERT(args[1]->getType()->isPointerTy(), "First argument must be a pointer");
const llvm::DataLayout &dl = llvm_module_->getDataLayout();
llvm::Type *pointee_type = args[1]->getType()->getPointerElementType();
int64_t offset = llvm::cast<llvm::ConstantInt>(args[2])->getSExtValue();
if (auto struct_type = llvm::dyn_cast<llvm::StructType>(pointee_type)) {
const uint32_t elem_index = dl.getStructLayout(struct_type)->getElementContainingOffset(offset);
llvm::Value *addr = ir_builder->CreateStructGEP(args[1], elem_index);
ir_builder->CreateStore(addr, args[0]);
} else {
llvm::SmallVector<llvm::Value *, 2> gep_args;
uint32_t elem_size = dl.getTypeSizeInBits(pointee_type);
if (llvm::isa<llvm::ArrayType>(pointee_type)) {
llvm::Type *const arr_type = pointee_type->getArrayElementType();
elem_size = dl.getTypeSizeInBits(arr_type) / common::Constants::K_BITS_PER_BYTE;
gep_args.push_back(llvm::ConstantInt::get(type_map_->Int64Type(), 0));
}
gep_args.push_back(llvm::ConstantInt::get(type_map_->Int64Type(), offset / elem_size));
llvm::Value *addr = ir_builder->CreateInBoundsGEP(args[1], gep_args);
ir_builder->CreateStore(addr, args[0]);
}
break;
}
case Bytecode::LeaScaled: {
NOISEPAGE_ASSERT(args[1]->getType()->isPointerTy(), "First argument must be a pointer");
// For any LeaScaled, the scale is handled by LLVM's GEP. If it's an
// array of structures, we need to handle the final offset/displacement
// into the struct as the last GEP index.
llvm::Type *pointee_type = args[1]->getType()->getPointerElementType();
if (auto struct_type = llvm::dyn_cast<llvm::StructType>(pointee_type)) {
llvm::Value *addr = ir_builder->CreateInBoundsGEP(args[1], {args[2]});
const uint64_t elem_offset = llvm::cast<llvm::ConstantInt>(args[4])->getZExtValue();
if (elem_offset != 0) {
const uint32_t elem_index =
llvm_module_->getDataLayout().getStructLayout(struct_type)->getElementContainingOffset(elem_offset);
addr = ir_builder->CreateStructGEP(addr, elem_index);
}
ir_builder->CreateStore(addr, args[0]);
} else {
NOISEPAGE_ASSERT(llvm::cast<llvm::ConstantInt>(args[4])->getSExtValue() == 0,
"LeaScaled on arrays cannot have a displacement");
llvm::SmallVector<llvm::Value *, 2> gep_args;
if (llvm::isa<llvm::ArrayType>(pointee_type)) {
gep_args.push_back(llvm::ConstantInt::get(type_map_->Int64Type(), 0));
}
gep_args.push_back(args[2]);
llvm::Value *addr = ir_builder->CreateInBoundsGEP(args[1], gep_args);
ir_builder->CreateStore(addr, args[0]);
}
break;
}
case Bytecode::Return: {
if (FunctionHasDirectReturn(func_info.GetFuncType())) {
llvm::Value *ret_val = locals_map.GetArgumentById(func_info.GetReturnValueLocal());
ir_builder->CreateRet(ir_builder->CreateLoad(ret_val));
} else {
ir_builder->CreateRetVoid();
}
break;
}
default: {
// In the default case, each bytecode makes a function call into its bytecode handler
llvm::Function *handler = LookupBytecodeHandler(bytecode);
issue_call(handler, args);
break;
}
}
// If the next bytecode marks the start of a new basic block (based on the CFG), we need to
// switch insertion points to it before continuing IR generation. But, it could be the case that
// we're starting a new block
auto next_bytecode_pos = iter.GetPosition() + iter.CurrentBytecodeSize();
if (auto blocks_iter = blocks.find(next_bytecode_pos); blocks_iter != blocks.end()) {
if (!Bytecodes::IsTerminal(bytecode)) {
ir_builder->CreateBr(blocks_iter->second);
}
ir_builder->SetInsertPoint(blocks_iter->second);
}
}
}
void LLVMEngine::CompiledModuleBuilder::DefineFunctions() {
llvm::IRBuilder<> ir_builder(*context_);
for (const auto &func_info : tpl_module_.GetFunctionsInfo()) {
DefineFunction(func_info, &ir_builder);
}
}
void LLVMEngine::CompiledModuleBuilder::Verify() {
std::string result;
llvm::raw_string_ostream ostream(result);
if (bool has_error = llvm::verifyModule(*llvm_module_, &ostream); has_error) {
// TODO(pmenon): Do something more here ...
EXECUTION_LOG_ERROR("ERROR IN MODULE:\n{}", ostream.str());
}
}
void LLVMEngine::CompiledModuleBuilder::Simplify() {
// When this function is called, the generated IR consists of many function
// calls to cross-compiled bytecode handler functions. We now inline those
// function calls directly into the body of the functions we've generated
// by running the 'AlwaysInliner' pass.
llvm::legacy::PassManager pass_manager;
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
pass_manager.add(llvm::createGlobalDCEPass());
pass_manager.run(*llvm_module_);
}
void LLVMEngine::CompiledModuleBuilder::Optimize() {
llvm::legacy::FunctionPassManager function_passes(llvm_module_.get());
// Add the appropriate TargetTransformInfo.
function_passes.add(llvm::createTargetTransformInfoWrapperPass(target_machine_->getTargetIRAnalysis()));
// Build up optimization pipeline.
llvm::PassManagerBuilder pm_builder;
uint32_t opt_level = 3;
uint32_t size_opt_level = 0;
bool disable_inline_hot_call_site = false;
pm_builder.OptLevel = opt_level;
pm_builder.Inliner = llvm::createFunctionInliningPass(opt_level, size_opt_level, disable_inline_hot_call_site);
pm_builder.populateFunctionPassManager(function_passes);
// Add custom passes. Hand-selected based on empirical evaluation.
function_passes.add(llvm::createInstructionCombiningPass());
function_passes.add(llvm::createReassociatePass());
function_passes.add(llvm::createGVNPass());
function_passes.add(llvm::createCFGSimplificationPass());
function_passes.add(llvm::createAggressiveDCEPass());
function_passes.add(llvm::createCFGSimplificationPass());
// Run optimization passes on all functions.
function_passes.doInitialization();
for (llvm::Function &func : *llvm_module_) {
function_passes.run(func);
}
function_passes.doFinalization();
}
std::unique_ptr<LLVMEngine::CompiledModule> LLVMEngine::CompiledModuleBuilder::Finalize() {
std::unique_ptr<llvm::MemoryBuffer> obj = EmitObject();
if (options_.ShouldPersistObjectFile()) {
PersistObjectToFile(*obj);
}
return std::make_unique<CompiledModule>(std::move(obj));
}
std::unique_ptr<llvm::MemoryBuffer> LLVMEngine::CompiledModuleBuilder::EmitObject() {
// Buffer holding the machine code. The returned buffer will take ownership of
// this one when we return
llvm::SmallString<4096> obj_buffer;
// The pass manager we insert the EmitMC pass into
llvm::legacy::PassManager pass_manager;