LLVM  mainline
IRBuilder.cpp
Go to the documentation of this file.
00001 //===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the IRBuilder class, which is used as a convenient way
00011 // to create LLVM instructions with a consistent and simplified interface.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/IR/Function.h"
00016 #include "llvm/IR/GlobalVariable.h"
00017 #include "llvm/IR/IRBuilder.h"
00018 #include "llvm/IR/Intrinsics.h"
00019 #include "llvm/IR/LLVMContext.h"
00020 #include "llvm/IR/Statepoint.h"
00021 using namespace llvm;
00022 
00023 /// CreateGlobalString - Make a new global variable with an initializer that
00024 /// has array of i8 type filled in with the nul terminated string value
00025 /// specified.  If Name is specified, it is the name of the global variable
00026 /// created.
00027 GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str,
00028                                                   const Twine &Name,
00029                                                   unsigned AddressSpace) {
00030   Constant *StrConstant = ConstantDataArray::getString(Context, Str);
00031   Module &M = *BB->getParent()->getParent();
00032   GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(),
00033                                           true, GlobalValue::PrivateLinkage,
00034                                           StrConstant, Name, nullptr,
00035                                           GlobalVariable::NotThreadLocal,
00036                                           AddressSpace);
00037   GV->setUnnamedAddr(true);
00038   return GV;
00039 }
00040 
00041 Type *IRBuilderBase::getCurrentFunctionReturnType() const {
00042   assert(BB && BB->getParent() && "No current function!");
00043   return BB->getParent()->getReturnType();
00044 }
00045 
00046 Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) {
00047   PointerType *PT = cast<PointerType>(Ptr->getType());
00048   if (PT->getElementType()->isIntegerTy(8))
00049     return Ptr;
00050   
00051   // Otherwise, we need to insert a bitcast.
00052   PT = getInt8PtrTy(PT->getAddressSpace());
00053   BitCastInst *BCI = new BitCastInst(Ptr, PT, "");
00054   BB->getInstList().insert(InsertPt, BCI);
00055   SetInstDebugLocation(BCI);
00056   return BCI;
00057 }
00058 
00059 static CallInst *createCallHelper(Value *Callee, ArrayRef<Value *> Ops,
00060                                   IRBuilderBase *Builder,
00061                                   const Twine& Name="") {
00062   CallInst *CI = CallInst::Create(Callee, Ops, Name);
00063   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI);
00064   Builder->SetInstDebugLocation(CI);
00065   return CI;  
00066 }
00067 
00068 static InvokeInst *createInvokeHelper(Value *Invokee, BasicBlock *NormalDest,
00069                                       BasicBlock *UnwindDest,
00070                                       ArrayRef<Value *> Ops,
00071                                       IRBuilderBase *Builder,
00072                                       const Twine &Name = "") {
00073   InvokeInst *II =
00074       InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name);
00075   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),
00076                                                   II);
00077   Builder->SetInstDebugLocation(II);
00078   return II;
00079 }
00080 
00081 CallInst *IRBuilderBase::
00082 CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
00083              bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
00084              MDNode *NoAliasTag) {
00085   Ptr = getCastedInt8PtrValue(Ptr);
00086   Value *Ops[] = { Ptr, Val, Size, getInt32(Align), getInt1(isVolatile) };
00087   Type *Tys[] = { Ptr->getType(), Size->getType() };
00088   Module *M = BB->getParent()->getParent();
00089   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
00090   
00091   CallInst *CI = createCallHelper(TheFn, Ops, this);
00092   
00093   // Set the TBAA info if present.
00094   if (TBAATag)
00095     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
00096 
00097   if (ScopeTag)
00098     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
00099  
00100   if (NoAliasTag)
00101     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
00102  
00103   return CI;
00104 }
00105 
00106 CallInst *IRBuilderBase::
00107 CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
00108              bool isVolatile, MDNode *TBAATag, MDNode *TBAAStructTag,
00109              MDNode *ScopeTag, MDNode *NoAliasTag) {
00110   Dst = getCastedInt8PtrValue(Dst);
00111   Src = getCastedInt8PtrValue(Src);
00112 
00113   Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) };
00114   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
00115   Module *M = BB->getParent()->getParent();
00116   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
00117   
00118   CallInst *CI = createCallHelper(TheFn, Ops, this);
00119   
00120   // Set the TBAA info if present.
00121   if (TBAATag)
00122     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
00123 
00124   // Set the TBAA Struct info if present.
00125   if (TBAAStructTag)
00126     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
00127  
00128   if (ScopeTag)
00129     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
00130  
00131   if (NoAliasTag)
00132     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
00133  
00134   return CI;  
00135 }
00136 
00137 CallInst *IRBuilderBase::
00138 CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
00139               bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
00140               MDNode *NoAliasTag) {
00141   Dst = getCastedInt8PtrValue(Dst);
00142   Src = getCastedInt8PtrValue(Src);
00143   
00144   Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) };
00145   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
00146   Module *M = BB->getParent()->getParent();
00147   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys);
00148   
00149   CallInst *CI = createCallHelper(TheFn, Ops, this);
00150   
00151   // Set the TBAA info if present.
00152   if (TBAATag)
00153     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
00154  
00155   if (ScopeTag)
00156     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
00157  
00158   if (NoAliasTag)
00159     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
00160  
00161   return CI;  
00162 }
00163 
00164 CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) {
00165   assert(isa<PointerType>(Ptr->getType()) &&
00166          "lifetime.start only applies to pointers.");
00167   Ptr = getCastedInt8PtrValue(Ptr);
00168   if (!Size)
00169     Size = getInt64(-1);
00170   else
00171     assert(Size->getType() == getInt64Ty() &&
00172            "lifetime.start requires the size to be an i64");
00173   Value *Ops[] = { Size, Ptr };
00174   Module *M = BB->getParent()->getParent();
00175   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_start);
00176   return createCallHelper(TheFn, Ops, this);
00177 }
00178 
00179 CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) {
00180   assert(isa<PointerType>(Ptr->getType()) &&
00181          "lifetime.end only applies to pointers.");
00182   Ptr = getCastedInt8PtrValue(Ptr);
00183   if (!Size)
00184     Size = getInt64(-1);
00185   else
00186     assert(Size->getType() == getInt64Ty() &&
00187            "lifetime.end requires the size to be an i64");
00188   Value *Ops[] = { Size, Ptr };
00189   Module *M = BB->getParent()->getParent();
00190   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_end);
00191   return createCallHelper(TheFn, Ops, this);
00192 }
00193 
00194 CallInst *IRBuilderBase::CreateAssumption(Value *Cond) {
00195   assert(Cond->getType() == getInt1Ty() &&
00196          "an assumption condition must be of type i1");
00197 
00198   Value *Ops[] = { Cond };
00199   Module *M = BB->getParent()->getParent();
00200   Value *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume);
00201   return createCallHelper(FnAssume, Ops, this);
00202 }
00203 
00204 /// Create a call to a Masked Load intrinsic.
00205 /// Ptr      - the base pointer for the load
00206 /// Align    - alignment of the source location
00207 /// Mask     - an vector of booleans which indicates what vector lanes should
00208 ///            be accessed in memory
00209 /// PassThru - a pass-through value that is used to fill the masked-off lanes
00210 ///            of the result
00211 /// Name     - name of the result variable
00212 CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, unsigned Align,
00213                                           Value *Mask, Value *PassThru,
00214                                           const Twine &Name) {
00215   assert(Ptr->getType()->isPointerTy() && "Ptr must be of pointer type");
00216   // DataTy is the overloaded type
00217   Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
00218   assert(DataTy->isVectorTy() && "Ptr should point to a vector");
00219   if (!PassThru)
00220     PassThru = UndefValue::get(DataTy);
00221   Value *Ops[] = { Ptr, getInt32(Align), Mask,  PassThru};
00222   return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops, DataTy, Name);
00223 }
00224 
00225 /// Create a call to a Masked Store intrinsic.
00226 /// Val   - the data to be stored,
00227 /// Ptr   - the base pointer for the store
00228 /// Align - alignment of the destination location
00229 /// Mask  - an vector of booleans which indicates what vector lanes should
00230 ///         be accessed in memory
00231 CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr,
00232                                            unsigned Align, Value *Mask) {
00233   Value *Ops[] = { Val, Ptr, getInt32(Align), Mask };
00234   // Type of the data to be stored - the only one overloaded type
00235   return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, Val->getType());
00236 }
00237 
00238 /// Create a call to a Masked intrinsic, with given intrinsic Id,
00239 /// an array of operands - Ops, and one overloaded type - DataTy
00240 CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id,
00241                                                ArrayRef<Value *> Ops,
00242                                                Type *DataTy,
00243                                                const Twine &Name) {
00244   Module *M = BB->getParent()->getParent();
00245   Type *OverloadedTypes[] = { DataTy };
00246   Value *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes);
00247   return createCallHelper(TheFn, Ops, this, Name);
00248 }
00249 
00250 static std::vector<Value *>
00251 getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes,
00252                   Value *ActualCallee, ArrayRef<Value *> CallArgs,
00253                   ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs) {
00254   std::vector<Value *> Args;
00255   Args.push_back(B.getInt64(ID));
00256   Args.push_back(B.getInt32(NumPatchBytes));
00257   Args.push_back(ActualCallee);
00258   Args.push_back(B.getInt32(CallArgs.size()));
00259   Args.push_back(B.getInt32((unsigned)StatepointFlags::None));
00260   Args.insert(Args.end(), CallArgs.begin(), CallArgs.end());
00261   Args.push_back(B.getInt32(0 /* no transition args */));
00262   Args.push_back(B.getInt32(DeoptArgs.size()));
00263   Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end());
00264   Args.insert(Args.end(), GCArgs.begin(), GCArgs.end());
00265 
00266   return Args;
00267 }
00268 
00269 CallInst *IRBuilderBase::CreateGCStatepointCall(
00270     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
00271     ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs,
00272     ArrayRef<Value *> GCArgs, const Twine &Name) {
00273   // Extract out the type of the callee.
00274   PointerType *FuncPtrType = cast<PointerType>(ActualCallee->getType());
00275   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
00276          "actual callee must be a callable value");
00277 
00278   Module *M = BB->getParent()->getParent();
00279   // Fill in the one generic type'd argument (the function is also vararg)
00280   Type *ArgTypes[] = { FuncPtrType };
00281   Function *FnStatepoint =
00282     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint,
00283                               ArgTypes);
00284 
00285   std::vector<llvm::Value *> Args = getStatepointArgs(
00286       *this, ID, NumPatchBytes, ActualCallee, CallArgs, DeoptArgs, GCArgs);
00287   return createCallHelper(FnStatepoint, Args, this, Name);
00288 }
00289 
00290 CallInst *IRBuilderBase::CreateGCStatepointCall(
00291     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
00292     ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs,
00293     ArrayRef<Value *> GCArgs, const Twine &Name) {
00294   std::vector<Value *> VCallArgs;
00295   for (auto &U : CallArgs)
00296     VCallArgs.push_back(U.get());
00297   return CreateGCStatepointCall(ID, NumPatchBytes, ActualCallee, VCallArgs,
00298                                 DeoptArgs, GCArgs, Name);
00299 }
00300 
00301 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
00302     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
00303     BasicBlock *NormalDest, BasicBlock *UnwindDest,
00304     ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs,
00305     ArrayRef<Value *> GCArgs, const Twine &Name) {
00306   // Extract out the type of the callee.
00307   PointerType *FuncPtrType = cast<PointerType>(ActualInvokee->getType());
00308   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
00309          "actual callee must be a callable value");
00310 
00311   Module *M = BB->getParent()->getParent();
00312   // Fill in the one generic type'd argument (the function is also vararg)
00313   Function *FnStatepoint = Intrinsic::getDeclaration(
00314       M, Intrinsic::experimental_gc_statepoint, {FuncPtrType});
00315 
00316   std::vector<llvm::Value *> Args = getStatepointArgs(
00317       *this, ID, NumPatchBytes, ActualInvokee, InvokeArgs, DeoptArgs, GCArgs);
00318   return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, this,
00319                             Name);
00320 }
00321 
00322 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
00323     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
00324     BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
00325     ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
00326   std::vector<Value *> VCallArgs;
00327   for (auto &U : InvokeArgs)
00328     VCallArgs.push_back(U.get());
00329   return CreateGCStatepointInvoke(ID, NumPatchBytes, ActualInvokee, NormalDest,
00330                                   UnwindDest, VCallArgs, DeoptArgs, GCArgs,
00331                                   Name);
00332 }
00333 
00334 CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint,
00335                                        Type *ResultType,
00336                                        const Twine &Name) {
00337  Intrinsic::ID ID = Intrinsic::experimental_gc_result;
00338  Module *M = BB->getParent()->getParent();
00339  Type *Types[] = {ResultType};
00340  Value *FnGCResult = Intrinsic::getDeclaration(M, ID, Types);
00341 
00342  Value *Args[] = {Statepoint};
00343  return createCallHelper(FnGCResult, Args, this, Name);
00344 }
00345 
00346 CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint,
00347                                          int BaseOffset,
00348                                          int DerivedOffset,
00349                                          Type *ResultType,
00350                                          const Twine &Name) {
00351  Module *M = BB->getParent()->getParent();
00352  Type *Types[] = {ResultType};
00353  Value *FnGCRelocate =
00354    Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
00355 
00356  Value *Args[] = {Statepoint,
00357                   getInt32(BaseOffset),
00358                   getInt32(DerivedOffset)};
00359  return createCallHelper(FnGCRelocate, Args, this, Name);
00360 }