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