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