]> git.lizzy.rs Git - rust.git/blob - src/rustllvm/PassWrapper.cpp
Auto merge of #58406 - Disasm:rv64-support, r=nagisa
[rust.git] / src / rustllvm / PassWrapper.cpp
1 #include <stdio.h>
2
3 #include <vector>
4 #include <set>
5
6 #include "rustllvm.h"
7
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
24 #include "llvm-c/Transforms/PassManagerBuilder.h"
25
26 using namespace llvm;
27 using namespace llvm::legacy;
28
29 extern cl::opt<bool> EnableARMEHABI;
30
31 typedef struct LLVMOpaquePass *LLVMPassRef;
32 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
33
34 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
35 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
36 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
37                                    LLVMPassManagerBuilderRef)
38
39 extern "C" void LLVMInitializePasses() {
40   PassRegistry &Registry = *PassRegistry::getPassRegistry();
41   initializeCore(Registry);
42   initializeCodeGen(Registry);
43   initializeScalarOpts(Registry);
44   initializeVectorization(Registry);
45   initializeIPO(Registry);
46   initializeAnalysis(Registry);
47   initializeTransformUtils(Registry);
48   initializeInstCombine(Registry);
49   initializeInstrumentation(Registry);
50   initializeTarget(Registry);
51 }
52
53 enum class LLVMRustPassKind {
54   Other,
55   Function,
56   Module,
57 };
58
59 static LLVMRustPassKind toRust(PassKind Kind) {
60   switch (Kind) {
61   case PT_Function:
62     return LLVMRustPassKind::Function;
63   case PT_Module:
64     return LLVMRustPassKind::Module;
65   default:
66     return LLVMRustPassKind::Other;
67   }
68 }
69
70 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
71   StringRef SR(PassName);
72   PassRegistry *PR = PassRegistry::getPassRegistry();
73
74   const PassInfo *PI = PR->getPassInfo(SR);
75   if (PI) {
76     return wrap(PI->createPass());
77   }
78   return nullptr;
79 }
80
81 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
82   assert(RustPass);
83   Pass *Pass = unwrap(RustPass);
84   return toRust(Pass->getPassKind());
85 }
86
87 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
88   assert(RustPass);
89   Pass *Pass = unwrap(RustPass);
90   PassManagerBase *PMB = unwrap(PMR);
91   PMB->add(Pass);
92 }
93
94 extern "C"
95 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
96   LLVMPassManagerBuilderRef PMBR,
97   LLVMPassManagerRef PMR
98 ) {
99   unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
100 }
101
102 #ifdef LLVM_COMPONENT_X86
103 #define SUBTARGET_X86 SUBTARGET(X86)
104 #else
105 #define SUBTARGET_X86
106 #endif
107
108 #ifdef LLVM_COMPONENT_ARM
109 #define SUBTARGET_ARM SUBTARGET(ARM)
110 #else
111 #define SUBTARGET_ARM
112 #endif
113
114 #ifdef LLVM_COMPONENT_AARCH64
115 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
116 #else
117 #define SUBTARGET_AARCH64
118 #endif
119
120 #ifdef LLVM_COMPONENT_MIPS
121 #define SUBTARGET_MIPS SUBTARGET(Mips)
122 #else
123 #define SUBTARGET_MIPS
124 #endif
125
126 #ifdef LLVM_COMPONENT_POWERPC
127 #define SUBTARGET_PPC SUBTARGET(PPC)
128 #else
129 #define SUBTARGET_PPC
130 #endif
131
132 #ifdef LLVM_COMPONENT_SYSTEMZ
133 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
134 #else
135 #define SUBTARGET_SYSTEMZ
136 #endif
137
138 #ifdef LLVM_COMPONENT_MSP430
139 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
140 #else
141 #define SUBTARGET_MSP430
142 #endif
143
144 #ifdef LLVM_COMPONENT_RISCV
145 #define SUBTARGET_RISCV SUBTARGET(RISCV)
146 #else
147 #define SUBTARGET_RISCV
148 #endif
149
150 #ifdef LLVM_COMPONENT_SPARC
151 #define SUBTARGET_SPARC SUBTARGET(Sparc)
152 #else
153 #define SUBTARGET_SPARC
154 #endif
155
156 #ifdef LLVM_COMPONENT_HEXAGON
157 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
158 #else
159 #define SUBTARGET_HEXAGON
160 #endif
161
162 #define GEN_SUBTARGETS                                                         \
163   SUBTARGET_X86                                                                \
164   SUBTARGET_ARM                                                                \
165   SUBTARGET_AARCH64                                                            \
166   SUBTARGET_MIPS                                                               \
167   SUBTARGET_PPC                                                                \
168   SUBTARGET_SYSTEMZ                                                            \
169   SUBTARGET_MSP430                                                             \
170   SUBTARGET_SPARC                                                              \
171   SUBTARGET_HEXAGON                                                            \
172   SUBTARGET_RISCV                                                              \
173
174 #define SUBTARGET(x)                                                           \
175   namespace llvm {                                                             \
176   extern const SubtargetFeatureKV x##FeatureKV[];                              \
177   extern const SubtargetFeatureKV x##SubTypeKV[];                              \
178   }
179
180 GEN_SUBTARGETS
181 #undef SUBTARGET
182
183 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
184                                    const char *Feature) {
185   TargetMachine *Target = unwrap(TM);
186   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
187   return MCInfo->checkFeatures(std::string("+") + Feature);
188 }
189
190 enum class LLVMRustCodeModel {
191   Other,
192   Small,
193   Kernel,
194   Medium,
195   Large,
196   None,
197 };
198
199 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
200   switch (Model) {
201   case LLVMRustCodeModel::Small:
202     return CodeModel::Small;
203   case LLVMRustCodeModel::Kernel:
204     return CodeModel::Kernel;
205   case LLVMRustCodeModel::Medium:
206     return CodeModel::Medium;
207   case LLVMRustCodeModel::Large:
208     return CodeModel::Large;
209   default:
210     report_fatal_error("Bad CodeModel.");
211   }
212 }
213
214 enum class LLVMRustCodeGenOptLevel {
215   Other,
216   None,
217   Less,
218   Default,
219   Aggressive,
220 };
221
222 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
223   switch (Level) {
224   case LLVMRustCodeGenOptLevel::None:
225     return CodeGenOpt::None;
226   case LLVMRustCodeGenOptLevel::Less:
227     return CodeGenOpt::Less;
228   case LLVMRustCodeGenOptLevel::Default:
229     return CodeGenOpt::Default;
230   case LLVMRustCodeGenOptLevel::Aggressive:
231     return CodeGenOpt::Aggressive;
232   default:
233     report_fatal_error("Bad CodeGenOptLevel.");
234   }
235 }
236
237 enum class LLVMRustRelocMode {
238   Default,
239   Static,
240   PIC,
241   DynamicNoPic,
242   ROPI,
243   RWPI,
244   ROPIRWPI,
245 };
246
247 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
248   switch (RustReloc) {
249   case LLVMRustRelocMode::Default:
250     return None;
251   case LLVMRustRelocMode::Static:
252     return Reloc::Static;
253   case LLVMRustRelocMode::PIC:
254     return Reloc::PIC_;
255   case LLVMRustRelocMode::DynamicNoPic:
256     return Reloc::DynamicNoPIC;
257   case LLVMRustRelocMode::ROPI:
258     return Reloc::ROPI;
259   case LLVMRustRelocMode::RWPI:
260     return Reloc::RWPI;
261   case LLVMRustRelocMode::ROPIRWPI:
262     return Reloc::ROPI_RWPI;
263   }
264   report_fatal_error("Bad RelocModel.");
265 }
266
267 #ifdef LLVM_RUSTLLVM
268 /// getLongestEntryLength - Return the length of the longest entry in the table.
269 ///
270 static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
271   size_t MaxLen = 0;
272   for (auto &I : Table)
273     MaxLen = std::max(MaxLen, std::strlen(I.Key));
274   return MaxLen;
275 }
276
277 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
278   const TargetMachine *Target = unwrap(TM);
279   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
280   const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
281   const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
282   const ArrayRef<SubtargetFeatureKV> CPUTable = MCInfo->getCPUTable();
283   unsigned MaxCPULen = getLongestEntryLength(CPUTable);
284
285   printf("Available CPUs for this target:\n");
286   if (HostArch == TargetArch) {
287     const StringRef HostCPU = sys::getHostCPUName();
288     printf("    %-*s - Select the CPU of the current host (currently %.*s).\n",
289       MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
290   }
291   for (auto &CPU : CPUTable)
292     printf("    %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
293   printf("\n");
294 }
295
296 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
297   const TargetMachine *Target = unwrap(TM);
298   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
299   const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
300   unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
301
302   printf("Available features for this target:\n");
303   for (auto &Feature : FeatTable)
304     printf("    %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
305   printf("\n");
306
307   printf("Use +feature to enable a feature, or -feature to disable it.\n"
308          "For example, rustc -C -target-cpu=mycpu -C "
309          "target-feature=+feature1,-feature2\n\n");
310 }
311
312 #else
313
314 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
315   printf("Target CPU help is not supported by this LLVM version.\n\n");
316 }
317
318 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
319   printf("Target features help is not supported by this LLVM version.\n\n");
320 }
321 #endif
322
323 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
324   StringRef Name = sys::getHostCPUName();
325   *len = Name.size();
326   return Name.data();
327 }
328
329 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
330     const char *TripleStr, const char *CPU, const char *Feature,
331     LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
332     LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
333     bool PositionIndependentExecutable, bool FunctionSections,
334     bool DataSections,
335     bool TrapUnreachable,
336     bool Singlethread,
337     bool AsmComments,
338     bool EmitStackSizeSection) {
339
340   auto OptLevel = fromRust(RustOptLevel);
341   auto RM = fromRust(RustReloc);
342
343   std::string Error;
344   Triple Trip(Triple::normalize(TripleStr));
345   const llvm::Target *TheTarget =
346       TargetRegistry::lookupTarget(Trip.getTriple(), Error);
347   if (TheTarget == nullptr) {
348     LLVMRustSetLastError(Error.c_str());
349     return nullptr;
350   }
351
352   TargetOptions Options;
353
354   Options.FloatABIType = FloatABI::Default;
355   if (UseSoftFloat) {
356     Options.FloatABIType = FloatABI::Soft;
357   }
358   Options.DataSections = DataSections;
359   Options.FunctionSections = FunctionSections;
360   Options.MCOptions.AsmVerbose = AsmComments;
361   Options.MCOptions.PreserveAsmComments = AsmComments;
362
363   if (TrapUnreachable) {
364     // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
365     // This limits the extent of possible undefined behavior in some cases, as
366     // it prevents control flow from "falling through" into whatever code
367     // happens to be laid out next in memory.
368     Options.TrapUnreachable = true;
369   }
370
371   if (Singlethread) {
372     Options.ThreadModel = ThreadModel::Single;
373   }
374
375   Options.EmitStackSizeSection = EmitStackSizeSection;
376
377   Optional<CodeModel::Model> CM;
378   if (RustCM != LLVMRustCodeModel::None)
379     CM = fromRust(RustCM);
380   TargetMachine *TM = TheTarget->createTargetMachine(
381       Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
382   return wrap(TM);
383 }
384
385 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
386   delete unwrap(TM);
387 }
388
389 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
390 // passes for a target to a pass manager. We export that functionality through
391 // this function.
392 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
393                                           LLVMPassManagerRef PMR,
394                                           LLVMModuleRef M) {
395   PassManagerBase *PM = unwrap(PMR);
396   PM->add(
397       createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
398 }
399
400 extern "C" void LLVMRustConfigurePassManagerBuilder(
401     LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
402     bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
403     const char* PGOGenPath, const char* PGOUsePath) {
404 #if LLVM_VERSION_GE(7, 0)
405   unwrap(PMBR)->MergeFunctions = MergeFunctions;
406 #endif
407   unwrap(PMBR)->SLPVectorize = SLPVectorize;
408   unwrap(PMBR)->OptLevel = fromRust(OptLevel);
409   unwrap(PMBR)->LoopVectorize = LoopVectorize;
410   unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
411
412   if (PGOGenPath) {
413     assert(!PGOUsePath);
414     unwrap(PMBR)->EnablePGOInstrGen = true;
415     unwrap(PMBR)->PGOInstrGen = PGOGenPath;
416   }
417   if (PGOUsePath) {
418     assert(!PGOGenPath);
419     unwrap(PMBR)->PGOInstrUse = PGOUsePath;
420   }
421 }
422
423 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
424 // field of a PassManagerBuilder, we expose our own method of doing so.
425 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
426                                               LLVMModuleRef M,
427                                               bool DisableSimplifyLibCalls) {
428   Triple TargetTriple(unwrap(M)->getTargetTriple());
429   TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
430   if (DisableSimplifyLibCalls)
431     TLI->disableAllFunctions();
432   unwrap(PMBR)->LibraryInfo = TLI;
433 }
434
435 // Unfortunately, the LLVM C API doesn't provide a way to create the
436 // TargetLibraryInfo pass, so we use this method to do so.
437 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
438                                        bool DisableSimplifyLibCalls) {
439   Triple TargetTriple(unwrap(M)->getTargetTriple());
440   TargetLibraryInfoImpl TLII(TargetTriple);
441   if (DisableSimplifyLibCalls)
442     TLII.disableAllFunctions();
443   unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
444 }
445
446 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
447 // all the functions in a module, so we do that manually here. You'll find
448 // similar code in clang's BackendUtil.cpp file.
449 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
450                                                LLVMModuleRef M) {
451   llvm::legacy::FunctionPassManager *P =
452       unwrap<llvm::legacy::FunctionPassManager>(PMR);
453   P->doInitialization();
454
455   // Upgrade all calls to old intrinsics first.
456   for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
457     UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
458
459   for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
460        ++I)
461     if (!I->isDeclaration())
462       P->run(*I);
463
464   P->doFinalization();
465 }
466
467 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
468   // Initializing the command-line options more than once is not allowed. So,
469   // check if they've already been initialized.  (This could happen if we're
470   // being called from rustpkg, for example). If the arguments change, then
471   // that's just kinda unfortunate.
472   static bool Initialized = false;
473   if (Initialized)
474     return;
475   Initialized = true;
476   cl::ParseCommandLineOptions(Argc, Argv);
477 }
478
479 enum class LLVMRustFileType {
480   Other,
481   AssemblyFile,
482   ObjectFile,
483 };
484
485 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
486   switch (Type) {
487   case LLVMRustFileType::AssemblyFile:
488     return TargetMachine::CGFT_AssemblyFile;
489   case LLVMRustFileType::ObjectFile:
490     return TargetMachine::CGFT_ObjectFile;
491   default:
492     report_fatal_error("Bad FileType.");
493   }
494 }
495
496 extern "C" LLVMRustResult
497 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
498                         LLVMModuleRef M, const char *Path,
499                         LLVMRustFileType RustFileType) {
500   llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
501   auto FileType = fromRust(RustFileType);
502
503   std::string ErrorInfo;
504   std::error_code EC;
505   raw_fd_ostream OS(Path, EC, sys::fs::F_None);
506   if (EC)
507     ErrorInfo = EC.message();
508   if (ErrorInfo != "") {
509     LLVMRustSetLastError(ErrorInfo.c_str());
510     return LLVMRustResult::Failure;
511   }
512
513 #if LLVM_VERSION_GE(7, 0)
514   buffer_ostream BOS(OS);
515   unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
516 #else
517   unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
518 #endif
519   PM->run(*unwrap(M));
520
521   // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
522   // stream (OS), so the only real safe place to delete this is here? Don't we
523   // wish this was written in Rust?
524   delete PM;
525   return LLVMRustResult::Success;
526 }
527
528
529 // Callback to demangle function name
530 // Parameters:
531 // * name to be demangled
532 // * name len
533 // * output buffer
534 // * output buffer len
535 // Returns len of demangled string, or 0 if demangle failed.
536 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
537
538
539 namespace {
540
541 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
542   DemangleFn Demangle;
543   std::vector<char> Buf;
544
545 public:
546   RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
547
548   // Return empty string if demangle failed
549   // or if name does not need to be demangled
550   StringRef CallDemangle(StringRef name) {
551     if (!Demangle) {
552       return StringRef();
553     }
554
555     if (Buf.size() < name.size() * 2) {
556       // Semangled name usually shorter than mangled,
557       // but allocate twice as much memory just in case
558       Buf.resize(name.size() * 2);
559     }
560
561     auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
562     if (!R) {
563       // Demangle failed.
564       return StringRef();
565     }
566
567     auto Demangled = StringRef(Buf.data(), R);
568     if (Demangled == name) {
569       // Do not print anything if demangled name is equal to mangled.
570       return StringRef();
571     }
572
573     return Demangled;
574   }
575
576   void emitFunctionAnnot(const Function *F,
577                          formatted_raw_ostream &OS) override {
578     StringRef Demangled = CallDemangle(F->getName());
579     if (Demangled.empty()) {
580         return;
581     }
582
583     OS << "; " << Demangled << "\n";
584   }
585
586   void emitInstructionAnnot(const Instruction *I,
587                             formatted_raw_ostream &OS) override {
588     const char *Name;
589     const Value *Value;
590     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
591       Name = "call";
592       Value = CI->getCalledValue();
593     } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
594       Name = "invoke";
595       Value = II->getCalledValue();
596     } else {
597       // Could demangle more operations, e. g.
598       // `store %place, @function`.
599       return;
600     }
601
602     if (!Value->hasName()) {
603       return;
604     }
605
606     StringRef Demangled = CallDemangle(Value->getName());
607     if (Demangled.empty()) {
608       return;
609     }
610
611     OS << "; " << Name << " " << Demangled << "\n";
612   }
613 };
614
615 class RustPrintModulePass : public ModulePass {
616   raw_ostream* OS;
617   DemangleFn Demangle;
618 public:
619   static char ID;
620   RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
621   RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
622       : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
623
624   bool runOnModule(Module &M) override {
625     RustAssemblyAnnotationWriter AW(Demangle);
626
627     M.print(*OS, &AW, false);
628
629     return false;
630   }
631
632   void getAnalysisUsage(AnalysisUsage &AU) const override {
633     AU.setPreservesAll();
634   }
635
636   static StringRef name() { return "RustPrintModulePass"; }
637 };
638
639 } // namespace
640
641 namespace llvm {
642   void initializeRustPrintModulePassPass(PassRegistry&);
643 }
644
645 char RustPrintModulePass::ID = 0;
646 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
647                 "Print rust module to stderr", false, false)
648
649 extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
650                                     const char *Path, DemangleFn Demangle) {
651   llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
652   std::string ErrorInfo;
653
654   std::error_code EC;
655   raw_fd_ostream OS(Path, EC, sys::fs::F_None);
656   if (EC)
657     ErrorInfo = EC.message();
658
659   formatted_raw_ostream FOS(OS);
660
661   PM->add(new RustPrintModulePass(FOS, Demangle));
662
663   PM->run(*unwrap(M));
664 }
665
666 extern "C" void LLVMRustPrintPasses() {
667   LLVMInitializePasses();
668   struct MyListener : PassRegistrationListener {
669     void passEnumerate(const PassInfo *Info) {
670       StringRef PassArg = Info->getPassArgument();
671       StringRef PassName = Info->getPassName();
672       if (!PassArg.empty()) {
673         // These unsigned->signed casts could theoretically overflow, but
674         // realistically never will (and even if, the result is implementation
675         // defined rather plain UB).
676         printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
677                (int)PassName.size(), PassName.data());
678       }
679     }
680   } Listener;
681
682   PassRegistry *PR = PassRegistry::getPassRegistry();
683   PR->enumerateWith(&Listener);
684 }
685
686 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
687                                             bool AddLifetimes) {
688   unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
689 }
690
691 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
692                                            size_t Len) {
693   llvm::legacy::PassManager passes;
694
695   auto PreserveFunctions = [=](const GlobalValue &GV) {
696     for (size_t I = 0; I < Len; I++) {
697       if (GV.getName() == Symbols[I]) {
698         return true;
699       }
700     }
701     return false;
702   };
703
704   passes.add(llvm::createInternalizePass(PreserveFunctions));
705
706   passes.run(*unwrap(M));
707 }
708
709 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
710   for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
711        ++GV) {
712     GV->setDoesNotThrow();
713     Function *F = dyn_cast<Function>(GV);
714     if (F == nullptr)
715       continue;
716
717     for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
718       for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
719         if (isa<InvokeInst>(I)) {
720           InvokeInst *CI = cast<InvokeInst>(I);
721           CI->setDoesNotThrow();
722         }
723       }
724     }
725   }
726 }
727
728 extern "C" void
729 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
730                                        LLVMTargetMachineRef TMR) {
731   TargetMachine *Target = unwrap(TMR);
732   unwrap(Module)->setDataLayout(Target->createDataLayout());
733 }
734
735 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
736   unwrap(M)->setPIELevel(PIELevel::Level::Large);
737 }
738
739 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
740 // right now. This ThinLTO support is only enabled on "recent ish" versions of
741 // LLVM, and otherwise it's just blanket rejected from other compilers.
742 //
743 // Most of this implementation is straight copied from LLVM. At the time of
744 // this writing it wasn't *quite* suitable to reuse more code from upstream
745 // for our purposes, but we should strive to upstream this support once it's
746 // ready to go! I figure we may want a bit of testing locally first before
747 // sending this upstream to LLVM. I hear though they're quite eager to receive
748 // feedback like this!
749 //
750 // If you're reading this code and wondering "what in the world" or you're
751 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
752 // then fear not! (ok maybe fear a little). All code here is mostly based
753 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
754 //
755 // You'll find that the general layout here roughly corresponds to the `run`
756 // method in that file as well as `ProcessThinLTOModule`. Functions are
757 // specifically commented below as well, but if you're updating this code
758 // or otherwise trying to understand it, the LLVM source will be useful in
759 // interpreting the mysteries within.
760 //
761 // Otherwise I'll apologize in advance, it probably requires a relatively
762 // significant investment on your part to "truly understand" what's going on
763 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
764 // and various online resources about ThinLTO to make heads or tails of all
765 // this.
766
767 // This is a shared data structure which *must* be threadsafe to share
768 // read-only amongst threads. This also corresponds basically to the arguments
769 // of the `ProcessThinLTOModule` function in the LLVM source.
770 struct LLVMRustThinLTOData {
771   // The combined index that is the global analysis over all modules we're
772   // performing ThinLTO for. This is mostly managed by LLVM.
773   ModuleSummaryIndex Index;
774
775   // All modules we may look at, stored as in-memory serialized versions. This
776   // is later used when inlining to ensure we can extract any module to inline
777   // from.
778   StringMap<MemoryBufferRef> ModuleMap;
779
780   // A set that we manage of everything we *don't* want internalized. Note that
781   // this includes all transitive references right now as well, but it may not
782   // always!
783   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
784
785   // Not 100% sure what these are, but they impact what's internalized and
786   // what's inlined across modules, I believe.
787   StringMap<FunctionImporter::ImportMapTy> ImportLists;
788   StringMap<FunctionImporter::ExportSetTy> ExportLists;
789   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
790
791 #if LLVM_VERSION_GE(7, 0)
792   LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {}
793 #endif
794 };
795
796 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
797 struct LLVMRustThinLTOModule {
798   const char *identifier;
799   const char *data;
800   size_t len;
801 };
802
803 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
804 // does.
805 static const GlobalValueSummary *
806 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
807   auto StrongDefForLinker = llvm::find_if(
808       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
809         auto Linkage = Summary->linkage();
810         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
811                !GlobalValue::isWeakForLinker(Linkage);
812       });
813   if (StrongDefForLinker != GVSummaryList.end())
814     return StrongDefForLinker->get();
815
816   auto FirstDefForLinker = llvm::find_if(
817       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
818         auto Linkage = Summary->linkage();
819         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
820       });
821   if (FirstDefForLinker == GVSummaryList.end())
822     return nullptr;
823   return FirstDefForLinker->get();
824 }
825
826 // The main entry point for creating the global ThinLTO analysis. The structure
827 // here is basically the same as before threads are spawned in the `run`
828 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
829 extern "C" LLVMRustThinLTOData*
830 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
831                           int num_modules,
832                           const char **preserved_symbols,
833                           int num_symbols) {
834   auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
835
836   // Load each module's summary and merge it into one combined index
837   for (int i = 0; i < num_modules; i++) {
838     auto module = &modules[i];
839     StringRef buffer(module->data, module->len);
840     MemoryBufferRef mem_buffer(buffer, module->identifier);
841
842     Ret->ModuleMap[module->identifier] = mem_buffer;
843
844     if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
845       LLVMRustSetLastError(toString(std::move(Err)).c_str());
846       return nullptr;
847     }
848   }
849
850   // Collect for each module the list of function it defines (GUID -> Summary)
851   Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
852
853   // Convert the preserved symbols set from string to GUID, this is then needed
854   // for internalization.
855   for (int i = 0; i < num_symbols; i++) {
856     auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
857     Ret->GUIDPreservedSymbols.insert(GUID);
858   }
859
860   // Collect the import/export lists for all modules from the call-graph in the
861   // combined index
862   //
863   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
864 #if LLVM_VERSION_GE(7, 0)
865   auto deadIsPrevailing = [&](GlobalValue::GUID G) {
866     return PrevailingType::Unknown;
867   };
868 #if LLVM_VERSION_GE(8, 0)
869   computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
870                                   deadIsPrevailing, /* ImportEnabled = */ true);
871 #else
872   computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
873 #endif
874 #else
875   computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
876 #endif
877   ComputeCrossModuleImport(
878     Ret->Index,
879     Ret->ModuleToDefinedGVSummaries,
880     Ret->ImportLists,
881     Ret->ExportLists
882   );
883
884   // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
885   // impacts the caching.
886   //
887   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
888   // being lifted from `lib/LTO/LTO.cpp` as well
889   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
890   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
891   for (auto &I : Ret->Index) {
892     if (I.second.SummaryList.size() > 1)
893       PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
894   }
895   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
896     const auto &Prevailing = PrevailingCopy.find(GUID);
897     if (Prevailing == PrevailingCopy.end())
898       return true;
899     return Prevailing->second == S;
900   };
901   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
902                               GlobalValue::GUID GUID,
903                               GlobalValue::LinkageTypes NewLinkage) {
904     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
905   };
906 #if LLVM_VERSION_GE(8, 0)
907   thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
908 #else
909   thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
910 #endif
911
912   // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
913   // callback below. This callback below will dictate the linkage for all
914   // summaries in the index, and we basically just only want to ensure that dead
915   // symbols are internalized. Otherwise everything that's already external
916   // linkage will stay as external, and internal will stay as internal.
917   std::set<GlobalValue::GUID> ExportedGUIDs;
918   for (auto &List : Ret->Index) {
919     for (auto &GVS: List.second.SummaryList) {
920       if (GlobalValue::isLocalLinkage(GVS->linkage()))
921         continue;
922       auto GUID = GVS->getOriginalName();
923       if (GVS->flags().Live)
924         ExportedGUIDs.insert(GUID);
925     }
926   }
927   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
928     const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
929     return (ExportList != Ret->ExportLists.end() &&
930       ExportList->second.count(GUID)) ||
931       ExportedGUIDs.count(GUID);
932   };
933   thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
934
935   return Ret.release();
936 }
937
938 extern "C" void
939 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
940   delete Data;
941 }
942
943 // Below are the various passes that happen *per module* when doing ThinLTO.
944 //
945 // In other words, these are the functions that are all run concurrently
946 // with one another, one per module. The passes here correspond to the analysis
947 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
948 // `ProcessThinLTOModule` function. Here they're split up into separate steps
949 // so rustc can save off the intermediate bytecode between each step.
950
951 extern "C" bool
952 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
953   Module &Mod = *unwrap(M);
954   if (renameModuleForThinLTO(Mod, Data->Index)) {
955     LLVMRustSetLastError("renameModuleForThinLTO failed");
956     return false;
957   }
958   return true;
959 }
960
961 extern "C" bool
962 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
963   Module &Mod = *unwrap(M);
964   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
965 #if LLVM_VERSION_GE(8, 0)
966   thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
967 #else
968   thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
969 #endif
970   return true;
971 }
972
973 extern "C" bool
974 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
975   Module &Mod = *unwrap(M);
976   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
977   thinLTOInternalizeModule(Mod, DefinedGlobals);
978   return true;
979 }
980
981 extern "C" bool
982 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
983   Module &Mod = *unwrap(M);
984
985   const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
986   auto Loader = [&](StringRef Identifier) {
987     const auto &Memory = Data->ModuleMap.lookup(Identifier);
988     auto &Context = Mod.getContext();
989     auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
990
991     if (!MOrErr)
992       return MOrErr;
993
994     // The rest of this closure is a workaround for
995     // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
996     // we accidentally import wasm custom sections into different modules,
997     // duplicating them by in the final output artifact.
998     //
999     // The issue is worked around here by manually removing the
1000     // `wasm.custom_sections` named metadata node from any imported module. This
1001     // we know isn't used by any optimization pass so there's no need for it to
1002     // be imported.
1003     //
1004     // Note that the metadata is currently lazily loaded, so we materialize it
1005     // here before looking up if there's metadata inside. The `FunctionImporter`
1006     // will immediately materialize metadata anyway after an import, so this
1007     // shouldn't be a perf hit.
1008     if (Error Err = (*MOrErr)->materializeMetadata()) {
1009       Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1010       return Ret;
1011     }
1012
1013     auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1014     if (WasmCustomSections)
1015       WasmCustomSections->eraseFromParent();
1016
1017     return MOrErr;
1018   };
1019   FunctionImporter Importer(Data->Index, Loader);
1020   Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1021   if (!Result) {
1022     LLVMRustSetLastError(toString(Result.takeError()).c_str());
1023     return false;
1024   }
1025   return true;
1026 }
1027
1028 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1029                                                       const char*, // importing module name
1030                                                       const char*); // imported module name
1031
1032 // Calls `module_name_callback` for each module import done by ThinLTO.
1033 // The callback is provided with regular null-terminated C strings.
1034 extern "C" void
1035 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1036                                 LLVMRustModuleNameCallback module_name_callback,
1037                                 void* callback_payload) {
1038   for (const auto& importing_module : data->ImportLists) {
1039     const std::string importing_module_id = importing_module.getKey().str();
1040     const auto& imports = importing_module.getValue();
1041     for (const auto& imported_module : imports) {
1042       const std::string imported_module_id = imported_module.getKey().str();
1043       module_name_callback(callback_payload,
1044                            importing_module_id.c_str(),
1045                            imported_module_id.c_str());
1046     }
1047   }
1048 }
1049
1050 // This struct and various functions are sort of a hack right now, but the
1051 // problem is that we've got in-memory LLVM modules after we generate and
1052 // optimize all codegen-units for one compilation in rustc. To be compatible
1053 // with the LTO support above we need to serialize the modules plus their
1054 // ThinLTO summary into memory.
1055 //
1056 // This structure is basically an owned version of a serialize module, with
1057 // a ThinLTO summary attached.
1058 struct LLVMRustThinLTOBuffer {
1059   std::string data;
1060 };
1061
1062 extern "C" LLVMRustThinLTOBuffer*
1063 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1064   auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1065   {
1066     raw_string_ostream OS(Ret->data);
1067     {
1068       legacy::PassManager PM;
1069       PM.add(createWriteThinLTOBitcodePass(OS));
1070       PM.run(*unwrap(M));
1071     }
1072   }
1073   return Ret.release();
1074 }
1075
1076 extern "C" void
1077 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1078   delete Buffer;
1079 }
1080
1081 extern "C" const void*
1082 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1083   return Buffer->data.data();
1084 }
1085
1086 extern "C" size_t
1087 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1088   return Buffer->data.length();
1089 }
1090
1091 // This is what we used to parse upstream bitcode for actual ThinLTO
1092 // processing.  We'll call this once per module optimized through ThinLTO, and
1093 // it'll be called concurrently on many threads.
1094 extern "C" LLVMModuleRef
1095 LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1096                            const char *data,
1097                            size_t len,
1098                            const char *identifier) {
1099   StringRef Data(data, len);
1100   MemoryBufferRef Buffer(Data, identifier);
1101   unwrap(Context)->enableDebugTypeODRUniquing();
1102   Expected<std::unique_ptr<Module>> SrcOrError =
1103       parseBitcodeFile(Buffer, *unwrap(Context));
1104   if (!SrcOrError) {
1105     LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1106     return nullptr;
1107   }
1108   return wrap(std::move(*SrcOrError).release());
1109 }
1110
1111 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1112 // the comment in `back/lto.rs` for why this exists.
1113 extern "C" void
1114 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1115                                 DICompileUnit **A,
1116                                 DICompileUnit **B) {
1117   Module *M = unwrap(Mod);
1118   DICompileUnit **Cur = A;
1119   DICompileUnit **Next = B;
1120   for (DICompileUnit *CU : M->debug_compile_units()) {
1121     *Cur = CU;
1122     Cur = Next;
1123     Next = nullptr;
1124     if (Cur == nullptr)
1125       break;
1126   }
1127 }
1128
1129 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1130 // the comment in `back/lto.rs` for why this exists.
1131 extern "C" void
1132 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1133   Module *M = unwrap(Mod);
1134
1135   // If the original source module didn't have a `DICompileUnit` then try to
1136   // merge all the existing compile units. If there aren't actually any though
1137   // then there's not much for us to do so return.
1138   if (Unit == nullptr) {
1139     for (DICompileUnit *CU : M->debug_compile_units()) {
1140       Unit = CU;
1141       break;
1142     }
1143     if (Unit == nullptr)
1144       return;
1145   }
1146
1147   // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1148   // process it recursively. Note that we specifically iterate over instructions
1149   // to ensure we feed everything into it.
1150   DebugInfoFinder Finder;
1151   Finder.processModule(*M);
1152   for (Function &F : M->functions()) {
1153     for (auto &FI : F) {
1154       for (Instruction &BI : FI) {
1155         if (auto Loc = BI.getDebugLoc())
1156           Finder.processLocation(*M, Loc);
1157         if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1158           Finder.processValue(*M, DVI);
1159         if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1160           Finder.processDeclare(*M, DDI);
1161       }
1162     }
1163   }
1164
1165   // After we've found all our debuginfo, rewrite all subprograms to point to
1166   // the same `DICompileUnit`.
1167   for (auto &F : Finder.subprograms()) {
1168     F->replaceUnit(Unit);
1169   }
1170
1171   // Erase any other references to other `DICompileUnit` instances, the verifier
1172   // will later ensure that we don't actually have any other stale references to
1173   // worry about.
1174   auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1175   MD->clearOperands();
1176   MD->addOperand(Unit);
1177 }