-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
codegen_llvm.cc
2118 lines (1911 loc) · 80.2 KB
/
codegen_llvm.cc
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 Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file codegen_llvm.cc
*/
#ifdef TVM_LLVM_VERSION
// Part of the code are adapted from Halide's CodeGen_LLVM
#include "codegen_llvm.h"
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/ADT/StringRef.h>
#if LLVM_VERSION_MAJOR >= 17
#include <llvm/TargetParser/Triple.h>
#else
#include <llvm/ADT/Triple.h>
#endif
#include <llvm/Analysis/TargetTransformInfo.h>
#if TVM_LLVM_VERSION >= 50
#include <llvm/BinaryFormat/Dwarf.h>
#else
#include <llvm/Support/Dwarf.h>
#endif
#if TVM_LLVM_VERSION >= 60
#include <llvm/CodeGen/TargetSubtargetInfo.h>
#else
#include <llvm/Target/TargetSubtargetInfo.h>
#endif
#include <llvm/IR/Argument.h>
#include <llvm/IR/Attributes.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/DebugInfoMetadata.h>
#include <llvm/IR/DerivedTypes.h>
#if TVM_LLVM_VERSION >= 150
#include <llvm/IR/FMF.h>
#else
#include <llvm/IR/Operator.h>
#endif
#include <llvm/IR/Function.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/MDBuilder.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Linker/Linker.h>
#include <llvm/Pass.h>
#if TVM_LLVM_VERSION >= 160
#include <llvm/IR/Verifier.h> // For VerifierPass
#include <llvm/Passes/PassBuilder.h>
#include <llvm/Passes/StandardInstrumentations.h>
#include <llvm/TargetParser/Host.h>
#else
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Support/Host.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#endif
#if TVM_LLVM_VERSION >= 100
#include <llvm/Support/Alignment.h>
#include <llvm/Support/TypeSize.h>
#endif
#include <llvm/Support/CodeGen.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/Utils/ModuleUtils.h>
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/crt/error_codes.h>
#include <tvm/runtime/device_api.h>
#include <tvm/tir/op.h>
#include <algorithm>
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "../../arith/pattern_match.h"
#include "../build_common.h"
#include "../func_registry_generator.h"
#include "codegen_params.h"
#include "llvm_instance.h"
namespace tvm {
namespace codegen {
// CodeGenLLVM has members of type std::unique_ptr<T>. These members will be
// instantiated in the constructor, which will requre that the type T is
// complete at that point. Put the constructor (and destructor) here, since
// all types should be complete here.
CodeGenLLVM::CodeGenLLVM() = default;
CodeGenLLVM::~CodeGenLLVM() = default;
CodeGenLLVM::DebugInfo::~DebugInfo() = default;
std::unique_ptr<CodeGenLLVM> CodeGenLLVM::Create(LLVMTarget* llvm_target) {
std::string target = llvm_target->GetOrCreateTargetMachine()->getTarget().getName();
std::string factory_template = "tvm.codegen.llvm.target_";
void* handle = nullptr;
if (const PackedFunc* f = runtime::Registry::Get(factory_template + target)) {
handle = (*f)();
} else if (const PackedFunc* f = runtime::Registry::Get(factory_template + "cpu")) {
handle = (*f)();
} else {
LOG(FATAL) << "no factory function for codegen for target " << target;
}
if (handle) {
return std::unique_ptr<CodeGenLLVM>(static_cast<CodeGenLLVM*>(handle));
} else {
LOG(FATAL) << "unable to create codegen for target " << target;
}
}
void CodeGenLLVM::Init(const std::string& module_name, LLVMTarget* llvm_target,
Optional<String> system_lib_prefix, bool dynamic_lookup,
bool target_c_runtime) {
llvm_target_ = llvm_target;
llvm::LLVMContext* ctx = llvm_target_->GetContext();
builder_.reset(new IRBuilder(*ctx));
module_.reset(new llvm::Module(module_name, *ctx));
md_builder_.reset(new llvm::MDBuilder(*ctx));
// types
t_void_ = llvm::Type::getVoidTy(*ctx);
t_void_p_ = llvm::Type::getInt8Ty(*ctx)->getPointerTo(GetGlobalAddressSpace());
t_int_ = llvm::Type::getInt32Ty(*ctx);
t_char_ = llvm::Type::getInt8Ty(*ctx);
t_int8_ = llvm::Type::getInt8Ty(*ctx);
t_int16_ = llvm::Type::getInt16Ty(*ctx);
t_int32_ = llvm::Type::getInt32Ty(*ctx);
t_int64_ = llvm::Type::getInt64Ty(*ctx);
t_float64_ = llvm::Type::getDoubleTy(*ctx);
// meta data
md_very_likely_branch_ = md_builder_->createBranchWeights(1 << 20, 1);
md_tbaa_root_ = md_builder_->createTBAARoot("tvm-tbaa");
md_tbaa_alias_set_ = md_builder_->createTBAANode("tvm-alias", md_tbaa_root_);
InitTarget();
}
void CodeGenLLVM::SetFastMathFlags(llvm::FastMathFlags fmf) { builder_->setFastMathFlags(fmf); }
void CodeGenLLVM::InitTarget() {
llvm::TargetMachine* tm = llvm_target_->GetOrCreateTargetMachine();
module_->setTargetTriple(tm->getTargetTriple().str());
module_->setDataLayout(tm->createDataLayout());
data_layout_.reset(new llvm::DataLayout(module_.get()));
if (native_vector_bits_ == 0) {
const auto& arch = tm->getTargetTriple().getArch();
if (arch == llvm::Triple::x86_64) {
// for avx512
native_vector_bits_ = 512;
} else if (arch == llvm::Triple::x86) {
native_vector_bits_ = 256;
} else if (arch == llvm::Triple::arm || arch == llvm::Triple::aarch64) {
native_vector_bits_ = 128;
} else {
native_vector_bits_ = 128;
std::string arch_name = std::string(tm->getTargetTriple().getArchName());
LOG(WARNING) << "Set native vector bits to be 128 for " << arch_name;
}
}
#if TVM_LLVM_VERSION >= 60
bool use_float16_abi = false;
#if TVM_LLVM_VERSION >= 150
// For conversions between _Float16 and float, LLVM uses runtime functions
// __extendhfsf2 and __truncsfhf2. On X86 up until version 14, LLVM used
// "uint16_t" for representing _Float16. Starting with LLVM 15, half-precision
// values can be passed in XMM registers (i.e. as floating-point). This happens
// when the compilation target has SSE2 enabled (either directly, or by enabling
// a feature that implies SSE2).
// Because the names of the conversion functions remain unchanged, it is impossible
// for TVM to provide them in the runtime, and have them work in both cases.
// To alleviate this issue, emit these functions directly into the target module
// after detecting whether or not to use floating-point ABI. To allow the linker
// to remove potential duplicates (or if they are unused), they are weak and
// reside in a separate section (ELF).
llvm::Triple::ArchType arch_type = tm->getTargetTriple().getArch();
if (arch_type == llvm::Triple::x86 || arch_type == llvm::Triple::x86_64) {
// Detect if SSE2 is enabled. This determines whether float16 ABI is used.
std::stringstream os;
const char fname[] = "test_sse2";
os << "target triple = \"" << llvm_target_->GetTargetTriple() << "\"\n"
<< "define void @" << fname << "() #0 { ret void } attributes #0 = { \"target-cpu\"=\""
<< llvm_target_->GetCPU() << "\" ";
if (auto&& fs = llvm_target_->GetTargetFeatureString(); !fs.empty()) {
os << "\"target-features\"=\"" << fs << "\" ";
}
os << "}\n";
auto mod = llvm_target_->GetInstance().ParseIR(os.str());
auto* test_sse2 = mod->getFunction(fname);
ICHECK(test_sse2 != nullptr) << "Module creation error";
use_float16_abi = tm->getSubtargetImpl(*test_sse2)->checkFeatures("+sse2");
}
#endif // TVM_LLVM_VERSION >= 150
// Call this function only with LLVM >= 6.0. The code it emits uses "dso_local"
// which was introduced in LLVM 6.
EmitFloat16ConversionBuiltins(use_float16_abi);
#endif // TVM_LLVM_VERSION >= 60
}
llvm::Function* CodeGenLLVM::DeclareFunction(const GlobalVar& gvar, const PrimFunc& f) {
return this->DeclareFunctionInternal(gvar, f);
}
void CodeGenLLVM::AddFunction(const GlobalVar& gvar, const PrimFunc& f) {
this->AddFunctionInternal(gvar, f);
}
void CodeGenLLVM::InitFuncState() {
var_map_.clear();
alias_var_set_.clear();
alloc_storage_info_.clear();
volatile_buf_.clear();
analyzer_.reset(new arith::Analyzer());
}
std::tuple<std::string, llvm::Function::LinkageTypes> CodeGenLLVM::GetLinkage(
const GlobalVar& gvar, const PrimFunc& func) {
if (auto global_symbol = func->GetAttr<String>(tvm::attr::kGlobalSymbol)) {
return {global_symbol.value(), llvm::Function::ExternalLinkage};
}
std::string symbol_name = [&]() {
std::stringstream ss;
ss << "_internal_";
ss << gvar->name_hint;
return ss.str();
}();
return {symbol_name, llvm::Function::PrivateLinkage};
}
llvm::Function* CodeGenLLVM::DeclareFunctionInternal(const GlobalVar& gvar, const PrimFunc& func) {
if (auto it = functions_.find(gvar.get()); it != functions_.end()) {
return it->second;
}
ICHECK_EQ(func->buffer_map.size(), 0U)
<< "Cannot codegen function with buffer_map, please lower them first";
std::vector<llvm::Type*> param_types;
is_restricted_ = func->HasNonzeroAttr(tir::attr::kNoAlias);
for (Var param : func->params) {
param_types.push_back(GetLLVMType(param));
if (!is_restricted_ && param.dtype().is_handle()) {
alias_var_set_.insert(param.get());
}
}
llvm::FunctionType* ftype =
llvm::FunctionType::get(GetLLVMType(func->ret_type), param_types, false);
auto [symbol_name, linkage_type] = GetLinkage(gvar, func);
auto function = module_->getFunction(MakeStringRef(symbol_name));
if (function == nullptr) {
function =
llvm::Function::Create(ftype, linkage_type, MakeStringRef(symbol_name), module_.get());
}
function->setCallingConv(llvm::CallingConv::C);
function->setDLLStorageClass(llvm::GlobalValue::DLLStorageClassTypes::DLLExportStorageClass);
SetTargetAttributes(function);
functions_[gvar.get()] = function;
return function;
}
void CodeGenLLVM::AddFunctionInternal(const GlobalVar& gvar, const PrimFunc& f) {
this->InitFuncState();
function_ = DeclareFunctionInternal(gvar, f);
// set var map and align information
auto arg_it = function_->arg_begin();
for (size_t i = 0; i < f->params.size(); ++i, ++arg_it) {
llvm::Argument* v = &(*arg_it);
const Var& var = f->params[i];
var_map_[var.get()] = v;
v->setName(std::string(var->name_hint));
if (is_restricted_) {
if (var.dtype().is_handle() && !alias_var_set_.count(var.get())) {
// set non alias.
#if TVM_LLVM_VERSION >= 50
function_->addParamAttr(i, llvm::Attribute::NoAlias);
#else
function_->setDoesNotAlias(i + 1);
#endif
}
}
}
llvm::LLVMContext* ctx = llvm_target_->GetContext();
llvm::BasicBlock* entry = llvm::BasicBlock::Create(*ctx, "entry", function_);
builder_->SetInsertPoint(entry);
this->VisitStmt(f->body);
// Add alignment attribute if needed.
#if TVM_LLVM_VERSION >= 50
for (size_t i = 0; i < f->params.size(); ++i) {
const Var& var = f->params[i];
auto f = alloc_storage_info_.find(var.get());
if (f != alloc_storage_info_.end()) {
unsigned align = f->second.alignment;
if (align > 1) {
auto attr = llvm::Attribute::get(*ctx, llvm::Attribute::Alignment, align);
function_->addParamAttr(i, attr);
}
}
}
#endif
EmitDebugLocation(f->span);
if (IsVoidType(f->ret_type)) {
// All other return types are handled when encountering
// builtin::ret().
builder_->CreateRetVoid();
} else {
builder_->CreateRet(ConstInt32(0));
}
}
void CodeGenLLVM::Verify() const {
std::string verify_errors_storage;
llvm::raw_string_ostream verify_errors(verify_errors_storage);
LOG_IF(FATAL, llvm::verifyModule(*module_, &verify_errors))
<< "LLVM module verification failed with the following errors: \n"
<< verify_errors.str();
}
std::unique_ptr<llvm::Module> CodeGenLLVM::Finish() {
this->AddStartupFunction();
for (size_t i = 0; i < link_modules_.size(); ++i) {
ICHECK(!llvm::Linker::linkModules(*module_, std::move(link_modules_[i])))
<< "Failed to link modules";
}
link_modules_.clear();
this->Verify();
this->Optimize();
this->Verify();
return std::move(module_);
}
void CodeGenLLVM::HandleImport(const std::string& code) {
llvm::StringRef code_str(code);
std::unique_ptr<llvm::Module> mlib;
if (code_str.endswith(".ll") || code_str.endswith(".bc")) {
mlib = llvm_target_->GetInstance().LoadIR(code);
} else {
mlib = llvm_target_->GetInstance().ParseIR(code);
}
mlib->setTargetTriple(llvm_target_->GetTargetTriple());
mlib->setDataLayout(llvm_target_->GetOrCreateTargetMachine()->createDataLayout());
// mark all the functions as force inline
for (llvm::Function& f : mlib->functions()) {
f.removeFnAttr(llvm::Attribute::OptimizeNone);
f.removeFnAttr(llvm::Attribute::NoInline);
f.addFnAttr(llvm::Attribute::AlwaysInline);
f.setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
}
// add to linker libraries.
this->AddLinkModule(std::move(mlib));
}
void CodeGenLLVM::AddLinkModule(std::unique_ptr<llvm::Module>&& mod) {
link_modules_.emplace_back(std::move(mod));
}
void CodeGenLLVM::AddMainFunction(const std::string& entry_func_name) {
LOG(FATAL) << "not implemented";
}
llvm::Value* CodeGenLLVM::GetThreadIndex(const IterVar& iv) { LOG(FATAL) << "not implemented"; }
llvm::Value* CodeGenLLVM::CreateStorageSync(const CallNode* op) { LOG(FATAL) << "not implemented"; }
#if TVM_LLVM_VERSION >= 160
// Use new pass manager
void CodeGenLLVM::Optimize() {
llvm::TargetMachine* tm = llvm_target_->GetOrCreateTargetMachine();
bool debug_logging = false;
bool verify_each = false;
llvm::PipelineTuningOptions pto = llvm::PipelineTuningOptions();
llvm::PassInstrumentationCallbacks pic;
llvm::PassBuilder builder(tm, pto, std::nullopt, &pic);
llvm::LoopAnalysisManager lam;
llvm::FunctionAnalysisManager fam;
llvm::CGSCCAnalysisManager cgam;
llvm::ModuleAnalysisManager mam;
builder.registerLoopAnalyses(lam);
builder.registerFunctionAnalyses(fam);
builder.registerCGSCCAnalyses(cgam);
builder.registerModuleAnalyses(mam);
builder.crossRegisterProxies(lam, fam, cgam, mam);
// Construct the default pass pipeline depending on the opt level.
std::string pipeline;
switch (llvm_target_->GetOptLevel()) {
case llvm::CodeGenOpt::Level::None:
pipeline = "default<O0>";
break;
case llvm::CodeGenOpt::Level::Less:
pipeline = "default<O1>";
break;
case llvm::CodeGenOpt::Level::Default:
pipeline = "default<O2>";
break;
default:
// CodeGenOpt::Level::Aggressive
pipeline = "default<O3>";
break;
}
llvm::StandardInstrumentations si(*llvm_target_->GetContext(), debug_logging, verify_each);
#if LLVM_VERSION_MAJOR >= 17
si.registerCallbacks(pic, &mam);
#else
si.registerCallbacks(pic, &fam);
#endif
llvm::ModulePassManager mpass;
if (verify_each) {
mpass.addPass(llvm::VerifierPass());
}
if (auto err = builder.parsePassPipeline(mpass, pipeline)) {
LOG(FATAL) << "error parsing pass pipeline '" << pipeline
<< "':" << llvm::toString(std::move(err)) << '\n';
}
mpass.run(*module_, mam);
}
#else // TVM_LLVM_VERSION
class FPassManager : public llvm::legacy::FunctionPassManager {
public:
explicit FPassManager(llvm::Module* m) : llvm::legacy::FunctionPassManager(m) {}
// override add to allow messaging
void add(llvm::Pass* p) final { llvm::legacy::FunctionPassManager::add(p); }
};
class MPassManager : public llvm::legacy::PassManager {
public:
// override add to allow messaging
void add(llvm::Pass* p) final { llvm::legacy::PassManager::add(p); }
};
void CodeGenLLVM::InitPassManagerBuilder(llvm::PassManagerBuilder* builder) {}
void CodeGenLLVM::Optimize() {
// pass manager
FPassManager fpass(module_.get());
MPassManager mpass;
llvm::TargetMachine* tm = llvm_target_->GetOrCreateTargetMachine();
mpass.add(llvm::createTargetTransformInfoWrapperPass(tm->getTargetIRAnalysis()));
fpass.add(llvm::createTargetTransformInfoWrapperPass(tm->getTargetIRAnalysis()));
// place optimization pass
llvm::PassManagerBuilder builder;
// Use the same opt-level as specified in TargetMachine for running passes
llvm::CodeGenOpt::Level opt_level = llvm_target_->GetOptLevel();
switch (opt_level) {
case llvm::CodeGenOpt::Level::None:
builder.OptLevel = 0;
break;
case llvm::CodeGenOpt::Level::Less:
builder.OptLevel = 1;
break;
case llvm::CodeGenOpt::Level::Default:
builder.OptLevel = 2;
break;
default:
// CodeGenOpt::Level::Aggressive
builder.OptLevel = 3;
}
#if TVM_LLVM_VERSION >= 50
builder.Inliner = llvm::createFunctionInliningPass(builder.OptLevel, 0, false);
#else
builder.Inliner = llvm::createFunctionInliningPass(builder.OptLevel, 0);
#endif
builder.LoopVectorize = true;
builder.SLPVectorize = true;
this->InitPassManagerBuilder(&builder);
#if TVM_LLVM_VERSION >= 50
tm->adjustPassManager(builder);
#endif
builder.populateFunctionPassManager(fpass);
builder.populateModulePassManager(mpass);
fpass.doInitialization();
for (auto it = module_->begin(); it != module_->end(); ++it) {
fpass.run(*it);
}
fpass.doFinalization();
mpass.run(*module_);
}
#endif // TVM_LLVM_VERSION
int CodeGenLLVM::NativeVectorBits(const runtime::StorageScope& storage_scope) const {
return native_vector_bits_;
}
unsigned CodeGenLLVM::GetGlobalAddressSpace() const { return 0; }
llvm::Type* CodeGenLLVM::DTypeToLLVMType(const DataType& dtype) const {
if (dtype.is_handle()) {
ICHECK_EQ(dtype.lanes(), 1);
return t_void_p_;
}
if (dtype.is_void()) {
return t_void_;
}
llvm::Type* etype = nullptr;
llvm::LLVMContext* ctx = llvm_target_->GetContext();
if (dtype.is_int() || dtype.is_uint()) {
etype = llvm::Type::getIntNTy(*ctx, dtype.bits());
} else if (dtype.is_float()) {
switch (dtype.bits()) {
case 16:
etype = llvm::Type::getHalfTy(*ctx);
break;
case 32:
etype = llvm::Type::getFloatTy(*ctx);
break;
case 64:
etype = llvm::Type::getDoubleTy(*ctx);
break;
default:
LOG(FATAL) << "do not support " << dtype;
}
}
if (dtype.lanes() != 1) {
#if TVM_LLVM_VERSION >= 110
return llvm::FixedVectorType::get(etype, dtype.lanes());
#else
return llvm::VectorType::get(etype, dtype.lanes());
#endif
} else {
return etype;
}
} // namespace codegen
llvm::Type* CodeGenLLVM::GetLLVMType(const Type& type) const {
if (auto* ptr = type.as<PrimTypeNode>()) {
return DTypeToLLVMType(ptr->dtype);
} else if (auto* ptr = type.as<PointerTypeNode>()) {
// LLVM IR doesn't allow void*, nor do we require custom datatypes
// to have LLVM equivalents, so we need to recognize these
// patterns explicitly.
if (auto* primtype = ptr->element_type.as<PrimTypeNode>()) {
if (primtype->dtype.is_void() || primtype->dtype.code() >= DataType::kCustomBegin) {
return t_void_p_;
}
}
// TODO(tvm-team) consider put storage scope into the pointer type.
return GetLLVMType(ptr->element_type)->getPointerTo(GetGlobalAddressSpace());
} else if (IsVoidType(type)) {
return t_void_;
} else {
LOG(FATAL) << "Type " << type << " does not have a corresponding LLVM Type";
}
}
llvm::Type* CodeGenLLVM::GetLLVMType(const PrimExpr& expr) const {
return GetLLVMType(GetType(expr));
}
// Add tbaa alias information for load
//
// use a binary tree typed system to declare information
// and allow alias to be distinguished across nodes.
//
// This trick comes from Halide's CodeGen_LLVM
//
void CodeGenLLVM::AddAliasInfo(llvm::Instruction* inst, const VarNode* buffer_var, PrimExpr index,
DataType access_dtype) {
if (alias_var_set_.count(buffer_var) != 0) {
// Mark all possibly aliased pointer as same type.
llvm::MDNode* meta = md_tbaa_alias_set_;
inst->setMetadata("tbaa", md_builder_->createTBAAStructTagNode(meta, meta, 0));
return;
}
int64_t base = 0, width = 0;
arith::PVar<IntImm> pbase, pstride;
arith::PVar<int> planes;
// create meta-data for alias analysis
// Use a group of binary tree ranges of memory banks.
int64_t xwith = 0;
if (arith::ramp(pbase, pstride, planes).Match(index)) {
base = pbase.Eval()->value;
xwith = planes.Eval() * pstride.Eval()->value;
} else if (auto* ptr = index.as<tir::IntImmNode>()) {
base = ptr->value;
xwith = 1;
}
// adjust address index unit to byte
const int64_t unit_bit_width = 8;
const int64_t access_elem_bits = access_dtype.bits() * access_dtype.lanes();
base = base * access_elem_bits / unit_bit_width;
xwith = (xwith * access_elem_bits + unit_bit_width - 1) / unit_bit_width;
if (xwith > 0) {
width = 1;
while (width < xwith) {
width *= 2;
}
while (base % width) {
base -= base % width;
width *= 2;
}
}
llvm::MDNode* meta = md_tbaa_root_;
std::ostringstream buffer_addr;
buffer_addr << buffer_var;
meta = md_builder_->createTBAAScalarTypeNode(buffer_addr.str(), meta);
// create a tree-shape access structure.
if (width != 0) {
for (int64_t w = 1024; w >= width; w /= 2) {
int64_t b = (base / w) * w;
std::stringstream os;
os << buffer_var << ".w" << w << ".b" << b;
meta = md_builder_->createTBAAScalarTypeNode(os.str(), meta);
}
}
inst->setMetadata("tbaa", md_builder_->createTBAAStructTagNode(meta, meta, 0));
}
void CodeGenLLVM::GetAlignment(DataType t, const VarNode* buf_var, const PrimExpr& index,
int* p_alignment, int* p_native_bits) {
int max_align_bits = t.bits();
auto it = alloc_storage_info_.find(buf_var);
if (it != alloc_storage_info_.end()) {
const StorageInfo& info = it->second;
*p_native_bits =
NativeVectorBits(runtime::StorageScope::Create(GetPtrStorageScope(GetRef<Var>(buf_var))));
max_align_bits = info.alignment * 8;
} else {
*p_native_bits = native_vector_bits_;
}
arith::ModularSet me = analyzer_->modular_set(index);
int64_t base = me->base;
int64_t coeff = me->coeff;
int align_bits = t.bits();
while (align_bits < max_align_bits && base % 2 == 0 && coeff % 2 == 0) {
base = base / 2;
coeff = coeff / 2;
align_bits *= 2;
}
if (align_bits < 8) {
align_bits = 8;
}
*p_alignment = align_bits / 8;
}
llvm::GlobalVariable* CodeGenLLVM::AllocateSharedMemory(DataType dtype, size_t size,
unsigned int shared_address_space,
int alignment,
llvm::GlobalValue::LinkageTypes linkage) {
llvm::Type* type = llvm::ArrayType::get(DTypeToLLVMType(dtype), size);
llvm::GlobalVariable* global =
new llvm::GlobalVariable(*module_, type, false, linkage, llvm::UndefValue::get(type), "shmem",
nullptr, llvm::GlobalValue::NotThreadLocal, shared_address_space);
#if TVM_LLVM_VERSION >= 100
global->setAlignment(llvm::Align(alignment));
#else
global->setAlignment(alignment);
#endif
return global;
}
std::unique_ptr<CodeGenLLVM::DebugInfo> CodeGenLLVM::CreateDebugInfo(llvm::Module* module) {
#if TVM_LLVM_VERSION >= 100
auto debug_info = std::make_unique<CodeGenLLVM::DebugInfo>();
debug_info->di_builder_ = std::make_unique<llvm::DIBuilder>(*module);
#else
auto debug_info = llvm::make_unique<CodeGenLLVM::DebugInfo>();
debug_info->di_builder_ = llvm::make_unique<llvm::DIBuilder>(*module);
#endif
// TODO(tulloch): pass this information through relay::Span classes to the IRModule instance?
debug_info->file_ = debug_info->di_builder_->createFile("main.tir", ".");
const int runtime_version = 0;
const bool is_optimized = false;
const char* compiler_flags = "";
debug_info->compilation_unit_ = debug_info->di_builder_->createCompileUnit(
/*Lang=*/llvm::dwarf::DW_LANG_C, /*File=*/debug_info->file_, /*Producer=*/"TVM", is_optimized,
compiler_flags, runtime_version);
return debug_info;
}
llvm::Value* CodeGenLLVM::CreateBroadcast(llvm::Value* value, int lanes) {
#if TVM_LLVM_VERSION >= 110
llvm::Type* type = llvm::FixedVectorType::get(value->getType(), lanes);
#else
llvm::Type* type = llvm::VectorType::get(value->getType(), lanes);
#endif
llvm::Constant* undef = llvm::UndefValue::get(type);
llvm::Constant* zero = ConstInt32(0);
value = builder_->CreateInsertElement(undef, value, zero);
#if TVM_LLVM_VERSION >= 120
llvm::Constant* mask = llvm::ConstantVector::getSplat(llvm::ElementCount::getFixed(lanes), zero);
#elif TVM_LLVM_VERSION >= 110
llvm::Constant* mask =
llvm::ConstantVector::getSplat(llvm::ElementCount(lanes, /*Scalable=*/false), zero);
#else
llvm::Constant* mask = llvm::ConstantVector::getSplat(lanes, zero);
#endif
return builder_->CreateShuffleVector(value, undef, mask);
}
llvm::Value* CodeGenLLVM::CreateVecSlice(llvm::Value* vec, int begin, int extent) {
int num_elems = GetVectorNumElements(vec);
if (extent == num_elems && begin == 0) return vec;
ICHECK(begin >= 0 && extent <= num_elems) << "Slicing out of bound!\n";
std::vector<llvm::Constant*> indices;
indices.reserve(extent);
for (int i = 0; i < extent; ++i) {
if (begin + i >= 0 && begin + i < num_elems) {
indices.push_back(llvm::ConstantInt::get(t_int32_, begin + i));
} else {
indices.push_back(llvm::UndefValue::get(t_int32_));
}
}
return builder_->CreateShuffleVector(vec, vec, llvm::ConstantVector::get(indices));
}
llvm::Value* CodeGenLLVM::CreateVecFlip(llvm::Value* vec) {
int num_elems = GetVectorNumElements(vec);
#if TVM_LLVM_VERSION >= 110
std::vector<int> indices;
#else
std::vector<unsigned> indices;
#endif
for (int i = 0; i < num_elems; ++i) {
indices.push_back(num_elems - i - 1);
}
return builder_->CreateShuffleVector(vec, vec, indices);
}
llvm::Value* CodeGenLLVM::CreateVecPad(llvm::Value* vec, int target_lanes) {
llvm::Value* mask = llvm::UndefValue::get(DTypeToLLVMType(DataType::Int(32, target_lanes)));
int num_elems = GetVectorNumElements(vec);
if (num_elems == target_lanes) return vec;
ICHECK_LT(num_elems, target_lanes);
for (int i = 0; i < num_elems; ++i) {
mask = builder_->CreateInsertElement(mask, ConstInt32(i), ConstInt32(i));
}
return builder_->CreateShuffleVector(vec, vec, mask);
}
llvm::Value* CodeGenLLVM::CreateVecConcat(std::vector<llvm::Value*> vecs) {
// To allow creating vectors from scalars, convert any scalars in "vecs" to single-lane
// LLVM vector types.
for (size_t i = 0, e = vecs.size(); i != e; ++i) {
llvm::Value* v = vecs[i];
if (!v->getType()->isVectorTy()) {
#if TVM_LLVM_VERSION >= 110
llvm::Type* vec_ty = llvm::FixedVectorType::get(v->getType(), 1);
#else
llvm::Type* vec_ty = llvm::VectorType::get(v->getType(), 1);
#endif
vecs[i] = builder_->CreateInsertElement(llvm::UndefValue::get(vec_ty), v, ConstInt32(0));
}
}
// concat vector, tree shape reduction
int total_lanes = 0;
for (llvm::Value* v : vecs) {
total_lanes += GetVectorNumElements(v);
}
while (vecs.size() > 1) {
std::vector<llvm::Value*> new_vecs;
for (size_t i = 0; i < vecs.size() - 1; i += 2) {
llvm::Value* lhs = vecs[i];
llvm::Value* rhs = vecs[i + 1];
const size_t lhs_lanes = GetVectorNumElements(lhs);
const size_t rhs_lanes = GetVectorNumElements(rhs);
if (lhs_lanes < rhs_lanes) {
lhs = CreateVecPad(lhs, rhs_lanes);
} else if (rhs_lanes < lhs_lanes) {
rhs = CreateVecPad(rhs, lhs_lanes);
}
const size_t shared_lanes = std::max(lhs_lanes, rhs_lanes);
#if TVM_LLVM_VERSION >= 110
std::vector<int> mask;
#else
std::vector<unsigned> mask;
#endif
for (size_t i = 0; i < lhs_lanes; ++i) {
mask.push_back(i);
}
for (size_t i = 0; i < rhs_lanes; ++i) {
mask.push_back(shared_lanes + i);
}
new_vecs.push_back(builder_->CreateShuffleVector(lhs, rhs, mask));
}
if (vecs.size() % 2 != 0) {
new_vecs.push_back(vecs.back());
}
vecs.swap(new_vecs);
}
return CreateVecSlice(vecs[0], 0, total_lanes);
}
void CodeGenLLVM::CreateSerialFor(llvm::Value* begin, llvm::Value* end, llvm::Value* stride,
const Var& loop_var, const Stmt& body) {
EmitDebugLocation(body->span);
llvm::BasicBlock* pre_block = builder_->GetInsertBlock();
std::string loop_var_name = loop_var->name_hint;
llvm::LLVMContext* ctx = llvm_target_->GetContext();
auto* for_begin = llvm::BasicBlock::Create(*ctx, "for_begin_" + loop_var_name, function_);
auto* for_body = llvm::BasicBlock::Create(*ctx, "for_body_" + loop_var_name, function_);
auto* for_end = llvm::BasicBlock::Create(*ctx, "for_end_" + loop_var_name, function_);
builder_->CreateBr(for_begin);
builder_->SetInsertPoint(for_begin);
llvm::PHINode* loop_value = builder_->CreatePHI(begin->getType(), 2);
loop_value->setName(loop_var->name_hint.c_str());
loop_value->addIncoming(begin, pre_block);
ICHECK(!var_map_.count(loop_var.get()));
var_map_[loop_var.get()] = loop_value;
auto lt = CreateLT(loop_var.dtype(), loop_value, end);
builder_->CreateCondBr(lt, for_body, for_end, md_very_likely_branch_);
builder_->SetInsertPoint(for_body);
this->VisitStmt(body);
var_map_.erase(loop_var.get());
llvm::Value* loop_next = CreateAdd(loop_var.dtype(), loop_value, stride);
loop_value->addIncoming(loop_next, builder_->GetInsertBlock());
builder_->CreateBr(for_begin);
builder_->SetInsertPoint(for_end);
}
// cast operatpr
llvm::Value* CodeGenLLVM::CreateCast(DataType from, DataType to, llvm::Value* value) {
llvm::Type* target = DTypeToLLVMType(to);
if (value->getType() == target) return value;
// TODO(tvm-team): consider add native support
ICHECK(!from.is_bfloat16()) << "BF16 needs to be storaged lowered first";
ICHECK(!to.is_bfloat16()) << "BF16 needs to be storaged lowered first";
if (to.is_handle()) {
return builder_->CreateBitCast(value, target);
} else if (to.is_uint() && to.bits() == 1) {
if (from.is_float()) {
llvm::Constant* zero = llvm::ConstantFP::get(DTypeToLLVMType(from), 0.);
return builder_->CreateFCmpONE(value, zero);
} else {
llvm::Constant* zero = llvm::ConstantInt::get(DTypeToLLVMType(from), 0);
return builder_->CreateICmpNE(value, zero);
}
} else if (!from.is_float() && !to.is_float()) {
return builder_->CreateIntCast(value, target, from.is_int());
} else if (from.is_float() && to.is_int()) {
return builder_->CreateFPToSI(value, target);
} else if (from.is_float() && to.is_uint()) {
if (to.bits() < 8) {
value = builder_->CreateFPToUI(value, DTypeToLLVMType(to.with_bits(8)));
return builder_->CreateIntCast(value, target, false);
} else {
return builder_->CreateFPToUI(value, target);
}
} else if (from.is_int() && to.is_float()) {
return builder_->CreateSIToFP(value, target);
} else if (from.is_uint() && to.is_float()) {
return builder_->CreateUIToFP(value, target);
} else {
ICHECK(from.is_float() && to.is_float());
return builder_->CreateFPCast(value, target);
}
}
llvm::Constant* CodeGenLLVM::GetGlobalConstant(llvm::Constant* const_data, const std::string& name,
llvm::GlobalValue::LinkageTypes linkage_type) {
llvm::Type* ty = const_data->getType();
llvm::GlobalVariable* global =
new llvm::GlobalVariable(*module_, ty, true, linkage_type, const_data, name);
#if TVM_LLVM_VERSION >= 100
global->setAlignment(llvm::Align(1));
#else
global->setAlignment(1);
#endif
llvm::Constant* zero = ConstInt32(0);
llvm::Constant* indices[] = {zero, zero};
llvm::Constant* ptr = llvm::ConstantExpr::getGetElementPtr(ty, global, indices);
return ptr;
}
llvm::Constant* CodeGenLLVM::GetConstString(const std::string& str) {
auto it = str_map_.find(str);
if (it != str_map_.end()) return it->second;
auto llvm_str = llvm::ConstantDataArray::getString(*llvm_target_->GetContext(), str);
auto ptr = GetGlobalConstant(llvm_str, ".str", llvm::GlobalValue::PrivateLinkage);
str_map_[str] = ptr;
return ptr;
}
CodeGenLLVM::TypedPointer CodeGenLLVM::CreateBufferPtr(llvm::Value* buffer_ptr,
DataType buffer_element_dtype,
llvm::ArrayRef<llvm::Value*> indices,
DataType value_dtype) {
ICHECK_EQ(indices.size(), 1) << "CodeGenLLVM requires all buffers to be flat 1-d buffers.";
llvm::Value* index = indices[0];
llvm::PointerType* buffer_ptr_type = llvm::dyn_cast<llvm::PointerType>(buffer_ptr->getType());
ICHECK(buffer_ptr_type != nullptr);
auto address_space = buffer_ptr_type->getAddressSpace();
llvm::Type* element_type = DTypeToLLVMType(buffer_element_dtype);
llvm::PointerType* element_ptr_type =
DTypeToLLVMType(buffer_element_dtype)->getPointerTo(address_space);
llvm::Type* value_type = DTypeToLLVMType(value_dtype);
llvm::PointerType* value_ptr_type = value_type->getPointerTo(address_space);
ICHECK(index->getType()->isIntegerTy()) << "Expected buffer index to be an integer";
if (buffer_ptr_type != element_ptr_type) {
buffer_ptr = builder_->CreatePointerCast(buffer_ptr, element_ptr_type);
}
ICHECK(!HasAlignmentPadding(buffer_element_dtype))
<< "DType " << buffer_element_dtype
<< " has padding for alignment. TVM data arrays are expected to be densely packed, with no "
"padding for alignment.";
llvm::Value* value_ptr = builder_->CreateInBoundsGEP(element_type, buffer_ptr, index);
if (element_ptr_type != value_ptr_type) {
value_ptr = builder_->CreatePointerCast(value_ptr, value_ptr_type);
}
return TypedPointer(value_type, value_ptr);
}
llvm::Value* CodeGenLLVM::GetVarValue(const VarNode* v) const {
auto it = var_map_.find(v);
ICHECK(it != var_map_.end()) << "cannot find variable " << v->name_hint;
return it->second;
}
void CodeGenLLVM::CreatePrintf(const std::string& format,
llvm::ArrayRef<llvm::Value*> format_args) {
EmitDebugLocation();
llvm::Function* func_printf = module_->getFunction("printf");
if (func_printf == nullptr) {
llvm::FunctionType* ftype = llvm::FunctionType::get(t_int32_, true);
func_printf =
llvm::Function::Create(ftype, llvm::Function::ExternalLinkage, "printf", module_.get());
}
llvm::Function* func_fflush = module_->getFunction("fflush");
if (!func_fflush) {
llvm::FunctionType* ftype = llvm::FunctionType::get(t_int32_, {t_void_p_}, false);
func_fflush =
llvm::Function::Create(ftype, llvm::Function::ExternalLinkage, "fflush", module_.get());
}
llvm::Value* str = builder_->CreateGlobalStringPtr(format);
str->setName("printf_format_str");