8 #include "llvm/Analysis/TargetLibraryInfo.h"
9 #include "llvm/Analysis/TargetTransformInfo.h"
10 #include "llvm/CodeGen/TargetSubtargetInfo.h"
11 #include "llvm/InitializePasses.h"
12 #include "llvm/IR/AutoUpgrade.h"
13 #include "llvm/IR/AssemblyAnnotationWriter.h"
14 #include "llvm/IR/IntrinsicInst.h"
15 #include "llvm/Support/CBindingWrapping.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/Host.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
20 #include "llvm/Transforms/IPO/AlwaysInliner.h"
21 #include "llvm/Transforms/IPO/FunctionImport.h"
22 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm-c/Transforms/PassManagerBuilder.h"
26 #include "llvm/Transforms/Instrumentation.h"
27 #if LLVM_VERSION_GE(9, 0)
28 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
30 #if LLVM_VERSION_GE(8, 0)
31 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
32 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
36 using namespace llvm::legacy;
38 typedef struct LLVMOpaquePass *LLVMPassRef;
39 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
41 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
42 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
43 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
44 LLVMPassManagerBuilderRef)
46 extern "C" void LLVMInitializePasses() {
47 PassRegistry &Registry = *PassRegistry::getPassRegistry();
48 initializeCore(Registry);
49 initializeCodeGen(Registry);
50 initializeScalarOpts(Registry);
51 initializeVectorization(Registry);
52 initializeIPO(Registry);
53 initializeAnalysis(Registry);
54 initializeTransformUtils(Registry);
55 initializeInstCombine(Registry);
56 initializeInstrumentation(Registry);
57 initializeTarget(Registry);
60 enum class LLVMRustPassKind {
66 static LLVMRustPassKind toRust(PassKind Kind) {
69 return LLVMRustPassKind::Function;
71 return LLVMRustPassKind::Module;
73 return LLVMRustPassKind::Other;
77 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
78 StringRef SR(PassName);
79 PassRegistry *PR = PassRegistry::getPassRegistry();
81 const PassInfo *PI = PR->getPassInfo(SR);
83 return wrap(PI->createPass());
88 extern "C" LLVMPassRef LLVMRustCreateAddressSanitizerFunctionPass(bool Recover) {
89 const bool CompileKernel = false;
90 const bool UseAfterScope = true;
92 return wrap(createAddressSanitizerFunctionPass(CompileKernel, Recover, UseAfterScope));
95 extern "C" LLVMPassRef LLVMRustCreateModuleAddressSanitizerPass(bool Recover) {
96 const bool CompileKernel = false;
98 #if LLVM_VERSION_GE(9, 0)
99 return wrap(createModuleAddressSanitizerLegacyPassPass(CompileKernel, Recover));
101 return wrap(createAddressSanitizerModulePass(CompileKernel, Recover));
105 extern "C" LLVMPassRef LLVMRustCreateMemorySanitizerPass(int TrackOrigins, bool Recover) {
106 #if LLVM_VERSION_GE(9, 0)
107 const bool CompileKernel = false;
109 return wrap(createMemorySanitizerLegacyPassPass(
110 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
111 #elif LLVM_VERSION_GE(8, 0)
112 return wrap(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover));
114 return wrap(createMemorySanitizerPass(TrackOrigins, Recover));
118 extern "C" LLVMPassRef LLVMRustCreateThreadSanitizerPass() {
119 #if LLVM_VERSION_GE(8, 0)
120 return wrap(createThreadSanitizerLegacyPassPass());
122 return wrap(createThreadSanitizerPass());
126 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
128 Pass *Pass = unwrap(RustPass);
129 return toRust(Pass->getPassKind());
132 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
134 Pass *Pass = unwrap(RustPass);
135 PassManagerBase *PMB = unwrap(PMR);
140 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
141 LLVMPassManagerBuilderRef PMBR,
142 LLVMPassManagerRef PMR
144 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
148 void LLVMRustAddLastExtensionPasses(
149 LLVMPassManagerBuilderRef PMBR, LLVMPassRef *Passes, size_t NumPasses) {
150 auto AddExtensionPasses = [Passes, NumPasses](
151 const PassManagerBuilder &Builder, PassManagerBase &PM) {
152 for (size_t I = 0; I < NumPasses; I++) {
153 PM.add(unwrap(Passes[I]));
156 // Add the passes to both of the pre-finalization extension points,
157 // so they are run for optimized and non-optimized builds.
158 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_OptimizerLast,
160 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
164 #ifdef LLVM_COMPONENT_X86
165 #define SUBTARGET_X86 SUBTARGET(X86)
167 #define SUBTARGET_X86
170 #ifdef LLVM_COMPONENT_ARM
171 #define SUBTARGET_ARM SUBTARGET(ARM)
173 #define SUBTARGET_ARM
176 #ifdef LLVM_COMPONENT_AARCH64
177 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
179 #define SUBTARGET_AARCH64
182 #ifdef LLVM_COMPONENT_MIPS
183 #define SUBTARGET_MIPS SUBTARGET(Mips)
185 #define SUBTARGET_MIPS
188 #ifdef LLVM_COMPONENT_POWERPC
189 #define SUBTARGET_PPC SUBTARGET(PPC)
191 #define SUBTARGET_PPC
194 #ifdef LLVM_COMPONENT_SYSTEMZ
195 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
197 #define SUBTARGET_SYSTEMZ
200 #ifdef LLVM_COMPONENT_MSP430
201 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
203 #define SUBTARGET_MSP430
206 #ifdef LLVM_COMPONENT_RISCV
207 #define SUBTARGET_RISCV SUBTARGET(RISCV)
209 #define SUBTARGET_RISCV
212 #ifdef LLVM_COMPONENT_SPARC
213 #define SUBTARGET_SPARC SUBTARGET(Sparc)
215 #define SUBTARGET_SPARC
218 #ifdef LLVM_COMPONENT_HEXAGON
219 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
221 #define SUBTARGET_HEXAGON
224 #define GEN_SUBTARGETS \
236 #define SUBTARGET(x) \
238 extern const SubtargetFeatureKV x##FeatureKV[]; \
239 extern const SubtargetFeatureKV x##SubTypeKV[]; \
245 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
246 const char *Feature) {
247 TargetMachine *Target = unwrap(TM);
248 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
249 return MCInfo->checkFeatures(std::string("+") + Feature);
252 enum class LLVMRustCodeModel {
261 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
263 case LLVMRustCodeModel::Small:
264 return CodeModel::Small;
265 case LLVMRustCodeModel::Kernel:
266 return CodeModel::Kernel;
267 case LLVMRustCodeModel::Medium:
268 return CodeModel::Medium;
269 case LLVMRustCodeModel::Large:
270 return CodeModel::Large;
272 report_fatal_error("Bad CodeModel.");
276 enum class LLVMRustCodeGenOptLevel {
284 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
286 case LLVMRustCodeGenOptLevel::None:
287 return CodeGenOpt::None;
288 case LLVMRustCodeGenOptLevel::Less:
289 return CodeGenOpt::Less;
290 case LLVMRustCodeGenOptLevel::Default:
291 return CodeGenOpt::Default;
292 case LLVMRustCodeGenOptLevel::Aggressive:
293 return CodeGenOpt::Aggressive;
295 report_fatal_error("Bad CodeGenOptLevel.");
299 enum class LLVMRustRelocMode {
309 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
311 case LLVMRustRelocMode::Default:
313 case LLVMRustRelocMode::Static:
314 return Reloc::Static;
315 case LLVMRustRelocMode::PIC:
317 case LLVMRustRelocMode::DynamicNoPic:
318 return Reloc::DynamicNoPIC;
319 case LLVMRustRelocMode::ROPI:
321 case LLVMRustRelocMode::RWPI:
323 case LLVMRustRelocMode::ROPIRWPI:
324 return Reloc::ROPI_RWPI;
326 report_fatal_error("Bad RelocModel.");
330 /// getLongestEntryLength - Return the length of the longest entry in the table.
331 template<typename KV>
332 static size_t getLongestEntryLength(ArrayRef<KV> Table) {
334 for (auto &I : Table)
335 MaxLen = std::max(MaxLen, std::strlen(I.Key));
339 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
340 const TargetMachine *Target = unwrap(TM);
341 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
342 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
343 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
344 const ArrayRef<SubtargetSubTypeKV> CPUTable = MCInfo->getCPUTable();
345 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
347 printf("Available CPUs for this target:\n");
348 if (HostArch == TargetArch) {
349 const StringRef HostCPU = sys::getHostCPUName();
350 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
351 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
353 for (auto &CPU : CPUTable)
354 printf(" %-*s\n", MaxCPULen, CPU.Key);
358 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
359 const TargetMachine *Target = unwrap(TM);
360 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
361 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
362 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
364 printf("Available features for this target:\n");
365 for (auto &Feature : FeatTable)
366 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
369 printf("Use +feature to enable a feature, or -feature to disable it.\n"
370 "For example, rustc -C -target-cpu=mycpu -C "
371 "target-feature=+feature1,-feature2\n\n");
376 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
377 printf("Target CPU help is not supported by this LLVM version.\n\n");
380 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
381 printf("Target features help is not supported by this LLVM version.\n\n");
385 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
386 StringRef Name = sys::getHostCPUName();
391 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
392 const char *TripleStr, const char *CPU, const char *Feature,
393 const char *ABIStr, LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
394 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
395 bool PositionIndependentExecutable, bool FunctionSections,
397 bool TrapUnreachable,
400 bool EmitStackSizeSection,
401 bool RelaxELFRelocations) {
403 auto OptLevel = fromRust(RustOptLevel);
404 auto RM = fromRust(RustReloc);
407 Triple Trip(Triple::normalize(TripleStr));
408 const llvm::Target *TheTarget =
409 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
410 if (TheTarget == nullptr) {
411 LLVMRustSetLastError(Error.c_str());
415 TargetOptions Options;
417 Options.FloatABIType = FloatABI::Default;
419 Options.FloatABIType = FloatABI::Soft;
421 Options.DataSections = DataSections;
422 Options.FunctionSections = FunctionSections;
423 Options.MCOptions.AsmVerbose = AsmComments;
424 Options.MCOptions.PreserveAsmComments = AsmComments;
425 Options.MCOptions.ABIName = ABIStr;
426 Options.RelaxELFRelocations = RelaxELFRelocations;
428 if (TrapUnreachable) {
429 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
430 // This limits the extent of possible undefined behavior in some cases, as
431 // it prevents control flow from "falling through" into whatever code
432 // happens to be laid out next in memory.
433 Options.TrapUnreachable = true;
437 Options.ThreadModel = ThreadModel::Single;
440 Options.EmitStackSizeSection = EmitStackSizeSection;
442 Optional<CodeModel::Model> CM;
443 if (RustCM != LLVMRustCodeModel::None)
444 CM = fromRust(RustCM);
445 TargetMachine *TM = TheTarget->createTargetMachine(
446 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
450 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
454 extern "C" void LLVMRustConfigurePassManagerBuilder(
455 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
456 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
457 const char* PGOGenPath, const char* PGOUsePath) {
458 unwrap(PMBR)->MergeFunctions = MergeFunctions;
459 unwrap(PMBR)->SLPVectorize = SLPVectorize;
460 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
461 unwrap(PMBR)->LoopVectorize = LoopVectorize;
462 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
466 unwrap(PMBR)->EnablePGOInstrGen = true;
467 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
471 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
475 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
476 // field of a PassManagerBuilder, we expose our own method of doing so.
477 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
479 bool DisableSimplifyLibCalls) {
480 Triple TargetTriple(unwrap(M)->getTargetTriple());
481 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
482 if (DisableSimplifyLibCalls)
483 TLI->disableAllFunctions();
484 unwrap(PMBR)->LibraryInfo = TLI;
487 // Unfortunately, the LLVM C API doesn't provide a way to create the
488 // TargetLibraryInfo pass, so we use this method to do so.
489 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
490 bool DisableSimplifyLibCalls) {
491 Triple TargetTriple(unwrap(M)->getTargetTriple());
492 TargetLibraryInfoImpl TLII(TargetTriple);
493 if (DisableSimplifyLibCalls)
494 TLII.disableAllFunctions();
495 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
498 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
499 // all the functions in a module, so we do that manually here. You'll find
500 // similar code in clang's BackendUtil.cpp file.
501 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
503 llvm::legacy::FunctionPassManager *P =
504 unwrap<llvm::legacy::FunctionPassManager>(PMR);
505 P->doInitialization();
507 // Upgrade all calls to old intrinsics first.
508 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
509 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
511 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
513 if (!I->isDeclaration())
519 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
520 // Initializing the command-line options more than once is not allowed. So,
521 // check if they've already been initialized. (This could happen if we're
522 // being called from rustpkg, for example). If the arguments change, then
523 // that's just kinda unfortunate.
524 static bool Initialized = false;
528 cl::ParseCommandLineOptions(Argc, Argv);
531 enum class LLVMRustFileType {
537 #if LLVM_VERSION_GE(10, 0)
538 static CodeGenFileType fromRust(LLVMRustFileType Type) {
540 case LLVMRustFileType::AssemblyFile:
541 return CGFT_AssemblyFile;
542 case LLVMRustFileType::ObjectFile:
543 return CGFT_ObjectFile;
545 report_fatal_error("Bad FileType.");
549 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
551 case LLVMRustFileType::AssemblyFile:
552 return TargetMachine::CGFT_AssemblyFile;
553 case LLVMRustFileType::ObjectFile:
554 return TargetMachine::CGFT_ObjectFile;
556 report_fatal_error("Bad FileType.");
561 extern "C" LLVMRustResult
562 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
563 LLVMModuleRef M, const char *Path,
564 LLVMRustFileType RustFileType) {
565 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
566 auto FileType = fromRust(RustFileType);
568 std::string ErrorInfo;
570 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
572 ErrorInfo = EC.message();
573 if (ErrorInfo != "") {
574 LLVMRustSetLastError(ErrorInfo.c_str());
575 return LLVMRustResult::Failure;
578 buffer_ostream BOS(OS);
579 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
582 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
583 // stream (OS), so the only real safe place to delete this is here? Don't we
584 // wish this was written in Rust?
585 LLVMDisposePassManager(PMR);
586 return LLVMRustResult::Success;
590 // Callback to demangle function name
592 // * name to be demangled
595 // * output buffer len
596 // Returns len of demangled string, or 0 if demangle failed.
597 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
602 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
604 std::vector<char> Buf;
607 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
609 // Return empty string if demangle failed
610 // or if name does not need to be demangled
611 StringRef CallDemangle(StringRef name) {
616 if (Buf.size() < name.size() * 2) {
617 // Semangled name usually shorter than mangled,
618 // but allocate twice as much memory just in case
619 Buf.resize(name.size() * 2);
622 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
628 auto Demangled = StringRef(Buf.data(), R);
629 if (Demangled == name) {
630 // Do not print anything if demangled name is equal to mangled.
637 void emitFunctionAnnot(const Function *F,
638 formatted_raw_ostream &OS) override {
639 StringRef Demangled = CallDemangle(F->getName());
640 if (Demangled.empty()) {
644 OS << "; " << Demangled << "\n";
647 void emitInstructionAnnot(const Instruction *I,
648 formatted_raw_ostream &OS) override {
651 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
653 Value = CI->getCalledValue();
654 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
656 Value = II->getCalledValue();
658 // Could demangle more operations, e. g.
659 // `store %place, @function`.
663 if (!Value->hasName()) {
667 StringRef Demangled = CallDemangle(Value->getName());
668 if (Demangled.empty()) {
672 OS << "; " << Name << " " << Demangled << "\n";
678 extern "C" LLVMRustResult
679 LLVMRustPrintModule(LLVMModuleRef M, const char *Path, DemangleFn Demangle) {
680 std::string ErrorInfo;
682 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
684 ErrorInfo = EC.message();
685 if (ErrorInfo != "") {
686 LLVMRustSetLastError(ErrorInfo.c_str());
687 return LLVMRustResult::Failure;
690 RustAssemblyAnnotationWriter AAW(Demangle);
691 formatted_raw_ostream FOS(OS);
692 unwrap(M)->print(FOS, &AAW);
694 return LLVMRustResult::Success;
697 extern "C" void LLVMRustPrintPasses() {
698 LLVMInitializePasses();
699 struct MyListener : PassRegistrationListener {
700 void passEnumerate(const PassInfo *Info) {
701 StringRef PassArg = Info->getPassArgument();
702 StringRef PassName = Info->getPassName();
703 if (!PassArg.empty()) {
704 // These unsigned->signed casts could theoretically overflow, but
705 // realistically never will (and even if, the result is implementation
706 // defined rather plain UB).
707 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
708 (int)PassName.size(), PassName.data());
713 PassRegistry *PR = PassRegistry::getPassRegistry();
714 PR->enumerateWith(&Listener);
717 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
719 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
722 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
724 llvm::legacy::PassManager passes;
726 auto PreserveFunctions = [=](const GlobalValue &GV) {
727 for (size_t I = 0; I < Len; I++) {
728 if (GV.getName() == Symbols[I]) {
735 passes.add(llvm::createInternalizePass(PreserveFunctions));
737 passes.run(*unwrap(M));
740 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
741 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
743 GV->setDoesNotThrow();
744 Function *F = dyn_cast<Function>(GV);
748 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
749 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
750 if (isa<InvokeInst>(I)) {
751 InvokeInst *CI = cast<InvokeInst>(I);
752 CI->setDoesNotThrow();
760 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
761 LLVMTargetMachineRef TMR) {
762 TargetMachine *Target = unwrap(TMR);
763 unwrap(Module)->setDataLayout(Target->createDataLayout());
766 extern "C" void LLVMRustSetModulePICLevel(LLVMModuleRef M) {
767 unwrap(M)->setPICLevel(PICLevel::Level::BigPIC);
770 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
771 unwrap(M)->setPIELevel(PIELevel::Level::Large);
774 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
775 // right now. This ThinLTO support is only enabled on "recent ish" versions of
776 // LLVM, and otherwise it's just blanket rejected from other compilers.
778 // Most of this implementation is straight copied from LLVM. At the time of
779 // this writing it wasn't *quite* suitable to reuse more code from upstream
780 // for our purposes, but we should strive to upstream this support once it's
781 // ready to go! I figure we may want a bit of testing locally first before
782 // sending this upstream to LLVM. I hear though they're quite eager to receive
783 // feedback like this!
785 // If you're reading this code and wondering "what in the world" or you're
786 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
787 // then fear not! (ok maybe fear a little). All code here is mostly based
788 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
790 // You'll find that the general layout here roughly corresponds to the `run`
791 // method in that file as well as `ProcessThinLTOModule`. Functions are
792 // specifically commented below as well, but if you're updating this code
793 // or otherwise trying to understand it, the LLVM source will be useful in
794 // interpreting the mysteries within.
796 // Otherwise I'll apologize in advance, it probably requires a relatively
797 // significant investment on your part to "truly understand" what's going on
798 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
799 // and various online resources about ThinLTO to make heads or tails of all
802 // This is a shared data structure which *must* be threadsafe to share
803 // read-only amongst threads. This also corresponds basically to the arguments
804 // of the `ProcessThinLTOModule` function in the LLVM source.
805 struct LLVMRustThinLTOData {
806 // The combined index that is the global analysis over all modules we're
807 // performing ThinLTO for. This is mostly managed by LLVM.
808 ModuleSummaryIndex Index;
810 // All modules we may look at, stored as in-memory serialized versions. This
811 // is later used when inlining to ensure we can extract any module to inline
813 StringMap<MemoryBufferRef> ModuleMap;
815 // A set that we manage of everything we *don't* want internalized. Note that
816 // this includes all transitive references right now as well, but it may not
818 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
820 // Not 100% sure what these are, but they impact what's internalized and
821 // what's inlined across modules, I believe.
822 StringMap<FunctionImporter::ImportMapTy> ImportLists;
823 StringMap<FunctionImporter::ExportSetTy> ExportLists;
824 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
826 LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {}
829 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
830 struct LLVMRustThinLTOModule {
831 const char *identifier;
836 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
838 static const GlobalValueSummary *
839 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
840 auto StrongDefForLinker = llvm::find_if(
841 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
842 auto Linkage = Summary->linkage();
843 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
844 !GlobalValue::isWeakForLinker(Linkage);
846 if (StrongDefForLinker != GVSummaryList.end())
847 return StrongDefForLinker->get();
849 auto FirstDefForLinker = llvm::find_if(
850 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
851 auto Linkage = Summary->linkage();
852 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
854 if (FirstDefForLinker == GVSummaryList.end())
856 return FirstDefForLinker->get();
859 // The main entry point for creating the global ThinLTO analysis. The structure
860 // here is basically the same as before threads are spawned in the `run`
861 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
862 extern "C" LLVMRustThinLTOData*
863 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
865 const char **preserved_symbols,
867 #if LLVM_VERSION_GE(10, 0)
868 auto Ret = std::make_unique<LLVMRustThinLTOData>();
870 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
873 // Load each module's summary and merge it into one combined index
874 for (int i = 0; i < num_modules; i++) {
875 auto module = &modules[i];
876 StringRef buffer(module->data, module->len);
877 MemoryBufferRef mem_buffer(buffer, module->identifier);
879 Ret->ModuleMap[module->identifier] = mem_buffer;
881 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
882 LLVMRustSetLastError(toString(std::move(Err)).c_str());
887 // Collect for each module the list of function it defines (GUID -> Summary)
888 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
890 // Convert the preserved symbols set from string to GUID, this is then needed
891 // for internalization.
892 for (int i = 0; i < num_symbols; i++) {
893 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
894 Ret->GUIDPreservedSymbols.insert(GUID);
897 // Collect the import/export lists for all modules from the call-graph in the
900 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
901 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
902 return PrevailingType::Unknown;
904 #if LLVM_VERSION_GE(8, 0)
905 // We don't have a complete picture in our use of ThinLTO, just our immediate
906 // crate, so we need `ImportEnabled = false` to limit internalization.
907 // Otherwise, we sometimes lose `static` values -- see #60184.
908 computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
909 deadIsPrevailing, /* ImportEnabled = */ false);
911 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
913 ComputeCrossModuleImport(
915 Ret->ModuleToDefinedGVSummaries,
920 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
921 // impacts the caching.
923 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
924 // being lifted from `lib/LTO/LTO.cpp` as well
925 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
926 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
927 for (auto &I : Ret->Index) {
928 if (I.second.SummaryList.size() > 1)
929 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
931 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
932 const auto &Prevailing = PrevailingCopy.find(GUID);
933 if (Prevailing == PrevailingCopy.end())
935 return Prevailing->second == S;
937 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
938 GlobalValue::GUID GUID,
939 GlobalValue::LinkageTypes NewLinkage) {
940 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
942 #if LLVM_VERSION_GE(9, 0)
943 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage,
944 Ret->GUIDPreservedSymbols);
945 #elif LLVM_VERSION_GE(8, 0)
946 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
948 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
951 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
952 // callback below. This callback below will dictate the linkage for all
953 // summaries in the index, and we basically just only want to ensure that dead
954 // symbols are internalized. Otherwise everything that's already external
955 // linkage will stay as external, and internal will stay as internal.
956 std::set<GlobalValue::GUID> ExportedGUIDs;
957 for (auto &List : Ret->Index) {
958 for (auto &GVS: List.second.SummaryList) {
959 if (GlobalValue::isLocalLinkage(GVS->linkage()))
961 auto GUID = GVS->getOriginalName();
962 if (GVS->flags().Live)
963 ExportedGUIDs.insert(GUID);
966 #if LLVM_VERSION_GE(10, 0)
967 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
968 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
969 return (ExportList != Ret->ExportLists.end() &&
970 ExportList->second.count(VI)) ||
971 ExportedGUIDs.count(VI.getGUID());
973 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported, isPrevailing);
975 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
976 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
977 return (ExportList != Ret->ExportLists.end() &&
978 ExportList->second.count(GUID)) ||
979 ExportedGUIDs.count(GUID);
981 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
984 return Ret.release();
988 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
992 // Below are the various passes that happen *per module* when doing ThinLTO.
994 // In other words, these are the functions that are all run concurrently
995 // with one another, one per module. The passes here correspond to the analysis
996 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
997 // `ProcessThinLTOModule` function. Here they're split up into separate steps
998 // so rustc can save off the intermediate bytecode between each step.
1001 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1002 Module &Mod = *unwrap(M);
1003 if (renameModuleForThinLTO(Mod, Data->Index)) {
1004 LLVMRustSetLastError("renameModuleForThinLTO failed");
1011 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1012 Module &Mod = *unwrap(M);
1013 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1014 #if LLVM_VERSION_GE(8, 0)
1015 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
1017 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1023 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1024 Module &Mod = *unwrap(M);
1025 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1026 thinLTOInternalizeModule(Mod, DefinedGlobals);
1031 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1032 Module &Mod = *unwrap(M);
1034 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1035 auto Loader = [&](StringRef Identifier) {
1036 const auto &Memory = Data->ModuleMap.lookup(Identifier);
1037 auto &Context = Mod.getContext();
1038 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1043 // The rest of this closure is a workaround for
1044 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1045 // we accidentally import wasm custom sections into different modules,
1046 // duplicating them by in the final output artifact.
1048 // The issue is worked around here by manually removing the
1049 // `wasm.custom_sections` named metadata node from any imported module. This
1050 // we know isn't used by any optimization pass so there's no need for it to
1053 // Note that the metadata is currently lazily loaded, so we materialize it
1054 // here before looking up if there's metadata inside. The `FunctionImporter`
1055 // will immediately materialize metadata anyway after an import, so this
1056 // shouldn't be a perf hit.
1057 if (Error Err = (*MOrErr)->materializeMetadata()) {
1058 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1062 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1063 if (WasmCustomSections)
1064 WasmCustomSections->eraseFromParent();
1068 FunctionImporter Importer(Data->Index, Loader);
1069 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1071 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1077 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1078 const char*, // importing module name
1079 const char*); // imported module name
1081 // Calls `module_name_callback` for each module import done by ThinLTO.
1082 // The callback is provided with regular null-terminated C strings.
1084 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1085 LLVMRustModuleNameCallback module_name_callback,
1086 void* callback_payload) {
1087 for (const auto& importing_module : data->ImportLists) {
1088 const std::string importing_module_id = importing_module.getKey().str();
1089 const auto& imports = importing_module.getValue();
1090 for (const auto& imported_module : imports) {
1091 const std::string imported_module_id = imported_module.getKey().str();
1092 module_name_callback(callback_payload,
1093 importing_module_id.c_str(),
1094 imported_module_id.c_str());
1099 // This struct and various functions are sort of a hack right now, but the
1100 // problem is that we've got in-memory LLVM modules after we generate and
1101 // optimize all codegen-units for one compilation in rustc. To be compatible
1102 // with the LTO support above we need to serialize the modules plus their
1103 // ThinLTO summary into memory.
1105 // This structure is basically an owned version of a serialize module, with
1106 // a ThinLTO summary attached.
1107 struct LLVMRustThinLTOBuffer {
1111 extern "C" LLVMRustThinLTOBuffer*
1112 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1113 #if LLVM_VERSION_GE(10, 0)
1114 auto Ret = std::make_unique<LLVMRustThinLTOBuffer>();
1116 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1119 raw_string_ostream OS(Ret->data);
1121 legacy::PassManager PM;
1122 PM.add(createWriteThinLTOBitcodePass(OS));
1126 return Ret.release();
1130 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1134 extern "C" const void*
1135 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1136 return Buffer->data.data();
1140 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1141 return Buffer->data.length();
1144 // This is what we used to parse upstream bitcode for actual ThinLTO
1145 // processing. We'll call this once per module optimized through ThinLTO, and
1146 // it'll be called concurrently on many threads.
1147 extern "C" LLVMModuleRef
1148 LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1151 const char *identifier) {
1152 StringRef Data(data, len);
1153 MemoryBufferRef Buffer(Data, identifier);
1154 unwrap(Context)->enableDebugTypeODRUniquing();
1155 Expected<std::unique_ptr<Module>> SrcOrError =
1156 parseBitcodeFile(Buffer, *unwrap(Context));
1158 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1161 return wrap(std::move(*SrcOrError).release());
1164 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1165 // the comment in `back/lto.rs` for why this exists.
1167 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1169 DICompileUnit **B) {
1170 Module *M = unwrap(Mod);
1171 DICompileUnit **Cur = A;
1172 DICompileUnit **Next = B;
1173 for (DICompileUnit *CU : M->debug_compile_units()) {
1182 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1183 // the comment in `back/lto.rs` for why this exists.
1185 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1186 Module *M = unwrap(Mod);
1188 // If the original source module didn't have a `DICompileUnit` then try to
1189 // merge all the existing compile units. If there aren't actually any though
1190 // then there's not much for us to do so return.
1191 if (Unit == nullptr) {
1192 for (DICompileUnit *CU : M->debug_compile_units()) {
1196 if (Unit == nullptr)
1200 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1201 // process it recursively. Note that we specifically iterate over instructions
1202 // to ensure we feed everything into it.
1203 DebugInfoFinder Finder;
1204 Finder.processModule(*M);
1205 for (Function &F : M->functions()) {
1206 for (auto &FI : F) {
1207 for (Instruction &BI : FI) {
1208 if (auto Loc = BI.getDebugLoc())
1209 Finder.processLocation(*M, Loc);
1210 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1211 Finder.processValue(*M, DVI);
1212 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1213 Finder.processDeclare(*M, DDI);
1218 // After we've found all our debuginfo, rewrite all subprograms to point to
1219 // the same `DICompileUnit`.
1220 for (auto &F : Finder.subprograms()) {
1221 F->replaceUnit(Unit);
1224 // Erase any other references to other `DICompileUnit` instances, the verifier
1225 // will later ensure that we don't actually have any other stale references to
1227 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1228 MD->clearOperands();
1229 MD->addOperand(Unit);