//===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
-//
+//
// 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.
-//
+//
//===----------------------------------------------------------------------===//
//
// Correlated Expression Elimination propagates information from conditional
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
+#include "llvm/Constants.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
-#include "llvm/iTerminators.h"
-#include "llvm/iPHINode.h"
-#include "llvm/iOperators.h"
-#include "llvm/ConstantHandling.h"
-#include "llvm/Assembly/Writer.h"
+#include "llvm/Instructions.h"
+#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
+#include "llvm/Assembly/Writer.h"
#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/CFG.h"
-#include "Support/Debug.h"
-#include "Support/PostOrderIterator.h"
-#include "Support/Statistic.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/ADT/Statistic.h"
#include <algorithm>
+using namespace llvm;
namespace {
Statistic<> NumSetCCRemoved("cee", "Number of setcc instruction eliminated");
// empty - return true if this region has no information known about it.
bool empty() const { return ValueMap.empty(); }
-
+
const RegionInfo &operator=(const RegionInfo &RI) {
ValueMap = RI.ValueMap;
return *this;
if (I != ValueMap.end()) return &I->second;
return 0;
}
-
+
/// removeValueInfo - Remove anything known about V from our records. This
/// works whether or not we know anything about V.
///
class CEE : public FunctionPass {
std::map<Value*, unsigned> RankMap;
std::map<BasicBlock*, RegionInfo> RegionInfoMap;
- DominatorSet *DS;
+ ETForest *EF;
DominatorTree *DT;
public:
virtual bool runOnFunction(Function &F);
// We don't modify the program, so we preserve all analyses
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
- AU.addRequired<DominatorSet>();
+ AU.addRequired<ETForest>();
AU.addRequired<DominatorTree>();
AU.addRequiredID(BreakCriticalEdgesID);
};
void BuildRankMap(Function &F);
unsigned getRank(Value *V) const {
- if (isa<Constant>(V) || isa<GlobalValue>(V)) return 0;
+ if (isa<Constant>(V)) return 0;
std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
if (I != RankMap.end()) return I->second;
return 0; // Must be some other global thing
bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
- };
+ };
RegisterOpt<CEE> X("cee", "Correlated Expression Elimination");
}
-Pass *createCorrelatedExpressionEliminationPass() { return new CEE(); }
+FunctionPass *llvm::createCorrelatedExpressionEliminationPass() {
+ return new CEE();
+}
bool CEE::runOnFunction(Function &F) {
// Traverse the dominator tree, computing information for each node in the
// tree. Note that our traversal will not even touch unreachable basic
// blocks.
- DS = &getAnalysis<DominatorSet>();
+ EF = &getAnalysis<ETForest>();
DT = &getAnalysis<DominatorTree>();
-
+
std::set<BasicBlock*> VisitedBlocks;
bool Changed = TransformRegion(&F.getEntryBlock(), VisitedBlocks);
// Check to see if we dominate the block. If so, this block will get the
// condition turned to a constant anyway.
//
- //if (DS->dominates(RI.getEntryBlock(), BB))
+ //if (EF->dominates(RI.getEntryBlock(), BB))
// return 0;
BasicBlock *BB = TI->getParent();
for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
if (I->getType() != Type::VoidTy)
NewRI.removeValueInfo(I);
-
+
// Put the newly discovered information into the RegionInfo...
for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
if (PHINode *PN = dyn_cast<PHINode>(I)) {
int OpNum = PN->getBasicBlockIndex(BB);
assert(OpNum != -1 && "PHI doesn't have incoming edge for predecessor!?");
- PropagateEquality(PN, PN->getIncomingValue(OpNum), NewRI);
+ PropagateEquality(PN, PN->getIncomingValue(OpNum), NewRI);
} else if (SetCondInst *SCI = dyn_cast<SetCondInst>(I)) {
Relation::KnownResult Res = getSetCCResult(SCI, NewRI);
if (Res == Relation::Unknown) return false;
} else {
assert(isa<BranchInst>(*I) && "Unexpected instruction type!");
}
-
+
// Compute the facts implied by what we have discovered...
ComputeReplacements(NewRI);
ValueInfo &PredicateVI = NewRI.getValueInfo(BI->getCondition());
if (PredicateVI.getReplacement() &&
- isa<Constant>(PredicateVI.getReplacement())) {
+ isa<Constant>(PredicateVI.getReplacement()) &&
+ !isa<GlobalValue>(PredicateVI.getReplacement())) {
ConstantBool *CB = cast<ConstantBool>(PredicateVI.getReplacement());
// Forward to the successor that corresponds to the branch we will take.
ForwardSuccessorTo(TI, SuccNo, BI->getSuccessor(!CB->getValue()), NewRI);
return true;
}
-
+
return false;
}
// insert dead phi nodes, but it is more trouble to see if they are used than
// to just blindly insert them.
//
- if (DS->dominates(OldSucc, Dest)) {
+ if (EF->dominates(OldSucc, Dest)) {
// RegionExitBlocks - Find all of the blocks that are not dominated by Dest,
// but have predecessors that are. Additionally, prune down the set to only
// include blocks that are dominated by OldSucc as well.
// edge from the PHI node, and we need to replace any references to the PHI
// node with a new value.
//
- for (BasicBlock::iterator I = OldSucc->begin();
- PHINode *PN = dyn_cast<PHINode>(I); ) {
+ for (BasicBlock::iterator I = OldSucc->begin(); isa<PHINode>(I); ) {
+ PHINode *PN = cast<PHINode>(I);
// Get the value flowing across the old edge and remove the PHI node entry
// for this edge: we are about to remove the edge! Don't remove the PHI
// node yet though if this is the last edge into it.
Value *EdgeValue = PN->removeIncomingValue(BB, false);
- // Make sure that anything that used to use PN now refers to EdgeValue
+ // Make sure that anything that used to use PN now refers to EdgeValue
ReplaceUsesOfValueInRegion(PN, EdgeValue, Dest);
// If there is only one value left coming into the PHI node, replace the PHI
++I; // Otherwise, move on to the next PHI node
}
}
-
+
// Actually revector the branch now...
TI->setSuccessor(SuccNo, Dest);
// If we just introduced a critical edge in the flow graph, make sure to break
// it right away...
- if (isCriticalEdge(TI, SuccNo))
- SplitCriticalEdge(TI, SuccNo, this);
+ SplitCriticalEdge(TI, SuccNo, this);
// Make sure that we don't introduce critical edges from oldsucc now!
for (unsigned i = 0, e = OldSucc->getTerminator()->getNumSuccessors();
// Since we invalidated the CFG, recalculate the dominator set so that it is
// useful for later processing!
// FIXME: This is much worse than it really should be!
- //DS->recalculate();
+ //EF->recalculate();
DEBUG(std::cerr << "After forwarding: " << *BB->getParent());
}
assert(Orig != New && "Cannot replace value with itself");
std::vector<Instruction*> InstsToChange;
std::vector<PHINode*> PHIsToChange;
- InstsToChange.reserve(Orig->use_size());
+ InstsToChange.reserve(Orig->getNumUses());
// Loop over instructions adding them to InstsToChange vector, this allows us
// an easy way to avoid invalidating the use_iterator at a bad time.
for (Value::use_iterator I = Orig->use_begin(), E = Orig->use_end();
I != E; ++I)
if (Instruction *User = dyn_cast<Instruction>(*I))
- if (DS->dominates(RegionDominator, User->getParent()))
+ if (EF->dominates(RegionDominator, User->getParent()))
InstsToChange.push_back(User);
else if (PHINode *PN = dyn_cast<PHINode>(User)) {
PHIsToChange.push_back(PN);
PHINode *PN = PHIsToChange[i];
for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
if (PN->getIncomingValue(j) == Orig &&
- DS->dominates(RegionDominator, PN->getIncomingBlock(j)))
+ EF->dominates(RegionDominator, PN->getIncomingBlock(j)))
PN->setIncomingValue(j, New);
}
// values that correspond to basic blocks in the region.
for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
if (PN->getIncomingValue(j) == Orig &&
- DS->dominates(RegionDominator, PN->getIncomingBlock(j)))
+ EF->dominates(RegionDominator, PN->getIncomingBlock(j)))
PN->setIncomingValue(j, New);
} else {
static void CalcRegionExitBlocks(BasicBlock *Header, BasicBlock *BB,
std::set<BasicBlock*> &Visited,
- DominatorSet &DS,
+ ETForest &EF,
std::vector<BasicBlock*> &RegionExitBlocks) {
if (Visited.count(BB)) return;
Visited.insert(BB);
- if (DS.dominates(Header, BB)) { // Block in the region, recursively traverse
+ if (EF.dominates(Header, BB)) { // Block in the region, recursively traverse
for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
- CalcRegionExitBlocks(Header, *I, Visited, DS, RegionExitBlocks);
+ CalcRegionExitBlocks(Header, *I, Visited, EF, RegionExitBlocks);
} else {
// Header does not dominate this block, but we have a predecessor that does
// dominate us. Add ourself to the list.
- RegionExitBlocks.push_back(BB);
+ RegionExitBlocks.push_back(BB);
}
}
std::set<BasicBlock*> Visited; // Don't infinite loop
// Recursively calculate blocks we are interested in...
- CalcRegionExitBlocks(BB, BB, Visited, *DS, RegionExitBlocks);
-
+ CalcRegionExitBlocks(BB, BB, Visited, *EF, RegionExitBlocks);
+
// Filter out blocks that are not dominated by OldSucc...
for (unsigned i = 0; i != RegionExitBlocks.size(); ) {
- if (DS->dominates(OldSucc, RegionExitBlocks[i]))
+ if (EF->dominates(OldSucc, RegionExitBlocks[i]))
++i; // Block is ok, keep it.
else {
// Move to end of list...
PI != PE; ++PI) {
// If the incoming edge is from the region dominated by BB, use BBVal,
// otherwise use OldVal.
- NewPN->addIncoming(DS->dominates(BB, *PI) ? BBVal : OldVal, *PI);
+ NewPN->addIncoming(EF->dominates(BB, *PI) ? BBVal : OldVal, *PI);
}
-
+
// Now make everyone dominated by this block use this new value!
ReplaceUsesOfValueInRegion(OldVal, NewPN, FBlock);
}
unsigned Rank = 1; // Skip rank zero.
// Number the arguments...
- for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
+ for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
RankMap[I] = Rank++;
// Number the instructions in reverse post order...
//
PropagateEquality(BI->getCondition(), ConstantBool::True,
getRegionInfo(BI->getSuccessor(0)));
-
+
// Propagate information into the false block...
//
PropagateEquality(BI->getCondition(), ConstantBool::False,
PropagateEquality(Inst->getOperand(0), CB, RI);
PropagateEquality(Inst->getOperand(1), CB, RI);
}
-
+
// If we know that this instruction is an OR instruction, and the result
// is false, this means that both operands to the OR are know to be false
// as well.
PropagateEquality(Inst->getOperand(0), CB, RI);
PropagateEquality(Inst->getOperand(1), CB, RI);
}
-
+
// If we know that this instruction is a NOT instruction, we know that the
// operand is known to be the inverse of whatever the current value is.
//
} else { // If we know the condition is false...
// We know the opposite of the condition is true...
Instruction::BinaryOps C = SCI->getInverseCondition();
-
+
PropagateRelation(C, SCI->getOperand(0), SCI->getOperand(1), RI);
PropagateRelation(SetCondInst::getSwappedCondition(C),
SCI->getOperand(1), SCI->getOperand(0), RI);
// here. This check is also effectively checking to make sure that Inst
// is in the same function as our region (in case V is a global f.e.).
//
- if (DS->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
+ if (EF->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
IncorporateInstruction(Inst, RI);
}
}
Relation::KnownResult Result = getSetCCResult(SCI, RI);
if (Result != Relation::Unknown) {
DEBUG(std::cerr << "Replacing setcc with " << Result
- << " constant: " << SCI);
+ << " constant: " << *SCI);
SCI->replaceAllUsesWith(ConstantBool::get((bool)Result));
// The instruction is now dead, remove it from the program.
if (Value *Repl = VI->getReplacement()) {
// If we know if a replacement with lower rank than Op0, make the
// replacement now.
- DEBUG(std::cerr << "In Inst: " << I << " Replacing operand #" << i
- << " with " << Repl << "\n");
+ DEBUG(std::cerr << "In Inst: " << *I << " Replacing operand #" << i
+ << " with " << *Repl << "\n");
I->setOperand(i, Repl);
Changed = true;
++NumOperandsCann;
const RegionInfo &RI) {
Value *Op0 = SCI->getOperand(0), *Op1 = SCI->getOperand(1);
Instruction::BinaryOps Opcode = SCI->getOpcode();
-
+
if (isa<Constant>(Op0)) {
if (isa<Constant>(Op1)) {
if (Constant *Result = ConstantFoldInstruction(SCI)) {
// Wow, this is easy, directly eliminate the SetCondInst.
- DEBUG(std::cerr << "Replacing setcc with constant fold: " << SCI);
+ DEBUG(std::cerr << "Replacing setcc with constant fold: " << *SCI);
return cast<ConstantBool>(Result)->getValue()
? Relation::KnownTrue : Relation::KnownFalse;
}
// If the intersection of the two ranges is empty, then the condition
// could never be true!
- //
+ //
if (Int.isEmptySet()) {
Result = Relation::KnownFalse;
assert(C != 0 && "C is not specified!");
if (Bound == 0) return false;
- ConstantBool *Val;
- switch (BO) {
- default: assert(0 && "Unknown Condition code!");
- case Instruction::SetEQ: Val = *Bound == *C; break;
- case Instruction::SetNE: Val = *Bound != *C; break;
- case Instruction::SetLT: Val = *Bound < *C; break;
- case Instruction::SetGT: Val = *Bound > *C; break;
- case Instruction::SetLE: Val = *Bound <= *C; break;
- case Instruction::SetGE: Val = *Bound >= *C; break;
- }
-
- // ConstantHandling code may not succeed in the comparison...
- if (Val == 0) return false;
- return !Val->getValue(); // Return true if the condition is false...
+ Constant *Val = ConstantExpr::get(BO, Bound, C);
+ if (ConstantBool *CB = dyn_cast<ConstantBool>(Val))
+ return !CB->getValue(); // Return true if the condition is false...
+ return false;
}
// contradicts - Return true if the relationship specified by the operand
// print - Implement the standard print form to print out analysis information.
void CEE::print(std::ostream &O, const Module *M) const {
O << "\nPrinting Correlated Expression Info:\n";
- for (std::map<BasicBlock*, RegionInfo>::const_iterator I =
+ for (std::map<BasicBlock*, RegionInfo>::const_iterator I =
RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
I->second.print(O);
}