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