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