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