LLVM  mainline
Loads.cpp
Go to the documentation of this file.
00001 //===- Loads.cpp - Local load analysis ------------------------------------===//
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 defines simple local analyses for load instructions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Analysis/Loads.h"
00015 #include "llvm/Analysis/AliasAnalysis.h"
00016 #include "llvm/Analysis/ValueTracking.h"
00017 #include "llvm/IR/DataLayout.h"
00018 #include "llvm/IR/GlobalAlias.h"
00019 #include "llvm/IR/GlobalVariable.h"
00020 #include "llvm/IR/IntrinsicInst.h"
00021 #include "llvm/IR/LLVMContext.h"
00022 #include "llvm/IR/Module.h"
00023 #include "llvm/IR/Operator.h"
00024 using namespace llvm;
00025 
00026 /// \brief Test if A and B will obviously have the same value.
00027 ///
00028 /// This includes recognizing that %t0 and %t1 will have the same
00029 /// value in code like this:
00030 /// \code
00031 ///   %t0 = getelementptr \@a, 0, 3
00032 ///   store i32 0, i32* %t0
00033 ///   %t1 = getelementptr \@a, 0, 3
00034 ///   %t2 = load i32* %t1
00035 /// \endcode
00036 ///
00037 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
00038   // Test if the values are trivially equivalent.
00039   if (A == B)
00040     return true;
00041 
00042   // Test if the values come from identical arithmetic instructions.
00043   // Use isIdenticalToWhenDefined instead of isIdenticalTo because
00044   // this function is only used when one address use dominates the
00045   // other, which means that they'll always either have the same
00046   // value or one of them will have an undefined value.
00047   if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
00048       isa<GetElementPtrInst>(A))
00049     if (const Instruction *BI = dyn_cast<Instruction>(B))
00050       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
00051         return true;
00052 
00053   // Otherwise they may not be equivalent.
00054   return false;
00055 }
00056 
00057 /// \brief Check if executing a load of this pointer value cannot trap.
00058 ///
00059 /// If it is not obviously safe to load from the specified pointer, we do
00060 /// a quick local scan of the basic block containing \c ScanFrom, to determine
00061 /// if the address is already accessed.
00062 ///
00063 /// This uses the pointee type to determine how many bytes need to be safe to
00064 /// load from the pointer.
00065 bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
00066                                        unsigned Align) {
00067   const DataLayout &DL = ScanFrom->getModule()->getDataLayout();
00068   int64_t ByteOffset = 0;
00069   Value *Base = V;
00070   Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
00071 
00072   if (ByteOffset < 0) // out of bounds
00073     return false;
00074 
00075   Type *BaseType = nullptr;
00076   unsigned BaseAlign = 0;
00077   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
00078     // An alloca is safe to load from as load as it is suitably aligned.
00079     BaseType = AI->getAllocatedType();
00080     BaseAlign = AI->getAlignment();
00081   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
00082     // Global variables are not necessarily safe to load from if they are
00083     // overridden. Their size may change or they may be weak and require a test
00084     // to determine if they were in fact provided.
00085     if (!GV->mayBeOverridden()) {
00086       BaseType = GV->getType()->getElementType();
00087       BaseAlign = GV->getAlignment();
00088     }
00089   }
00090 
00091   PointerType *AddrTy = cast<PointerType>(V->getType());
00092   uint64_t LoadSize = DL.getTypeStoreSize(AddrTy->getElementType());
00093 
00094   // If we found a base allocated type from either an alloca or global variable,
00095   // try to see if we are definitively within the allocated region. We need to
00096   // know the size of the base type and the loaded type to do anything in this
00097   // case.
00098   if (BaseType && BaseType->isSized()) {
00099     if (BaseAlign == 0)
00100       BaseAlign = DL.getPrefTypeAlignment(BaseType);
00101 
00102     if (Align <= BaseAlign) {
00103       // Check if the load is within the bounds of the underlying object.
00104       if (ByteOffset + LoadSize <= DL.getTypeAllocSize(BaseType) &&
00105           (Align == 0 || (ByteOffset % Align) == 0))
00106         return true;
00107     }
00108   }
00109 
00110   // Otherwise, be a little bit aggressive by scanning the local block where we
00111   // want to check to see if the pointer is already being loaded or stored
00112   // from/to.  If so, the previous load or store would have already trapped,
00113   // so there is no harm doing an extra load (also, CSE will later eliminate
00114   // the load entirely).
00115   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
00116 
00117   // We can at least always strip pointer casts even though we can't use the
00118   // base here.
00119   V = V->stripPointerCasts();
00120 
00121   while (BBI != E) {
00122     --BBI;
00123 
00124     // If we see a free or a call which may write to memory (i.e. which might do
00125     // a free) the pointer could be marked invalid.
00126     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
00127         !isa<DbgInfoIntrinsic>(BBI))
00128       return false;
00129 
00130     Value *AccessedPtr;
00131     if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
00132       AccessedPtr = LI->getPointerOperand();
00133     else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
00134       AccessedPtr = SI->getPointerOperand();
00135     else
00136       continue;
00137 
00138     // Handle trivial cases.
00139     if (AccessedPtr == V)
00140       return true;
00141 
00142     auto *AccessedTy = cast<PointerType>(AccessedPtr->getType());
00143     if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
00144         LoadSize <= DL.getTypeStoreSize(AccessedTy->getElementType()))
00145       return true;
00146   }
00147   return false;
00148 }
00149 
00150 /// \brief Scan the ScanBB block backwards to see if we have the value at the
00151 /// memory address *Ptr locally available within a small number of instructions.
00152 ///
00153 /// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
00154 /// instructions to scan in the block. If it is set to \c 0, it will scan the whole
00155 /// block.
00156 ///
00157 /// If the value is available, this function returns it. If not, it returns the
00158 /// iterator for the last validated instruction that the value would be live
00159 /// through. If we scanned the entire block and didn't find something that
00160 /// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
00161 /// instruction processed and this returns null.
00162 ///
00163 /// You can also optionally specify an alias analysis implementation, which
00164 /// makes this more precise.
00165 ///
00166 /// If \c AATags is non-null and a load or store is found, the AA tags from the
00167 /// load or store are recorded there. If there are no AA tags or if no access is
00168 /// found, it is left unmodified.
00169 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
00170                                       BasicBlock::iterator &ScanFrom,
00171                                       unsigned MaxInstsToScan,
00172                                       AliasAnalysis *AA, AAMDNodes *AATags) {
00173   if (MaxInstsToScan == 0)
00174     MaxInstsToScan = ~0U;
00175 
00176   Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
00177 
00178   const DataLayout &DL = ScanBB->getModule()->getDataLayout();
00179 
00180   // Try to get the store size for the type.
00181   uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
00182 
00183   Value *StrippedPtr = Ptr->stripPointerCasts();
00184 
00185   while (ScanFrom != ScanBB->begin()) {
00186     // We must ignore debug info directives when counting (otherwise they
00187     // would affect codegen).
00188     Instruction *Inst = --ScanFrom;
00189     if (isa<DbgInfoIntrinsic>(Inst))
00190       continue;
00191 
00192     // Restore ScanFrom to expected value in case next test succeeds
00193     ScanFrom++;
00194 
00195     // Don't scan huge blocks.
00196     if (MaxInstsToScan-- == 0)
00197       return nullptr;
00198 
00199     --ScanFrom;
00200     // If this is a load of Ptr, the loaded value is available.
00201     // (This is true even if the load is volatile or atomic, although
00202     // those cases are unlikely.)
00203     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
00204       if (AreEquivalentAddressValues(
00205               LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
00206           CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
00207         if (AATags)
00208           LI->getAAMetadata(*AATags);
00209         return LI;
00210       }
00211 
00212     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00213       Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
00214       // If this is a store through Ptr, the value is available!
00215       // (This is true even if the store is volatile or atomic, although
00216       // those cases are unlikely.)
00217       if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
00218           CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
00219                                                AccessTy, DL)) {
00220         if (AATags)
00221           SI->getAAMetadata(*AATags);
00222         return SI->getOperand(0);
00223       }
00224 
00225       // If both StrippedPtr and StorePtr reach all the way to an alloca or
00226       // global and they are different, ignore the store. This is a trivial form
00227       // of alias analysis that is important for reg2mem'd code.
00228       if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
00229           (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
00230           StrippedPtr != StorePtr)
00231         continue;
00232 
00233       // If we have alias analysis and it says the store won't modify the loaded
00234       // value, ignore the store.
00235       if (AA &&
00236           (AA->getModRefInfo(SI, StrippedPtr, AccessSize) &
00237            AliasAnalysis::Mod) == 0)
00238         continue;
00239 
00240       // Otherwise the store that may or may not alias the pointer, bail out.
00241       ++ScanFrom;
00242       return nullptr;
00243     }
00244 
00245     // If this is some other instruction that may clobber Ptr, bail out.
00246     if (Inst->mayWriteToMemory()) {
00247       // If alias analysis claims that it really won't modify the load,
00248       // ignore it.
00249       if (AA &&
00250           (AA->getModRefInfo(Inst, StrippedPtr, AccessSize) &
00251            AliasAnalysis::Mod) == 0)
00252         continue;
00253 
00254       // May modify the pointer, bail out.
00255       ++ScanFrom;
00256       return nullptr;
00257     }
00258   }
00259 
00260   // Got to the start of the block, we didn't find it, but are done for this
00261   // block.
00262   return nullptr;
00263 }