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