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