-//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
+//===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
//
-// This pass is designed to be a very quick global transformation that
-// eliminates global common subexpressions from a function. It does this by
-// examining the SSA value graph of the function, instead of doing slow, dense,
-// bit-vector computations.
+// The LLVM Compiler Infrastructure
//
-// This pass works best if it is proceeded with a simple constant propogation
-// pass and an instruction combination pass because this pass does not do any
-// value numbering (in order to be speedy).
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
//
-// This pass does not attempt to CSE load instructions, because it does not use
-// pointer analysis to determine when it is safe.
+//===----------------------------------------------------------------------===//
+//
+// This pass is designed to be a very quick global transformation that
+// eliminates global common subexpressions from a function. It does this by
+// using an existing value numbering implementation to identify the common
+// subexpressions, eliminating them when possible.
//
//===----------------------------------------------------------------------===//
+#define DEBUG_TYPE "gcse"
#include "llvm/Transforms/Scalar.h"
-#include "llvm/InstrTypes.h"
-#include "llvm/iMemory.h"
+#include "llvm/Instructions.h"
+#include "llvm/Function.h"
+#include "llvm/Type.h"
+#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/Dominators.h"
-#include "llvm/Support/InstVisitor.h"
-#include "llvm/Support/InstIterator.h"
-#include "Support/StatisticReporter.h"
+#include "llvm/Analysis/ValueNumbering.h"
+#include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/Support/Compiler.h"
#include <algorithm>
-
-static Statistic<> NumInstRemoved("gcse\t\t- Number of instructions removed");
-
+using namespace llvm;
+
+STATISTIC(NumInstRemoved, "Number of instructions removed");
+STATISTIC(NumLoadRemoved, "Number of loads removed");
+STATISTIC(NumCallRemoved, "Number of calls removed");
+STATISTIC(NumNonInsts , "Number of instructions removed due "
+ "to non-instruction values");
+STATISTIC(NumArgsRepl , "Number of function arguments replaced "
+ "with constant values");
namespace {
- class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
- set<Instruction*> WorkList;
- DominatorSet *DomSetInfo;
- ImmediateDominators *ImmDominator;
- public:
- const char *getPassName() const {
- return "Global Common Subexpression Elimination";
- }
-
- virtual bool runOnFunction(Function *F);
+ struct VISIBILITY_HIDDEN GCSE : public FunctionPass {
+ static char ID; // Pass identification, replacement for typeid
+ GCSE() : FunctionPass((intptr_t)&ID) {}
- // Visitation methods, these are invoked depending on the type of
- // instruction being checked. They should return true if a common
- // subexpression was folded.
- //
- bool visitUnaryOperator(Instruction *I);
- bool visitBinaryOperator(Instruction *I);
- bool visitGetElementPtrInst(GetElementPtrInst *I);
- bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
- bool visitShiftInst(ShiftInst *I) {
- return visitBinaryOperator((Instruction*)I);
- }
- bool visitInstruction(Instruction *) { return false; }
+ virtual bool runOnFunction(Function &F);
private:
- void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
- void CommonSubExpressionFound(Instruction *I, Instruction *Other);
+ void ReplaceInstructionWith(Instruction *I, Value *V);
// This transformation requires dominator and immediate dominator info
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
- AU.preservesCFG();
- AU.addRequired(DominatorSet::ID);
- AU.addRequired(ImmediateDominators::ID);
+ AU.setPreservesCFG();
+ AU.addRequired<DominatorTree>();
+ AU.addRequired<ValueNumbering>();
}
};
+
+ char GCSE::ID = 0;
+ RegisterPass<GCSE> X("gcse", "Global Common Subexpression Elimination");
}
// createGCSEPass - The public interface to this file...
-Pass *createGCSEPass() { return new GCSE(); }
-
+FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
// GCSE::runOnFunction - This is the main transformation entry point for a
// function.
//
-bool GCSE::runOnFunction(Function *F) {
+bool GCSE::runOnFunction(Function &F) {
bool Changed = false;
- DomSetInfo = &getAnalysis<DominatorSet>();
- ImmDominator = &getAnalysis<ImmediateDominators>();
-
- // Step #1: Add all instructions in the function to the worklist for
- // processing. All of the instructions are considered to be our
- // subexpressions to eliminate if possible.
- //
- WorkList.insert(inst_begin(F), inst_end(F));
+ // Get pointers to the analysis results that we will be using...
+ DominatorTree &DT = getAnalysis<DominatorTree>();
+ ValueNumbering &VN = getAnalysis<ValueNumbering>();
+
+ std::vector<Value*> EqualValues;
+
+ // Check for value numbers of arguments. If the value numbering
+ // implementation can prove that an incoming argument is a constant or global
+ // value address, substitute it, making the argument dead.
+ for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
+ if (!AI->use_empty()) {
+ VN.getEqualNumberNodes(AI, EqualValues);
+ if (!EqualValues.empty()) {
+ for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
+ if (isa<Constant>(EqualValues[i])) {
+ AI->replaceAllUsesWith(EqualValues[i]);
+ ++NumArgsRepl;
+ Changed = true;
+ break;
+ }
+ EqualValues.clear();
+ }
+ }
- // Step #2: WorkList processing. Iterate through all of the instructions,
- // checking to see if there are any additionally defined subexpressions in the
- // program. If so, eliminate them!
- //
- while (!WorkList.empty()) {
- Instruction *I = *WorkList.begin(); // Get an instruction from the worklist
- WorkList.erase(WorkList.begin());
+ // Traverse the CFG of the function in dominator order, so that we see each
+ // instruction after we see its operands.
+ for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
+ E = df_end(DT.getRootNode()); DI != E; ++DI) {
+ BasicBlock *BB = DI->getBlock();
+
+ // Remember which instructions we've seen in this basic block as we scan.
+ std::set<Instruction*> BlockInsts;
+
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+ Instruction *Inst = I++;
+
+ if (Constant *C = ConstantFoldInstruction(Inst)) {
+ ReplaceInstructionWith(Inst, C);
+ } else if (Inst->getType() != Type::VoidTy) {
+ // If this instruction computes a value, try to fold together common
+ // instructions that compute it.
+ //
+ VN.getEqualNumberNodes(Inst, EqualValues);
+
+ // If this instruction computes a value that is already computed
+ // elsewhere, try to recycle the old value.
+ if (!EqualValues.empty()) {
+ if (Inst == &*BB->begin())
+ I = BB->end();
+ else {
+ I = Inst; --I;
+ }
+
+ // First check to see if we were able to value number this instruction
+ // to a non-instruction value. If so, prefer that value over other
+ // instructions which may compute the same thing.
+ for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
+ if (!isa<Instruction>(EqualValues[i])) {
+ ++NumNonInsts; // Keep track of # of insts repl with values
+
+ // Change all users of Inst to use the replacement and remove it
+ // from the program.
+ ReplaceInstructionWith(Inst, EqualValues[i]);
+ Inst = 0;
+ EqualValues.clear(); // don't enter the next loop
+ break;
+ }
+
+ // If there were no non-instruction values that this instruction
+ // produces, find a dominating instruction that produces the same
+ // value. If we find one, use it's value instead of ours.
+ for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) {
+ Instruction *OtherI = cast<Instruction>(EqualValues[i]);
+ bool Dominates = false;
+ if (OtherI->getParent() == BB)
+ Dominates = BlockInsts.count(OtherI);
+ else
+ Dominates = DT.dominates(OtherI->getParent(), BB);
+
+ if (Dominates) {
+ // Okay, we found an instruction with the same value as this one
+ // and that dominates this one. Replace this instruction with the
+ // specified one.
+ ReplaceInstructionWith(Inst, OtherI);
+ Inst = 0;
+ break;
+ }
+ }
+
+ EqualValues.clear();
+
+ if (Inst) {
+ I = Inst; ++I; // Deleted no instructions
+ } else if (I == BB->end()) { // Deleted first instruction
+ I = BB->begin();
+ } else { // Deleted inst in middle of block.
+ ++I;
+ }
+ }
- // Visit the instruction, dispatching to the correct visit function based on
- // the instruction type. This does the checking.
- //
- Changed |= visit(I);
+ if (Inst)
+ BlockInsts.insert(Inst);
+ }
+ }
}
-
+
// When the worklist is empty, return whether or not we changed anything...
return Changed;
}
-// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
-// uses of the instruction use First now instead.
-//
-void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
- Instruction *Second = *SI;
-
- //cerr << "DEL " << (void*)Second << Second;
-
- // Add the first instruction back to the worklist
- WorkList.insert(First);
-
- // Add all uses of the second instruction to the worklist
- for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
- UI != UE; ++UI)
- WorkList.insert(cast<Instruction>(*UI));
-
- // Make all users of 'Second' now use 'First'
- Second->replaceAllUsesWith(First);
+void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) {
+ if (isa<LoadInst>(I))
+ ++NumLoadRemoved; // Keep track of loads eliminated
+ if (isa<CallInst>(I))
+ ++NumCallRemoved; // Keep track of calls eliminated
+ ++NumInstRemoved; // Keep track of number of insts eliminated
- // Erase the second instruction from the program
- delete Second->getParent()->getInstList().remove(SI);
-}
-
-// CommonSubExpressionFound - The two instruction I & Other have been found to
-// be common subexpressions. This function is responsible for eliminating one
-// of them, and for fixing the worklist to be correct.
-//
-void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
- // I has already been removed from the worklist, Other needs to be.
- assert(I != Other && WorkList.count(I) == 0 && "I shouldn't be on worklist!");
+ // Update value numbering
+ getAnalysis<ValueNumbering>().deleteValue(I);
- WorkList.erase(Other); // Other may not actually be on the worklist anymore...
+ I->replaceAllUsesWith(V);
- ++NumInstRemoved; // Keep track of number of instructions eliminated
-
- // Handle the easy case, where both instructions are in the same basic block
- BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
- if (BB1 == BB2) {
- // Eliminate the second occuring instruction. Add all uses of the second
- // instruction to the worklist.
- //
- // Scan the basic block looking for the "first" instruction
- BasicBlock::iterator BI = BB1->begin();
- while (*BI != I && *BI != Other) {
- ++BI;
- assert(BI != BB1->end() && "Instructions not found in parent BB!");
- }
-
- // Keep track of which instructions occurred first & second
- Instruction *First = *BI;
- Instruction *Second = I != First ? I : Other; // Get iterator to second inst
- BI = find(BI, BB1->end(), Second);
- assert(BI != BB1->end() && "Second instruction not found in parent block!");
-
- // Destroy Second, using First instead.
- ReplaceInstWithInst(First, BI);
-
- // Otherwise, the two instructions are in different basic blocks. If one
- // dominates the other instruction, we can simply use it
- //
- } else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
- BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
- assert(BI != BB2->end() && "Other not in parent basic block!");
- ReplaceInstWithInst(I, BI);
- } else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
- BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
- assert(BI != BB1->end() && "I not in parent basic block!");
- ReplaceInstWithInst(Other, BI);
- } else {
- // Handle the most general case now. In this case, neither I dom Other nor
- // Other dom I. Because we are in SSA form, we are guaranteed that the
- // operands of the two instructions both dominate the uses, so we _know_
- // that there must exist a block that dominates both instructions (if the
- // operands of the instructions are globals or constants, worst case we
- // would get the entry node of the function). Search for this block now.
- //
-
- // Search up the immediate dominator chain of BB1 for the shared dominator
- BasicBlock *SharedDom = (*ImmDominator)[BB1];
- while (!DomSetInfo->dominates(SharedDom, BB2))
- SharedDom = (*ImmDominator)[SharedDom];
-
- // At this point, shared dom must dominate BOTH BB1 and BB2...
- assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
- DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
-
- // Rip 'I' out of BB1, and move it to the end of SharedDom.
- BB1->getInstList().remove(I);
- SharedDom->getInstList().insert(SharedDom->end()-1, I);
-
- // Eliminate 'Other' now.
- BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
- assert(BI != BB2->end() && "I not in parent basic block!");
- ReplaceInstWithInst(I, BI);
+ if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
+ // Removing an invoke instruction requires adding a branch to the normal
+ // destination and removing PHI node entries in the exception destination.
+ BranchInst::Create(II->getNormalDest(), II);
+ II->getUnwindDest()->removePredecessor(II->getParent());
}
-}
-//===----------------------------------------------------------------------===//
-//
-// Visitation methods, these are invoked depending on the type of instruction
-// being checked. They should return true if a common subexpression was folded.
-//
-//===----------------------------------------------------------------------===//
-
-bool GCSE::visitUnaryOperator(Instruction *I) {
- Value *Op = I->getOperand(0);
- Function *F = I->getParent()->getParent();
-
- for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
- UI != UE; ++UI)
- if (Instruction *Other = dyn_cast<Instruction>(*UI))
- // Check to see if this new binary operator is not I, but same operand...
- if (Other != I && Other->getOpcode() == I->getOpcode() &&
- Other->getOperand(0) == Op && // Is the operand the same?
- // Is it embeded in the same function? (This could be false if LHS
- // is a constant or global!)
- Other->getParent()->getParent() == F &&
-
- // Check that the types are the same, since this code handles casts...
- Other->getType() == I->getType()) {
-
- // These instructions are identical. Handle the situation.
- CommonSubExpressionFound(I, Other);
- return true; // One instruction eliminated!
- }
-
- return false;
-}
-
-bool GCSE::visitBinaryOperator(Instruction *I) {
- Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
- Function *F = I->getParent()->getParent();
-
- for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
- UI != UE; ++UI)
- if (Instruction *Other = dyn_cast<Instruction>(*UI))
- // Check to see if this new binary operator is not I, but same operand...
- if (Other != I && Other->getOpcode() == I->getOpcode() &&
- // Are the LHS and RHS the same?
- Other->getOperand(0) == LHS && Other->getOperand(1) == RHS &&
- // Is it embeded in the same function? (This could be false if LHS
- // is a constant or global!)
- Other->getParent()->getParent() == F) {
-
- // These instructions are identical. Handle the situation.
- CommonSubExpressionFound(I, Other);
- return true; // One instruction eliminated!
- }
-
- return false;
-}
-
-bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
- Value *Op = I->getOperand(0);
- Function *F = I->getParent()->getParent();
-
- for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
- UI != UE; ++UI)
- if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
- // Check to see if this new binary operator is not I, but same operand...
- if (Other != I && Other->getParent()->getParent() == F &&
- Other->getType() == I->getType()) {
-
- // Check to see that all operators past the 0th are the same...
- unsigned i = 1, e = I->getNumOperands();
- for (; i != e; ++i)
- if (I->getOperand(i) != Other->getOperand(i)) break;
-
- if (i == e) {
- // These instructions are identical. Handle the situation.
- CommonSubExpressionFound(I, Other);
- return true; // One instruction eliminated!
- }
- }
-
- return false;
+ // Erase the instruction from the program.
+ I->getParent()->getInstList().erase(I);
}