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