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