LLVM API Documentation

DeadStoreElimination.cpp
Go to the documentation of this file.
00001 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
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 a trivial dead store elimination that only considers
00011 // basic-block local redundant stores.
00012 //
00013 // FIXME: This should eventually be extended to be a post-dominator tree
00014 // traversal.  Doing so would be pretty trivial.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/Transforms/Scalar.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SetVector.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/AliasAnalysis.h"
00023 #include "llvm/Analysis/CaptureTracking.h"
00024 #include "llvm/Analysis/MemoryBuiltins.h"
00025 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00026 #include "llvm/Analysis/ValueTracking.h"
00027 #include "llvm/IR/Constants.h"
00028 #include "llvm/IR/DataLayout.h"
00029 #include "llvm/IR/Dominators.h"
00030 #include "llvm/IR/Function.h"
00031 #include "llvm/IR/GlobalVariable.h"
00032 #include "llvm/IR/Instructions.h"
00033 #include "llvm/IR/IntrinsicInst.h"
00034 #include "llvm/Pass.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Target/TargetLibraryInfo.h"
00037 #include "llvm/Transforms/Utils/Local.h"
00038 using namespace llvm;
00039 
00040 #define DEBUG_TYPE "dse"
00041 
00042 STATISTIC(NumFastStores, "Number of stores deleted");
00043 STATISTIC(NumFastOther , "Number of other instrs removed");
00044 
00045 namespace {
00046   struct DSE : public FunctionPass {
00047     AliasAnalysis *AA;
00048     MemoryDependenceAnalysis *MD;
00049     DominatorTree *DT;
00050     const TargetLibraryInfo *TLI;
00051 
00052     static char ID; // Pass identification, replacement for typeid
00053     DSE() : FunctionPass(ID), AA(nullptr), MD(nullptr), DT(nullptr) {
00054       initializeDSEPass(*PassRegistry::getPassRegistry());
00055     }
00056 
00057     bool runOnFunction(Function &F) override {
00058       if (skipOptnoneFunction(F))
00059         return false;
00060 
00061       AA = &getAnalysis<AliasAnalysis>();
00062       MD = &getAnalysis<MemoryDependenceAnalysis>();
00063       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00064       TLI = AA->getTargetLibraryInfo();
00065 
00066       bool Changed = false;
00067       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
00068         // Only check non-dead blocks.  Dead blocks may have strange pointer
00069         // cycles that will confuse alias analysis.
00070         if (DT->isReachableFromEntry(I))
00071           Changed |= runOnBasicBlock(*I);
00072 
00073       AA = nullptr; MD = nullptr; DT = nullptr;
00074       return Changed;
00075     }
00076 
00077     bool runOnBasicBlock(BasicBlock &BB);
00078     bool HandleFree(CallInst *F);
00079     bool handleEndBlock(BasicBlock &BB);
00080     void RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
00081                                SmallSetVector<Value*, 16> &DeadStackObjects);
00082 
00083     void getAnalysisUsage(AnalysisUsage &AU) const override {
00084       AU.setPreservesCFG();
00085       AU.addRequired<DominatorTreeWrapperPass>();
00086       AU.addRequired<AliasAnalysis>();
00087       AU.addRequired<MemoryDependenceAnalysis>();
00088       AU.addPreserved<AliasAnalysis>();
00089       AU.addPreserved<DominatorTreeWrapperPass>();
00090       AU.addPreserved<MemoryDependenceAnalysis>();
00091     }
00092   };
00093 }
00094 
00095 char DSE::ID = 0;
00096 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
00097 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00098 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00099 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00100 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
00101 
00102 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
00103 
00104 //===----------------------------------------------------------------------===//
00105 // Helper functions
00106 //===----------------------------------------------------------------------===//
00107 
00108 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
00109 /// and zero out all the operands of this instruction.  If any of them become
00110 /// dead, delete them and the computation tree that feeds them.
00111 ///
00112 /// If ValueSet is non-null, remove any deleted instructions from it as well.
00113 ///
00114 static void DeleteDeadInstruction(Instruction *I,
00115                                MemoryDependenceAnalysis &MD,
00116                                const TargetLibraryInfo *TLI,
00117                                SmallSetVector<Value*, 16> *ValueSet = nullptr) {
00118   SmallVector<Instruction*, 32> NowDeadInsts;
00119 
00120   NowDeadInsts.push_back(I);
00121   --NumFastOther;
00122 
00123   // Before we touch this instruction, remove it from memdep!
00124   do {
00125     Instruction *DeadInst = NowDeadInsts.pop_back_val();
00126     ++NumFastOther;
00127 
00128     // This instruction is dead, zap it, in stages.  Start by removing it from
00129     // MemDep, which needs to know the operands and needs it to be in the
00130     // function.
00131     MD.removeInstruction(DeadInst);
00132 
00133     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
00134       Value *Op = DeadInst->getOperand(op);
00135       DeadInst->setOperand(op, nullptr);
00136 
00137       // If this operand just became dead, add it to the NowDeadInsts list.
00138       if (!Op->use_empty()) continue;
00139 
00140       if (Instruction *OpI = dyn_cast<Instruction>(Op))
00141         if (isInstructionTriviallyDead(OpI, TLI))
00142           NowDeadInsts.push_back(OpI);
00143     }
00144 
00145     DeadInst->eraseFromParent();
00146 
00147     if (ValueSet) ValueSet->remove(DeadInst);
00148   } while (!NowDeadInsts.empty());
00149 }
00150 
00151 
00152 /// hasMemoryWrite - Does this instruction write some memory?  This only returns
00153 /// true for things that we can analyze with other helpers below.
00154 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo *TLI) {
00155   if (isa<StoreInst>(I))
00156     return true;
00157   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00158     switch (II->getIntrinsicID()) {
00159     default:
00160       return false;
00161     case Intrinsic::memset:
00162     case Intrinsic::memmove:
00163     case Intrinsic::memcpy:
00164     case Intrinsic::init_trampoline:
00165     case Intrinsic::lifetime_end:
00166       return true;
00167     }
00168   }
00169   if (CallSite CS = I) {
00170     if (Function *F = CS.getCalledFunction()) {
00171       if (TLI && TLI->has(LibFunc::strcpy) &&
00172           F->getName() == TLI->getName(LibFunc::strcpy)) {
00173         return true;
00174       }
00175       if (TLI && TLI->has(LibFunc::strncpy) &&
00176           F->getName() == TLI->getName(LibFunc::strncpy)) {
00177         return true;
00178       }
00179       if (TLI && TLI->has(LibFunc::strcat) &&
00180           F->getName() == TLI->getName(LibFunc::strcat)) {
00181         return true;
00182       }
00183       if (TLI && TLI->has(LibFunc::strncat) &&
00184           F->getName() == TLI->getName(LibFunc::strncat)) {
00185         return true;
00186       }
00187     }
00188   }
00189   return false;
00190 }
00191 
00192 /// getLocForWrite - Return a Location stored to by the specified instruction.
00193 /// If isRemovable returns true, this function and getLocForRead completely
00194 /// describe the memory operations for this instruction.
00195 static AliasAnalysis::Location
00196 getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
00197   const DataLayout *DL = AA.getDataLayout();
00198   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00199     return AA.getLocation(SI);
00200 
00201   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
00202     // memcpy/memmove/memset.
00203     AliasAnalysis::Location Loc = AA.getLocationForDest(MI);
00204     // If we don't have target data around, an unknown size in Location means
00205     // that we should use the size of the pointee type.  This isn't valid for
00206     // memset/memcpy, which writes more than an i8.
00207     if (Loc.Size == AliasAnalysis::UnknownSize && DL == nullptr)
00208       return AliasAnalysis::Location();
00209     return Loc;
00210   }
00211 
00212   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
00213   if (!II) return AliasAnalysis::Location();
00214 
00215   switch (II->getIntrinsicID()) {
00216   default: return AliasAnalysis::Location(); // Unhandled intrinsic.
00217   case Intrinsic::init_trampoline:
00218     // If we don't have target data around, an unknown size in Location means
00219     // that we should use the size of the pointee type.  This isn't valid for
00220     // init.trampoline, which writes more than an i8.
00221     if (!DL) return AliasAnalysis::Location();
00222 
00223     // FIXME: We don't know the size of the trampoline, so we can't really
00224     // handle it here.
00225     return AliasAnalysis::Location(II->getArgOperand(0));
00226   case Intrinsic::lifetime_end: {
00227     uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
00228     return AliasAnalysis::Location(II->getArgOperand(1), Len);
00229   }
00230   }
00231 }
00232 
00233 /// getLocForRead - Return the location read by the specified "hasMemoryWrite"
00234 /// instruction if any.
00235 static AliasAnalysis::Location
00236 getLocForRead(Instruction *Inst, AliasAnalysis &AA) {
00237   assert(hasMemoryWrite(Inst, AA.getTargetLibraryInfo()) &&
00238          "Unknown instruction case");
00239 
00240   // The only instructions that both read and write are the mem transfer
00241   // instructions (memcpy/memmove).
00242   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
00243     return AA.getLocationForSource(MTI);
00244   return AliasAnalysis::Location();
00245 }
00246 
00247 
00248 /// isRemovable - If the value of this instruction and the memory it writes to
00249 /// is unused, may we delete this instruction?
00250 static bool isRemovable(Instruction *I) {
00251   // Don't remove volatile/atomic stores.
00252   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00253     return SI->isUnordered();
00254 
00255   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00256     switch (II->getIntrinsicID()) {
00257     default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
00258     case Intrinsic::lifetime_end:
00259       // Never remove dead lifetime_end's, e.g. because it is followed by a
00260       // free.
00261       return false;
00262     case Intrinsic::init_trampoline:
00263       // Always safe to remove init_trampoline.
00264       return true;
00265 
00266     case Intrinsic::memset:
00267     case Intrinsic::memmove:
00268     case Intrinsic::memcpy:
00269       // Don't remove volatile memory intrinsics.
00270       return !cast<MemIntrinsic>(II)->isVolatile();
00271     }
00272   }
00273 
00274   if (CallSite CS = I)
00275     return CS.getInstruction()->use_empty();
00276 
00277   return false;
00278 }
00279 
00280 
00281 /// isShortenable - Returns true if this instruction can be safely shortened in
00282 /// length.
00283 static bool isShortenable(Instruction *I) {
00284   // Don't shorten stores for now
00285   if (isa<StoreInst>(I))
00286     return false;
00287 
00288   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00289     switch (II->getIntrinsicID()) {
00290       default: return false;
00291       case Intrinsic::memset:
00292       case Intrinsic::memcpy:
00293         // Do shorten memory intrinsics.
00294         return true;
00295     }
00296   }
00297 
00298   // Don't shorten libcalls calls for now.
00299 
00300   return false;
00301 }
00302 
00303 /// getStoredPointerOperand - Return the pointer that is being written to.
00304 static Value *getStoredPointerOperand(Instruction *I) {
00305   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00306     return SI->getPointerOperand();
00307   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
00308     return MI->getDest();
00309 
00310   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00311     switch (II->getIntrinsicID()) {
00312     default: llvm_unreachable("Unexpected intrinsic!");
00313     case Intrinsic::init_trampoline:
00314       return II->getArgOperand(0);
00315     }
00316   }
00317 
00318   CallSite CS = I;
00319   // All the supported functions so far happen to have dest as their first
00320   // argument.
00321   return CS.getArgument(0);
00322 }
00323 
00324 static uint64_t getPointerSize(const Value *V, AliasAnalysis &AA) {
00325   uint64_t Size;
00326   if (getObjectSize(V, Size, AA.getDataLayout(), AA.getTargetLibraryInfo()))
00327     return Size;
00328   return AliasAnalysis::UnknownSize;
00329 }
00330 
00331 namespace {
00332   enum OverwriteResult
00333   {
00334     OverwriteComplete,
00335     OverwriteEnd,
00336     OverwriteUnknown
00337   };
00338 }
00339 
00340 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location
00341 /// completely overwrites a store to the 'Earlier' location.
00342 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely
00343 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined
00344 static OverwriteResult isOverwrite(const AliasAnalysis::Location &Later,
00345                                    const AliasAnalysis::Location &Earlier,
00346                                    AliasAnalysis &AA,
00347                                    int64_t &EarlierOff,
00348                                    int64_t &LaterOff) {
00349   const DataLayout *DL = AA.getDataLayout();
00350   const Value *P1 = Earlier.Ptr->stripPointerCasts();
00351   const Value *P2 = Later.Ptr->stripPointerCasts();
00352 
00353   // If the start pointers are the same, we just have to compare sizes to see if
00354   // the later store was larger than the earlier store.
00355   if (P1 == P2) {
00356     // If we don't know the sizes of either access, then we can't do a
00357     // comparison.
00358     if (Later.Size == AliasAnalysis::UnknownSize ||
00359         Earlier.Size == AliasAnalysis::UnknownSize)
00360       return OverwriteUnknown;
00361 
00362     // Make sure that the Later size is >= the Earlier size.
00363     if (Later.Size >= Earlier.Size)
00364       return OverwriteComplete;
00365   }
00366 
00367   // Otherwise, we have to have size information, and the later store has to be
00368   // larger than the earlier one.
00369   if (Later.Size == AliasAnalysis::UnknownSize ||
00370       Earlier.Size == AliasAnalysis::UnknownSize || DL == nullptr)
00371     return OverwriteUnknown;
00372 
00373   // Check to see if the later store is to the entire object (either a global,
00374   // an alloca, or a byval/inalloca argument).  If so, then it clearly
00375   // overwrites any other store to the same object.
00376   const Value *UO1 = GetUnderlyingObject(P1, DL),
00377               *UO2 = GetUnderlyingObject(P2, DL);
00378 
00379   // If we can't resolve the same pointers to the same object, then we can't
00380   // analyze them at all.
00381   if (UO1 != UO2)
00382     return OverwriteUnknown;
00383 
00384   // If the "Later" store is to a recognizable object, get its size.
00385   uint64_t ObjectSize = getPointerSize(UO2, AA);
00386   if (ObjectSize != AliasAnalysis::UnknownSize)
00387     if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
00388       return OverwriteComplete;
00389 
00390   // Okay, we have stores to two completely different pointers.  Try to
00391   // decompose the pointer into a "base + constant_offset" form.  If the base
00392   // pointers are equal, then we can reason about the two stores.
00393   EarlierOff = 0;
00394   LaterOff = 0;
00395   const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
00396   const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
00397 
00398   // If the base pointers still differ, we have two completely different stores.
00399   if (BP1 != BP2)
00400     return OverwriteUnknown;
00401 
00402   // The later store completely overlaps the earlier store if:
00403   //
00404   // 1. Both start at the same offset and the later one's size is greater than
00405   //    or equal to the earlier one's, or
00406   //
00407   //      |--earlier--|
00408   //      |--   later   --|
00409   //
00410   // 2. The earlier store has an offset greater than the later offset, but which
00411   //    still lies completely within the later store.
00412   //
00413   //        |--earlier--|
00414   //    |-----  later  ------|
00415   //
00416   // We have to be careful here as *Off is signed while *.Size is unsigned.
00417   if (EarlierOff >= LaterOff &&
00418       Later.Size >= Earlier.Size &&
00419       uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
00420     return OverwriteComplete;
00421 
00422   // The other interesting case is if the later store overwrites the end of
00423   // the earlier store
00424   //
00425   //      |--earlier--|
00426   //                |--   later   --|
00427   //
00428   // In this case we may want to trim the size of earlier to avoid generating
00429   // writes to addresses which will definitely be overwritten later
00430   if (LaterOff > EarlierOff &&
00431       LaterOff < int64_t(EarlierOff + Earlier.Size) &&
00432       int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
00433     return OverwriteEnd;
00434 
00435   // Otherwise, they don't completely overlap.
00436   return OverwriteUnknown;
00437 }
00438 
00439 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a
00440 /// memory region into an identical pointer) then it doesn't actually make its
00441 /// input dead in the traditional sense.  Consider this case:
00442 ///
00443 ///   memcpy(A <- B)
00444 ///   memcpy(A <- A)
00445 ///
00446 /// In this case, the second store to A does not make the first store to A dead.
00447 /// The usual situation isn't an explicit A<-A store like this (which can be
00448 /// trivially removed) but a case where two pointers may alias.
00449 ///
00450 /// This function detects when it is unsafe to remove a dependent instruction
00451 /// because the DSE inducing instruction may be a self-read.
00452 static bool isPossibleSelfRead(Instruction *Inst,
00453                                const AliasAnalysis::Location &InstStoreLoc,
00454                                Instruction *DepWrite, AliasAnalysis &AA) {
00455   // Self reads can only happen for instructions that read memory.  Get the
00456   // location read.
00457   AliasAnalysis::Location InstReadLoc = getLocForRead(Inst, AA);
00458   if (!InstReadLoc.Ptr) return false;  // Not a reading instruction.
00459 
00460   // If the read and written loc obviously don't alias, it isn't a read.
00461   if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
00462 
00463   // Okay, 'Inst' may copy over itself.  However, we can still remove a the
00464   // DepWrite instruction if we can prove that it reads from the same location
00465   // as Inst.  This handles useful cases like:
00466   //   memcpy(A <- B)
00467   //   memcpy(A <- B)
00468   // Here we don't know if A/B may alias, but we do know that B/B are must
00469   // aliases, so removing the first memcpy is safe (assuming it writes <= #
00470   // bytes as the second one.
00471   AliasAnalysis::Location DepReadLoc = getLocForRead(DepWrite, AA);
00472 
00473   if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
00474     return false;
00475 
00476   // If DepWrite doesn't read memory or if we can't prove it is a must alias,
00477   // then it can't be considered dead.
00478   return true;
00479 }
00480 
00481 
00482 //===----------------------------------------------------------------------===//
00483 // DSE Pass
00484 //===----------------------------------------------------------------------===//
00485 
00486 bool DSE::runOnBasicBlock(BasicBlock &BB) {
00487   bool MadeChange = false;
00488 
00489   // Do a top-down walk on the BB.
00490   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
00491     Instruction *Inst = BBI++;
00492 
00493     // Handle 'free' calls specially.
00494     if (CallInst *F = isFreeCall(Inst, TLI)) {
00495       MadeChange |= HandleFree(F);
00496       continue;
00497     }
00498 
00499     // If we find something that writes memory, get its memory dependence.
00500     if (!hasMemoryWrite(Inst, TLI))
00501       continue;
00502 
00503     MemDepResult InstDep = MD->getDependency(Inst);
00504 
00505     // Ignore any store where we can't find a local dependence.
00506     // FIXME: cross-block DSE would be fun. :)
00507     if (!InstDep.isDef() && !InstDep.isClobber())
00508       continue;
00509 
00510     // If we're storing the same value back to a pointer that we just
00511     // loaded from, then the store can be removed.
00512     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00513       if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
00514         if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
00515             SI->getOperand(0) == DepLoad && isRemovable(SI)) {
00516           DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n  "
00517                        << "LOAD: " << *DepLoad << "\n  STORE: " << *SI << '\n');
00518 
00519           // DeleteDeadInstruction can delete the current instruction.  Save BBI
00520           // in case we need it.
00521           WeakVH NextInst(BBI);
00522 
00523           DeleteDeadInstruction(SI, *MD, TLI);
00524 
00525           if (!NextInst)  // Next instruction deleted.
00526             BBI = BB.begin();
00527           else if (BBI != BB.begin())  // Revisit this instruction if possible.
00528             --BBI;
00529           ++NumFastStores;
00530           MadeChange = true;
00531           continue;
00532         }
00533       }
00534     }
00535 
00536     // Figure out what location is being stored to.
00537     AliasAnalysis::Location Loc = getLocForWrite(Inst, *AA);
00538 
00539     // If we didn't get a useful location, fail.
00540     if (!Loc.Ptr)
00541       continue;
00542 
00543     while (InstDep.isDef() || InstDep.isClobber()) {
00544       // Get the memory clobbered by the instruction we depend on.  MemDep will
00545       // skip any instructions that 'Loc' clearly doesn't interact with.  If we
00546       // end up depending on a may- or must-aliased load, then we can't optimize
00547       // away the store and we bail out.  However, if we depend on on something
00548       // that overwrites the memory location we *can* potentially optimize it.
00549       //
00550       // Find out what memory location the dependent instruction stores.
00551       Instruction *DepWrite = InstDep.getInst();
00552       AliasAnalysis::Location DepLoc = getLocForWrite(DepWrite, *AA);
00553       // If we didn't get a useful location, or if it isn't a size, bail out.
00554       if (!DepLoc.Ptr)
00555         break;
00556 
00557       // If we find a write that is a) removable (i.e., non-volatile), b) is
00558       // completely obliterated by the store to 'Loc', and c) which we know that
00559       // 'Inst' doesn't load from, then we can remove it.
00560       if (isRemovable(DepWrite) &&
00561           !isPossibleSelfRead(Inst, Loc, DepWrite, *AA)) {
00562         int64_t InstWriteOffset, DepWriteOffset;
00563         OverwriteResult OR = isOverwrite(Loc, DepLoc, *AA,
00564                                          DepWriteOffset, InstWriteOffset);
00565         if (OR == OverwriteComplete) {
00566           DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: "
00567                 << *DepWrite << "\n  KILLER: " << *Inst << '\n');
00568 
00569           // Delete the store and now-dead instructions that feed it.
00570           DeleteDeadInstruction(DepWrite, *MD, TLI);
00571           ++NumFastStores;
00572           MadeChange = true;
00573 
00574           // DeleteDeadInstruction can delete the current instruction in loop
00575           // cases, reset BBI.
00576           BBI = Inst;
00577           if (BBI != BB.begin())
00578             --BBI;
00579           break;
00580         } else if (OR == OverwriteEnd && isShortenable(DepWrite)) {
00581           // TODO: base this on the target vector size so that if the earlier
00582           // store was too small to get vector writes anyway then its likely
00583           // a good idea to shorten it
00584           // Power of 2 vector writes are probably always a bad idea to optimize
00585           // as any store/memset/memcpy is likely using vector instructions so
00586           // shortening it to not vector size is likely to be slower
00587           MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
00588           unsigned DepWriteAlign = DepIntrinsic->getAlignment();
00589           if (llvm::isPowerOf2_64(InstWriteOffset) ||
00590               ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
00591 
00592             DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW END: "
00593                   << *DepWrite << "\n  KILLER (offset "
00594                   << InstWriteOffset << ", "
00595                   << DepLoc.Size << ")"
00596                   << *Inst << '\n');
00597 
00598             Value* DepWriteLength = DepIntrinsic->getLength();
00599             Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(),
00600                                                     InstWriteOffset -
00601                                                     DepWriteOffset);
00602             DepIntrinsic->setLength(TrimmedLength);
00603             MadeChange = true;
00604           }
00605         }
00606       }
00607 
00608       // If this is a may-aliased store that is clobbering the store value, we
00609       // can keep searching past it for another must-aliased pointer that stores
00610       // to the same location.  For example, in:
00611       //   store -> P
00612       //   store -> Q
00613       //   store -> P
00614       // we can remove the first store to P even though we don't know if P and Q
00615       // alias.
00616       if (DepWrite == &BB.front()) break;
00617 
00618       // Can't look past this instruction if it might read 'Loc'.
00619       if (AA->getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
00620         break;
00621 
00622       InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
00623     }
00624   }
00625 
00626   // If this block ends in a return, unwind, or unreachable, all allocas are
00627   // dead at its end, which means stores to them are also dead.
00628   if (BB.getTerminator()->getNumSuccessors() == 0)
00629     MadeChange |= handleEndBlock(BB);
00630 
00631   return MadeChange;
00632 }
00633 
00634 /// Find all blocks that will unconditionally lead to the block BB and append
00635 /// them to F.
00636 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
00637                                    BasicBlock *BB, DominatorTree *DT) {
00638   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
00639     BasicBlock *Pred = *I;
00640     if (Pred == BB) continue;
00641     TerminatorInst *PredTI = Pred->getTerminator();
00642     if (PredTI->getNumSuccessors() != 1)
00643       continue;
00644 
00645     if (DT->isReachableFromEntry(Pred))
00646       Blocks.push_back(Pred);
00647   }
00648 }
00649 
00650 /// HandleFree - Handle frees of entire structures whose dependency is a store
00651 /// to a field of that structure.
00652 bool DSE::HandleFree(CallInst *F) {
00653   bool MadeChange = false;
00654 
00655   AliasAnalysis::Location Loc = AliasAnalysis::Location(F->getOperand(0));
00656   SmallVector<BasicBlock *, 16> Blocks;
00657   Blocks.push_back(F->getParent());
00658 
00659   while (!Blocks.empty()) {
00660     BasicBlock *BB = Blocks.pop_back_val();
00661     Instruction *InstPt = BB->getTerminator();
00662     if (BB == F->getParent()) InstPt = F;
00663 
00664     MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
00665     while (Dep.isDef() || Dep.isClobber()) {
00666       Instruction *Dependency = Dep.getInst();
00667       if (!hasMemoryWrite(Dependency, TLI) || !isRemovable(Dependency))
00668         break;
00669 
00670       Value *DepPointer =
00671         GetUnderlyingObject(getStoredPointerOperand(Dependency));
00672 
00673       // Check for aliasing.
00674       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
00675         break;
00676 
00677       Instruction *Next = std::next(BasicBlock::iterator(Dependency));
00678 
00679       // DCE instructions only used to calculate that store
00680       DeleteDeadInstruction(Dependency, *MD, TLI);
00681       ++NumFastStores;
00682       MadeChange = true;
00683 
00684       // Inst's old Dependency is now deleted. Compute the next dependency,
00685       // which may also be dead, as in
00686       //    s[0] = 0;
00687       //    s[1] = 0; // This has just been deleted.
00688       //    free(s);
00689       Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
00690     }
00691 
00692     if (Dep.isNonLocal())
00693       FindUnconditionalPreds(Blocks, BB, DT);
00694   }
00695 
00696   return MadeChange;
00697 }
00698 
00699 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
00700 /// function end block.  Ex:
00701 /// %A = alloca i32
00702 /// ...
00703 /// store i32 1, i32* %A
00704 /// ret void
00705 bool DSE::handleEndBlock(BasicBlock &BB) {
00706   bool MadeChange = false;
00707 
00708   // Keep track of all of the stack objects that are dead at the end of the
00709   // function.
00710   SmallSetVector<Value*, 16> DeadStackObjects;
00711 
00712   // Find all of the alloca'd pointers in the entry block.
00713   BasicBlock *Entry = BB.getParent()->begin();
00714   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
00715     if (isa<AllocaInst>(I))
00716       DeadStackObjects.insert(I);
00717 
00718     // Okay, so these are dead heap objects, but if the pointer never escapes
00719     // then it's leaked by this function anyways.
00720     else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
00721       DeadStackObjects.insert(I);
00722   }
00723 
00724   // Treat byval or inalloca arguments the same, stores to them are dead at the
00725   // end of the function.
00726   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
00727        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
00728     if (AI->hasByValOrInAllocaAttr())
00729       DeadStackObjects.insert(AI);
00730 
00731   // Scan the basic block backwards
00732   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
00733     --BBI;
00734 
00735     // If we find a store, check to see if it points into a dead stack value.
00736     if (hasMemoryWrite(BBI, TLI) && isRemovable(BBI)) {
00737       // See through pointer-to-pointer bitcasts
00738       SmallVector<Value *, 4> Pointers;
00739       GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers);
00740 
00741       // Stores to stack values are valid candidates for removal.
00742       bool AllDead = true;
00743       for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
00744            E = Pointers.end(); I != E; ++I)
00745         if (!DeadStackObjects.count(*I)) {
00746           AllDead = false;
00747           break;
00748         }
00749 
00750       if (AllDead) {
00751         Instruction *Dead = BBI++;
00752 
00753         DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
00754                      << *Dead << "\n  Objects: ";
00755               for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
00756                    E = Pointers.end(); I != E; ++I) {
00757                 dbgs() << **I;
00758                 if (std::next(I) != E)
00759                   dbgs() << ", ";
00760               }
00761               dbgs() << '\n');
00762 
00763         // DCE instructions only used to calculate that store.
00764         DeleteDeadInstruction(Dead, *MD, TLI, &DeadStackObjects);
00765         ++NumFastStores;
00766         MadeChange = true;
00767         continue;
00768       }
00769     }
00770 
00771     // Remove any dead non-memory-mutating instructions.
00772     if (isInstructionTriviallyDead(BBI, TLI)) {
00773       Instruction *Inst = BBI++;
00774       DeleteDeadInstruction(Inst, *MD, TLI, &DeadStackObjects);
00775       ++NumFastOther;
00776       MadeChange = true;
00777       continue;
00778     }
00779 
00780     if (isa<AllocaInst>(BBI)) {
00781       // Remove allocas from the list of dead stack objects; there can't be
00782       // any references before the definition.
00783       DeadStackObjects.remove(BBI);
00784       continue;
00785     }
00786 
00787     if (CallSite CS = cast<Value>(BBI)) {
00788       // Remove allocation function calls from the list of dead stack objects; 
00789       // there can't be any references before the definition.
00790       if (isAllocLikeFn(BBI, TLI))
00791         DeadStackObjects.remove(BBI);
00792 
00793       // If this call does not access memory, it can't be loading any of our
00794       // pointers.
00795       if (AA->doesNotAccessMemory(CS))
00796         continue;
00797 
00798       // If the call might load from any of our allocas, then any store above
00799       // the call is live.
00800       DeadStackObjects.remove_if([&](Value *I) {
00801         // See if the call site touches the value.
00802         AliasAnalysis::ModRefResult A =
00803             AA->getModRefInfo(CS, I, getPointerSize(I, *AA));
00804 
00805         return A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref;
00806       });
00807 
00808       // If all of the allocas were clobbered by the call then we're not going
00809       // to find anything else to process.
00810       if (DeadStackObjects.empty())
00811         break;
00812 
00813       continue;
00814     }
00815 
00816     AliasAnalysis::Location LoadedLoc;
00817 
00818     // If we encounter a use of the pointer, it is no longer considered dead
00819     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
00820       if (!L->isUnordered()) // Be conservative with atomic/volatile load
00821         break;
00822       LoadedLoc = AA->getLocation(L);
00823     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
00824       LoadedLoc = AA->getLocation(V);
00825     } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
00826       LoadedLoc = AA->getLocationForSource(MTI);
00827     } else if (!BBI->mayReadFromMemory()) {
00828       // Instruction doesn't read memory.  Note that stores that weren't removed
00829       // above will hit this case.
00830       continue;
00831     } else {
00832       // Unknown inst; assume it clobbers everything.
00833       break;
00834     }
00835 
00836     // Remove any allocas from the DeadPointer set that are loaded, as this
00837     // makes any stores above the access live.
00838     RemoveAccessedObjects(LoadedLoc, DeadStackObjects);
00839 
00840     // If all of the allocas were clobbered by the access then we're not going
00841     // to find anything else to process.
00842     if (DeadStackObjects.empty())
00843       break;
00844   }
00845 
00846   return MadeChange;
00847 }
00848 
00849 /// RemoveAccessedObjects - Check to see if the specified location may alias any
00850 /// of the stack objects in the DeadStackObjects set.  If so, they become live
00851 /// because the location is being loaded.
00852 void DSE::RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
00853                                 SmallSetVector<Value*, 16> &DeadStackObjects) {
00854   const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr);
00855 
00856   // A constant can't be in the dead pointer set.
00857   if (isa<Constant>(UnderlyingPointer))
00858     return;
00859 
00860   // If the kill pointer can be easily reduced to an alloca, don't bother doing
00861   // extraneous AA queries.
00862   if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
00863     DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
00864     return;
00865   }
00866 
00867   // Remove objects that could alias LoadedLoc.
00868   DeadStackObjects.remove_if([&](Value *I) {
00869     // See if the loaded location could alias the stack location.
00870     AliasAnalysis::Location StackLoc(I, getPointerSize(I, *AA));
00871     return !AA->isNoAlias(StackLoc, LoadedLoc);
00872   });
00873 }