2 #include "llvm/IR/CallSite.h"
3 #include "llvm/IR/DebugInfoMetadata.h"
4 #include "llvm/IR/DiagnosticInfo.h"
5 #include "llvm/IR/DiagnosticPrinter.h"
6 #include "llvm/IR/GlobalVariable.h"
7 #include "llvm/IR/Instructions.h"
8 #include "llvm/Object/Archive.h"
9 #include "llvm/Object/ObjectFile.h"
10 #include "llvm/Bitcode/BitcodeWriterPass.h"
11 #include "llvm/Support/Signals.h"
12 #include "llvm/ADT/Optional.h"
16 //===----------------------------------------------------------------------===
18 // This file defines alternate interfaces to core functions that are more
19 // readily callable by Rust's FFI.
21 //===----------------------------------------------------------------------===
24 using namespace llvm::sys;
25 using namespace llvm::object;
27 // LLVMAtomicOrdering is already an enum - don't create another
29 static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
31 case LLVMAtomicOrderingNotAtomic:
32 return AtomicOrdering::NotAtomic;
33 case LLVMAtomicOrderingUnordered:
34 return AtomicOrdering::Unordered;
35 case LLVMAtomicOrderingMonotonic:
36 return AtomicOrdering::Monotonic;
37 case LLVMAtomicOrderingAcquire:
38 return AtomicOrdering::Acquire;
39 case LLVMAtomicOrderingRelease:
40 return AtomicOrdering::Release;
41 case LLVMAtomicOrderingAcquireRelease:
42 return AtomicOrdering::AcquireRelease;
43 case LLVMAtomicOrderingSequentiallyConsistent:
44 return AtomicOrdering::SequentiallyConsistent;
47 report_fatal_error("Invalid LLVMAtomicOrdering value!");
50 static LLVM_THREAD_LOCAL char *LastError;
52 // Custom error handler for fatal LLVM errors.
54 // Notably it exits the process with code 101, unlike LLVM's default of 1.
55 static void FatalErrorHandler(void *UserData,
56 const std::string& Reason,
58 // Do the same thing that the default error handler does.
59 std::cerr << "LLVM ERROR: " << Reason << std::endl;
61 // Since this error handler exits the process, we have to run any cleanup that
62 // LLVM would run after handling the error. This might change with an LLVM
64 sys::RunInterruptHandlers();
69 extern "C" void LLVMRustInstallFatalErrorHandler() {
70 install_fatal_error_handler(FatalErrorHandler);
73 extern "C" LLVMMemoryBufferRef
74 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
75 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
76 MemoryBuffer::getFile(Path, -1, false);
78 LLVMRustSetLastError(BufOr.getError().message().c_str());
81 return wrap(BufOr.get().release());
84 extern "C" char *LLVMRustGetLastError(void) {
85 char *Ret = LastError;
90 extern "C" void LLVMRustSetLastError(const char *Err) {
91 free((void *)LastError);
92 LastError = strdup(Err);
95 extern "C" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) {
96 auto ctx = new LLVMContext();
97 ctx->setDiscardValueNames(shouldDiscardNames);
101 extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
102 const char *Triple) {
103 unwrap(M)->setTargetTriple(Triple::normalize(Triple));
106 extern "C" void LLVMRustPrintPassTimings() {
107 raw_fd_ostream OS(2, false); // stderr.
108 TimerGroup::printAll(OS);
111 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
113 return wrap(unwrap(M)->getNamedValue(Name));
116 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
118 LLVMTypeRef FunctionTy) {
120 unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy)));
123 extern "C" LLVMValueRef
124 LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
125 return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
128 extern "C" LLVMValueRef
129 LLVMRustInsertPrivateGlobal(LLVMModuleRef M, LLVMTypeRef Ty) {
130 return wrap(new GlobalVariable(*unwrap(M),
133 GlobalValue::PrivateLinkage,
137 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
138 return wrap(Type::getMetadataTy(*unwrap(C)));
141 static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
144 return Attribute::AlwaysInline;
146 return Attribute::ByVal;
148 return Attribute::Cold;
150 return Attribute::InlineHint;
152 return Attribute::MinSize;
154 return Attribute::Naked;
156 return Attribute::NoAlias;
158 return Attribute::NoCapture;
160 return Attribute::NoInline;
162 return Attribute::NonNull;
164 return Attribute::NoRedZone;
166 return Attribute::NoReturn;
168 return Attribute::NoUnwind;
169 case OptimizeForSize:
170 return Attribute::OptimizeForSize;
172 return Attribute::ReadOnly;
174 return Attribute::SExt;
176 return Attribute::StructRet;
178 return Attribute::UWTable;
180 return Attribute::ZExt;
182 return Attribute::InReg;
184 return Attribute::SanitizeThread;
185 case SanitizeAddress:
186 return Attribute::SanitizeAddress;
188 return Attribute::SanitizeMemory;
190 return Attribute::NonLazyBind;
192 return Attribute::OptimizeNone;
194 report_fatal_error("bad AttributeKind");
197 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
198 LLVMRustAttribute RustAttr) {
199 CallSite Call = CallSite(unwrap<Instruction>(Instr));
200 Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
201 Call.addAttribute(Index, Attr);
204 extern "C" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr,
207 CallSite Call = CallSite(unwrap<Instruction>(Instr));
209 B.addAlignmentAttr(Bytes);
210 Call.setAttributes(Call.getAttributes().addAttributes(
211 Call->getContext(), Index, B));
214 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
217 CallSite Call = CallSite(unwrap<Instruction>(Instr));
219 B.addDereferenceableAttr(Bytes);
220 Call.setAttributes(Call.getAttributes().addAttributes(
221 Call->getContext(), Index, B));
224 extern "C" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr,
227 CallSite Call = CallSite(unwrap<Instruction>(Instr));
229 B.addDereferenceableOrNullAttr(Bytes);
230 Call.setAttributes(Call.getAttributes().addAttributes(
231 Call->getContext(), Index, B));
234 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
235 LLVMRustAttribute RustAttr) {
236 Function *A = unwrap<Function>(Fn);
237 Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
239 A->addAttributes(Index, B);
242 extern "C" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn,
245 Function *A = unwrap<Function>(Fn);
247 B.addAlignmentAttr(Bytes);
248 A->addAttributes(Index, B);
251 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
253 Function *A = unwrap<Function>(Fn);
255 B.addDereferenceableAttr(Bytes);
256 A->addAttributes(Index, B);
259 extern "C" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn,
262 Function *A = unwrap<Function>(Fn);
264 B.addDereferenceableOrNullAttr(Bytes);
265 A->addAttributes(Index, B);
268 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
272 Function *F = unwrap<Function>(Fn);
274 B.addAttribute(Name, Value);
275 F->addAttributes(Index, B);
278 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
280 LLVMRustAttribute RustAttr) {
281 Function *F = unwrap<Function>(Fn);
282 Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
284 auto PAL = F->getAttributes();
285 auto PALNew = PAL.removeAttributes(F->getContext(), Index, B);
286 F->setAttributes(PALNew);
289 // enable fpmath flag UnsafeAlgebra
290 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
291 if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
296 extern "C" LLVMValueRef
297 LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
298 LLVMAtomicOrdering Order) {
299 LoadInst *LI = new LoadInst(unwrap(Source));
300 LI->setAtomic(fromRust(Order));
301 return wrap(unwrap(B)->Insert(LI, Name));
304 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
307 LLVMAtomicOrdering Order) {
308 StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
309 SI->setAtomic(fromRust(Order));
310 return wrap(unwrap(B)->Insert(SI));
313 extern "C" LLVMValueRef
314 LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
315 LLVMValueRef Old, LLVMValueRef Source,
316 LLVMAtomicOrdering Order,
317 LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
318 AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
319 unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
320 fromRust(FailureOrder));
325 enum class LLVMRustSynchronizationScope {
331 static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) {
333 case LLVMRustSynchronizationScope::SingleThread:
334 return SyncScope::SingleThread;
335 case LLVMRustSynchronizationScope::CrossThread:
336 return SyncScope::System;
338 report_fatal_error("bad SynchronizationScope.");
342 extern "C" LLVMValueRef
343 LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
344 LLVMRustSynchronizationScope Scope) {
345 return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
348 enum class LLVMRustAsmDialect {
354 static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
356 case LLVMRustAsmDialect::Att:
357 return InlineAsm::AD_ATT;
358 case LLVMRustAsmDialect::Intel:
359 return InlineAsm::AD_Intel;
361 report_fatal_error("bad AsmDialect.");
365 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
367 LLVMBool HasSideEffects,
368 LLVMBool IsAlignStack,
369 LLVMRustAsmDialect Dialect) {
370 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
371 HasSideEffects, IsAlignStack, fromRust(Dialect)));
374 extern "C" bool LLVMRustInlineAsmVerify(LLVMTypeRef Ty,
376 return InlineAsm::Verify(unwrap<FunctionType>(Ty), Constraints);
379 extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
380 unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
383 typedef DIBuilder *LLVMRustDIBuilderRef;
385 template <typename DIT> DIT *unwrapDIPtr(LLVMMetadataRef Ref) {
386 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
389 #define DIDescriptor DIScope
390 #define DIArray DINodeArray
391 #define unwrapDI unwrapDIPtr
393 // These values **must** match debuginfo::DIFlags! They also *happen*
394 // to match LLVM, but that isn't required as we do giant sets of
395 // matching below. The value shouldn't be directly passed to LLVM.
396 enum class LLVMRustDIFlags : uint32_t {
401 FlagFwdDecl = (1 << 2),
402 FlagAppleBlock = (1 << 3),
403 FlagBlockByrefStruct = (1 << 4),
404 FlagVirtual = (1 << 5),
405 FlagArtificial = (1 << 6),
406 FlagExplicit = (1 << 7),
407 FlagPrototyped = (1 << 8),
408 FlagObjcClassComplete = (1 << 9),
409 FlagObjectPointer = (1 << 10),
410 FlagVector = (1 << 11),
411 FlagStaticMember = (1 << 12),
412 FlagLValueReference = (1 << 13),
413 FlagRValueReference = (1 << 14),
414 FlagExternalTypeRef = (1 << 15),
415 FlagIntroducedVirtual = (1 << 18),
416 FlagBitField = (1 << 19),
417 FlagNoReturn = (1 << 20),
418 FlagMainSubprogram = (1 << 21),
419 // Do not add values that are not supported by the minimum LLVM
420 // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
423 inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
424 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
425 static_cast<uint32_t>(B));
428 inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
429 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
430 static_cast<uint32_t>(B));
433 inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
437 inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
439 inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
440 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
443 static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
444 DINode::DIFlags Result = DINode::DIFlags::FlagZero;
446 switch (visibility(Flags)) {
447 case LLVMRustDIFlags::FlagPrivate:
448 Result |= DINode::DIFlags::FlagPrivate;
450 case LLVMRustDIFlags::FlagProtected:
451 Result |= DINode::DIFlags::FlagProtected;
453 case LLVMRustDIFlags::FlagPublic:
454 Result |= DINode::DIFlags::FlagPublic;
457 // The rest are handled below
461 if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
462 Result |= DINode::DIFlags::FlagFwdDecl;
464 if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
465 Result |= DINode::DIFlags::FlagAppleBlock;
467 if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
468 Result |= DINode::DIFlags::FlagBlockByrefStruct;
470 if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
471 Result |= DINode::DIFlags::FlagVirtual;
473 if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
474 Result |= DINode::DIFlags::FlagArtificial;
476 if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
477 Result |= DINode::DIFlags::FlagExplicit;
479 if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
480 Result |= DINode::DIFlags::FlagPrototyped;
482 if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
483 Result |= DINode::DIFlags::FlagObjcClassComplete;
485 if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
486 Result |= DINode::DIFlags::FlagObjectPointer;
488 if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
489 Result |= DINode::DIFlags::FlagVector;
491 if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
492 Result |= DINode::DIFlags::FlagStaticMember;
494 if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
495 Result |= DINode::DIFlags::FlagLValueReference;
497 if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
498 Result |= DINode::DIFlags::FlagRValueReference;
500 if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) {
501 Result |= DINode::DIFlags::FlagIntroducedVirtual;
503 if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) {
504 Result |= DINode::DIFlags::FlagBitField;
506 if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) {
507 Result |= DINode::DIFlags::FlagNoReturn;
509 if (isSet(Flags & LLVMRustDIFlags::FlagMainSubprogram)) {
510 Result |= DINode::DIFlags::FlagMainSubprogram;
516 // These values **must** match debuginfo::DISPFlags! They also *happen*
517 // to match LLVM, but that isn't required as we do giant sets of
518 // matching below. The value shouldn't be directly passed to LLVM.
519 enum class LLVMRustDISPFlags : uint32_t {
522 SPFlagPureVirtual = 2,
523 SPFlagLocalToUnit = (1 << 2),
524 SPFlagDefinition = (1 << 3),
525 SPFlagOptimized = (1 << 4),
526 // Do not add values that are not supported by the minimum LLVM
527 // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
528 // (In LLVM < 8, createFunction supported these as separate bool arguments.)
531 inline LLVMRustDISPFlags operator&(LLVMRustDISPFlags A, LLVMRustDISPFlags B) {
532 return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(A) &
533 static_cast<uint32_t>(B));
536 inline LLVMRustDISPFlags operator|(LLVMRustDISPFlags A, LLVMRustDISPFlags B) {
537 return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(A) |
538 static_cast<uint32_t>(B));
541 inline LLVMRustDISPFlags &operator|=(LLVMRustDISPFlags &A, LLVMRustDISPFlags B) {
545 inline bool isSet(LLVMRustDISPFlags F) { return F != LLVMRustDISPFlags::SPFlagZero; }
547 inline LLVMRustDISPFlags virtuality(LLVMRustDISPFlags F) {
548 return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(F) & 0x3);
551 #if LLVM_VERSION_GE(8, 0)
552 static DISubprogram::DISPFlags fromRust(LLVMRustDISPFlags SPFlags) {
553 DISubprogram::DISPFlags Result = DISubprogram::DISPFlags::SPFlagZero;
555 switch (virtuality(SPFlags)) {
556 case LLVMRustDISPFlags::SPFlagVirtual:
557 Result |= DISubprogram::DISPFlags::SPFlagVirtual;
559 case LLVMRustDISPFlags::SPFlagPureVirtual:
560 Result |= DISubprogram::DISPFlags::SPFlagPureVirtual;
563 // The rest are handled below
567 if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagLocalToUnit)) {
568 Result |= DISubprogram::DISPFlags::SPFlagLocalToUnit;
570 if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagDefinition)) {
571 Result |= DISubprogram::DISPFlags::SPFlagDefinition;
573 if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagOptimized)) {
574 Result |= DISubprogram::DISPFlags::SPFlagOptimized;
581 enum class LLVMRustDebugEmissionKind {
587 static DICompileUnit::DebugEmissionKind fromRust(LLVMRustDebugEmissionKind Kind) {
589 case LLVMRustDebugEmissionKind::NoDebug:
590 return DICompileUnit::DebugEmissionKind::NoDebug;
591 case LLVMRustDebugEmissionKind::FullDebug:
592 return DICompileUnit::DebugEmissionKind::FullDebug;
593 case LLVMRustDebugEmissionKind::LineTablesOnly:
594 return DICompileUnit::DebugEmissionKind::LineTablesOnly;
596 report_fatal_error("bad DebugEmissionKind.");
600 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
601 return DEBUG_METADATA_VERSION;
604 extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
606 extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
608 extern "C" bool LLVMRustIsRustLLVM() {
616 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
618 unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
621 extern "C" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
622 return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
625 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
626 return new DIBuilder(*unwrap(M));
629 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
633 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
637 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
638 LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
639 const char *Producer, bool isOptimized, const char *Flags,
640 unsigned RuntimeVer, const char *SplitName,
641 LLVMRustDebugEmissionKind Kind) {
642 auto *File = unwrapDI<DIFile>(FileRef);
644 return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
645 Flags, RuntimeVer, SplitName,
649 extern "C" LLVMMetadataRef
650 LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
651 const char *Directory) {
652 return wrap(Builder->createFile(Filename, Directory));
655 extern "C" LLVMMetadataRef
656 LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
657 LLVMMetadataRef File,
658 LLVMMetadataRef ParameterTypes) {
659 return wrap(Builder->createSubroutineType(
660 DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
663 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
664 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
665 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
666 LLVMMetadataRef Ty, unsigned ScopeLine, LLVMRustDIFlags Flags,
667 LLVMRustDISPFlags SPFlags, LLVMValueRef Fn, LLVMMetadataRef TParam,
668 LLVMMetadataRef Decl) {
669 DITemplateParameterArray TParams =
670 DITemplateParameterArray(unwrap<MDTuple>(TParam));
671 #if LLVM_VERSION_GE(8, 0)
672 DISubprogram *Sub = Builder->createFunction(
673 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
674 LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine, fromRust(Flags),
675 fromRust(SPFlags), TParams, unwrapDIPtr<DISubprogram>(Decl));
677 bool IsLocalToUnit = isSet(SPFlags & LLVMRustDISPFlags::SPFlagLocalToUnit);
678 bool IsDefinition = isSet(SPFlags & LLVMRustDISPFlags::SPFlagDefinition);
679 bool IsOptimized = isSet(SPFlags & LLVMRustDISPFlags::SPFlagOptimized);
680 DISubprogram *Sub = Builder->createFunction(
681 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
682 LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
683 ScopeLine, fromRust(Flags), IsOptimized, TParams,
684 unwrapDIPtr<DISubprogram>(Decl));
686 unwrap<Function>(Fn)->setSubprogram(Sub);
690 extern "C" LLVMMetadataRef
691 LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
692 uint64_t SizeInBits, uint32_t AlignInBits,
694 return wrap(Builder->createBasicType(Name, SizeInBits, Encoding));
697 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
698 LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
699 uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
700 return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
701 SizeInBits, AlignInBits,
702 /* DWARFAddressSpace */ None,
706 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
707 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
708 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
709 uint32_t AlignInBits, LLVMRustDIFlags Flags,
710 LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
711 unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
712 const char *UniqueId) {
713 return wrap(Builder->createStructType(
714 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
715 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
716 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
717 unwrapDI<DIType>(VTableHolder), UniqueId));
720 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart(
721 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
722 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
723 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator,
724 LLVMMetadataRef Elements, const char *UniqueId) {
725 #if LLVM_VERSION_GE(7, 0)
726 return wrap(Builder->createVariantPart(
727 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
728 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIDerivedType>(Discriminator),
729 DINodeArray(unwrapDI<MDTuple>(Elements)), UniqueId));
735 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
736 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
737 LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
738 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
739 LLVMMetadataRef Ty) {
740 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
741 unwrapDI<DIFile>(File), LineNo,
742 SizeInBits, AlignInBits, OffsetInBits,
743 fromRust(Flags), unwrapDI<DIType>(Ty)));
746 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType(
747 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
748 const char *Name, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
749 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant,
750 LLVMRustDIFlags Flags, LLVMMetadataRef Ty) {
751 #if LLVM_VERSION_GE(7, 0)
752 llvm::ConstantInt* D = nullptr;
754 D = unwrap<llvm::ConstantInt>(Discriminant);
756 return wrap(Builder->createVariantMemberType(unwrapDI<DIDescriptor>(Scope), Name,
757 unwrapDI<DIFile>(File), LineNo,
758 SizeInBits, AlignInBits, OffsetInBits, D,
759 fromRust(Flags), unwrapDI<DIType>(Ty)));
761 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
762 unwrapDI<DIFile>(File), LineNo,
763 SizeInBits, AlignInBits, OffsetInBits,
764 fromRust(Flags), unwrapDI<DIType>(Ty)));
768 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
769 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
770 LLVMMetadataRef File, unsigned Line, unsigned Col) {
771 return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
772 unwrapDI<DIFile>(File), Line, Col));
775 extern "C" LLVMMetadataRef
776 LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
777 LLVMMetadataRef Scope,
778 LLVMMetadataRef File) {
779 return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
780 unwrapDI<DIFile>(File)));
783 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
784 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
785 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
786 LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
787 LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
788 llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
790 llvm::DIExpression *InitExpr = nullptr;
791 if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
792 InitExpr = Builder->createConstantValueExpression(
793 IntVal->getValue().getSExtValue());
794 } else if (llvm::ConstantFP *FPVal =
795 llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
796 InitExpr = Builder->createConstantValueExpression(
797 FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
800 llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
801 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
802 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
803 InitExpr, unwrapDIPtr<MDNode>(Decl),
804 #if LLVM_VERSION_GE(8, 0)
805 /* templateParams */ nullptr,
809 InitVal->setMetadata("dbg", VarExpr);
811 return wrap(VarExpr);
814 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
815 LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
816 const char *Name, LLVMMetadataRef File, unsigned LineNo,
817 LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
818 unsigned ArgNo, uint32_t AlignInBits) {
819 if (Tag == 0x100) { // DW_TAG_auto_variable
820 return wrap(Builder->createAutoVariable(
821 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
822 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits));
824 return wrap(Builder->createParameterVariable(
825 unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
826 LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
830 extern "C" LLVMMetadataRef
831 LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
832 uint32_t AlignInBits, LLVMMetadataRef Ty,
833 LLVMMetadataRef Subscripts) {
835 Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
836 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
839 extern "C" LLVMMetadataRef
840 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
842 return wrap(Builder->getOrCreateSubrange(Lo, Count));
845 extern "C" LLVMMetadataRef
846 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
847 LLVMMetadataRef *Ptr, unsigned Count) {
848 Metadata **DataValue = unwrap(Ptr);
850 Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
853 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
854 LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
855 int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
856 LLVMBasicBlockRef InsertAtEnd) {
857 return wrap(Builder->insertDeclare(
858 unwrap(V), unwrap<DILocalVariable>(VarInfo),
859 Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
860 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
861 unwrap(InsertAtEnd)));
864 extern "C" LLVMMetadataRef
865 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
866 const char *Name, uint64_t Val) {
867 return wrap(Builder->createEnumerator(Name, Val));
870 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
871 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
872 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
873 uint32_t AlignInBits, LLVMMetadataRef Elements,
874 LLVMMetadataRef ClassTy, bool IsScoped) {
875 #if LLVM_VERSION_GE(7, 0)
876 return wrap(Builder->createEnumerationType(
877 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
878 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
879 unwrapDI<DIType>(ClassTy), "", IsScoped));
881 // Ignore IsScoped on older LLVM.
882 return wrap(Builder->createEnumerationType(
883 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
884 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
885 unwrapDI<DIType>(ClassTy), ""));
889 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
890 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
891 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
892 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
893 unsigned RunTimeLang, const char *UniqueId) {
894 return wrap(Builder->createUnionType(
895 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
896 SizeInBits, AlignInBits, fromRust(Flags),
897 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
900 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
901 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
902 LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
904 return wrap(Builder->createTemplateTypeParameter(
905 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
908 extern "C" LLVMMetadataRef
909 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
910 LLVMMetadataRef Scope, const char *Name,
911 LLVMMetadataRef File, unsigned LineNo) {
912 return wrap(Builder->createNameSpace(
913 unwrapDI<DIDescriptor>(Scope), Name,
914 false // ExportSymbols (only relevant for C++ anonymous namespaces)
919 LLVMRustDICompositeTypeReplaceArrays(LLVMRustDIBuilderRef Builder,
920 LLVMMetadataRef CompositeTy,
921 LLVMMetadataRef Elements,
922 LLVMMetadataRef Params) {
923 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
924 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(Elements)),
925 DINodeArray(unwrap<MDTuple>(Params)));
928 extern "C" LLVMValueRef
929 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
930 unsigned Column, LLVMMetadataRef Scope,
931 LLVMMetadataRef InlinedAt) {
932 LLVMContext &Context = *unwrap(ContextRef);
934 DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
935 unwrapDIPtr<MDNode>(InlinedAt));
937 return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
940 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
941 return dwarf::DW_OP_deref;
944 extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
945 return dwarf::DW_OP_plus_uconst;
948 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
949 RawRustStringOstream OS(Str);
950 unwrap<llvm::Type>(Ty)->print(OS);
953 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
955 RawRustStringOstream OS(Str);
960 unwrap<llvm::Value>(V)->getType()->print(OS);
962 unwrap<llvm::Value>(V)->print(OS);
967 // Note that the two following functions look quite similar to the
968 // LLVMGetSectionName function. Sadly, it appears that this function only
969 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
970 // function provided by LLVM doesn't return the length, so we've created our own
971 // function which returns the length as well as the data pointer.
973 // For an example of this not returning a null terminated string, see
974 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
975 // branches explicitly creates a StringRef without a null terminator, and then
978 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
979 return reinterpret_cast<section_iterator *>(SI);
982 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
985 if (std::error_code EC = (*unwrap(SI))->getName(Ret))
986 report_fatal_error(EC.message());
991 // LLVMArrayType function does not support 64-bit ElementCount
992 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
993 uint64_t ElementCount) {
994 return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
997 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
999 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
1000 RawRustStringOstream OS(Str);
1001 unwrap(T)->print(OS);
1004 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
1005 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
1006 LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
1007 RustStringRef FilenameOut, RustStringRef MessageOut) {
1008 // Undefined to call this not on an optimization diagnostic!
1009 llvm::DiagnosticInfoOptimizationBase *Opt =
1010 static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
1012 RawRustStringOstream PassNameOS(PassNameOut);
1013 PassNameOS << Opt->getPassName();
1014 *FunctionOut = wrap(&Opt->getFunction());
1016 RawRustStringOstream FilenameOS(FilenameOut);
1017 DiagnosticLocation loc = Opt->getLocation();
1018 if (loc.isValid()) {
1019 *Line = loc.getLine();
1020 *Column = loc.getColumn();
1021 #if LLVM_VERSION_GE(8, 0)
1022 FilenameOS << loc.getAbsolutePath();
1024 FilenameOS << loc.getFilename();
1028 RawRustStringOstream MessageOS(MessageOut);
1029 MessageOS << Opt->getMsg();
1033 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
1034 LLVMTwineRef *MessageOut,
1035 LLVMValueRef *InstructionOut) {
1036 // Undefined to call this not on an inline assembly diagnostic!
1037 llvm::DiagnosticInfoInlineAsm *IA =
1038 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
1040 *CookieOut = IA->getLocCookie();
1041 *MessageOut = wrap(&IA->getMsgStr());
1042 *InstructionOut = wrap(IA->getInstruction());
1045 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
1046 RustStringRef Str) {
1047 RawRustStringOstream OS(Str);
1048 DiagnosticPrinterRawOStream DP(OS);
1049 unwrap(DI)->print(DP);
1052 enum class LLVMRustDiagnosticKind {
1056 DebugMetadataVersion,
1059 OptimizationRemarkMissed,
1060 OptimizationRemarkAnalysis,
1061 OptimizationRemarkAnalysisFPCommute,
1062 OptimizationRemarkAnalysisAliasing,
1063 OptimizationRemarkOther,
1064 OptimizationFailure,
1069 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
1072 return LLVMRustDiagnosticKind::InlineAsm;
1074 return LLVMRustDiagnosticKind::StackSize;
1075 case DK_DebugMetadataVersion:
1076 return LLVMRustDiagnosticKind::DebugMetadataVersion;
1077 case DK_SampleProfile:
1078 return LLVMRustDiagnosticKind::SampleProfile;
1079 case DK_OptimizationRemark:
1080 return LLVMRustDiagnosticKind::OptimizationRemark;
1081 case DK_OptimizationRemarkMissed:
1082 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
1083 case DK_OptimizationRemarkAnalysis:
1084 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
1085 case DK_OptimizationRemarkAnalysisFPCommute:
1086 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
1087 case DK_OptimizationRemarkAnalysisAliasing:
1088 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
1090 return LLVMRustDiagnosticKind::PGOProfile;
1092 return LLVMRustDiagnosticKind::Linker;
1094 return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
1095 ? LLVMRustDiagnosticKind::OptimizationRemarkOther
1096 : LLVMRustDiagnosticKind::Other;
1100 extern "C" LLVMRustDiagnosticKind
1101 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
1102 return toRust((DiagnosticKind)unwrap(DI)->getKind());
1104 // This is kept distinct from LLVMGetTypeKind, because when
1105 // a new type kind is added, the Rust-side enum must be
1106 // updated or UB will result.
1107 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
1108 switch (unwrap(Ty)->getTypeID()) {
1109 case Type::VoidTyID:
1110 return LLVMVoidTypeKind;
1111 case Type::HalfTyID:
1112 return LLVMHalfTypeKind;
1113 case Type::FloatTyID:
1114 return LLVMFloatTypeKind;
1115 case Type::DoubleTyID:
1116 return LLVMDoubleTypeKind;
1117 case Type::X86_FP80TyID:
1118 return LLVMX86_FP80TypeKind;
1119 case Type::FP128TyID:
1120 return LLVMFP128TypeKind;
1121 case Type::PPC_FP128TyID:
1122 return LLVMPPC_FP128TypeKind;
1123 case Type::LabelTyID:
1124 return LLVMLabelTypeKind;
1125 case Type::MetadataTyID:
1126 return LLVMMetadataTypeKind;
1127 case Type::IntegerTyID:
1128 return LLVMIntegerTypeKind;
1129 case Type::FunctionTyID:
1130 return LLVMFunctionTypeKind;
1131 case Type::StructTyID:
1132 return LLVMStructTypeKind;
1133 case Type::ArrayTyID:
1134 return LLVMArrayTypeKind;
1135 case Type::PointerTyID:
1136 return LLVMPointerTypeKind;
1137 case Type::VectorTyID:
1138 return LLVMVectorTypeKind;
1139 case Type::X86_MMXTyID:
1140 return LLVMX86_MMXTypeKind;
1141 case Type::TokenTyID:
1142 return LLVMTokenTypeKind;
1144 report_fatal_error("Unhandled TypeID.");
1147 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
1149 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
1150 LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
1151 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
1154 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
1155 RustStringRef Str) {
1156 RawRustStringOstream OS(Str);
1157 unwrap(D)->print("", OS);
1160 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
1161 LLVMValueRef ParentPad,
1163 LLVMValueRef *LLArgs,
1165 Value **Args = unwrap(LLArgs);
1166 if (ParentPad == nullptr) {
1167 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1168 ParentPad = wrap(Constant::getNullValue(Ty));
1170 return wrap(unwrap(B)->CreateCleanupPad(
1171 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1174 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
1175 LLVMValueRef CleanupPad,
1176 LLVMBasicBlockRef UnwindBB) {
1177 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
1178 return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
1181 extern "C" LLVMValueRef
1182 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1183 unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1184 Value **Args = unwrap(LLArgs);
1185 return wrap(unwrap(B)->CreateCatchPad(
1186 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1189 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1191 LLVMBasicBlockRef BB) {
1192 return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1196 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1197 LLVMValueRef ParentPad,
1198 LLVMBasicBlockRef BB,
1199 unsigned NumHandlers,
1201 if (ParentPad == nullptr) {
1202 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1203 ParentPad = wrap(Constant::getNullValue(Ty));
1205 return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1206 NumHandlers, Name));
1209 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1210 LLVMBasicBlockRef Handler) {
1211 Value *CatchSwitch = unwrap(CatchSwitchRef);
1212 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1215 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1216 LLVMValueRef *Inputs,
1217 unsigned NumInputs) {
1218 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1221 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1225 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1226 LLVMValueRef *Args, unsigned NumArgs,
1227 OperandBundleDef *Bundle,
1229 unsigned Len = Bundle ? 1 : 0;
1230 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1231 return wrap(unwrap(B)->CreateCall(
1232 unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1235 extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B,
1236 LLVMValueRef Dst, unsigned DstAlign,
1237 LLVMValueRef Src, unsigned SrcAlign,
1238 LLVMValueRef Size, bool IsVolatile) {
1239 #if LLVM_VERSION_GE(7, 0)
1240 return wrap(unwrap(B)->CreateMemCpy(
1241 unwrap(Dst), DstAlign,
1242 unwrap(Src), SrcAlign,
1243 unwrap(Size), IsVolatile));
1245 unsigned Align = std::min(DstAlign, SrcAlign);
1246 return wrap(unwrap(B)->CreateMemCpy(
1247 unwrap(Dst), unwrap(Src),
1248 unwrap(Size), Align, IsVolatile));
1252 extern "C" LLVMValueRef LLVMRustBuildMemMove(LLVMBuilderRef B,
1253 LLVMValueRef Dst, unsigned DstAlign,
1254 LLVMValueRef Src, unsigned SrcAlign,
1255 LLVMValueRef Size, bool IsVolatile) {
1256 #if LLVM_VERSION_GE(7, 0)
1257 return wrap(unwrap(B)->CreateMemMove(
1258 unwrap(Dst), DstAlign,
1259 unwrap(Src), SrcAlign,
1260 unwrap(Size), IsVolatile));
1262 unsigned Align = std::min(DstAlign, SrcAlign);
1263 return wrap(unwrap(B)->CreateMemMove(
1264 unwrap(Dst), unwrap(Src),
1265 unwrap(Size), Align, IsVolatile));
1269 extern "C" LLVMValueRef
1270 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1271 unsigned NumArgs, LLVMBasicBlockRef Then,
1272 LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1274 unsigned Len = Bundle ? 1 : 0;
1275 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1276 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1277 makeArrayRef(unwrap(Args), NumArgs),
1281 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1282 LLVMBasicBlockRef BB) {
1283 auto Point = unwrap(BB)->getFirstInsertionPt();
1284 unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1287 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1289 Triple TargetTriple(unwrap(M)->getTargetTriple());
1290 GlobalObject *GV = unwrap<GlobalObject>(V);
1291 if (!TargetTriple.isOSBinFormatMachO()) {
1292 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1296 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1297 GlobalObject *GV = unwrap<GlobalObject>(V);
1298 GV->setComdat(nullptr);
1301 enum class LLVMRustLinkage {
1302 ExternalLinkage = 0,
1303 AvailableExternallyLinkage = 1,
1304 LinkOnceAnyLinkage = 2,
1305 LinkOnceODRLinkage = 3,
1308 AppendingLinkage = 6,
1309 InternalLinkage = 7,
1311 ExternalWeakLinkage = 9,
1315 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1317 case LLVMExternalLinkage:
1318 return LLVMRustLinkage::ExternalLinkage;
1319 case LLVMAvailableExternallyLinkage:
1320 return LLVMRustLinkage::AvailableExternallyLinkage;
1321 case LLVMLinkOnceAnyLinkage:
1322 return LLVMRustLinkage::LinkOnceAnyLinkage;
1323 case LLVMLinkOnceODRLinkage:
1324 return LLVMRustLinkage::LinkOnceODRLinkage;
1325 case LLVMWeakAnyLinkage:
1326 return LLVMRustLinkage::WeakAnyLinkage;
1327 case LLVMWeakODRLinkage:
1328 return LLVMRustLinkage::WeakODRLinkage;
1329 case LLVMAppendingLinkage:
1330 return LLVMRustLinkage::AppendingLinkage;
1331 case LLVMInternalLinkage:
1332 return LLVMRustLinkage::InternalLinkage;
1333 case LLVMPrivateLinkage:
1334 return LLVMRustLinkage::PrivateLinkage;
1335 case LLVMExternalWeakLinkage:
1336 return LLVMRustLinkage::ExternalWeakLinkage;
1337 case LLVMCommonLinkage:
1338 return LLVMRustLinkage::CommonLinkage;
1340 report_fatal_error("Invalid LLVMRustLinkage value!");
1344 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1346 case LLVMRustLinkage::ExternalLinkage:
1347 return LLVMExternalLinkage;
1348 case LLVMRustLinkage::AvailableExternallyLinkage:
1349 return LLVMAvailableExternallyLinkage;
1350 case LLVMRustLinkage::LinkOnceAnyLinkage:
1351 return LLVMLinkOnceAnyLinkage;
1352 case LLVMRustLinkage::LinkOnceODRLinkage:
1353 return LLVMLinkOnceODRLinkage;
1354 case LLVMRustLinkage::WeakAnyLinkage:
1355 return LLVMWeakAnyLinkage;
1356 case LLVMRustLinkage::WeakODRLinkage:
1357 return LLVMWeakODRLinkage;
1358 case LLVMRustLinkage::AppendingLinkage:
1359 return LLVMAppendingLinkage;
1360 case LLVMRustLinkage::InternalLinkage:
1361 return LLVMInternalLinkage;
1362 case LLVMRustLinkage::PrivateLinkage:
1363 return LLVMPrivateLinkage;
1364 case LLVMRustLinkage::ExternalWeakLinkage:
1365 return LLVMExternalWeakLinkage;
1366 case LLVMRustLinkage::CommonLinkage:
1367 return LLVMCommonLinkage;
1369 report_fatal_error("Invalid LLVMRustLinkage value!");
1372 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1373 return toRust(LLVMGetLinkage(V));
1376 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1377 LLVMRustLinkage RustLinkage) {
1378 LLVMSetLinkage(V, fromRust(RustLinkage));
1381 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1382 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1383 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1385 auto C = unwrap<llvm::ConstantInt>(CV);
1386 if (C->getBitWidth() > 128) { return false; }
1389 AP = C->getValue().sextOrSelf(128);
1391 AP = C->getValue().zextOrSelf(128);
1393 *low = AP.getLoBits(64).getZExtValue();
1394 *high = AP.getHiBits(64).getZExtValue();
1398 enum class LLVMRustVisibility {
1404 static LLVMRustVisibility toRust(LLVMVisibility Vis) {
1406 case LLVMDefaultVisibility:
1407 return LLVMRustVisibility::Default;
1408 case LLVMHiddenVisibility:
1409 return LLVMRustVisibility::Hidden;
1410 case LLVMProtectedVisibility:
1411 return LLVMRustVisibility::Protected;
1413 report_fatal_error("Invalid LLVMRustVisibility value!");
1416 static LLVMVisibility fromRust(LLVMRustVisibility Vis) {
1418 case LLVMRustVisibility::Default:
1419 return LLVMDefaultVisibility;
1420 case LLVMRustVisibility::Hidden:
1421 return LLVMHiddenVisibility;
1422 case LLVMRustVisibility::Protected:
1423 return LLVMProtectedVisibility;
1425 report_fatal_error("Invalid LLVMRustVisibility value!");
1428 extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) {
1429 return toRust(LLVMGetVisibility(V));
1432 // Oh hey, a binding that makes sense for once? (because LLVM’s own do not)
1433 extern "C" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
1434 LLVMTypeRef DestTy, bool isSigned) {
1435 return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, ""));
1438 extern "C" void LLVMRustSetVisibility(LLVMValueRef V,
1439 LLVMRustVisibility RustVisibility) {
1440 LLVMSetVisibility(V, fromRust(RustVisibility));
1443 struct LLVMRustModuleBuffer {
1447 extern "C" LLVMRustModuleBuffer*
1448 LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1449 auto Ret = llvm::make_unique<LLVMRustModuleBuffer>();
1451 raw_string_ostream OS(Ret->data);
1453 legacy::PassManager PM;
1454 PM.add(createBitcodeWriterPass(OS));
1458 return Ret.release();
1462 LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1466 extern "C" const void*
1467 LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
1468 return Buffer->data.data();
1472 LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1473 return Buffer->data.length();
1477 LLVMRustModuleCost(LLVMModuleRef M) {
1478 auto f = unwrap(M)->functions();
1479 return std::distance(std::begin(f), std::end(f));
1482 // Vector reductions:
1483 extern "C" LLVMValueRef
1484 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1485 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1487 extern "C" LLVMValueRef
1488 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1489 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1491 extern "C" LLVMValueRef
1492 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1493 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1495 extern "C" LLVMValueRef
1496 LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1497 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1499 extern "C" LLVMValueRef
1500 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1501 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1503 extern "C" LLVMValueRef
1504 LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1505 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1507 extern "C" LLVMValueRef
1508 LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1509 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1511 extern "C" LLVMValueRef
1512 LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1513 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1515 extern "C" LLVMValueRef
1516 LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1517 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1519 extern "C" LLVMValueRef
1520 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1521 return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN));
1523 extern "C" LLVMValueRef
1524 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1525 return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN));
1528 extern "C" LLVMValueRef
1529 LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1530 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1532 extern "C" LLVMValueRef
1533 LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1534 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));