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