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