Remove useless check.
[oota-llvm.git] / lib / Transforms / Scalar / TailDuplication.cpp
index 0a05d0f9e72246a6337f391161537cb310e4fe58..8cb28a3b06c4a87da75bba365b9bc60d553afd02 100644 (file)
@@ -1,10 +1,10 @@
 //===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by the LLVM research group and is distributed under
-// the University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
 //===----------------------------------------------------------------------===//
 //
 // This pass performs a limited form of tail duplication, intended to simplify
@@ -18,6 +18,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#define DEBUG_TYPE "tailduplicate"
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Constant.h"
 #include "llvm/Function.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include <map>
 using namespace llvm;
 
+STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
+
+static cl::opt<unsigned>
+Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
+          cl::init(6), cl::Hidden);
+
 namespace {
-  cl::opt<unsigned>
-  Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
-            cl::init(6), cl::Hidden);
-  Statistic<> NumEliminated("tailduplicate",
-                            "Number of unconditional branches eliminated");
-  Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
-
-  class TailDup : public FunctionPass {
+  class VISIBILITY_HIDDEN TailDup : public FunctionPass {
     bool runOnFunction(Function &F);
+  public:
+    static char ID; // Pass identification, replacement for typeid
+    TailDup() : FunctionPass((intptr_t)&ID) {}
+
   private:
     inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
     inline void eliminateUnconditionalBranch(BranchInst *BI);
+    SmallPtrSet<BasicBlock*, 4> CycleDetector;
   };
-  RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
 }
 
+char TailDup::ID = 0;
+static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
+
 // Public interface to the Tail Duplication pass
 FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
 
 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
-/// the function, eliminating it if it looks attractive enough.
-///
+/// the function, eliminating it if it looks attractive enough.  CycleDetector
+/// prevents infinite loops by checking that we aren't redirecting a branch to
+/// a place it already pointed to earlier; see PR 2323.
 bool TailDup::runOnFunction(Function &F) {
   bool Changed = false;
-  for (Function::iterator I = F.begin(), E = F.end(); I != E; )
+  CycleDetector.clear();
+  for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
     if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
       Changed = true;
     } else {
       ++I;
+      CycleDetector.clear();
     }
+  }
   return Changed;
 }
 
@@ -95,13 +109,9 @@ bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
   if (!DTI->use_empty())
     return false;
 
-  // Do not bother working on dead blocks...
-  pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
-  if (PI == PE && Dest != Dest->getParent()->begin())
-    return false;   // It's just a dead block, ignore it...
-
-  // Also, do not bother with blocks with only a single predecessor: simplify
+  // Do not bother with blocks with only a single predecessor: simplify
   // CFG will fold these two blocks together!
+  pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
   ++PI;
   if (PI == PE) return false;  // Exactly one predecessor!
 
@@ -110,6 +120,11 @@ bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
 
   for (unsigned Size = 0; I != Dest->end(); ++I) {
     if (Size == Threshold) return false;  // The block is too large.
+    
+    // Don't tail duplicate call instructions.  They are very large compared to
+    // other instructions.
+    if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
+    
     // Only count instructions that are not debugger intrinsics.
     if (!isa<DbgInfoIntrinsic>(I)) ++Size;
   }
@@ -126,8 +141,43 @@ bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
     for (; PI != PE; ++PI)
       if (TooMany-- == 0) return false;
   }
+  
+  // If this unconditional branch is a fall-through, be careful about
+  // tail duplicating it.  In particular, we don't want to taildup it if the
+  // original block will still be there after taildup is completed: doing so
+  // would eliminate the fall-through, requiring unconditional branches.
+  Function::iterator DestI = Dest;
+  if (&*--DestI == BI->getParent()) {
+    // The uncond branch is a fall-through.  Tail duplication of the block is
+    // will eliminate the fall-through-ness and end up cloning the terminator
+    // at the end of the Dest block.  Since the original Dest block will
+    // continue to exist, this means that one or the other will not be able to
+    // fall through.  One typical example that this helps with is code like:
+    // if (a)
+    //   foo();
+    // if (b)
+    //   foo();
+    // Cloning the 'if b' block into the end of the first foo block is messy.
+    
+    // The messy case is when the fall-through block falls through to other
+    // blocks.  This is what we would be preventing if we cloned the block.
+    DestI = Dest;
+    if (++DestI != Dest->getParent()->end()) {
+      BasicBlock *DestSucc = DestI;
+      // If any of Dest's successors are fall-throughs, don't do this xform.
+      for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
+           SI != SE; ++SI)
+        if (*SI == DestSucc)
+          return false;
+    }
+  }
 
-  return true;  
+  // Finally, check that we haven't redirected to this target block earlier;
+  // there are cases where we loop forever if we don't check this (PR 2323).
+  if (!CycleDetector.insert(Dest))
+    return false;
+
+  return true;
 }
 
 /// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
@@ -141,7 +191,7 @@ static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
   if (PI == PE || ++PI != PE) return 0;
 
   BasicBlock *SrcPred = *pred_begin(SrcBlock);
-  
+
   // Look at the predecessors of DstBlock.  One of them will be SrcBlock.  If
   // there is only one other pred, get it, otherwise we can't handle it.
   PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
@@ -183,14 +233,13 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
   BasicBlock *DestBlock = Branch->getSuccessor(0);
   assert(SourceBlock != DestBlock && "Our predicate is broken!");
 
-  DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
-                  << "]: Eliminating branch: " << *Branch);
+  DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
+       << "]: Eliminating branch: " << *Branch;
 
   // See if we can avoid duplicating code by moving it up to a dominator of both
   // blocks.
   if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
-    DEBUG(std::cerr << "Found shared dominator: " << DomBlock->getName()
-                    << "\n");
+    DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
 
     // If there are non-phi instructions in DestBlock that have no operands
     // defined in DestBlock, and if the instruction has no side effects, we can
@@ -199,7 +248,7 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
     while (isa<PHINode>(BBI)) ++BBI;
     while (!isa<TerminatorInst>(BBI)) {
       Instruction *I = BBI++;
-      
+
       bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
       if (CanHoist) {
         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
@@ -213,7 +262,7 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
           // Remove from DestBlock, move right before the term in DomBlock.
           DestBlock->getInstList().remove(I);
           DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
-          DEBUG(std::cerr << "Hoisted: " << *I);
+          DOUT << "Hoisted: " << *I;
         }
       }
     }
@@ -224,40 +273,10 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
   // this reason, we spill all values that are used outside of the tail to the
   // stack.
   for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
-    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
-         ++UI) {
-      bool ShouldDemote = false;
-      if (cast<Instruction>(*UI)->getParent() != DestBlock) {
-        // We must allow our successors to use tail values in their PHI nodes
-        // (if the incoming value corresponds to the tail block).
-        if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
-          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
-            if (PN->getIncomingValue(i) == I &&
-                PN->getIncomingBlock(i) != DestBlock) {
-              ShouldDemote = true;
-              break;
-            }
-
-        } else {
-          ShouldDemote = true;
-        }
-      } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
-        // If the user of this instruction is a PHI node in the current block,
-        // which has an entry from another block using the value, spill it.
-        for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
-          if (PN->getIncomingValue(i) == I &&
-              PN->getIncomingBlock(i) != DestBlock) {
-            ShouldDemote = true;
-            break;
-          }
-      }
-
-      if (ShouldDemote) {
-        // We found a use outside of the tail.  Create a new stack slot to
-        // break this inter-block usage pattern.
-        DemoteRegToStack(*I);
-        break;
-      }
+    if (I->isUsedOutsideOfBlock(DestBlock)) {
+      // We found a use outside of the tail.  Create a new stack slot to
+      // break this inter-block usage pattern.
+      DemoteRegToStack(*I);
     }
 
   // We are going to have to map operands from the original block B to the new
@@ -303,7 +322,7 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
       // Ok, we have a PHI node.  Figure out what the incoming value was for the
       // DestBlock.
       Value *IV = PN->getIncomingValueForBlock(DestBlock);
-      
+
       // Remap the value if necessary...
       if (Value *MappedIV = ValueMapping[IV])
         IV = MappedIV;