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