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