1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/AutoUpgrade.h"
21 #include "llvm/IR/AssemblyAnnotationWriter.h"
22 #include "llvm/Support/CBindingWrapping.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Host.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
28 #if LLVM_VERSION_GE(6, 0)
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include "llvm/Transforms/IPO/AlwaysInliner.h"
36 #include "llvm/Transforms/IPO/FunctionImport.h"
37 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
38 #include "llvm/LTO/LTO.h"
40 #include "llvm-c/Transforms/PassManagerBuilder.h"
43 using namespace llvm::legacy;
45 extern cl::opt<bool> EnableARMEHABI;
47 typedef struct LLVMOpaquePass *LLVMPassRef;
48 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
50 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
51 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
52 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
53 LLVMPassManagerBuilderRef)
55 extern "C" void LLVMInitializePasses() {
56 PassRegistry &Registry = *PassRegistry::getPassRegistry();
57 initializeCore(Registry);
58 initializeCodeGen(Registry);
59 initializeScalarOpts(Registry);
60 initializeVectorization(Registry);
61 initializeIPO(Registry);
62 initializeAnalysis(Registry);
63 initializeTransformUtils(Registry);
64 initializeInstCombine(Registry);
65 initializeInstrumentation(Registry);
66 initializeTarget(Registry);
69 enum class LLVMRustPassKind {
75 static LLVMRustPassKind toRust(PassKind Kind) {
78 return LLVMRustPassKind::Function;
80 return LLVMRustPassKind::Module;
82 return LLVMRustPassKind::Other;
86 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
87 StringRef SR(PassName);
88 PassRegistry *PR = PassRegistry::getPassRegistry();
90 const PassInfo *PI = PR->getPassInfo(SR);
92 return wrap(PI->createPass());
97 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
99 Pass *Pass = unwrap(RustPass);
100 return toRust(Pass->getPassKind());
103 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
105 Pass *Pass = unwrap(RustPass);
106 PassManagerBase *PMB = unwrap(PMR);
111 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
112 LLVMPassManagerBuilderRef PMBR,
113 LLVMPassManagerRef PMR
115 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
118 #ifdef LLVM_COMPONENT_X86
119 #define SUBTARGET_X86 SUBTARGET(X86)
121 #define SUBTARGET_X86
124 #ifdef LLVM_COMPONENT_ARM
125 #define SUBTARGET_ARM SUBTARGET(ARM)
127 #define SUBTARGET_ARM
130 #ifdef LLVM_COMPONENT_AARCH64
131 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
133 #define SUBTARGET_AARCH64
136 #ifdef LLVM_COMPONENT_MIPS
137 #define SUBTARGET_MIPS SUBTARGET(Mips)
139 #define SUBTARGET_MIPS
142 #ifdef LLVM_COMPONENT_POWERPC
143 #define SUBTARGET_PPC SUBTARGET(PPC)
145 #define SUBTARGET_PPC
148 #ifdef LLVM_COMPONENT_SYSTEMZ
149 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
151 #define SUBTARGET_SYSTEMZ
154 #ifdef LLVM_COMPONENT_MSP430
155 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
157 #define SUBTARGET_MSP430
160 #ifdef LLVM_COMPONENT_RISCV
161 #define SUBTARGET_RISCV SUBTARGET(RISCV)
163 #define SUBTARGET_RISCV
166 #ifdef LLVM_COMPONENT_SPARC
167 #define SUBTARGET_SPARC SUBTARGET(Sparc)
169 #define SUBTARGET_SPARC
172 #ifdef LLVM_COMPONENT_HEXAGON
173 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
175 #define SUBTARGET_HEXAGON
178 #define GEN_SUBTARGETS \
190 #define SUBTARGET(x) \
192 extern const SubtargetFeatureKV x##FeatureKV[]; \
193 extern const SubtargetFeatureKV x##SubTypeKV[]; \
199 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
200 const char *Feature) {
201 #if LLVM_VERSION_GE(6, 0)
202 TargetMachine *Target = unwrap(TM);
203 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
204 return MCInfo->checkFeatures(std::string("+") + Feature);
210 enum class LLVMRustCodeModel {
219 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
221 case LLVMRustCodeModel::Small:
222 return CodeModel::Small;
223 case LLVMRustCodeModel::Kernel:
224 return CodeModel::Kernel;
225 case LLVMRustCodeModel::Medium:
226 return CodeModel::Medium;
227 case LLVMRustCodeModel::Large:
228 return CodeModel::Large;
230 report_fatal_error("Bad CodeModel.");
234 enum class LLVMRustCodeGenOptLevel {
242 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
244 case LLVMRustCodeGenOptLevel::None:
245 return CodeGenOpt::None;
246 case LLVMRustCodeGenOptLevel::Less:
247 return CodeGenOpt::Less;
248 case LLVMRustCodeGenOptLevel::Default:
249 return CodeGenOpt::Default;
250 case LLVMRustCodeGenOptLevel::Aggressive:
251 return CodeGenOpt::Aggressive;
253 report_fatal_error("Bad CodeGenOptLevel.");
257 enum class LLVMRustRelocMode {
267 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
269 case LLVMRustRelocMode::Default:
271 case LLVMRustRelocMode::Static:
272 return Reloc::Static;
273 case LLVMRustRelocMode::PIC:
275 case LLVMRustRelocMode::DynamicNoPic:
276 return Reloc::DynamicNoPIC;
277 case LLVMRustRelocMode::ROPI:
279 case LLVMRustRelocMode::RWPI:
281 case LLVMRustRelocMode::ROPIRWPI:
282 return Reloc::ROPI_RWPI;
284 report_fatal_error("Bad RelocModel.");
288 /// getLongestEntryLength - Return the length of the longest entry in the table.
290 static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
292 for (auto &I : Table)
293 MaxLen = std::max(MaxLen, std::strlen(I.Key));
297 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
298 const TargetMachine *Target = unwrap(TM);
299 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
300 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
301 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
302 const ArrayRef<SubtargetFeatureKV> CPUTable = MCInfo->getCPUTable();
303 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
305 printf("Available CPUs for this target:\n");
306 if (HostArch == TargetArch) {
307 const StringRef HostCPU = sys::getHostCPUName();
308 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
309 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
311 for (auto &CPU : CPUTable)
312 printf(" %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
316 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
317 const TargetMachine *Target = unwrap(TM);
318 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
319 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
320 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
322 printf("Available features for this target:\n");
323 for (auto &Feature : FeatTable)
324 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
327 printf("Use +feature to enable a feature, or -feature to disable it.\n"
328 "For example, rustc -C -target-cpu=mycpu -C "
329 "target-feature=+feature1,-feature2\n\n");
334 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
335 printf("Target CPU help is not supported by this LLVM version.\n\n");
338 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
339 printf("Target features help is not supported by this LLVM version.\n\n");
343 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
344 StringRef Name = sys::getHostCPUName();
349 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
350 const char *TripleStr, const char *CPU, const char *Feature,
351 LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
352 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
353 bool PositionIndependentExecutable, bool FunctionSections,
355 bool TrapUnreachable,
358 bool EmitStackSizeSection) {
360 auto OptLevel = fromRust(RustOptLevel);
361 auto RM = fromRust(RustReloc);
364 Triple Trip(Triple::normalize(TripleStr));
365 const llvm::Target *TheTarget =
366 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
367 if (TheTarget == nullptr) {
368 LLVMRustSetLastError(Error.c_str());
372 TargetOptions Options;
374 Options.FloatABIType = FloatABI::Default;
376 Options.FloatABIType = FloatABI::Soft;
378 Options.DataSections = DataSections;
379 Options.FunctionSections = FunctionSections;
380 Options.MCOptions.AsmVerbose = AsmComments;
381 Options.MCOptions.PreserveAsmComments = AsmComments;
383 if (TrapUnreachable) {
384 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
385 // This limits the extent of possible undefined behavior in some cases, as
386 // it prevents control flow from "falling through" into whatever code
387 // happens to be laid out next in memory.
388 Options.TrapUnreachable = true;
392 Options.ThreadModel = ThreadModel::Single;
395 #if LLVM_VERSION_GE(6, 0)
396 Options.EmitStackSizeSection = EmitStackSizeSection;
398 Optional<CodeModel::Model> CM;
400 CodeModel::Model CM = CodeModel::Model::Default;
402 if (RustCM != LLVMRustCodeModel::None)
403 CM = fromRust(RustCM);
404 TargetMachine *TM = TheTarget->createTargetMachine(
405 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
409 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
413 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
414 // passes for a target to a pass manager. We export that functionality through
416 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
417 LLVMPassManagerRef PMR,
419 PassManagerBase *PM = unwrap(PMR);
421 createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
424 extern "C" void LLVMRustConfigurePassManagerBuilder(
425 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
426 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
427 const char* PGOGenPath, const char* PGOUsePath) {
428 #if LLVM_VERSION_GE(7, 0)
429 unwrap(PMBR)->MergeFunctions = MergeFunctions;
431 unwrap(PMBR)->SLPVectorize = SLPVectorize;
432 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
433 unwrap(PMBR)->LoopVectorize = LoopVectorize;
434 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
438 unwrap(PMBR)->EnablePGOInstrGen = true;
439 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
443 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
447 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
448 // field of a PassManagerBuilder, we expose our own method of doing so.
449 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
451 bool DisableSimplifyLibCalls) {
452 Triple TargetTriple(unwrap(M)->getTargetTriple());
453 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
454 if (DisableSimplifyLibCalls)
455 TLI->disableAllFunctions();
456 unwrap(PMBR)->LibraryInfo = TLI;
459 // Unfortunately, the LLVM C API doesn't provide a way to create the
460 // TargetLibraryInfo pass, so we use this method to do so.
461 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
462 bool DisableSimplifyLibCalls) {
463 Triple TargetTriple(unwrap(M)->getTargetTriple());
464 TargetLibraryInfoImpl TLII(TargetTriple);
465 if (DisableSimplifyLibCalls)
466 TLII.disableAllFunctions();
467 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
470 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
471 // all the functions in a module, so we do that manually here. You'll find
472 // similar code in clang's BackendUtil.cpp file.
473 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
475 llvm::legacy::FunctionPassManager *P =
476 unwrap<llvm::legacy::FunctionPassManager>(PMR);
477 P->doInitialization();
479 // Upgrade all calls to old intrinsics first.
480 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
481 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
483 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
485 if (!I->isDeclaration())
491 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
492 // Initializing the command-line options more than once is not allowed. So,
493 // check if they've already been initialized. (This could happen if we're
494 // being called from rustpkg, for example). If the arguments change, then
495 // that's just kinda unfortunate.
496 static bool Initialized = false;
500 cl::ParseCommandLineOptions(Argc, Argv);
503 enum class LLVMRustFileType {
509 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
511 case LLVMRustFileType::AssemblyFile:
512 return TargetMachine::CGFT_AssemblyFile;
513 case LLVMRustFileType::ObjectFile:
514 return TargetMachine::CGFT_ObjectFile;
516 report_fatal_error("Bad FileType.");
520 extern "C" LLVMRustResult
521 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
522 LLVMModuleRef M, const char *Path,
523 LLVMRustFileType RustFileType) {
524 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
525 auto FileType = fromRust(RustFileType);
527 std::string ErrorInfo;
529 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
531 ErrorInfo = EC.message();
532 if (ErrorInfo != "") {
533 LLVMRustSetLastError(ErrorInfo.c_str());
534 return LLVMRustResult::Failure;
537 #if LLVM_VERSION_GE(7, 0)
538 buffer_ostream BOS(OS);
539 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
541 unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
545 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
546 // stream (OS), so the only real safe place to delete this is here? Don't we
547 // wish this was written in Rust?
549 return LLVMRustResult::Success;
553 // Callback to demangle function name
555 // * name to be demangled
558 // * output buffer len
559 // Returns len of demangled string, or 0 if demangle failed.
560 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
565 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
567 std::vector<char> Buf;
570 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
572 // Return empty string if demangle failed
573 // or if name does not need to be demangled
574 StringRef CallDemangle(StringRef name) {
579 if (Buf.size() < name.size() * 2) {
580 // Semangled name usually shorter than mangled,
581 // but allocate twice as much memory just in case
582 Buf.resize(name.size() * 2);
585 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
591 auto Demangled = StringRef(Buf.data(), R);
592 if (Demangled == name) {
593 // Do not print anything if demangled name is equal to mangled.
600 void emitFunctionAnnot(const Function *F,
601 formatted_raw_ostream &OS) override {
602 StringRef Demangled = CallDemangle(F->getName());
603 if (Demangled.empty()) {
607 OS << "; " << Demangled << "\n";
610 void emitInstructionAnnot(const Instruction *I,
611 formatted_raw_ostream &OS) override {
614 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
616 Value = CI->getCalledValue();
617 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
619 Value = II->getCalledValue();
621 // Could demangle more operations, e. g.
622 // `store %place, @function`.
626 if (!Value->hasName()) {
630 StringRef Demangled = CallDemangle(Value->getName());
631 if (Demangled.empty()) {
635 OS << "; " << Name << " " << Demangled << "\n";
639 class RustPrintModulePass : public ModulePass {
644 RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
645 RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
646 : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
648 bool runOnModule(Module &M) override {
649 RustAssemblyAnnotationWriter AW(Demangle);
651 M.print(*OS, &AW, false);
656 void getAnalysisUsage(AnalysisUsage &AU) const override {
657 AU.setPreservesAll();
660 static StringRef name() { return "RustPrintModulePass"; }
666 void initializeRustPrintModulePassPass(PassRegistry&);
669 char RustPrintModulePass::ID = 0;
670 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
671 "Print rust module to stderr", false, false)
673 extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
674 const char *Path, DemangleFn Demangle) {
675 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
676 std::string ErrorInfo;
679 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
681 ErrorInfo = EC.message();
683 formatted_raw_ostream FOS(OS);
685 PM->add(new RustPrintModulePass(FOS, Demangle));
690 extern "C" void LLVMRustPrintPasses() {
691 LLVMInitializePasses();
692 struct MyListener : PassRegistrationListener {
693 void passEnumerate(const PassInfo *Info) {
694 StringRef PassArg = Info->getPassArgument();
695 StringRef PassName = Info->getPassName();
696 if (!PassArg.empty()) {
697 // These unsigned->signed casts could theoretically overflow, but
698 // realistically never will (and even if, the result is implementation
699 // defined rather plain UB).
700 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
701 (int)PassName.size(), PassName.data());
706 PassRegistry *PR = PassRegistry::getPassRegistry();
707 PR->enumerateWith(&Listener);
710 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
712 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
715 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
717 llvm::legacy::PassManager passes;
719 auto PreserveFunctions = [=](const GlobalValue &GV) {
720 for (size_t I = 0; I < Len; I++) {
721 if (GV.getName() == Symbols[I]) {
728 passes.add(llvm::createInternalizePass(PreserveFunctions));
730 passes.run(*unwrap(M));
733 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
734 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
736 GV->setDoesNotThrow();
737 Function *F = dyn_cast<Function>(GV);
741 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
742 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
743 if (isa<InvokeInst>(I)) {
744 InvokeInst *CI = cast<InvokeInst>(I);
745 CI->setDoesNotThrow();
753 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
754 LLVMTargetMachineRef TMR) {
755 TargetMachine *Target = unwrap(TMR);
756 unwrap(Module)->setDataLayout(Target->createDataLayout());
759 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
760 unwrap(M)->setPIELevel(PIELevel::Level::Large);
763 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
764 // right now. This ThinLTO support is only enabled on "recent ish" versions of
765 // LLVM, and otherwise it's just blanket rejected from other compilers.
767 // Most of this implementation is straight copied from LLVM. At the time of
768 // this writing it wasn't *quite* suitable to reuse more code from upstream
769 // for our purposes, but we should strive to upstream this support once it's
770 // ready to go! I figure we may want a bit of testing locally first before
771 // sending this upstream to LLVM. I hear though they're quite eager to receive
772 // feedback like this!
774 // If you're reading this code and wondering "what in the world" or you're
775 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
776 // then fear not! (ok maybe fear a little). All code here is mostly based
777 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
779 // You'll find that the general layout here roughly corresponds to the `run`
780 // method in that file as well as `ProcessThinLTOModule`. Functions are
781 // specifically commented below as well, but if you're updating this code
782 // or otherwise trying to understand it, the LLVM source will be useful in
783 // interpreting the mysteries within.
785 // Otherwise I'll apologize in advance, it probably requires a relatively
786 // significant investment on your part to "truly understand" what's going on
787 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
788 // and various online resources about ThinLTO to make heads or tails of all
791 // This is a shared data structure which *must* be threadsafe to share
792 // read-only amongst threads. This also corresponds basically to the arguments
793 // of the `ProcessThinLTOModule` function in the LLVM source.
794 struct LLVMRustThinLTOData {
795 // The combined index that is the global analysis over all modules we're
796 // performing ThinLTO for. This is mostly managed by LLVM.
797 ModuleSummaryIndex Index;
799 // All modules we may look at, stored as in-memory serialized versions. This
800 // is later used when inlining to ensure we can extract any module to inline
802 StringMap<MemoryBufferRef> ModuleMap;
804 // A set that we manage of everything we *don't* want internalized. Note that
805 // this includes all transitive references right now as well, but it may not
807 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
809 // Not 100% sure what these are, but they impact what's internalized and
810 // what's inlined across modules, I believe.
811 StringMap<FunctionImporter::ImportMapTy> ImportLists;
812 StringMap<FunctionImporter::ExportSetTy> ExportLists;
813 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
815 #if LLVM_VERSION_GE(7, 0)
816 LLVMRustThinLTOData() : Index(/* isPerformingAnalysis = */ false) {}
820 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
821 struct LLVMRustThinLTOModule {
822 const char *identifier;
827 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
829 static const GlobalValueSummary *
830 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
831 auto StrongDefForLinker = llvm::find_if(
832 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
833 auto Linkage = Summary->linkage();
834 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
835 !GlobalValue::isWeakForLinker(Linkage);
837 if (StrongDefForLinker != GVSummaryList.end())
838 return StrongDefForLinker->get();
840 auto FirstDefForLinker = llvm::find_if(
841 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
842 auto Linkage = Summary->linkage();
843 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
845 if (FirstDefForLinker == GVSummaryList.end())
847 return FirstDefForLinker->get();
850 // The main entry point for creating the global ThinLTO analysis. The structure
851 // here is basically the same as before threads are spawned in the `run`
852 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
853 extern "C" LLVMRustThinLTOData*
854 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
856 const char **preserved_symbols,
858 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
860 // Load each module's summary and merge it into one combined index
861 for (int i = 0; i < num_modules; i++) {
862 auto module = &modules[i];
863 StringRef buffer(module->data, module->len);
864 MemoryBufferRef mem_buffer(buffer, module->identifier);
866 Ret->ModuleMap[module->identifier] = mem_buffer;
868 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
869 LLVMRustSetLastError(toString(std::move(Err)).c_str());
874 // Collect for each module the list of function it defines (GUID -> Summary)
875 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
877 // Convert the preserved symbols set from string to GUID, this is then needed
878 // for internalization.
879 for (int i = 0; i < num_symbols; i++) {
880 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
881 Ret->GUIDPreservedSymbols.insert(GUID);
884 // Collect the import/export lists for all modules from the call-graph in the
887 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
888 #if LLVM_VERSION_GE(7, 0)
889 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
890 return PrevailingType::Unknown;
892 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
894 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
896 ComputeCrossModuleImport(
898 Ret->ModuleToDefinedGVSummaries,
903 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
904 // impacts the caching.
906 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
907 // being lifted from `lib/LTO/LTO.cpp` as well
908 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
909 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
910 for (auto &I : Ret->Index) {
911 if (I.second.SummaryList.size() > 1)
912 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
914 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
915 const auto &Prevailing = PrevailingCopy.find(GUID);
916 if (Prevailing == PrevailingCopy.end())
918 return Prevailing->second == S;
920 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
921 GlobalValue::GUID GUID,
922 GlobalValue::LinkageTypes NewLinkage) {
923 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
925 #if LLVM_VERSION_GE(8, 0)
926 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
928 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
931 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
932 // callback below. This callback below will dictate the linkage for all
933 // summaries in the index, and we basically just only want to ensure that dead
934 // symbols are internalized. Otherwise everything that's already external
935 // linkage will stay as external, and internal will stay as internal.
936 std::set<GlobalValue::GUID> ExportedGUIDs;
937 for (auto &List : Ret->Index) {
938 for (auto &GVS: List.second.SummaryList) {
939 if (GlobalValue::isLocalLinkage(GVS->linkage()))
941 auto GUID = GVS->getOriginalName();
942 if (GVS->flags().Live)
943 ExportedGUIDs.insert(GUID);
946 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
947 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
948 return (ExportList != Ret->ExportLists.end() &&
949 ExportList->second.count(GUID)) ||
950 ExportedGUIDs.count(GUID);
952 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
954 return Ret.release();
958 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
962 // Below are the various passes that happen *per module* when doing ThinLTO.
964 // In other words, these are the functions that are all run concurrently
965 // with one another, one per module. The passes here correspond to the analysis
966 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
967 // `ProcessThinLTOModule` function. Here they're split up into separate steps
968 // so rustc can save off the intermediate bytecode between each step.
971 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
972 Module &Mod = *unwrap(M);
973 if (renameModuleForThinLTO(Mod, Data->Index)) {
974 LLVMRustSetLastError("renameModuleForThinLTO failed");
981 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
982 Module &Mod = *unwrap(M);
983 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
984 #if LLVM_VERSION_GE(8, 0)
985 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
987 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
993 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
994 Module &Mod = *unwrap(M);
995 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
996 thinLTOInternalizeModule(Mod, DefinedGlobals);
1001 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1002 Module &Mod = *unwrap(M);
1004 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1005 auto Loader = [&](StringRef Identifier) {
1006 const auto &Memory = Data->ModuleMap.lookup(Identifier);
1007 auto &Context = Mod.getContext();
1008 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1013 // The rest of this closure is a workaround for
1014 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1015 // we accidentally import wasm custom sections into different modules,
1016 // duplicating them by in the final output artifact.
1018 // The issue is worked around here by manually removing the
1019 // `wasm.custom_sections` named metadata node from any imported module. This
1020 // we know isn't used by any optimization pass so there's no need for it to
1023 // Note that the metadata is currently lazily loaded, so we materialize it
1024 // here before looking up if there's metadata inside. The `FunctionImporter`
1025 // will immediately materialize metadata anyway after an import, so this
1026 // shouldn't be a perf hit.
1027 if (Error Err = (*MOrErr)->materializeMetadata()) {
1028 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1032 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1033 if (WasmCustomSections)
1034 WasmCustomSections->eraseFromParent();
1038 FunctionImporter Importer(Data->Index, Loader);
1039 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1041 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1047 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1048 const char*, // importing module name
1049 const char*); // imported module name
1051 // Calls `module_name_callback` for each module import done by ThinLTO.
1052 // The callback is provided with regular null-terminated C strings.
1054 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1055 LLVMRustModuleNameCallback module_name_callback,
1056 void* callback_payload) {
1057 for (const auto& importing_module : data->ImportLists) {
1058 const std::string importing_module_id = importing_module.getKey().str();
1059 const auto& imports = importing_module.getValue();
1060 for (const auto& imported_module : imports) {
1061 const std::string imported_module_id = imported_module.getKey().str();
1062 module_name_callback(callback_payload,
1063 importing_module_id.c_str(),
1064 imported_module_id.c_str());
1069 // This struct and various functions are sort of a hack right now, but the
1070 // problem is that we've got in-memory LLVM modules after we generate and
1071 // optimize all codegen-units for one compilation in rustc. To be compatible
1072 // with the LTO support above we need to serialize the modules plus their
1073 // ThinLTO summary into memory.
1075 // This structure is basically an owned version of a serialize module, with
1076 // a ThinLTO summary attached.
1077 struct LLVMRustThinLTOBuffer {
1081 extern "C" LLVMRustThinLTOBuffer*
1082 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1083 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1085 raw_string_ostream OS(Ret->data);
1087 legacy::PassManager PM;
1088 PM.add(createWriteThinLTOBitcodePass(OS));
1092 return Ret.release();
1096 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1100 extern "C" const void*
1101 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1102 return Buffer->data.data();
1106 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1107 return Buffer->data.length();
1110 // This is what we used to parse upstream bitcode for actual ThinLTO
1111 // processing. We'll call this once per module optimized through ThinLTO, and
1112 // it'll be called concurrently on many threads.
1113 extern "C" LLVMModuleRef
1114 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1117 const char *identifier) {
1118 StringRef Data(data, len);
1119 MemoryBufferRef Buffer(Data, identifier);
1120 unwrap(Context)->enableDebugTypeODRUniquing();
1121 Expected<std::unique_ptr<Module>> SrcOrError =
1122 parseBitcodeFile(Buffer, *unwrap(Context));
1124 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1127 return wrap(std::move(*SrcOrError).release());
1130 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1131 // the comment in `back/lto.rs` for why this exists.
1133 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1135 DICompileUnit **B) {
1136 Module *M = unwrap(Mod);
1137 DICompileUnit **Cur = A;
1138 DICompileUnit **Next = B;
1139 for (DICompileUnit *CU : M->debug_compile_units()) {
1148 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1149 // the comment in `back/lto.rs` for why this exists.
1151 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1152 Module *M = unwrap(Mod);
1154 // If the original source module didn't have a `DICompileUnit` then try to
1155 // merge all the existing compile units. If there aren't actually any though
1156 // then there's not much for us to do so return.
1157 if (Unit == nullptr) {
1158 for (DICompileUnit *CU : M->debug_compile_units()) {
1162 if (Unit == nullptr)
1166 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1167 // process it recursively. Note that we specifically iterate over instructions
1168 // to ensure we feed everything into it.
1169 DebugInfoFinder Finder;
1170 Finder.processModule(*M);
1171 for (Function &F : M->functions()) {
1172 for (auto &FI : F) {
1173 for (Instruction &BI : FI) {
1174 if (auto Loc = BI.getDebugLoc())
1175 Finder.processLocation(*M, Loc);
1176 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1177 Finder.processValue(*M, DVI);
1178 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1179 Finder.processDeclare(*M, DDI);
1184 // After we've found all our debuginfo, rewrite all subprograms to point to
1185 // the same `DICompileUnit`.
1186 for (auto &F : Finder.subprograms()) {
1187 F->replaceUnit(Unit);
1190 // Erase any other references to other `DICompileUnit` instances, the verifier
1191 // will later ensure that we don't actually have any other stale references to
1193 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1194 MD->clearOperands();
1195 MD->addOperand(Unit);