//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
+//
+// 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 implements sparse conditional constant propagation and merging:
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
-#include "llvm/ConstantHandling.h"
+#include "llvm/Constants.h"
#include "llvm/Function.h"
+#include "llvm/GlobalVariable.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
+#include "llvm/Type.h"
#include "llvm/Support/InstVisitor.h"
+#include "llvm/Transforms/Utils/Local.h"
#include "Support/Debug.h"
+#include "Support/hash_map"
#include "Support/Statistic.h"
#include "Support/STLExtras.h"
#include <algorithm>
#include <set>
+using namespace llvm;
// InstVal class - This class represents the different lattice values that an
// instruction may occupy. It is a simple class with value semantics.
inline bool isConstant() const { return LatticeValue == constant; }
inline bool isOverdefined() const { return LatticeValue == overdefined; }
- inline Constant *getConstant() const { return ConstantVal; }
+ inline Constant *getConstant() const {
+ assert(isConstant() && "Cannot get the constant of a non-constant!");
+ return ConstantVal;
+ }
};
} // end anonymous namespace
namespace {
class SCCP : public FunctionPass, public InstVisitor<SCCP> {
std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
- std::map<Value*, InstVal> ValueState; // The state each value is in...
-
+ hash_map<Value*, InstVal> ValueState; // The state each value is in...
+
+ // The reason for two worklists is that overdefined is the lowest state
+ // on the lattice, and moving things to overdefined as fast as possible
+ // makes SCCP converge much faster.
+ // By having a separate worklist, we accomplish this because everything
+ // possibly overdefined will become overdefined at the soonest possible
+ // point.
+ std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined
+ // instruction work list
std::vector<Instruction*> InstWorkList;// The instruction work list
+
+
std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
+ /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
+ /// overdefined, despite the fact that the PHI node is overdefined.
+ std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
+
/// KnownFeasibleEdges - Entries in this set are edges which have already had
/// PHI nodes retriggered.
typedef std::pair<BasicBlock*,BasicBlock*> Edge;
private:
friend class InstVisitor<SCCP>; // Allow callbacks from visitor
- // markValueOverdefined - Make a value be marked as "constant". If the value
+ // markConstant - Make a value be marked as "constant". If the value
// is not already a constant, add it to the instruction work list so that
// the users of the instruction are updated later.
//
markConstant(ValueState[I], I, C);
}
- // markValueOverdefined - Make a value be marked as "overdefined". If the
- // value is not already overdefined, add it to the instruction work list so
- // that the users of the instruction are updated later.
- //
+ // markOverdefined - Make a value be marked as "overdefined". If the
+ // value is not already overdefined, add it to the overdefined instruction
+ // work list so that the users of the instruction are updated later.
+
inline void markOverdefined(InstVal &IV, Instruction *I) {
if (IV.markOverdefined()) {
DEBUG(std::cerr << "markOverdefined: " << *I);
- InstWorkList.push_back(I); // Only instructions go on the work list
+ OverdefinedInstWorkList.push_back(I); // Only instructions go on the work list
}
}
inline void markOverdefined(Instruction *I) {
// Instruction object, then use this accessor to get its value from the map.
//
inline InstVal &getValueState(Value *V) {
- std::map<Value*, InstVal>::iterator I = ValueState.find(V);
+ hash_map<Value*, InstVal>::iterator I = ValueState.find(V);
if (I != ValueState.end()) return I->second; // Common case, in the map
if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
ValueState[CPV].markConstant(CPV);
} else if (isa<Argument>(V)) { // Arguments are overdefined
ValueState[V].markOverdefined();
- } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
- // The address of a global is a constant...
- ValueState[V].markConstant(ConstantPointerRef::get(GV));
}
// All others are underdefined by default...
return ValueState[V];
void visitTerminatorInst(TerminatorInst &TI);
void visitCastInst(CastInst &I);
+ void visitSelectInst(SelectInst &I);
void visitBinaryOperator(Instruction &I);
void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
// Instructions that cannot be folded away...
void visitStoreInst (Instruction &I) { /*returns void*/ }
- void visitLoadInst (Instruction &I) { markOverdefined(&I); }
+ void visitLoadInst (LoadInst &I);
void visitGetElementPtrInst(GetElementPtrInst &I);
- void visitCallInst (Instruction &I) { markOverdefined(&I); }
+ void visitCallInst (CallInst &I);
void visitInvokeInst (TerminatorInst &I) {
if (I.getType() != Type::VoidTy) markOverdefined(&I);
visitTerminatorInst(I);
// createSCCPPass - This is the public interface to this file...
-//
-Pass *createSCCPPass() {
+Pass *llvm::createSCCPPass() {
return new SCCP();
}
BBExecutable.insert(F.begin()); // Basic block is executable!
BBWorkList.push_back(F.begin()); // Add the block to the work list!
- // Process the work lists until their are empty!
- while (!BBWorkList.empty() || !InstWorkList.empty()) {
+ // Process the work lists until they are empty!
+ while (!BBWorkList.empty() || !InstWorkList.empty() ||
+ !OverdefinedInstWorkList.empty()) {
+ // Process the instruction work list...
+ while (!OverdefinedInstWorkList.empty()) {
+ Instruction *I = OverdefinedInstWorkList.back();
+ OverdefinedInstWorkList.pop_back();
+
+ DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
+
+ // "I" got into the work list because it either made the transition from
+ // bottom to constant
+ //
+ // Anything on this worklist that is overdefined need not be visited
+ // since all of its users will have already been marked as overdefined
+ // Update all of the users of this instruction's value...
+ //
+ for_each(I->use_begin(), I->use_end(),
+ bind_obj(this, &SCCP::OperandChangedState));
+ }
// Process the instruction work list...
while (!InstWorkList.empty()) {
Instruction *I = InstWorkList.back();
InstWorkList.pop_back();
- DEBUG(std::cerr << "\nPopped off I-WL: " << I);
+ DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
// "I" got into the work list because it either made the transition from
- // bottom to constant, or to Overdefined.
+ // bottom to constant
//
+ // Anything on this worklist that is overdefined need not be visited
+ // since all of its users will have already been marked as overdefined.
// Update all of the users of this instruction's value...
//
- for_each(I->use_begin(), I->use_end(),
- bind_obj(this, &SCCP::OperandChangedState));
+ InstVal &Ival = getValueState (I);
+ if (!Ival.isOverdefined())
+ for_each(I->use_begin(), I->use_end(),
+ bind_obj(this, &SCCP::OperandChangedState));
}
// Process the basic block work list...
BasicBlock *BB = BBWorkList.back();
BBWorkList.pop_back();
- DEBUG(std::cerr << "\nPopped off BBWL: " << BB);
+ DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
// Notify all instructions in this basic block that they are newly
// executable.
InstVal &IV = ValueState[&Inst];
if (IV.isConstant()) {
Constant *Const = IV.getConstant();
- DEBUG(std::cerr << "Constant: " << Const << " = " << Inst);
+ DEBUG(std::cerr << "Constant: " << *Const << " = " << Inst);
// Replaces all of the uses of a variable with uses of the constant.
Inst.replaceAllUsesWith(Const);
// Reset state so that the next invocation will have empty data structures
BBExecutable.clear();
ValueState.clear();
+ std::vector<Instruction*>().swap(OverdefinedInstWorkList);
std::vector<Instruction*>().swap(InstWorkList);
std::vector<BasicBlock*>().swap(BBWorkList);
Succs[0] = true;
} else {
InstVal &BCValue = getValueState(BI->getCondition());
- if (BCValue.isOverdefined()) {
- // Overdefined condition variables mean the branch could go either way.
+ if (BCValue.isOverdefined() ||
+ (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
+ // Overdefined condition variables, and branches on unfoldable constant
+ // conditions, mean the branch could go either way.
Succs[0] = Succs[1] = true;
} else if (BCValue.isConstant()) {
// Constant condition variables mean the branch can only go a single way
Succs[0] = Succs[1] = true;
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
InstVal &SCValue = getValueState(SI->getCondition());
- if (SCValue.isOverdefined()) { // Overdefined condition?
+ if (SCValue.isOverdefined() || // Overdefined condition?
+ (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
// All destinations are executable!
Succs.assign(TI.getNumSuccessors(), true);
} else if (SCValue.isConstant()) {
// Overdefined condition variables mean the branch could go either way.
return true;
} else if (BCValue.isConstant()) {
+ // Not branching on an evaluatable constant?
+ if (!isa<ConstantBool>(BCValue.getConstant())) return true;
+
// Constant condition variables mean the branch can only go a single way
return BI->getSuccessor(BCValue.getConstant() ==
ConstantBool::False) == To;
return true;
} else if (SCValue.isConstant()) {
Constant *CPV = SCValue.getConstant();
+ if (!isa<ConstantInt>(CPV))
+ return true; // not a foldable constant?
+
// Make sure to skip the "default value" which isn't a value
for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
//
void SCCP::visitPHINode(PHINode &PN) {
InstVal &PNIV = getValueState(&PN);
- if (PNIV.isOverdefined()) return; // Quick exit
+ if (PNIV.isOverdefined()) {
+ // There may be instructions using this PHI node that are not overdefined
+ // themselves. If so, make sure that they know that the PHI node operand
+ // changed.
+ std::multimap<PHINode*, Instruction*>::iterator I, E;
+ tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
+ if (I != E) {
+ std::vector<Instruction*> Users;
+ Users.reserve(std::distance(I, E));
+ for (; I != E; ++I) Users.push_back(I->second);
+ while (!Users.empty()) {
+ visit(Users.back());
+ Users.pop_back();
+ }
+ }
+ return; // Quick exit
+ }
+
+ // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
+ // and slow us down a lot. Just mark them overdefined.
+ if (PN.getNumIncomingValues() > 64) {
+ markOverdefined(PNIV, &PN);
+ return;
+ }
// Look at all of the executable operands of the PHI node. If any of them
// are overdefined, the PHI becomes overdefined as well. If they are all
void SCCP::visitCastInst(CastInst &I) {
Value *V = I.getOperand(0);
InstVal &VState = getValueState(V);
- if (VState.isOverdefined()) { // Inherit overdefinedness of operand
+ if (VState.isOverdefined()) // Inherit overdefinedness of operand
markOverdefined(&I);
- } else if (VState.isConstant()) { // Propagate constant value
- Constant *Result =
- ConstantFoldCastInstruction(VState.getConstant(), I.getType());
-
- if (Result) // If this instruction constant folds!
- markConstant(&I, Result);
- else
- markOverdefined(&I); // Don't know how to fold this instruction. :(
+ else if (VState.isConstant()) // Propagate constant value
+ markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
+}
+
+void SCCP::visitSelectInst(SelectInst &I) {
+ InstVal &CondValue = getValueState(I.getCondition());
+ if (CondValue.isOverdefined())
+ markOverdefined(&I);
+ else if (CondValue.isConstant()) {
+ if (CondValue.getConstant() == ConstantBool::True) {
+ InstVal &Val = getValueState(I.getTrueValue());
+ if (Val.isOverdefined())
+ markOverdefined(&I);
+ else if (Val.isConstant())
+ markConstant(&I, Val.getConstant());
+ } else if (CondValue.getConstant() == ConstantBool::False) {
+ InstVal &Val = getValueState(I.getFalseValue());
+ if (Val.isOverdefined())
+ markOverdefined(&I);
+ else if (Val.isConstant())
+ markConstant(&I, Val.getConstant());
+ } else
+ markOverdefined(&I);
}
}
// Handle BinaryOperators and Shift Instructions...
void SCCP::visitBinaryOperator(Instruction &I) {
+ InstVal &IV = ValueState[&I];
+ if (IV.isOverdefined()) return;
+
InstVal &V1State = getValueState(I.getOperand(0));
InstVal &V2State = getValueState(I.getOperand(1));
+
if (V1State.isOverdefined() || V2State.isOverdefined()) {
- markOverdefined(&I);
+ // If both operands are PHI nodes, it is possible that this instruction has
+ // a constant value, despite the fact that the PHI node doesn't. Check for
+ // this condition now.
+ if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
+ if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
+ if (PN1->getParent() == PN2->getParent()) {
+ // Since the two PHI nodes are in the same basic block, they must have
+ // entries for the same predecessors. Walk the predecessor list, and
+ // if all of the incoming values are constants, and the result of
+ // evaluating this expression with all incoming value pairs is the
+ // same, then this expression is a constant even though the PHI node
+ // is not a constant!
+ InstVal Result;
+ for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
+ InstVal &In1 = getValueState(PN1->getIncomingValue(i));
+ BasicBlock *InBlock = PN1->getIncomingBlock(i);
+ InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
+
+ if (In1.isOverdefined() || In2.isOverdefined()) {
+ Result.markOverdefined();
+ break; // Cannot fold this operation over the PHI nodes!
+ } else if (In1.isConstant() && In2.isConstant()) {
+ Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
+ In2.getConstant());
+ if (Result.isUndefined())
+ Result.markConstant(V);
+ else if (Result.isConstant() && Result.getConstant() != V) {
+ Result.markOverdefined();
+ break;
+ }
+ }
+ }
+
+ // If we found a constant value here, then we know the instruction is
+ // constant despite the fact that the PHI nodes are overdefined.
+ if (Result.isConstant()) {
+ markConstant(IV, &I, Result.getConstant());
+ // Remember that this instruction is virtually using the PHI node
+ // operands.
+ UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
+ UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
+ return;
+ } else if (Result.isUndefined()) {
+ return;
+ }
+
+ // Okay, this really is overdefined now. Since we might have
+ // speculatively thought that this was not overdefined before, and
+ // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
+ // make sure to clean out any entries that we put there, for
+ // efficiency.
+ std::multimap<PHINode*, Instruction*>::iterator It, E;
+ tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
+ while (It != E) {
+ if (It->second == &I) {
+ UsersOfOverdefinedPHIs.erase(It++);
+ } else
+ ++It;
+ }
+ tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
+ while (It != E) {
+ if (It->second == &I) {
+ UsersOfOverdefinedPHIs.erase(It++);
+ } else
+ ++It;
+ }
+ }
+
+ markOverdefined(IV, &I);
} else if (V1State.isConstant() && V2State.isConstant()) {
- Constant *Result = 0;
- if (isa<BinaryOperator>(I))
- Result = ConstantFoldBinaryInstruction(I.getOpcode(),
- V1State.getConstant(),
- V2State.getConstant());
- else if (isa<ShiftInst>(I))
- Result = ConstantFoldShiftInstruction(I.getOpcode(),
- V1State.getConstant(),
- V2State.getConstant());
- if (Result)
- markConstant(&I, Result); // This instruction constant folds!
- else
- markOverdefined(&I); // Don't know how to fold this instruction. :(
+ markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
+ V2State.getConstant()));
}
}
// can turn this into a getelementptr ConstantExpr.
//
void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
+ InstVal &IV = ValueState[&I];
+ if (IV.isOverdefined()) return;
+
std::vector<Constant*> Operands;
Operands.reserve(I.getNumOperands());
if (State.isUndefined())
return; // Operands are not resolved yet...
else if (State.isOverdefined()) {
- markOverdefined(&I);
+ markOverdefined(IV, &I);
return;
}
assert(State.isConstant() && "Unknown state!");
Constant *Ptr = Operands[0];
Operands.erase(Operands.begin()); // Erase the pointer from idx list...
- markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Operands));
+ markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
+}
+
+/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
+/// return the constant value being addressed by the constant expression, or
+/// null if something is funny.
+///
+static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
+ if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
+ return 0; // Do not allow stepping over the value!
+
+ // Loop over all of the operands, tracking down which value we are
+ // addressing...
+ for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
+ if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
+ ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
+ if (CS == 0) return 0;
+ if (CU->getValue() >= CS->getNumOperands()) return 0;
+ C = CS->getOperand(CU->getValue());
+ } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
+ ConstantArray *CA = dyn_cast<ConstantArray>(C);
+ if (CA == 0) return 0;
+ if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
+ C = CA->getOperand(CS->getValue());
+ } else
+ return 0;
+ return C;
+}
+
+// Handle load instructions. If the operand is a constant pointer to a constant
+// global, we can replace the load with the loaded constant value!
+void SCCP::visitLoadInst(LoadInst &I) {
+ InstVal &IV = ValueState[&I];
+ if (IV.isOverdefined()) return;
+
+ InstVal &PtrVal = getValueState(I.getOperand(0));
+ if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
+ if (PtrVal.isConstant() && !I.isVolatile()) {
+ Value *Ptr = PtrVal.getConstant();
+ if (isa<ConstantPointerNull>(Ptr)) {
+ // load null -> null
+ markConstant(IV, &I, Constant::getNullValue(I.getType()));
+ return;
+ }
+
+ // Transform load (constant global) into the value loaded.
+ if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
+ if (GV->isConstant() && !GV->isExternal()) {
+ markConstant(IV, &I, GV->getInitializer());
+ return;
+ }
+
+ // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
+ if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
+ if (CE->getOpcode() == Instruction::GetElementPtr)
+ if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
+ if (GV->isConstant() && !GV->isExternal())
+ if (Constant *V =
+ GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
+ markConstant(IV, &I, V);
+ return;
+ }
+ }
+
+ // Otherwise we cannot say for certain what value this load will produce.
+ // Bail out.
+ markOverdefined(IV, &I);
+}
+
+void SCCP::visitCallInst(CallInst &I) {
+ InstVal &IV = ValueState[&I];
+ if (IV.isOverdefined()) return;
+
+ Function *F = I.getCalledFunction();
+ if (F == 0 || !canConstantFoldCallTo(F)) {
+ markOverdefined(IV, &I);
+ return;
+ }
+
+ std::vector<Constant*> Operands;
+ Operands.reserve(I.getNumOperands()-1);
+
+ for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
+ InstVal &State = getValueState(I.getOperand(i));
+ if (State.isUndefined())
+ return; // Operands are not resolved yet...
+ else if (State.isOverdefined()) {
+ markOverdefined(IV, &I);
+ return;
+ }
+ assert(State.isConstant() && "Unknown state!");
+ Operands.push_back(State.getConstant());
+ }
+
+ if (Constant *C = ConstantFoldCall(F, Operands))
+ markConstant(IV, &I, C);
+ else
+ markOverdefined(IV, &I);
}