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