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