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/CallSite.h"
13 #include "llvm/IR/DebugInfoMetadata.h"
14 #include "llvm/IR/DiagnosticInfo.h"
15 #include "llvm/IR/DiagnosticPrinter.h"
16 #include "llvm/IR/GlobalVariable.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/Object/Archive.h"
19 #include "llvm/Object/ObjectFile.h"
20 #include "llvm/Bitcode/BitcodeWriterPass.h"
21 #include "llvm/Support/Signals.h"
22 #include "llvm/ADT/Optional.h"
26 //===----------------------------------------------------------------------===
28 // This file defines alternate interfaces to core functions that are more
29 // readily callable by Rust's FFI.
31 //===----------------------------------------------------------------------===
34 using namespace llvm::sys;
35 using namespace llvm::object;
37 // LLVMAtomicOrdering is already an enum - don't create another
39 static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
41 case LLVMAtomicOrderingNotAtomic:
42 return AtomicOrdering::NotAtomic;
43 case LLVMAtomicOrderingUnordered:
44 return AtomicOrdering::Unordered;
45 case LLVMAtomicOrderingMonotonic:
46 return AtomicOrdering::Monotonic;
47 case LLVMAtomicOrderingAcquire:
48 return AtomicOrdering::Acquire;
49 case LLVMAtomicOrderingRelease:
50 return AtomicOrdering::Release;
51 case LLVMAtomicOrderingAcquireRelease:
52 return AtomicOrdering::AcquireRelease;
53 case LLVMAtomicOrderingSequentiallyConsistent:
54 return AtomicOrdering::SequentiallyConsistent;
57 report_fatal_error("Invalid LLVMAtomicOrdering value!");
60 static LLVM_THREAD_LOCAL char *LastError;
62 // Custom error handler for fatal LLVM errors.
64 // Notably it exits the process with code 101, unlike LLVM's default of 1.
65 static void FatalErrorHandler(void *UserData,
66 const std::string& Reason,
68 // Do the same thing that the default error handler does.
69 std::cerr << "LLVM ERROR: " << Reason << std::endl;
71 // Since this error handler exits the process, we have to run any cleanup that
72 // LLVM would run after handling the error. This might change with an LLVM
74 sys::RunInterruptHandlers();
79 extern "C" void LLVMRustInstallFatalErrorHandler() {
80 install_fatal_error_handler(FatalErrorHandler);
83 extern "C" LLVMMemoryBufferRef
84 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
85 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
86 MemoryBuffer::getFile(Path, -1, false);
88 LLVMRustSetLastError(BufOr.getError().message().c_str());
91 return wrap(BufOr.get().release());
94 extern "C" char *LLVMRustGetLastError(void) {
95 char *Ret = LastError;
100 extern "C" void LLVMRustSetLastError(const char *Err) {
101 free((void *)LastError);
102 LastError = strdup(Err);
105 extern "C" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) {
106 auto ctx = new LLVMContext();
107 ctx->setDiscardValueNames(shouldDiscardNames);
111 extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
112 const char *Triple) {
113 unwrap(M)->setTargetTriple(Triple::normalize(Triple));
116 extern "C" void LLVMRustPrintPassTimings() {
117 raw_fd_ostream OS(2, false); // stderr.
118 TimerGroup::printAll(OS);
121 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
123 return wrap(unwrap(M)->getNamedValue(Name));
126 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
128 LLVMTypeRef FunctionTy) {
130 unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy)));
133 extern "C" LLVMValueRef
134 LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
135 return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
138 extern "C" LLVMValueRef
139 LLVMRustInsertPrivateGlobal(LLVMModuleRef M, LLVMTypeRef Ty) {
140 return wrap(new GlobalVariable(*unwrap(M),
143 GlobalValue::PrivateLinkage,
147 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
148 return wrap(Type::getMetadataTy(*unwrap(C)));
151 static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
154 return Attribute::AlwaysInline;
156 return Attribute::ByVal;
158 return Attribute::Cold;
160 return Attribute::InlineHint;
162 return Attribute::MinSize;
164 return Attribute::Naked;
166 return Attribute::NoAlias;
168 return Attribute::NoCapture;
170 return Attribute::NoInline;
172 return Attribute::NonNull;
174 return Attribute::NoRedZone;
176 return Attribute::NoReturn;
178 return Attribute::NoUnwind;
179 case OptimizeForSize:
180 return Attribute::OptimizeForSize;
182 return Attribute::ReadOnly;
184 return Attribute::SExt;
186 return Attribute::StructRet;
188 return Attribute::UWTable;
190 return Attribute::ZExt;
192 return Attribute::InReg;
194 return Attribute::SanitizeThread;
195 case SanitizeAddress:
196 return Attribute::SanitizeAddress;
198 return Attribute::SanitizeMemory;
200 return Attribute::NonLazyBind;
202 report_fatal_error("bad AttributeKind");
205 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
206 LLVMRustAttribute RustAttr) {
207 CallSite Call = CallSite(unwrap<Instruction>(Instr));
208 Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
209 Call.addAttribute(Index, Attr);
212 extern "C" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr,
215 CallSite Call = CallSite(unwrap<Instruction>(Instr));
217 B.addAlignmentAttr(Bytes);
218 Call.setAttributes(Call.getAttributes().addAttributes(
219 Call->getContext(), Index, B));
222 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
225 CallSite Call = CallSite(unwrap<Instruction>(Instr));
227 B.addDereferenceableAttr(Bytes);
228 Call.setAttributes(Call.getAttributes().addAttributes(
229 Call->getContext(), Index, B));
232 extern "C" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr,
235 CallSite Call = CallSite(unwrap<Instruction>(Instr));
237 B.addDereferenceableOrNullAttr(Bytes);
238 Call.setAttributes(Call.getAttributes().addAttributes(
239 Call->getContext(), Index, B));
242 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
243 LLVMRustAttribute RustAttr) {
244 Function *A = unwrap<Function>(Fn);
245 Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
247 A->addAttributes(Index, B);
250 extern "C" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn,
253 Function *A = unwrap<Function>(Fn);
255 B.addAlignmentAttr(Bytes);
256 A->addAttributes(Index, B);
259 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
261 Function *A = unwrap<Function>(Fn);
263 B.addDereferenceableAttr(Bytes);
264 A->addAttributes(Index, B);
267 extern "C" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn,
270 Function *A = unwrap<Function>(Fn);
272 B.addDereferenceableOrNullAttr(Bytes);
273 A->addAttributes(Index, B);
276 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
280 Function *F = unwrap<Function>(Fn);
282 B.addAttribute(Name, Value);
283 F->addAttributes(Index, B);
286 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
288 LLVMRustAttribute RustAttr) {
289 Function *F = unwrap<Function>(Fn);
290 Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
292 auto PAL = F->getAttributes();
293 auto PALNew = PAL.removeAttributes(F->getContext(), Index, B);
294 F->setAttributes(PALNew);
297 // enable fpmath flag UnsafeAlgebra
298 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
299 if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
304 extern "C" LLVMValueRef
305 LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
306 LLVMAtomicOrdering Order) {
307 LoadInst *LI = new LoadInst(unwrap(Source), 0);
308 LI->setAtomic(fromRust(Order));
309 return wrap(unwrap(B)->Insert(LI, Name));
312 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
315 LLVMAtomicOrdering Order) {
316 StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
317 SI->setAtomic(fromRust(Order));
318 return wrap(unwrap(B)->Insert(SI));
321 extern "C" LLVMValueRef
322 LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
323 LLVMValueRef Old, LLVMValueRef Source,
324 LLVMAtomicOrdering Order,
325 LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
326 AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
327 unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
328 fromRust(FailureOrder));
333 enum class LLVMRustSynchronizationScope {
339 static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) {
341 case LLVMRustSynchronizationScope::SingleThread:
342 return SyncScope::SingleThread;
343 case LLVMRustSynchronizationScope::CrossThread:
344 return SyncScope::System;
346 report_fatal_error("bad SynchronizationScope.");
350 extern "C" LLVMValueRef
351 LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
352 LLVMRustSynchronizationScope Scope) {
353 return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
356 enum class LLVMRustAsmDialect {
362 static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
364 case LLVMRustAsmDialect::Att:
365 return InlineAsm::AD_ATT;
366 case LLVMRustAsmDialect::Intel:
367 return InlineAsm::AD_Intel;
369 report_fatal_error("bad AsmDialect.");
373 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
375 LLVMBool HasSideEffects,
376 LLVMBool IsAlignStack,
377 LLVMRustAsmDialect Dialect) {
378 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
379 HasSideEffects, IsAlignStack, fromRust(Dialect)));
382 extern "C" bool LLVMRustInlineAsmVerify(LLVMTypeRef Ty,
384 return InlineAsm::Verify(unwrap<FunctionType>(Ty), Constraints);
387 extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
388 unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
391 typedef DIBuilder *LLVMRustDIBuilderRef;
393 template <typename DIT> DIT *unwrapDIPtr(LLVMMetadataRef Ref) {
394 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
397 #define DIDescriptor DIScope
398 #define DIArray DINodeArray
399 #define unwrapDI unwrapDIPtr
401 // These values **must** match debuginfo::DIFlags! They also *happen*
402 // to match LLVM, but that isn't required as we do giant sets of
403 // matching below. The value shouldn't be directly passed to LLVM.
404 enum class LLVMRustDIFlags : uint32_t {
409 FlagFwdDecl = (1 << 2),
410 FlagAppleBlock = (1 << 3),
411 FlagBlockByrefStruct = (1 << 4),
412 FlagVirtual = (1 << 5),
413 FlagArtificial = (1 << 6),
414 FlagExplicit = (1 << 7),
415 FlagPrototyped = (1 << 8),
416 FlagObjcClassComplete = (1 << 9),
417 FlagObjectPointer = (1 << 10),
418 FlagVector = (1 << 11),
419 FlagStaticMember = (1 << 12),
420 FlagLValueReference = (1 << 13),
421 FlagRValueReference = (1 << 14),
422 FlagExternalTypeRef = (1 << 15),
423 FlagIntroducedVirtual = (1 << 18),
424 FlagBitField = (1 << 19),
425 FlagNoReturn = (1 << 20),
426 FlagMainSubprogram = (1 << 21),
427 // Do not add values that are not supported by the minimum LLVM
428 // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
431 inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
432 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
433 static_cast<uint32_t>(B));
436 inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
437 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
438 static_cast<uint32_t>(B));
441 inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
445 inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
447 inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
448 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
451 static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
452 DINode::DIFlags Result = DINode::DIFlags::FlagZero;
454 switch (visibility(Flags)) {
455 case LLVMRustDIFlags::FlagPrivate:
456 Result |= DINode::DIFlags::FlagPrivate;
458 case LLVMRustDIFlags::FlagProtected:
459 Result |= DINode::DIFlags::FlagProtected;
461 case LLVMRustDIFlags::FlagPublic:
462 Result |= DINode::DIFlags::FlagPublic;
465 // The rest are handled below
469 if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
470 Result |= DINode::DIFlags::FlagFwdDecl;
472 if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
473 Result |= DINode::DIFlags::FlagAppleBlock;
475 if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
476 Result |= DINode::DIFlags::FlagBlockByrefStruct;
478 if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
479 Result |= DINode::DIFlags::FlagVirtual;
481 if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
482 Result |= DINode::DIFlags::FlagArtificial;
484 if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
485 Result |= DINode::DIFlags::FlagExplicit;
487 if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
488 Result |= DINode::DIFlags::FlagPrototyped;
490 if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
491 Result |= DINode::DIFlags::FlagObjcClassComplete;
493 if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
494 Result |= DINode::DIFlags::FlagObjectPointer;
496 if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
497 Result |= DINode::DIFlags::FlagVector;
499 if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
500 Result |= DINode::DIFlags::FlagStaticMember;
502 if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
503 Result |= DINode::DIFlags::FlagLValueReference;
505 if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
506 Result |= DINode::DIFlags::FlagRValueReference;
508 if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) {
509 Result |= DINode::DIFlags::FlagIntroducedVirtual;
511 if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) {
512 Result |= DINode::DIFlags::FlagBitField;
514 if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) {
515 Result |= DINode::DIFlags::FlagNoReturn;
517 if (isSet(Flags & LLVMRustDIFlags::FlagMainSubprogram)) {
518 Result |= DINode::DIFlags::FlagMainSubprogram;
524 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
525 return DEBUG_METADATA_VERSION;
528 extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
530 extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
532 extern "C" bool LLVMRustIsRustLLVM() {
540 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
542 unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
545 extern "C" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
546 return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
549 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
550 return new DIBuilder(*unwrap(M));
553 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
557 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
561 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
562 LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
563 const char *Producer, bool isOptimized, const char *Flags,
564 unsigned RuntimeVer, const char *SplitName) {
565 auto *File = unwrapDI<DIFile>(FileRef);
567 return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
568 Flags, RuntimeVer, SplitName));
571 extern "C" LLVMMetadataRef
572 LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
573 const char *Directory) {
574 return wrap(Builder->createFile(Filename, Directory));
577 extern "C" LLVMMetadataRef
578 LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
579 LLVMMetadataRef File,
580 LLVMMetadataRef ParameterTypes) {
581 return wrap(Builder->createSubroutineType(
582 DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
585 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
586 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
587 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
588 LLVMMetadataRef Ty, bool IsLocalToUnit, bool IsDefinition,
589 unsigned ScopeLine, LLVMRustDIFlags Flags, bool IsOptimized,
590 LLVMValueRef Fn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) {
591 DITemplateParameterArray TParams =
592 DITemplateParameterArray(unwrap<MDTuple>(TParam));
593 DISubprogram *Sub = Builder->createFunction(
594 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
595 LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
596 ScopeLine, fromRust(Flags), IsOptimized, TParams,
597 unwrapDIPtr<DISubprogram>(Decl));
598 unwrap<Function>(Fn)->setSubprogram(Sub);
602 extern "C" LLVMMetadataRef
603 LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
604 uint64_t SizeInBits, uint32_t AlignInBits,
606 return wrap(Builder->createBasicType(Name, SizeInBits, Encoding));
609 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
610 LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
611 uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
612 return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
613 SizeInBits, AlignInBits,
614 /* DWARFAddressSpace */ None,
618 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
619 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
620 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
621 uint32_t AlignInBits, LLVMRustDIFlags Flags,
622 LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
623 unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
624 const char *UniqueId) {
625 return wrap(Builder->createStructType(
626 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
627 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
628 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
629 unwrapDI<DIType>(VTableHolder), UniqueId));
632 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart(
633 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
634 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
635 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator,
636 LLVMMetadataRef Elements, const char *UniqueId) {
637 #if LLVM_VERSION_GE(7, 0)
638 return wrap(Builder->createVariantPart(
639 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
640 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIDerivedType>(Discriminator),
641 DINodeArray(unwrapDI<MDTuple>(Elements)), UniqueId));
647 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
648 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
649 LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
650 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
651 LLVMMetadataRef Ty) {
652 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
653 unwrapDI<DIFile>(File), LineNo,
654 SizeInBits, AlignInBits, OffsetInBits,
655 fromRust(Flags), unwrapDI<DIType>(Ty)));
658 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType(
659 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
660 const char *Name, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
661 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant,
662 LLVMRustDIFlags Flags, LLVMMetadataRef Ty) {
663 #if LLVM_VERSION_GE(7, 0)
664 llvm::ConstantInt* D = nullptr;
666 D = unwrap<llvm::ConstantInt>(Discriminant);
668 return wrap(Builder->createVariantMemberType(unwrapDI<DIDescriptor>(Scope), Name,
669 unwrapDI<DIFile>(File), LineNo,
670 SizeInBits, AlignInBits, OffsetInBits, D,
671 fromRust(Flags), unwrapDI<DIType>(Ty)));
673 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
674 unwrapDI<DIFile>(File), LineNo,
675 SizeInBits, AlignInBits, OffsetInBits,
676 fromRust(Flags), unwrapDI<DIType>(Ty)));
680 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
681 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
682 LLVMMetadataRef File, unsigned Line, unsigned Col) {
683 return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
684 unwrapDI<DIFile>(File), Line, Col));
687 extern "C" LLVMMetadataRef
688 LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
689 LLVMMetadataRef Scope,
690 LLVMMetadataRef File) {
691 return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
692 unwrapDI<DIFile>(File)));
695 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
696 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
697 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
698 LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
699 LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
700 llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
702 llvm::DIExpression *InitExpr = nullptr;
703 if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
704 InitExpr = Builder->createConstantValueExpression(
705 IntVal->getValue().getSExtValue());
706 } else if (llvm::ConstantFP *FPVal =
707 llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
708 InitExpr = Builder->createConstantValueExpression(
709 FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
712 llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
713 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
714 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
715 InitExpr, unwrapDIPtr<MDNode>(Decl),
716 #if LLVM_VERSION_GE(8, 0)
717 /* templateParams */ nullptr,
721 InitVal->setMetadata("dbg", VarExpr);
723 return wrap(VarExpr);
726 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
727 LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
728 const char *Name, LLVMMetadataRef File, unsigned LineNo,
729 LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
730 unsigned ArgNo, uint32_t AlignInBits) {
731 if (Tag == 0x100) { // DW_TAG_auto_variable
732 return wrap(Builder->createAutoVariable(
733 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
734 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits));
736 return wrap(Builder->createParameterVariable(
737 unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
738 LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
742 extern "C" LLVMMetadataRef
743 LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
744 uint32_t AlignInBits, LLVMMetadataRef Ty,
745 LLVMMetadataRef Subscripts) {
747 Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
748 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
751 extern "C" LLVMMetadataRef
752 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
754 return wrap(Builder->getOrCreateSubrange(Lo, Count));
757 extern "C" LLVMMetadataRef
758 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
759 LLVMMetadataRef *Ptr, unsigned Count) {
760 Metadata **DataValue = unwrap(Ptr);
762 Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
765 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
766 LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
767 int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
768 LLVMBasicBlockRef InsertAtEnd) {
769 return wrap(Builder->insertDeclare(
770 unwrap(V), unwrap<DILocalVariable>(VarInfo),
771 Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
772 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
773 unwrap(InsertAtEnd)));
776 extern "C" LLVMMetadataRef
777 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
778 const char *Name, uint64_t Val) {
779 return wrap(Builder->createEnumerator(Name, Val));
782 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
783 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
784 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
785 uint32_t AlignInBits, LLVMMetadataRef Elements,
786 LLVMMetadataRef ClassTy, bool IsFixed) {
787 #if LLVM_VERSION_GE(7, 0)
788 return wrap(Builder->createEnumerationType(
789 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
790 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
791 unwrapDI<DIType>(ClassTy), "", IsFixed));
793 // Ignore IsFixed on older LLVM.
794 return wrap(Builder->createEnumerationType(
795 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
796 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
797 unwrapDI<DIType>(ClassTy), ""));
801 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
802 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
803 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
804 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
805 unsigned RunTimeLang, const char *UniqueId) {
806 return wrap(Builder->createUnionType(
807 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
808 SizeInBits, AlignInBits, fromRust(Flags),
809 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
812 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
813 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
814 LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
816 return wrap(Builder->createTemplateTypeParameter(
817 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
820 extern "C" LLVMMetadataRef
821 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
822 LLVMMetadataRef Scope, const char *Name,
823 LLVMMetadataRef File, unsigned LineNo) {
824 return wrap(Builder->createNameSpace(
825 unwrapDI<DIDescriptor>(Scope), Name,
826 false // ExportSymbols (only relevant for C++ anonymous namespaces)
831 LLVMRustDICompositeTypeReplaceArrays(LLVMRustDIBuilderRef Builder,
832 LLVMMetadataRef CompositeTy,
833 LLVMMetadataRef Elements,
834 LLVMMetadataRef Params) {
835 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
836 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(Elements)),
837 DINodeArray(unwrap<MDTuple>(Params)));
840 extern "C" LLVMValueRef
841 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
842 unsigned Column, LLVMMetadataRef Scope,
843 LLVMMetadataRef InlinedAt) {
844 LLVMContext &Context = *unwrap(ContextRef);
846 DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
847 unwrapDIPtr<MDNode>(InlinedAt));
849 return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
852 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
853 return dwarf::DW_OP_deref;
856 extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
857 return dwarf::DW_OP_plus_uconst;
860 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
861 RawRustStringOstream OS(Str);
862 unwrap<llvm::Type>(Ty)->print(OS);
865 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
867 RawRustStringOstream OS(Str);
872 unwrap<llvm::Value>(V)->getType()->print(OS);
874 unwrap<llvm::Value>(V)->print(OS);
879 // Note that the two following functions look quite similar to the
880 // LLVMGetSectionName function. Sadly, it appears that this function only
881 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
882 // function provided by LLVM doesn't return the length, so we've created our own
883 // function which returns the length as well as the data pointer.
885 // For an example of this not returning a null terminated string, see
886 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
887 // branches explicitly creates a StringRef without a null terminator, and then
890 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
891 return reinterpret_cast<section_iterator *>(SI);
894 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
897 if (std::error_code EC = (*unwrap(SI))->getName(Ret))
898 report_fatal_error(EC.message());
903 // LLVMArrayType function does not support 64-bit ElementCount
904 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
905 uint64_t ElementCount) {
906 return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
909 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
911 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
912 RawRustStringOstream OS(Str);
913 unwrap(T)->print(OS);
916 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
917 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
918 LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
919 RustStringRef FilenameOut, RustStringRef MessageOut) {
920 // Undefined to call this not on an optimization diagnostic!
921 llvm::DiagnosticInfoOptimizationBase *Opt =
922 static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
924 RawRustStringOstream PassNameOS(PassNameOut);
925 PassNameOS << Opt->getPassName();
926 *FunctionOut = wrap(&Opt->getFunction());
928 RawRustStringOstream FilenameOS(FilenameOut);
929 DiagnosticLocation loc = Opt->getLocation();
931 *Line = loc.getLine();
932 *Column = loc.getColumn();
933 FilenameOS << loc.getFilename();
936 RawRustStringOstream MessageOS(MessageOut);
937 MessageOS << Opt->getMsg();
941 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
942 LLVMTwineRef *MessageOut,
943 LLVMValueRef *InstructionOut) {
944 // Undefined to call this not on an inline assembly diagnostic!
945 llvm::DiagnosticInfoInlineAsm *IA =
946 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
948 *CookieOut = IA->getLocCookie();
949 *MessageOut = wrap(&IA->getMsgStr());
950 *InstructionOut = wrap(IA->getInstruction());
953 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
955 RawRustStringOstream OS(Str);
956 DiagnosticPrinterRawOStream DP(OS);
957 unwrap(DI)->print(DP);
960 enum class LLVMRustDiagnosticKind {
964 DebugMetadataVersion,
967 OptimizationRemarkMissed,
968 OptimizationRemarkAnalysis,
969 OptimizationRemarkAnalysisFPCommute,
970 OptimizationRemarkAnalysisAliasing,
971 OptimizationRemarkOther,
977 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
980 return LLVMRustDiagnosticKind::InlineAsm;
982 return LLVMRustDiagnosticKind::StackSize;
983 case DK_DebugMetadataVersion:
984 return LLVMRustDiagnosticKind::DebugMetadataVersion;
985 case DK_SampleProfile:
986 return LLVMRustDiagnosticKind::SampleProfile;
987 case DK_OptimizationRemark:
988 return LLVMRustDiagnosticKind::OptimizationRemark;
989 case DK_OptimizationRemarkMissed:
990 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
991 case DK_OptimizationRemarkAnalysis:
992 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
993 case DK_OptimizationRemarkAnalysisFPCommute:
994 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
995 case DK_OptimizationRemarkAnalysisAliasing:
996 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
998 return LLVMRustDiagnosticKind::PGOProfile;
1000 return LLVMRustDiagnosticKind::Linker;
1002 return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
1003 ? LLVMRustDiagnosticKind::OptimizationRemarkOther
1004 : LLVMRustDiagnosticKind::Other;
1008 extern "C" LLVMRustDiagnosticKind
1009 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
1010 return toRust((DiagnosticKind)unwrap(DI)->getKind());
1012 // This is kept distinct from LLVMGetTypeKind, because when
1013 // a new type kind is added, the Rust-side enum must be
1014 // updated or UB will result.
1015 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
1016 switch (unwrap(Ty)->getTypeID()) {
1017 case Type::VoidTyID:
1018 return LLVMVoidTypeKind;
1019 case Type::HalfTyID:
1020 return LLVMHalfTypeKind;
1021 case Type::FloatTyID:
1022 return LLVMFloatTypeKind;
1023 case Type::DoubleTyID:
1024 return LLVMDoubleTypeKind;
1025 case Type::X86_FP80TyID:
1026 return LLVMX86_FP80TypeKind;
1027 case Type::FP128TyID:
1028 return LLVMFP128TypeKind;
1029 case Type::PPC_FP128TyID:
1030 return LLVMPPC_FP128TypeKind;
1031 case Type::LabelTyID:
1032 return LLVMLabelTypeKind;
1033 case Type::MetadataTyID:
1034 return LLVMMetadataTypeKind;
1035 case Type::IntegerTyID:
1036 return LLVMIntegerTypeKind;
1037 case Type::FunctionTyID:
1038 return LLVMFunctionTypeKind;
1039 case Type::StructTyID:
1040 return LLVMStructTypeKind;
1041 case Type::ArrayTyID:
1042 return LLVMArrayTypeKind;
1043 case Type::PointerTyID:
1044 return LLVMPointerTypeKind;
1045 case Type::VectorTyID:
1046 return LLVMVectorTypeKind;
1047 case Type::X86_MMXTyID:
1048 return LLVMX86_MMXTypeKind;
1049 case Type::TokenTyID:
1050 return LLVMTokenTypeKind;
1052 report_fatal_error("Unhandled TypeID.");
1055 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
1057 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
1058 LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
1059 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
1062 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
1063 RustStringRef Str) {
1064 RawRustStringOstream OS(Str);
1065 unwrap(D)->print("", OS);
1068 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
1069 LLVMValueRef ParentPad,
1071 LLVMValueRef *LLArgs,
1073 Value **Args = unwrap(LLArgs);
1074 if (ParentPad == nullptr) {
1075 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1076 ParentPad = wrap(Constant::getNullValue(Ty));
1078 return wrap(unwrap(B)->CreateCleanupPad(
1079 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1082 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
1083 LLVMValueRef CleanupPad,
1084 LLVMBasicBlockRef UnwindBB) {
1085 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
1086 return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
1089 extern "C" LLVMValueRef
1090 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1091 unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1092 Value **Args = unwrap(LLArgs);
1093 return wrap(unwrap(B)->CreateCatchPad(
1094 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1097 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1099 LLVMBasicBlockRef BB) {
1100 return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1104 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1105 LLVMValueRef ParentPad,
1106 LLVMBasicBlockRef BB,
1107 unsigned NumHandlers,
1109 if (ParentPad == nullptr) {
1110 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1111 ParentPad = wrap(Constant::getNullValue(Ty));
1113 return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1114 NumHandlers, Name));
1117 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1118 LLVMBasicBlockRef Handler) {
1119 Value *CatchSwitch = unwrap(CatchSwitchRef);
1120 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1123 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1124 LLVMValueRef *Inputs,
1125 unsigned NumInputs) {
1126 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1129 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1133 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1134 LLVMValueRef *Args, unsigned NumArgs,
1135 OperandBundleDef *Bundle,
1137 unsigned Len = Bundle ? 1 : 0;
1138 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1139 return wrap(unwrap(B)->CreateCall(
1140 unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1143 extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B,
1144 LLVMValueRef Dst, unsigned DstAlign,
1145 LLVMValueRef Src, unsigned SrcAlign,
1146 LLVMValueRef Size, bool IsVolatile) {
1147 #if LLVM_VERSION_GE(7, 0)
1148 return wrap(unwrap(B)->CreateMemCpy(
1149 unwrap(Dst), DstAlign,
1150 unwrap(Src), SrcAlign,
1151 unwrap(Size), IsVolatile));
1153 unsigned Align = std::min(DstAlign, SrcAlign);
1154 return wrap(unwrap(B)->CreateMemCpy(
1155 unwrap(Dst), unwrap(Src),
1156 unwrap(Size), Align, IsVolatile));
1160 extern "C" LLVMValueRef LLVMRustBuildMemMove(LLVMBuilderRef B,
1161 LLVMValueRef Dst, unsigned DstAlign,
1162 LLVMValueRef Src, unsigned SrcAlign,
1163 LLVMValueRef Size, bool IsVolatile) {
1164 #if LLVM_VERSION_GE(7, 0)
1165 return wrap(unwrap(B)->CreateMemMove(
1166 unwrap(Dst), DstAlign,
1167 unwrap(Src), SrcAlign,
1168 unwrap(Size), IsVolatile));
1170 unsigned Align = std::min(DstAlign, SrcAlign);
1171 return wrap(unwrap(B)->CreateMemMove(
1172 unwrap(Dst), unwrap(Src),
1173 unwrap(Size), Align, IsVolatile));
1177 extern "C" LLVMValueRef
1178 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1179 unsigned NumArgs, LLVMBasicBlockRef Then,
1180 LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1182 unsigned Len = Bundle ? 1 : 0;
1183 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1184 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1185 makeArrayRef(unwrap(Args), NumArgs),
1189 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1190 LLVMBasicBlockRef BB) {
1191 auto Point = unwrap(BB)->getFirstInsertionPt();
1192 unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1195 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1197 Triple TargetTriple(unwrap(M)->getTargetTriple());
1198 GlobalObject *GV = unwrap<GlobalObject>(V);
1199 if (!TargetTriple.isOSBinFormatMachO()) {
1200 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1204 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1205 GlobalObject *GV = unwrap<GlobalObject>(V);
1206 GV->setComdat(nullptr);
1209 enum class LLVMRustLinkage {
1210 ExternalLinkage = 0,
1211 AvailableExternallyLinkage = 1,
1212 LinkOnceAnyLinkage = 2,
1213 LinkOnceODRLinkage = 3,
1216 AppendingLinkage = 6,
1217 InternalLinkage = 7,
1219 ExternalWeakLinkage = 9,
1223 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1225 case LLVMExternalLinkage:
1226 return LLVMRustLinkage::ExternalLinkage;
1227 case LLVMAvailableExternallyLinkage:
1228 return LLVMRustLinkage::AvailableExternallyLinkage;
1229 case LLVMLinkOnceAnyLinkage:
1230 return LLVMRustLinkage::LinkOnceAnyLinkage;
1231 case LLVMLinkOnceODRLinkage:
1232 return LLVMRustLinkage::LinkOnceODRLinkage;
1233 case LLVMWeakAnyLinkage:
1234 return LLVMRustLinkage::WeakAnyLinkage;
1235 case LLVMWeakODRLinkage:
1236 return LLVMRustLinkage::WeakODRLinkage;
1237 case LLVMAppendingLinkage:
1238 return LLVMRustLinkage::AppendingLinkage;
1239 case LLVMInternalLinkage:
1240 return LLVMRustLinkage::InternalLinkage;
1241 case LLVMPrivateLinkage:
1242 return LLVMRustLinkage::PrivateLinkage;
1243 case LLVMExternalWeakLinkage:
1244 return LLVMRustLinkage::ExternalWeakLinkage;
1245 case LLVMCommonLinkage:
1246 return LLVMRustLinkage::CommonLinkage;
1248 report_fatal_error("Invalid LLVMRustLinkage value!");
1252 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1254 case LLVMRustLinkage::ExternalLinkage:
1255 return LLVMExternalLinkage;
1256 case LLVMRustLinkage::AvailableExternallyLinkage:
1257 return LLVMAvailableExternallyLinkage;
1258 case LLVMRustLinkage::LinkOnceAnyLinkage:
1259 return LLVMLinkOnceAnyLinkage;
1260 case LLVMRustLinkage::LinkOnceODRLinkage:
1261 return LLVMLinkOnceODRLinkage;
1262 case LLVMRustLinkage::WeakAnyLinkage:
1263 return LLVMWeakAnyLinkage;
1264 case LLVMRustLinkage::WeakODRLinkage:
1265 return LLVMWeakODRLinkage;
1266 case LLVMRustLinkage::AppendingLinkage:
1267 return LLVMAppendingLinkage;
1268 case LLVMRustLinkage::InternalLinkage:
1269 return LLVMInternalLinkage;
1270 case LLVMRustLinkage::PrivateLinkage:
1271 return LLVMPrivateLinkage;
1272 case LLVMRustLinkage::ExternalWeakLinkage:
1273 return LLVMExternalWeakLinkage;
1274 case LLVMRustLinkage::CommonLinkage:
1275 return LLVMCommonLinkage;
1277 report_fatal_error("Invalid LLVMRustLinkage value!");
1280 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1281 return toRust(LLVMGetLinkage(V));
1284 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1285 LLVMRustLinkage RustLinkage) {
1286 LLVMSetLinkage(V, fromRust(RustLinkage));
1289 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1290 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1291 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1293 auto C = unwrap<llvm::ConstantInt>(CV);
1294 if (C->getBitWidth() > 128) { return false; }
1297 AP = C->getValue().sextOrSelf(128);
1299 AP = C->getValue().zextOrSelf(128);
1301 *low = AP.getLoBits(64).getZExtValue();
1302 *high = AP.getHiBits(64).getZExtValue();
1306 enum class LLVMRustVisibility {
1312 static LLVMRustVisibility toRust(LLVMVisibility Vis) {
1314 case LLVMDefaultVisibility:
1315 return LLVMRustVisibility::Default;
1316 case LLVMHiddenVisibility:
1317 return LLVMRustVisibility::Hidden;
1318 case LLVMProtectedVisibility:
1319 return LLVMRustVisibility::Protected;
1321 report_fatal_error("Invalid LLVMRustVisibility value!");
1324 static LLVMVisibility fromRust(LLVMRustVisibility Vis) {
1326 case LLVMRustVisibility::Default:
1327 return LLVMDefaultVisibility;
1328 case LLVMRustVisibility::Hidden:
1329 return LLVMHiddenVisibility;
1330 case LLVMRustVisibility::Protected:
1331 return LLVMProtectedVisibility;
1333 report_fatal_error("Invalid LLVMRustVisibility value!");
1336 extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) {
1337 return toRust(LLVMGetVisibility(V));
1340 // Oh hey, a binding that makes sense for once? (because LLVM’s own do not)
1341 extern "C" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
1342 LLVMTypeRef DestTy, bool isSigned) {
1343 return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, ""));
1346 extern "C" void LLVMRustSetVisibility(LLVMValueRef V,
1347 LLVMRustVisibility RustVisibility) {
1348 LLVMSetVisibility(V, fromRust(RustVisibility));
1351 struct LLVMRustModuleBuffer {
1355 extern "C" LLVMRustModuleBuffer*
1356 LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1357 auto Ret = llvm::make_unique<LLVMRustModuleBuffer>();
1359 raw_string_ostream OS(Ret->data);
1361 legacy::PassManager PM;
1362 PM.add(createBitcodeWriterPass(OS));
1366 return Ret.release();
1370 LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1374 extern "C" const void*
1375 LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
1376 return Buffer->data.data();
1380 LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1381 return Buffer->data.length();
1385 LLVMRustModuleCost(LLVMModuleRef M) {
1386 auto f = unwrap(M)->functions();
1387 return std::distance(std::begin(f), std::end(f));
1390 // Vector reductions:
1391 extern "C" LLVMValueRef
1392 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1393 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1395 extern "C" LLVMValueRef
1396 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1397 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1399 extern "C" LLVMValueRef
1400 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1401 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1403 extern "C" LLVMValueRef
1404 LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1405 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1407 extern "C" LLVMValueRef
1408 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1409 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1411 extern "C" LLVMValueRef
1412 LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1413 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1415 extern "C" LLVMValueRef
1416 LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1417 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1419 extern "C" LLVMValueRef
1420 LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1421 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1423 extern "C" LLVMValueRef
1424 LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1425 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1427 extern "C" LLVMValueRef
1428 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1429 return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN));
1431 extern "C" LLVMValueRef
1432 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1433 return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN));
1436 extern "C" LLVMValueRef
1437 LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1438 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1440 extern "C" LLVMValueRef
1441 LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1442 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));