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