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