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