]> git.lizzy.rs Git - rust.git/blob - src/rustllvm/PassWrapper.cpp
Merge branch 'android-run-pass' of https://github.com/malbarbo/rust into rollup
[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
841 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
842 struct LLVMRustThinLTOModule {
843   const char *identifier;
844   const char *data;
845   size_t len;
846 };
847
848 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
849 // does.
850 static const GlobalValueSummary *
851 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
852   auto StrongDefForLinker = llvm::find_if(
853       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
854         auto Linkage = Summary->linkage();
855         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
856                !GlobalValue::isWeakForLinker(Linkage);
857       });
858   if (StrongDefForLinker != GVSummaryList.end())
859     return StrongDefForLinker->get();
860
861   auto FirstDefForLinker = llvm::find_if(
862       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
863         auto Linkage = Summary->linkage();
864         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
865       });
866   if (FirstDefForLinker == GVSummaryList.end())
867     return nullptr;
868   return FirstDefForLinker->get();
869 }
870
871 // The main entry point for creating the global ThinLTO analysis. The structure
872 // here is basically the same as before threads are spawned in the `run`
873 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
874 extern "C" LLVMRustThinLTOData*
875 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
876                           int num_modules,
877                           const char **preserved_symbols,
878                           int num_symbols) {
879   auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
880
881   // Load each module's summary and merge it into one combined index
882   for (int i = 0; i < num_modules; i++) {
883     auto module = &modules[i];
884     StringRef buffer(module->data, module->len);
885     MemoryBufferRef mem_buffer(buffer, module->identifier);
886
887     Ret->ModuleMap[module->identifier] = mem_buffer;
888
889 #if LLVM_VERSION_GE(5, 0)
890     if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
891       LLVMRustSetLastError(toString(std::move(Err)).c_str());
892       return nullptr;
893     }
894 #else
895     Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
896       object::ModuleSummaryIndexObjectFile::create(mem_buffer);
897     if (!ObjOrErr) {
898       LLVMRustSetLastError(toString(ObjOrErr.takeError()).c_str());
899       return nullptr;
900     }
901     auto Index = (*ObjOrErr)->takeIndex();
902     Ret->Index.mergeFrom(std::move(Index), i);
903 #endif
904   }
905
906   // Collect for each module the list of function it defines (GUID -> Summary)
907   Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
908
909   // Convert the preserved symbols set from string to GUID, this is then needed
910   // for internalization.
911   for (int i = 0; i < num_symbols; i++) {
912     auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
913     Ret->GUIDPreservedSymbols.insert(GUID);
914   }
915
916   // Collect the import/export lists for all modules from the call-graph in the
917   // combined index
918   //
919   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
920 #if LLVM_VERSION_GE(5, 0)
921   computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
922   ComputeCrossModuleImport(
923     Ret->Index,
924     Ret->ModuleToDefinedGVSummaries,
925     Ret->ImportLists,
926     Ret->ExportLists
927   );
928 #else
929   auto DeadSymbols = computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
930   ComputeCrossModuleImport(
931     Ret->Index,
932     Ret->ModuleToDefinedGVSummaries,
933     Ret->ImportLists,
934     Ret->ExportLists,
935     &DeadSymbols
936   );
937 #endif
938
939   // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
940   // impacts the caching.
941   //
942   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
943   // being lifted from `lib/LTO/LTO.cpp` as well
944   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
945   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
946   for (auto &I : Ret->Index) {
947 #if LLVM_VERSION_GE(5, 0)
948     if (I.second.SummaryList.size() > 1)
949       PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
950 #else
951     if (I.second.size() > 1)
952       PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
953 #endif
954   }
955   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
956     const auto &Prevailing = PrevailingCopy.find(GUID);
957     if (Prevailing == PrevailingCopy.end())
958       return true;
959     return Prevailing->second == S;
960   };
961   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
962                               GlobalValue::GUID GUID,
963                               GlobalValue::LinkageTypes NewLinkage) {
964     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
965   };
966   thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
967
968   // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
969   // callback below. This callback below will dictate the linkage for all
970   // summaries in the index, and we basically just only want to ensure that dead
971   // symbols are internalized. Otherwise everything that's already external
972   // linkage will stay as external, and internal will stay as internal.
973   std::set<GlobalValue::GUID> ExportedGUIDs;
974   for (auto &List : Ret->Index) {
975 #if LLVM_VERSION_GE(5, 0)
976     for (auto &GVS: List.second.SummaryList) {
977 #else
978     for (auto &GVS: List.second) {
979 #endif
980       if (GlobalValue::isLocalLinkage(GVS->linkage()))
981         continue;
982       auto GUID = GVS->getOriginalName();
983 #if LLVM_VERSION_GE(5, 0)
984       if (GVS->flags().Live)
985 #else
986       if (!DeadSymbols.count(GUID))
987 #endif
988         ExportedGUIDs.insert(GUID);
989     }
990   }
991   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
992     const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
993     return (ExportList != Ret->ExportLists.end() &&
994       ExportList->second.count(GUID)) ||
995       ExportedGUIDs.count(GUID);
996   };
997   thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
998
999   return Ret.release();
1000 }
1001
1002 extern "C" void
1003 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1004   delete Data;
1005 }
1006
1007 // Below are the various passes that happen *per module* when doing ThinLTO.
1008 //
1009 // In other words, these are the functions that are all run concurrently
1010 // with one another, one per module. The passes here correspond to the analysis
1011 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
1012 // `ProcessThinLTOModule` function. Here they're split up into separate steps
1013 // so rustc can save off the intermediate bytecode between each step.
1014
1015 extern "C" bool
1016 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1017   Module &Mod = *unwrap(M);
1018   if (renameModuleForThinLTO(Mod, Data->Index)) {
1019     LLVMRustSetLastError("renameModuleForThinLTO failed");
1020     return false;
1021   }
1022   return true;
1023 }
1024
1025 extern "C" bool
1026 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1027   Module &Mod = *unwrap(M);
1028   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1029   thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1030   return true;
1031 }
1032
1033 extern "C" bool
1034 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1035   Module &Mod = *unwrap(M);
1036   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1037   thinLTOInternalizeModule(Mod, DefinedGlobals);
1038   return true;
1039 }
1040
1041 extern "C" bool
1042 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1043   Module &Mod = *unwrap(M);
1044   const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1045   auto Loader = [&](StringRef Identifier) {
1046     const auto &Memory = Data->ModuleMap.lookup(Identifier);
1047     auto &Context = Mod.getContext();
1048     return getLazyBitcodeModule(Memory, Context, true, true);
1049   };
1050   FunctionImporter Importer(Data->Index, Loader);
1051   Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1052   if (!Result) {
1053     LLVMRustSetLastError(toString(Result.takeError()).c_str());
1054     return false;
1055   }
1056   return true;
1057 }
1058
1059 // This struct and various functions are sort of a hack right now, but the
1060 // problem is that we've got in-memory LLVM modules after we generate and
1061 // optimize all codegen-units for one compilation in rustc. To be compatible
1062 // with the LTO support above we need to serialize the modules plus their
1063 // ThinLTO summary into memory.
1064 //
1065 // This structure is basically an owned version of a serialize module, with
1066 // a ThinLTO summary attached.
1067 struct LLVMRustThinLTOBuffer {
1068   std::string data;
1069 };
1070
1071 extern "C" LLVMRustThinLTOBuffer*
1072 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1073   auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1074   {
1075     raw_string_ostream OS(Ret->data);
1076     {
1077       legacy::PassManager PM;
1078       PM.add(createWriteThinLTOBitcodePass(OS));
1079       PM.run(*unwrap(M));
1080     }
1081   }
1082   return Ret.release();
1083 }
1084
1085 extern "C" void
1086 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1087   delete Buffer;
1088 }
1089
1090 extern "C" const void*
1091 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1092   return Buffer->data.data();
1093 }
1094
1095 extern "C" size_t
1096 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1097   return Buffer->data.length();
1098 }
1099
1100 // This is what we used to parse upstream bitcode for actual ThinLTO
1101 // processing.  We'll call this once per module optimized through ThinLTO, and
1102 // it'll be called concurrently on many threads.
1103 extern "C" LLVMModuleRef
1104 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1105                                const char *data,
1106                                size_t len,
1107                                const char *identifier) {
1108   StringRef Data(data, len);
1109   MemoryBufferRef Buffer(Data, identifier);
1110   unwrap(Context)->enableDebugTypeODRUniquing();
1111   Expected<std::unique_ptr<Module>> SrcOrError =
1112       parseBitcodeFile(Buffer, *unwrap(Context));
1113   if (!SrcOrError) {
1114     LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1115     return nullptr;
1116   }
1117   return wrap(std::move(*SrcOrError).release());
1118 }
1119
1120 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1121 // the comment in `back/lto.rs` for why this exists.
1122 extern "C" void
1123 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1124                                 DICompileUnit **A,
1125                                 DICompileUnit **B) {
1126   Module *M = unwrap(Mod);
1127   DICompileUnit **Cur = A;
1128   DICompileUnit **Next = B;
1129   for (DICompileUnit *CU : M->debug_compile_units()) {
1130     *Cur = CU;
1131     Cur = Next;
1132     Next = nullptr;
1133     if (Cur == nullptr)
1134       break;
1135   }
1136 }
1137
1138 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1139 // the comment in `back/lto.rs` for why this exists.
1140 extern "C" void
1141 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1142   Module *M = unwrap(Mod);
1143
1144   // If the original source module didn't have a `DICompileUnit` then try to
1145   // merge all the existing compile units. If there aren't actually any though
1146   // then there's not much for us to do so return.
1147   if (Unit == nullptr) {
1148     for (DICompileUnit *CU : M->debug_compile_units()) {
1149       Unit = CU;
1150       break;
1151     }
1152     if (Unit == nullptr)
1153       return;
1154   }
1155
1156   // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1157   // process it recursively. Note that we specifically iterate over instructions
1158   // to ensure we feed everything into it.
1159   DebugInfoFinder Finder;
1160   Finder.processModule(*M);
1161   for (Function &F : M->functions()) {
1162     for (auto &FI : F) {
1163       for (Instruction &BI : FI) {
1164         if (auto Loc = BI.getDebugLoc())
1165           Finder.processLocation(*M, Loc);
1166         if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1167           Finder.processValue(*M, DVI);
1168         if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1169           Finder.processDeclare(*M, DDI);
1170       }
1171     }
1172   }
1173
1174   // After we've found all our debuginfo, rewrite all subprograms to point to
1175   // the same `DICompileUnit`.
1176   for (auto &F : Finder.subprograms()) {
1177     F->replaceUnit(Unit);
1178   }
1179
1180   // Erase any other references to other `DICompileUnit` instances, the verifier
1181   // will later ensure that we don't actually have any other stale references to
1182   // worry about.
1183   auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1184   MD->clearOperands();
1185   MD->addOperand(Unit);
1186 }
1187
1188 extern "C" void
1189 LLVMRustThinLTORemoveAvailableExternally(LLVMModuleRef Mod) {
1190   Module *M = unwrap(Mod);
1191   for (Function &F : M->functions()) {
1192     if (F.hasAvailableExternallyLinkage())
1193       F.deleteBody();
1194   }
1195 }
1196
1197 #else
1198
1199 extern "C" bool
1200 LLVMRustWriteThinBitcodeToFile(LLVMPassManagerRef PMR,
1201                                LLVMModuleRef M,
1202                                const char *BcFile) {
1203   report_fatal_error("ThinLTO not available");
1204 }
1205
1206 struct LLVMRustThinLTOData {
1207 };
1208
1209 struct LLVMRustThinLTOModule {
1210 };
1211
1212 extern "C" LLVMRustThinLTOData*
1213 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
1214                           int num_modules,
1215                           const char **preserved_symbols,
1216                           int num_symbols) {
1217   report_fatal_error("ThinLTO not available");
1218 }
1219
1220 extern "C" bool
1221 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1222   report_fatal_error("ThinLTO not available");
1223 }
1224
1225 extern "C" bool
1226 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1227   report_fatal_error("ThinLTO not available");
1228 }
1229
1230 extern "C" bool
1231 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1232   report_fatal_error("ThinLTO not available");
1233 }
1234
1235 extern "C" bool
1236 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1237   report_fatal_error("ThinLTO not available");
1238 }
1239
1240 extern "C" void
1241 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1242   report_fatal_error("ThinLTO not available");
1243 }
1244
1245 struct LLVMRustThinLTOBuffer {
1246 };
1247
1248 extern "C" LLVMRustThinLTOBuffer*
1249 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1250   report_fatal_error("ThinLTO not available");
1251 }
1252
1253 extern "C" void
1254 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1255   report_fatal_error("ThinLTO not available");
1256 }
1257
1258 extern "C" const void*
1259 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1260   report_fatal_error("ThinLTO not available");
1261 }
1262
1263 extern "C" size_t
1264 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1265   report_fatal_error("ThinLTO not available");
1266 }
1267
1268 extern "C" LLVMModuleRef
1269 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1270                                const char *data,
1271                                size_t len,
1272                                const char *identifier) {
1273   report_fatal_error("ThinLTO not available");
1274 }
1275
1276 extern "C" void
1277 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1278                                 DICompileUnit **A,
1279                                 DICompileUnit **B) {
1280   report_fatal_error("ThinLTO not available");
1281 }
1282
1283 extern "C" void
1284 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod) {
1285   report_fatal_error("ThinLTO not available");
1286 }
1287
1288 extern "C" void
1289 LLVMRustThinLTORemoveAvailableExternally(LLVMModuleRef Mod) {
1290   report_fatal_error("ThinLTO not available");
1291 }
1292
1293 #endif // LLVM_VERSION_GE(4, 0)