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