LLVM API Documentation

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