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