]> git.lizzy.rs Git - rust.git/blob - src/rustllvm/RustWrapper.cpp
bump minimum LLVM version to 5.0
[rust.git] / src / rustllvm / RustWrapper.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 "rustllvm.h"
12 #include "llvm/IR/DebugInfoMetadata.h"
13 #include "llvm/IR/DiagnosticInfo.h"
14 #include "llvm/IR/DiagnosticPrinter.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/Object/Archive.h"
17 #include "llvm/Object/ObjectFile.h"
18 #include "llvm/Bitcode/BitcodeWriterPass.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/ADT/Optional.h"
21
22 //===----------------------------------------------------------------------===
23 //
24 // This file defines alternate interfaces to core functions that are more
25 // readily callable by Rust's FFI.
26 //
27 //===----------------------------------------------------------------------===
28
29 using namespace llvm;
30 using namespace llvm::sys;
31 using namespace llvm::object;
32
33 // LLVMAtomicOrdering is already an enum - don't create another
34 // one.
35 static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
36   switch (Ordering) {
37   case LLVMAtomicOrderingNotAtomic:
38     return AtomicOrdering::NotAtomic;
39   case LLVMAtomicOrderingUnordered:
40     return AtomicOrdering::Unordered;
41   case LLVMAtomicOrderingMonotonic:
42     return AtomicOrdering::Monotonic;
43   case LLVMAtomicOrderingAcquire:
44     return AtomicOrdering::Acquire;
45   case LLVMAtomicOrderingRelease:
46     return AtomicOrdering::Release;
47   case LLVMAtomicOrderingAcquireRelease:
48     return AtomicOrdering::AcquireRelease;
49   case LLVMAtomicOrderingSequentiallyConsistent:
50     return AtomicOrdering::SequentiallyConsistent;
51   }
52
53   report_fatal_error("Invalid LLVMAtomicOrdering value!");
54 }
55
56 static LLVM_THREAD_LOCAL char *LastError;
57
58 extern "C" LLVMMemoryBufferRef
59 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
60   ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
61       MemoryBuffer::getFile(Path, -1, false);
62   if (!BufOr) {
63     LLVMRustSetLastError(BufOr.getError().message().c_str());
64     return nullptr;
65   }
66   return wrap(BufOr.get().release());
67 }
68
69 extern "C" char *LLVMRustGetLastError(void) {
70   char *Ret = LastError;
71   LastError = nullptr;
72   return Ret;
73 }
74
75 extern "C" void LLVMRustSetLastError(const char *Err) {
76   free((void *)LastError);
77   LastError = strdup(Err);
78 }
79
80 extern "C" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) {
81   auto ctx = new LLVMContext();
82   ctx->setDiscardValueNames(shouldDiscardNames);
83   return wrap(ctx);
84 }
85
86 extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
87                                             const char *Triple) {
88   unwrap(M)->setTargetTriple(Triple::normalize(Triple));
89 }
90
91 extern "C" void LLVMRustPrintPassTimings() {
92   raw_fd_ostream OS(2, false); // stderr.
93   TimerGroup::printAll(OS);
94 }
95
96 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
97                                               const char *Name) {
98   return wrap(unwrap(M)->getNamedValue(Name));
99 }
100
101 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
102                                                     const char *Name,
103                                                     LLVMTypeRef FunctionTy) {
104   return wrap(
105       unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy)));
106 }
107
108 extern "C" LLVMValueRef
109 LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
110   return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
111 }
112
113 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
114   return wrap(Type::getMetadataTy(*unwrap(C)));
115 }
116
117 static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
118   switch (Kind) {
119   case AlwaysInline:
120     return Attribute::AlwaysInline;
121   case ByVal:
122     return Attribute::ByVal;
123   case Cold:
124     return Attribute::Cold;
125   case InlineHint:
126     return Attribute::InlineHint;
127   case MinSize:
128     return Attribute::MinSize;
129   case Naked:
130     return Attribute::Naked;
131   case NoAlias:
132     return Attribute::NoAlias;
133   case NoCapture:
134     return Attribute::NoCapture;
135   case NoInline:
136     return Attribute::NoInline;
137   case NonNull:
138     return Attribute::NonNull;
139   case NoRedZone:
140     return Attribute::NoRedZone;
141   case NoReturn:
142     return Attribute::NoReturn;
143   case NoUnwind:
144     return Attribute::NoUnwind;
145   case OptimizeForSize:
146     return Attribute::OptimizeForSize;
147   case ReadOnly:
148     return Attribute::ReadOnly;
149   case SExt:
150     return Attribute::SExt;
151   case StructRet:
152     return Attribute::StructRet;
153   case UWTable:
154     return Attribute::UWTable;
155   case ZExt:
156     return Attribute::ZExt;
157   case InReg:
158     return Attribute::InReg;
159   case SanitizeThread:
160     return Attribute::SanitizeThread;
161   case SanitizeAddress:
162     return Attribute::SanitizeAddress;
163   case SanitizeMemory:
164     return Attribute::SanitizeMemory;
165   }
166   report_fatal_error("bad AttributeKind");
167 }
168
169 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
170                                              LLVMRustAttribute RustAttr) {
171   CallSite Call = CallSite(unwrap<Instruction>(Instr));
172   Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
173   Call.addAttribute(Index, Attr);
174 }
175
176 extern "C" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr,
177                                                  unsigned Index,
178                                                  uint32_t Bytes) {
179   CallSite Call = CallSite(unwrap<Instruction>(Instr));
180   AttrBuilder B;
181   B.addAlignmentAttr(Bytes);
182   Call.setAttributes(Call.getAttributes().addAttributes(
183       Call->getContext(), Index, B));
184 }
185
186 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
187                                                        unsigned Index,
188                                                        uint64_t Bytes) {
189   CallSite Call = CallSite(unwrap<Instruction>(Instr));
190   AttrBuilder B;
191   B.addDereferenceableAttr(Bytes);
192   Call.setAttributes(Call.getAttributes().addAttributes(
193       Call->getContext(), Index, B));
194 }
195
196 extern "C" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr,
197                                                              unsigned Index,
198                                                              uint64_t Bytes) {
199   CallSite Call = CallSite(unwrap<Instruction>(Instr));
200   AttrBuilder B;
201   B.addDereferenceableOrNullAttr(Bytes);
202   Call.setAttributes(Call.getAttributes().addAttributes(
203       Call->getContext(), Index, B));
204 }
205
206 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
207                                              LLVMRustAttribute RustAttr) {
208   Function *A = unwrap<Function>(Fn);
209   Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
210   AttrBuilder B(Attr);
211   A->addAttributes(Index, B);
212 }
213
214 extern "C" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn,
215                                          unsigned Index,
216                                          uint32_t Bytes) {
217   Function *A = unwrap<Function>(Fn);
218   AttrBuilder B;
219   B.addAlignmentAttr(Bytes);
220   A->addAttributes(Index, B);
221 }
222
223 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
224                                                uint64_t Bytes) {
225   Function *A = unwrap<Function>(Fn);
226   AttrBuilder B;
227   B.addDereferenceableAttr(Bytes);
228   A->addAttributes(Index, B);
229 }
230
231 extern "C" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn,
232                                                      unsigned Index,
233                                                      uint64_t Bytes) {
234   Function *A = unwrap<Function>(Fn);
235   AttrBuilder B;
236   B.addDereferenceableOrNullAttr(Bytes);
237   A->addAttributes(Index, B);
238 }
239
240 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
241                                                    unsigned Index,
242                                                    const char *Name,
243                                                    const char *Value) {
244   Function *F = unwrap<Function>(Fn);
245   AttrBuilder B;
246   B.addAttribute(Name, Value);
247   F->addAttributes(Index, B);
248 }
249
250 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
251                                                  unsigned Index,
252                                                  LLVMRustAttribute RustAttr) {
253   Function *F = unwrap<Function>(Fn);
254   Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
255   AttrBuilder B(Attr);
256   auto PAL = F->getAttributes();
257   auto PALNew = PAL.removeAttributes(F->getContext(), Index, B);
258   F->setAttributes(PALNew);
259 }
260
261 // enable fpmath flag UnsafeAlgebra
262 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
263   if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
264 #if LLVM_VERSION_GE(6, 0)
265     I->setFast(true);
266 #else
267     I->setHasUnsafeAlgebra(true);
268 #endif
269   }
270 }
271
272 extern "C" LLVMValueRef
273 LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
274                         LLVMAtomicOrdering Order) {
275   LoadInst *LI = new LoadInst(unwrap(Source), 0);
276   LI->setAtomic(fromRust(Order));
277   return wrap(unwrap(B)->Insert(LI, Name));
278 }
279
280 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
281                                                  LLVMValueRef V,
282                                                  LLVMValueRef Target,
283                                                  LLVMAtomicOrdering Order) {
284   StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
285   SI->setAtomic(fromRust(Order));
286   return wrap(unwrap(B)->Insert(SI));
287 }
288
289 extern "C" LLVMValueRef
290 LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
291                            LLVMValueRef Old, LLVMValueRef Source,
292                            LLVMAtomicOrdering Order,
293                            LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
294   AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
295       unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
296       fromRust(FailureOrder));
297   ACXI->setWeak(Weak);
298   return wrap(ACXI);
299 }
300
301 enum class LLVMRustSynchronizationScope {
302   Other,
303   SingleThread,
304   CrossThread,
305 };
306
307 static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) {
308   switch (Scope) {
309   case LLVMRustSynchronizationScope::SingleThread:
310     return SyncScope::SingleThread;
311   case LLVMRustSynchronizationScope::CrossThread:
312     return SyncScope::System;
313   default:
314     report_fatal_error("bad SynchronizationScope.");
315   }
316 }
317
318 extern "C" LLVMValueRef
319 LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
320                          LLVMRustSynchronizationScope Scope) {
321   return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
322 }
323
324 enum class LLVMRustAsmDialect {
325   Other,
326   Att,
327   Intel,
328 };
329
330 static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
331   switch (Dialect) {
332   case LLVMRustAsmDialect::Att:
333     return InlineAsm::AD_ATT;
334   case LLVMRustAsmDialect::Intel:
335     return InlineAsm::AD_Intel;
336   default:
337     report_fatal_error("bad AsmDialect.");
338   }
339 }
340
341 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
342                                           char *Constraints,
343                                           LLVMBool HasSideEffects,
344                                           LLVMBool IsAlignStack,
345                                           LLVMRustAsmDialect Dialect) {
346   return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
347                              HasSideEffects, IsAlignStack, fromRust(Dialect)));
348 }
349
350 extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
351   unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
352 }
353
354 typedef DIBuilder *LLVMRustDIBuilderRef;
355
356 template <typename DIT> DIT *unwrapDIPtr(LLVMMetadataRef Ref) {
357   return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
358 }
359
360 #define DIDescriptor DIScope
361 #define DIArray DINodeArray
362 #define unwrapDI unwrapDIPtr
363
364 // These values **must** match debuginfo::DIFlags! They also *happen*
365 // to match LLVM, but that isn't required as we do giant sets of
366 // matching below. The value shouldn't be directly passed to LLVM.
367 enum class LLVMRustDIFlags : uint32_t {
368   FlagZero = 0,
369   FlagPrivate = 1,
370   FlagProtected = 2,
371   FlagPublic = 3,
372   FlagFwdDecl = (1 << 2),
373   FlagAppleBlock = (1 << 3),
374   FlagBlockByrefStruct = (1 << 4),
375   FlagVirtual = (1 << 5),
376   FlagArtificial = (1 << 6),
377   FlagExplicit = (1 << 7),
378   FlagPrototyped = (1 << 8),
379   FlagObjcClassComplete = (1 << 9),
380   FlagObjectPointer = (1 << 10),
381   FlagVector = (1 << 11),
382   FlagStaticMember = (1 << 12),
383   FlagLValueReference = (1 << 13),
384   FlagRValueReference = (1 << 14),
385   FlagExternalTypeRef = (1 << 15),
386   FlagIntroducedVirtual = (1 << 18),
387   FlagBitField = (1 << 19),
388   FlagNoReturn = (1 << 20),
389   FlagMainSubprogram = (1 << 21),
390   // Do not add values that are not supported by the minimum LLVM
391   // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
392 };
393
394 inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
395   return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
396                                       static_cast<uint32_t>(B));
397 }
398
399 inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
400   return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
401                                       static_cast<uint32_t>(B));
402 }
403
404 inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
405   return A = A | B;
406 }
407
408 inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
409
410 inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
411   return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
412 }
413
414 static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
415   DINode::DIFlags Result = DINode::DIFlags::FlagZero;
416
417   switch (visibility(Flags)) {
418   case LLVMRustDIFlags::FlagPrivate:
419     Result |= DINode::DIFlags::FlagPrivate;
420     break;
421   case LLVMRustDIFlags::FlagProtected:
422     Result |= DINode::DIFlags::FlagProtected;
423     break;
424   case LLVMRustDIFlags::FlagPublic:
425     Result |= DINode::DIFlags::FlagPublic;
426     break;
427   default:
428     // The rest are handled below
429     break;
430   }
431
432   if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
433     Result |= DINode::DIFlags::FlagFwdDecl;
434   }
435   if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
436     Result |= DINode::DIFlags::FlagAppleBlock;
437   }
438   if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
439     Result |= DINode::DIFlags::FlagBlockByrefStruct;
440   }
441   if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
442     Result |= DINode::DIFlags::FlagVirtual;
443   }
444   if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
445     Result |= DINode::DIFlags::FlagArtificial;
446   }
447   if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
448     Result |= DINode::DIFlags::FlagExplicit;
449   }
450   if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
451     Result |= DINode::DIFlags::FlagPrototyped;
452   }
453   if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
454     Result |= DINode::DIFlags::FlagObjcClassComplete;
455   }
456   if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
457     Result |= DINode::DIFlags::FlagObjectPointer;
458   }
459   if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
460     Result |= DINode::DIFlags::FlagVector;
461   }
462   if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
463     Result |= DINode::DIFlags::FlagStaticMember;
464   }
465   if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
466     Result |= DINode::DIFlags::FlagLValueReference;
467   }
468   if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
469     Result |= DINode::DIFlags::FlagRValueReference;
470   }
471   if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) {
472     Result |= DINode::DIFlags::FlagIntroducedVirtual;
473   }
474   if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) {
475     Result |= DINode::DIFlags::FlagBitField;
476   }
477   if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) {
478     Result |= DINode::DIFlags::FlagNoReturn;
479   }
480   if (isSet(Flags & LLVMRustDIFlags::FlagMainSubprogram)) {
481     Result |= DINode::DIFlags::FlagMainSubprogram;
482   }
483
484   return Result;
485 }
486
487 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
488   return DEBUG_METADATA_VERSION;
489 }
490
491 extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
492
493 extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
494
495 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
496                                       uint32_t Value) {
497   unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
498 }
499
500 extern "C" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
501   return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
502 }
503
504 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
505   return new DIBuilder(*unwrap(M));
506 }
507
508 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
509   delete Builder;
510 }
511
512 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
513   Builder->finalize();
514 }
515
516 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
517     LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
518     const char *Producer, bool isOptimized, const char *Flags,
519     unsigned RuntimeVer, const char *SplitName) {
520   auto *File = unwrapDI<DIFile>(FileRef);
521
522   return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
523                                          Flags, RuntimeVer, SplitName));
524 }
525
526 extern "C" LLVMMetadataRef
527 LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
528                             const char *Directory) {
529   return wrap(Builder->createFile(Filename, Directory));
530 }
531
532 extern "C" LLVMMetadataRef
533 LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
534                                       LLVMMetadataRef File,
535                                       LLVMMetadataRef ParameterTypes) {
536   return wrap(Builder->createSubroutineType(
537       DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
538 }
539
540 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
541     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
542     const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
543     LLVMMetadataRef Ty, bool IsLocalToUnit, bool IsDefinition,
544     unsigned ScopeLine, LLVMRustDIFlags Flags, bool IsOptimized,
545     LLVMValueRef Fn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) {
546   DITemplateParameterArray TParams =
547       DITemplateParameterArray(unwrap<MDTuple>(TParam));
548   DISubprogram *Sub = Builder->createFunction(
549       unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
550       LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
551       ScopeLine, fromRust(Flags), IsOptimized, TParams,
552       unwrapDIPtr<DISubprogram>(Decl));
553   unwrap<Function>(Fn)->setSubprogram(Sub);
554   return wrap(Sub);
555 }
556
557 extern "C" LLVMMetadataRef
558 LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
559                                  uint64_t SizeInBits, uint32_t AlignInBits,
560                                  unsigned Encoding) {
561   return wrap(Builder->createBasicType(Name, SizeInBits, Encoding));
562 }
563
564 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
565     LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
566     uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
567   return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
568                                          SizeInBits, AlignInBits,
569                                          /* DWARFAddressSpace */ None,
570                                          Name));
571 }
572
573 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
574     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
575     LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
576     uint32_t AlignInBits, LLVMRustDIFlags Flags,
577     LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
578     unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
579     const char *UniqueId) {
580   return wrap(Builder->createStructType(
581       unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
582       SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
583       DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
584       unwrapDI<DIType>(VTableHolder), UniqueId));
585 }
586
587 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
588     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
589     LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
590     uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
591     LLVMMetadataRef Ty) {
592   return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
593                                         unwrapDI<DIFile>(File), LineNo,
594                                         SizeInBits, AlignInBits, OffsetInBits,
595                                         fromRust(Flags), unwrapDI<DIType>(Ty)));
596 }
597
598 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
599     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
600     LLVMMetadataRef File, unsigned Line, unsigned Col) {
601   return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
602                                           unwrapDI<DIFile>(File), Line, Col));
603 }
604
605 extern "C" LLVMMetadataRef
606 LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
607                                         LLVMMetadataRef Scope,
608                                         LLVMMetadataRef File) {
609   return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
610                                               unwrapDI<DIFile>(File)));
611 }
612
613 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
614     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
615     const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
616     LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
617     LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
618   llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
619
620   llvm::DIExpression *InitExpr = nullptr;
621   if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
622     InitExpr = Builder->createConstantValueExpression(
623         IntVal->getValue().getSExtValue());
624   } else if (llvm::ConstantFP *FPVal =
625                  llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
626     InitExpr = Builder->createConstantValueExpression(
627         FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
628   }
629
630   llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
631       unwrapDI<DIDescriptor>(Context), Name, LinkageName,
632       unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
633       InitExpr, unwrapDIPtr<MDNode>(Decl), AlignInBits);
634
635   InitVal->setMetadata("dbg", VarExpr);
636
637   return wrap(VarExpr);
638 }
639
640 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
641     LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
642     const char *Name, LLVMMetadataRef File, unsigned LineNo,
643     LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
644     unsigned ArgNo, uint32_t AlignInBits) {
645   if (Tag == 0x100) { // DW_TAG_auto_variable
646     return wrap(Builder->createAutoVariable(
647         unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
648         unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits));
649   } else {
650     return wrap(Builder->createParameterVariable(
651         unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
652         LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
653   }
654 }
655
656 extern "C" LLVMMetadataRef
657 LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
658                                  uint32_t AlignInBits, LLVMMetadataRef Ty,
659                                  LLVMMetadataRef Subscripts) {
660   return wrap(
661       Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
662                                DINodeArray(unwrapDI<MDTuple>(Subscripts))));
663 }
664
665 extern "C" LLVMMetadataRef
666 LLVMRustDIBuilderCreateVectorType(LLVMRustDIBuilderRef Builder, uint64_t Size,
667                                   uint32_t AlignInBits, LLVMMetadataRef Ty,
668                                   LLVMMetadataRef Subscripts) {
669   return wrap(
670       Builder->createVectorType(Size, AlignInBits, unwrapDI<DIType>(Ty),
671                                 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
672 }
673
674 extern "C" LLVMMetadataRef
675 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
676                                      int64_t Count) {
677   return wrap(Builder->getOrCreateSubrange(Lo, Count));
678 }
679
680 extern "C" LLVMMetadataRef
681 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
682                                   LLVMMetadataRef *Ptr, unsigned Count) {
683   Metadata **DataValue = unwrap(Ptr);
684   return wrap(
685       Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
686 }
687
688 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
689     LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
690     int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
691     LLVMBasicBlockRef InsertAtEnd) {
692   return wrap(Builder->insertDeclare(
693       unwrap(V), unwrap<DILocalVariable>(VarInfo),
694       Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
695       DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
696       unwrap(InsertAtEnd)));
697 }
698
699 extern "C" LLVMMetadataRef
700 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
701                                   const char *Name, uint64_t Val) {
702   return wrap(Builder->createEnumerator(Name, Val));
703 }
704
705 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
706     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
707     LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
708     uint32_t AlignInBits, LLVMMetadataRef Elements,
709     LLVMMetadataRef ClassTy) {
710   return wrap(Builder->createEnumerationType(
711       unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
712       SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
713       unwrapDI<DIType>(ClassTy)));
714 }
715
716 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
717     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
718     LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
719     uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
720     unsigned RunTimeLang, const char *UniqueId) {
721   return wrap(Builder->createUnionType(
722       unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
723       SizeInBits, AlignInBits, fromRust(Flags),
724       DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
725 }
726
727 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
728     LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
729     LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
730     unsigned ColumnNo) {
731   return wrap(Builder->createTemplateTypeParameter(
732       unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
733 }
734
735 extern "C" LLVMMetadataRef
736 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
737                                  LLVMMetadataRef Scope, const char *Name,
738                                  LLVMMetadataRef File, unsigned LineNo) {
739   return wrap(Builder->createNameSpace(
740       unwrapDI<DIDescriptor>(Scope), Name,
741       false // ExportSymbols (only relevant for C++ anonymous namespaces)
742       ));
743 }
744
745 extern "C" void
746 LLVMRustDICompositeTypeSetTypeArray(LLVMRustDIBuilderRef Builder,
747                                     LLVMMetadataRef CompositeTy,
748                                     LLVMMetadataRef TyArray) {
749   DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
750   Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(TyArray)));
751 }
752
753 extern "C" LLVMValueRef
754 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
755                                      unsigned Column, LLVMMetadataRef Scope,
756                                      LLVMMetadataRef InlinedAt) {
757   LLVMContext &Context = *unwrap(ContextRef);
758
759   DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
760                                      unwrapDIPtr<MDNode>(InlinedAt));
761
762   return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
763 }
764
765 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
766   return dwarf::DW_OP_deref;
767 }
768
769 extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
770   return dwarf::DW_OP_plus_uconst;
771 }
772
773 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
774   RawRustStringOstream OS(Str);
775   unwrap<llvm::Type>(Ty)->print(OS);
776 }
777
778 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
779                                            RustStringRef Str) {
780   RawRustStringOstream OS(Str);
781   if (!V) {
782     OS << "(null)";
783   } else {
784     OS << "(";
785     unwrap<llvm::Value>(V)->getType()->print(OS);
786     OS << ":";
787     unwrap<llvm::Value>(V)->print(OS);
788     OS << ")";
789   }
790 }
791
792 // Note that the two following functions look quite similar to the
793 // LLVMGetSectionName function. Sadly, it appears that this function only
794 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
795 // function provided by LLVM doesn't return the length, so we've created our own
796 // function which returns the length as well as the data pointer.
797 //
798 // For an example of this not returning a null terminated string, see
799 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
800 // branches explicitly creates a StringRef without a null terminator, and then
801 // that's returned.
802
803 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
804   return reinterpret_cast<section_iterator *>(SI);
805 }
806
807 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
808                                          const char **Ptr) {
809   StringRef Ret;
810   if (std::error_code EC = (*unwrap(SI))->getName(Ret))
811     report_fatal_error(EC.message());
812   *Ptr = Ret.data();
813   return Ret.size();
814 }
815
816 // LLVMArrayType function does not support 64-bit ElementCount
817 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
818                                          uint64_t ElementCount) {
819   return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
820 }
821
822 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
823
824 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
825   RawRustStringOstream OS(Str);
826   unwrap(T)->print(OS);
827 }
828
829 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
830     LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
831     LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
832     RustStringRef FilenameOut, RustStringRef MessageOut) {
833   // Undefined to call this not on an optimization diagnostic!
834   llvm::DiagnosticInfoOptimizationBase *Opt =
835       static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
836
837   RawRustStringOstream PassNameOS(PassNameOut);
838   PassNameOS << Opt->getPassName();
839   *FunctionOut = wrap(&Opt->getFunction());
840
841   RawRustStringOstream FilenameOS(FilenameOut);
842   DiagnosticLocation loc = Opt->getLocation();
843   if (loc.isValid()) {
844     *Line = loc.getLine();
845     *Column = loc.getColumn();
846     FilenameOS << loc.getFilename();
847   }
848
849   RawRustStringOstream MessageOS(MessageOut);
850   MessageOS << Opt->getMsg();
851 }
852
853 extern "C" void
854 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
855                                   LLVMTwineRef *MessageOut,
856                                   LLVMValueRef *InstructionOut) {
857   // Undefined to call this not on an inline assembly diagnostic!
858   llvm::DiagnosticInfoInlineAsm *IA =
859       static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
860
861   *CookieOut = IA->getLocCookie();
862   *MessageOut = wrap(&IA->getMsgStr());
863   *InstructionOut = wrap(IA->getInstruction());
864 }
865
866 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
867                                                     RustStringRef Str) {
868   RawRustStringOstream OS(Str);
869   DiagnosticPrinterRawOStream DP(OS);
870   unwrap(DI)->print(DP);
871 }
872
873 enum class LLVMRustDiagnosticKind {
874   Other,
875   InlineAsm,
876   StackSize,
877   DebugMetadataVersion,
878   SampleProfile,
879   OptimizationRemark,
880   OptimizationRemarkMissed,
881   OptimizationRemarkAnalysis,
882   OptimizationRemarkAnalysisFPCommute,
883   OptimizationRemarkAnalysisAliasing,
884   OptimizationRemarkOther,
885   OptimizationFailure,
886   PGOProfile,
887 };
888
889 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
890   switch (Kind) {
891   case DK_InlineAsm:
892     return LLVMRustDiagnosticKind::InlineAsm;
893   case DK_StackSize:
894     return LLVMRustDiagnosticKind::StackSize;
895   case DK_DebugMetadataVersion:
896     return LLVMRustDiagnosticKind::DebugMetadataVersion;
897   case DK_SampleProfile:
898     return LLVMRustDiagnosticKind::SampleProfile;
899   case DK_OptimizationRemark:
900     return LLVMRustDiagnosticKind::OptimizationRemark;
901   case DK_OptimizationRemarkMissed:
902     return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
903   case DK_OptimizationRemarkAnalysis:
904     return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
905   case DK_OptimizationRemarkAnalysisFPCommute:
906     return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
907   case DK_OptimizationRemarkAnalysisAliasing:
908     return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
909   case DK_PGOProfile:
910     return LLVMRustDiagnosticKind::PGOProfile;
911   default:
912     return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
913                ? LLVMRustDiagnosticKind::OptimizationRemarkOther
914                : LLVMRustDiagnosticKind::Other;
915   }
916 }
917
918 extern "C" LLVMRustDiagnosticKind
919 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
920   return toRust((DiagnosticKind)unwrap(DI)->getKind());
921 }
922 // This is kept distinct from LLVMGetTypeKind, because when
923 // a new type kind is added, the Rust-side enum must be
924 // updated or UB will result.
925 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
926   switch (unwrap(Ty)->getTypeID()) {
927   case Type::VoidTyID:
928     return LLVMVoidTypeKind;
929   case Type::HalfTyID:
930     return LLVMHalfTypeKind;
931   case Type::FloatTyID:
932     return LLVMFloatTypeKind;
933   case Type::DoubleTyID:
934     return LLVMDoubleTypeKind;
935   case Type::X86_FP80TyID:
936     return LLVMX86_FP80TypeKind;
937   case Type::FP128TyID:
938     return LLVMFP128TypeKind;
939   case Type::PPC_FP128TyID:
940     return LLVMPPC_FP128TypeKind;
941   case Type::LabelTyID:
942     return LLVMLabelTypeKind;
943   case Type::MetadataTyID:
944     return LLVMMetadataTypeKind;
945   case Type::IntegerTyID:
946     return LLVMIntegerTypeKind;
947   case Type::FunctionTyID:
948     return LLVMFunctionTypeKind;
949   case Type::StructTyID:
950     return LLVMStructTypeKind;
951   case Type::ArrayTyID:
952     return LLVMArrayTypeKind;
953   case Type::PointerTyID:
954     return LLVMPointerTypeKind;
955   case Type::VectorTyID:
956     return LLVMVectorTypeKind;
957   case Type::X86_MMXTyID:
958     return LLVMX86_MMXTypeKind;
959   case Type::TokenTyID:
960     return LLVMTokenTypeKind;
961   }
962   report_fatal_error("Unhandled TypeID.");
963 }
964
965 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
966
967 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
968     LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
969   unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
970 }
971
972 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
973                                                   RustStringRef Str) {
974   RawRustStringOstream OS(Str);
975   unwrap(D)->print("", OS);
976 }
977
978 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
979                                                 LLVMValueRef ParentPad,
980                                                 unsigned ArgCount,
981                                                 LLVMValueRef *LLArgs,
982                                                 const char *Name) {
983   Value **Args = unwrap(LLArgs);
984   if (ParentPad == nullptr) {
985     Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
986     ParentPad = wrap(Constant::getNullValue(Ty));
987   }
988   return wrap(unwrap(B)->CreateCleanupPad(
989       unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
990 }
991
992 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
993                                                 LLVMValueRef CleanupPad,
994                                                 LLVMBasicBlockRef UnwindBB) {
995   CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
996   return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
997 }
998
999 extern "C" LLVMValueRef
1000 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1001                       unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1002   Value **Args = unwrap(LLArgs);
1003   return wrap(unwrap(B)->CreateCatchPad(
1004       unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1005 }
1006
1007 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1008                                               LLVMValueRef Pad,
1009                                               LLVMBasicBlockRef BB) {
1010   return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1011                                               unwrap(BB)));
1012 }
1013
1014 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1015                                                  LLVMValueRef ParentPad,
1016                                                  LLVMBasicBlockRef BB,
1017                                                  unsigned NumHandlers,
1018                                                  const char *Name) {
1019   if (ParentPad == nullptr) {
1020     Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1021     ParentPad = wrap(Constant::getNullValue(Ty));
1022   }
1023   return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1024                                                  NumHandlers, Name));
1025 }
1026
1027 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1028                                    LLVMBasicBlockRef Handler) {
1029   Value *CatchSwitch = unwrap(CatchSwitchRef);
1030   cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1031 }
1032
1033 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1034                                                            LLVMValueRef *Inputs,
1035                                                            unsigned NumInputs) {
1036   return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1037 }
1038
1039 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1040   delete Bundle;
1041 }
1042
1043 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1044                                           LLVMValueRef *Args, unsigned NumArgs,
1045                                           OperandBundleDef *Bundle,
1046                                           const char *Name) {
1047   unsigned Len = Bundle ? 1 : 0;
1048   ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1049   return wrap(unwrap(B)->CreateCall(
1050       unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1051 }
1052
1053 extern "C" LLVMValueRef
1054 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1055                     unsigned NumArgs, LLVMBasicBlockRef Then,
1056                     LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1057                     const char *Name) {
1058   unsigned Len = Bundle ? 1 : 0;
1059   ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1060   return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1061                                       makeArrayRef(unwrap(Args), NumArgs),
1062                                       Bundles, Name));
1063 }
1064
1065 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1066                                                LLVMBasicBlockRef BB) {
1067   auto Point = unwrap(BB)->getFirstInsertionPt();
1068   unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1069 }
1070
1071 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1072                                   const char *Name) {
1073   Triple TargetTriple(unwrap(M)->getTargetTriple());
1074   GlobalObject *GV = unwrap<GlobalObject>(V);
1075   if (!TargetTriple.isOSBinFormatMachO()) {
1076     GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1077   }
1078 }
1079
1080 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1081   GlobalObject *GV = unwrap<GlobalObject>(V);
1082   GV->setComdat(nullptr);
1083 }
1084
1085 enum class LLVMRustLinkage {
1086   ExternalLinkage = 0,
1087   AvailableExternallyLinkage = 1,
1088   LinkOnceAnyLinkage = 2,
1089   LinkOnceODRLinkage = 3,
1090   WeakAnyLinkage = 4,
1091   WeakODRLinkage = 5,
1092   AppendingLinkage = 6,
1093   InternalLinkage = 7,
1094   PrivateLinkage = 8,
1095   ExternalWeakLinkage = 9,
1096   CommonLinkage = 10,
1097 };
1098
1099 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1100   switch (Linkage) {
1101   case LLVMExternalLinkage:
1102     return LLVMRustLinkage::ExternalLinkage;
1103   case LLVMAvailableExternallyLinkage:
1104     return LLVMRustLinkage::AvailableExternallyLinkage;
1105   case LLVMLinkOnceAnyLinkage:
1106     return LLVMRustLinkage::LinkOnceAnyLinkage;
1107   case LLVMLinkOnceODRLinkage:
1108     return LLVMRustLinkage::LinkOnceODRLinkage;
1109   case LLVMWeakAnyLinkage:
1110     return LLVMRustLinkage::WeakAnyLinkage;
1111   case LLVMWeakODRLinkage:
1112     return LLVMRustLinkage::WeakODRLinkage;
1113   case LLVMAppendingLinkage:
1114     return LLVMRustLinkage::AppendingLinkage;
1115   case LLVMInternalLinkage:
1116     return LLVMRustLinkage::InternalLinkage;
1117   case LLVMPrivateLinkage:
1118     return LLVMRustLinkage::PrivateLinkage;
1119   case LLVMExternalWeakLinkage:
1120     return LLVMRustLinkage::ExternalWeakLinkage;
1121   case LLVMCommonLinkage:
1122     return LLVMRustLinkage::CommonLinkage;
1123   default:
1124     report_fatal_error("Invalid LLVMRustLinkage value!");
1125   }
1126 }
1127
1128 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1129   switch (Linkage) {
1130   case LLVMRustLinkage::ExternalLinkage:
1131     return LLVMExternalLinkage;
1132   case LLVMRustLinkage::AvailableExternallyLinkage:
1133     return LLVMAvailableExternallyLinkage;
1134   case LLVMRustLinkage::LinkOnceAnyLinkage:
1135     return LLVMLinkOnceAnyLinkage;
1136   case LLVMRustLinkage::LinkOnceODRLinkage:
1137     return LLVMLinkOnceODRLinkage;
1138   case LLVMRustLinkage::WeakAnyLinkage:
1139     return LLVMWeakAnyLinkage;
1140   case LLVMRustLinkage::WeakODRLinkage:
1141     return LLVMWeakODRLinkage;
1142   case LLVMRustLinkage::AppendingLinkage:
1143     return LLVMAppendingLinkage;
1144   case LLVMRustLinkage::InternalLinkage:
1145     return LLVMInternalLinkage;
1146   case LLVMRustLinkage::PrivateLinkage:
1147     return LLVMPrivateLinkage;
1148   case LLVMRustLinkage::ExternalWeakLinkage:
1149     return LLVMExternalWeakLinkage;
1150   case LLVMRustLinkage::CommonLinkage:
1151     return LLVMCommonLinkage;
1152   }
1153   report_fatal_error("Invalid LLVMRustLinkage value!");
1154 }
1155
1156 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1157   return toRust(LLVMGetLinkage(V));
1158 }
1159
1160 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1161                                    LLVMRustLinkage RustLinkage) {
1162   LLVMSetLinkage(V, fromRust(RustLinkage));
1163 }
1164
1165 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1166 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1167 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1168 {
1169     auto C = unwrap<llvm::ConstantInt>(CV);
1170     if (C->getBitWidth() > 128) { return false; }
1171     APInt AP;
1172     if (sext) {
1173         AP = C->getValue().sextOrSelf(128);
1174     } else {
1175         AP = C->getValue().zextOrSelf(128);
1176     }
1177     *low = AP.getLoBits(64).getZExtValue();
1178     *high = AP.getHiBits(64).getZExtValue();
1179     return true;
1180 }
1181
1182 enum class LLVMRustVisibility {
1183   Default = 0,
1184   Hidden = 1,
1185   Protected = 2,
1186 };
1187
1188 static LLVMRustVisibility toRust(LLVMVisibility Vis) {
1189   switch (Vis) {
1190   case LLVMDefaultVisibility:
1191     return LLVMRustVisibility::Default;
1192   case LLVMHiddenVisibility:
1193     return LLVMRustVisibility::Hidden;
1194   case LLVMProtectedVisibility:
1195     return LLVMRustVisibility::Protected;
1196   }
1197   report_fatal_error("Invalid LLVMRustVisibility value!");
1198 }
1199
1200 static LLVMVisibility fromRust(LLVMRustVisibility Vis) {
1201   switch (Vis) {
1202   case LLVMRustVisibility::Default:
1203     return LLVMDefaultVisibility;
1204   case LLVMRustVisibility::Hidden:
1205     return LLVMHiddenVisibility;
1206   case LLVMRustVisibility::Protected:
1207     return LLVMProtectedVisibility;
1208   }
1209   report_fatal_error("Invalid LLVMRustVisibility value!");
1210 }
1211
1212 extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) {
1213   return toRust(LLVMGetVisibility(V));
1214 }
1215
1216 // Oh hey, a binding that makes sense for once? (because LLVM’s own do not)
1217 extern "C" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
1218                                              LLVMTypeRef DestTy, bool isSigned) {
1219   return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, ""));
1220 }
1221
1222 extern "C" void LLVMRustSetVisibility(LLVMValueRef V,
1223                                       LLVMRustVisibility RustVisibility) {
1224   LLVMSetVisibility(V, fromRust(RustVisibility));
1225 }
1226
1227 struct LLVMRustModuleBuffer {
1228   std::string data;
1229 };
1230
1231 extern "C" LLVMRustModuleBuffer*
1232 LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1233   auto Ret = llvm::make_unique<LLVMRustModuleBuffer>();
1234   {
1235     raw_string_ostream OS(Ret->data);
1236     {
1237       legacy::PassManager PM;
1238       PM.add(createBitcodeWriterPass(OS));
1239       PM.run(*unwrap(M));
1240     }
1241   }
1242   return Ret.release();
1243 }
1244
1245 extern "C" void
1246 LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1247   delete Buffer;
1248 }
1249
1250 extern "C" const void*
1251 LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
1252   return Buffer->data.data();
1253 }
1254
1255 extern "C" size_t
1256 LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1257   return Buffer->data.length();
1258 }
1259
1260 extern "C" uint64_t
1261 LLVMRustModuleCost(LLVMModuleRef M) {
1262   auto f = unwrap(M)->functions();
1263   return std::distance(std::begin(f), std::end(f));
1264 }
1265
1266 // Vector reductions:
1267 extern "C" LLVMValueRef
1268 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1269     return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1270 }
1271 extern "C" LLVMValueRef
1272 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1273     return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1274 }
1275 extern "C" LLVMValueRef
1276 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1277     return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1278 }
1279 extern "C" LLVMValueRef
1280 LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1281     return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1282 }
1283 extern "C" LLVMValueRef
1284 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1285     return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1286 }
1287 extern "C" LLVMValueRef
1288 LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1289     return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1290 }
1291 extern "C" LLVMValueRef
1292 LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1293     return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1294 }
1295 extern "C" LLVMValueRef
1296 LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1297     return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1298 }
1299 extern "C" LLVMValueRef
1300 LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1301     return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1302 }
1303 extern "C" LLVMValueRef
1304 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1305    return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN));
1306 }
1307 extern "C" LLVMValueRef
1308 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1309   return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN));
1310 }
1311
1312 #if LLVM_VERSION_GE(6, 0)
1313 extern "C" LLVMValueRef
1314 LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1315     return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1316 }
1317 extern "C" LLVMValueRef
1318 LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1319     return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));
1320 }
1321 #else
1322 extern "C" LLVMValueRef
1323 LLVMRustBuildMinNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1324    return nullptr;
1325 }
1326 extern "C" LLVMValueRef
1327 LLVMRustBuildMaxNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1328    return nullptr;
1329 }
1330 #endif