brintos

brintos / llvm-project-archived public Read only

0
0
Text · 159.6 KiB · 26c4f4e Raw
4663 lines · cpp
1//===-- Core.cpp ----------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the common infrastructure (including the C bindings)10// for libLLVMCore.a, which implements the LLVM intermediate representation.11//12//===----------------------------------------------------------------------===//13 14#include "llvm-c/Core.h"15#include "llvm-c/Types.h"16#include "llvm/IR/Attributes.h"17#include "llvm/IR/BasicBlock.h"18#include "llvm/IR/ConstantRange.h"19#include "llvm/IR/Constants.h"20#include "llvm/IR/DebugInfoMetadata.h"21#include "llvm/IR/DebugProgramInstruction.h"22#include "llvm/IR/DerivedTypes.h"23#include "llvm/IR/DiagnosticInfo.h"24#include "llvm/IR/DiagnosticPrinter.h"25#include "llvm/IR/GlobalAlias.h"26#include "llvm/IR/GlobalVariable.h"27#include "llvm/IR/IRBuilder.h"28#include "llvm/IR/InlineAsm.h"29#include "llvm/IR/Instructions.h"30#include "llvm/IR/IntrinsicInst.h"31#include "llvm/IR/LLVMContext.h"32#include "llvm/IR/LegacyPassManager.h"33#include "llvm/IR/Module.h"34#include "llvm/InitializePasses.h"35#include "llvm/PassRegistry.h"36#include "llvm/Support/Debug.h"37#include "llvm/Support/ErrorHandling.h"38#include "llvm/Support/FileSystem.h"39#include "llvm/Support/ManagedStatic.h"40#include "llvm/Support/MathExtras.h"41#include "llvm/Support/MemoryBuffer.h"42#include "llvm/Support/Threading.h"43#include "llvm/Support/raw_ostream.h"44#include <cassert>45#include <cstdlib>46#include <cstring>47#include <system_error>48 49using namespace llvm;50 51DEFINE_SIMPLE_CONVERSION_FUNCTIONS(OperandBundleDef, LLVMOperandBundleRef)52 53inline BasicBlock **unwrap(LLVMBasicBlockRef *BBs) {54  return reinterpret_cast<BasicBlock **>(BBs);55}56 57#define DEBUG_TYPE "ir"58 59void llvm::initializeCore(PassRegistry &Registry) {60  initializeDominatorTreeWrapperPassPass(Registry);61  initializePrintModulePassWrapperPass(Registry);62  initializePrintFunctionPassWrapperPass(Registry);63  initializeSafepointIRVerifierPass(Registry);64  initializeVerifierLegacyPassPass(Registry);65}66 67void LLVMShutdown() {68  llvm_shutdown();69}70 71/*===-- Version query -----------------------------------------------------===*/72 73void LLVMGetVersion(unsigned *Major, unsigned *Minor, unsigned *Patch) {74    if (Major)75        *Major = LLVM_VERSION_MAJOR;76    if (Minor)77        *Minor = LLVM_VERSION_MINOR;78    if (Patch)79        *Patch = LLVM_VERSION_PATCH;80}81 82/*===-- Error handling ----------------------------------------------------===*/83 84char *LLVMCreateMessage(const char *Message) {85  return strdup(Message);86}87 88void LLVMDisposeMessage(char *Message) {89  free(Message);90}91 92 93/*===-- Operations on contexts --------------------------------------------===*/94 95static LLVMContext &getGlobalContext() {96  static LLVMContext GlobalContext;97  return GlobalContext;98}99 100LLVMContextRef LLVMContextCreate() {101  return wrap(new LLVMContext());102}103 104LLVMContextRef LLVMGetGlobalContext() { return wrap(&getGlobalContext()); }105 106void LLVMContextSetDiagnosticHandler(LLVMContextRef C,107                                     LLVMDiagnosticHandler Handler,108                                     void *DiagnosticContext) {109  unwrap(C)->setDiagnosticHandlerCallBack(110      LLVM_EXTENSION reinterpret_cast<DiagnosticHandler::DiagnosticHandlerTy>(111          Handler),112      DiagnosticContext);113}114 115LLVMDiagnosticHandler LLVMContextGetDiagnosticHandler(LLVMContextRef C) {116  return LLVM_EXTENSION reinterpret_cast<LLVMDiagnosticHandler>(117      unwrap(C)->getDiagnosticHandlerCallBack());118}119 120void *LLVMContextGetDiagnosticContext(LLVMContextRef C) {121  return unwrap(C)->getDiagnosticContext();122}123 124void LLVMContextSetYieldCallback(LLVMContextRef C, LLVMYieldCallback Callback,125                                 void *OpaqueHandle) {126  auto YieldCallback =127    LLVM_EXTENSION reinterpret_cast<LLVMContext::YieldCallbackTy>(Callback);128  unwrap(C)->setYieldCallback(YieldCallback, OpaqueHandle);129}130 131LLVMBool LLVMContextShouldDiscardValueNames(LLVMContextRef C) {132  return unwrap(C)->shouldDiscardValueNames();133}134 135void LLVMContextSetDiscardValueNames(LLVMContextRef C, LLVMBool Discard) {136  unwrap(C)->setDiscardValueNames(Discard);137}138 139void LLVMContextDispose(LLVMContextRef C) {140  delete unwrap(C);141}142 143unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char *Name,144                                  unsigned SLen) {145  return unwrap(C)->getMDKindID(StringRef(Name, SLen));146}147 148unsigned LLVMGetMDKindID(const char *Name, unsigned SLen) {149  return LLVMGetMDKindIDInContext(LLVMGetGlobalContext(), Name, SLen);150}151 152unsigned LLVMGetSyncScopeID(LLVMContextRef C, const char *Name, size_t SLen) {153  return unwrap(C)->getOrInsertSyncScopeID(StringRef(Name, SLen));154}155 156unsigned LLVMGetEnumAttributeKindForName(const char *Name, size_t SLen) {157  return Attribute::getAttrKindFromName(StringRef(Name, SLen));158}159 160unsigned LLVMGetLastEnumAttributeKind(void) {161  return Attribute::AttrKind::EndAttrKinds;162}163 164LLVMAttributeRef LLVMCreateEnumAttribute(LLVMContextRef C, unsigned KindID,165                                         uint64_t Val) {166  auto &Ctx = *unwrap(C);167  auto AttrKind = (Attribute::AttrKind)KindID;168  return wrap(Attribute::get(Ctx, AttrKind, Val));169}170 171unsigned LLVMGetEnumAttributeKind(LLVMAttributeRef A) {172  return unwrap(A).getKindAsEnum();173}174 175uint64_t LLVMGetEnumAttributeValue(LLVMAttributeRef A) {176  auto Attr = unwrap(A);177  if (Attr.isEnumAttribute())178    return 0;179  return Attr.getValueAsInt();180}181 182LLVMAttributeRef LLVMCreateTypeAttribute(LLVMContextRef C, unsigned KindID,183                                         LLVMTypeRef type_ref) {184  auto &Ctx = *unwrap(C);185  auto AttrKind = (Attribute::AttrKind)KindID;186  return wrap(Attribute::get(Ctx, AttrKind, unwrap(type_ref)));187}188 189LLVMTypeRef LLVMGetTypeAttributeValue(LLVMAttributeRef A) {190  auto Attr = unwrap(A);191  return wrap(Attr.getValueAsType());192}193 194LLVMAttributeRef LLVMCreateConstantRangeAttribute(LLVMContextRef C,195                                                  unsigned KindID,196                                                  unsigned NumBits,197                                                  const uint64_t LowerWords[],198                                                  const uint64_t UpperWords[]) {199  auto &Ctx = *unwrap(C);200  auto AttrKind = (Attribute::AttrKind)KindID;201  unsigned NumWords = divideCeil(NumBits, 64);202  return wrap(Attribute::get(203      Ctx, AttrKind,204      ConstantRange(APInt(NumBits, ArrayRef(LowerWords, NumWords)),205                    APInt(NumBits, ArrayRef(UpperWords, NumWords)))));206}207 208LLVMAttributeRef LLVMCreateStringAttribute(LLVMContextRef C,209                                           const char *K, unsigned KLength,210                                           const char *V, unsigned VLength) {211  return wrap(Attribute::get(*unwrap(C), StringRef(K, KLength),212                             StringRef(V, VLength)));213}214 215const char *LLVMGetStringAttributeKind(LLVMAttributeRef A,216                                       unsigned *Length) {217  auto S = unwrap(A).getKindAsString();218  *Length = S.size();219  return S.data();220}221 222const char *LLVMGetStringAttributeValue(LLVMAttributeRef A,223                                        unsigned *Length) {224  auto S = unwrap(A).getValueAsString();225  *Length = S.size();226  return S.data();227}228 229LLVMBool LLVMIsEnumAttribute(LLVMAttributeRef A) {230  auto Attr = unwrap(A);231  return Attr.isEnumAttribute() || Attr.isIntAttribute();232}233 234LLVMBool LLVMIsStringAttribute(LLVMAttributeRef A) {235  return unwrap(A).isStringAttribute();236}237 238LLVMBool LLVMIsTypeAttribute(LLVMAttributeRef A) {239  return unwrap(A).isTypeAttribute();240}241 242char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI) {243  std::string MsgStorage;244  raw_string_ostream Stream(MsgStorage);245  DiagnosticPrinterRawOStream DP(Stream);246 247  unwrap(DI)->print(DP);248  Stream.flush();249 250  return LLVMCreateMessage(MsgStorage.c_str());251}252 253LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI) {254    LLVMDiagnosticSeverity severity;255 256    switch(unwrap(DI)->getSeverity()) {257    default:258      severity = LLVMDSError;259      break;260    case DS_Warning:261      severity = LLVMDSWarning;262      break;263    case DS_Remark:264      severity = LLVMDSRemark;265      break;266    case DS_Note:267      severity = LLVMDSNote;268      break;269    }270 271    return severity;272}273 274/*===-- Operations on modules ---------------------------------------------===*/275 276LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) {277  return wrap(new Module(ModuleID, getGlobalContext()));278}279 280LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID,281                                                LLVMContextRef C) {282  return wrap(new Module(ModuleID, *unwrap(C)));283}284 285void LLVMDisposeModule(LLVMModuleRef M) {286  delete unwrap(M);287}288 289const char *LLVMGetModuleIdentifier(LLVMModuleRef M, size_t *Len) {290  auto &Str = unwrap(M)->getModuleIdentifier();291  *Len = Str.length();292  return Str.c_str();293}294 295void LLVMSetModuleIdentifier(LLVMModuleRef M, const char *Ident, size_t Len) {296  unwrap(M)->setModuleIdentifier(StringRef(Ident, Len));297}298 299const char *LLVMGetSourceFileName(LLVMModuleRef M, size_t *Len) {300  auto &Str = unwrap(M)->getSourceFileName();301  *Len = Str.length();302  return Str.c_str();303}304 305void LLVMSetSourceFileName(LLVMModuleRef M, const char *Name, size_t Len) {306  unwrap(M)->setSourceFileName(StringRef(Name, Len));307}308 309/*--.. Data layout .........................................................--*/310const char *LLVMGetDataLayoutStr(LLVMModuleRef M) {311  return unwrap(M)->getDataLayoutStr().c_str();312}313 314const char *LLVMGetDataLayout(LLVMModuleRef M) {315  return LLVMGetDataLayoutStr(M);316}317 318void LLVMSetDataLayout(LLVMModuleRef M, const char *DataLayoutStr) {319  unwrap(M)->setDataLayout(DataLayoutStr);320}321 322/*--.. Target triple .......................................................--*/323const char * LLVMGetTarget(LLVMModuleRef M) {324  return unwrap(M)->getTargetTriple().str().c_str();325}326 327void LLVMSetTarget(LLVMModuleRef M, const char *TripleStr) {328  unwrap(M)->setTargetTriple(Triple(TripleStr));329}330 331/*--.. Module flags ........................................................--*/332struct LLVMOpaqueModuleFlagEntry {333  LLVMModuleFlagBehavior Behavior;334  const char *Key;335  size_t KeyLen;336  LLVMMetadataRef Metadata;337};338 339static Module::ModFlagBehavior340map_to_llvmModFlagBehavior(LLVMModuleFlagBehavior Behavior) {341  switch (Behavior) {342  case LLVMModuleFlagBehaviorError:343    return Module::ModFlagBehavior::Error;344  case LLVMModuleFlagBehaviorWarning:345    return Module::ModFlagBehavior::Warning;346  case LLVMModuleFlagBehaviorRequire:347    return Module::ModFlagBehavior::Require;348  case LLVMModuleFlagBehaviorOverride:349    return Module::ModFlagBehavior::Override;350  case LLVMModuleFlagBehaviorAppend:351    return Module::ModFlagBehavior::Append;352  case LLVMModuleFlagBehaviorAppendUnique:353    return Module::ModFlagBehavior::AppendUnique;354  }355  llvm_unreachable("Unknown LLVMModuleFlagBehavior");356}357 358static LLVMModuleFlagBehavior359map_from_llvmModFlagBehavior(Module::ModFlagBehavior Behavior) {360  switch (Behavior) {361  case Module::ModFlagBehavior::Error:362    return LLVMModuleFlagBehaviorError;363  case Module::ModFlagBehavior::Warning:364    return LLVMModuleFlagBehaviorWarning;365  case Module::ModFlagBehavior::Require:366    return LLVMModuleFlagBehaviorRequire;367  case Module::ModFlagBehavior::Override:368    return LLVMModuleFlagBehaviorOverride;369  case Module::ModFlagBehavior::Append:370    return LLVMModuleFlagBehaviorAppend;371  case Module::ModFlagBehavior::AppendUnique:372    return LLVMModuleFlagBehaviorAppendUnique;373  default:374    llvm_unreachable("Unhandled Flag Behavior");375  }376}377 378LLVMModuleFlagEntry *LLVMCopyModuleFlagsMetadata(LLVMModuleRef M, size_t *Len) {379  SmallVector<Module::ModuleFlagEntry, 8> MFEs;380  unwrap(M)->getModuleFlagsMetadata(MFEs);381 382  LLVMOpaqueModuleFlagEntry *Result = static_cast<LLVMOpaqueModuleFlagEntry *>(383      safe_malloc(MFEs.size() * sizeof(LLVMOpaqueModuleFlagEntry)));384  for (unsigned i = 0; i < MFEs.size(); ++i) {385    const auto &ModuleFlag = MFEs[i];386    Result[i].Behavior = map_from_llvmModFlagBehavior(ModuleFlag.Behavior);387    Result[i].Key = ModuleFlag.Key->getString().data();388    Result[i].KeyLen = ModuleFlag.Key->getString().size();389    Result[i].Metadata = wrap(ModuleFlag.Val);390  }391  *Len = MFEs.size();392  return Result;393}394 395void LLVMDisposeModuleFlagsMetadata(LLVMModuleFlagEntry *Entries) {396  free(Entries);397}398 399LLVMModuleFlagBehavior400LLVMModuleFlagEntriesGetFlagBehavior(LLVMModuleFlagEntry *Entries,401                                     unsigned Index) {402  LLVMOpaqueModuleFlagEntry MFE =403      static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);404  return MFE.Behavior;405}406 407const char *LLVMModuleFlagEntriesGetKey(LLVMModuleFlagEntry *Entries,408                                        unsigned Index, size_t *Len) {409  LLVMOpaqueModuleFlagEntry MFE =410      static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);411  *Len = MFE.KeyLen;412  return MFE.Key;413}414 415LLVMMetadataRef LLVMModuleFlagEntriesGetMetadata(LLVMModuleFlagEntry *Entries,416                                                 unsigned Index) {417  LLVMOpaqueModuleFlagEntry MFE =418      static_cast<LLVMOpaqueModuleFlagEntry>(Entries[Index]);419  return MFE.Metadata;420}421 422LLVMMetadataRef LLVMGetModuleFlag(LLVMModuleRef M,423                                  const char *Key, size_t KeyLen) {424  return wrap(unwrap(M)->getModuleFlag({Key, KeyLen}));425}426 427void LLVMAddModuleFlag(LLVMModuleRef M, LLVMModuleFlagBehavior Behavior,428                       const char *Key, size_t KeyLen,429                       LLVMMetadataRef Val) {430  unwrap(M)->addModuleFlag(map_to_llvmModFlagBehavior(Behavior),431                           {Key, KeyLen}, unwrap(Val));432}433 434LLVMBool LLVMIsNewDbgInfoFormat(LLVMModuleRef M) { return true; }435 436void LLVMSetIsNewDbgInfoFormat(LLVMModuleRef M, LLVMBool UseNewFormat) {437  if (!UseNewFormat)438    llvm_unreachable("LLVM no longer supports intrinsic based debug-info");439  (void)M;440}441 442/*--.. Printing modules ....................................................--*/443 444void LLVMDumpModule(LLVMModuleRef M) {445  unwrap(M)->print(errs(), nullptr,446                   /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);447}448 449LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename,450                               char **ErrorMessage) {451  std::error_code EC;452  raw_fd_ostream dest(Filename, EC, sys::fs::OF_TextWithCRLF);453  if (EC) {454    *ErrorMessage = strdup(EC.message().c_str());455    return true;456  }457 458  unwrap(M)->print(dest, nullptr);459 460  dest.close();461 462  if (dest.has_error()) {463    std::string E = "Error printing to file: " + dest.error().message();464    *ErrorMessage = strdup(E.c_str());465    return true;466  }467 468  return false;469}470 471char *LLVMPrintModuleToString(LLVMModuleRef M) {472  std::string buf;473  raw_string_ostream os(buf);474 475  unwrap(M)->print(os, nullptr);476  os.flush();477 478  return strdup(buf.c_str());479}480 481/*--.. Operations on inline assembler ......................................--*/482void LLVMSetModuleInlineAsm2(LLVMModuleRef M, const char *Asm, size_t Len) {483  unwrap(M)->setModuleInlineAsm(StringRef(Asm, Len));484}485 486void LLVMSetModuleInlineAsm(LLVMModuleRef M, const char *Asm) {487  unwrap(M)->setModuleInlineAsm(StringRef(Asm));488}489 490void LLVMAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm, size_t Len) {491  unwrap(M)->appendModuleInlineAsm(StringRef(Asm, Len));492}493 494const char *LLVMGetModuleInlineAsm(LLVMModuleRef M, size_t *Len) {495  auto &Str = unwrap(M)->getModuleInlineAsm();496  *Len = Str.length();497  return Str.c_str();498}499 500LLVMValueRef LLVMGetInlineAsm(LLVMTypeRef Ty, const char *AsmString,501                              size_t AsmStringSize, const char *Constraints,502                              size_t ConstraintsSize, LLVMBool HasSideEffects,503                              LLVMBool IsAlignStack,504                              LLVMInlineAsmDialect Dialect, LLVMBool CanThrow) {505  InlineAsm::AsmDialect AD;506  switch (Dialect) {507  case LLVMInlineAsmDialectATT:508    AD = InlineAsm::AD_ATT;509    break;510  case LLVMInlineAsmDialectIntel:511    AD = InlineAsm::AD_Intel;512    break;513  }514  return wrap(InlineAsm::get(unwrap<FunctionType>(Ty),515                             StringRef(AsmString, AsmStringSize),516                             StringRef(Constraints, ConstraintsSize),517                             HasSideEffects, IsAlignStack, AD, CanThrow));518}519 520const char *LLVMGetInlineAsmAsmString(LLVMValueRef InlineAsmVal, size_t *Len) {521 522  Value *Val = unwrap<Value>(InlineAsmVal);523  StringRef AsmString = cast<InlineAsm>(Val)->getAsmString();524 525  *Len = AsmString.size();526  return AsmString.data();527}528 529const char *LLVMGetInlineAsmConstraintString(LLVMValueRef InlineAsmVal,530                                             size_t *Len) {531  Value *Val = unwrap<Value>(InlineAsmVal);532  StringRef ConstraintString = cast<InlineAsm>(Val)->getConstraintString();533 534  *Len = ConstraintString.size();535  return ConstraintString.data();536}537 538LLVMInlineAsmDialect LLVMGetInlineAsmDialect(LLVMValueRef InlineAsmVal) {539 540  Value *Val = unwrap<Value>(InlineAsmVal);541  InlineAsm::AsmDialect Dialect = cast<InlineAsm>(Val)->getDialect();542 543  switch (Dialect) {544  case InlineAsm::AD_ATT:545    return LLVMInlineAsmDialectATT;546  case InlineAsm::AD_Intel:547    return LLVMInlineAsmDialectIntel;548  }549 550  llvm_unreachable("Unrecognized inline assembly dialect");551  return LLVMInlineAsmDialectATT;552}553 554LLVMTypeRef LLVMGetInlineAsmFunctionType(LLVMValueRef InlineAsmVal) {555  Value *Val = unwrap<Value>(InlineAsmVal);556  return (LLVMTypeRef)cast<InlineAsm>(Val)->getFunctionType();557}558 559LLVMBool LLVMGetInlineAsmHasSideEffects(LLVMValueRef InlineAsmVal) {560  Value *Val = unwrap<Value>(InlineAsmVal);561  return cast<InlineAsm>(Val)->hasSideEffects();562}563 564LLVMBool LLVMGetInlineAsmNeedsAlignedStack(LLVMValueRef InlineAsmVal) {565  Value *Val = unwrap<Value>(InlineAsmVal);566  return cast<InlineAsm>(Val)->isAlignStack();567}568 569LLVMBool LLVMGetInlineAsmCanUnwind(LLVMValueRef InlineAsmVal) {570  Value *Val = unwrap<Value>(InlineAsmVal);571  return cast<InlineAsm>(Val)->canThrow();572}573 574/*--.. Operations on module contexts ......................................--*/575LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M) {576  return wrap(&unwrap(M)->getContext());577}578 579 580/*===-- Operations on types -----------------------------------------------===*/581 582/*--.. Operations on all types (mostly) ....................................--*/583 584LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty) {585  switch (unwrap(Ty)->getTypeID()) {586  case Type::VoidTyID:587    return LLVMVoidTypeKind;588  case Type::HalfTyID:589    return LLVMHalfTypeKind;590  case Type::BFloatTyID:591    return LLVMBFloatTypeKind;592  case Type::FloatTyID:593    return LLVMFloatTypeKind;594  case Type::DoubleTyID:595    return LLVMDoubleTypeKind;596  case Type::X86_FP80TyID:597    return LLVMX86_FP80TypeKind;598  case Type::FP128TyID:599    return LLVMFP128TypeKind;600  case Type::PPC_FP128TyID:601    return LLVMPPC_FP128TypeKind;602  case Type::LabelTyID:603    return LLVMLabelTypeKind;604  case Type::MetadataTyID:605    return LLVMMetadataTypeKind;606  case Type::IntegerTyID:607    return LLVMIntegerTypeKind;608  case Type::FunctionTyID:609    return LLVMFunctionTypeKind;610  case Type::StructTyID:611    return LLVMStructTypeKind;612  case Type::ArrayTyID:613    return LLVMArrayTypeKind;614  case Type::PointerTyID:615    return LLVMPointerTypeKind;616  case Type::FixedVectorTyID:617    return LLVMVectorTypeKind;618  case Type::X86_AMXTyID:619    return LLVMX86_AMXTypeKind;620  case Type::TokenTyID:621    return LLVMTokenTypeKind;622  case Type::ScalableVectorTyID:623    return LLVMScalableVectorTypeKind;624  case Type::TargetExtTyID:625    return LLVMTargetExtTypeKind;626  case Type::TypedPointerTyID:627    llvm_unreachable("Typed pointers are unsupported via the C API");628  }629  llvm_unreachable("Unhandled TypeID.");630}631 632LLVMBool LLVMTypeIsSized(LLVMTypeRef Ty)633{634    return unwrap(Ty)->isSized();635}636 637LLVMContextRef LLVMGetTypeContext(LLVMTypeRef Ty) {638  return wrap(&unwrap(Ty)->getContext());639}640 641void LLVMDumpType(LLVMTypeRef Ty) {642  return unwrap(Ty)->print(errs(), /*IsForDebug=*/true);643}644 645char *LLVMPrintTypeToString(LLVMTypeRef Ty) {646  std::string buf;647  raw_string_ostream os(buf);648 649  if (unwrap(Ty))650    unwrap(Ty)->print(os);651  else652    os << "Printing <null> Type";653 654  os.flush();655 656  return strdup(buf.c_str());657}658 659/*--.. Operations on integer types .........................................--*/660 661LLVMTypeRef LLVMInt1TypeInContext(LLVMContextRef C)  {662  return (LLVMTypeRef) Type::getInt1Ty(*unwrap(C));663}664LLVMTypeRef LLVMInt8TypeInContext(LLVMContextRef C)  {665  return (LLVMTypeRef) Type::getInt8Ty(*unwrap(C));666}667LLVMTypeRef LLVMInt16TypeInContext(LLVMContextRef C) {668  return (LLVMTypeRef) Type::getInt16Ty(*unwrap(C));669}670LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C) {671  return (LLVMTypeRef) Type::getInt32Ty(*unwrap(C));672}673LLVMTypeRef LLVMInt64TypeInContext(LLVMContextRef C) {674  return (LLVMTypeRef) Type::getInt64Ty(*unwrap(C));675}676LLVMTypeRef LLVMInt128TypeInContext(LLVMContextRef C) {677  return (LLVMTypeRef) Type::getInt128Ty(*unwrap(C));678}679LLVMTypeRef LLVMIntTypeInContext(LLVMContextRef C, unsigned NumBits) {680  return wrap(IntegerType::get(*unwrap(C), NumBits));681}682 683LLVMTypeRef LLVMInt1Type(void)  {684  return LLVMInt1TypeInContext(LLVMGetGlobalContext());685}686LLVMTypeRef LLVMInt8Type(void)  {687  return LLVMInt8TypeInContext(LLVMGetGlobalContext());688}689LLVMTypeRef LLVMInt16Type(void) {690  return LLVMInt16TypeInContext(LLVMGetGlobalContext());691}692LLVMTypeRef LLVMInt32Type(void) {693  return LLVMInt32TypeInContext(LLVMGetGlobalContext());694}695LLVMTypeRef LLVMInt64Type(void) {696  return LLVMInt64TypeInContext(LLVMGetGlobalContext());697}698LLVMTypeRef LLVMInt128Type(void) {699  return LLVMInt128TypeInContext(LLVMGetGlobalContext());700}701LLVMTypeRef LLVMIntType(unsigned NumBits) {702  return LLVMIntTypeInContext(LLVMGetGlobalContext(), NumBits);703}704 705unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy) {706  return unwrap<IntegerType>(IntegerTy)->getBitWidth();707}708 709/*--.. Operations on real types ............................................--*/710 711LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C) {712  return (LLVMTypeRef) Type::getHalfTy(*unwrap(C));713}714LLVMTypeRef LLVMBFloatTypeInContext(LLVMContextRef C) {715  return (LLVMTypeRef) Type::getBFloatTy(*unwrap(C));716}717LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C) {718  return (LLVMTypeRef) Type::getFloatTy(*unwrap(C));719}720LLVMTypeRef LLVMDoubleTypeInContext(LLVMContextRef C) {721  return (LLVMTypeRef) Type::getDoubleTy(*unwrap(C));722}723LLVMTypeRef LLVMX86FP80TypeInContext(LLVMContextRef C) {724  return (LLVMTypeRef) Type::getX86_FP80Ty(*unwrap(C));725}726LLVMTypeRef LLVMFP128TypeInContext(LLVMContextRef C) {727  return (LLVMTypeRef) Type::getFP128Ty(*unwrap(C));728}729LLVMTypeRef LLVMPPCFP128TypeInContext(LLVMContextRef C) {730  return (LLVMTypeRef) Type::getPPC_FP128Ty(*unwrap(C));731}732LLVMTypeRef LLVMX86AMXTypeInContext(LLVMContextRef C) {733  return (LLVMTypeRef) Type::getX86_AMXTy(*unwrap(C));734}735 736LLVMTypeRef LLVMHalfType(void) {737  return LLVMHalfTypeInContext(LLVMGetGlobalContext());738}739LLVMTypeRef LLVMBFloatType(void) {740  return LLVMBFloatTypeInContext(LLVMGetGlobalContext());741}742LLVMTypeRef LLVMFloatType(void) {743  return LLVMFloatTypeInContext(LLVMGetGlobalContext());744}745LLVMTypeRef LLVMDoubleType(void) {746  return LLVMDoubleTypeInContext(LLVMGetGlobalContext());747}748LLVMTypeRef LLVMX86FP80Type(void) {749  return LLVMX86FP80TypeInContext(LLVMGetGlobalContext());750}751LLVMTypeRef LLVMFP128Type(void) {752  return LLVMFP128TypeInContext(LLVMGetGlobalContext());753}754LLVMTypeRef LLVMPPCFP128Type(void) {755  return LLVMPPCFP128TypeInContext(LLVMGetGlobalContext());756}757LLVMTypeRef LLVMX86AMXType(void) {758  return LLVMX86AMXTypeInContext(LLVMGetGlobalContext());759}760 761/*--.. Operations on function types ........................................--*/762 763LLVMTypeRef LLVMFunctionType(LLVMTypeRef ReturnType,764                             LLVMTypeRef *ParamTypes, unsigned ParamCount,765                             LLVMBool IsVarArg) {766  ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);767  return wrap(FunctionType::get(unwrap(ReturnType), Tys, IsVarArg != 0));768}769 770LLVMBool LLVMIsFunctionVarArg(LLVMTypeRef FunctionTy) {771  return unwrap<FunctionType>(FunctionTy)->isVarArg();772}773 774LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy) {775  return wrap(unwrap<FunctionType>(FunctionTy)->getReturnType());776}777 778unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy) {779  return unwrap<FunctionType>(FunctionTy)->getNumParams();780}781 782void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest) {783  FunctionType *Ty = unwrap<FunctionType>(FunctionTy);784  for (Type *T : Ty->params())785    *Dest++ = wrap(T);786}787 788/*--.. Operations on struct types ..........................................--*/789 790LLVMTypeRef LLVMStructTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes,791                           unsigned ElementCount, LLVMBool Packed) {792  ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount);793  return wrap(StructType::get(*unwrap(C), Tys, Packed != 0));794}795 796LLVMTypeRef LLVMStructType(LLVMTypeRef *ElementTypes,797                           unsigned ElementCount, LLVMBool Packed) {798  return LLVMStructTypeInContext(LLVMGetGlobalContext(), ElementTypes,799                                 ElementCount, Packed);800}801 802LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name)803{804  return wrap(StructType::create(*unwrap(C), Name));805}806 807const char *LLVMGetStructName(LLVMTypeRef Ty)808{809  StructType *Type = unwrap<StructType>(Ty);810  if (!Type->hasName())811    return nullptr;812  return Type->getName().data();813}814 815void LLVMStructSetBody(LLVMTypeRef StructTy, LLVMTypeRef *ElementTypes,816                       unsigned ElementCount, LLVMBool Packed) {817  ArrayRef<Type*> Tys(unwrap(ElementTypes), ElementCount);818  unwrap<StructType>(StructTy)->setBody(Tys, Packed != 0);819}820 821unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy) {822  return unwrap<StructType>(StructTy)->getNumElements();823}824 825void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest) {826  StructType *Ty = unwrap<StructType>(StructTy);827  for (Type *T : Ty->elements())828    *Dest++ = wrap(T);829}830 831LLVMTypeRef LLVMStructGetTypeAtIndex(LLVMTypeRef StructTy, unsigned i) {832  StructType *Ty = unwrap<StructType>(StructTy);833  return wrap(Ty->getTypeAtIndex(i));834}835 836LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy) {837  return unwrap<StructType>(StructTy)->isPacked();838}839 840LLVMBool LLVMIsOpaqueStruct(LLVMTypeRef StructTy) {841  return unwrap<StructType>(StructTy)->isOpaque();842}843 844LLVMBool LLVMIsLiteralStruct(LLVMTypeRef StructTy) {845  return unwrap<StructType>(StructTy)->isLiteral();846}847 848LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name) {849  return wrap(StructType::getTypeByName(unwrap(M)->getContext(), Name));850}851 852LLVMTypeRef LLVMGetTypeByName2(LLVMContextRef C, const char *Name) {853  return wrap(StructType::getTypeByName(*unwrap(C), Name));854}855 856/*--.. Operations on array, pointer, and vector types (sequence types) .....--*/857 858void LLVMGetSubtypes(LLVMTypeRef Tp, LLVMTypeRef *Arr) {859    int i = 0;860    for (auto *T : unwrap(Tp)->subtypes()) {861        Arr[i] = wrap(T);862        i++;863    }864}865 866LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount) {867  return wrap(ArrayType::get(unwrap(ElementType), ElementCount));868}869 870LLVMTypeRef LLVMArrayType2(LLVMTypeRef ElementType, uint64_t ElementCount) {871  return wrap(ArrayType::get(unwrap(ElementType), ElementCount));872}873 874LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace) {875  return wrap(876      PointerType::get(unwrap(ElementType)->getContext(), AddressSpace));877}878 879LLVMBool LLVMPointerTypeIsOpaque(LLVMTypeRef Ty) {880  return true;881}882 883LLVMTypeRef LLVMVectorType(LLVMTypeRef ElementType, unsigned ElementCount) {884  return wrap(FixedVectorType::get(unwrap(ElementType), ElementCount));885}886 887LLVMTypeRef LLVMScalableVectorType(LLVMTypeRef ElementType,888                                   unsigned ElementCount) {889  return wrap(ScalableVectorType::get(unwrap(ElementType), ElementCount));890}891 892LLVMTypeRef LLVMGetElementType(LLVMTypeRef WrappedTy) {893  auto *Ty = unwrap(WrappedTy);894  if (auto *ATy = dyn_cast<ArrayType>(Ty))895    return wrap(ATy->getElementType());896  return wrap(cast<VectorType>(Ty)->getElementType());897}898 899unsigned LLVMGetNumContainedTypes(LLVMTypeRef Tp) {900    return unwrap(Tp)->getNumContainedTypes();901}902 903unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy) {904  return unwrap<ArrayType>(ArrayTy)->getNumElements();905}906 907uint64_t LLVMGetArrayLength2(LLVMTypeRef ArrayTy) {908  return unwrap<ArrayType>(ArrayTy)->getNumElements();909}910 911unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy) {912  return unwrap<PointerType>(PointerTy)->getAddressSpace();913}914 915unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy) {916  return unwrap<VectorType>(VectorTy)->getElementCount().getKnownMinValue();917}918 919LLVMValueRef LLVMGetConstantPtrAuthPointer(LLVMValueRef PtrAuth) {920  return wrap(unwrap<ConstantPtrAuth>(PtrAuth)->getPointer());921}922 923LLVMValueRef LLVMGetConstantPtrAuthKey(LLVMValueRef PtrAuth) {924  return wrap(unwrap<ConstantPtrAuth>(PtrAuth)->getKey());925}926 927LLVMValueRef LLVMGetConstantPtrAuthDiscriminator(LLVMValueRef PtrAuth) {928  return wrap(unwrap<ConstantPtrAuth>(PtrAuth)->getDiscriminator());929}930 931LLVMValueRef LLVMGetConstantPtrAuthAddrDiscriminator(LLVMValueRef PtrAuth) {932  return wrap(unwrap<ConstantPtrAuth>(PtrAuth)->getAddrDiscriminator());933}934 935/*--.. Operations on other types ...........................................--*/936 937LLVMTypeRef LLVMPointerTypeInContext(LLVMContextRef C, unsigned AddressSpace) {938  return wrap(PointerType::get(*unwrap(C), AddressSpace));939}940 941LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C)  {942  return wrap(Type::getVoidTy(*unwrap(C)));943}944LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C) {945  return wrap(Type::getLabelTy(*unwrap(C)));946}947LLVMTypeRef LLVMTokenTypeInContext(LLVMContextRef C) {948  return wrap(Type::getTokenTy(*unwrap(C)));949}950LLVMTypeRef LLVMMetadataTypeInContext(LLVMContextRef C) {951  return wrap(Type::getMetadataTy(*unwrap(C)));952}953 954LLVMTypeRef LLVMVoidType(void)  {955  return LLVMVoidTypeInContext(LLVMGetGlobalContext());956}957LLVMTypeRef LLVMLabelType(void) {958  return LLVMLabelTypeInContext(LLVMGetGlobalContext());959}960 961LLVMTypeRef LLVMTargetExtTypeInContext(LLVMContextRef C, const char *Name,962                                       LLVMTypeRef *TypeParams,963                                       unsigned TypeParamCount,964                                       unsigned *IntParams,965                                       unsigned IntParamCount) {966  ArrayRef<Type *> TypeParamArray(unwrap(TypeParams), TypeParamCount);967  ArrayRef<unsigned> IntParamArray(IntParams, IntParamCount);968  return wrap(969      TargetExtType::get(*unwrap(C), Name, TypeParamArray, IntParamArray));970}971 972const char *LLVMGetTargetExtTypeName(LLVMTypeRef TargetExtTy) {973  TargetExtType *Type = unwrap<TargetExtType>(TargetExtTy);974  return Type->getName().data();975}976 977unsigned LLVMGetTargetExtTypeNumTypeParams(LLVMTypeRef TargetExtTy) {978  TargetExtType *Type = unwrap<TargetExtType>(TargetExtTy);979  return Type->getNumTypeParameters();980}981 982LLVMTypeRef LLVMGetTargetExtTypeTypeParam(LLVMTypeRef TargetExtTy,983                                          unsigned Idx) {984  TargetExtType *Type = unwrap<TargetExtType>(TargetExtTy);985  return wrap(Type->getTypeParameter(Idx));986}987 988unsigned LLVMGetTargetExtTypeNumIntParams(LLVMTypeRef TargetExtTy) {989  TargetExtType *Type = unwrap<TargetExtType>(TargetExtTy);990  return Type->getNumIntParameters();991}992 993unsigned LLVMGetTargetExtTypeIntParam(LLVMTypeRef TargetExtTy, unsigned Idx) {994  TargetExtType *Type = unwrap<TargetExtType>(TargetExtTy);995  return Type->getIntParameter(Idx);996}997 998/*===-- Operations on values ----------------------------------------------===*/999 1000/*--.. Operations on all values ............................................--*/1001 1002LLVMTypeRef LLVMTypeOf(LLVMValueRef Val) {1003  return wrap(unwrap(Val)->getType());1004}1005 1006LLVMValueKind LLVMGetValueKind(LLVMValueRef Val) {1007    switch(unwrap(Val)->getValueID()) {1008#define LLVM_C_API 11009#define HANDLE_VALUE(Name) \1010  case Value::Name##Val: \1011    return LLVM##Name##ValueKind;1012#include "llvm/IR/Value.def"1013  default:1014    return LLVMInstructionValueKind;1015  }1016}1017 1018const char *LLVMGetValueName2(LLVMValueRef Val, size_t *Length) {1019  auto *V = unwrap(Val);1020  *Length = V->getName().size();1021  return V->getName().data();1022}1023 1024void LLVMSetValueName2(LLVMValueRef Val, const char *Name, size_t NameLen) {1025  unwrap(Val)->setName(StringRef(Name, NameLen));1026}1027 1028const char *LLVMGetValueName(LLVMValueRef Val) {1029  return unwrap(Val)->getName().data();1030}1031 1032void LLVMSetValueName(LLVMValueRef Val, const char *Name) {1033  unwrap(Val)->setName(Name);1034}1035 1036void LLVMDumpValue(LLVMValueRef Val) {1037  unwrap(Val)->print(errs(), /*IsForDebug=*/true);1038}1039 1040char* LLVMPrintValueToString(LLVMValueRef Val) {1041  std::string buf;1042  raw_string_ostream os(buf);1043 1044  if (unwrap(Val))1045    unwrap(Val)->print(os);1046  else1047    os << "Printing <null> Value";1048 1049  os.flush();1050 1051  return strdup(buf.c_str());1052}1053 1054LLVMContextRef LLVMGetValueContext(LLVMValueRef Val) {1055  return wrap(&unwrap(Val)->getContext());1056}1057 1058char *LLVMPrintDbgRecordToString(LLVMDbgRecordRef Record) {1059  std::string buf;1060  raw_string_ostream os(buf);1061 1062  if (unwrap(Record))1063    unwrap(Record)->print(os);1064  else1065    os << "Printing <null> DbgRecord";1066 1067  os.flush();1068 1069  return strdup(buf.c_str());1070}1071 1072void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal) {1073  unwrap(OldVal)->replaceAllUsesWith(unwrap(NewVal));1074}1075 1076int LLVMHasMetadata(LLVMValueRef Inst) {1077  return unwrap<Instruction>(Inst)->hasMetadata();1078}1079 1080LLVMValueRef LLVMGetMetadata(LLVMValueRef Inst, unsigned KindID) {1081  auto *I = unwrap<Instruction>(Inst);1082  assert(I && "Expected instruction");1083  if (auto *MD = I->getMetadata(KindID))1084    return wrap(MetadataAsValue::get(I->getContext(), MD));1085  return nullptr;1086}1087 1088// MetadataAsValue uses a canonical format which strips the actual MDNode for1089// MDNode with just a single constant value, storing just a ConstantAsMetadata1090// This undoes this canonicalization, reconstructing the MDNode.1091static MDNode *extractMDNode(MetadataAsValue *MAV) {1092  Metadata *MD = MAV->getMetadata();1093  assert((isa<MDNode>(MD) || isa<ConstantAsMetadata>(MD)) &&1094      "Expected a metadata node or a canonicalized constant");1095 1096  if (MDNode *N = dyn_cast<MDNode>(MD))1097    return N;1098 1099  return MDNode::get(MAV->getContext(), MD);1100}1101 1102void LLVMSetMetadata(LLVMValueRef Inst, unsigned KindID, LLVMValueRef Val) {1103  MDNode *N = Val ? extractMDNode(unwrap<MetadataAsValue>(Val)) : nullptr;1104 1105  unwrap<Instruction>(Inst)->setMetadata(KindID, N);1106}1107 1108struct LLVMOpaqueValueMetadataEntry {1109  unsigned Kind;1110  LLVMMetadataRef Metadata;1111};1112 1113using MetadataEntries = SmallVectorImpl<std::pair<unsigned, MDNode *>>;1114static LLVMValueMetadataEntry *1115llvm_getMetadata(size_t *NumEntries,1116                 llvm::function_ref<void(MetadataEntries &)> AccessMD) {1117  SmallVector<std::pair<unsigned, MDNode *>, 8> MVEs;1118  AccessMD(MVEs);1119 1120  LLVMOpaqueValueMetadataEntry *Result =1121  static_cast<LLVMOpaqueValueMetadataEntry *>(1122                                              safe_malloc(MVEs.size() * sizeof(LLVMOpaqueValueMetadataEntry)));1123  for (unsigned i = 0; i < MVEs.size(); ++i) {1124    const auto &ModuleFlag = MVEs[i];1125    Result[i].Kind = ModuleFlag.first;1126    Result[i].Metadata = wrap(ModuleFlag.second);1127  }1128  *NumEntries = MVEs.size();1129  return Result;1130}1131 1132LLVMValueMetadataEntry *1133LLVMInstructionGetAllMetadataOtherThanDebugLoc(LLVMValueRef Value,1134                                               size_t *NumEntries) {1135  return llvm_getMetadata(NumEntries, [&Value](MetadataEntries &Entries) {1136    Entries.clear();1137    unwrap<Instruction>(Value)->getAllMetadata(Entries);1138  });1139}1140 1141/*--.. Conversion functions ................................................--*/1142 1143#define LLVM_DEFINE_VALUE_CAST(name)                                       \1144  LLVMValueRef LLVMIsA##name(LLVMValueRef Val) {                           \1145    return wrap(static_cast<Value*>(dyn_cast_or_null<name>(unwrap(Val)))); \1146  }1147 1148LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DEFINE_VALUE_CAST)1149 1150LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val) {1151  if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))1152    if (isa<MDNode>(MD->getMetadata()) ||1153        isa<ValueAsMetadata>(MD->getMetadata()))1154      return Val;1155  return nullptr;1156}1157 1158LLVMValueRef LLVMIsAValueAsMetadata(LLVMValueRef Val) {1159  if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))1160    if (isa<ValueAsMetadata>(MD->getMetadata()))1161      return Val;1162  return nullptr;1163}1164 1165LLVMValueRef LLVMIsAMDString(LLVMValueRef Val) {1166  if (auto *MD = dyn_cast_or_null<MetadataAsValue>(unwrap(Val)))1167    if (isa<MDString>(MD->getMetadata()))1168      return Val;1169  return nullptr;1170}1171 1172/*--.. Operations on Uses ..................................................--*/1173LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val) {1174  Value *V = unwrap(Val);1175  Value::use_iterator I = V->use_begin();1176  if (I == V->use_end())1177    return nullptr;1178  return wrap(&*I);1179}1180 1181LLVMUseRef LLVMGetNextUse(LLVMUseRef U) {1182  Use *Next = unwrap(U)->getNext();1183  if (Next)1184    return wrap(Next);1185  return nullptr;1186}1187 1188LLVMValueRef LLVMGetUser(LLVMUseRef U) {1189  return wrap(unwrap(U)->getUser());1190}1191 1192LLVMValueRef LLVMGetUsedValue(LLVMUseRef U) {1193  return wrap(unwrap(U)->get());1194}1195 1196/*--.. Operations on Users .................................................--*/1197 1198static LLVMValueRef getMDNodeOperandImpl(LLVMContext &Context, const MDNode *N,1199                                         unsigned Index) {1200  Metadata *Op = N->getOperand(Index);1201  if (!Op)1202    return nullptr;1203  if (auto *C = dyn_cast<ConstantAsMetadata>(Op))1204    return wrap(C->getValue());1205  return wrap(MetadataAsValue::get(Context, Op));1206}1207 1208LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index) {1209  Value *V = unwrap(Val);1210  if (auto *MD = dyn_cast<MetadataAsValue>(V)) {1211    if (auto *L = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {1212      assert(Index == 0 && "Function-local metadata can only have one operand");1213      return wrap(L->getValue());1214    }1215    return getMDNodeOperandImpl(V->getContext(),1216                                cast<MDNode>(MD->getMetadata()), Index);1217  }1218 1219  return wrap(cast<User>(V)->getOperand(Index));1220}1221 1222LLVMUseRef LLVMGetOperandUse(LLVMValueRef Val, unsigned Index) {1223  Value *V = unwrap(Val);1224  return wrap(&cast<User>(V)->getOperandUse(Index));1225}1226 1227void LLVMSetOperand(LLVMValueRef Val, unsigned Index, LLVMValueRef Op) {1228  unwrap<User>(Val)->setOperand(Index, unwrap(Op));1229}1230 1231int LLVMGetNumOperands(LLVMValueRef Val) {1232  Value *V = unwrap(Val);1233  if (isa<MetadataAsValue>(V))1234    return LLVMGetMDNodeNumOperands(Val);1235 1236  return cast<User>(V)->getNumOperands();1237}1238 1239/*--.. Operations on constants of any type .................................--*/1240 1241LLVMValueRef LLVMConstNull(LLVMTypeRef Ty) {1242  return wrap(Constant::getNullValue(unwrap(Ty)));1243}1244 1245LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty) {1246  return wrap(Constant::getAllOnesValue(unwrap(Ty)));1247}1248 1249LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty) {1250  return wrap(UndefValue::get(unwrap(Ty)));1251}1252 1253LLVMValueRef LLVMGetPoison(LLVMTypeRef Ty) {1254  return wrap(PoisonValue::get(unwrap(Ty)));1255}1256 1257LLVMBool LLVMIsConstant(LLVMValueRef Ty) {1258  return isa<Constant>(unwrap(Ty));1259}1260 1261LLVMBool LLVMIsNull(LLVMValueRef Val) {1262  if (Constant *C = dyn_cast<Constant>(unwrap(Val)))1263    return C->isNullValue();1264  return false;1265}1266 1267LLVMBool LLVMIsUndef(LLVMValueRef Val) {1268  return isa<UndefValue>(unwrap(Val));1269}1270 1271LLVMBool LLVMIsPoison(LLVMValueRef Val) {1272  return isa<PoisonValue>(unwrap(Val));1273}1274 1275LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty) {1276  return wrap(ConstantPointerNull::get(unwrap<PointerType>(Ty)));1277}1278 1279/*--.. Operations on metadata nodes ........................................--*/1280 1281LLVMMetadataRef LLVMMDStringInContext2(LLVMContextRef C, const char *Str,1282                                       size_t SLen) {1283  return wrap(MDString::get(*unwrap(C), StringRef(Str, SLen)));1284}1285 1286LLVMMetadataRef LLVMMDNodeInContext2(LLVMContextRef C, LLVMMetadataRef *MDs,1287                                     size_t Count) {1288  return wrap(MDNode::get(*unwrap(C), ArrayRef<Metadata*>(unwrap(MDs), Count)));1289}1290 1291LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,1292                                   unsigned SLen) {1293  LLVMContext &Context = *unwrap(C);1294  return wrap(MetadataAsValue::get(1295      Context, MDString::get(Context, StringRef(Str, SLen))));1296}1297 1298LLVMValueRef LLVMMDString(const char *Str, unsigned SLen) {1299  return LLVMMDStringInContext(LLVMGetGlobalContext(), Str, SLen);1300}1301 1302LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals,1303                                 unsigned Count) {1304  LLVMContext &Context = *unwrap(C);1305  SmallVector<Metadata *, 8> MDs;1306  for (auto *OV : ArrayRef(Vals, Count)) {1307    Value *V = unwrap(OV);1308    Metadata *MD;1309    if (!V)1310      MD = nullptr;1311    else if (auto *C = dyn_cast<Constant>(V))1312      MD = ConstantAsMetadata::get(C);1313    else if (auto *MDV = dyn_cast<MetadataAsValue>(V)) {1314      MD = MDV->getMetadata();1315      assert(!isa<LocalAsMetadata>(MD) && "Unexpected function-local metadata "1316                                          "outside of direct argument to call");1317    } else {1318      // This is function-local metadata.  Pretend to make an MDNode.1319      assert(Count == 1 &&1320             "Expected only one operand to function-local metadata");1321      return wrap(MetadataAsValue::get(Context, LocalAsMetadata::get(V)));1322    }1323 1324    MDs.push_back(MD);1325  }1326  return wrap(MetadataAsValue::get(Context, MDNode::get(Context, MDs)));1327}1328 1329LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count) {1330  return LLVMMDNodeInContext(LLVMGetGlobalContext(), Vals, Count);1331}1332 1333LLVMValueRef LLVMMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {1334  return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));1335}1336 1337LLVMMetadataRef LLVMValueAsMetadata(LLVMValueRef Val) {1338  auto *V = unwrap(Val);1339  if (auto *C = dyn_cast<Constant>(V))1340    return wrap(ConstantAsMetadata::get(C));1341  if (auto *MAV = dyn_cast<MetadataAsValue>(V))1342    return wrap(MAV->getMetadata());1343  return wrap(ValueAsMetadata::get(V));1344}1345 1346const char *LLVMGetMDString(LLVMValueRef V, unsigned *Length) {1347  if (const auto *MD = dyn_cast<MetadataAsValue>(unwrap(V)))1348    if (const MDString *S = dyn_cast<MDString>(MD->getMetadata())) {1349      *Length = S->getString().size();1350      return S->getString().data();1351    }1352  *Length = 0;1353  return nullptr;1354}1355 1356unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V) {1357  auto *MD = unwrap<MetadataAsValue>(V);1358  if (isa<ValueAsMetadata>(MD->getMetadata()))1359    return 1;1360  return cast<MDNode>(MD->getMetadata())->getNumOperands();1361}1362 1363LLVMNamedMDNodeRef LLVMGetFirstNamedMetadata(LLVMModuleRef M) {1364  Module *Mod = unwrap(M);1365  Module::named_metadata_iterator I = Mod->named_metadata_begin();1366  if (I == Mod->named_metadata_end())1367    return nullptr;1368  return wrap(&*I);1369}1370 1371LLVMNamedMDNodeRef LLVMGetLastNamedMetadata(LLVMModuleRef M) {1372  Module *Mod = unwrap(M);1373  Module::named_metadata_iterator I = Mod->named_metadata_end();1374  if (I == Mod->named_metadata_begin())1375    return nullptr;1376  return wrap(&*--I);1377}1378 1379LLVMNamedMDNodeRef LLVMGetNextNamedMetadata(LLVMNamedMDNodeRef NMD) {1380  NamedMDNode *NamedNode = unwrap(NMD);1381  Module::named_metadata_iterator I(NamedNode);1382  if (++I == NamedNode->getParent()->named_metadata_end())1383    return nullptr;1384  return wrap(&*I);1385}1386 1387LLVMNamedMDNodeRef LLVMGetPreviousNamedMetadata(LLVMNamedMDNodeRef NMD) {1388  NamedMDNode *NamedNode = unwrap(NMD);1389  Module::named_metadata_iterator I(NamedNode);1390  if (I == NamedNode->getParent()->named_metadata_begin())1391    return nullptr;1392  return wrap(&*--I);1393}1394 1395LLVMNamedMDNodeRef LLVMGetNamedMetadata(LLVMModuleRef M,1396                                        const char *Name, size_t NameLen) {1397  return wrap(unwrap(M)->getNamedMetadata(StringRef(Name, NameLen)));1398}1399 1400LLVMNamedMDNodeRef LLVMGetOrInsertNamedMetadata(LLVMModuleRef M,1401                                                const char *Name, size_t NameLen) {1402  return wrap(unwrap(M)->getOrInsertNamedMetadata({Name, NameLen}));1403}1404 1405const char *LLVMGetNamedMetadataName(LLVMNamedMDNodeRef NMD, size_t *NameLen) {1406  NamedMDNode *NamedNode = unwrap(NMD);1407  *NameLen = NamedNode->getName().size();1408  return NamedNode->getName().data();1409}1410 1411void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest) {1412  auto *MD = unwrap<MetadataAsValue>(V);1413  if (auto *MDV = dyn_cast<ValueAsMetadata>(MD->getMetadata())) {1414    *Dest = wrap(MDV->getValue());1415    return;1416  }1417  const auto *N = cast<MDNode>(MD->getMetadata());1418  const unsigned numOperands = N->getNumOperands();1419  LLVMContext &Context = unwrap(V)->getContext();1420  for (unsigned i = 0; i < numOperands; i++)1421    Dest[i] = getMDNodeOperandImpl(Context, N, i);1422}1423 1424void LLVMReplaceMDNodeOperandWith(LLVMValueRef V, unsigned Index,1425                                  LLVMMetadataRef Replacement) {1426  auto *MD = cast<MetadataAsValue>(unwrap(V));1427  auto *N = cast<MDNode>(MD->getMetadata());1428  N->replaceOperandWith(Index, unwrap<Metadata>(Replacement));1429}1430 1431unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char *Name) {1432  if (NamedMDNode *N = unwrap(M)->getNamedMetadata(Name)) {1433    return N->getNumOperands();1434  }1435  return 0;1436}1437 1438void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char *Name,1439                                  LLVMValueRef *Dest) {1440  NamedMDNode *N = unwrap(M)->getNamedMetadata(Name);1441  if (!N)1442    return;1443  LLVMContext &Context = unwrap(M)->getContext();1444  for (unsigned i=0;i<N->getNumOperands();i++)1445    Dest[i] = wrap(MetadataAsValue::get(Context, N->getOperand(i)));1446}1447 1448void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char *Name,1449                                 LLVMValueRef Val) {1450  NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(Name);1451  if (!N)1452    return;1453  if (!Val)1454    return;1455  N->addOperand(extractMDNode(unwrap<MetadataAsValue>(Val)));1456}1457 1458const char *LLVMGetDebugLocDirectory(LLVMValueRef Val, unsigned *Length) {1459  if (!Length) return nullptr;1460  StringRef S;1461  if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {1462    if (const auto &DL = I->getDebugLoc()) {1463      S = DL->getDirectory();1464    }1465  } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {1466    SmallVector<DIGlobalVariableExpression *, 1> GVEs;1467    GV->getDebugInfo(GVEs);1468    if (GVEs.size())1469      if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())1470        S = DGV->getDirectory();1471  } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {1472    if (const DISubprogram *DSP = F->getSubprogram())1473      S = DSP->getDirectory();1474  } else {1475    assert(0 && "Expected Instruction, GlobalVariable or Function");1476    return nullptr;1477  }1478  *Length = S.size();1479  return S.data();1480}1481 1482const char *LLVMGetDebugLocFilename(LLVMValueRef Val, unsigned *Length) {1483  if (!Length) return nullptr;1484  StringRef S;1485  if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {1486    if (const auto &DL = I->getDebugLoc()) {1487      S = DL->getFilename();1488    }1489  } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {1490    SmallVector<DIGlobalVariableExpression *, 1> GVEs;1491    GV->getDebugInfo(GVEs);1492    if (GVEs.size())1493      if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())1494        S = DGV->getFilename();1495  } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {1496    if (const DISubprogram *DSP = F->getSubprogram())1497      S = DSP->getFilename();1498  } else {1499    assert(0 && "Expected Instruction, GlobalVariable or Function");1500    return nullptr;1501  }1502  *Length = S.size();1503  return S.data();1504}1505 1506unsigned LLVMGetDebugLocLine(LLVMValueRef Val) {1507  unsigned L = 0;1508  if (const auto *I = dyn_cast<Instruction>(unwrap(Val))) {1509    if (const auto &DL = I->getDebugLoc()) {1510      L = DL->getLine();1511    }1512  } else if (const auto *GV = dyn_cast<GlobalVariable>(unwrap(Val))) {1513    SmallVector<DIGlobalVariableExpression *, 1> GVEs;1514    GV->getDebugInfo(GVEs);1515    if (GVEs.size())1516      if (const DIGlobalVariable *DGV = GVEs[0]->getVariable())1517        L = DGV->getLine();1518  } else if (const auto *F = dyn_cast<Function>(unwrap(Val))) {1519    if (const DISubprogram *DSP = F->getSubprogram())1520      L = DSP->getLine();1521  } else {1522    assert(0 && "Expected Instruction, GlobalVariable or Function");1523    return -1;1524  }1525  return L;1526}1527 1528unsigned LLVMGetDebugLocColumn(LLVMValueRef Val) {1529  unsigned C = 0;1530  if (const auto *I = dyn_cast<Instruction>(unwrap(Val)))1531    if (const auto &DL = I->getDebugLoc())1532      C = DL->getColumn();1533  return C;1534}1535 1536/*--.. Operations on scalar constants ......................................--*/1537 1538LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N,1539                          LLVMBool SignExtend) {1540  return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), N, SignExtend != 0));1541}1542 1543LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy,1544                                              unsigned NumWords,1545                                              const uint64_t Words[]) {1546    IntegerType *Ty = unwrap<IntegerType>(IntTy);1547    return wrap(ConstantInt::get(1548        Ty->getContext(), APInt(Ty->getBitWidth(), ArrayRef(Words, NumWords))));1549}1550 1551LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char Str[],1552                                  uint8_t Radix) {1553  return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str),1554                               Radix));1555}1556 1557LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char Str[],1558                                         unsigned SLen, uint8_t Radix) {1559  return wrap(ConstantInt::get(unwrap<IntegerType>(IntTy), StringRef(Str, SLen),1560                               Radix));1561}1562 1563LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N) {1564  return wrap(ConstantFP::get(unwrap(RealTy), N));1565}1566 1567LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text) {1568  return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Text)));1569}1570 1571LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char Str[],1572                                          unsigned SLen) {1573  return wrap(ConstantFP::get(unwrap(RealTy), StringRef(Str, SLen)));1574}1575 1576unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal) {1577  return unwrap<ConstantInt>(ConstantVal)->getZExtValue();1578}1579 1580long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal) {1581  return unwrap<ConstantInt>(ConstantVal)->getSExtValue();1582}1583 1584double LLVMConstRealGetDouble(LLVMValueRef ConstantVal, LLVMBool *LosesInfo) {1585  ConstantFP *cFP = unwrap<ConstantFP>(ConstantVal) ;1586  Type *Ty = cFP->getType();1587 1588  if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||1589      Ty->isDoubleTy()) {1590    *LosesInfo = false;1591    return cFP->getValueAPF().convertToDouble();1592  }1593 1594  bool APFLosesInfo;1595  APFloat APF = cFP->getValueAPF();1596  APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &APFLosesInfo);1597  *LosesInfo = APFLosesInfo;1598  return APF.convertToDouble();1599}1600 1601/*--.. Operations on composite constants ...................................--*/1602 1603LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str,1604                                      unsigned Length,1605                                      LLVMBool DontNullTerminate) {1606  /* Inverted the sense of AddNull because ', 0)' is a1607     better mnemonic for null termination than ', 1)'. */1608  return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length),1609                                           DontNullTerminate == 0));1610}1611 1612LLVMValueRef LLVMConstStringInContext2(LLVMContextRef C, const char *Str,1613                                       size_t Length,1614                                       LLVMBool DontNullTerminate) {1615  /* Inverted the sense of AddNull because ', 0)' is a1616     better mnemonic for null termination than ', 1)'. */1617  return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length),1618                                           DontNullTerminate == 0));1619}1620 1621LLVMValueRef LLVMConstString(const char *Str, unsigned Length,1622                             LLVMBool DontNullTerminate) {1623  return LLVMConstStringInContext(LLVMGetGlobalContext(), Str, Length,1624                                  DontNullTerminate);1625}1626 1627LLVMValueRef LLVMGetAggregateElement(LLVMValueRef C, unsigned Idx) {1628  return wrap(unwrap<Constant>(C)->getAggregateElement(Idx));1629}1630 1631LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx) {1632  return wrap(unwrap<ConstantDataSequential>(C)->getElementAsConstant(idx));1633}1634 1635LLVMBool LLVMIsConstantString(LLVMValueRef C) {1636  return unwrap<ConstantDataSequential>(C)->isString();1637}1638 1639const char *LLVMGetAsString(LLVMValueRef C, size_t *Length) {1640  StringRef Str = unwrap<ConstantDataSequential>(C)->getAsString();1641  *Length = Str.size();1642  return Str.data();1643}1644 1645const char *LLVMGetRawDataValues(LLVMValueRef C, size_t *SizeInBytes) {1646  StringRef Str = unwrap<ConstantDataSequential>(C)->getRawDataValues();1647  *SizeInBytes = Str.size();1648  return Str.data();1649}1650 1651LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,1652                            LLVMValueRef *ConstantVals, unsigned Length) {1653  ArrayRef<Constant*> V(unwrap<Constant>(ConstantVals, Length), Length);1654  return wrap(ConstantArray::get(ArrayType::get(unwrap(ElementTy), Length), V));1655}1656 1657LLVMValueRef LLVMConstArray2(LLVMTypeRef ElementTy, LLVMValueRef *ConstantVals,1658                             uint64_t Length) {1659  ArrayRef<Constant *> V(unwrap<Constant>(ConstantVals, Length), Length);1660  return wrap(ConstantArray::get(ArrayType::get(unwrap(ElementTy), Length), V));1661}1662 1663LLVMValueRef LLVMConstDataArray(LLVMTypeRef ElementTy, const char *Data,1664                                size_t SizeInBytes) {1665  Type *Ty = unwrap(ElementTy);1666  size_t Len = SizeInBytes / (Ty->getPrimitiveSizeInBits() / 8);1667  return wrap(ConstantDataArray::getRaw(StringRef(Data, SizeInBytes), Len, Ty));1668}1669 1670LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,1671                                      LLVMValueRef *ConstantVals,1672                                      unsigned Count, LLVMBool Packed) {1673  Constant **Elements = unwrap<Constant>(ConstantVals, Count);1674  return wrap(ConstantStruct::getAnon(*unwrap(C), ArrayRef(Elements, Count),1675                                      Packed != 0));1676}1677 1678LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,1679                             LLVMBool Packed) {1680  return LLVMConstStructInContext(LLVMGetGlobalContext(), ConstantVals, Count,1681                                  Packed);1682}1683 1684LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,1685                                  LLVMValueRef *ConstantVals,1686                                  unsigned Count) {1687  Constant **Elements = unwrap<Constant>(ConstantVals, Count);1688  StructType *Ty = unwrap<StructType>(StructTy);1689 1690  return wrap(ConstantStruct::get(Ty, ArrayRef(Elements, Count)));1691}1692 1693LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size) {1694  return wrap(ConstantVector::get(1695      ArrayRef(unwrap<Constant>(ScalarConstantVals, Size), Size)));1696}1697 1698LLVMValueRef LLVMConstantPtrAuth(LLVMValueRef Ptr, LLVMValueRef Key,1699                                 LLVMValueRef Disc, LLVMValueRef AddrDisc) {1700  return wrap(ConstantPtrAuth::get(1701      unwrap<Constant>(Ptr), unwrap<ConstantInt>(Key),1702      unwrap<ConstantInt>(Disc), unwrap<Constant>(AddrDisc),1703      ConstantPointerNull::get(1704          cast<PointerType>(unwrap<Constant>(AddrDisc)->getType()))));1705}1706 1707/*-- Opcode mapping */1708 1709static LLVMOpcode map_to_llvmopcode(int opcode)1710{1711    switch (opcode) {1712      default: llvm_unreachable("Unhandled Opcode.");1713#define HANDLE_INST(num, opc, clas) case num: return LLVM##opc;1714#include "llvm/IR/Instruction.def"1715#undef HANDLE_INST1716    }1717}1718 1719static int map_from_llvmopcode(LLVMOpcode code)1720{1721    switch (code) {1722#define HANDLE_INST(num, opc, clas) case LLVM##opc: return num;1723#include "llvm/IR/Instruction.def"1724#undef HANDLE_INST1725    }1726    llvm_unreachable("Unhandled Opcode.");1727}1728 1729/*-- GEP wrap flag conversions */1730 1731static GEPNoWrapFlags mapFromLLVMGEPNoWrapFlags(LLVMGEPNoWrapFlags GEPFlags) {1732  GEPNoWrapFlags NewGEPFlags;1733  if ((GEPFlags & LLVMGEPFlagInBounds) != 0)1734    NewGEPFlags |= GEPNoWrapFlags::inBounds();1735  if ((GEPFlags & LLVMGEPFlagNUSW) != 0)1736    NewGEPFlags |= GEPNoWrapFlags::noUnsignedSignedWrap();1737  if ((GEPFlags & LLVMGEPFlagNUW) != 0)1738    NewGEPFlags |= GEPNoWrapFlags::noUnsignedWrap();1739 1740  return NewGEPFlags;1741}1742 1743static LLVMGEPNoWrapFlags mapToLLVMGEPNoWrapFlags(GEPNoWrapFlags GEPFlags) {1744  LLVMGEPNoWrapFlags NewGEPFlags = 0;1745  if (GEPFlags.isInBounds())1746    NewGEPFlags |= LLVMGEPFlagInBounds;1747  if (GEPFlags.hasNoUnsignedSignedWrap())1748    NewGEPFlags |= LLVMGEPFlagNUSW;1749  if (GEPFlags.hasNoUnsignedWrap())1750    NewGEPFlags |= LLVMGEPFlagNUW;1751 1752  return NewGEPFlags;1753}1754 1755/*--.. Constant expressions ................................................--*/1756 1757LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal) {1758  return map_to_llvmopcode(unwrap<ConstantExpr>(ConstantVal)->getOpcode());1759}1760 1761LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty) {1762  return wrap(ConstantExpr::getAlignOf(unwrap(Ty)));1763}1764 1765LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty) {1766  return wrap(ConstantExpr::getSizeOf(unwrap(Ty)));1767}1768 1769LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal) {1770  return wrap(ConstantExpr::getNeg(unwrap<Constant>(ConstantVal)));1771}1772 1773LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal) {1774  return wrap(ConstantExpr::getNSWNeg(unwrap<Constant>(ConstantVal)));1775}1776 1777LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal) {1778  return wrap(ConstantExpr::getNeg(unwrap<Constant>(ConstantVal)));1779}1780 1781 1782LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal) {1783  return wrap(ConstantExpr::getNot(unwrap<Constant>(ConstantVal)));1784}1785 1786LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {1787  return wrap(ConstantExpr::getAdd(unwrap<Constant>(LHSConstant),1788                                   unwrap<Constant>(RHSConstant)));1789}1790 1791LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant,1792                             LLVMValueRef RHSConstant) {1793  return wrap(ConstantExpr::getNSWAdd(unwrap<Constant>(LHSConstant),1794                                      unwrap<Constant>(RHSConstant)));1795}1796 1797LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant,1798                             LLVMValueRef RHSConstant) {1799  return wrap(ConstantExpr::getNUWAdd(unwrap<Constant>(LHSConstant),1800                                      unwrap<Constant>(RHSConstant)));1801}1802 1803LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {1804  return wrap(ConstantExpr::getSub(unwrap<Constant>(LHSConstant),1805                                   unwrap<Constant>(RHSConstant)));1806}1807 1808LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant,1809                             LLVMValueRef RHSConstant) {1810  return wrap(ConstantExpr::getNSWSub(unwrap<Constant>(LHSConstant),1811                                      unwrap<Constant>(RHSConstant)));1812}1813 1814LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant,1815                             LLVMValueRef RHSConstant) {1816  return wrap(ConstantExpr::getNUWSub(unwrap<Constant>(LHSConstant),1817                                      unwrap<Constant>(RHSConstant)));1818}1819 1820LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant) {1821  return wrap(ConstantExpr::getXor(unwrap<Constant>(LHSConstant),1822                                   unwrap<Constant>(RHSConstant)));1823}1824 1825LLVMValueRef LLVMConstGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,1826                           LLVMValueRef *ConstantIndices, unsigned NumIndices) {1827  ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),1828                               NumIndices);1829  Constant *Val = unwrap<Constant>(ConstantVal);1830  return wrap(ConstantExpr::getGetElementPtr(unwrap(Ty), Val, IdxList));1831}1832 1833LLVMValueRef LLVMConstInBoundsGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,1834                                   LLVMValueRef *ConstantIndices,1835                                   unsigned NumIndices) {1836  ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),1837                               NumIndices);1838  Constant *Val = unwrap<Constant>(ConstantVal);1839  return wrap(ConstantExpr::getInBoundsGetElementPtr(unwrap(Ty), Val, IdxList));1840}1841 1842LLVMValueRef LLVMConstGEPWithNoWrapFlags(LLVMTypeRef Ty,1843                                         LLVMValueRef ConstantVal,1844                                         LLVMValueRef *ConstantIndices,1845                                         unsigned NumIndices,1846                                         LLVMGEPNoWrapFlags NoWrapFlags) {1847  ArrayRef<Constant *> IdxList(unwrap<Constant>(ConstantIndices, NumIndices),1848                               NumIndices);1849  Constant *Val = unwrap<Constant>(ConstantVal);1850  return wrap(ConstantExpr::getGetElementPtr(1851      unwrap(Ty), Val, IdxList, mapFromLLVMGEPNoWrapFlags(NoWrapFlags)));1852}1853 1854LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {1855  return wrap(ConstantExpr::getTrunc(unwrap<Constant>(ConstantVal),1856                                     unwrap(ToType)));1857}1858 1859LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {1860  return wrap(ConstantExpr::getPtrToInt(unwrap<Constant>(ConstantVal),1861                                        unwrap(ToType)));1862}1863 1864LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {1865  return wrap(ConstantExpr::getIntToPtr(unwrap<Constant>(ConstantVal),1866                                        unwrap(ToType)));1867}1868 1869LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType) {1870  return wrap(ConstantExpr::getBitCast(unwrap<Constant>(ConstantVal),1871                                       unwrap(ToType)));1872}1873 1874LLVMValueRef LLVMConstAddrSpaceCast(LLVMValueRef ConstantVal,1875                                    LLVMTypeRef ToType) {1876  return wrap(ConstantExpr::getAddrSpaceCast(unwrap<Constant>(ConstantVal),1877                                             unwrap(ToType)));1878}1879 1880LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal,1881                                     LLVMTypeRef ToType) {1882  return wrap(ConstantExpr::getTruncOrBitCast(unwrap<Constant>(ConstantVal),1883                                              unwrap(ToType)));1884}1885 1886LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal,1887                                  LLVMTypeRef ToType) {1888  return wrap(ConstantExpr::getPointerCast(unwrap<Constant>(ConstantVal),1889                                           unwrap(ToType)));1890}1891 1892LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,1893                                     LLVMValueRef IndexConstant) {1894  return wrap(ConstantExpr::getExtractElement(unwrap<Constant>(VectorConstant),1895                                              unwrap<Constant>(IndexConstant)));1896}1897 1898LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,1899                                    LLVMValueRef ElementValueConstant,1900                                    LLVMValueRef IndexConstant) {1901  return wrap(ConstantExpr::getInsertElement(unwrap<Constant>(VectorConstant),1902                                         unwrap<Constant>(ElementValueConstant),1903                                             unwrap<Constant>(IndexConstant)));1904}1905 1906LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,1907                                    LLVMValueRef VectorBConstant,1908                                    LLVMValueRef MaskConstant) {1909  SmallVector<int, 16> IntMask;1910  ShuffleVectorInst::getShuffleMask(unwrap<Constant>(MaskConstant), IntMask);1911  return wrap(ConstantExpr::getShuffleVector(unwrap<Constant>(VectorAConstant),1912                                             unwrap<Constant>(VectorBConstant),1913                                             IntMask));1914}1915 1916LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty, const char *AsmString,1917                                const char *Constraints,1918                                LLVMBool HasSideEffects,1919                                LLVMBool IsAlignStack) {1920  return wrap(InlineAsm::get(dyn_cast<FunctionType>(unwrap(Ty)), AsmString,1921                             Constraints, HasSideEffects, IsAlignStack));1922}1923 1924LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB) {1925  return wrap(BlockAddress::get(unwrap<Function>(F), unwrap(BB)));1926}1927 1928LLVMValueRef LLVMGetBlockAddressFunction(LLVMValueRef BlockAddr) {1929  return wrap(unwrap<BlockAddress>(BlockAddr)->getFunction());1930}1931 1932LLVMBasicBlockRef LLVMGetBlockAddressBasicBlock(LLVMValueRef BlockAddr) {1933  return wrap(unwrap<BlockAddress>(BlockAddr)->getBasicBlock());1934}1935 1936/*--.. Operations on global variables, functions, and aliases (globals) ....--*/1937 1938LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global) {1939  return wrap(unwrap<GlobalValue>(Global)->getParent());1940}1941 1942LLVMBool LLVMIsDeclaration(LLVMValueRef Global) {1943  return unwrap<GlobalValue>(Global)->isDeclaration();1944}1945 1946LLVMLinkage LLVMGetLinkage(LLVMValueRef Global) {1947  switch (unwrap<GlobalValue>(Global)->getLinkage()) {1948  case GlobalValue::ExternalLinkage:1949    return LLVMExternalLinkage;1950  case GlobalValue::AvailableExternallyLinkage:1951    return LLVMAvailableExternallyLinkage;1952  case GlobalValue::LinkOnceAnyLinkage:1953    return LLVMLinkOnceAnyLinkage;1954  case GlobalValue::LinkOnceODRLinkage:1955    return LLVMLinkOnceODRLinkage;1956  case GlobalValue::WeakAnyLinkage:1957    return LLVMWeakAnyLinkage;1958  case GlobalValue::WeakODRLinkage:1959    return LLVMWeakODRLinkage;1960  case GlobalValue::AppendingLinkage:1961    return LLVMAppendingLinkage;1962  case GlobalValue::InternalLinkage:1963    return LLVMInternalLinkage;1964  case GlobalValue::PrivateLinkage:1965    return LLVMPrivateLinkage;1966  case GlobalValue::ExternalWeakLinkage:1967    return LLVMExternalWeakLinkage;1968  case GlobalValue::CommonLinkage:1969    return LLVMCommonLinkage;1970  }1971 1972  llvm_unreachable("Invalid GlobalValue linkage!");1973}1974 1975void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage) {1976  GlobalValue *GV = unwrap<GlobalValue>(Global);1977 1978  switch (Linkage) {1979  case LLVMExternalLinkage:1980    GV->setLinkage(GlobalValue::ExternalLinkage);1981    break;1982  case LLVMAvailableExternallyLinkage:1983    GV->setLinkage(GlobalValue::AvailableExternallyLinkage);1984    break;1985  case LLVMLinkOnceAnyLinkage:1986    GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);1987    break;1988  case LLVMLinkOnceODRLinkage:1989    GV->setLinkage(GlobalValue::LinkOnceODRLinkage);1990    break;1991  case LLVMLinkOnceODRAutoHideLinkage:1992    LLVM_DEBUG(1993        errs() << "LLVMSetLinkage(): LLVMLinkOnceODRAutoHideLinkage is no "1994                  "longer supported.");1995    break;1996  case LLVMWeakAnyLinkage:1997    GV->setLinkage(GlobalValue::WeakAnyLinkage);1998    break;1999  case LLVMWeakODRLinkage:2000    GV->setLinkage(GlobalValue::WeakODRLinkage);2001    break;2002  case LLVMAppendingLinkage:2003    GV->setLinkage(GlobalValue::AppendingLinkage);2004    break;2005  case LLVMInternalLinkage:2006    GV->setLinkage(GlobalValue::InternalLinkage);2007    break;2008  case LLVMPrivateLinkage:2009    GV->setLinkage(GlobalValue::PrivateLinkage);2010    break;2011  case LLVMLinkerPrivateLinkage:2012    GV->setLinkage(GlobalValue::PrivateLinkage);2013    break;2014  case LLVMLinkerPrivateWeakLinkage:2015    GV->setLinkage(GlobalValue::PrivateLinkage);2016    break;2017  case LLVMDLLImportLinkage:2018    LLVM_DEBUG(2019        errs()2020        << "LLVMSetLinkage(): LLVMDLLImportLinkage is no longer supported.");2021    break;2022  case LLVMDLLExportLinkage:2023    LLVM_DEBUG(2024        errs()2025        << "LLVMSetLinkage(): LLVMDLLExportLinkage is no longer supported.");2026    break;2027  case LLVMExternalWeakLinkage:2028    GV->setLinkage(GlobalValue::ExternalWeakLinkage);2029    break;2030  case LLVMGhostLinkage:2031    LLVM_DEBUG(2032        errs() << "LLVMSetLinkage(): LLVMGhostLinkage is no longer supported.");2033    break;2034  case LLVMCommonLinkage:2035    GV->setLinkage(GlobalValue::CommonLinkage);2036    break;2037  }2038}2039 2040const char *LLVMGetSection(LLVMValueRef Global) {2041  // Using .data() is safe because of how GlobalObject::setSection is2042  // implemented.2043  return unwrap<GlobalValue>(Global)->getSection().data();2044}2045 2046void LLVMSetSection(LLVMValueRef Global, const char *Section) {2047  unwrap<GlobalObject>(Global)->setSection(Section);2048}2049 2050LLVMVisibility LLVMGetVisibility(LLVMValueRef Global) {2051  return static_cast<LLVMVisibility>(2052    unwrap<GlobalValue>(Global)->getVisibility());2053}2054 2055void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz) {2056  unwrap<GlobalValue>(Global)2057    ->setVisibility(static_cast<GlobalValue::VisibilityTypes>(Viz));2058}2059 2060LLVMDLLStorageClass LLVMGetDLLStorageClass(LLVMValueRef Global) {2061  return static_cast<LLVMDLLStorageClass>(2062      unwrap<GlobalValue>(Global)->getDLLStorageClass());2063}2064 2065void LLVMSetDLLStorageClass(LLVMValueRef Global, LLVMDLLStorageClass Class) {2066  unwrap<GlobalValue>(Global)->setDLLStorageClass(2067      static_cast<GlobalValue::DLLStorageClassTypes>(Class));2068}2069 2070LLVMUnnamedAddr LLVMGetUnnamedAddress(LLVMValueRef Global) {2071  switch (unwrap<GlobalValue>(Global)->getUnnamedAddr()) {2072  case GlobalVariable::UnnamedAddr::None:2073    return LLVMNoUnnamedAddr;2074  case GlobalVariable::UnnamedAddr::Local:2075    return LLVMLocalUnnamedAddr;2076  case GlobalVariable::UnnamedAddr::Global:2077    return LLVMGlobalUnnamedAddr;2078  }2079  llvm_unreachable("Unknown UnnamedAddr kind!");2080}2081 2082void LLVMSetUnnamedAddress(LLVMValueRef Global, LLVMUnnamedAddr UnnamedAddr) {2083  GlobalValue *GV = unwrap<GlobalValue>(Global);2084 2085  switch (UnnamedAddr) {2086  case LLVMNoUnnamedAddr:2087    return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::None);2088  case LLVMLocalUnnamedAddr:2089    return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Local);2090  case LLVMGlobalUnnamedAddr:2091    return GV->setUnnamedAddr(GlobalVariable::UnnamedAddr::Global);2092  }2093}2094 2095LLVMBool LLVMHasUnnamedAddr(LLVMValueRef Global) {2096  return unwrap<GlobalValue>(Global)->hasGlobalUnnamedAddr();2097}2098 2099void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr) {2100  unwrap<GlobalValue>(Global)->setUnnamedAddr(2101      HasUnnamedAddr ? GlobalValue::UnnamedAddr::Global2102                     : GlobalValue::UnnamedAddr::None);2103}2104 2105LLVMTypeRef LLVMGlobalGetValueType(LLVMValueRef Global) {2106  return wrap(unwrap<GlobalValue>(Global)->getValueType());2107}2108 2109/*--.. Operations on global variables, load and store instructions .........--*/2110 2111unsigned LLVMGetAlignment(LLVMValueRef V) {2112  Value *P = unwrap(V);2113  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P))2114    return GV->getAlign() ? GV->getAlign()->value() : 0;2115  if (Function *F = dyn_cast<Function>(P))2116    return F->getAlign() ? F->getAlign()->value() : 0;2117  if (AllocaInst *AI = dyn_cast<AllocaInst>(P))2118    return AI->getAlign().value();2119  if (LoadInst *LI = dyn_cast<LoadInst>(P))2120    return LI->getAlign().value();2121  if (StoreInst *SI = dyn_cast<StoreInst>(P))2122    return SI->getAlign().value();2123  if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(P))2124    return RMWI->getAlign().value();2125  if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(P))2126    return CXI->getAlign().value();2127 2128  llvm_unreachable(2129      "only GlobalValue, AllocaInst, LoadInst, StoreInst, AtomicRMWInst, "2130      "and AtomicCmpXchgInst have alignment");2131}2132 2133void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes) {2134  Value *P = unwrap(V);2135  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P))2136    GV->setAlignment(MaybeAlign(Bytes));2137  else if (Function *F = dyn_cast<Function>(P))2138    F->setAlignment(MaybeAlign(Bytes));2139  else if (AllocaInst *AI = dyn_cast<AllocaInst>(P))2140    AI->setAlignment(Align(Bytes));2141  else if (LoadInst *LI = dyn_cast<LoadInst>(P))2142    LI->setAlignment(Align(Bytes));2143  else if (StoreInst *SI = dyn_cast<StoreInst>(P))2144    SI->setAlignment(Align(Bytes));2145  else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(P))2146    RMWI->setAlignment(Align(Bytes));2147  else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(P))2148    CXI->setAlignment(Align(Bytes));2149  else2150    llvm_unreachable(2151        "only GlobalValue, AllocaInst, LoadInst, StoreInst, AtomicRMWInst, and "2152        "and AtomicCmpXchgInst have alignment");2153}2154 2155LLVMValueMetadataEntry *LLVMGlobalCopyAllMetadata(LLVMValueRef Value,2156                                                  size_t *NumEntries) {2157  return llvm_getMetadata(NumEntries, [&Value](MetadataEntries &Entries) {2158    Entries.clear();2159    if (Instruction *Instr = dyn_cast<Instruction>(unwrap(Value))) {2160      Instr->getAllMetadata(Entries);2161    } else {2162      unwrap<GlobalObject>(Value)->getAllMetadata(Entries);2163    }2164  });2165}2166 2167unsigned LLVMValueMetadataEntriesGetKind(LLVMValueMetadataEntry *Entries,2168                                         unsigned Index) {2169  LLVMOpaqueValueMetadataEntry MVE =2170      static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);2171  return MVE.Kind;2172}2173 2174LLVMMetadataRef2175LLVMValueMetadataEntriesGetMetadata(LLVMValueMetadataEntry *Entries,2176                                    unsigned Index) {2177  LLVMOpaqueValueMetadataEntry MVE =2178      static_cast<LLVMOpaqueValueMetadataEntry>(Entries[Index]);2179  return MVE.Metadata;2180}2181 2182void LLVMDisposeValueMetadataEntries(LLVMValueMetadataEntry *Entries) {2183  free(Entries);2184}2185 2186void LLVMGlobalSetMetadata(LLVMValueRef Global, unsigned Kind,2187                           LLVMMetadataRef MD) {2188  unwrap<GlobalObject>(Global)->setMetadata(Kind, unwrap<MDNode>(MD));2189}2190 2191void LLVMGlobalAddMetadata(LLVMValueRef Global, unsigned Kind,2192                           LLVMMetadataRef MD) {2193  unwrap<GlobalObject>(Global)->addMetadata(Kind, *unwrap<MDNode>(MD));2194}2195 2196void LLVMGlobalEraseMetadata(LLVMValueRef Global, unsigned Kind) {2197  unwrap<GlobalObject>(Global)->eraseMetadata(Kind);2198}2199 2200void LLVMGlobalClearMetadata(LLVMValueRef Global) {2201  unwrap<GlobalObject>(Global)->clearMetadata();2202}2203 2204void LLVMGlobalAddDebugInfo(LLVMValueRef Global, LLVMMetadataRef GVE) {2205  unwrap<GlobalVariable>(Global)->addDebugInfo(2206      unwrap<DIGlobalVariableExpression>(GVE));2207}2208 2209/*--.. Operations on global variables ......................................--*/2210 2211LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name) {2212  return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,2213                                 GlobalValue::ExternalLinkage, nullptr, Name));2214}2215 2216LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty,2217                                         const char *Name,2218                                         unsigned AddressSpace) {2219  return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,2220                                 GlobalValue::ExternalLinkage, nullptr, Name,2221                                 nullptr, GlobalVariable::NotThreadLocal,2222                                 AddressSpace));2223}2224 2225LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name) {2226  return wrap(unwrap(M)->getNamedGlobal(Name));2227}2228 2229LLVMValueRef LLVMGetNamedGlobalWithLength(LLVMModuleRef M, const char *Name,2230                                          size_t Length) {2231  return wrap(unwrap(M)->getNamedGlobal(StringRef(Name, Length)));2232}2233 2234LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M) {2235  Module *Mod = unwrap(M);2236  Module::global_iterator I = Mod->global_begin();2237  if (I == Mod->global_end())2238    return nullptr;2239  return wrap(&*I);2240}2241 2242LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {2243  Module *Mod = unwrap(M);2244  Module::global_iterator I = Mod->global_end();2245  if (I == Mod->global_begin())2246    return nullptr;2247  return wrap(&*--I);2248}2249 2250LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {2251  GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);2252  Module::global_iterator I(GV);2253  if (++I == GV->getParent()->global_end())2254    return nullptr;2255  return wrap(&*I);2256}2257 2258LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {2259  GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);2260  Module::global_iterator I(GV);2261  if (I == GV->getParent()->global_begin())2262    return nullptr;2263  return wrap(&*--I);2264}2265 2266void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {2267  unwrap<GlobalVariable>(GlobalVar)->eraseFromParent();2268}2269 2270LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {2271  GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);2272  if ( !GV->hasInitializer() )2273    return nullptr;2274  return wrap(GV->getInitializer());2275}2276 2277void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal) {2278  unwrap<GlobalVariable>(GlobalVar)->setInitializer(2279      ConstantVal ? unwrap<Constant>(ConstantVal) : nullptr);2280}2281 2282LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar) {2283  return unwrap<GlobalVariable>(GlobalVar)->isThreadLocal();2284}2285 2286void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal) {2287  unwrap<GlobalVariable>(GlobalVar)->setThreadLocal(IsThreadLocal != 0);2288}2289 2290LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar) {2291  return unwrap<GlobalVariable>(GlobalVar)->isConstant();2292}2293 2294void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant) {2295  unwrap<GlobalVariable>(GlobalVar)->setConstant(IsConstant != 0);2296}2297 2298LLVMThreadLocalMode LLVMGetThreadLocalMode(LLVMValueRef GlobalVar) {2299  switch (unwrap<GlobalVariable>(GlobalVar)->getThreadLocalMode()) {2300  case GlobalVariable::NotThreadLocal:2301    return LLVMNotThreadLocal;2302  case GlobalVariable::GeneralDynamicTLSModel:2303    return LLVMGeneralDynamicTLSModel;2304  case GlobalVariable::LocalDynamicTLSModel:2305    return LLVMLocalDynamicTLSModel;2306  case GlobalVariable::InitialExecTLSModel:2307    return LLVMInitialExecTLSModel;2308  case GlobalVariable::LocalExecTLSModel:2309    return LLVMLocalExecTLSModel;2310  }2311 2312  llvm_unreachable("Invalid GlobalVariable thread local mode");2313}2314 2315void LLVMSetThreadLocalMode(LLVMValueRef GlobalVar, LLVMThreadLocalMode Mode) {2316  GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);2317 2318  switch (Mode) {2319  case LLVMNotThreadLocal:2320    GV->setThreadLocalMode(GlobalVariable::NotThreadLocal);2321    break;2322  case LLVMGeneralDynamicTLSModel:2323    GV->setThreadLocalMode(GlobalVariable::GeneralDynamicTLSModel);2324    break;2325  case LLVMLocalDynamicTLSModel:2326    GV->setThreadLocalMode(GlobalVariable::LocalDynamicTLSModel);2327    break;2328  case LLVMInitialExecTLSModel:2329    GV->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);2330    break;2331  case LLVMLocalExecTLSModel:2332    GV->setThreadLocalMode(GlobalVariable::LocalExecTLSModel);2333    break;2334  }2335}2336 2337LLVMBool LLVMIsExternallyInitialized(LLVMValueRef GlobalVar) {2338  return unwrap<GlobalVariable>(GlobalVar)->isExternallyInitialized();2339}2340 2341void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit) {2342  unwrap<GlobalVariable>(GlobalVar)->setExternallyInitialized(IsExtInit);2343}2344 2345/*--.. Operations on aliases ......................................--*/2346 2347LLVMValueRef LLVMAddAlias2(LLVMModuleRef M, LLVMTypeRef ValueTy,2348                           unsigned AddrSpace, LLVMValueRef Aliasee,2349                           const char *Name) {2350  return wrap(GlobalAlias::create(unwrap(ValueTy), AddrSpace,2351                                  GlobalValue::ExternalLinkage, Name,2352                                  unwrap<Constant>(Aliasee), unwrap(M)));2353}2354 2355LLVMValueRef LLVMGetNamedGlobalAlias(LLVMModuleRef M,2356                                     const char *Name, size_t NameLen) {2357  return wrap(unwrap(M)->getNamedAlias(StringRef(Name, NameLen)));2358}2359 2360LLVMValueRef LLVMGetFirstGlobalAlias(LLVMModuleRef M) {2361  Module *Mod = unwrap(M);2362  Module::alias_iterator I = Mod->alias_begin();2363  if (I == Mod->alias_end())2364    return nullptr;2365  return wrap(&*I);2366}2367 2368LLVMValueRef LLVMGetLastGlobalAlias(LLVMModuleRef M) {2369  Module *Mod = unwrap(M);2370  Module::alias_iterator I = Mod->alias_end();2371  if (I == Mod->alias_begin())2372    return nullptr;2373  return wrap(&*--I);2374}2375 2376LLVMValueRef LLVMGetNextGlobalAlias(LLVMValueRef GA) {2377  GlobalAlias *Alias = unwrap<GlobalAlias>(GA);2378  Module::alias_iterator I(Alias);2379  if (++I == Alias->getParent()->alias_end())2380    return nullptr;2381  return wrap(&*I);2382}2383 2384LLVMValueRef LLVMGetPreviousGlobalAlias(LLVMValueRef GA) {2385  GlobalAlias *Alias = unwrap<GlobalAlias>(GA);2386  Module::alias_iterator I(Alias);2387  if (I == Alias->getParent()->alias_begin())2388    return nullptr;2389  return wrap(&*--I);2390}2391 2392LLVMValueRef LLVMAliasGetAliasee(LLVMValueRef Alias) {2393  return wrap(unwrap<GlobalAlias>(Alias)->getAliasee());2394}2395 2396void LLVMAliasSetAliasee(LLVMValueRef Alias, LLVMValueRef Aliasee) {2397  unwrap<GlobalAlias>(Alias)->setAliasee(unwrap<Constant>(Aliasee));2398}2399 2400/*--.. Operations on functions .............................................--*/2401 2402LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,2403                             LLVMTypeRef FunctionTy) {2404  return wrap(Function::Create(unwrap<FunctionType>(FunctionTy),2405                               GlobalValue::ExternalLinkage, Name, unwrap(M)));2406}2407 2408LLVMValueRef LLVMGetOrInsertFunction(LLVMModuleRef M, const char *Name,2409                                     size_t NameLen, LLVMTypeRef FunctionTy) {2410  return wrap(unwrap(M)2411                  ->getOrInsertFunction(StringRef(Name, NameLen),2412                                        unwrap<FunctionType>(FunctionTy))2413                  .getCallee());2414}2415 2416LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name) {2417  return wrap(unwrap(M)->getFunction(Name));2418}2419 2420LLVMValueRef LLVMGetNamedFunctionWithLength(LLVMModuleRef M, const char *Name,2421                                            size_t Length) {2422  return wrap(unwrap(M)->getFunction(StringRef(Name, Length)));2423}2424 2425LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M) {2426  Module *Mod = unwrap(M);2427  Module::iterator I = Mod->begin();2428  if (I == Mod->end())2429    return nullptr;2430  return wrap(&*I);2431}2432 2433LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {2434  Module *Mod = unwrap(M);2435  Module::iterator I = Mod->end();2436  if (I == Mod->begin())2437    return nullptr;2438  return wrap(&*--I);2439}2440 2441LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {2442  Function *Func = unwrap<Function>(Fn);2443  Module::iterator I(Func);2444  if (++I == Func->getParent()->end())2445    return nullptr;2446  return wrap(&*I);2447}2448 2449LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {2450  Function *Func = unwrap<Function>(Fn);2451  Module::iterator I(Func);2452  if (I == Func->getParent()->begin())2453    return nullptr;2454  return wrap(&*--I);2455}2456 2457void LLVMDeleteFunction(LLVMValueRef Fn) {2458  unwrap<Function>(Fn)->eraseFromParent();2459}2460 2461LLVMBool LLVMHasPersonalityFn(LLVMValueRef Fn) {2462  return unwrap<Function>(Fn)->hasPersonalityFn();2463}2464 2465LLVMValueRef LLVMGetPersonalityFn(LLVMValueRef Fn) {2466  return wrap(unwrap<Function>(Fn)->getPersonalityFn());2467}2468 2469void LLVMSetPersonalityFn(LLVMValueRef Fn, LLVMValueRef PersonalityFn) {2470  unwrap<Function>(Fn)->setPersonalityFn(2471      PersonalityFn ? unwrap<Constant>(PersonalityFn) : nullptr);2472}2473 2474unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {2475  if (Function *F = dyn_cast<Function>(unwrap(Fn)))2476    return F->getIntrinsicID();2477  return 0;2478}2479 2480static Intrinsic::ID llvm_map_to_intrinsic_id(unsigned ID) {2481  assert(ID < llvm::Intrinsic::num_intrinsics && "Intrinsic ID out of range");2482  return llvm::Intrinsic::ID(ID);2483}2484 2485LLVMValueRef LLVMGetIntrinsicDeclaration(LLVMModuleRef Mod,2486                                         unsigned ID,2487                                         LLVMTypeRef *ParamTypes,2488                                         size_t ParamCount) {2489  ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);2490  auto IID = llvm_map_to_intrinsic_id(ID);2491  return wrap(llvm::Intrinsic::getOrInsertDeclaration(unwrap(Mod), IID, Tys));2492}2493 2494const char *LLVMIntrinsicGetName(unsigned ID, size_t *NameLength) {2495  auto IID = llvm_map_to_intrinsic_id(ID);2496  auto Str = llvm::Intrinsic::getName(IID);2497  *NameLength = Str.size();2498  return Str.data();2499}2500 2501LLVMTypeRef LLVMIntrinsicGetType(LLVMContextRef Ctx, unsigned ID,2502                                 LLVMTypeRef *ParamTypes, size_t ParamCount) {2503  auto IID = llvm_map_to_intrinsic_id(ID);2504  ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);2505  return wrap(llvm::Intrinsic::getType(*unwrap(Ctx), IID, Tys));2506}2507 2508char *LLVMIntrinsicCopyOverloadedName(unsigned ID, LLVMTypeRef *ParamTypes,2509                                      size_t ParamCount, size_t *NameLength) {2510  auto IID = llvm_map_to_intrinsic_id(ID);2511  ArrayRef<Type*> Tys(unwrap(ParamTypes), ParamCount);2512  auto Str = llvm::Intrinsic::getNameNoUnnamedTypes(IID, Tys);2513  *NameLength = Str.length();2514  return strdup(Str.c_str());2515}2516 2517char *LLVMIntrinsicCopyOverloadedName2(LLVMModuleRef Mod, unsigned ID,2518                                       LLVMTypeRef *ParamTypes,2519                                       size_t ParamCount, size_t *NameLength) {2520  auto IID = llvm_map_to_intrinsic_id(ID);2521  ArrayRef<Type *> Tys(unwrap(ParamTypes), ParamCount);2522  auto Str = llvm::Intrinsic::getName(IID, Tys, unwrap(Mod));2523  *NameLength = Str.length();2524  return strdup(Str.c_str());2525}2526 2527unsigned LLVMLookupIntrinsicID(const char *Name, size_t NameLen) {2528  return Intrinsic::lookupIntrinsicID({Name, NameLen});2529}2530 2531LLVMBool LLVMIntrinsicIsOverloaded(unsigned ID) {2532  auto IID = llvm_map_to_intrinsic_id(ID);2533  return llvm::Intrinsic::isOverloaded(IID);2534}2535 2536unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn) {2537  return unwrap<Function>(Fn)->getCallingConv();2538}2539 2540void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC) {2541  return unwrap<Function>(Fn)->setCallingConv(2542    static_cast<CallingConv::ID>(CC));2543}2544 2545const char *LLVMGetGC(LLVMValueRef Fn) {2546  Function *F = unwrap<Function>(Fn);2547  return F->hasGC()? F->getGC().c_str() : nullptr;2548}2549 2550void LLVMSetGC(LLVMValueRef Fn, const char *GC) {2551  Function *F = unwrap<Function>(Fn);2552  if (GC)2553    F->setGC(GC);2554  else2555    F->clearGC();2556}2557 2558LLVMValueRef LLVMGetPrefixData(LLVMValueRef Fn) {2559  Function *F = unwrap<Function>(Fn);2560  return wrap(F->getPrefixData());2561}2562 2563LLVMBool LLVMHasPrefixData(LLVMValueRef Fn) {2564  Function *F = unwrap<Function>(Fn);2565  return F->hasPrefixData();2566}2567 2568void LLVMSetPrefixData(LLVMValueRef Fn, LLVMValueRef prefixData) {2569  Function *F = unwrap<Function>(Fn);2570  Constant *prefix = unwrap<Constant>(prefixData);2571  F->setPrefixData(prefix);2572}2573 2574LLVMValueRef LLVMGetPrologueData(LLVMValueRef Fn) {2575  Function *F = unwrap<Function>(Fn);2576  return wrap(F->getPrologueData());2577}2578 2579LLVMBool LLVMHasPrologueData(LLVMValueRef Fn) {2580  Function *F = unwrap<Function>(Fn);2581  return F->hasPrologueData();2582}2583 2584void LLVMSetPrologueData(LLVMValueRef Fn, LLVMValueRef prologueData) {2585  Function *F = unwrap<Function>(Fn);2586  Constant *prologue = unwrap<Constant>(prologueData);2587  F->setPrologueData(prologue);2588}2589 2590void LLVMAddAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,2591                             LLVMAttributeRef A) {2592  unwrap<Function>(F)->addAttributeAtIndex(Idx, unwrap(A));2593}2594 2595unsigned LLVMGetAttributeCountAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx) {2596  auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);2597  return AS.getNumAttributes();2598}2599 2600void LLVMGetAttributesAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,2601                              LLVMAttributeRef *Attrs) {2602  auto AS = unwrap<Function>(F)->getAttributes().getAttributes(Idx);2603  for (auto A : AS)2604    *Attrs++ = wrap(A);2605}2606 2607LLVMAttributeRef LLVMGetEnumAttributeAtIndex(LLVMValueRef F,2608                                             LLVMAttributeIndex Idx,2609                                             unsigned KindID) {2610  return wrap(unwrap<Function>(F)->getAttributeAtIndex(2611      Idx, (Attribute::AttrKind)KindID));2612}2613 2614LLVMAttributeRef LLVMGetStringAttributeAtIndex(LLVMValueRef F,2615                                               LLVMAttributeIndex Idx,2616                                               const char *K, unsigned KLen) {2617  return wrap(2618      unwrap<Function>(F)->getAttributeAtIndex(Idx, StringRef(K, KLen)));2619}2620 2621void LLVMRemoveEnumAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,2622                                    unsigned KindID) {2623  unwrap<Function>(F)->removeAttributeAtIndex(Idx, (Attribute::AttrKind)KindID);2624}2625 2626void LLVMRemoveStringAttributeAtIndex(LLVMValueRef F, LLVMAttributeIndex Idx,2627                                      const char *K, unsigned KLen) {2628  unwrap<Function>(F)->removeAttributeAtIndex(Idx, StringRef(K, KLen));2629}2630 2631void LLVMAddTargetDependentFunctionAttr(LLVMValueRef Fn, const char *A,2632                                        const char *V) {2633  Function *Func = unwrap<Function>(Fn);2634  Attribute Attr = Attribute::get(Func->getContext(), A, V);2635  Func->addFnAttr(Attr);2636}2637 2638/*--.. Operations on parameters ............................................--*/2639 2640unsigned LLVMCountParams(LLVMValueRef FnRef) {2641  // This function is strictly redundant to2642  //   LLVMCountParamTypes(LLVMGlobalGetValueType(FnRef))2643  return unwrap<Function>(FnRef)->arg_size();2644}2645 2646void LLVMGetParams(LLVMValueRef FnRef, LLVMValueRef *ParamRefs) {2647  Function *Fn = unwrap<Function>(FnRef);2648  for (Argument &A : Fn->args())2649    *ParamRefs++ = wrap(&A);2650}2651 2652LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {2653  Function *Fn = unwrap<Function>(FnRef);2654  return wrap(&Fn->arg_begin()[index]);2655}2656 2657LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {2658  return wrap(unwrap<Argument>(V)->getParent());2659}2660 2661LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn) {2662  Function *Func = unwrap<Function>(Fn);2663  Function::arg_iterator I = Func->arg_begin();2664  if (I == Func->arg_end())2665    return nullptr;2666  return wrap(&*I);2667}2668 2669LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {2670  Function *Func = unwrap<Function>(Fn);2671  Function::arg_iterator I = Func->arg_end();2672  if (I == Func->arg_begin())2673    return nullptr;2674  return wrap(&*--I);2675}2676 2677LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {2678  Argument *A = unwrap<Argument>(Arg);2679  Function *Fn = A->getParent();2680  if (A->getArgNo() + 1 >= Fn->arg_size())2681    return nullptr;2682  return wrap(&Fn->arg_begin()[A->getArgNo() + 1]);2683}2684 2685LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {2686  Argument *A = unwrap<Argument>(Arg);2687  if (A->getArgNo() == 0)2688    return nullptr;2689  return wrap(&A->getParent()->arg_begin()[A->getArgNo() - 1]);2690}2691 2692void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align) {2693  Argument *A = unwrap<Argument>(Arg);2694  A->addAttr(Attribute::getWithAlignment(A->getContext(), Align(align)));2695}2696 2697/*--.. Operations on ifuncs ................................................--*/2698 2699LLVMValueRef LLVMAddGlobalIFunc(LLVMModuleRef M,2700                                const char *Name, size_t NameLen,2701                                LLVMTypeRef Ty, unsigned AddrSpace,2702                                LLVMValueRef Resolver) {2703  return wrap(GlobalIFunc::create(unwrap(Ty), AddrSpace,2704                                  GlobalValue::ExternalLinkage,2705                                  StringRef(Name, NameLen),2706                                  unwrap<Constant>(Resolver), unwrap(M)));2707}2708 2709LLVMValueRef LLVMGetNamedGlobalIFunc(LLVMModuleRef M,2710                                     const char *Name, size_t NameLen) {2711  return wrap(unwrap(M)->getNamedIFunc(StringRef(Name, NameLen)));2712}2713 2714LLVMValueRef LLVMGetFirstGlobalIFunc(LLVMModuleRef M) {2715  Module *Mod = unwrap(M);2716  Module::ifunc_iterator I = Mod->ifunc_begin();2717  if (I == Mod->ifunc_end())2718    return nullptr;2719  return wrap(&*I);2720}2721 2722LLVMValueRef LLVMGetLastGlobalIFunc(LLVMModuleRef M) {2723  Module *Mod = unwrap(M);2724  Module::ifunc_iterator I = Mod->ifunc_end();2725  if (I == Mod->ifunc_begin())2726    return nullptr;2727  return wrap(&*--I);2728}2729 2730LLVMValueRef LLVMGetNextGlobalIFunc(LLVMValueRef IFunc) {2731  GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);2732  Module::ifunc_iterator I(GIF);2733  if (++I == GIF->getParent()->ifunc_end())2734    return nullptr;2735  return wrap(&*I);2736}2737 2738LLVMValueRef LLVMGetPreviousGlobalIFunc(LLVMValueRef IFunc) {2739  GlobalIFunc *GIF = unwrap<GlobalIFunc>(IFunc);2740  Module::ifunc_iterator I(GIF);2741  if (I == GIF->getParent()->ifunc_begin())2742    return nullptr;2743  return wrap(&*--I);2744}2745 2746LLVMValueRef LLVMGetGlobalIFuncResolver(LLVMValueRef IFunc) {2747  return wrap(unwrap<GlobalIFunc>(IFunc)->getResolver());2748}2749 2750void LLVMSetGlobalIFuncResolver(LLVMValueRef IFunc, LLVMValueRef Resolver) {2751  unwrap<GlobalIFunc>(IFunc)->setResolver(unwrap<Constant>(Resolver));2752}2753 2754void LLVMEraseGlobalIFunc(LLVMValueRef IFunc) {2755  unwrap<GlobalIFunc>(IFunc)->eraseFromParent();2756}2757 2758void LLVMRemoveGlobalIFunc(LLVMValueRef IFunc) {2759  unwrap<GlobalIFunc>(IFunc)->removeFromParent();2760}2761 2762/*--.. Operations on operand bundles........................................--*/2763 2764LLVMOperandBundleRef LLVMCreateOperandBundle(const char *Tag, size_t TagLen,2765                                             LLVMValueRef *Args,2766                                             unsigned NumArgs) {2767  return wrap(new OperandBundleDef(std::string(Tag, TagLen),2768                                   ArrayRef(unwrap(Args), NumArgs)));2769}2770 2771void LLVMDisposeOperandBundle(LLVMOperandBundleRef Bundle) {2772  delete unwrap(Bundle);2773}2774 2775const char *LLVMGetOperandBundleTag(LLVMOperandBundleRef Bundle, size_t *Len) {2776  StringRef Str = unwrap(Bundle)->getTag();2777  *Len = Str.size();2778  return Str.data();2779}2780 2781unsigned LLVMGetNumOperandBundleArgs(LLVMOperandBundleRef Bundle) {2782  return unwrap(Bundle)->inputs().size();2783}2784 2785LLVMValueRef LLVMGetOperandBundleArgAtIndex(LLVMOperandBundleRef Bundle,2786                                            unsigned Index) {2787  return wrap(unwrap(Bundle)->inputs()[Index]);2788}2789 2790/*--.. Operations on basic blocks ..........................................--*/2791 2792LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB) {2793  return wrap(static_cast<Value*>(unwrap(BB)));2794}2795 2796LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val) {2797  return isa<BasicBlock>(unwrap(Val));2798}2799 2800LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val) {2801  return wrap(unwrap<BasicBlock>(Val));2802}2803 2804const char *LLVMGetBasicBlockName(LLVMBasicBlockRef BB) {2805  return unwrap(BB)->getName().data();2806}2807 2808LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB) {2809  return wrap(unwrap(BB)->getParent());2810}2811 2812LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB) {2813  return wrap(unwrap(BB)->getTerminator());2814}2815 2816unsigned LLVMCountBasicBlocks(LLVMValueRef FnRef) {2817  return unwrap<Function>(FnRef)->size();2818}2819 2820void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){2821  Function *Fn = unwrap<Function>(FnRef);2822  for (BasicBlock &BB : *Fn)2823    *BasicBlocksRefs++ = wrap(&BB);2824}2825 2826LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {2827  return wrap(&unwrap<Function>(Fn)->getEntryBlock());2828}2829 2830LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn) {2831  Function *Func = unwrap<Function>(Fn);2832  Function::iterator I = Func->begin();2833  if (I == Func->end())2834    return nullptr;2835  return wrap(&*I);2836}2837 2838LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {2839  Function *Func = unwrap<Function>(Fn);2840  Function::iterator I = Func->end();2841  if (I == Func->begin())2842    return nullptr;2843  return wrap(&*--I);2844}2845 2846LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {2847  BasicBlock *Block = unwrap(BB);2848  Function::iterator I(Block);2849  if (++I == Block->getParent()->end())2850    return nullptr;2851  return wrap(&*I);2852}2853 2854LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {2855  BasicBlock *Block = unwrap(BB);2856  Function::iterator I(Block);2857  if (I == Block->getParent()->begin())2858    return nullptr;2859  return wrap(&*--I);2860}2861 2862LLVMBasicBlockRef LLVMCreateBasicBlockInContext(LLVMContextRef C,2863                                                const char *Name) {2864  return wrap(llvm::BasicBlock::Create(*unwrap(C), Name));2865}2866 2867void LLVMInsertExistingBasicBlockAfterInsertBlock(LLVMBuilderRef Builder,2868                                                  LLVMBasicBlockRef BB) {2869  BasicBlock *ToInsert = unwrap(BB);2870  BasicBlock *CurBB = unwrap(Builder)->GetInsertBlock();2871  assert(CurBB && "current insertion point is invalid!");2872  CurBB->getParent()->insert(std::next(CurBB->getIterator()), ToInsert);2873}2874 2875void LLVMAppendExistingBasicBlock(LLVMValueRef Fn,2876                                  LLVMBasicBlockRef BB) {2877  unwrap<Function>(Fn)->insert(unwrap<Function>(Fn)->end(), unwrap(BB));2878}2879 2880LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,2881                                                LLVMValueRef FnRef,2882                                                const char *Name) {2883  return wrap(BasicBlock::Create(*unwrap(C), Name, unwrap<Function>(FnRef)));2884}2885 2886LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef FnRef, const char *Name) {2887  return LLVMAppendBasicBlockInContext(LLVMGetGlobalContext(), FnRef, Name);2888}2889 2890LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C,2891                                                LLVMBasicBlockRef BBRef,2892                                                const char *Name) {2893  BasicBlock *BB = unwrap(BBRef);2894  return wrap(BasicBlock::Create(*unwrap(C), Name, BB->getParent(), BB));2895}2896 2897LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef BBRef,2898                                       const char *Name) {2899  return LLVMInsertBasicBlockInContext(LLVMGetGlobalContext(), BBRef, Name);2900}2901 2902void LLVMDeleteBasicBlock(LLVMBasicBlockRef BBRef) {2903  unwrap(BBRef)->eraseFromParent();2904}2905 2906void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BBRef) {2907  unwrap(BBRef)->removeFromParent();2908}2909 2910void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {2911  unwrap(BB)->moveBefore(unwrap(MovePos));2912}2913 2914void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos) {2915  unwrap(BB)->moveAfter(unwrap(MovePos));2916}2917 2918/*--.. Operations on instructions ..........................................--*/2919 2920LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst) {2921  return wrap(unwrap<Instruction>(Inst)->getParent());2922}2923 2924LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB) {2925  BasicBlock *Block = unwrap(BB);2926  BasicBlock::iterator I = Block->begin();2927  if (I == Block->end())2928    return nullptr;2929  return wrap(&*I);2930}2931 2932LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {2933  BasicBlock *Block = unwrap(BB);2934  BasicBlock::iterator I = Block->end();2935  if (I == Block->begin())2936    return nullptr;2937  return wrap(&*--I);2938}2939 2940LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {2941  Instruction *Instr = unwrap<Instruction>(Inst);2942  BasicBlock::iterator I(Instr);2943  if (++I == Instr->getParent()->end())2944    return nullptr;2945  return wrap(&*I);2946}2947 2948LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {2949  Instruction *Instr = unwrap<Instruction>(Inst);2950  BasicBlock::iterator I(Instr);2951  if (I == Instr->getParent()->begin())2952    return nullptr;2953  return wrap(&*--I);2954}2955 2956void LLVMInstructionRemoveFromParent(LLVMValueRef Inst) {2957  unwrap<Instruction>(Inst)->removeFromParent();2958}2959 2960void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {2961  unwrap<Instruction>(Inst)->eraseFromParent();2962}2963 2964void LLVMDeleteInstruction(LLVMValueRef Inst) {2965  unwrap<Instruction>(Inst)->deleteValue();2966}2967 2968LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst) {2969  if (ICmpInst *I = dyn_cast<ICmpInst>(unwrap(Inst)))2970    return (LLVMIntPredicate)I->getPredicate();2971  return (LLVMIntPredicate)0;2972}2973 2974LLVMBool LLVMGetICmpSameSign(LLVMValueRef Inst) {2975  return unwrap<ICmpInst>(Inst)->hasSameSign();2976}2977 2978void LLVMSetICmpSameSign(LLVMValueRef Inst, LLVMBool SameSign) {2979  unwrap<ICmpInst>(Inst)->setSameSign(SameSign);2980}2981 2982LLVMRealPredicate LLVMGetFCmpPredicate(LLVMValueRef Inst) {2983  if (FCmpInst *I = dyn_cast<FCmpInst>(unwrap(Inst)))2984    return (LLVMRealPredicate)I->getPredicate();2985  return (LLVMRealPredicate)0;2986}2987 2988LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst) {2989  if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))2990    return map_to_llvmopcode(C->getOpcode());2991  return (LLVMOpcode)0;2992}2993 2994LLVMValueRef LLVMInstructionClone(LLVMValueRef Inst) {2995  if (Instruction *C = dyn_cast<Instruction>(unwrap(Inst)))2996    return wrap(C->clone());2997  return nullptr;2998}2999 3000LLVMValueRef LLVMIsATerminatorInst(LLVMValueRef Inst) {3001  Instruction *I = dyn_cast<Instruction>(unwrap(Inst));3002  return (I && I->isTerminator()) ? wrap(I) : nullptr;3003}3004 3005LLVMDbgRecordRef LLVMGetFirstDbgRecord(LLVMValueRef Inst) {3006  Instruction *Instr = unwrap<Instruction>(Inst);3007  if (!Instr->DebugMarker)3008    return nullptr;3009  auto I = Instr->DebugMarker->StoredDbgRecords.begin();3010  if (I == Instr->DebugMarker->StoredDbgRecords.end())3011    return nullptr;3012  return wrap(&*I);3013}3014 3015LLVMDbgRecordRef LLVMGetLastDbgRecord(LLVMValueRef Inst) {3016  Instruction *Instr = unwrap<Instruction>(Inst);3017  if (!Instr->DebugMarker)3018    return nullptr;3019  auto I = Instr->DebugMarker->StoredDbgRecords.rbegin();3020  if (I == Instr->DebugMarker->StoredDbgRecords.rend())3021    return nullptr;3022  return wrap(&*I);3023}3024 3025LLVMDbgRecordRef LLVMGetNextDbgRecord(LLVMDbgRecordRef Rec) {3026  DbgRecord *Record = unwrap<DbgRecord>(Rec);3027  simple_ilist<DbgRecord>::iterator I(Record);3028  if (++I == Record->getInstruction()->DebugMarker->StoredDbgRecords.end())3029    return nullptr;3030  return wrap(&*I);3031}3032 3033LLVMDbgRecordRef LLVMGetPreviousDbgRecord(LLVMDbgRecordRef Rec) {3034  DbgRecord *Record = unwrap<DbgRecord>(Rec);3035  simple_ilist<DbgRecord>::iterator I(Record);3036  if (I == Record->getInstruction()->DebugMarker->StoredDbgRecords.begin())3037    return nullptr;3038  return wrap(&*--I);3039}3040 3041LLVMMetadataRef LLVMDbgRecordGetDebugLoc(LLVMDbgRecordRef Rec) {3042  return wrap(unwrap<DbgRecord>(Rec)->getDebugLoc().getAsMDNode());3043}3044 3045LLVMDbgRecordKind LLVMDbgRecordGetKind(LLVMDbgRecordRef Rec) {3046  DbgRecord *Record = unwrap<DbgRecord>(Rec);3047  if (isa<DbgLabelRecord>(Record))3048    return LLVMDbgRecordLabel;3049  DbgVariableRecord *VariableRecord = dyn_cast<DbgVariableRecord>(Record);3050  assert(VariableRecord && "unexpected record");3051  if (VariableRecord->isDbgDeclare())3052    return LLVMDbgRecordDeclare;3053  if (VariableRecord->isDbgValue())3054    return LLVMDbgRecordValue;3055  assert(VariableRecord->isDbgAssign() && "unexpected record");3056  return LLVMDbgRecordAssign;3057}3058 3059LLVMValueRef LLVMDbgVariableRecordGetValue(LLVMDbgRecordRef Rec,3060                                           unsigned OpIdx) {3061  return wrap(unwrap<DbgVariableRecord>(Rec)->getValue(OpIdx));3062}3063 3064LLVMMetadataRef LLVMDbgVariableRecordGetVariable(LLVMDbgRecordRef Rec) {3065  return wrap(unwrap<DbgVariableRecord>(Rec)->getRawVariable());3066}3067 3068LLVMMetadataRef LLVMDbgVariableRecordGetExpression(LLVMDbgRecordRef Rec) {3069  return wrap(unwrap<DbgVariableRecord>(Rec)->getRawExpression());3070}3071 3072unsigned LLVMGetNumArgOperands(LLVMValueRef Instr) {3073  if (FuncletPadInst *FPI = dyn_cast<FuncletPadInst>(unwrap(Instr))) {3074    return FPI->arg_size();3075  }3076  return unwrap<CallBase>(Instr)->arg_size();3077}3078 3079/*--.. Call and invoke instructions ........................................--*/3080 3081unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr) {3082  return unwrap<CallBase>(Instr)->getCallingConv();3083}3084 3085void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC) {3086  return unwrap<CallBase>(Instr)->setCallingConv(3087      static_cast<CallingConv::ID>(CC));3088}3089 3090void LLVMSetInstrParamAlignment(LLVMValueRef Instr, LLVMAttributeIndex Idx,3091                                unsigned align) {3092  auto *Call = unwrap<CallBase>(Instr);3093  Attribute AlignAttr =3094      Attribute::getWithAlignment(Call->getContext(), Align(align));3095  Call->addAttributeAtIndex(Idx, AlignAttr);3096}3097 3098void LLVMAddCallSiteAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,3099                              LLVMAttributeRef A) {3100  unwrap<CallBase>(C)->addAttributeAtIndex(Idx, unwrap(A));3101}3102 3103unsigned LLVMGetCallSiteAttributeCount(LLVMValueRef C,3104                                       LLVMAttributeIndex Idx) {3105  auto *Call = unwrap<CallBase>(C);3106  auto AS = Call->getAttributes().getAttributes(Idx);3107  return AS.getNumAttributes();3108}3109 3110void LLVMGetCallSiteAttributes(LLVMValueRef C, LLVMAttributeIndex Idx,3111                               LLVMAttributeRef *Attrs) {3112  auto *Call = unwrap<CallBase>(C);3113  auto AS = Call->getAttributes().getAttributes(Idx);3114  for (auto A : AS)3115    *Attrs++ = wrap(A);3116}3117 3118LLVMAttributeRef LLVMGetCallSiteEnumAttribute(LLVMValueRef C,3119                                              LLVMAttributeIndex Idx,3120                                              unsigned KindID) {3121  return wrap(unwrap<CallBase>(C)->getAttributeAtIndex(3122      Idx, (Attribute::AttrKind)KindID));3123}3124 3125LLVMAttributeRef LLVMGetCallSiteStringAttribute(LLVMValueRef C,3126                                                LLVMAttributeIndex Idx,3127                                                const char *K, unsigned KLen) {3128  return wrap(3129      unwrap<CallBase>(C)->getAttributeAtIndex(Idx, StringRef(K, KLen)));3130}3131 3132void LLVMRemoveCallSiteEnumAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,3133                                     unsigned KindID) {3134  unwrap<CallBase>(C)->removeAttributeAtIndex(Idx, (Attribute::AttrKind)KindID);3135}3136 3137void LLVMRemoveCallSiteStringAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,3138                                       const char *K, unsigned KLen) {3139  unwrap<CallBase>(C)->removeAttributeAtIndex(Idx, StringRef(K, KLen));3140}3141 3142LLVMValueRef LLVMGetCalledValue(LLVMValueRef Instr) {3143  return wrap(unwrap<CallBase>(Instr)->getCalledOperand());3144}3145 3146LLVMTypeRef LLVMGetCalledFunctionType(LLVMValueRef Instr) {3147  return wrap(unwrap<CallBase>(Instr)->getFunctionType());3148}3149 3150unsigned LLVMGetNumOperandBundles(LLVMValueRef C) {3151  return unwrap<CallBase>(C)->getNumOperandBundles();3152}3153 3154LLVMOperandBundleRef LLVMGetOperandBundleAtIndex(LLVMValueRef C,3155                                                 unsigned Index) {3156  return wrap(3157      new OperandBundleDef(unwrap<CallBase>(C)->getOperandBundleAt(Index)));3158}3159 3160/*--.. Operations on call instructions (only) ..............................--*/3161 3162LLVMBool LLVMIsTailCall(LLVMValueRef Call) {3163  return unwrap<CallInst>(Call)->isTailCall();3164}3165 3166void LLVMSetTailCall(LLVMValueRef Call, LLVMBool isTailCall) {3167  unwrap<CallInst>(Call)->setTailCall(isTailCall);3168}3169 3170LLVMTailCallKind LLVMGetTailCallKind(LLVMValueRef Call) {3171  return (LLVMTailCallKind)unwrap<CallInst>(Call)->getTailCallKind();3172}3173 3174void LLVMSetTailCallKind(LLVMValueRef Call, LLVMTailCallKind kind) {3175  unwrap<CallInst>(Call)->setTailCallKind((CallInst::TailCallKind)kind);3176}3177 3178/*--.. Operations on invoke instructions (only) ............................--*/3179 3180LLVMBasicBlockRef LLVMGetNormalDest(LLVMValueRef Invoke) {3181  return wrap(unwrap<InvokeInst>(Invoke)->getNormalDest());3182}3183 3184LLVMBasicBlockRef LLVMGetUnwindDest(LLVMValueRef Invoke) {3185  if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {3186    return wrap(CRI->getUnwindDest());3187  } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {3188    return wrap(CSI->getUnwindDest());3189  }3190  return wrap(unwrap<InvokeInst>(Invoke)->getUnwindDest());3191}3192 3193void LLVMSetNormalDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {3194  unwrap<InvokeInst>(Invoke)->setNormalDest(unwrap(B));3195}3196 3197void LLVMSetUnwindDest(LLVMValueRef Invoke, LLVMBasicBlockRef B) {3198  if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(unwrap(Invoke))) {3199    return CRI->setUnwindDest(unwrap(B));3200  } else if (CatchSwitchInst *CSI = dyn_cast<CatchSwitchInst>(unwrap(Invoke))) {3201    return CSI->setUnwindDest(unwrap(B));3202  }3203  unwrap<InvokeInst>(Invoke)->setUnwindDest(unwrap(B));3204}3205 3206LLVMBasicBlockRef LLVMGetCallBrDefaultDest(LLVMValueRef CallBr) {3207  return wrap(unwrap<CallBrInst>(CallBr)->getDefaultDest());3208}3209 3210unsigned LLVMGetCallBrNumIndirectDests(LLVMValueRef CallBr) {3211  return unwrap<CallBrInst>(CallBr)->getNumIndirectDests();3212}3213 3214LLVMBasicBlockRef LLVMGetCallBrIndirectDest(LLVMValueRef CallBr, unsigned Idx) {3215  return wrap(unwrap<CallBrInst>(CallBr)->getIndirectDest(Idx));3216}3217 3218/*--.. Operations on terminators ...........................................--*/3219 3220unsigned LLVMGetNumSuccessors(LLVMValueRef Term) {3221  return unwrap<Instruction>(Term)->getNumSuccessors();3222}3223 3224LLVMBasicBlockRef LLVMGetSuccessor(LLVMValueRef Term, unsigned i) {3225  return wrap(unwrap<Instruction>(Term)->getSuccessor(i));3226}3227 3228void LLVMSetSuccessor(LLVMValueRef Term, unsigned i, LLVMBasicBlockRef block) {3229  return unwrap<Instruction>(Term)->setSuccessor(i, unwrap(block));3230}3231 3232/*--.. Operations on branch instructions (only) ............................--*/3233 3234LLVMBool LLVMIsConditional(LLVMValueRef Branch) {3235  return unwrap<BranchInst>(Branch)->isConditional();3236}3237 3238LLVMValueRef LLVMGetCondition(LLVMValueRef Branch) {3239  return wrap(unwrap<BranchInst>(Branch)->getCondition());3240}3241 3242void LLVMSetCondition(LLVMValueRef Branch, LLVMValueRef Cond) {3243  return unwrap<BranchInst>(Branch)->setCondition(unwrap(Cond));3244}3245 3246/*--.. Operations on switch instructions (only) ............................--*/3247 3248LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef Switch) {3249  return wrap(unwrap<SwitchInst>(Switch)->getDefaultDest());3250}3251 3252/*--.. Operations on alloca instructions (only) ............................--*/3253 3254LLVMTypeRef LLVMGetAllocatedType(LLVMValueRef Alloca) {3255  return wrap(unwrap<AllocaInst>(Alloca)->getAllocatedType());3256}3257 3258/*--.. Operations on gep instructions (only) ...............................--*/3259 3260LLVMBool LLVMIsInBounds(LLVMValueRef GEP) {3261  return unwrap<GEPOperator>(GEP)->isInBounds();3262}3263 3264void LLVMSetIsInBounds(LLVMValueRef GEP, LLVMBool InBounds) {3265  return unwrap<GetElementPtrInst>(GEP)->setIsInBounds(InBounds);3266}3267 3268LLVMTypeRef LLVMGetGEPSourceElementType(LLVMValueRef GEP) {3269  return wrap(unwrap<GEPOperator>(GEP)->getSourceElementType());3270}3271 3272LLVMGEPNoWrapFlags LLVMGEPGetNoWrapFlags(LLVMValueRef GEP) {3273  GEPOperator *GEPOp = unwrap<GEPOperator>(GEP);3274  return mapToLLVMGEPNoWrapFlags(GEPOp->getNoWrapFlags());3275}3276 3277void LLVMGEPSetNoWrapFlags(LLVMValueRef GEP, LLVMGEPNoWrapFlags NoWrapFlags) {3278  GetElementPtrInst *GEPInst = unwrap<GetElementPtrInst>(GEP);3279  GEPInst->setNoWrapFlags(mapFromLLVMGEPNoWrapFlags(NoWrapFlags));3280}3281 3282/*--.. Operations on phi nodes .............................................--*/3283 3284void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues,3285                     LLVMBasicBlockRef *IncomingBlocks, unsigned Count) {3286  PHINode *PhiVal = unwrap<PHINode>(PhiNode);3287  for (unsigned I = 0; I != Count; ++I)3288    PhiVal->addIncoming(unwrap(IncomingValues[I]), unwrap(IncomingBlocks[I]));3289}3290 3291unsigned LLVMCountIncoming(LLVMValueRef PhiNode) {3292  return unwrap<PHINode>(PhiNode)->getNumIncomingValues();3293}3294 3295LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index) {3296  return wrap(unwrap<PHINode>(PhiNode)->getIncomingValue(Index));3297}3298 3299LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index) {3300  return wrap(unwrap<PHINode>(PhiNode)->getIncomingBlock(Index));3301}3302 3303/*--.. Operations on extractvalue and insertvalue nodes ....................--*/3304 3305unsigned LLVMGetNumIndices(LLVMValueRef Inst) {3306  auto *I = unwrap(Inst);3307  if (auto *GEP = dyn_cast<GEPOperator>(I))3308    return GEP->getNumIndices();3309  if (auto *EV = dyn_cast<ExtractValueInst>(I))3310    return EV->getNumIndices();3311  if (auto *IV = dyn_cast<InsertValueInst>(I))3312    return IV->getNumIndices();3313  llvm_unreachable(3314    "LLVMGetNumIndices applies only to extractvalue and insertvalue!");3315}3316 3317const unsigned *LLVMGetIndices(LLVMValueRef Inst) {3318  auto *I = unwrap(Inst);3319  if (auto *EV = dyn_cast<ExtractValueInst>(I))3320    return EV->getIndices().data();3321  if (auto *IV = dyn_cast<InsertValueInst>(I))3322    return IV->getIndices().data();3323  llvm_unreachable(3324    "LLVMGetIndices applies only to extractvalue and insertvalue!");3325}3326 3327 3328/*===-- Instruction builders ----------------------------------------------===*/3329 3330LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C) {3331  return wrap(new IRBuilder<>(*unwrap(C)));3332}3333 3334LLVMBuilderRef LLVMCreateBuilder(void) {3335  return LLVMCreateBuilderInContext(LLVMGetGlobalContext());3336}3337 3338static void LLVMPositionBuilderImpl(IRBuilder<> *Builder, BasicBlock *Block,3339                                    Instruction *Instr, bool BeforeDbgRecords) {3340  BasicBlock::iterator I = Instr ? Instr->getIterator() : Block->end();3341  I.setHeadBit(BeforeDbgRecords);3342  Builder->SetInsertPoint(Block, I);3343}3344 3345void LLVMPositionBuilder(LLVMBuilderRef Builder, LLVMBasicBlockRef Block,3346                         LLVMValueRef Instr) {3347  return LLVMPositionBuilderImpl(unwrap(Builder), unwrap(Block),3348                                 unwrap<Instruction>(Instr), false);3349}3350 3351void LLVMPositionBuilderBeforeDbgRecords(LLVMBuilderRef Builder,3352                                         LLVMBasicBlockRef Block,3353                                         LLVMValueRef Instr) {3354  return LLVMPositionBuilderImpl(unwrap(Builder), unwrap(Block),3355                                 unwrap<Instruction>(Instr), true);3356}3357 3358void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) {3359  Instruction *I = unwrap<Instruction>(Instr);3360  return LLVMPositionBuilderImpl(unwrap(Builder), I->getParent(), I, false);3361}3362 3363void LLVMPositionBuilderBeforeInstrAndDbgRecords(LLVMBuilderRef Builder,3364                                                 LLVMValueRef Instr) {3365  Instruction *I = unwrap<Instruction>(Instr);3366  return LLVMPositionBuilderImpl(unwrap(Builder), I->getParent(), I, true);3367}3368 3369void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) {3370  BasicBlock *BB = unwrap(Block);3371  unwrap(Builder)->SetInsertPoint(BB);3372}3373 3374LLVMBasicBlockRef LLVMGetInsertBlock(LLVMBuilderRef Builder) {3375   return wrap(unwrap(Builder)->GetInsertBlock());3376}3377 3378void LLVMClearInsertionPosition(LLVMBuilderRef Builder) {3379  unwrap(Builder)->ClearInsertionPoint();3380}3381 3382void LLVMInsertIntoBuilder(LLVMBuilderRef Builder, LLVMValueRef Instr) {3383  unwrap(Builder)->Insert(unwrap<Instruction>(Instr));3384}3385 3386void LLVMInsertIntoBuilderWithName(LLVMBuilderRef Builder, LLVMValueRef Instr,3387                                   const char *Name) {3388  unwrap(Builder)->Insert(unwrap<Instruction>(Instr), Name);3389}3390 3391void LLVMDisposeBuilder(LLVMBuilderRef Builder) {3392  delete unwrap(Builder);3393}3394 3395/*--.. Metadata builders ...................................................--*/3396 3397LLVMMetadataRef LLVMGetCurrentDebugLocation2(LLVMBuilderRef Builder) {3398  return wrap(unwrap(Builder)->getCurrentDebugLocation().getAsMDNode());3399}3400 3401void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Builder, LLVMMetadataRef Loc) {3402  if (Loc)3403    unwrap(Builder)->SetCurrentDebugLocation(DebugLoc(unwrap<MDNode>(Loc)));3404  else3405    unwrap(Builder)->SetCurrentDebugLocation(DebugLoc());3406}3407 3408void LLVMSetCurrentDebugLocation(LLVMBuilderRef Builder, LLVMValueRef L) {3409  MDNode *Loc =3410      L ? cast<MDNode>(unwrap<MetadataAsValue>(L)->getMetadata()) : nullptr;3411  unwrap(Builder)->SetCurrentDebugLocation(DebugLoc(Loc));3412}3413 3414LLVMValueRef LLVMGetCurrentDebugLocation(LLVMBuilderRef Builder) {3415  LLVMContext &Context = unwrap(Builder)->getContext();3416  return wrap(MetadataAsValue::get(3417      Context, unwrap(Builder)->getCurrentDebugLocation().getAsMDNode()));3418}3419 3420void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst) {3421  unwrap(Builder)->SetInstDebugLocation(unwrap<Instruction>(Inst));3422}3423 3424void LLVMAddMetadataToInst(LLVMBuilderRef Builder, LLVMValueRef Inst) {3425  unwrap(Builder)->AddMetadataToInst(unwrap<Instruction>(Inst));3426}3427 3428void LLVMBuilderSetDefaultFPMathTag(LLVMBuilderRef Builder,3429                                    LLVMMetadataRef FPMathTag) {3430 3431  unwrap(Builder)->setDefaultFPMathTag(FPMathTag3432                                       ? unwrap<MDNode>(FPMathTag)3433                                       : nullptr);3434}3435 3436LLVMContextRef LLVMGetBuilderContext(LLVMBuilderRef Builder) {3437  return wrap(&unwrap(Builder)->getContext());3438}3439 3440LLVMMetadataRef LLVMBuilderGetDefaultFPMathTag(LLVMBuilderRef Builder) {3441  return wrap(unwrap(Builder)->getDefaultFPMathTag());3442}3443 3444/*--.. Instruction builders ................................................--*/3445 3446LLVMValueRef LLVMBuildRetVoid(LLVMBuilderRef B) {3447  return wrap(unwrap(B)->CreateRetVoid());3448}3449 3450LLVMValueRef LLVMBuildRet(LLVMBuilderRef B, LLVMValueRef V) {3451  return wrap(unwrap(B)->CreateRet(unwrap(V)));3452}3453 3454LLVMValueRef LLVMBuildAggregateRet(LLVMBuilderRef B, LLVMValueRef *RetVals,3455                                   unsigned N) {3456  return wrap(unwrap(B)->CreateAggregateRet(unwrap(RetVals), N));3457}3458 3459LLVMValueRef LLVMBuildBr(LLVMBuilderRef B, LLVMBasicBlockRef Dest) {3460  return wrap(unwrap(B)->CreateBr(unwrap(Dest)));3461}3462 3463LLVMValueRef LLVMBuildCondBr(LLVMBuilderRef B, LLVMValueRef If,3464                             LLVMBasicBlockRef Then, LLVMBasicBlockRef Else) {3465  return wrap(unwrap(B)->CreateCondBr(unwrap(If), unwrap(Then), unwrap(Else)));3466}3467 3468LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef B, LLVMValueRef V,3469                             LLVMBasicBlockRef Else, unsigned NumCases) {3470  return wrap(unwrap(B)->CreateSwitch(unwrap(V), unwrap(Else), NumCases));3471}3472 3473LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr,3474                                 unsigned NumDests) {3475  return wrap(unwrap(B)->CreateIndirectBr(unwrap(Addr), NumDests));3476}3477 3478LLVMValueRef LLVMBuildCallBr(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,3479                             LLVMBasicBlockRef DefaultDest,3480                             LLVMBasicBlockRef *IndirectDests,3481                             unsigned NumIndirectDests, LLVMValueRef *Args,3482                             unsigned NumArgs, LLVMOperandBundleRef *Bundles,3483                             unsigned NumBundles, const char *Name) {3484 3485  SmallVector<OperandBundleDef, 8> OBs;3486  for (auto *Bundle : ArrayRef(Bundles, NumBundles)) {3487    OperandBundleDef *OB = unwrap(Bundle);3488    OBs.push_back(*OB);3489  }3490 3491  return wrap(unwrap(B)->CreateCallBr(3492      unwrap<FunctionType>(Ty), unwrap(Fn), unwrap(DefaultDest),3493      ArrayRef(unwrap(IndirectDests), NumIndirectDests),3494      ArrayRef<Value *>(unwrap(Args), NumArgs), OBs, Name));3495}3496 3497LLVMValueRef LLVMBuildInvoke2(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,3498                              LLVMValueRef *Args, unsigned NumArgs,3499                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,3500                              const char *Name) {3501  return wrap(unwrap(B)->CreateInvoke(unwrap<FunctionType>(Ty), unwrap(Fn),3502                                      unwrap(Then), unwrap(Catch),3503                                      ArrayRef(unwrap(Args), NumArgs), Name));3504}3505 3506LLVMValueRef LLVMBuildInvokeWithOperandBundles(3507    LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn, LLVMValueRef *Args,3508    unsigned NumArgs, LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,3509    LLVMOperandBundleRef *Bundles, unsigned NumBundles, const char *Name) {3510  SmallVector<OperandBundleDef, 8> OBs;3511  for (auto *Bundle : ArrayRef(Bundles, NumBundles)) {3512    OperandBundleDef *OB = unwrap(Bundle);3513    OBs.push_back(*OB);3514  }3515  return wrap(unwrap(B)->CreateInvoke(3516      unwrap<FunctionType>(Ty), unwrap(Fn), unwrap(Then), unwrap(Catch),3517      ArrayRef(unwrap(Args), NumArgs), OBs, Name));3518}3519 3520LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,3521                                 LLVMValueRef PersFn, unsigned NumClauses,3522                                 const char *Name) {3523  // The personality used to live on the landingpad instruction, but now it3524  // lives on the parent function. For compatibility, take the provided3525  // personality and put it on the parent function.3526  if (PersFn)3527    unwrap(B)->GetInsertBlock()->getParent()->setPersonalityFn(3528        unwrap<Function>(PersFn));3529  return wrap(unwrap(B)->CreateLandingPad(unwrap(Ty), NumClauses, Name));3530}3531 3532LLVMValueRef LLVMBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,3533                               LLVMValueRef *Args, unsigned NumArgs,3534                               const char *Name) {3535  return wrap(unwrap(B)->CreateCatchPad(unwrap(ParentPad),3536                                        ArrayRef(unwrap(Args), NumArgs), Name));3537}3538 3539LLVMValueRef LLVMBuildCleanupPad(LLVMBuilderRef B, LLVMValueRef ParentPad,3540                                 LLVMValueRef *Args, unsigned NumArgs,3541                                 const char *Name) {3542  if (ParentPad == nullptr) {3543    Type *Ty = Type::getTokenTy(unwrap(B)->getContext());3544    ParentPad = wrap(Constant::getNullValue(Ty));3545  }3546  return wrap(unwrap(B)->CreateCleanupPad(3547      unwrap(ParentPad), ArrayRef(unwrap(Args), NumArgs), Name));3548}3549 3550LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn) {3551  return wrap(unwrap(B)->CreateResume(unwrap(Exn)));3552}3553 3554LLVMValueRef LLVMBuildCatchSwitch(LLVMBuilderRef B, LLVMValueRef ParentPad,3555                                  LLVMBasicBlockRef UnwindBB,3556                                  unsigned NumHandlers, const char *Name) {3557  if (ParentPad == nullptr) {3558    Type *Ty = Type::getTokenTy(unwrap(B)->getContext());3559    ParentPad = wrap(Constant::getNullValue(Ty));3560  }3561  return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(UnwindBB),3562                                           NumHandlers, Name));3563}3564 3565LLVMValueRef LLVMBuildCatchRet(LLVMBuilderRef B, LLVMValueRef CatchPad,3566                               LLVMBasicBlockRef BB) {3567  return wrap(unwrap(B)->CreateCatchRet(unwrap<CatchPadInst>(CatchPad),3568                                        unwrap(BB)));3569}3570 3571LLVMValueRef LLVMBuildCleanupRet(LLVMBuilderRef B, LLVMValueRef CatchPad,3572                                 LLVMBasicBlockRef BB) {3573  return wrap(unwrap(B)->CreateCleanupRet(unwrap<CleanupPadInst>(CatchPad),3574                                          unwrap(BB)));3575}3576 3577LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef B) {3578  return wrap(unwrap(B)->CreateUnreachable());3579}3580 3581void LLVMAddCase(LLVMValueRef Switch, LLVMValueRef OnVal,3582                 LLVMBasicBlockRef Dest) {3583  unwrap<SwitchInst>(Switch)->addCase(unwrap<ConstantInt>(OnVal), unwrap(Dest));3584}3585 3586void LLVMAddDestination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest) {3587  unwrap<IndirectBrInst>(IndirectBr)->addDestination(unwrap(Dest));3588}3589 3590unsigned LLVMGetNumClauses(LLVMValueRef LandingPad) {3591  return unwrap<LandingPadInst>(LandingPad)->getNumClauses();3592}3593 3594LLVMValueRef LLVMGetClause(LLVMValueRef LandingPad, unsigned Idx) {3595  return wrap(unwrap<LandingPadInst>(LandingPad)->getClause(Idx));3596}3597 3598void LLVMAddClause(LLVMValueRef LandingPad, LLVMValueRef ClauseVal) {3599  unwrap<LandingPadInst>(LandingPad)->addClause(unwrap<Constant>(ClauseVal));3600}3601 3602LLVMBool LLVMIsCleanup(LLVMValueRef LandingPad) {3603  return unwrap<LandingPadInst>(LandingPad)->isCleanup();3604}3605 3606void LLVMSetCleanup(LLVMValueRef LandingPad, LLVMBool Val) {3607  unwrap<LandingPadInst>(LandingPad)->setCleanup(Val);3608}3609 3610void LLVMAddHandler(LLVMValueRef CatchSwitch, LLVMBasicBlockRef Dest) {3611  unwrap<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Dest));3612}3613 3614unsigned LLVMGetNumHandlers(LLVMValueRef CatchSwitch) {3615  return unwrap<CatchSwitchInst>(CatchSwitch)->getNumHandlers();3616}3617 3618void LLVMGetHandlers(LLVMValueRef CatchSwitch, LLVMBasicBlockRef *Handlers) {3619  CatchSwitchInst *CSI = unwrap<CatchSwitchInst>(CatchSwitch);3620  for (const BasicBlock *H : CSI->handlers())3621    *Handlers++ = wrap(H);3622}3623 3624LLVMValueRef LLVMGetParentCatchSwitch(LLVMValueRef CatchPad) {3625  return wrap(unwrap<CatchPadInst>(CatchPad)->getCatchSwitch());3626}3627 3628void LLVMSetParentCatchSwitch(LLVMValueRef CatchPad, LLVMValueRef CatchSwitch) {3629  unwrap<CatchPadInst>(CatchPad)3630    ->setCatchSwitch(unwrap<CatchSwitchInst>(CatchSwitch));3631}3632 3633/*--.. Funclets ...........................................................--*/3634 3635LLVMValueRef LLVMGetArgOperand(LLVMValueRef Funclet, unsigned i) {3636  return wrap(unwrap<FuncletPadInst>(Funclet)->getArgOperand(i));3637}3638 3639void LLVMSetArgOperand(LLVMValueRef Funclet, unsigned i, LLVMValueRef value) {3640  unwrap<FuncletPadInst>(Funclet)->setArgOperand(i, unwrap(value));3641}3642 3643/*--.. Arithmetic ..........................................................--*/3644 3645static FastMathFlags mapFromLLVMFastMathFlags(LLVMFastMathFlags FMF) {3646  FastMathFlags NewFMF;3647  NewFMF.setAllowReassoc((FMF & LLVMFastMathAllowReassoc) != 0);3648  NewFMF.setNoNaNs((FMF & LLVMFastMathNoNaNs) != 0);3649  NewFMF.setNoInfs((FMF & LLVMFastMathNoInfs) != 0);3650  NewFMF.setNoSignedZeros((FMF & LLVMFastMathNoSignedZeros) != 0);3651  NewFMF.setAllowReciprocal((FMF & LLVMFastMathAllowReciprocal) != 0);3652  NewFMF.setAllowContract((FMF & LLVMFastMathAllowContract) != 0);3653  NewFMF.setApproxFunc((FMF & LLVMFastMathApproxFunc) != 0);3654 3655  return NewFMF;3656}3657 3658static LLVMFastMathFlags mapToLLVMFastMathFlags(FastMathFlags FMF) {3659  LLVMFastMathFlags NewFMF = LLVMFastMathNone;3660  if (FMF.allowReassoc())3661    NewFMF |= LLVMFastMathAllowReassoc;3662  if (FMF.noNaNs())3663    NewFMF |= LLVMFastMathNoNaNs;3664  if (FMF.noInfs())3665    NewFMF |= LLVMFastMathNoInfs;3666  if (FMF.noSignedZeros())3667    NewFMF |= LLVMFastMathNoSignedZeros;3668  if (FMF.allowReciprocal())3669    NewFMF |= LLVMFastMathAllowReciprocal;3670  if (FMF.allowContract())3671    NewFMF |= LLVMFastMathAllowContract;3672  if (FMF.approxFunc())3673    NewFMF |= LLVMFastMathApproxFunc;3674 3675  return NewFMF;3676}3677 3678LLVMValueRef LLVMBuildAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3679                          const char *Name) {3680  return wrap(unwrap(B)->CreateAdd(unwrap(LHS), unwrap(RHS), Name));3681}3682 3683LLVMValueRef LLVMBuildNSWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3684                          const char *Name) {3685  return wrap(unwrap(B)->CreateNSWAdd(unwrap(LHS), unwrap(RHS), Name));3686}3687 3688LLVMValueRef LLVMBuildNUWAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3689                          const char *Name) {3690  return wrap(unwrap(B)->CreateNUWAdd(unwrap(LHS), unwrap(RHS), Name));3691}3692 3693LLVMValueRef LLVMBuildFAdd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3694                          const char *Name) {3695  return wrap(unwrap(B)->CreateFAdd(unwrap(LHS), unwrap(RHS), Name));3696}3697 3698LLVMValueRef LLVMBuildSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3699                          const char *Name) {3700  return wrap(unwrap(B)->CreateSub(unwrap(LHS), unwrap(RHS), Name));3701}3702 3703LLVMValueRef LLVMBuildNSWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3704                          const char *Name) {3705  return wrap(unwrap(B)->CreateNSWSub(unwrap(LHS), unwrap(RHS), Name));3706}3707 3708LLVMValueRef LLVMBuildNUWSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3709                          const char *Name) {3710  return wrap(unwrap(B)->CreateNUWSub(unwrap(LHS), unwrap(RHS), Name));3711}3712 3713LLVMValueRef LLVMBuildFSub(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3714                          const char *Name) {3715  return wrap(unwrap(B)->CreateFSub(unwrap(LHS), unwrap(RHS), Name));3716}3717 3718LLVMValueRef LLVMBuildMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3719                          const char *Name) {3720  return wrap(unwrap(B)->CreateMul(unwrap(LHS), unwrap(RHS), Name));3721}3722 3723LLVMValueRef LLVMBuildNSWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3724                          const char *Name) {3725  return wrap(unwrap(B)->CreateNSWMul(unwrap(LHS), unwrap(RHS), Name));3726}3727 3728LLVMValueRef LLVMBuildNUWMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3729                          const char *Name) {3730  return wrap(unwrap(B)->CreateNUWMul(unwrap(LHS), unwrap(RHS), Name));3731}3732 3733LLVMValueRef LLVMBuildFMul(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3734                          const char *Name) {3735  return wrap(unwrap(B)->CreateFMul(unwrap(LHS), unwrap(RHS), Name));3736}3737 3738LLVMValueRef LLVMBuildUDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3739                           const char *Name) {3740  return wrap(unwrap(B)->CreateUDiv(unwrap(LHS), unwrap(RHS), Name));3741}3742 3743LLVMValueRef LLVMBuildExactUDiv(LLVMBuilderRef B, LLVMValueRef LHS,3744                                LLVMValueRef RHS, const char *Name) {3745  return wrap(unwrap(B)->CreateExactUDiv(unwrap(LHS), unwrap(RHS), Name));3746}3747 3748LLVMValueRef LLVMBuildSDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3749                           const char *Name) {3750  return wrap(unwrap(B)->CreateSDiv(unwrap(LHS), unwrap(RHS), Name));3751}3752 3753LLVMValueRef LLVMBuildExactSDiv(LLVMBuilderRef B, LLVMValueRef LHS,3754                                LLVMValueRef RHS, const char *Name) {3755  return wrap(unwrap(B)->CreateExactSDiv(unwrap(LHS), unwrap(RHS), Name));3756}3757 3758LLVMValueRef LLVMBuildFDiv(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3759                           const char *Name) {3760  return wrap(unwrap(B)->CreateFDiv(unwrap(LHS), unwrap(RHS), Name));3761}3762 3763LLVMValueRef LLVMBuildURem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3764                           const char *Name) {3765  return wrap(unwrap(B)->CreateURem(unwrap(LHS), unwrap(RHS), Name));3766}3767 3768LLVMValueRef LLVMBuildSRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3769                           const char *Name) {3770  return wrap(unwrap(B)->CreateSRem(unwrap(LHS), unwrap(RHS), Name));3771}3772 3773LLVMValueRef LLVMBuildFRem(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3774                           const char *Name) {3775  return wrap(unwrap(B)->CreateFRem(unwrap(LHS), unwrap(RHS), Name));3776}3777 3778LLVMValueRef LLVMBuildShl(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3779                          const char *Name) {3780  return wrap(unwrap(B)->CreateShl(unwrap(LHS), unwrap(RHS), Name));3781}3782 3783LLVMValueRef LLVMBuildLShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3784                           const char *Name) {3785  return wrap(unwrap(B)->CreateLShr(unwrap(LHS), unwrap(RHS), Name));3786}3787 3788LLVMValueRef LLVMBuildAShr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3789                           const char *Name) {3790  return wrap(unwrap(B)->CreateAShr(unwrap(LHS), unwrap(RHS), Name));3791}3792 3793LLVMValueRef LLVMBuildAnd(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3794                          const char *Name) {3795  return wrap(unwrap(B)->CreateAnd(unwrap(LHS), unwrap(RHS), Name));3796}3797 3798LLVMValueRef LLVMBuildOr(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3799                         const char *Name) {3800  return wrap(unwrap(B)->CreateOr(unwrap(LHS), unwrap(RHS), Name));3801}3802 3803LLVMValueRef LLVMBuildXor(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS,3804                          const char *Name) {3805  return wrap(unwrap(B)->CreateXor(unwrap(LHS), unwrap(RHS), Name));3806}3807 3808LLVMValueRef LLVMBuildBinOp(LLVMBuilderRef B, LLVMOpcode Op,3809                            LLVMValueRef LHS, LLVMValueRef RHS,3810                            const char *Name) {3811  return wrap(unwrap(B)->CreateBinOp(Instruction::BinaryOps(map_from_llvmopcode(Op)), unwrap(LHS),3812                                     unwrap(RHS), Name));3813}3814 3815LLVMValueRef LLVMBuildNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {3816  return wrap(unwrap(B)->CreateNeg(unwrap(V), Name));3817}3818 3819LLVMValueRef LLVMBuildNSWNeg(LLVMBuilderRef B, LLVMValueRef V,3820                             const char *Name) {3821  return wrap(unwrap(B)->CreateNSWNeg(unwrap(V), Name));3822}3823 3824LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V,3825                             const char *Name) {3826  Value *Neg = unwrap(B)->CreateNeg(unwrap(V), Name);3827  if (auto *I = dyn_cast<BinaryOperator>(Neg))3828    I->setHasNoUnsignedWrap();3829  return wrap(Neg);3830}3831 3832LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {3833  return wrap(unwrap(B)->CreateFNeg(unwrap(V), Name));3834}3835 3836LLVMValueRef LLVMBuildNot(LLVMBuilderRef B, LLVMValueRef V, const char *Name) {3837  return wrap(unwrap(B)->CreateNot(unwrap(V), Name));3838}3839 3840LLVMBool LLVMGetNUW(LLVMValueRef ArithInst) {3841  Value *P = unwrap<Value>(ArithInst);3842  return cast<Instruction>(P)->hasNoUnsignedWrap();3843}3844 3845void LLVMSetNUW(LLVMValueRef ArithInst, LLVMBool HasNUW) {3846  Value *P = unwrap<Value>(ArithInst);3847  cast<Instruction>(P)->setHasNoUnsignedWrap(HasNUW);3848}3849 3850LLVMBool LLVMGetNSW(LLVMValueRef ArithInst) {3851  Value *P = unwrap<Value>(ArithInst);3852  return cast<Instruction>(P)->hasNoSignedWrap();3853}3854 3855void LLVMSetNSW(LLVMValueRef ArithInst, LLVMBool HasNSW) {3856  Value *P = unwrap<Value>(ArithInst);3857  cast<Instruction>(P)->setHasNoSignedWrap(HasNSW);3858}3859 3860LLVMBool LLVMGetExact(LLVMValueRef DivOrShrInst) {3861  Value *P = unwrap<Value>(DivOrShrInst);3862  return cast<Instruction>(P)->isExact();3863}3864 3865void LLVMSetExact(LLVMValueRef DivOrShrInst, LLVMBool IsExact) {3866  Value *P = unwrap<Value>(DivOrShrInst);3867  cast<Instruction>(P)->setIsExact(IsExact);3868}3869 3870LLVMBool LLVMGetNNeg(LLVMValueRef NonNegInst) {3871  Value *P = unwrap<Value>(NonNegInst);3872  return cast<Instruction>(P)->hasNonNeg();3873}3874 3875void LLVMSetNNeg(LLVMValueRef NonNegInst, LLVMBool IsNonNeg) {3876  Value *P = unwrap<Value>(NonNegInst);3877  cast<Instruction>(P)->setNonNeg(IsNonNeg);3878}3879 3880LLVMFastMathFlags LLVMGetFastMathFlags(LLVMValueRef FPMathInst) {3881  Value *P = unwrap<Value>(FPMathInst);3882  FastMathFlags FMF = cast<Instruction>(P)->getFastMathFlags();3883  return mapToLLVMFastMathFlags(FMF);3884}3885 3886void LLVMSetFastMathFlags(LLVMValueRef FPMathInst, LLVMFastMathFlags FMF) {3887  Value *P = unwrap<Value>(FPMathInst);3888  cast<Instruction>(P)->setFastMathFlags(mapFromLLVMFastMathFlags(FMF));3889}3890 3891LLVMBool LLVMCanValueUseFastMathFlags(LLVMValueRef V) {3892  Value *Val = unwrap<Value>(V);3893  return isa<FPMathOperator>(Val);3894}3895 3896LLVMBool LLVMGetIsDisjoint(LLVMValueRef Inst) {3897  Value *P = unwrap<Value>(Inst);3898  return cast<PossiblyDisjointInst>(P)->isDisjoint();3899}3900 3901void LLVMSetIsDisjoint(LLVMValueRef Inst, LLVMBool IsDisjoint) {3902  Value *P = unwrap<Value>(Inst);3903  cast<PossiblyDisjointInst>(P)->setIsDisjoint(IsDisjoint);3904}3905 3906/*--.. Memory ..............................................................--*/3907 3908LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,3909                             const char *Name) {3910  Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());3911  Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));3912  AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);3913  return wrap(unwrap(B)->CreateMalloc(ITy, unwrap(Ty), AllocSize, nullptr,3914                                      nullptr, Name));3915}3916 3917LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef B, LLVMTypeRef Ty,3918                                  LLVMValueRef Val, const char *Name) {3919  Type* ITy = Type::getInt32Ty(unwrap(B)->GetInsertBlock()->getContext());3920  Constant* AllocSize = ConstantExpr::getSizeOf(unwrap(Ty));3921  AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);3922  return wrap(unwrap(B)->CreateMalloc(ITy, unwrap(Ty), AllocSize, unwrap(Val),3923                                      nullptr, Name));3924}3925 3926LLVMValueRef LLVMBuildMemSet(LLVMBuilderRef B, LLVMValueRef Ptr,3927                             LLVMValueRef Val, LLVMValueRef Len,3928                             unsigned Align) {3929  return wrap(unwrap(B)->CreateMemSet(unwrap(Ptr), unwrap(Val), unwrap(Len),3930                                      MaybeAlign(Align)));3931}3932 3933LLVMValueRef LLVMBuildMemCpy(LLVMBuilderRef B,3934                             LLVMValueRef Dst, unsigned DstAlign,3935                             LLVMValueRef Src, unsigned SrcAlign,3936                             LLVMValueRef Size) {3937  return wrap(unwrap(B)->CreateMemCpy(unwrap(Dst), MaybeAlign(DstAlign),3938                                      unwrap(Src), MaybeAlign(SrcAlign),3939                                      unwrap(Size)));3940}3941 3942LLVMValueRef LLVMBuildMemMove(LLVMBuilderRef B,3943                              LLVMValueRef Dst, unsigned DstAlign,3944                              LLVMValueRef Src, unsigned SrcAlign,3945                              LLVMValueRef Size) {3946  return wrap(unwrap(B)->CreateMemMove(unwrap(Dst), MaybeAlign(DstAlign),3947                                       unwrap(Src), MaybeAlign(SrcAlign),3948                                       unwrap(Size)));3949}3950 3951LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,3952                             const char *Name) {3953  return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), nullptr, Name));3954}3955 3956LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef B, LLVMTypeRef Ty,3957                                  LLVMValueRef Val, const char *Name) {3958  return wrap(unwrap(B)->CreateAlloca(unwrap(Ty), unwrap(Val), Name));3959}3960 3961LLVMValueRef LLVMBuildFree(LLVMBuilderRef B, LLVMValueRef PointerVal) {3962  return wrap(unwrap(B)->CreateFree(unwrap(PointerVal)));3963}3964 3965LLVMValueRef LLVMBuildLoad2(LLVMBuilderRef B, LLVMTypeRef Ty,3966                            LLVMValueRef PointerVal, const char *Name) {3967  return wrap(unwrap(B)->CreateLoad(unwrap(Ty), unwrap(PointerVal), Name));3968}3969 3970LLVMValueRef LLVMBuildStore(LLVMBuilderRef B, LLVMValueRef Val,3971                            LLVMValueRef PointerVal) {3972  return wrap(unwrap(B)->CreateStore(unwrap(Val), unwrap(PointerVal)));3973}3974 3975static AtomicOrdering mapFromLLVMOrdering(LLVMAtomicOrdering Ordering) {3976  switch (Ordering) {3977    case LLVMAtomicOrderingNotAtomic: return AtomicOrdering::NotAtomic;3978    case LLVMAtomicOrderingUnordered: return AtomicOrdering::Unordered;3979    case LLVMAtomicOrderingMonotonic: return AtomicOrdering::Monotonic;3980    case LLVMAtomicOrderingAcquire: return AtomicOrdering::Acquire;3981    case LLVMAtomicOrderingRelease: return AtomicOrdering::Release;3982    case LLVMAtomicOrderingAcquireRelease:3983      return AtomicOrdering::AcquireRelease;3984    case LLVMAtomicOrderingSequentiallyConsistent:3985      return AtomicOrdering::SequentiallyConsistent;3986  }3987 3988  llvm_unreachable("Invalid LLVMAtomicOrdering value!");3989}3990 3991static LLVMAtomicOrdering mapToLLVMOrdering(AtomicOrdering Ordering) {3992  switch (Ordering) {3993    case AtomicOrdering::NotAtomic: return LLVMAtomicOrderingNotAtomic;3994    case AtomicOrdering::Unordered: return LLVMAtomicOrderingUnordered;3995    case AtomicOrdering::Monotonic: return LLVMAtomicOrderingMonotonic;3996    case AtomicOrdering::Acquire: return LLVMAtomicOrderingAcquire;3997    case AtomicOrdering::Release: return LLVMAtomicOrderingRelease;3998    case AtomicOrdering::AcquireRelease:3999      return LLVMAtomicOrderingAcquireRelease;4000    case AtomicOrdering::SequentiallyConsistent:4001      return LLVMAtomicOrderingSequentiallyConsistent;4002  }4003 4004  llvm_unreachable("Invalid AtomicOrdering value!");4005}4006 4007static AtomicRMWInst::BinOp mapFromLLVMRMWBinOp(LLVMAtomicRMWBinOp BinOp) {4008  switch (BinOp) {4009    case LLVMAtomicRMWBinOpXchg: return AtomicRMWInst::Xchg;4010    case LLVMAtomicRMWBinOpAdd: return AtomicRMWInst::Add;4011    case LLVMAtomicRMWBinOpSub: return AtomicRMWInst::Sub;4012    case LLVMAtomicRMWBinOpAnd: return AtomicRMWInst::And;4013    case LLVMAtomicRMWBinOpNand: return AtomicRMWInst::Nand;4014    case LLVMAtomicRMWBinOpOr: return AtomicRMWInst::Or;4015    case LLVMAtomicRMWBinOpXor: return AtomicRMWInst::Xor;4016    case LLVMAtomicRMWBinOpMax: return AtomicRMWInst::Max;4017    case LLVMAtomicRMWBinOpMin: return AtomicRMWInst::Min;4018    case LLVMAtomicRMWBinOpUMax: return AtomicRMWInst::UMax;4019    case LLVMAtomicRMWBinOpUMin: return AtomicRMWInst::UMin;4020    case LLVMAtomicRMWBinOpFAdd: return AtomicRMWInst::FAdd;4021    case LLVMAtomicRMWBinOpFSub: return AtomicRMWInst::FSub;4022    case LLVMAtomicRMWBinOpFMax: return AtomicRMWInst::FMax;4023    case LLVMAtomicRMWBinOpFMin: return AtomicRMWInst::FMin;4024    case LLVMAtomicRMWBinOpFMaximum:4025      return AtomicRMWInst::FMaximum;4026    case LLVMAtomicRMWBinOpFMinimum:4027      return AtomicRMWInst::FMinimum;4028    case LLVMAtomicRMWBinOpUIncWrap:4029      return AtomicRMWInst::UIncWrap;4030    case LLVMAtomicRMWBinOpUDecWrap:4031      return AtomicRMWInst::UDecWrap;4032    case LLVMAtomicRMWBinOpUSubCond:4033      return AtomicRMWInst::USubCond;4034    case LLVMAtomicRMWBinOpUSubSat:4035      return AtomicRMWInst::USubSat;4036  }4037 4038  llvm_unreachable("Invalid LLVMAtomicRMWBinOp value!");4039}4040 4041static LLVMAtomicRMWBinOp mapToLLVMRMWBinOp(AtomicRMWInst::BinOp BinOp) {4042  switch (BinOp) {4043    case AtomicRMWInst::Xchg: return LLVMAtomicRMWBinOpXchg;4044    case AtomicRMWInst::Add: return LLVMAtomicRMWBinOpAdd;4045    case AtomicRMWInst::Sub: return LLVMAtomicRMWBinOpSub;4046    case AtomicRMWInst::And: return LLVMAtomicRMWBinOpAnd;4047    case AtomicRMWInst::Nand: return LLVMAtomicRMWBinOpNand;4048    case AtomicRMWInst::Or: return LLVMAtomicRMWBinOpOr;4049    case AtomicRMWInst::Xor: return LLVMAtomicRMWBinOpXor;4050    case AtomicRMWInst::Max: return LLVMAtomicRMWBinOpMax;4051    case AtomicRMWInst::Min: return LLVMAtomicRMWBinOpMin;4052    case AtomicRMWInst::UMax: return LLVMAtomicRMWBinOpUMax;4053    case AtomicRMWInst::UMin: return LLVMAtomicRMWBinOpUMin;4054    case AtomicRMWInst::FAdd: return LLVMAtomicRMWBinOpFAdd;4055    case AtomicRMWInst::FSub: return LLVMAtomicRMWBinOpFSub;4056    case AtomicRMWInst::FMax: return LLVMAtomicRMWBinOpFMax;4057    case AtomicRMWInst::FMin: return LLVMAtomicRMWBinOpFMin;4058    case AtomicRMWInst::FMaximum:4059      return LLVMAtomicRMWBinOpFMaximum;4060    case AtomicRMWInst::FMinimum:4061      return LLVMAtomicRMWBinOpFMinimum;4062    case AtomicRMWInst::UIncWrap:4063      return LLVMAtomicRMWBinOpUIncWrap;4064    case AtomicRMWInst::UDecWrap:4065      return LLVMAtomicRMWBinOpUDecWrap;4066    case AtomicRMWInst::USubCond:4067      return LLVMAtomicRMWBinOpUSubCond;4068    case AtomicRMWInst::USubSat:4069      return LLVMAtomicRMWBinOpUSubSat;4070    default: break;4071  }4072 4073  llvm_unreachable("Invalid AtomicRMWBinOp value!");4074}4075 4076LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering Ordering,4077                            LLVMBool isSingleThread, const char *Name) {4078  return wrap(4079    unwrap(B)->CreateFence(mapFromLLVMOrdering(Ordering),4080                           isSingleThread ? SyncScope::SingleThread4081                                          : SyncScope::System,4082                           Name));4083}4084 4085LLVMValueRef LLVMBuildFenceSyncScope(LLVMBuilderRef B,4086                                     LLVMAtomicOrdering Ordering, unsigned SSID,4087                                     const char *Name) {4088  return wrap(4089      unwrap(B)->CreateFence(mapFromLLVMOrdering(Ordering), SSID, Name));4090}4091 4092LLVMValueRef LLVMBuildGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,4093                           LLVMValueRef Pointer, LLVMValueRef *Indices,4094                           unsigned NumIndices, const char *Name) {4095  ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);4096  return wrap(unwrap(B)->CreateGEP(unwrap(Ty), unwrap(Pointer), IdxList, Name));4097}4098 4099LLVMValueRef LLVMBuildInBoundsGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,4100                                   LLVMValueRef Pointer, LLVMValueRef *Indices,4101                                   unsigned NumIndices, const char *Name) {4102  ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);4103  return wrap(4104      unwrap(B)->CreateInBoundsGEP(unwrap(Ty), unwrap(Pointer), IdxList, Name));4105}4106 4107LLVMValueRef LLVMBuildGEPWithNoWrapFlags(LLVMBuilderRef B, LLVMTypeRef Ty,4108                                         LLVMValueRef Pointer,4109                                         LLVMValueRef *Indices,4110                                         unsigned NumIndices, const char *Name,4111                                         LLVMGEPNoWrapFlags NoWrapFlags) {4112  ArrayRef<Value *> IdxList(unwrap(Indices), NumIndices);4113  return wrap(unwrap(B)->CreateGEP(unwrap(Ty), unwrap(Pointer), IdxList, Name,4114                                   mapFromLLVMGEPNoWrapFlags(NoWrapFlags)));4115}4116 4117LLVMValueRef LLVMBuildStructGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,4118                                 LLVMValueRef Pointer, unsigned Idx,4119                                 const char *Name) {4120  return wrap(4121      unwrap(B)->CreateStructGEP(unwrap(Ty), unwrap(Pointer), Idx, Name));4122}4123 4124LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str,4125                                   const char *Name) {4126  return wrap(unwrap(B)->CreateGlobalString(Str, Name));4127}4128 4129LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str,4130                                      const char *Name) {4131  return wrap(unwrap(B)->CreateGlobalString(Str, Name));4132}4133 4134LLVMBool LLVMGetVolatile(LLVMValueRef Inst) {4135  return cast<Instruction>(unwrap(Inst))->isVolatile();4136}4137 4138void LLVMSetVolatile(LLVMValueRef MemAccessInst, LLVMBool isVolatile) {4139  Value *P = unwrap(MemAccessInst);4140  if (LoadInst *LI = dyn_cast<LoadInst>(P))4141    return LI->setVolatile(isVolatile);4142  if (StoreInst *SI = dyn_cast<StoreInst>(P))4143    return SI->setVolatile(isVolatile);4144  if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(P))4145    return AI->setVolatile(isVolatile);4146  return cast<AtomicCmpXchgInst>(P)->setVolatile(isVolatile);4147}4148 4149LLVMBool LLVMGetWeak(LLVMValueRef CmpXchgInst) {4150  return unwrap<AtomicCmpXchgInst>(CmpXchgInst)->isWeak();4151}4152 4153void LLVMSetWeak(LLVMValueRef CmpXchgInst, LLVMBool isWeak) {4154  return unwrap<AtomicCmpXchgInst>(CmpXchgInst)->setWeak(isWeak);4155}4156 4157LLVMAtomicOrdering LLVMGetOrdering(LLVMValueRef MemAccessInst) {4158  Value *P = unwrap(MemAccessInst);4159  AtomicOrdering O;4160  if (LoadInst *LI = dyn_cast<LoadInst>(P))4161    O = LI->getOrdering();4162  else if (StoreInst *SI = dyn_cast<StoreInst>(P))4163    O = SI->getOrdering();4164  else if (FenceInst *FI = dyn_cast<FenceInst>(P))4165    O = FI->getOrdering();4166  else4167    O = cast<AtomicRMWInst>(P)->getOrdering();4168  return mapToLLVMOrdering(O);4169}4170 4171void LLVMSetOrdering(LLVMValueRef MemAccessInst, LLVMAtomicOrdering Ordering) {4172  Value *P = unwrap(MemAccessInst);4173  AtomicOrdering O = mapFromLLVMOrdering(Ordering);4174 4175  if (LoadInst *LI = dyn_cast<LoadInst>(P))4176    return LI->setOrdering(O);4177  else if (FenceInst *FI = dyn_cast<FenceInst>(P))4178    return FI->setOrdering(O);4179  else if (AtomicRMWInst *ARWI = dyn_cast<AtomicRMWInst>(P))4180    return ARWI->setOrdering(O);4181  return cast<StoreInst>(P)->setOrdering(O);4182}4183 4184LLVMAtomicRMWBinOp LLVMGetAtomicRMWBinOp(LLVMValueRef Inst) {4185  return mapToLLVMRMWBinOp(unwrap<AtomicRMWInst>(Inst)->getOperation());4186}4187 4188void LLVMSetAtomicRMWBinOp(LLVMValueRef Inst, LLVMAtomicRMWBinOp BinOp) {4189  unwrap<AtomicRMWInst>(Inst)->setOperation(mapFromLLVMRMWBinOp(BinOp));4190}4191 4192/*--.. Casts ...............................................................--*/4193 4194LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef B, LLVMValueRef Val,4195                            LLVMTypeRef DestTy, const char *Name) {4196  return wrap(unwrap(B)->CreateTrunc(unwrap(Val), unwrap(DestTy), Name));4197}4198 4199LLVMValueRef LLVMBuildZExt(LLVMBuilderRef B, LLVMValueRef Val,4200                           LLVMTypeRef DestTy, const char *Name) {4201  return wrap(unwrap(B)->CreateZExt(unwrap(Val), unwrap(DestTy), Name));4202}4203 4204LLVMValueRef LLVMBuildSExt(LLVMBuilderRef B, LLVMValueRef Val,4205                           LLVMTypeRef DestTy, const char *Name) {4206  return wrap(unwrap(B)->CreateSExt(unwrap(Val), unwrap(DestTy), Name));4207}4208 4209LLVMValueRef LLVMBuildFPToUI(LLVMBuilderRef B, LLVMValueRef Val,4210                             LLVMTypeRef DestTy, const char *Name) {4211  return wrap(unwrap(B)->CreateFPToUI(unwrap(Val), unwrap(DestTy), Name));4212}4213 4214LLVMValueRef LLVMBuildFPToSI(LLVMBuilderRef B, LLVMValueRef Val,4215                             LLVMTypeRef DestTy, const char *Name) {4216  return wrap(unwrap(B)->CreateFPToSI(unwrap(Val), unwrap(DestTy), Name));4217}4218 4219LLVMValueRef LLVMBuildUIToFP(LLVMBuilderRef B, LLVMValueRef Val,4220                             LLVMTypeRef DestTy, const char *Name) {4221  return wrap(unwrap(B)->CreateUIToFP(unwrap(Val), unwrap(DestTy), Name));4222}4223 4224LLVMValueRef LLVMBuildSIToFP(LLVMBuilderRef B, LLVMValueRef Val,4225                             LLVMTypeRef DestTy, const char *Name) {4226  return wrap(unwrap(B)->CreateSIToFP(unwrap(Val), unwrap(DestTy), Name));4227}4228 4229LLVMValueRef LLVMBuildFPTrunc(LLVMBuilderRef B, LLVMValueRef Val,4230                              LLVMTypeRef DestTy, const char *Name) {4231  return wrap(unwrap(B)->CreateFPTrunc(unwrap(Val), unwrap(DestTy), Name));4232}4233 4234LLVMValueRef LLVMBuildFPExt(LLVMBuilderRef B, LLVMValueRef Val,4235                            LLVMTypeRef DestTy, const char *Name) {4236  return wrap(unwrap(B)->CreateFPExt(unwrap(Val), unwrap(DestTy), Name));4237}4238 4239LLVMValueRef LLVMBuildPtrToInt(LLVMBuilderRef B, LLVMValueRef Val,4240                               LLVMTypeRef DestTy, const char *Name) {4241  return wrap(unwrap(B)->CreatePtrToInt(unwrap(Val), unwrap(DestTy), Name));4242}4243 4244LLVMValueRef LLVMBuildIntToPtr(LLVMBuilderRef B, LLVMValueRef Val,4245                               LLVMTypeRef DestTy, const char *Name) {4246  return wrap(unwrap(B)->CreateIntToPtr(unwrap(Val), unwrap(DestTy), Name));4247}4248 4249LLVMValueRef LLVMBuildBitCast(LLVMBuilderRef B, LLVMValueRef Val,4250                              LLVMTypeRef DestTy, const char *Name) {4251  return wrap(unwrap(B)->CreateBitCast(unwrap(Val), unwrap(DestTy), Name));4252}4253 4254LLVMValueRef LLVMBuildAddrSpaceCast(LLVMBuilderRef B, LLVMValueRef Val,4255                                    LLVMTypeRef DestTy, const char *Name) {4256  return wrap(unwrap(B)->CreateAddrSpaceCast(unwrap(Val), unwrap(DestTy), Name));4257}4258 4259LLVMValueRef LLVMBuildZExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,4260                                    LLVMTypeRef DestTy, const char *Name) {4261  return wrap(unwrap(B)->CreateZExtOrBitCast(unwrap(Val), unwrap(DestTy),4262                                             Name));4263}4264 4265LLVMValueRef LLVMBuildSExtOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,4266                                    LLVMTypeRef DestTy, const char *Name) {4267  return wrap(unwrap(B)->CreateSExtOrBitCast(unwrap(Val), unwrap(DestTy),4268                                             Name));4269}4270 4271LLVMValueRef LLVMBuildTruncOrBitCast(LLVMBuilderRef B, LLVMValueRef Val,4272                                     LLVMTypeRef DestTy, const char *Name) {4273  return wrap(unwrap(B)->CreateTruncOrBitCast(unwrap(Val), unwrap(DestTy),4274                                              Name));4275}4276 4277LLVMValueRef LLVMBuildCast(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef Val,4278                           LLVMTypeRef DestTy, const char *Name) {4279  return wrap(unwrap(B)->CreateCast(Instruction::CastOps(map_from_llvmopcode(Op)), unwrap(Val),4280                                    unwrap(DestTy), Name));4281}4282 4283LLVMValueRef LLVMBuildPointerCast(LLVMBuilderRef B, LLVMValueRef Val,4284                                  LLVMTypeRef DestTy, const char *Name) {4285  return wrap(unwrap(B)->CreatePointerCast(unwrap(Val), unwrap(DestTy), Name));4286}4287 4288LLVMValueRef LLVMBuildIntCast2(LLVMBuilderRef B, LLVMValueRef Val,4289                               LLVMTypeRef DestTy, LLVMBool IsSigned,4290                               const char *Name) {4291  return wrap(4292      unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), IsSigned, Name));4293}4294 4295LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,4296                              LLVMTypeRef DestTy, const char *Name) {4297  return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy),4298                                       /*isSigned*/true, Name));4299}4300 4301LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef B, LLVMValueRef Val,4302                             LLVMTypeRef DestTy, const char *Name) {4303  return wrap(unwrap(B)->CreateFPCast(unwrap(Val), unwrap(DestTy), Name));4304}4305 4306LLVMOpcode LLVMGetCastOpcode(LLVMValueRef Src, LLVMBool SrcIsSigned,4307                             LLVMTypeRef DestTy, LLVMBool DestIsSigned) {4308  return map_to_llvmopcode(CastInst::getCastOpcode(4309      unwrap(Src), SrcIsSigned, unwrap(DestTy), DestIsSigned));4310}4311 4312/*--.. Comparisons .........................................................--*/4313 4314LLVMValueRef LLVMBuildICmp(LLVMBuilderRef B, LLVMIntPredicate Op,4315                           LLVMValueRef LHS, LLVMValueRef RHS,4316                           const char *Name) {4317  return wrap(unwrap(B)->CreateICmp(static_cast<ICmpInst::Predicate>(Op),4318                                    unwrap(LHS), unwrap(RHS), Name));4319}4320 4321LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef B, LLVMRealPredicate Op,4322                           LLVMValueRef LHS, LLVMValueRef RHS,4323                           const char *Name) {4324  return wrap(unwrap(B)->CreateFCmp(static_cast<FCmpInst::Predicate>(Op),4325                                    unwrap(LHS), unwrap(RHS), Name));4326}4327 4328/*--.. Miscellaneous instructions ..........................................--*/4329 4330LLVMValueRef LLVMBuildPhi(LLVMBuilderRef B, LLVMTypeRef Ty, const char *Name) {4331  return wrap(unwrap(B)->CreatePHI(unwrap(Ty), 0, Name));4332}4333 4334LLVMValueRef LLVMBuildCall2(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,4335                            LLVMValueRef *Args, unsigned NumArgs,4336                            const char *Name) {4337  FunctionType *FTy = unwrap<FunctionType>(Ty);4338  return wrap(unwrap(B)->CreateCall(FTy, unwrap(Fn),4339                                    ArrayRef(unwrap(Args), NumArgs), Name));4340}4341 4342LLVMValueRef4343LLVMBuildCallWithOperandBundles(LLVMBuilderRef B, LLVMTypeRef Ty,4344                                LLVMValueRef Fn, LLVMValueRef *Args,4345                                unsigned NumArgs, LLVMOperandBundleRef *Bundles,4346                                unsigned NumBundles, const char *Name) {4347  FunctionType *FTy = unwrap<FunctionType>(Ty);4348  SmallVector<OperandBundleDef, 8> OBs;4349  for (auto *Bundle : ArrayRef(Bundles, NumBundles)) {4350    OperandBundleDef *OB = unwrap(Bundle);4351    OBs.push_back(*OB);4352  }4353  return wrap(unwrap(B)->CreateCall(4354      FTy, unwrap(Fn), ArrayRef(unwrap(Args), NumArgs), OBs, Name));4355}4356 4357LLVMValueRef LLVMBuildSelect(LLVMBuilderRef B, LLVMValueRef If,4358                             LLVMValueRef Then, LLVMValueRef Else,4359                             const char *Name) {4360  return wrap(unwrap(B)->CreateSelect(unwrap(If), unwrap(Then), unwrap(Else),4361                                      Name));4362}4363 4364LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef B, LLVMValueRef List,4365                            LLVMTypeRef Ty, const char *Name) {4366  return wrap(unwrap(B)->CreateVAArg(unwrap(List), unwrap(Ty), Name));4367}4368 4369LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef B, LLVMValueRef VecVal,4370                                      LLVMValueRef Index, const char *Name) {4371  return wrap(unwrap(B)->CreateExtractElement(unwrap(VecVal), unwrap(Index),4372                                              Name));4373}4374 4375LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef B, LLVMValueRef VecVal,4376                                    LLVMValueRef EltVal, LLVMValueRef Index,4377                                    const char *Name) {4378  return wrap(unwrap(B)->CreateInsertElement(unwrap(VecVal), unwrap(EltVal),4379                                             unwrap(Index), Name));4380}4381 4382LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef B, LLVMValueRef V1,4383                                    LLVMValueRef V2, LLVMValueRef Mask,4384                                    const char *Name) {4385  return wrap(unwrap(B)->CreateShuffleVector(unwrap(V1), unwrap(V2),4386                                             unwrap(Mask), Name));4387}4388 4389LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef B, LLVMValueRef AggVal,4390                                   unsigned Index, const char *Name) {4391  return wrap(unwrap(B)->CreateExtractValue(unwrap(AggVal), Index, Name));4392}4393 4394LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef B, LLVMValueRef AggVal,4395                                  LLVMValueRef EltVal, unsigned Index,4396                                  const char *Name) {4397  return wrap(unwrap(B)->CreateInsertValue(unwrap(AggVal), unwrap(EltVal),4398                                           Index, Name));4399}4400 4401LLVMValueRef LLVMBuildFreeze(LLVMBuilderRef B, LLVMValueRef Val,4402                             const char *Name) {4403  return wrap(unwrap(B)->CreateFreeze(unwrap(Val), Name));4404}4405 4406LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef B, LLVMValueRef Val,4407                             const char *Name) {4408  return wrap(unwrap(B)->CreateIsNull(unwrap(Val), Name));4409}4410 4411LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef B, LLVMValueRef Val,4412                                const char *Name) {4413  return wrap(unwrap(B)->CreateIsNotNull(unwrap(Val), Name));4414}4415 4416LLVMValueRef LLVMBuildPtrDiff2(LLVMBuilderRef B, LLVMTypeRef ElemTy,4417                               LLVMValueRef LHS, LLVMValueRef RHS,4418                               const char *Name) {4419  return wrap(unwrap(B)->CreatePtrDiff(unwrap(ElemTy), unwrap(LHS),4420                                       unwrap(RHS), Name));4421}4422 4423LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B,LLVMAtomicRMWBinOp op,4424                               LLVMValueRef PTR, LLVMValueRef Val,4425                               LLVMAtomicOrdering ordering,4426                               LLVMBool singleThread) {4427  AtomicRMWInst::BinOp intop = mapFromLLVMRMWBinOp(op);4428  return wrap(unwrap(B)->CreateAtomicRMW(4429      intop, unwrap(PTR), unwrap(Val), MaybeAlign(),4430      mapFromLLVMOrdering(ordering),4431      singleThread ? SyncScope::SingleThread : SyncScope::System));4432}4433 4434LLVMValueRef LLVMBuildAtomicRMWSyncScope(LLVMBuilderRef B,4435                                         LLVMAtomicRMWBinOp op,4436                                         LLVMValueRef PTR, LLVMValueRef Val,4437                                         LLVMAtomicOrdering ordering,4438                                         unsigned SSID) {4439  AtomicRMWInst::BinOp intop = mapFromLLVMRMWBinOp(op);4440  return wrap(unwrap(B)->CreateAtomicRMW(intop, unwrap(PTR), unwrap(Val),4441                                         MaybeAlign(),4442                                         mapFromLLVMOrdering(ordering), SSID));4443}4444 4445LLVMValueRef LLVMBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Ptr,4446                                    LLVMValueRef Cmp, LLVMValueRef New,4447                                    LLVMAtomicOrdering SuccessOrdering,4448                                    LLVMAtomicOrdering FailureOrdering,4449                                    LLVMBool singleThread) {4450 4451  return wrap(unwrap(B)->CreateAtomicCmpXchg(4452      unwrap(Ptr), unwrap(Cmp), unwrap(New), MaybeAlign(),4453      mapFromLLVMOrdering(SuccessOrdering),4454      mapFromLLVMOrdering(FailureOrdering),4455      singleThread ? SyncScope::SingleThread : SyncScope::System));4456}4457 4458LLVMValueRef LLVMBuildAtomicCmpXchgSyncScope(LLVMBuilderRef B, LLVMValueRef Ptr,4459                                             LLVMValueRef Cmp, LLVMValueRef New,4460                                             LLVMAtomicOrdering SuccessOrdering,4461                                             LLVMAtomicOrdering FailureOrdering,4462                                             unsigned SSID) {4463  return wrap(unwrap(B)->CreateAtomicCmpXchg(4464      unwrap(Ptr), unwrap(Cmp), unwrap(New), MaybeAlign(),4465      mapFromLLVMOrdering(SuccessOrdering),4466      mapFromLLVMOrdering(FailureOrdering), SSID));4467}4468 4469unsigned LLVMGetNumMaskElements(LLVMValueRef SVInst) {4470  Value *P = unwrap(SVInst);4471  ShuffleVectorInst *I = cast<ShuffleVectorInst>(P);4472  return I->getShuffleMask().size();4473}4474 4475int LLVMGetMaskValue(LLVMValueRef SVInst, unsigned Elt) {4476  Value *P = unwrap(SVInst);4477  ShuffleVectorInst *I = cast<ShuffleVectorInst>(P);4478  return I->getMaskValue(Elt);4479}4480 4481int LLVMGetUndefMaskElem(void) { return PoisonMaskElem; }4482 4483LLVMBool LLVMIsAtomic(LLVMValueRef Inst) {4484  return unwrap<Instruction>(Inst)->isAtomic();4485}4486 4487LLVMBool LLVMIsAtomicSingleThread(LLVMValueRef AtomicInst) {4488  // Backwards compatibility: return false for non-atomic instructions4489  Instruction *I = unwrap<Instruction>(AtomicInst);4490  if (!I->isAtomic())4491    return 0;4492 4493  return *getAtomicSyncScopeID(I) == SyncScope::SingleThread;4494}4495 4496void LLVMSetAtomicSingleThread(LLVMValueRef AtomicInst, LLVMBool NewValue) {4497  // Backwards compatibility: ignore non-atomic instructions4498  Instruction *I = unwrap<Instruction>(AtomicInst);4499  if (!I->isAtomic())4500    return;4501 4502  SyncScope::ID SSID = NewValue ? SyncScope::SingleThread : SyncScope::System;4503  setAtomicSyncScopeID(I, SSID);4504}4505 4506unsigned LLVMGetAtomicSyncScopeID(LLVMValueRef AtomicInst) {4507  Instruction *I = unwrap<Instruction>(AtomicInst);4508  assert(I->isAtomic() && "Expected an atomic instruction");4509  return *getAtomicSyncScopeID(I);4510}4511 4512void LLVMSetAtomicSyncScopeID(LLVMValueRef AtomicInst, unsigned SSID) {4513  Instruction *I = unwrap<Instruction>(AtomicInst);4514  assert(I->isAtomic() && "Expected an atomic instruction");4515  setAtomicSyncScopeID(I, SSID);4516}4517 4518LLVMAtomicOrdering LLVMGetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst)  {4519  Value *P = unwrap(CmpXchgInst);4520  return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getSuccessOrdering());4521}4522 4523void LLVMSetCmpXchgSuccessOrdering(LLVMValueRef CmpXchgInst,4524                                   LLVMAtomicOrdering Ordering) {4525  Value *P = unwrap(CmpXchgInst);4526  AtomicOrdering O = mapFromLLVMOrdering(Ordering);4527 4528  return cast<AtomicCmpXchgInst>(P)->setSuccessOrdering(O);4529}4530 4531LLVMAtomicOrdering LLVMGetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst)  {4532  Value *P = unwrap(CmpXchgInst);4533  return mapToLLVMOrdering(cast<AtomicCmpXchgInst>(P)->getFailureOrdering());4534}4535 4536void LLVMSetCmpXchgFailureOrdering(LLVMValueRef CmpXchgInst,4537                                   LLVMAtomicOrdering Ordering) {4538  Value *P = unwrap(CmpXchgInst);4539  AtomicOrdering O = mapFromLLVMOrdering(Ordering);4540 4541  return cast<AtomicCmpXchgInst>(P)->setFailureOrdering(O);4542}4543 4544/*===-- Module providers --------------------------------------------------===*/4545 4546LLVMModuleProviderRef4547LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M) {4548  return reinterpret_cast<LLVMModuleProviderRef>(M);4549}4550 4551void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP) {4552  delete unwrap(MP);4553}4554 4555 4556/*===-- Memory buffers ----------------------------------------------------===*/4557 4558LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(4559    const char *Path,4560    LLVMMemoryBufferRef *OutMemBuf,4561    char **OutMessage) {4562 4563  ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path);4564  if (std::error_code EC = MBOrErr.getError()) {4565    *OutMessage = strdup(EC.message().c_str());4566    return 1;4567  }4568  *OutMemBuf = wrap(MBOrErr.get().release());4569  return 0;4570}4571 4572LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,4573                                         char **OutMessage) {4574  ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getSTDIN();4575  if (std::error_code EC = MBOrErr.getError()) {4576    *OutMessage = strdup(EC.message().c_str());4577    return 1;4578  }4579  *OutMemBuf = wrap(MBOrErr.get().release());4580  return 0;4581}4582 4583LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(4584    const char *InputData,4585    size_t InputDataLength,4586    const char *BufferName,4587    LLVMBool RequiresNullTerminator) {4588 4589  return wrap(MemoryBuffer::getMemBuffer(StringRef(InputData, InputDataLength),4590                                         StringRef(BufferName),4591                                         RequiresNullTerminator).release());4592}4593 4594LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(4595    const char *InputData,4596    size_t InputDataLength,4597    const char *BufferName) {4598 4599  return wrap(4600      MemoryBuffer::getMemBufferCopy(StringRef(InputData, InputDataLength),4601                                     StringRef(BufferName)).release());4602}4603 4604const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf) {4605  return unwrap(MemBuf)->getBufferStart();4606}4607 4608size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf) {4609  return unwrap(MemBuf)->getBufferSize();4610}4611 4612void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf) {4613  delete unwrap(MemBuf);4614}4615 4616/*===-- Pass Manager ------------------------------------------------------===*/4617 4618LLVMPassManagerRef LLVMCreatePassManager() {4619  return wrap(new legacy::PassManager());4620}4621 4622LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {4623  return wrap(new legacy::FunctionPassManager(unwrap(M)));4624}4625 4626LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {4627  return LLVMCreateFunctionPassManagerForModule(4628                                            reinterpret_cast<LLVMModuleRef>(P));4629}4630 4631LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {4632  return unwrap<legacy::PassManager>(PM)->run(*unwrap(M));4633}4634 4635LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {4636  return unwrap<legacy::FunctionPassManager>(FPM)->doInitialization();4637}4638 4639LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {4640  return unwrap<legacy::FunctionPassManager>(FPM)->run(*unwrap<Function>(F));4641}4642 4643LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {4644  return unwrap<legacy::FunctionPassManager>(FPM)->doFinalization();4645}4646 4647void LLVMDisposePassManager(LLVMPassManagerRef PM) {4648  delete unwrap(PM);4649}4650 4651/*===-- Threading ------------------------------------------------------===*/4652 4653LLVMBool LLVMStartMultithreaded() {4654  return LLVMIsMultithreaded();4655}4656 4657void LLVMStopMultithreaded() {4658}4659 4660LLVMBool LLVMIsMultithreaded() {4661  return llvm_is_multithreaded();4662}4663