teach DSE to use GetPointerBaseWithConstantOffset to analyze
[oota-llvm.git] / lib / Transforms / Scalar / DeadStoreElimination.cpp
index 40986d1a36faf3cb97d4fd638232ec8936cca654..78004595ece8a7331f15164b9848f66788e889eb 100644 (file)
@@ -28,6 +28,7 @@
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Transforms/Utils/Local.h"
 using namespace llvm;
@@ -64,10 +65,8 @@ namespace {
     bool runOnBasicBlock(BasicBlock &BB);
     bool HandleFree(CallInst *F);
     bool handleEndBlock(BasicBlock &BB);
-    void RemoveAccessedObjects(Value *Ptr, uint64_t killPointerSize,
-                               SmallPtrSet<Value*, 16> &deadPointers);
-    void DeleteDeadInstruction(Instruction *I,
-                               SmallPtrSet<Value*, 16> *deadPointers = 0);
+    void RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
+                               SmallPtrSet<Value*, 16> &DeadStackObjects);
     
 
     // getAnalysisUsage - We require post dominance frontiers (aka Control
@@ -93,6 +92,53 @@ INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
 
 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
 
+//===----------------------------------------------------------------------===//
+// Helper functions
+//===----------------------------------------------------------------------===//
+
+/// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
+/// and zero out all the operands of this instruction.  If any of them become
+/// dead, delete them and the computation tree that feeds them.
+///
+/// If ValueSet is non-null, remove any deleted instructions from it as well.
+///
+static void DeleteDeadInstruction(Instruction *I,
+                                  MemoryDependenceAnalysis &MD,
+                                  SmallPtrSet<Value*, 16> *ValueSet = 0) {
+  SmallVector<Instruction*, 32> NowDeadInsts;
+  
+  NowDeadInsts.push_back(I);
+  --NumFastOther;
+  
+  // Before we touch this instruction, remove it from memdep!
+  do {
+    Instruction *DeadInst = NowDeadInsts.pop_back_val();
+    ++NumFastOther;
+    
+    // This instruction is dead, zap it, in stages.  Start by removing it from
+    // MemDep, which needs to know the operands and needs it to be in the
+    // function.
+    MD.removeInstruction(DeadInst);
+    
+    for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
+      Value *Op = DeadInst->getOperand(op);
+      DeadInst->setOperand(op, 0);
+      
+      // If this operand just became dead, add it to the NowDeadInsts list.
+      if (!Op->use_empty()) continue;
+      
+      if (Instruction *OpI = dyn_cast<Instruction>(Op))
+        if (isInstructionTriviallyDead(OpI))
+          NowDeadInsts.push_back(OpI);
+    }
+    
+    DeadInst->eraseFromParent();
+    
+    if (ValueSet) ValueSet->erase(DeadInst);
+  } while (!NowDeadInsts.empty());
+}
+
+
 /// hasMemoryWrite - Does this instruction write some memory?  This only returns
 /// true for things that we can analyze with other helpers below.
 static bool hasMemoryWrite(Instruction *I) {
@@ -177,21 +223,18 @@ static bool isRemovable(Instruction *I) {
   }
 }
 
-/// getPointerOperand - Return the pointer that is being written to.
-static Value *getPointerOperand(Instruction *I) {
-  assert(hasMemoryWrite(I));
+/// getStoredPointerOperand - Return the pointer that is being written to.
+static Value *getStoredPointerOperand(Instruction *I) {
   if (StoreInst *SI = dyn_cast<StoreInst>(I))
     return SI->getPointerOperand();
   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
-    return MI->getArgOperand(0);
+    return MI->getDest();
 
   IntrinsicInst *II = cast<IntrinsicInst>(I);
   switch (II->getIntrinsicID()) {
   default: assert(false && "Unexpected intrinsic!");
   case Intrinsic::init_trampoline:
     return II->getArgOperand(0);
-  case Intrinsic::lifetime_end:
-    return II->getArgOperand(1);
   }
 }
 
@@ -218,31 +261,68 @@ static uint64_t getPointerSize(Value *V, AliasAnalysis &AA) {
 static bool isCompleteOverwrite(const AliasAnalysis::Location &Later,
                                 const AliasAnalysis::Location &Earlier,
                                 AliasAnalysis &AA) {
-  const Value *P1 = Later.Ptr->stripPointerCasts();
-  const Value *P2 = Earlier.Ptr->stripPointerCasts();
+  const Value *P1 = Earlier.Ptr->stripPointerCasts();
+  const Value *P2 = Later.Ptr->stripPointerCasts();
   
-  // Make sure that the start pointers are the same.
-  if (P1 != P2)
-    return false;
-
-  // If we don't know the sizes of either access, then we can't do a comparison.
+  // If the start pointers are the same, we just have to compare sizes to see if
+  // the later store was larger than the earlier store.
+  if (P1 == P2) {
+    // If we don't know the sizes of either access, then we can't do a
+    // comparison.
+    if (Later.Size == AliasAnalysis::UnknownSize ||
+        Earlier.Size == AliasAnalysis::UnknownSize) {
+      // If we have no TargetData information around, then the size of the store
+      // is inferrable from the pointee type.  If they are the same type, then
+      // we know that the store is safe.
+      if (AA.getTargetData() == 0)
+        return Later.Ptr->getType() == Earlier.Ptr->getType();
+      return false;
+    }
+    
+    // Make sure that the Later size is >= the Earlier size.
+    if (Later.Size < Earlier.Size)
+      return false;
+    return true;
+  }
+  
+  // Otherwise, we have to have size information, and the later store has to be
+  // larger than the earlier one.
   if (Later.Size == AliasAnalysis::UnknownSize ||
-      Earlier.Size == AliasAnalysis::UnknownSize) {
-    // If we have no TargetData information around, then the size of the store
-    // is inferrable from the pointee type.  If they are the same type, then we
-    // know that the store is safe.
-    if (AA.getTargetData() == 0)
-      return Later.Ptr->getType() == Earlier.Ptr->getType();
+      Earlier.Size == AliasAnalysis::UnknownSize ||
+      Later.Size <= Earlier.Size ||
+      AA.getTargetData() == 0)
     return false;
-  }
   
-  // Make sure that the Later size is >= the Earlier size.
-  if (Later.Size < Earlier.Size)
+  const TargetData &TD = *AA.getTargetData();
+  
+  // Okay, we have stores to two completely different pointers.  Try to
+  // decompose the pointer into a "base + constant_offset" form.  If the base
+  // pointers are equal, then we can reason about the two stores.
+  int64_t Off1 = 0, Off2 = 0;
+  const Value *BP1 = GetPointerBaseWithConstantOffset(P1, Off1, TD);
+  const Value *BP2 = GetPointerBaseWithConstantOffset(P2, Off2, TD);
+  
+  // If the base pointers still differ, we have two completely different stores.
+  if (BP1 != BP2)
     return false;
   
+  // Otherwise, we might have a situation like:
+  //  store i16 -> P + 1 Byte
+  //  store i32 -> P
+  // In this case, we see if the later store completely overlaps all bytes
+  // stored by the previous store.
+  if (Off1 < Off2 ||                       // Earlier starts before Later.
+      Off1+Earlier.Size > Off2+Later.Size) // Earlier goes beyond Later.
+    return false;
+  // Otherwise, we have complete overlap.
   return true;
 }
 
+
+//===----------------------------------------------------------------------===//
+// DSE Pass
+//===----------------------------------------------------------------------===//
+
 bool DSE::runOnBasicBlock(BasicBlock &BB) {
   bool MadeChange = false;
   
@@ -280,7 +360,7 @@ bool DSE::runOnBasicBlock(BasicBlock &BB) {
           // in case we need it.
           WeakVH NextInst(BBI);
           
-          DeleteDeadInstruction(SI);
+          DeleteDeadInstruction(SI, *MD);
           
           if (NextInst == 0)  // Next instruction deleted.
             BBI = BB.begin();
@@ -318,7 +398,7 @@ bool DSE::runOnBasicBlock(BasicBlock &BB) {
       // store to 'Loc' then we can remove it.
       if (isRemovable(DepWrite) && isCompleteOverwrite(Loc, DepLoc, *AA)) {
         // Delete the store and now-dead instructions that feed it.
-        DeleteDeadInstruction(DepWrite);
+        DeleteDeadInstruction(DepWrite, *MD);
         ++NumFastStores;
         MadeChange = true;
         
@@ -367,7 +447,8 @@ bool DSE::HandleFree(CallInst *F) {
     if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
       return false;
   
-    Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
+    Value *DepPointer =
+      getStoredPointerOperand(Dependency)->getUnderlyingObject();
 
     // Check for aliasing.
     if (AA->alias(F->getArgOperand(0), 1, DepPointer, 1) !=
@@ -375,7 +456,7 @@ bool DSE::HandleFree(CallInst *F) {
       return false;
   
     // DCE instructions only used to calculate that store
-    DeleteDeadInstruction(Dependency);
+    DeleteDeadInstruction(Dependency, *MD);
     ++NumFastStores;
 
     // Inst's old Dependency is now deleted. Compute the next dependency,
@@ -422,14 +503,13 @@ bool DSE::handleEndBlock(BasicBlock &BB) {
     // If we find a store, check to see if it points into a dead stack value.
     if (hasMemoryWrite(BBI) && isRemovable(BBI)) {
       // See through pointer-to-pointer bitcasts
-      Value *Pointer = getPointerOperand(BBI)->getUnderlyingObject();
+      Value *Pointer = getStoredPointerOperand(BBI)->getUnderlyingObject();
 
-      // Alloca'd pointers or byval arguments (which are functionally like
-      // alloca's) are valid candidates for removal.
+      // Stores to stack values are valid candidates for removal.
       if (DeadStackObjects.count(Pointer)) {
         // DCE instructions only used to calculate that store.
         Instruction *Dead = BBI++;
-        DeleteDeadInstruction(Dead, &DeadStackObjects);
+        DeleteDeadInstruction(Dead, *MD, &DeadStackObjects);
         ++NumFastStores;
         MadeChange = true;
         continue;
@@ -439,7 +519,7 @@ bool DSE::handleEndBlock(BasicBlock &BB) {
     // Remove any dead non-memory-mutating instructions.
     if (isInstructionTriviallyDead(BBI)) {
       Instruction *Inst = BBI++;
-      DeleteDeadInstruction(Inst, &DeadStackObjects);
+      DeleteDeadInstruction(Inst, *MD, &DeadStackObjects);
       ++NumFastOther;
       MadeChange = true;
       continue;
@@ -494,18 +574,15 @@ bool DSE::handleEndBlock(BasicBlock &BB) {
       continue;
     }
     
-    Value *KillPointer = 0;
-    uint64_t KillPointerSize = AliasAnalysis::UnknownSize;
+    AliasAnalysis::Location LoadedLoc;
     
     // If we encounter a use of the pointer, it is no longer considered dead
     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
-      KillPointer = L->getPointerOperand();
+      LoadedLoc = AA->getLocation(L);
     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
-      KillPointer = V->getOperand(0);
+      LoadedLoc = AA->getLocation(V);
     } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
-      KillPointer = cast<MemTransferInst>(BBI)->getSource();
-      if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
-        KillPointerSize = Len->getZExtValue();
+      LoadedLoc = AA->getLocationForSource(MTI);
     } else {
       // Not a loading instruction.
       continue;
@@ -513,7 +590,7 @@ bool DSE::handleEndBlock(BasicBlock &BB) {
 
     // Remove any allocas from the DeadPointer set that are loaded, as this
     // makes any stores above the access live.
-    RemoveAccessedObjects(KillPointer, KillPointerSize, DeadStackObjects);
+    RemoveAccessedObjects(LoadedLoc, DeadStackObjects);
 
     // If all of the allocas were clobbered by the access then we're not going
     // to find anything else to process.
@@ -527,9 +604,9 @@ bool DSE::handleEndBlock(BasicBlock &BB) {
 /// RemoveAccessedObjects - Check to see if the specified location may alias any
 /// of the stack objects in the DeadStackObjects set.  If so, they become live
 /// because the location is being loaded.
-void DSE::RemoveAccessedObjects(Value *KillPointer, uint64_t KillPointerSize,
+void DSE::RemoveAccessedObjects(const AliasAnalysis::Location &LoadedLoc,
                                 SmallPtrSet<Value*, 16> &DeadStackObjects) {
-  Value *UnderlyingPointer = KillPointer->getUnderlyingObject();
+  const Value *UnderlyingPointer = LoadedLoc.Ptr->getUnderlyingObject();
 
   // A constant can't be in the dead pointer set.
   if (isa<Constant>(UnderlyingPointer))
@@ -538,17 +615,16 @@ void DSE::RemoveAccessedObjects(Value *KillPointer, uint64_t KillPointerSize,
   // If the kill pointer can be easily reduced to an alloca, don't bother doing
   // extraneous AA queries.
   if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
-    DeadStackObjects.erase(UnderlyingPointer);
+    DeadStackObjects.erase(const_cast<Value*>(UnderlyingPointer));
     return;
   }
   
   SmallVector<Value*, 16> NowLive;
   for (SmallPtrSet<Value*, 16>::iterator I = DeadStackObjects.begin(),
        E = DeadStackObjects.end(); I != E; ++I) {
-    // See if this pointer could alias it
-    AliasAnalysis::AliasResult A = AA->alias(*I, getPointerSize(*I, *AA),
-                                             KillPointer, KillPointerSize);
-    if (A != AliasAnalysis::NoAlias)
+    // See if the loaded location could alias the stack location.
+    AliasAnalysis::Location StackLoc(*I, getPointerSize(*I, *AA));
+    if (!AA->isNoAlias(StackLoc, LoadedLoc))
       NowLive.push_back(*I);
   }
 
@@ -557,45 +633,3 @@ void DSE::RemoveAccessedObjects(Value *KillPointer, uint64_t KillPointerSize,
     DeadStackObjects.erase(*I);
 }
 
-/// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
-/// and zero out all the operands of this instruction.  If any of them become
-/// dead, delete them and the computation tree that feeds them.
-///
-/// If ValueSet is non-null, remove any deleted instructions from it as well.
-///
-void DSE::DeleteDeadInstruction(Instruction *I,
-                                SmallPtrSet<Value*, 16> *ValueSet) {
-  SmallVector<Instruction*, 32> NowDeadInsts;
-  
-  NowDeadInsts.push_back(I);
-  --NumFastOther;
-
-  // Before we touch this instruction, remove it from memdep!
-  do {
-    Instruction *DeadInst = NowDeadInsts.pop_back_val();
-    
-    ++NumFastOther;
-    
-    // This instruction is dead, zap it, in stages.  Start by removing it from
-    // MemDep, which needs to know the operands and needs it to be in the
-    // function.
-    MD->removeInstruction(DeadInst);
-    
-    for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
-      Value *Op = DeadInst->getOperand(op);
-      DeadInst->setOperand(op, 0);
-      
-      // If this operand just became dead, add it to the NowDeadInsts list.
-      if (!Op->use_empty()) continue;
-      
-      if (Instruction *OpI = dyn_cast<Instruction>(Op))
-        if (isInstructionTriviallyDead(OpI))
-          NowDeadInsts.push_back(OpI);
-    }
-    
-    DeadInst->eraseFromParent();
-    
-    if (ValueSet) ValueSet->erase(DeadInst);
-  } while (!NowDeadInsts.empty());
-}
-