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