[RS4GC] Use an value handle to help isolate errors quickly
[oota-llvm.git] / lib / Transforms / Scalar / DCE.cpp
index 797edf50544898c8e4eb1aa9934893d936d498cb..b67c3c7742fd7d37bbf53b9c6e603c7880f0cd91 100644 (file)
 //===- DCE.cpp - Code to perform dead code elimination --------------------===//
 //
-// This file implements dead code elimination and basic block merging.
+//                     The LLVM Compiler Infrastructure
 //
-// Specifically, this:
-//   * removes definitions with no uses (including unused constants)
-//   * removes basic blocks with no predecessors
-//   * merges a basic block into its predecessor if there is only one and the
-//     predecessor only has one successor.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
-// TODO: This should REALLY be recursive instead of iterative.  Right now, we 
-// scan linearly through values, removing unused ones as we go.  The problem is
-// that this may cause other earlier values to become unused.  To make sure that
-// we get them all, we iterate until things stop changing.  Instead, when 
-// removing a value, recheck all of its operands to see if they are now unused.
-// Piece of cake, and more efficient as well.
+//===----------------------------------------------------------------------===//
+//
+// This file implements dead inst elimination and dead code elimination.
+//
+// Dead Inst Elimination performs a single pass over the function removing
+// instructions that are obviously dead.  Dead Code Elimination is similar, but
+// it rechecks instructions that were used by removed instructions to see if
+// they are newly dead.
 //
 //===----------------------------------------------------------------------===//
 
-#include "llvm/Module.h"
-#include "llvm/Method.h"
-#include "llvm/BasicBlock.h"
-#include "llvm/iTerminators.h"
-#include "llvm/Opt/AllOpts.h"
-
-struct ConstPoolDCE { 
-  enum { EndOffs = 0 };
-  static bool isDCEable(const Value *) { return true; } 
-};
-
-struct BasicBlockDCE {
-  enum { EndOffs = 1 };
-  static bool isDCEable(const Instruction *I) {
-    return !I->hasSideEffects();
-  }
-};
-
-template<class ValueSubclass, class ItemParentType, class DCEController>
-static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals, 
-                            DCEController DCEControl) {
-  bool Changed = false;
-  typedef ValueHolder<ValueSubclass, ItemParentType> Container;
-
-  int Offset = DCEController::EndOffs;
-  for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) {
-    // Look for un"used" definitions...
-    if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {
-      // Bye bye
-      delete Vals.remove(DI);
-      Changed = true;
-    } else {
-      DI++;
-    }
-  }
-  return Changed;
-}
-
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Instruction.h"
+#include "llvm/Pass.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Transforms/Utils/Local.h"
+using namespace llvm;
 
-bool DoRemoveUnusedConstants(SymTabValue *S) {
-  bool Changed = false;
-  ConstantPool &CP = S->getConstantPool();
-  for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI)
-    Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE());
-  return Changed;
-}
+#define DEBUG_TYPE "dce"
 
+STATISTIC(DIEEliminated, "Number of insts removed by DIE pass");
+STATISTIC(DCEEliminated, "Number of insts removed");
 
-static void ReplaceUsesWithConstant(Instruction *I) {
-  // Get the method level constant pool
-  ConstantPool &CP = I->getParent()->getParent()->getConstantPool();
+namespace {
+  //===--------------------------------------------------------------------===//
+  // DeadInstElimination pass implementation
+  //
+  struct DeadInstElimination : public BasicBlockPass {
+    static char ID; // Pass identification, replacement for typeid
+    DeadInstElimination() : BasicBlockPass(ID) {
+      initializeDeadInstEliminationPass(*PassRegistry::getPassRegistry());
+    }
+    bool runOnBasicBlock(BasicBlock &BB) override {
+      if (skipOptnoneFunction(BB))
+        return false;
+      auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
+      TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI() : nullptr;
+      bool Changed = false;
+      for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) {
+        Instruction *Inst = &*DI++;
+        if (isInstructionTriviallyDead(Inst, TLI)) {
+          Inst->eraseFromParent();
+          Changed = true;
+          ++DIEEliminated;
+        }
+      }
+      return Changed;
+    }
 
-  ConstPoolVal *CPV = 0;
-  ConstantPool::PlaneType *P;
-  if (!CP.getPlane(I->getType(), P)) {  // Does plane exist?
-    // Yes, is it empty?
-    if (!P->empty()) CPV = P->front();
-  }
+    void getAnalysisUsage(AnalysisUsage &AU) const override {
+      AU.setPreservesCFG();
+    }
+  };
+}
 
-  if (CPV == 0) { // We don't have an existing constant to reuse.  Just add one.
-    CPV = ConstPoolVal::getNullConstant(I->getType());  // Create a new constant
+char DeadInstElimination::ID = 0;
+INITIALIZE_PASS(DeadInstElimination, "die",
+                "Dead Instruction Elimination", false, false)
 
-    // Add the new value to the constant pool...
-    CP.insert(CPV);
-  }
-  
-  // Make all users of this instruction reference the constant instead
-  I->replaceAllUsesWith(CPV);
+Pass *llvm::createDeadInstEliminationPass() {
+  return new DeadInstElimination();
 }
 
-static bool DoDCEPass(Method *M) {
-  Method::BasicBlocksType::iterator BBIt;
-  Method::BasicBlocksType &BBs = M->getBasicBlocks();
-  bool Changed = false;
-
-  // Loop through now and remove instructions that have no uses...
-  for (BBIt = BBs.begin(); BBIt != BBs.end(); BBIt++)
-    Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());
 
-  // Scan through and remove basic blocks that have no predecessors (except,
-  // of course, the first one.  :)  (so skip first block)
+namespace {
+  //===--------------------------------------------------------------------===//
+  // DeadCodeElimination pass implementation
   //
-  for (BBIt = BBs.begin(), ++BBIt; BBIt != BBs.end(); BBIt++) {
-    BasicBlock *BB = *BBIt;
-    assert(BB->getTerminator() && 
-          "Degenerate basic block encountered!");  // Empty bb???
-
-    if (BB->pred_begin() == BB->pred_end() &&
-       !BB->hasConstantPoolReferences()) {
-
-      while (!BB->getInstList().empty()) {
-       Instruction *I = BB->getInstList().front();
-       // If this instruction is used, replace uses with an arbitrary
-       // constant value.  Because control flow can't get here, we don't care
-       // what we replace the value with.
-       if (!I->use_empty()) ReplaceUsesWithConstant(I);
-
-       // Remove the instruction from the basic block
-       BasicBlock::InstListType::iterator f = BB->getInstList().begin();
-       delete BB->getInstList().remove(f);
-      }
-
-      delete BBs.remove(BBIt);
-      ++BBIt;  // remove puts use on the previous block, we want the next one
-      Changed = true;
+  struct DCE : public FunctionPass {
+    static char ID; // Pass identification, replacement for typeid
+    DCE() : FunctionPass(ID) {
+      initializeDCEPass(*PassRegistry::getPassRegistry());
     }
-  }
-
-  // Loop through an merge basic blocks into their predecessor if there is only
-  // one, and if there is only one successor of the predecessor.
-  //
-  for (BBIt = BBs.begin(); BBIt != BBs.end(); BBIt++) {
-    BasicBlock *BB = *BBIt;
-
-    // Is there exactly one predecessor to this block?
-    BasicBlock::pred_iterator PI(BB->pred_begin());
-    if (PI != BB->pred_end() && ++PI == BB->pred_end() && 
-       !BB->hasConstantPoolReferences()) {
-      BasicBlock *Pred = *BB->pred_begin();
-      TerminatorInst *Term = Pred->getTerminator();
-      if (Term == 0) continue; // Err... malformed basic block!
-
-      // Is it an unconditional branch?
-      if (Term->getInstType() != Instruction::Br ||
-          !((BranchInst*)Term)->isUnconditional())
-        continue;  // Nope, maybe next time...
-
-      Changed = true;
-
-      // Make all branches to the predecessor now point to the successor...
-      Pred->replaceAllUsesWith(BB);
-
-      // Move all definitions in the predecessor to the successor...
-      BasicBlock::InstListType::iterator DI = Pred->getInstList().end();
-      assert(Pred->getTerminator() && 
-            "Degenerate basic block encountered!");  // Empty bb???      
-      delete Pred->getInstList().remove(--DI); // Remove terminator
-      
-      while (Pred->getInstList().begin() != (DI = Pred->getInstList().end())) {
-        Instruction *Def = Pred->getInstList().remove(--DI); // Remove from end
-        BB->getInstList().push_front(Def);                   // Add to front...
-      }
 
-      // Remove basic block from the method...
-      BBs.remove(Pred);
+    bool runOnFunction(Function &F) override;
 
-      // Always inherit predecessors name if it exists...
-      if (Pred->hasName()) BB->setName(Pred->getName());
+    void getAnalysisUsage(AnalysisUsage &AU) const override {
+      AU.setPreservesCFG();
+    }
+ };
+}
 
-      // So long you waste of a basic block you...
-      delete Pred;
+char DCE::ID = 0;
+INITIALIZE_PASS(DCE, "dce", "Dead Code Elimination", false, false)
+
+static bool DCEInstruction(Instruction *I,
+                           SmallSetVector<Instruction *, 16> &WorkList,
+                           const TargetLibraryInfo *TLI) {
+  if (isInstructionTriviallyDead(I, TLI)) {
+    // Null out all of the instruction's operands to see if any operand becomes
+    // dead as we go.
+    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
+      Value *OpV = I->getOperand(i);
+      I->setOperand(i, nullptr);
+
+      if (!OpV->use_empty() || I == OpV)
+        continue;
+
+      // If the operand is an instruction that became dead as we nulled out the
+      // operand, and if it is 'trivially' dead, delete it in a future loop
+      // iteration.
+      if (Instruction *OpI = dyn_cast<Instruction>(OpV))
+        if (isInstructionTriviallyDead(OpI, TLI))
+          WorkList.insert(OpI);
     }
-  }
 
-  // Remove unused constants
-  Changed |= DoRemoveUnusedConstants(M);
-  return Changed;
+    I->eraseFromParent();
+    ++DCEEliminated;
+    return true;
+  }
+  return false;
 }
 
+bool DCE::runOnFunction(Function &F) {
+  if (skipOptnoneFunction(F))
+    return false;
+
+  auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
+  TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI() : nullptr;
+
+  bool MadeChange = false;
+  SmallSetVector<Instruction *, 16> WorkList;
+  // Iterate over the original function, only adding insts to the worklist
+  // if they actually need to be revisited. This avoids having to pre-init
+  // the worklist with the entire function's worth of instructions.
+  for (inst_iterator FI = inst_begin(F), FE = inst_end(F); FI != FE;) {
+    Instruction *I = &*FI;
+    ++FI;
+
+    // We're visiting this instruction now, so make sure it's not in the
+    // worklist from an earlier visit.
+    if (!WorkList.count(I))
+      MadeChange |= DCEInstruction(I, WorkList, TLI);
+  }
 
-// It is possible that we may require multiple passes over the code to fully
-// eliminate dead code.  Iterate until we are done.
-//
-bool DoDeadCodeElimination(Method *M) {
-  bool Changed = false;
-  while (DoDCEPass(M)) Changed = true;
-  return Changed;
+  while (!WorkList.empty()) {
+    Instruction *I = WorkList.pop_back_val();
+    MadeChange |= DCEInstruction(I, WorkList, TLI);
+  }
+  return MadeChange;
 }
 
-bool DoDeadCodeElimination(Module *C) { 
-  bool Val = ApplyOptToAllMethods(C, DoDeadCodeElimination);
-  while (DoRemoveUnusedConstants(C)) Val = true;
-  return Val;
+FunctionPass *llvm::createDeadCodeEliminationPass() {
+  return new DCE();
 }
+