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.
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.
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"
20 #include "llvm/IR/CallSite.h"
22 #if LLVM_VERSION_GE(5, 0)
23 #include "llvm/ADT/Optional.h"
28 //===----------------------------------------------------------------------===
30 // This file defines alternate interfaces to core functions that are more
31 // readily callable by Rust's FFI.
33 //===----------------------------------------------------------------------===
36 using namespace llvm::sys;
37 using namespace llvm::object;
39 // LLVMAtomicOrdering is already an enum - don't create another
41 static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
43 case LLVMAtomicOrderingNotAtomic:
44 return AtomicOrdering::NotAtomic;
45 case LLVMAtomicOrderingUnordered:
46 return AtomicOrdering::Unordered;
47 case LLVMAtomicOrderingMonotonic:
48 return AtomicOrdering::Monotonic;
49 case LLVMAtomicOrderingAcquire:
50 return AtomicOrdering::Acquire;
51 case LLVMAtomicOrderingRelease:
52 return AtomicOrdering::Release;
53 case LLVMAtomicOrderingAcquireRelease:
54 return AtomicOrdering::AcquireRelease;
55 case LLVMAtomicOrderingSequentiallyConsistent:
56 return AtomicOrdering::SequentiallyConsistent;
59 report_fatal_error("Invalid LLVMAtomicOrdering value!");
62 static LLVM_THREAD_LOCAL char *LastError;
64 extern "C" LLVMMemoryBufferRef
65 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
66 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
67 MemoryBuffer::getFile(Path, -1, false);
69 LLVMRustSetLastError(BufOr.getError().message().c_str());
72 return wrap(BufOr.get().release());
75 extern "C" char *LLVMRustGetLastError(void) {
76 char *Ret = LastError;
81 extern "C" void LLVMRustSetLastError(const char *Err) {
82 free((void *)LastError);
83 LastError = strdup(Err);
86 extern "C" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) {
87 auto ctx = new LLVMContext();
88 ctx->setDiscardValueNames(shouldDiscardNames);
92 extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
94 unwrap(M)->setTargetTriple(Triple::normalize(Triple));
97 extern "C" void LLVMRustPrintPassTimings() {
98 raw_fd_ostream OS(2, false); // stderr.
99 TimerGroup::printAll(OS);
102 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
104 return wrap(unwrap(M)->getNamedValue(Name));
107 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
109 LLVMTypeRef FunctionTy) {
111 unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy)));
114 extern "C" LLVMValueRef
115 LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
116 return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
119 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
120 return wrap(Type::getMetadataTy(*unwrap(C)));
123 static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
126 return Attribute::AlwaysInline;
128 return Attribute::ByVal;
130 return Attribute::Cold;
132 return Attribute::InlineHint;
134 return Attribute::MinSize;
136 return Attribute::Naked;
138 return Attribute::NoAlias;
140 return Attribute::NoCapture;
142 return Attribute::NoInline;
144 return Attribute::NonNull;
146 return Attribute::NoRedZone;
148 return Attribute::NoReturn;
150 return Attribute::NoUnwind;
151 case OptimizeForSize:
152 return Attribute::OptimizeForSize;
154 return Attribute::ReadOnly;
156 return Attribute::SExt;
158 return Attribute::StructRet;
160 return Attribute::UWTable;
162 return Attribute::ZExt;
164 return Attribute::InReg;
166 return Attribute::SanitizeThread;
167 case SanitizeAddress:
168 return Attribute::SanitizeAddress;
170 return Attribute::SanitizeMemory;
172 report_fatal_error("bad AttributeKind");
175 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
176 LLVMRustAttribute RustAttr) {
177 CallSite Call = CallSite(unwrap<Instruction>(Instr));
178 Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
179 #if LLVM_VERSION_GE(5, 0)
180 Call.addAttribute(Index, Attr);
183 Call.setAttributes(Call.getAttributes().addAttributes(
184 Call->getContext(), Index,
185 AttributeSet::get(Call->getContext(), Index, B)));
189 extern "C" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr,
192 CallSite Call = CallSite(unwrap<Instruction>(Instr));
194 B.addAlignmentAttr(Bytes);
195 #if LLVM_VERSION_GE(5, 0)
196 Call.setAttributes(Call.getAttributes().addAttributes(
197 Call->getContext(), Index, B));
199 Call.setAttributes(Call.getAttributes().addAttributes(
200 Call->getContext(), Index,
201 AttributeSet::get(Call->getContext(), Index, B)));
205 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
208 CallSite Call = CallSite(unwrap<Instruction>(Instr));
210 B.addDereferenceableAttr(Bytes);
211 #if LLVM_VERSION_GE(5, 0)
212 Call.setAttributes(Call.getAttributes().addAttributes(
213 Call->getContext(), Index, B));
215 Call.setAttributes(Call.getAttributes().addAttributes(
216 Call->getContext(), Index,
217 AttributeSet::get(Call->getContext(), Index, B)));
221 extern "C" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr,
224 CallSite Call = CallSite(unwrap<Instruction>(Instr));
226 B.addDereferenceableOrNullAttr(Bytes);
227 #if LLVM_VERSION_GE(5, 0)
228 Call.setAttributes(Call.getAttributes().addAttributes(
229 Call->getContext(), Index, B));
231 Call.setAttributes(Call.getAttributes().addAttributes(
232 Call->getContext(), Index,
233 AttributeSet::get(Call->getContext(), Index, B)));
237 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
238 LLVMRustAttribute RustAttr) {
239 Function *A = unwrap<Function>(Fn);
240 Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
242 #if LLVM_VERSION_GE(5, 0)
243 A->addAttributes(Index, B);
245 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
249 extern "C" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn,
252 Function *A = unwrap<Function>(Fn);
254 B.addAlignmentAttr(Bytes);
255 #if LLVM_VERSION_GE(5, 0)
256 A->addAttributes(Index, B);
258 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
262 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
264 Function *A = unwrap<Function>(Fn);
266 B.addDereferenceableAttr(Bytes);
267 #if LLVM_VERSION_GE(5, 0)
268 A->addAttributes(Index, B);
270 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
274 extern "C" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn,
277 Function *A = unwrap<Function>(Fn);
279 B.addDereferenceableOrNullAttr(Bytes);
280 #if LLVM_VERSION_GE(5, 0)
281 A->addAttributes(Index, B);
283 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
287 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
291 Function *F = unwrap<Function>(Fn);
293 B.addAttribute(Name, Value);
294 #if LLVM_VERSION_GE(5, 0)
295 F->addAttributes(Index, B);
297 F->addAttributes(Index, AttributeSet::get(F->getContext(), Index, B));
301 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
303 LLVMRustAttribute RustAttr) {
304 Function *F = unwrap<Function>(Fn);
305 Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
307 auto PAL = F->getAttributes();
308 #if LLVM_VERSION_GE(5, 0)
309 auto PALNew = PAL.removeAttributes(F->getContext(), Index, B);
311 const AttributeSet PALNew = PAL.removeAttributes(
312 F->getContext(), Index, AttributeSet::get(F->getContext(), Index, B));
314 F->setAttributes(PALNew);
317 // enable fpmath flag UnsafeAlgebra
318 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
319 if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
320 #if LLVM_VERSION_GE(6, 0)
323 I->setHasUnsafeAlgebra(true);
328 extern "C" LLVMValueRef
329 LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
330 LLVMAtomicOrdering Order) {
331 LoadInst *LI = new LoadInst(unwrap(Source), 0);
332 LI->setAtomic(fromRust(Order));
333 return wrap(unwrap(B)->Insert(LI, Name));
336 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
339 LLVMAtomicOrdering Order) {
340 StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
341 SI->setAtomic(fromRust(Order));
342 return wrap(unwrap(B)->Insert(SI));
345 extern "C" LLVMValueRef
346 LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
347 LLVMValueRef Old, LLVMValueRef Source,
348 LLVMAtomicOrdering Order,
349 LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
350 AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
351 unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
352 fromRust(FailureOrder));
357 enum class LLVMRustSynchronizationScope {
363 #if LLVM_VERSION_GE(5, 0)
364 static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) {
366 case LLVMRustSynchronizationScope::SingleThread:
367 return SyncScope::SingleThread;
368 case LLVMRustSynchronizationScope::CrossThread:
369 return SyncScope::System;
371 report_fatal_error("bad SynchronizationScope.");
375 static SynchronizationScope fromRust(LLVMRustSynchronizationScope Scope) {
377 case LLVMRustSynchronizationScope::SingleThread:
379 case LLVMRustSynchronizationScope::CrossThread:
382 report_fatal_error("bad SynchronizationScope.");
387 extern "C" LLVMValueRef
388 LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
389 LLVMRustSynchronizationScope Scope) {
390 return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
393 enum class LLVMRustAsmDialect {
399 static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
401 case LLVMRustAsmDialect::Att:
402 return InlineAsm::AD_ATT;
403 case LLVMRustAsmDialect::Intel:
404 return InlineAsm::AD_Intel;
406 report_fatal_error("bad AsmDialect.");
410 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
412 LLVMBool HasSideEffects,
413 LLVMBool IsAlignStack,
414 LLVMRustAsmDialect Dialect) {
415 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
416 HasSideEffects, IsAlignStack, fromRust(Dialect)));
419 extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
420 unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
423 typedef DIBuilder *LLVMRustDIBuilderRef;
425 #if LLVM_VERSION_LT(5, 0)
426 typedef struct LLVMOpaqueMetadata *LLVMMetadataRef;
429 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef)
431 inline Metadata **unwrap(LLVMMetadataRef *Vals) {
432 return reinterpret_cast<Metadata **>(Vals);
437 template <typename DIT> DIT *unwrapDIPtr(LLVMMetadataRef Ref) {
438 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
441 #define DIDescriptor DIScope
442 #define DIArray DINodeArray
443 #define unwrapDI unwrapDIPtr
445 // These values **must** match debuginfo::DIFlags! They also *happen*
446 // to match LLVM, but that isn't required as we do giant sets of
447 // matching below. The value shouldn't be directly passed to LLVM.
448 enum class LLVMRustDIFlags : uint32_t {
453 FlagFwdDecl = (1 << 2),
454 FlagAppleBlock = (1 << 3),
455 FlagBlockByrefStruct = (1 << 4),
456 FlagVirtual = (1 << 5),
457 FlagArtificial = (1 << 6),
458 FlagExplicit = (1 << 7),
459 FlagPrototyped = (1 << 8),
460 FlagObjcClassComplete = (1 << 9),
461 FlagObjectPointer = (1 << 10),
462 FlagVector = (1 << 11),
463 FlagStaticMember = (1 << 12),
464 FlagLValueReference = (1 << 13),
465 FlagRValueReference = (1 << 14),
466 FlagExternalTypeRef = (1 << 15),
467 FlagIntroducedVirtual = (1 << 18),
468 FlagBitField = (1 << 19),
469 FlagNoReturn = (1 << 20),
470 FlagMainSubprogram = (1 << 21),
471 // Do not add values that are not supported by the minimum LLVM
472 // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
475 inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
476 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
477 static_cast<uint32_t>(B));
480 inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
481 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
482 static_cast<uint32_t>(B));
485 inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
489 inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
491 inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
492 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
495 #if LLVM_VERSION_GE(4, 0)
496 static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
497 DINode::DIFlags Result = DINode::DIFlags::FlagZero;
499 static unsigned fromRust(LLVMRustDIFlags Flags) {
503 switch (visibility(Flags)) {
504 case LLVMRustDIFlags::FlagPrivate:
505 Result |= DINode::DIFlags::FlagPrivate;
507 case LLVMRustDIFlags::FlagProtected:
508 Result |= DINode::DIFlags::FlagProtected;
510 case LLVMRustDIFlags::FlagPublic:
511 Result |= DINode::DIFlags::FlagPublic;
514 // The rest are handled below
518 if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
519 Result |= DINode::DIFlags::FlagFwdDecl;
521 if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
522 Result |= DINode::DIFlags::FlagAppleBlock;
524 if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
525 Result |= DINode::DIFlags::FlagBlockByrefStruct;
527 if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
528 Result |= DINode::DIFlags::FlagVirtual;
530 if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
531 Result |= DINode::DIFlags::FlagArtificial;
533 if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
534 Result |= DINode::DIFlags::FlagExplicit;
536 if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
537 Result |= DINode::DIFlags::FlagPrototyped;
539 if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
540 Result |= DINode::DIFlags::FlagObjcClassComplete;
542 if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
543 Result |= DINode::DIFlags::FlagObjectPointer;
545 if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
546 Result |= DINode::DIFlags::FlagVector;
548 if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
549 Result |= DINode::DIFlags::FlagStaticMember;
551 if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
552 Result |= DINode::DIFlags::FlagLValueReference;
554 if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
555 Result |= DINode::DIFlags::FlagRValueReference;
557 #if LLVM_VERSION_LE(4, 0)
558 if (isSet(Flags & LLVMRustDIFlags::FlagExternalTypeRef)) {
559 Result |= DINode::DIFlags::FlagExternalTypeRef;
562 if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) {
563 Result |= DINode::DIFlags::FlagIntroducedVirtual;
565 if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) {
566 Result |= DINode::DIFlags::FlagBitField;
568 #if LLVM_RUSTLLVM || LLVM_VERSION_GE(4, 0)
569 if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) {
570 Result |= DINode::DIFlags::FlagNoReturn;
572 if (isSet(Flags & LLVMRustDIFlags::FlagMainSubprogram)) {
573 Result |= DINode::DIFlags::FlagMainSubprogram;
580 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
581 return DEBUG_METADATA_VERSION;
584 extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
586 extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
588 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
590 unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
593 extern "C" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
594 return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
597 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
598 return new DIBuilder(*unwrap(M));
601 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
605 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
609 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
610 LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
611 const char *Producer, bool isOptimized, const char *Flags,
612 unsigned RuntimeVer, const char *SplitName) {
613 auto *File = unwrapDI<DIFile>(FileRef);
615 #if LLVM_VERSION_GE(4, 0)
616 return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
617 Flags, RuntimeVer, SplitName));
619 return wrap(Builder->createCompileUnit(Lang, File->getFilename(),
620 File->getDirectory(), Producer, isOptimized,
621 Flags, RuntimeVer, SplitName));
625 extern "C" LLVMMetadataRef
626 LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
627 const char *Directory) {
628 return wrap(Builder->createFile(Filename, Directory));
631 extern "C" LLVMMetadataRef
632 LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
633 LLVMMetadataRef File,
634 LLVMMetadataRef ParameterTypes) {
635 return wrap(Builder->createSubroutineType(
636 DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
639 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
640 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
641 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
642 LLVMMetadataRef Ty, bool IsLocalToUnit, bool IsDefinition,
643 unsigned ScopeLine, LLVMRustDIFlags Flags, bool IsOptimized,
644 LLVMValueRef Fn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) {
645 DITemplateParameterArray TParams =
646 DITemplateParameterArray(unwrap<MDTuple>(TParam));
647 DISubprogram *Sub = Builder->createFunction(
648 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
649 LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
650 ScopeLine, fromRust(Flags), IsOptimized, TParams,
651 unwrapDIPtr<DISubprogram>(Decl));
652 unwrap<Function>(Fn)->setSubprogram(Sub);
656 extern "C" LLVMMetadataRef
657 LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
658 uint64_t SizeInBits, uint32_t AlignInBits,
660 return wrap(Builder->createBasicType(Name, SizeInBits,
661 #if LLVM_VERSION_LE(3, 9)
667 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
668 LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
669 uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
670 return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
671 SizeInBits, AlignInBits,
672 #if LLVM_VERSION_GE(5, 0)
673 /* DWARFAddressSpace */ None,
678 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
679 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
680 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
681 uint32_t AlignInBits, LLVMRustDIFlags Flags,
682 LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
683 unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
684 const char *UniqueId) {
685 return wrap(Builder->createStructType(
686 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
687 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
688 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
689 unwrapDI<DIType>(VTableHolder), UniqueId));
692 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
693 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
694 LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
695 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
696 LLVMMetadataRef Ty) {
697 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
698 unwrapDI<DIFile>(File), LineNo,
699 SizeInBits, AlignInBits, OffsetInBits,
700 fromRust(Flags), unwrapDI<DIType>(Ty)));
703 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
704 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
705 LLVMMetadataRef File, unsigned Line, unsigned Col) {
706 return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
707 unwrapDI<DIFile>(File), Line, Col));
710 extern "C" LLVMMetadataRef
711 LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
712 LLVMMetadataRef Scope,
713 LLVMMetadataRef File) {
714 return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
715 unwrapDI<DIFile>(File)));
718 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
719 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
720 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
721 LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
722 LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
723 llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
725 #if LLVM_VERSION_GE(4, 0)
726 llvm::DIExpression *InitExpr = nullptr;
727 if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
728 InitExpr = Builder->createConstantValueExpression(
729 IntVal->getValue().getSExtValue());
730 } else if (llvm::ConstantFP *FPVal =
731 llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
732 InitExpr = Builder->createConstantValueExpression(
733 FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
736 llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
737 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
738 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
739 InitExpr, unwrapDIPtr<MDNode>(Decl), AlignInBits);
741 InitVal->setMetadata("dbg", VarExpr);
743 return wrap(VarExpr);
745 return wrap(Builder->createGlobalVariable(
746 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
747 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
748 InitVal, unwrapDIPtr<MDNode>(Decl)));
752 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
753 LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
754 const char *Name, LLVMMetadataRef File, unsigned LineNo,
755 LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
756 unsigned ArgNo, uint32_t AlignInBits) {
757 if (Tag == 0x100) { // DW_TAG_auto_variable
758 return wrap(Builder->createAutoVariable(
759 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
760 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)
761 #if LLVM_VERSION_GE(4, 0)
767 return wrap(Builder->createParameterVariable(
768 unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
769 LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
773 extern "C" LLVMMetadataRef
774 LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
775 uint32_t AlignInBits, LLVMMetadataRef Ty,
776 LLVMMetadataRef Subscripts) {
778 Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
779 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
782 extern "C" LLVMMetadataRef
783 LLVMRustDIBuilderCreateVectorType(LLVMRustDIBuilderRef Builder, uint64_t Size,
784 uint32_t AlignInBits, LLVMMetadataRef Ty,
785 LLVMMetadataRef Subscripts) {
787 Builder->createVectorType(Size, AlignInBits, unwrapDI<DIType>(Ty),
788 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
791 extern "C" LLVMMetadataRef
792 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
794 return wrap(Builder->getOrCreateSubrange(Lo, Count));
797 extern "C" LLVMMetadataRef
798 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
799 LLVMMetadataRef *Ptr, unsigned Count) {
800 Metadata **DataValue = unwrap(Ptr);
802 Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
805 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
806 LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
807 int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
808 LLVMBasicBlockRef InsertAtEnd) {
809 return wrap(Builder->insertDeclare(
810 unwrap(V), unwrap<DILocalVariable>(VarInfo),
811 Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
812 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
813 unwrap(InsertAtEnd)));
816 extern "C" LLVMMetadataRef
817 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
818 const char *Name, uint64_t Val) {
819 return wrap(Builder->createEnumerator(Name, Val));
822 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
823 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
824 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
825 uint32_t AlignInBits, LLVMMetadataRef Elements,
826 LLVMMetadataRef ClassTy) {
827 return wrap(Builder->createEnumerationType(
828 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
829 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
830 unwrapDI<DIType>(ClassTy)));
833 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
834 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
835 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
836 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
837 unsigned RunTimeLang, const char *UniqueId) {
838 return wrap(Builder->createUnionType(
839 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
840 SizeInBits, AlignInBits, fromRust(Flags),
841 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
844 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
845 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
846 LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
848 return wrap(Builder->createTemplateTypeParameter(
849 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
852 extern "C" LLVMMetadataRef
853 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
854 LLVMMetadataRef Scope, const char *Name,
855 LLVMMetadataRef File, unsigned LineNo) {
856 return wrap(Builder->createNameSpace(
857 unwrapDI<DIDescriptor>(Scope), Name
858 #if LLVM_VERSION_LT(5, 0)
860 unwrapDI<DIFile>(File), LineNo
862 #if LLVM_VERSION_GE(4, 0)
864 false // ExportSymbols (only relevant for C++ anonymous namespaces)
870 LLVMRustDICompositeTypeSetTypeArray(LLVMRustDIBuilderRef Builder,
871 LLVMMetadataRef CompositeTy,
872 LLVMMetadataRef TyArray) {
873 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
874 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(TyArray)));
877 extern "C" LLVMValueRef
878 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
879 unsigned Column, LLVMMetadataRef Scope,
880 LLVMMetadataRef InlinedAt) {
881 LLVMContext &Context = *unwrap(ContextRef);
883 DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
884 unwrapDIPtr<MDNode>(InlinedAt));
886 return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
889 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
890 return dwarf::DW_OP_deref;
893 extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
894 #if LLVM_VERSION_GE(5, 0)
895 return dwarf::DW_OP_plus_uconst;
897 // older LLVM used `plus` to behave like `plus_uconst`.
898 return dwarf::DW_OP_plus;
902 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
903 RawRustStringOstream OS(Str);
904 unwrap<llvm::Type>(Ty)->print(OS);
907 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
909 RawRustStringOstream OS(Str);
914 unwrap<llvm::Value>(V)->getType()->print(OS);
916 unwrap<llvm::Value>(V)->print(OS);
921 // Note that the two following functions look quite similar to the
922 // LLVMGetSectionName function. Sadly, it appears that this function only
923 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
924 // function provided by LLVM doesn't return the length, so we've created our own
925 // function which returns the length as well as the data pointer.
927 // For an example of this not returning a null terminated string, see
928 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
929 // branches explicitly creates a StringRef without a null terminator, and then
932 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
933 return reinterpret_cast<section_iterator *>(SI);
936 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
939 if (std::error_code EC = (*unwrap(SI))->getName(Ret))
940 report_fatal_error(EC.message());
945 // LLVMArrayType function does not support 64-bit ElementCount
946 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
947 uint64_t ElementCount) {
948 return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
951 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
953 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
954 RawRustStringOstream OS(Str);
955 unwrap(T)->print(OS);
958 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
959 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
960 LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
961 RustStringRef FilenameOut, RustStringRef MessageOut) {
962 // Undefined to call this not on an optimization diagnostic!
963 llvm::DiagnosticInfoOptimizationBase *Opt =
964 static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
966 RawRustStringOstream PassNameOS(PassNameOut);
967 PassNameOS << Opt->getPassName();
968 *FunctionOut = wrap(&Opt->getFunction());
970 RawRustStringOstream FilenameOS(FilenameOut);
971 #if LLVM_VERSION_GE(5,0)
972 DiagnosticLocation loc = Opt->getLocation();
974 *Line = loc.getLine();
975 *Column = loc.getColumn();
976 FilenameOS << loc.getFilename();
979 const DebugLoc &loc = Opt->getDebugLoc();
981 *Line = loc.getLine();
982 *Column = loc.getCol();
983 FilenameOS << cast<DIScope>(loc.getScope())->getFilename();
987 RawRustStringOstream MessageOS(MessageOut);
988 MessageOS << Opt->getMsg();
992 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
993 LLVMTwineRef *MessageOut,
994 LLVMValueRef *InstructionOut) {
995 // Undefined to call this not on an inline assembly diagnostic!
996 llvm::DiagnosticInfoInlineAsm *IA =
997 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
999 *CookieOut = IA->getLocCookie();
1000 *MessageOut = wrap(&IA->getMsgStr());
1001 *InstructionOut = wrap(IA->getInstruction());
1004 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
1005 RustStringRef Str) {
1006 RawRustStringOstream OS(Str);
1007 DiagnosticPrinterRawOStream DP(OS);
1008 unwrap(DI)->print(DP);
1011 enum class LLVMRustDiagnosticKind {
1015 DebugMetadataVersion,
1018 OptimizationRemarkMissed,
1019 OptimizationRemarkAnalysis,
1020 OptimizationRemarkAnalysisFPCommute,
1021 OptimizationRemarkAnalysisAliasing,
1022 OptimizationRemarkOther,
1023 OptimizationFailure,
1026 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
1029 return LLVMRustDiagnosticKind::InlineAsm;
1031 return LLVMRustDiagnosticKind::StackSize;
1032 case DK_DebugMetadataVersion:
1033 return LLVMRustDiagnosticKind::DebugMetadataVersion;
1034 case DK_SampleProfile:
1035 return LLVMRustDiagnosticKind::SampleProfile;
1036 case DK_OptimizationRemark:
1037 return LLVMRustDiagnosticKind::OptimizationRemark;
1038 case DK_OptimizationRemarkMissed:
1039 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
1040 case DK_OptimizationRemarkAnalysis:
1041 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
1042 case DK_OptimizationRemarkAnalysisFPCommute:
1043 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
1044 case DK_OptimizationRemarkAnalysisAliasing:
1045 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
1047 return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
1048 ? LLVMRustDiagnosticKind::OptimizationRemarkOther
1049 : LLVMRustDiagnosticKind::Other;
1053 extern "C" LLVMRustDiagnosticKind
1054 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
1055 return toRust((DiagnosticKind)unwrap(DI)->getKind());
1057 // This is kept distinct from LLVMGetTypeKind, because when
1058 // a new type kind is added, the Rust-side enum must be
1059 // updated or UB will result.
1060 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
1061 switch (unwrap(Ty)->getTypeID()) {
1062 case Type::VoidTyID:
1063 return LLVMVoidTypeKind;
1064 case Type::HalfTyID:
1065 return LLVMHalfTypeKind;
1066 case Type::FloatTyID:
1067 return LLVMFloatTypeKind;
1068 case Type::DoubleTyID:
1069 return LLVMDoubleTypeKind;
1070 case Type::X86_FP80TyID:
1071 return LLVMX86_FP80TypeKind;
1072 case Type::FP128TyID:
1073 return LLVMFP128TypeKind;
1074 case Type::PPC_FP128TyID:
1075 return LLVMPPC_FP128TypeKind;
1076 case Type::LabelTyID:
1077 return LLVMLabelTypeKind;
1078 case Type::MetadataTyID:
1079 return LLVMMetadataTypeKind;
1080 case Type::IntegerTyID:
1081 return LLVMIntegerTypeKind;
1082 case Type::FunctionTyID:
1083 return LLVMFunctionTypeKind;
1084 case Type::StructTyID:
1085 return LLVMStructTypeKind;
1086 case Type::ArrayTyID:
1087 return LLVMArrayTypeKind;
1088 case Type::PointerTyID:
1089 return LLVMPointerTypeKind;
1090 case Type::VectorTyID:
1091 return LLVMVectorTypeKind;
1092 case Type::X86_MMXTyID:
1093 return LLVMX86_MMXTypeKind;
1094 case Type::TokenTyID:
1095 return LLVMTokenTypeKind;
1097 report_fatal_error("Unhandled TypeID.");
1100 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
1102 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
1103 LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
1104 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
1107 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
1108 RustStringRef Str) {
1109 RawRustStringOstream OS(Str);
1110 unwrap(D)->print("", OS);
1113 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
1114 LLVMValueRef ParentPad,
1116 LLVMValueRef *LLArgs,
1118 Value **Args = unwrap(LLArgs);
1119 if (ParentPad == nullptr) {
1120 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1121 ParentPad = wrap(Constant::getNullValue(Ty));
1123 return wrap(unwrap(B)->CreateCleanupPad(
1124 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1127 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
1128 LLVMValueRef CleanupPad,
1129 LLVMBasicBlockRef UnwindBB) {
1130 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
1131 return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
1134 extern "C" LLVMValueRef
1135 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1136 unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1137 Value **Args = unwrap(LLArgs);
1138 return wrap(unwrap(B)->CreateCatchPad(
1139 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1142 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1144 LLVMBasicBlockRef BB) {
1145 return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1149 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1150 LLVMValueRef ParentPad,
1151 LLVMBasicBlockRef BB,
1152 unsigned NumHandlers,
1154 if (ParentPad == nullptr) {
1155 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1156 ParentPad = wrap(Constant::getNullValue(Ty));
1158 return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1159 NumHandlers, Name));
1162 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1163 LLVMBasicBlockRef Handler) {
1164 Value *CatchSwitch = unwrap(CatchSwitchRef);
1165 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1168 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1169 LLVMValueRef *Inputs,
1170 unsigned NumInputs) {
1171 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1174 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1178 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1179 LLVMValueRef *Args, unsigned NumArgs,
1180 OperandBundleDef *Bundle,
1182 unsigned Len = Bundle ? 1 : 0;
1183 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1184 return wrap(unwrap(B)->CreateCall(
1185 unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1188 extern "C" LLVMValueRef
1189 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1190 unsigned NumArgs, LLVMBasicBlockRef Then,
1191 LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1193 unsigned Len = Bundle ? 1 : 0;
1194 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1195 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1196 makeArrayRef(unwrap(Args), NumArgs),
1200 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1201 LLVMBasicBlockRef BB) {
1202 auto Point = unwrap(BB)->getFirstInsertionPt();
1203 unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1206 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1208 Triple TargetTriple(unwrap(M)->getTargetTriple());
1209 GlobalObject *GV = unwrap<GlobalObject>(V);
1210 if (!TargetTriple.isOSBinFormatMachO()) {
1211 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1215 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1216 GlobalObject *GV = unwrap<GlobalObject>(V);
1217 GV->setComdat(nullptr);
1220 enum class LLVMRustLinkage {
1221 ExternalLinkage = 0,
1222 AvailableExternallyLinkage = 1,
1223 LinkOnceAnyLinkage = 2,
1224 LinkOnceODRLinkage = 3,
1227 AppendingLinkage = 6,
1228 InternalLinkage = 7,
1230 ExternalWeakLinkage = 9,
1234 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1236 case LLVMExternalLinkage:
1237 return LLVMRustLinkage::ExternalLinkage;
1238 case LLVMAvailableExternallyLinkage:
1239 return LLVMRustLinkage::AvailableExternallyLinkage;
1240 case LLVMLinkOnceAnyLinkage:
1241 return LLVMRustLinkage::LinkOnceAnyLinkage;
1242 case LLVMLinkOnceODRLinkage:
1243 return LLVMRustLinkage::LinkOnceODRLinkage;
1244 case LLVMWeakAnyLinkage:
1245 return LLVMRustLinkage::WeakAnyLinkage;
1246 case LLVMWeakODRLinkage:
1247 return LLVMRustLinkage::WeakODRLinkage;
1248 case LLVMAppendingLinkage:
1249 return LLVMRustLinkage::AppendingLinkage;
1250 case LLVMInternalLinkage:
1251 return LLVMRustLinkage::InternalLinkage;
1252 case LLVMPrivateLinkage:
1253 return LLVMRustLinkage::PrivateLinkage;
1254 case LLVMExternalWeakLinkage:
1255 return LLVMRustLinkage::ExternalWeakLinkage;
1256 case LLVMCommonLinkage:
1257 return LLVMRustLinkage::CommonLinkage;
1259 report_fatal_error("Invalid LLVMRustLinkage value!");
1263 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1265 case LLVMRustLinkage::ExternalLinkage:
1266 return LLVMExternalLinkage;
1267 case LLVMRustLinkage::AvailableExternallyLinkage:
1268 return LLVMAvailableExternallyLinkage;
1269 case LLVMRustLinkage::LinkOnceAnyLinkage:
1270 return LLVMLinkOnceAnyLinkage;
1271 case LLVMRustLinkage::LinkOnceODRLinkage:
1272 return LLVMLinkOnceODRLinkage;
1273 case LLVMRustLinkage::WeakAnyLinkage:
1274 return LLVMWeakAnyLinkage;
1275 case LLVMRustLinkage::WeakODRLinkage:
1276 return LLVMWeakODRLinkage;
1277 case LLVMRustLinkage::AppendingLinkage:
1278 return LLVMAppendingLinkage;
1279 case LLVMRustLinkage::InternalLinkage:
1280 return LLVMInternalLinkage;
1281 case LLVMRustLinkage::PrivateLinkage:
1282 return LLVMPrivateLinkage;
1283 case LLVMRustLinkage::ExternalWeakLinkage:
1284 return LLVMExternalWeakLinkage;
1285 case LLVMRustLinkage::CommonLinkage:
1286 return LLVMCommonLinkage;
1288 report_fatal_error("Invalid LLVMRustLinkage value!");
1291 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1292 return toRust(LLVMGetLinkage(V));
1295 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1296 LLVMRustLinkage RustLinkage) {
1297 LLVMSetLinkage(V, fromRust(RustLinkage));
1300 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1301 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1302 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1304 auto C = unwrap<llvm::ConstantInt>(CV);
1305 if (C->getBitWidth() > 128) { return false; }
1308 AP = C->getValue().sextOrSelf(128);
1310 AP = C->getValue().zextOrSelf(128);
1312 *low = AP.getLoBits(64).getZExtValue();
1313 *high = AP.getHiBits(64).getZExtValue();
1317 enum class LLVMRustVisibility {
1323 static LLVMRustVisibility toRust(LLVMVisibility Vis) {
1325 case LLVMDefaultVisibility:
1326 return LLVMRustVisibility::Default;
1327 case LLVMHiddenVisibility:
1328 return LLVMRustVisibility::Hidden;
1329 case LLVMProtectedVisibility:
1330 return LLVMRustVisibility::Protected;
1332 report_fatal_error("Invalid LLVMRustVisibility value!");
1335 static LLVMVisibility fromRust(LLVMRustVisibility Vis) {
1337 case LLVMRustVisibility::Default:
1338 return LLVMDefaultVisibility;
1339 case LLVMRustVisibility::Hidden:
1340 return LLVMHiddenVisibility;
1341 case LLVMRustVisibility::Protected:
1342 return LLVMProtectedVisibility;
1344 report_fatal_error("Invalid LLVMRustVisibility value!");
1347 extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) {
1348 return toRust(LLVMGetVisibility(V));
1351 // Oh hey, a binding that makes sense for once? (because LLVM’s own do not)
1352 extern "C" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
1353 LLVMTypeRef DestTy, bool isSigned) {
1354 return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, ""));
1357 extern "C" void LLVMRustSetVisibility(LLVMValueRef V,
1358 LLVMRustVisibility RustVisibility) {
1359 LLVMSetVisibility(V, fromRust(RustVisibility));
1362 struct LLVMRustModuleBuffer {
1366 extern "C" LLVMRustModuleBuffer*
1367 LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1368 auto Ret = llvm::make_unique<LLVMRustModuleBuffer>();
1370 raw_string_ostream OS(Ret->data);
1372 legacy::PassManager PM;
1373 PM.add(createBitcodeWriterPass(OS));
1377 return Ret.release();
1381 LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1385 extern "C" const void*
1386 LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
1387 return Buffer->data.data();
1391 LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1392 return Buffer->data.length();
1396 LLVMRustModuleCost(LLVMModuleRef M) {
1397 auto f = unwrap(M)->functions();
1398 return std::distance(std::begin(f), std::end(f));
1401 // Vector reductions:
1402 #if LLVM_VERSION_GE(5, 0)
1403 extern "C" LLVMValueRef
1404 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1405 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1407 extern "C" LLVMValueRef
1408 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1409 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1411 extern "C" LLVMValueRef
1412 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1413 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1415 extern "C" LLVMValueRef
1416 LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1417 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1419 extern "C" LLVMValueRef
1420 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1421 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1423 extern "C" LLVMValueRef
1424 LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1425 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1427 extern "C" LLVMValueRef
1428 LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1429 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1431 extern "C" LLVMValueRef
1432 LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1433 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1435 extern "C" LLVMValueRef
1436 LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1437 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1439 extern "C" LLVMValueRef
1440 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1441 return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN));
1443 extern "C" LLVMValueRef
1444 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1445 return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN));
1450 extern "C" LLVMValueRef
1451 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1454 extern "C" LLVMValueRef
1455 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1458 extern "C" LLVMValueRef
1459 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef, LLVMValueRef) {
1462 extern "C" LLVMValueRef
1463 LLVMRustBuildVectorReduceMul(LLVMBuilderRef, LLVMValueRef) {
1466 extern "C" LLVMValueRef
1467 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef, LLVMValueRef) {
1470 extern "C" LLVMValueRef
1471 LLVMRustBuildVectorReduceOr(LLVMBuilderRef, LLVMValueRef) {
1474 extern "C" LLVMValueRef
1475 LLVMRustBuildVectorReduceXor(LLVMBuilderRef, LLVMValueRef) {
1478 extern "C" LLVMValueRef
1479 LLVMRustBuildVectorReduceMin(LLVMBuilderRef, LLVMValueRef, bool) {
1482 extern "C" LLVMValueRef
1483 LLVMRustBuildVectorReduceMax(LLVMBuilderRef, LLVMValueRef, bool) {
1486 extern "C" LLVMValueRef
1487 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef, LLVMValueRef, bool) {
1490 extern "C" LLVMValueRef
1491 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef, LLVMValueRef, bool) {
1496 #if LLVM_VERSION_LT(4, 0)
1497 extern "C" LLVMValueRef
1498 LLVMBuildExactUDiv(LLVMBuilderRef B, LLVMValueRef LHS,
1499 LLVMValueRef RHS, const char *Name) {
1500 return wrap(unwrap(B)->CreateExactUDiv(unwrap(LHS), unwrap(RHS), Name));
1504 #if LLVM_VERSION_GE(6, 0)
1505 extern "C" LLVMValueRef
1506 LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1507 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1509 extern "C" LLVMValueRef
1510 LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1511 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));
1514 extern "C" LLVMValueRef
1515 LLVMRustBuildMinNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1518 extern "C" LLVMValueRef
1519 LLVMRustBuildMaxNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {