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/Object/Archive.h"
13 #include "llvm/Object/ObjectFile.h"
14 #include "llvm/IR/DiagnosticInfo.h"
15 #include "llvm/IR/DiagnosticPrinter.h"
16 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/CallSite.h"
20 //===----------------------------------------------------------------------===
22 // This file defines alternate interfaces to core functions that are more
23 // readily callable by Rust's FFI.
25 //===----------------------------------------------------------------------===
28 using namespace llvm::sys;
29 using namespace llvm::object;
31 // LLVMAtomicOrdering is already an enum - don't create another
33 static AtomicOrdering from_rust(LLVMAtomicOrdering Ordering) {
35 case LLVMAtomicOrderingNotAtomic:
36 return AtomicOrdering::NotAtomic;
37 case LLVMAtomicOrderingUnordered:
38 return AtomicOrdering::Unordered;
39 case LLVMAtomicOrderingMonotonic:
40 return AtomicOrdering::Monotonic;
41 case LLVMAtomicOrderingAcquire:
42 return AtomicOrdering::Acquire;
43 case LLVMAtomicOrderingRelease:
44 return AtomicOrdering::Release;
45 case LLVMAtomicOrderingAcquireRelease:
46 return AtomicOrdering::AcquireRelease;
47 case LLVMAtomicOrderingSequentiallyConsistent:
48 return AtomicOrdering::SequentiallyConsistent;
51 llvm_unreachable("Invalid LLVMAtomicOrdering value!");
55 static char *LastError;
57 extern "C" LLVMMemoryBufferRef
58 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
59 ErrorOr<std::unique_ptr<MemoryBuffer>> buf_or = MemoryBuffer::getFile(Path,
63 LLVMRustSetLastError(buf_or.getError().message().c_str());
66 return wrap(buf_or.get().release());
69 extern "C" char *LLVMRustGetLastError(void) {
70 char *ret = LastError;
75 void LLVMRustSetLastError(const char *err) {
76 free((void*) LastError);
77 LastError = strdup(err);
81 LLVMRustSetNormalizedTarget(LLVMModuleRef M, const char *triple) {
82 unwrap(M)->setTargetTriple(Triple::normalize(triple));
85 extern "C" void LLVMRustPrintPassTimings() {
86 raw_fd_ostream OS (2, false); // stderr.
87 TimerGroup::printAll(OS);
90 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
92 return wrap(unwrap(M)->getNamedValue(Name));
95 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
97 LLVMTypeRef FunctionTy) {
98 return wrap(unwrap(M)->getOrInsertFunction(Name,
99 unwrap<FunctionType>(FunctionTy)));
102 extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
105 return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
108 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
109 return wrap(Type::getMetadataTy(*unwrap(C)));
112 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned index, uint64_t Val) {
113 CallSite Call = CallSite(unwrap<Instruction>(Instr));
117 Call.getAttributes().addAttributes(Call->getContext(), index,
118 AttributeSet::get(Call->getContext(),
123 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
127 CallSite Call = CallSite(unwrap<Instruction>(Instr));
129 B.addDereferenceableAttr(b);
131 Call.getAttributes().addAttributes(Call->getContext(), idx,
132 AttributeSet::get(Call->getContext(),
136 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn,
140 Function *A = unwrap<Function>(Fn);
143 A->addAttributes(index, AttributeSet::get(A->getContext(), index, B));
146 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn,
150 Function *A = unwrap<Function>(Fn);
152 B.addDereferenceableAttr(bytes);
153 A->addAttributes(index, AttributeSet::get(A->getContext(), index, B));
156 extern "C" void LLVMRustAddFunctionAttrString(LLVMValueRef Fn,
160 Function *F = unwrap<Function>(Fn);
162 B.addAttribute(Name);
163 F->addAttributes(index, AttributeSet::get(F->getContext(), index, B));
166 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
170 Function *F = unwrap<Function>(Fn);
172 B.addAttribute(Name, Value);
173 F->addAttributes(index, AttributeSet::get(F->getContext(), index, B));
176 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
180 Function *A = unwrap<Function>(Fn);
181 const AttributeSet PAL = A->getAttributes();
183 const AttributeSet PALnew =
184 PAL.removeAttributes(A->getContext(), index,
185 AttributeSet::get(A->getContext(), index, B));
186 A->setAttributes(PALnew);
189 extern "C" void LLVMRustRemoveFunctionAttrString(LLVMValueRef fn,
193 Function *f = unwrap<Function>(fn);
194 LLVMContext &C = f->getContext();
196 B.addAttribute(Name);
197 AttributeSet to_remove = AttributeSet::get(C, index, B);
199 AttributeSet attrs = f->getAttributes();
200 f->setAttributes(attrs.removeAttributes(f->getContext(),
205 // enable fpmath flag UnsafeAlgebra
206 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
207 if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
208 I->setHasUnsafeAlgebra(true);
212 extern "C" LLVMValueRef LLVMRustBuildAtomicLoad(LLVMBuilderRef B,
215 LLVMAtomicOrdering order,
216 unsigned alignment) {
217 LoadInst* li = new LoadInst(unwrap(source),0);
218 li->setAtomic(from_rust(order));
219 li->setAlignment(alignment);
220 return wrap(unwrap(B)->Insert(li, Name));
223 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
226 LLVMAtomicOrdering order,
227 unsigned alignment) {
228 StoreInst* si = new StoreInst(unwrap(val),unwrap(target));
229 si->setAtomic(from_rust(order));
230 si->setAlignment(alignment);
231 return wrap(unwrap(B)->Insert(si));
234 extern "C" LLVMValueRef LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B,
238 LLVMAtomicOrdering order,
239 LLVMAtomicOrdering failure_order,
241 AtomicCmpXchgInst* acxi = unwrap(B)->CreateAtomicCmpXchg(
246 from_rust(failure_order));
251 enum class LLVMRustSynchronizationScope {
257 static SynchronizationScope
258 from_rust(LLVMRustSynchronizationScope scope)
261 case LLVMRustSynchronizationScope::SingleThread:
263 case LLVMRustSynchronizationScope::CrossThread:
266 llvm_unreachable("bad SynchronizationScope.");
270 extern "C" LLVMValueRef LLVMRustBuildAtomicFence(
272 LLVMAtomicOrdering order,
273 LLVMRustSynchronizationScope scope)
275 return wrap(unwrap(B)->CreateFence(from_rust(order), from_rust(scope)));
278 extern "C" void LLVMRustSetDebug(int Enabled) {
284 enum class LLVMRustAsmDialect {
290 static InlineAsm::AsmDialect
291 from_rust(LLVMRustAsmDialect dialect)
294 case LLVMRustAsmDialect::Att:
295 return InlineAsm::AD_ATT;
296 case LLVMRustAsmDialect::Intel:
297 return InlineAsm::AD_Intel;
299 llvm_unreachable("bad AsmDialect.");
303 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty,
306 LLVMBool HasSideEffects,
307 LLVMBool IsAlignStack,
308 LLVMRustAsmDialect Dialect) {
309 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString,
310 Constraints, HasSideEffects,
311 IsAlignStack, from_rust(Dialect)));
314 typedef DIBuilder* LLVMRustDIBuilderRef;
316 typedef struct LLVMOpaqueMetadata *LLVMRustMetadataRef;
319 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMRustMetadataRef)
321 inline Metadata **unwrap(LLVMRustMetadataRef *Vals) {
322 return reinterpret_cast<Metadata**>(Vals);
326 template<typename DIT>
327 DIT* unwrapDIptr(LLVMRustMetadataRef ref) {
328 return (DIT*) (ref ? unwrap<MDNode>(ref) : NULL);
331 #define DIDescriptor DIScope
332 #define DIArray DINodeArray
333 #define unwrapDI unwrapDIptr
335 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
336 return DEBUG_METADATA_VERSION;
339 extern "C" uint32_t LLVMRustVersionMinor() {
340 return LLVM_VERSION_MINOR;
343 extern "C" uint32_t LLVMRustVersionMajor() {
344 return LLVM_VERSION_MAJOR;
347 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M,
350 unwrap(M)->addModuleFlag(Module::Warning, name, value);
353 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
354 return new DIBuilder(*unwrap(M));
357 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
361 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
365 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateCompileUnit(
366 LLVMRustDIBuilderRef Builder,
370 const char* Producer,
374 const char* SplitName) {
375 return wrap(Builder->createCompileUnit(Lang,
385 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateFile(
386 LLVMRustDIBuilderRef Builder,
387 const char* Filename,
388 const char* Directory) {
389 return wrap(Builder->createFile(Filename, Directory));
392 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateSubroutineType(
393 LLVMRustDIBuilderRef Builder,
394 LLVMRustMetadataRef File,
395 LLVMRustMetadataRef ParameterTypes) {
396 return wrap(Builder->createSubroutineType(
397 #if LLVM_VERSION_EQ(3, 7)
398 unwrapDI<DIFile>(File),
400 DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
403 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateFunction(
404 LLVMRustDIBuilderRef Builder,
405 LLVMRustMetadataRef Scope,
407 const char* LinkageName,
408 LLVMRustMetadataRef File,
410 LLVMRustMetadataRef Ty,
417 LLVMRustMetadataRef TParam,
418 LLVMRustMetadataRef Decl) {
419 #if LLVM_VERSION_GE(3, 8)
420 DITemplateParameterArray TParams =
421 DITemplateParameterArray(unwrap<MDTuple>(TParam));
422 DISubprogram *Sub = Builder->createFunction(
423 unwrapDI<DIScope>(Scope), Name, LinkageName,
424 unwrapDI<DIFile>(File), LineNo,
425 unwrapDI<DISubroutineType>(Ty), isLocalToUnit, isDefinition, ScopeLine,
428 unwrapDIptr<DISubprogram>(Decl));
429 unwrap<Function>(Fn)->setSubprogram(Sub);
432 return wrap(Builder->createFunction(
433 unwrapDI<DIScope>(Scope), Name, LinkageName,
434 unwrapDI<DIFile>(File), LineNo,
435 unwrapDI<DISubroutineType>(Ty), isLocalToUnit, isDefinition, ScopeLine,
437 unwrap<Function>(Fn),
438 unwrapDIptr<MDNode>(TParam),
439 unwrapDIptr<MDNode>(Decl)));
443 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateBasicType(
444 LLVMRustDIBuilderRef Builder,
447 uint64_t AlignInBits,
449 return wrap(Builder->createBasicType(
451 AlignInBits, Encoding));
454 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreatePointerType(
455 LLVMRustDIBuilderRef Builder,
456 LLVMRustMetadataRef PointeeTy,
458 uint64_t AlignInBits,
460 return wrap(Builder->createPointerType(
461 unwrapDI<DIType>(PointeeTy), SizeInBits, AlignInBits, Name));
464 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateStructType(
465 LLVMRustDIBuilderRef Builder,
466 LLVMRustMetadataRef Scope,
468 LLVMRustMetadataRef File,
471 uint64_t AlignInBits,
473 LLVMRustMetadataRef DerivedFrom,
474 LLVMRustMetadataRef Elements,
475 unsigned RunTimeLang,
476 LLVMRustMetadataRef VTableHolder,
477 const char *UniqueId) {
478 return wrap(Builder->createStructType(
479 unwrapDI<DIDescriptor>(Scope),
481 unwrapDI<DIFile>(File),
486 unwrapDI<DIType>(DerivedFrom),
487 DINodeArray(unwrapDI<MDTuple>(Elements)),
489 unwrapDI<DIType>(VTableHolder),
494 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateMemberType(
495 LLVMRustDIBuilderRef Builder,
496 LLVMRustMetadataRef Scope,
498 LLVMRustMetadataRef File,
501 uint64_t AlignInBits,
502 uint64_t OffsetInBits,
504 LLVMRustMetadataRef Ty) {
505 return wrap(Builder->createMemberType(
506 unwrapDI<DIDescriptor>(Scope), Name,
507 unwrapDI<DIFile>(File), LineNo,
508 SizeInBits, AlignInBits, OffsetInBits, Flags,
509 unwrapDI<DIType>(Ty)));
512 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
513 LLVMRustDIBuilderRef Builder,
514 LLVMRustMetadataRef Scope,
515 LLVMRustMetadataRef File,
518 return wrap(Builder->createLexicalBlock(
519 unwrapDI<DIDescriptor>(Scope),
520 unwrapDI<DIFile>(File), Line, Col
524 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateLexicalBlockFile(
525 LLVMRustDIBuilderRef Builder,
526 LLVMRustMetadataRef Scope,
527 LLVMRustMetadataRef File) {
528 return wrap(Builder->createLexicalBlockFile(
529 unwrapDI<DIDescriptor>(Scope),
530 unwrapDI<DIFile>(File)));
533 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateStaticVariable(
534 LLVMRustDIBuilderRef Builder,
535 LLVMRustMetadataRef Context,
537 const char* LinkageName,
538 LLVMRustMetadataRef File,
540 LLVMRustMetadataRef Ty,
543 LLVMRustMetadataRef Decl = NULL) {
544 return wrap(Builder->createGlobalVariable(unwrapDI<DIDescriptor>(Context),
547 unwrapDI<DIFile>(File),
549 unwrapDI<DIType>(Ty),
551 cast<Constant>(unwrap(Val)),
552 unwrapDIptr<MDNode>(Decl)));
555 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateVariable(
556 LLVMRustDIBuilderRef Builder,
558 LLVMRustMetadataRef Scope,
560 LLVMRustMetadataRef File,
562 LLVMRustMetadataRef Ty,
566 unsigned AddrOpsCount,
568 #if LLVM_VERSION_GE(3, 8)
569 if (Tag == 0x100) { // DW_TAG_auto_variable
570 return wrap(Builder->createAutoVariable(
571 unwrapDI<DIDescriptor>(Scope), Name,
572 unwrapDI<DIFile>(File),
574 unwrapDI<DIType>(Ty), AlwaysPreserve, Flags));
576 return wrap(Builder->createParameterVariable(
577 unwrapDI<DIDescriptor>(Scope), Name, ArgNo,
578 unwrapDI<DIFile>(File),
580 unwrapDI<DIType>(Ty), AlwaysPreserve, Flags));
583 return wrap(Builder->createLocalVariable(Tag,
584 unwrapDI<DIDescriptor>(Scope), Name,
585 unwrapDI<DIFile>(File),
587 unwrapDI<DIType>(Ty), AlwaysPreserve, Flags, ArgNo));
591 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateArrayType(
592 LLVMRustDIBuilderRef Builder,
594 uint64_t AlignInBits,
595 LLVMRustMetadataRef Ty,
596 LLVMRustMetadataRef Subscripts) {
597 return wrap(Builder->createArrayType(Size, AlignInBits,
598 unwrapDI<DIType>(Ty),
599 DINodeArray(unwrapDI<MDTuple>(Subscripts))
603 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateVectorType(
604 LLVMRustDIBuilderRef Builder,
606 uint64_t AlignInBits,
607 LLVMRustMetadataRef Ty,
608 LLVMRustMetadataRef Subscripts) {
609 return wrap(Builder->createVectorType(Size, AlignInBits,
610 unwrapDI<DIType>(Ty),
611 DINodeArray(unwrapDI<MDTuple>(Subscripts))
615 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderGetOrCreateSubrange(
616 LLVMRustDIBuilderRef Builder,
619 return wrap(Builder->getOrCreateSubrange(Lo, Count));
622 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderGetOrCreateArray(
623 LLVMRustDIBuilderRef Builder,
624 LLVMRustMetadataRef* Ptr,
626 Metadata **DataValue = unwrap(Ptr);
627 return wrap(Builder->getOrCreateArray(
628 ArrayRef<Metadata*>(DataValue, Count)).get());
631 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
632 LLVMRustDIBuilderRef Builder,
634 LLVMRustMetadataRef VarInfo,
636 unsigned AddrOpsCount,
638 LLVMBasicBlockRef InsertAtEnd) {
639 return wrap(Builder->insertDeclare(
641 unwrap<DILocalVariable>(VarInfo),
642 Builder->createExpression(
643 llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
644 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
645 unwrap(InsertAtEnd)));
648 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareBefore(
649 LLVMRustDIBuilderRef Builder,
651 LLVMRustMetadataRef VarInfo,
653 unsigned AddrOpsCount,
655 LLVMValueRef InsertBefore) {
656 return wrap(Builder->insertDeclare(
658 unwrap<DILocalVariable>(VarInfo),
659 Builder->createExpression(
660 llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
661 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
662 unwrap<Instruction>(InsertBefore)));
665 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateEnumerator(
666 LLVMRustDIBuilderRef Builder,
670 return wrap(Builder->createEnumerator(Name, Val));
673 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateEnumerationType(
674 LLVMRustDIBuilderRef Builder,
675 LLVMRustMetadataRef Scope,
677 LLVMRustMetadataRef File,
680 uint64_t AlignInBits,
681 LLVMRustMetadataRef Elements,
682 LLVMRustMetadataRef ClassType)
684 return wrap(Builder->createEnumerationType(
685 unwrapDI<DIDescriptor>(Scope),
687 unwrapDI<DIFile>(File),
691 DINodeArray(unwrapDI<MDTuple>(Elements)),
692 unwrapDI<DIType>(ClassType)));
695 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateUnionType(
696 LLVMRustDIBuilderRef Builder,
697 LLVMRustMetadataRef Scope,
699 LLVMRustMetadataRef File,
702 uint64_t AlignInBits,
704 LLVMRustMetadataRef Elements,
705 unsigned RunTimeLang,
706 const char* UniqueId)
708 return wrap(Builder->createUnionType(
709 unwrapDI<DIDescriptor>(Scope),
711 unwrapDI<DIFile>(File),
716 DINodeArray(unwrapDI<MDTuple>(Elements)),
722 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
723 LLVMRustDIBuilderRef Builder,
724 LLVMRustMetadataRef Scope,
726 LLVMRustMetadataRef Ty,
727 LLVMRustMetadataRef File,
731 return wrap(Builder->createTemplateTypeParameter(
732 unwrapDI<DIDescriptor>(Scope),
738 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateNameSpace(
739 LLVMRustDIBuilderRef Builder,
740 LLVMRustMetadataRef Scope,
742 LLVMRustMetadataRef File,
745 return wrap(Builder->createNameSpace(
746 unwrapDI<DIDescriptor>(Scope),
748 unwrapDI<DIFile>(File),
752 extern "C" void LLVMRustDICompositeTypeSetTypeArray(
753 LLVMRustDIBuilderRef Builder,
754 LLVMRustMetadataRef CompositeType,
755 LLVMRustMetadataRef TypeArray)
757 DICompositeType *tmp = unwrapDI<DICompositeType>(CompositeType);
758 Builder->replaceArrays(tmp, DINodeArray(unwrap<MDTuple>(TypeArray)));
761 extern "C" LLVMValueRef LLVMRustDIBuilderCreateDebugLocation(
762 LLVMContextRef Context,
765 LLVMRustMetadataRef Scope,
766 LLVMRustMetadataRef InlinedAt)
768 LLVMContext& context = *unwrap(Context);
770 DebugLoc debug_loc = DebugLoc::get(Line,
772 unwrapDIptr<MDNode>(Scope),
773 unwrapDIptr<MDNode>(InlinedAt));
775 return wrap(MetadataAsValue::get(context, debug_loc.getAsMDNode()));
778 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref()
780 return dwarf::DW_OP_deref;
783 extern "C" int64_t LLVMRustDIBuilderCreateOpPlus()
785 return dwarf::DW_OP_plus;
788 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Type, RustStringRef str) {
789 raw_rust_string_ostream os(str);
790 unwrap<llvm::Type>(Type)->print(os);
793 extern "C" void LLVMRustWriteValueToString(LLVMValueRef Value, RustStringRef str) {
794 raw_rust_string_ostream os(str);
796 unwrap<llvm::Value>(Value)->getType()->print(os);
798 unwrap<llvm::Value>(Value)->print(os);
803 LLVMRustLinkInExternalBitcode(LLVMModuleRef dst, char *bc, size_t len) {
804 Module *Dst = unwrap(dst);
805 std::unique_ptr<MemoryBuffer> buf = MemoryBuffer::getMemBufferCopy(StringRef(bc, len));
806 ErrorOr<std::unique_ptr<Module>> Src =
807 llvm::getLazyBitcodeModule(std::move(buf), Dst->getContext());
809 LLVMRustSetLastError(Src.getError().message().c_str());
815 raw_string_ostream Stream(Err);
816 DiagnosticPrinterRawOStream DP(Stream);
817 #if LLVM_VERSION_GE(3, 8)
818 if (Linker::linkModules(*Dst, std::move(Src.get()))) {
820 if (Linker::LinkModules(Dst, Src->get(), [&](const DiagnosticInfo &DI) { DI.print(DP); })) {
822 LLVMRustSetLastError(Err.c_str());
828 // Note that the two following functions look quite similar to the
829 // LLVMGetSectionName function. Sadly, it appears that this function only
830 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
831 // function provided by LLVM doesn't return the length, so we've created our own
832 // function which returns the length as well as the data pointer.
834 // For an example of this not returning a null terminated string, see
835 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
836 // branches explicitly creates a StringRef without a null terminator, and then
839 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
840 return reinterpret_cast<section_iterator*>(SI);
844 LLVMRustGetSectionName(LLVMSectionIteratorRef SI, const char **ptr) {
846 if (std::error_code ec = (*unwrap(SI))->getName(ret))
847 report_fatal_error(ec.message());
852 // LLVMArrayType function does not support 64-bit ElementCount
853 extern "C" LLVMTypeRef
854 LLVMRustArrayType(LLVMTypeRef ElementType, uint64_t ElementCount) {
855 return wrap(ArrayType::get(unwrap(ElementType), ElementCount));
858 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
859 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(DebugLoc, LLVMDebugLocRef)
862 LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef str) {
863 raw_rust_string_ostream os(str);
864 unwrap(T)->print(os);
868 LLVMRustUnpackOptimizationDiagnostic(
869 LLVMDiagnosticInfoRef di,
870 const char **pass_name_out,
871 LLVMValueRef *function_out,
872 LLVMDebugLocRef *debugloc_out,
873 LLVMTwineRef *message_out)
875 // Undefined to call this not on an optimization diagnostic!
876 llvm::DiagnosticInfoOptimizationBase *opt
877 = static_cast<llvm::DiagnosticInfoOptimizationBase*>(unwrap(di));
879 *pass_name_out = opt->getPassName();
880 *function_out = wrap(&opt->getFunction());
881 *debugloc_out = wrap(&opt->getDebugLoc());
882 *message_out = wrap(&opt->getMsg());
886 LLVMRustUnpackInlineAsmDiagnostic(
887 LLVMDiagnosticInfoRef di,
888 unsigned *cookie_out,
889 LLVMTwineRef *message_out,
890 LLVMValueRef *instruction_out)
892 // Undefined to call this not on an inline assembly diagnostic!
893 llvm::DiagnosticInfoInlineAsm *ia
894 = static_cast<llvm::DiagnosticInfoInlineAsm*>(unwrap(di));
896 *cookie_out = ia->getLocCookie();
897 *message_out = wrap(&ia->getMsgStr());
898 *instruction_out = wrap(ia->getInstruction());
901 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef di, RustStringRef str) {
902 raw_rust_string_ostream os(str);
903 DiagnosticPrinterRawOStream dp(os);
904 unwrap(di)->print(dp);
907 enum class LLVMRustDiagnosticKind {
911 DebugMetadataVersion,
914 OptimizationRemarkMissed,
915 OptimizationRemarkAnalysis,
916 OptimizationRemarkAnalysisFPCommute,
917 OptimizationRemarkAnalysisAliasing,
918 OptimizationRemarkOther,
922 static LLVMRustDiagnosticKind
923 to_rust(DiagnosticKind kind)
927 return LLVMRustDiagnosticKind::InlineAsm;
929 return LLVMRustDiagnosticKind::StackSize;
930 case DK_DebugMetadataVersion:
931 return LLVMRustDiagnosticKind::DebugMetadataVersion;
932 case DK_SampleProfile:
933 return LLVMRustDiagnosticKind::SampleProfile;
934 case DK_OptimizationRemark:
935 return LLVMRustDiagnosticKind::OptimizationRemark;
936 case DK_OptimizationRemarkMissed:
937 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
938 case DK_OptimizationRemarkAnalysis:
939 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
940 #if LLVM_VERSION_GE(3, 8)
941 case DK_OptimizationRemarkAnalysisFPCommute:
942 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
943 case DK_OptimizationRemarkAnalysisAliasing:
944 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
947 #if LLVM_VERSION_GE(3, 9)
948 return (kind >= DK_FirstRemark && kind <= DK_LastRemark) ?
949 LLVMRustDiagnosticKind::OptimizationRemarkOther :
950 LLVMRustDiagnosticKind::Other;
952 return LLVMRustDiagnosticKind::Other;
957 extern "C" LLVMRustDiagnosticKind LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef di) {
958 return to_rust((DiagnosticKind) unwrap(di)->getKind());
960 // This is kept distinct from LLVMGetTypeKind, because when
961 // a new type kind is added, the Rust-side enum must be
962 // updated or UB will result.
963 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
964 switch (unwrap(Ty)->getTypeID()) {
966 return LLVMVoidTypeKind;
968 return LLVMHalfTypeKind;
969 case Type::FloatTyID:
970 return LLVMFloatTypeKind;
971 case Type::DoubleTyID:
972 return LLVMDoubleTypeKind;
973 case Type::X86_FP80TyID:
974 return LLVMX86_FP80TypeKind;
975 case Type::FP128TyID:
976 return LLVMFP128TypeKind;
977 case Type::PPC_FP128TyID:
978 return LLVMPPC_FP128TypeKind;
979 case Type::LabelTyID:
980 return LLVMLabelTypeKind;
981 case Type::MetadataTyID:
982 return LLVMMetadataTypeKind;
983 case Type::IntegerTyID:
984 return LLVMIntegerTypeKind;
985 case Type::FunctionTyID:
986 return LLVMFunctionTypeKind;
987 case Type::StructTyID:
988 return LLVMStructTypeKind;
989 case Type::ArrayTyID:
990 return LLVMArrayTypeKind;
991 case Type::PointerTyID:
992 return LLVMPointerTypeKind;
993 case Type::VectorTyID:
994 return LLVMVectorTypeKind;
995 case Type::X86_MMXTyID:
996 return LLVMX86_MMXTypeKind;
997 #if LLVM_VERSION_GE(3, 8)
998 case Type::TokenTyID:
999 return LLVMTokenTypeKind;
1002 llvm_unreachable("Unhandled TypeID.");
1005 extern "C" void LLVMRustWriteDebugLocToString(
1010 raw_rust_string_ostream os(str);
1011 unwrap(dl)->print(os);
1014 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
1016 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
1018 LLVMContext::InlineAsmDiagHandlerTy H,
1021 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
1024 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef d,
1025 RustStringRef str) {
1026 raw_rust_string_ostream os(str);
1027 unwrap(d)->print("", os);
1030 extern "C" LLVMValueRef
1031 LLVMRustBuildLandingPad(LLVMBuilderRef Builder,
1033 LLVMValueRef PersFn,
1034 unsigned NumClauses,
1037 return LLVMBuildLandingPad(Builder, Ty, PersFn, NumClauses, Name);
1040 extern "C" LLVMValueRef
1041 LLVMRustBuildCleanupPad(LLVMBuilderRef Builder,
1042 LLVMValueRef ParentPad,
1044 LLVMValueRef *LLArgs,
1046 #if LLVM_VERSION_GE(3, 8)
1047 Value **Args = unwrap(LLArgs);
1048 if (ParentPad == NULL) {
1049 Type *Ty = Type::getTokenTy(unwrap(Builder)->getContext());
1050 ParentPad = wrap(Constant::getNullValue(Ty));
1052 return wrap(unwrap(Builder)->CreateCleanupPad(unwrap(ParentPad),
1053 ArrayRef<Value*>(Args, ArgCnt),
1060 extern "C" LLVMValueRef
1061 LLVMRustBuildCleanupRet(LLVMBuilderRef Builder,
1062 LLVMValueRef CleanupPad,
1063 LLVMBasicBlockRef UnwindBB) {
1064 #if LLVM_VERSION_GE(3, 8)
1065 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
1066 return wrap(unwrap(Builder)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
1072 extern "C" LLVMValueRef
1073 LLVMRustBuildCatchPad(LLVMBuilderRef Builder,
1074 LLVMValueRef ParentPad,
1076 LLVMValueRef *LLArgs,
1078 #if LLVM_VERSION_GE(3, 8)
1079 Value **Args = unwrap(LLArgs);
1080 return wrap(unwrap(Builder)->CreateCatchPad(unwrap(ParentPad),
1081 ArrayRef<Value*>(Args, ArgCnt),
1088 extern "C" LLVMValueRef
1089 LLVMRustBuildCatchRet(LLVMBuilderRef Builder,
1091 LLVMBasicBlockRef BB) {
1092 #if LLVM_VERSION_GE(3, 8)
1093 return wrap(unwrap(Builder)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1100 extern "C" LLVMValueRef
1101 LLVMRustBuildCatchSwitch(LLVMBuilderRef Builder,
1102 LLVMValueRef ParentPad,
1103 LLVMBasicBlockRef BB,
1104 unsigned NumHandlers,
1106 #if LLVM_VERSION_GE(3, 8)
1107 if (ParentPad == NULL) {
1108 Type *Ty = Type::getTokenTy(unwrap(Builder)->getContext());
1109 ParentPad = wrap(Constant::getNullValue(Ty));
1111 return wrap(unwrap(Builder)->CreateCatchSwitch(unwrap(ParentPad),
1121 LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1122 LLVMBasicBlockRef Handler) {
1123 #if LLVM_VERSION_GE(3, 8)
1124 Value *CatchSwitch = unwrap(CatchSwitchRef);
1125 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1130 LLVMRustSetPersonalityFn(LLVMBuilderRef B,
1131 LLVMValueRef Personality) {
1132 #if LLVM_VERSION_GE(3, 8)
1133 unwrap(B)->GetInsertBlock()
1135 ->setPersonalityFn(cast<Function>(unwrap(Personality)));
1139 #if LLVM_VERSION_GE(3, 8)
1140 extern "C" OperandBundleDef*
1141 LLVMRustBuildOperandBundleDef(const char *Name,
1142 LLVMValueRef *Inputs,
1143 unsigned NumInputs) {
1144 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1148 LLVMRustFreeOperandBundleDef(OperandBundleDef* Bundle) {
1152 extern "C" LLVMValueRef
1153 LLVMRustBuildCall(LLVMBuilderRef B,
1157 OperandBundleDef *Bundle,
1159 unsigned len = Bundle ? 1 : 0;
1160 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, len);
1161 return wrap(unwrap(B)->CreateCall(unwrap(Fn),
1162 makeArrayRef(unwrap(Args), NumArgs),
1167 extern "C" LLVMValueRef
1168 LLVMRustBuildInvoke(LLVMBuilderRef B,
1172 LLVMBasicBlockRef Then,
1173 LLVMBasicBlockRef Catch,
1174 OperandBundleDef *Bundle,
1176 unsigned len = Bundle ? 1 : 0;
1177 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, len);
1178 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1179 makeArrayRef(unwrap(Args), NumArgs),
1185 LLVMRustBuildOperandBundleDef(const char *Name,
1186 LLVMValueRef *Inputs,
1187 unsigned NumInputs) {
1192 LLVMRustFreeOperandBundleDef(void* Bundle) {
1195 extern "C" LLVMValueRef
1196 LLVMRustBuildCall(LLVMBuilderRef B,
1202 return LLVMBuildCall(B, Fn, Args, NumArgs, Name);
1205 extern "C" LLVMValueRef
1206 LLVMRustBuildInvoke(LLVMBuilderRef B,
1210 LLVMBasicBlockRef Then,
1211 LLVMBasicBlockRef Catch,
1214 return LLVMBuildInvoke(B, Fn, Args, NumArgs, Then, Catch, Name);
1218 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B, LLVMBasicBlockRef BB) {
1219 auto point = unwrap(BB)->getFirstInsertionPt();
1220 unwrap(B)->SetInsertPoint(unwrap(BB), point);
1223 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V, const char *Name) {
1224 Triple TargetTriple(unwrap(M)->getTargetTriple());
1225 GlobalObject *GV = unwrap<GlobalObject>(V);
1226 if (!TargetTriple.isOSBinFormatMachO()) {
1227 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1231 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1232 GlobalObject *GV = unwrap<GlobalObject>(V);
1233 GV->setComdat(nullptr);
1236 enum class LLVMRustLinkage {
1237 ExternalLinkage = 0,
1238 AvailableExternallyLinkage = 1,
1239 LinkOnceAnyLinkage = 2,
1240 LinkOnceODRLinkage = 3,
1243 AppendingLinkage = 6,
1244 InternalLinkage = 7,
1246 ExternalWeakLinkage = 9,
1250 static LLVMRustLinkage to_rust(LLVMLinkage linkage) {
1252 case LLVMExternalLinkage:
1253 return LLVMRustLinkage::ExternalLinkage;
1254 case LLVMAvailableExternallyLinkage:
1255 return LLVMRustLinkage::AvailableExternallyLinkage;
1256 case LLVMLinkOnceAnyLinkage:
1257 return LLVMRustLinkage::LinkOnceAnyLinkage;
1258 case LLVMLinkOnceODRLinkage:
1259 return LLVMRustLinkage::LinkOnceODRLinkage;
1260 case LLVMWeakAnyLinkage:
1261 return LLVMRustLinkage::WeakAnyLinkage;
1262 case LLVMWeakODRLinkage:
1263 return LLVMRustLinkage::WeakODRLinkage;
1264 case LLVMAppendingLinkage:
1265 return LLVMRustLinkage::AppendingLinkage;
1266 case LLVMInternalLinkage:
1267 return LLVMRustLinkage::InternalLinkage;
1268 case LLVMPrivateLinkage:
1269 return LLVMRustLinkage::PrivateLinkage;
1270 case LLVMExternalWeakLinkage:
1271 return LLVMRustLinkage::ExternalWeakLinkage;
1272 case LLVMCommonLinkage:
1273 return LLVMRustLinkage::CommonLinkage;
1275 llvm_unreachable("Invalid LLVMRustLinkage value!");
1279 static LLVMLinkage from_rust(LLVMRustLinkage linkage) {
1281 case LLVMRustLinkage::ExternalLinkage:
1282 return LLVMExternalLinkage;
1283 case LLVMRustLinkage::AvailableExternallyLinkage:
1284 return LLVMAvailableExternallyLinkage;
1285 case LLVMRustLinkage::LinkOnceAnyLinkage:
1286 return LLVMLinkOnceAnyLinkage;
1287 case LLVMRustLinkage::LinkOnceODRLinkage:
1288 return LLVMLinkOnceODRLinkage;
1289 case LLVMRustLinkage::WeakAnyLinkage:
1290 return LLVMWeakAnyLinkage;
1291 case LLVMRustLinkage::WeakODRLinkage:
1292 return LLVMWeakODRLinkage;
1293 case LLVMRustLinkage::AppendingLinkage:
1294 return LLVMAppendingLinkage;
1295 case LLVMRustLinkage::InternalLinkage:
1296 return LLVMInternalLinkage;
1297 case LLVMRustLinkage::PrivateLinkage:
1298 return LLVMPrivateLinkage;
1299 case LLVMRustLinkage::ExternalWeakLinkage:
1300 return LLVMExternalWeakLinkage;
1301 case LLVMRustLinkage::CommonLinkage:
1302 return LLVMCommonLinkage;
1304 llvm_unreachable("Invalid LLVMRustLinkage value!");
1308 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1309 return to_rust(LLVMGetLinkage(V));
1312 extern "C" void LLVMRustSetLinkage(LLVMValueRef V, LLVMRustLinkage RustLinkage) {
1313 LLVMSetLinkage(V, from_rust(RustLinkage));