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