8 #include "llvm/Analysis/TargetLibraryInfo.h"
9 #include "llvm/Analysis/TargetTransformInfo.h"
10 #include "llvm/CodeGen/TargetSubtargetInfo.h"
11 #include "llvm/IR/AutoUpgrade.h"
12 #include "llvm/IR/AssemblyAnnotationWriter.h"
13 #include "llvm/IR/IntrinsicInst.h"
14 #include "llvm/Support/CBindingWrapping.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/Host.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
19 #include "llvm/Transforms/IPO/AlwaysInliner.h"
20 #include "llvm/Transforms/IPO/FunctionImport.h"
21 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm-c/Transforms/PassManagerBuilder.h"
25 #include "llvm/Transforms/Instrumentation.h"
26 #if LLVM_VERSION_GE(9, 0)
27 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
29 #if LLVM_VERSION_GE(8, 0)
30 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
31 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
35 using namespace llvm::legacy;
37 typedef struct LLVMOpaquePass *LLVMPassRef;
38 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
40 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
41 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
42 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
43 LLVMPassManagerBuilderRef)
45 extern "C" void LLVMInitializePasses() {
46 PassRegistry &Registry = *PassRegistry::getPassRegistry();
47 initializeCore(Registry);
48 initializeCodeGen(Registry);
49 initializeScalarOpts(Registry);
50 initializeVectorization(Registry);
51 initializeIPO(Registry);
52 initializeAnalysis(Registry);
53 initializeTransformUtils(Registry);
54 initializeInstCombine(Registry);
55 initializeInstrumentation(Registry);
56 initializeTarget(Registry);
59 enum class LLVMRustPassKind {
65 static LLVMRustPassKind toRust(PassKind Kind) {
68 return LLVMRustPassKind::Function;
70 return LLVMRustPassKind::Module;
72 return LLVMRustPassKind::Other;
76 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
77 StringRef SR(PassName);
78 PassRegistry *PR = PassRegistry::getPassRegistry();
80 const PassInfo *PI = PR->getPassInfo(SR);
82 return wrap(PI->createPass());
87 extern "C" LLVMPassRef LLVMRustCreateAddressSanitizerFunctionPass(bool Recover) {
88 const bool CompileKernel = false;
90 return wrap(createAddressSanitizerFunctionPass(CompileKernel, Recover));
93 extern "C" LLVMPassRef LLVMRustCreateModuleAddressSanitizerPass(bool Recover) {
94 const bool CompileKernel = false;
96 #if LLVM_VERSION_GE(9, 0)
97 return wrap(createModuleAddressSanitizerLegacyPassPass(CompileKernel, Recover));
99 return wrap(createAddressSanitizerModulePass(CompileKernel, Recover));
103 extern "C" LLVMPassRef LLVMRustCreateMemorySanitizerPass(int TrackOrigins, bool Recover) {
104 #if LLVM_VERSION_GE(8, 0)
105 const bool CompileKernel = false;
107 return wrap(createMemorySanitizerLegacyPassPass(
108 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
110 return wrap(createMemorySanitizerPass(TrackOrigins, Recover));
114 extern "C" LLVMPassRef LLVMRustCreateThreadSanitizerPass() {
115 #if LLVM_VERSION_GE(8, 0)
116 return wrap(createThreadSanitizerLegacyPassPass());
118 return wrap(createThreadSanitizerPass());
122 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
124 Pass *Pass = unwrap(RustPass);
125 return toRust(Pass->getPassKind());
128 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
130 Pass *Pass = unwrap(RustPass);
131 PassManagerBase *PMB = unwrap(PMR);
136 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
137 LLVMPassManagerBuilderRef PMBR,
138 LLVMPassManagerRef PMR
140 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
144 void LLVMRustAddLastExtensionPasses(
145 LLVMPassManagerBuilderRef PMBR, LLVMPassRef *Passes, size_t NumPasses) {
146 auto AddExtensionPasses = [Passes, NumPasses](
147 const PassManagerBuilder &Builder, PassManagerBase &PM) {
148 for (size_t I = 0; I < NumPasses; I++) {
149 PM.add(unwrap(Passes[I]));
152 // Add the passes to both of the pre-finalization extension points,
153 // so they are run for optimized and non-optimized builds.
154 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_OptimizerLast,
156 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
160 #ifdef LLVM_COMPONENT_X86
161 #define SUBTARGET_X86 SUBTARGET(X86)
163 #define SUBTARGET_X86
166 #ifdef LLVM_COMPONENT_ARM
167 #define SUBTARGET_ARM SUBTARGET(ARM)
169 #define SUBTARGET_ARM
172 #ifdef LLVM_COMPONENT_AARCH64
173 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
175 #define SUBTARGET_AARCH64
178 #ifdef LLVM_COMPONENT_MIPS
179 #define SUBTARGET_MIPS SUBTARGET(Mips)
181 #define SUBTARGET_MIPS
184 #ifdef LLVM_COMPONENT_POWERPC
185 #define SUBTARGET_PPC SUBTARGET(PPC)
187 #define SUBTARGET_PPC
190 #ifdef LLVM_COMPONENT_SYSTEMZ
191 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
193 #define SUBTARGET_SYSTEMZ
196 #ifdef LLVM_COMPONENT_MSP430
197 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
199 #define SUBTARGET_MSP430
202 #ifdef LLVM_COMPONENT_RISCV
203 #define SUBTARGET_RISCV SUBTARGET(RISCV)
205 #define SUBTARGET_RISCV
208 #ifdef LLVM_COMPONENT_SPARC
209 #define SUBTARGET_SPARC SUBTARGET(Sparc)
211 #define SUBTARGET_SPARC
214 #ifdef LLVM_COMPONENT_HEXAGON
215 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
217 #define SUBTARGET_HEXAGON
220 #define GEN_SUBTARGETS \
232 #define SUBTARGET(x) \
234 extern const SubtargetFeatureKV x##FeatureKV[]; \
235 extern const SubtargetFeatureKV x##SubTypeKV[]; \
241 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
242 const char *Feature) {
243 TargetMachine *Target = unwrap(TM);
244 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
245 return MCInfo->checkFeatures(std::string("+") + Feature);
248 enum class LLVMRustCodeModel {
257 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
259 case LLVMRustCodeModel::Small:
260 return CodeModel::Small;
261 case LLVMRustCodeModel::Kernel:
262 return CodeModel::Kernel;
263 case LLVMRustCodeModel::Medium:
264 return CodeModel::Medium;
265 case LLVMRustCodeModel::Large:
266 return CodeModel::Large;
268 report_fatal_error("Bad CodeModel.");
272 enum class LLVMRustCodeGenOptLevel {
280 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
282 case LLVMRustCodeGenOptLevel::None:
283 return CodeGenOpt::None;
284 case LLVMRustCodeGenOptLevel::Less:
285 return CodeGenOpt::Less;
286 case LLVMRustCodeGenOptLevel::Default:
287 return CodeGenOpt::Default;
288 case LLVMRustCodeGenOptLevel::Aggressive:
289 return CodeGenOpt::Aggressive;
291 report_fatal_error("Bad CodeGenOptLevel.");
295 enum class LLVMRustRelocMode {
305 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
307 case LLVMRustRelocMode::Default:
309 case LLVMRustRelocMode::Static:
310 return Reloc::Static;
311 case LLVMRustRelocMode::PIC:
313 case LLVMRustRelocMode::DynamicNoPic:
314 return Reloc::DynamicNoPIC;
315 case LLVMRustRelocMode::ROPI:
317 case LLVMRustRelocMode::RWPI:
319 case LLVMRustRelocMode::ROPIRWPI:
320 return Reloc::ROPI_RWPI;
322 report_fatal_error("Bad RelocModel.");
326 /// getLongestEntryLength - Return the length of the longest entry in the table.
327 template<typename KV>
328 static size_t getLongestEntryLength(ArrayRef<KV> Table) {
330 for (auto &I : Table)
331 MaxLen = std::max(MaxLen, std::strlen(I.Key));
335 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
336 const TargetMachine *Target = unwrap(TM);
337 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
338 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
339 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
340 const ArrayRef<SubtargetSubTypeKV> CPUTable = MCInfo->getCPUTable();
341 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
343 printf("Available CPUs for this target:\n");
344 if (HostArch == TargetArch) {
345 const StringRef HostCPU = sys::getHostCPUName();
346 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
347 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
349 for (auto &CPU : CPUTable)
350 printf(" %-*s\n", MaxCPULen, CPU.Key);
354 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
355 const TargetMachine *Target = unwrap(TM);
356 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
357 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
358 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
360 printf("Available features for this target:\n");
361 for (auto &Feature : FeatTable)
362 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
365 printf("Use +feature to enable a feature, or -feature to disable it.\n"
366 "For example, rustc -C -target-cpu=mycpu -C "
367 "target-feature=+feature1,-feature2\n\n");
372 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
373 printf("Target CPU help is not supported by this LLVM version.\n\n");
376 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
377 printf("Target features help is not supported by this LLVM version.\n\n");
381 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
382 StringRef Name = sys::getHostCPUName();
387 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
388 const char *TripleStr, const char *CPU, const char *Feature,
389 const char *ABIStr, LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
390 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
391 bool PositionIndependentExecutable, bool FunctionSections,
393 bool TrapUnreachable,
396 bool EmitStackSizeSection,
397 bool RelaxELFRelocations) {
399 auto OptLevel = fromRust(RustOptLevel);
400 auto RM = fromRust(RustReloc);
403 Triple Trip(Triple::normalize(TripleStr));
404 const llvm::Target *TheTarget =
405 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
406 if (TheTarget == nullptr) {
407 LLVMRustSetLastError(Error.c_str());
411 TargetOptions Options;
413 Options.FloatABIType = FloatABI::Default;
415 Options.FloatABIType = FloatABI::Soft;
417 Options.DataSections = DataSections;
418 Options.FunctionSections = FunctionSections;
419 Options.MCOptions.AsmVerbose = AsmComments;
420 Options.MCOptions.PreserveAsmComments = AsmComments;
421 Options.MCOptions.ABIName = ABIStr;
422 Options.RelaxELFRelocations = RelaxELFRelocations;
424 if (TrapUnreachable) {
425 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
426 // This limits the extent of possible undefined behavior in some cases, as
427 // it prevents control flow from "falling through" into whatever code
428 // happens to be laid out next in memory.
429 Options.TrapUnreachable = true;
433 Options.ThreadModel = ThreadModel::Single;
436 Options.EmitStackSizeSection = EmitStackSizeSection;
438 Optional<CodeModel::Model> CM;
439 if (RustCM != LLVMRustCodeModel::None)
440 CM = fromRust(RustCM);
441 TargetMachine *TM = TheTarget->createTargetMachine(
442 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
446 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
450 extern "C" void LLVMRustConfigurePassManagerBuilder(
451 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
452 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
453 const char* PGOGenPath, const char* PGOUsePath) {
454 #if LLVM_VERSION_GE(7, 0)
455 unwrap(PMBR)->MergeFunctions = MergeFunctions;
457 unwrap(PMBR)->SLPVectorize = SLPVectorize;
458 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
459 unwrap(PMBR)->LoopVectorize = LoopVectorize;
460 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
464 unwrap(PMBR)->EnablePGOInstrGen = true;
465 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
469 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
473 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
474 // field of a PassManagerBuilder, we expose our own method of doing so.
475 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
477 bool DisableSimplifyLibCalls) {
478 Triple TargetTriple(unwrap(M)->getTargetTriple());
479 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
480 if (DisableSimplifyLibCalls)
481 TLI->disableAllFunctions();
482 unwrap(PMBR)->LibraryInfo = TLI;
485 // Unfortunately, the LLVM C API doesn't provide a way to create the
486 // TargetLibraryInfo pass, so we use this method to do so.
487 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
488 bool DisableSimplifyLibCalls) {
489 Triple TargetTriple(unwrap(M)->getTargetTriple());
490 TargetLibraryInfoImpl TLII(TargetTriple);
491 if (DisableSimplifyLibCalls)
492 TLII.disableAllFunctions();
493 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
496 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
497 // all the functions in a module, so we do that manually here. You'll find
498 // similar code in clang's BackendUtil.cpp file.
499 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
501 llvm::legacy::FunctionPassManager *P =
502 unwrap<llvm::legacy::FunctionPassManager>(PMR);
503 P->doInitialization();
505 // Upgrade all calls to old intrinsics first.
506 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
507 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
509 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
511 if (!I->isDeclaration())
517 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
518 // Initializing the command-line options more than once is not allowed. So,
519 // check if they've already been initialized. (This could happen if we're
520 // being called from rustpkg, for example). If the arguments change, then
521 // that's just kinda unfortunate.
522 static bool Initialized = false;
526 cl::ParseCommandLineOptions(Argc, Argv);
529 enum class LLVMRustFileType {
535 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
537 case LLVMRustFileType::AssemblyFile:
538 return TargetMachine::CGFT_AssemblyFile;
539 case LLVMRustFileType::ObjectFile:
540 return TargetMachine::CGFT_ObjectFile;
542 report_fatal_error("Bad FileType.");
546 extern "C" LLVMRustResult
547 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
548 LLVMModuleRef M, const char *Path,
549 LLVMRustFileType RustFileType) {
550 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
551 auto FileType = fromRust(RustFileType);
553 std::string ErrorInfo;
555 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
557 ErrorInfo = EC.message();
558 if (ErrorInfo != "") {
559 LLVMRustSetLastError(ErrorInfo.c_str());
560 return LLVMRustResult::Failure;
563 #if LLVM_VERSION_GE(7, 0)
564 buffer_ostream BOS(OS);
565 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
567 unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
571 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
572 // stream (OS), so the only real safe place to delete this is here? Don't we
573 // wish this was written in Rust?
574 LLVMDisposePassManager(PMR);
575 return LLVMRustResult::Success;
579 // Callback to demangle function name
581 // * name to be demangled
584 // * output buffer len
585 // Returns len of demangled string, or 0 if demangle failed.
586 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
591 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
593 std::vector<char> Buf;
596 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
598 // Return empty string if demangle failed
599 // or if name does not need to be demangled
600 StringRef CallDemangle(StringRef name) {
605 if (Buf.size() < name.size() * 2) {
606 // Semangled name usually shorter than mangled,
607 // but allocate twice as much memory just in case
608 Buf.resize(name.size() * 2);
611 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
617 auto Demangled = StringRef(Buf.data(), R);
618 if (Demangled == name) {
619 // Do not print anything if demangled name is equal to mangled.
626 void emitFunctionAnnot(const Function *F,
627 formatted_raw_ostream &OS) override {
628 StringRef Demangled = CallDemangle(F->getName());
629 if (Demangled.empty()) {
633 OS << "; " << Demangled << "\n";
636 void emitInstructionAnnot(const Instruction *I,
637 formatted_raw_ostream &OS) override {
640 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
642 Value = CI->getCalledValue();
643 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
645 Value = II->getCalledValue();
647 // Could demangle more operations, e. g.
648 // `store %place, @function`.
652 if (!Value->hasName()) {
656 StringRef Demangled = CallDemangle(Value->getName());
657 if (Demangled.empty()) {
661 OS << "; " << Name << " " << Demangled << "\n";
665 class RustPrintModulePass : public ModulePass {
670 RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
671 RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
672 : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
674 bool runOnModule(Module &M) override {
675 RustAssemblyAnnotationWriter AW(Demangle);
677 M.print(*OS, &AW, false);
682 void getAnalysisUsage(AnalysisUsage &AU) const override {
683 AU.setPreservesAll();
686 static StringRef name() { return "RustPrintModulePass"; }
692 void initializeRustPrintModulePassPass(PassRegistry&);
695 char RustPrintModulePass::ID = 0;
696 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
697 "Print rust module to stderr", false, false)
699 extern "C" LLVMRustResult
700 LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
701 const char *Path, DemangleFn Demangle) {
702 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
703 std::string ErrorInfo;
706 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
708 ErrorInfo = EC.message();
709 if (ErrorInfo != "") {
710 LLVMRustSetLastError(ErrorInfo.c_str());
711 return LLVMRustResult::Failure;
714 formatted_raw_ostream FOS(OS);
716 PM->add(new RustPrintModulePass(FOS, Demangle));
720 return LLVMRustResult::Success;
723 extern "C" void LLVMRustPrintPasses() {
724 LLVMInitializePasses();
725 struct MyListener : PassRegistrationListener {
726 void passEnumerate(const PassInfo *Info) {
727 StringRef PassArg = Info->getPassArgument();
728 StringRef PassName = Info->getPassName();
729 if (!PassArg.empty()) {
730 // These unsigned->signed casts could theoretically overflow, but
731 // realistically never will (and even if, the result is implementation
732 // defined rather plain UB).
733 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
734 (int)PassName.size(), PassName.data());
739 PassRegistry *PR = PassRegistry::getPassRegistry();
740 PR->enumerateWith(&Listener);
743 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
745 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
748 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
750 llvm::legacy::PassManager passes;
752 auto PreserveFunctions = [=](const GlobalValue &GV) {
753 for (size_t I = 0; I < Len; I++) {
754 if (GV.getName() == Symbols[I]) {
761 passes.add(llvm::createInternalizePass(PreserveFunctions));
763 passes.run(*unwrap(M));
766 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
767 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
769 GV->setDoesNotThrow();
770 Function *F = dyn_cast<Function>(GV);
774 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
775 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
776 if (isa<InvokeInst>(I)) {
777 InvokeInst *CI = cast<InvokeInst>(I);
778 CI->setDoesNotThrow();
786 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
787 LLVMTargetMachineRef TMR) {
788 TargetMachine *Target = unwrap(TMR);
789 unwrap(Module)->setDataLayout(Target->createDataLayout());
792 extern "C" void LLVMRustSetModulePICLevel(LLVMModuleRef M) {
793 unwrap(M)->setPICLevel(PICLevel::Level::BigPIC);
796 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
797 unwrap(M)->setPIELevel(PIELevel::Level::Large);
800 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
801 // right now. This ThinLTO support is only enabled on "recent ish" versions of
802 // LLVM, and otherwise it's just blanket rejected from other compilers.
804 // Most of this implementation is straight copied from LLVM. At the time of
805 // this writing it wasn't *quite* suitable to reuse more code from upstream
806 // for our purposes, but we should strive to upstream this support once it's
807 // ready to go! I figure we may want a bit of testing locally first before
808 // sending this upstream to LLVM. I hear though they're quite eager to receive
809 // feedback like this!
811 // If you're reading this code and wondering "what in the world" or you're
812 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
813 // then fear not! (ok maybe fear a little). All code here is mostly based
814 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
816 // You'll find that the general layout here roughly corresponds to the `run`
817 // method in that file as well as `ProcessThinLTOModule`. Functions are
818 // specifically commented below as well, but if you're updating this code
819 // or otherwise trying to understand it, the LLVM source will be useful in
820 // interpreting the mysteries within.
822 // Otherwise I'll apologize in advance, it probably requires a relatively
823 // significant investment on your part to "truly understand" what's going on
824 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
825 // and various online resources about ThinLTO to make heads or tails of all
828 // This is a shared data structure which *must* be threadsafe to share
829 // read-only amongst threads. This also corresponds basically to the arguments
830 // of the `ProcessThinLTOModule` function in the LLVM source.
831 struct LLVMRustThinLTOData {
832 // The combined index that is the global analysis over all modules we're
833 // performing ThinLTO for. This is mostly managed by LLVM.
834 ModuleSummaryIndex Index;
836 // All modules we may look at, stored as in-memory serialized versions. This
837 // is later used when inlining to ensure we can extract any module to inline
839 StringMap<MemoryBufferRef> ModuleMap;
841 // A set that we manage of everything we *don't* want internalized. Note that
842 // this includes all transitive references right now as well, but it may not
844 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
846 // Not 100% sure what these are, but they impact what's internalized and
847 // what's inlined across modules, I believe.
848 StringMap<FunctionImporter::ImportMapTy> ImportLists;
849 StringMap<FunctionImporter::ExportSetTy> ExportLists;
850 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
852 #if LLVM_VERSION_GE(7, 0)
853 LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {}
857 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
858 struct LLVMRustThinLTOModule {
859 const char *identifier;
864 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
866 static const GlobalValueSummary *
867 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
868 auto StrongDefForLinker = llvm::find_if(
869 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
870 auto Linkage = Summary->linkage();
871 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
872 !GlobalValue::isWeakForLinker(Linkage);
874 if (StrongDefForLinker != GVSummaryList.end())
875 return StrongDefForLinker->get();
877 auto FirstDefForLinker = llvm::find_if(
878 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
879 auto Linkage = Summary->linkage();
880 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
882 if (FirstDefForLinker == GVSummaryList.end())
884 return FirstDefForLinker->get();
887 // The main entry point for creating the global ThinLTO analysis. The structure
888 // here is basically the same as before threads are spawned in the `run`
889 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
890 extern "C" LLVMRustThinLTOData*
891 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
893 const char **preserved_symbols,
895 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
897 // Load each module's summary and merge it into one combined index
898 for (int i = 0; i < num_modules; i++) {
899 auto module = &modules[i];
900 StringRef buffer(module->data, module->len);
901 MemoryBufferRef mem_buffer(buffer, module->identifier);
903 Ret->ModuleMap[module->identifier] = mem_buffer;
905 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
906 LLVMRustSetLastError(toString(std::move(Err)).c_str());
911 // Collect for each module the list of function it defines (GUID -> Summary)
912 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
914 // Convert the preserved symbols set from string to GUID, this is then needed
915 // for internalization.
916 for (int i = 0; i < num_symbols; i++) {
917 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
918 Ret->GUIDPreservedSymbols.insert(GUID);
921 // Collect the import/export lists for all modules from the call-graph in the
924 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
925 #if LLVM_VERSION_GE(7, 0)
926 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
927 return PrevailingType::Unknown;
929 #if LLVM_VERSION_GE(8, 0)
930 // We don't have a complete picture in our use of ThinLTO, just our immediate
931 // crate, so we need `ImportEnabled = false` to limit internalization.
932 // Otherwise, we sometimes lose `static` values -- see #60184.
933 computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
934 deadIsPrevailing, /* ImportEnabled = */ false);
936 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
939 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
941 ComputeCrossModuleImport(
943 Ret->ModuleToDefinedGVSummaries,
948 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
949 // impacts the caching.
951 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
952 // being lifted from `lib/LTO/LTO.cpp` as well
953 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
954 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
955 for (auto &I : Ret->Index) {
956 if (I.second.SummaryList.size() > 1)
957 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
959 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
960 const auto &Prevailing = PrevailingCopy.find(GUID);
961 if (Prevailing == PrevailingCopy.end())
963 return Prevailing->second == S;
965 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
966 GlobalValue::GUID GUID,
967 GlobalValue::LinkageTypes NewLinkage) {
968 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
970 #if LLVM_VERSION_GE(9, 0)
971 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage,
972 Ret->GUIDPreservedSymbols);
973 #elif LLVM_VERSION_GE(8, 0)
974 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
976 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
979 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
980 // callback below. This callback below will dictate the linkage for all
981 // summaries in the index, and we basically just only want to ensure that dead
982 // symbols are internalized. Otherwise everything that's already external
983 // linkage will stay as external, and internal will stay as internal.
984 std::set<GlobalValue::GUID> ExportedGUIDs;
985 for (auto &List : Ret->Index) {
986 for (auto &GVS: List.second.SummaryList) {
987 if (GlobalValue::isLocalLinkage(GVS->linkage()))
989 auto GUID = GVS->getOriginalName();
990 if (GVS->flags().Live)
991 ExportedGUIDs.insert(GUID);
994 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
995 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
996 return (ExportList != Ret->ExportLists.end() &&
997 ExportList->second.count(GUID)) ||
998 ExportedGUIDs.count(GUID);
1000 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
1002 return Ret.release();
1006 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1010 // Below are the various passes that happen *per module* when doing ThinLTO.
1012 // In other words, these are the functions that are all run concurrently
1013 // with one another, one per module. The passes here correspond to the analysis
1014 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
1015 // `ProcessThinLTOModule` function. Here they're split up into separate steps
1016 // so rustc can save off the intermediate bytecode between each step.
1019 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1020 Module &Mod = *unwrap(M);
1021 if (renameModuleForThinLTO(Mod, Data->Index)) {
1022 LLVMRustSetLastError("renameModuleForThinLTO failed");
1029 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1030 Module &Mod = *unwrap(M);
1031 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1032 #if LLVM_VERSION_GE(8, 0)
1033 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
1035 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1041 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1042 Module &Mod = *unwrap(M);
1043 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1044 thinLTOInternalizeModule(Mod, DefinedGlobals);
1049 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1050 Module &Mod = *unwrap(M);
1052 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1053 auto Loader = [&](StringRef Identifier) {
1054 const auto &Memory = Data->ModuleMap.lookup(Identifier);
1055 auto &Context = Mod.getContext();
1056 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1061 // The rest of this closure is a workaround for
1062 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1063 // we accidentally import wasm custom sections into different modules,
1064 // duplicating them by in the final output artifact.
1066 // The issue is worked around here by manually removing the
1067 // `wasm.custom_sections` named metadata node from any imported module. This
1068 // we know isn't used by any optimization pass so there's no need for it to
1071 // Note that the metadata is currently lazily loaded, so we materialize it
1072 // here before looking up if there's metadata inside. The `FunctionImporter`
1073 // will immediately materialize metadata anyway after an import, so this
1074 // shouldn't be a perf hit.
1075 if (Error Err = (*MOrErr)->materializeMetadata()) {
1076 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1080 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1081 if (WasmCustomSections)
1082 WasmCustomSections->eraseFromParent();
1086 FunctionImporter Importer(Data->Index, Loader);
1087 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1089 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1095 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1096 const char*, // importing module name
1097 const char*); // imported module name
1099 // Calls `module_name_callback` for each module import done by ThinLTO.
1100 // The callback is provided with regular null-terminated C strings.
1102 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1103 LLVMRustModuleNameCallback module_name_callback,
1104 void* callback_payload) {
1105 for (const auto& importing_module : data->ImportLists) {
1106 const std::string importing_module_id = importing_module.getKey().str();
1107 const auto& imports = importing_module.getValue();
1108 for (const auto& imported_module : imports) {
1109 const std::string imported_module_id = imported_module.getKey().str();
1110 module_name_callback(callback_payload,
1111 importing_module_id.c_str(),
1112 imported_module_id.c_str());
1117 // This struct and various functions are sort of a hack right now, but the
1118 // problem is that we've got in-memory LLVM modules after we generate and
1119 // optimize all codegen-units for one compilation in rustc. To be compatible
1120 // with the LTO support above we need to serialize the modules plus their
1121 // ThinLTO summary into memory.
1123 // This structure is basically an owned version of a serialize module, with
1124 // a ThinLTO summary attached.
1125 struct LLVMRustThinLTOBuffer {
1129 extern "C" LLVMRustThinLTOBuffer*
1130 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1131 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1133 raw_string_ostream OS(Ret->data);
1135 legacy::PassManager PM;
1136 PM.add(createWriteThinLTOBitcodePass(OS));
1140 return Ret.release();
1144 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1148 extern "C" const void*
1149 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1150 return Buffer->data.data();
1154 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1155 return Buffer->data.length();
1158 // This is what we used to parse upstream bitcode for actual ThinLTO
1159 // processing. We'll call this once per module optimized through ThinLTO, and
1160 // it'll be called concurrently on many threads.
1161 extern "C" LLVMModuleRef
1162 LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1165 const char *identifier) {
1166 StringRef Data(data, len);
1167 MemoryBufferRef Buffer(Data, identifier);
1168 unwrap(Context)->enableDebugTypeODRUniquing();
1169 Expected<std::unique_ptr<Module>> SrcOrError =
1170 parseBitcodeFile(Buffer, *unwrap(Context));
1172 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1175 return wrap(std::move(*SrcOrError).release());
1178 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1179 // the comment in `back/lto.rs` for why this exists.
1181 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1183 DICompileUnit **B) {
1184 Module *M = unwrap(Mod);
1185 DICompileUnit **Cur = A;
1186 DICompileUnit **Next = B;
1187 for (DICompileUnit *CU : M->debug_compile_units()) {
1196 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1197 // the comment in `back/lto.rs` for why this exists.
1199 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1200 Module *M = unwrap(Mod);
1202 // If the original source module didn't have a `DICompileUnit` then try to
1203 // merge all the existing compile units. If there aren't actually any though
1204 // then there's not much for us to do so return.
1205 if (Unit == nullptr) {
1206 for (DICompileUnit *CU : M->debug_compile_units()) {
1210 if (Unit == nullptr)
1214 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1215 // process it recursively. Note that we specifically iterate over instructions
1216 // to ensure we feed everything into it.
1217 DebugInfoFinder Finder;
1218 Finder.processModule(*M);
1219 for (Function &F : M->functions()) {
1220 for (auto &FI : F) {
1221 for (Instruction &BI : FI) {
1222 if (auto Loc = BI.getDebugLoc())
1223 Finder.processLocation(*M, Loc);
1224 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1225 Finder.processValue(*M, DVI);
1226 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1227 Finder.processDeclare(*M, DDI);
1232 // After we've found all our debuginfo, rewrite all subprograms to point to
1233 // the same `DICompileUnit`.
1234 for (auto &F : Finder.subprograms()) {
1235 F->replaceUnit(Unit);
1238 // Erase any other references to other `DICompileUnit` instances, the verifier
1239 // will later ensure that we don't actually have any other stale references to
1241 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1242 MD->clearOperands();
1243 MD->addOperand(Unit);