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