1 //===- SCCP.cpp - Sparse Conditional Constant Propogation -----------------===//
3 // This file implements sparse conditional constant propogation and merging:
6 // * Assumes values are constant unless proven otherwise
7 // * Assumes BasicBlocks are dead unless proven otherwise
8 // * Proves values to be constant, and replaces them with constants
9 // * Proves conditional branches to be unconditional
12 // * This pass has a habit of making definitions be dead. It is a good idea
13 // to to run a DCE pass sometime after running this pass.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/ConstantHandling.h"
19 #include "llvm/Function.h"
20 #include "llvm/iPHINode.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/iOther.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/InstVisitor.h"
26 #include "Support/STLExtras.h"
27 #include "Support/Statistic.h"
32 // InstVal class - This class represents the different lattice values that an
33 // instruction may occupy. It is a simple class with value semantics.
36 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
40 undefined, // This instruction has no known value
41 constant, // This instruction has a constant value
42 overdefined // This instruction has an unknown value
43 } LatticeValue; // The current lattice position
44 Constant *ConstantVal; // If Constant value, the current value
46 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
48 // markOverdefined - Return true if this is a new status to be in...
49 inline bool markOverdefined() {
50 if (LatticeValue != overdefined) {
51 LatticeValue = overdefined;
57 // markConstant - Return true if this is a new status for us...
58 inline bool markConstant(Constant *V) {
59 if (LatticeValue != constant) {
60 LatticeValue = constant;
64 assert(ConstantVal == V && "Marking constant with different value");
69 inline bool isUndefined() const { return LatticeValue == undefined; }
70 inline bool isConstant() const { return LatticeValue == constant; }
71 inline bool isOverdefined() const { return LatticeValue == overdefined; }
73 inline Constant *getConstant() const { return ConstantVal; }
76 } // end anonymous namespace
79 //===----------------------------------------------------------------------===//
82 // This class does all of the work of Sparse Conditional Constant Propogation.
85 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
86 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
87 std::map<Value*, InstVal> ValueState; // The state each value is in...
89 std::vector<Instruction*> InstWorkList;// The instruction work list
90 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
93 // runOnFunction - Run the Sparse Conditional Constant Propogation algorithm,
94 // and return true if the function was modified.
96 bool runOnFunction(Function &F);
98 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
103 //===--------------------------------------------------------------------===//
104 // The implementation of this class
107 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
109 // markValueOverdefined - Make a value be marked as "constant". If the value
110 // is not already a constant, add it to the instruction work list so that
111 // the users of the instruction are updated later.
113 inline bool markConstant(Instruction *I, Constant *V) {
114 DEBUG(cerr << "markConstant: " << V << " = " << I);
116 if (ValueState[I].markConstant(V)) {
117 InstWorkList.push_back(I);
123 // markValueOverdefined - Make a value be marked as "overdefined". If the
124 // value is not already overdefined, add it to the instruction work list so
125 // that the users of the instruction are updated later.
127 inline bool markOverdefined(Value *V) {
128 if (ValueState[V].markOverdefined()) {
129 if (Instruction *I = dyn_cast<Instruction>(V)) {
130 DEBUG(cerr << "markOverdefined: " << V);
131 InstWorkList.push_back(I); // Only instructions go on the work list
138 // getValueState - Return the InstVal object that corresponds to the value.
139 // This function is neccesary because not all values should start out in the
140 // underdefined state... Argument's should be overdefined, and
141 // constants should be marked as constants. If a value is not known to be an
142 // Instruction object, then use this accessor to get its value from the map.
144 inline InstVal &getValueState(Value *V) {
145 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
146 if (I != ValueState.end()) return I->second; // Common case, in the map
148 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
149 ValueState[CPV].markConstant(CPV);
150 } else if (isa<Argument>(V)) { // Arguments are overdefined
151 ValueState[V].markOverdefined();
152 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
153 // The address of a global is a constant...
154 ValueState[V].markConstant(ConstantPointerRef::get(GV));
156 // All others are underdefined by default...
157 return ValueState[V];
160 // markExecutable - Mark a basic block as executable, adding it to the BB
161 // work list if it is not already executable...
163 void markExecutable(BasicBlock *BB) {
164 if (BBExecutable.count(BB)) return;
165 DEBUG(cerr << "Marking BB Executable: " << *BB);
166 BBExecutable.insert(BB); // Basic block is executable!
167 BBWorkList.push_back(BB); // Add the block to the work list!
171 // visit implementations - Something changed in this instruction... Either an
172 // operand made a transition, or the instruction is newly executable. Change
173 // the value type of I to reflect these changes if appropriate.
175 void visitPHINode(PHINode &I);
178 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
179 void visitTerminatorInst(TerminatorInst &TI);
181 void visitCastInst(CastInst &I);
182 void visitBinaryOperator(Instruction &I);
183 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
185 // Instructions that cannot be folded away...
186 void visitStoreInst (Instruction &I) { /*returns void*/ }
187 void visitLoadInst (Instruction &I) { markOverdefined(&I); }
188 void visitGetElementPtrInst(GetElementPtrInst &I);
189 void visitCallInst (Instruction &I) { markOverdefined(&I); }
190 void visitInvokeInst (Instruction &I) { markOverdefined(&I); }
191 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
192 void visitFreeInst (Instruction &I) { /*returns void*/ }
194 void visitInstruction(Instruction &I) {
195 // If a new instruction is added to LLVM that we don't handle...
196 cerr << "SCCP: Don't know how to handle: " << I;
197 markOverdefined(&I); // Just in case
200 // getFeasibleSuccessors - Return a vector of booleans to indicate which
201 // successors are reachable from a given terminator instruction.
203 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
205 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
206 // block to the 'To' basic block is currently feasible...
208 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
210 // OperandChangedState - This method is invoked on all of the users of an
211 // instruction that was just changed state somehow.... Based on this
212 // information, we need to update the specified user of this instruction.
214 void OperandChangedState(User *U) {
215 // Only instructions use other variable values!
216 Instruction &I = cast<Instruction>(*U);
217 if (!BBExecutable.count(I.getParent())) return;// Inst not executable yet!
222 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propogation");
223 } // end anonymous namespace
226 // createSCCPPass - This is the public interface to this file...
228 Pass *createSCCPPass() {
233 //===----------------------------------------------------------------------===//
234 // SCCP Class Implementation
237 // runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm,
238 // and return true if the function was modified.
240 bool SCCP::runOnFunction(Function &F) {
241 // Mark the first block of the function as being executable...
242 markExecutable(&F.front());
244 // Process the work lists until their are empty!
245 while (!BBWorkList.empty() || !InstWorkList.empty()) {
246 // Process the instruction work list...
247 while (!InstWorkList.empty()) {
248 Instruction *I = InstWorkList.back();
249 InstWorkList.pop_back();
251 DEBUG(cerr << "\nPopped off I-WL: " << I);
254 // "I" got into the work list because it either made the transition from
255 // bottom to constant, or to Overdefined.
257 // Update all of the users of this instruction's value...
259 for_each(I->use_begin(), I->use_end(),
260 bind_obj(this, &SCCP::OperandChangedState));
263 // Process the basic block work list...
264 while (!BBWorkList.empty()) {
265 BasicBlock *BB = BBWorkList.back();
266 BBWorkList.pop_back();
268 DEBUG(cerr << "\nPopped off BBWL: " << BB);
270 // If this block only has a single successor, mark it as executable as
271 // well... if not, terminate the do loop.
273 if (BB->getTerminator()->getNumSuccessors() == 1)
274 markExecutable(BB->getTerminator()->getSuccessor(0));
276 // Notify all instructions in this basic block that they are newly
283 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
284 if (!BBExecutable.count(I))
285 cerr << "BasicBlock Dead:" << *I;
288 // Iterate over all of the instructions in a function, replacing them with
289 // constants if we have found them to be of constant values.
291 bool MadeChanges = false;
292 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
293 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
294 Instruction &Inst = *BI;
295 InstVal &IV = ValueState[&Inst];
296 if (IV.isConstant()) {
297 Constant *Const = IV.getConstant();
298 DEBUG(cerr << "Constant: " << Const << " = " << Inst);
300 // Replaces all of the uses of a variable with uses of the constant.
301 Inst.replaceAllUsesWith(Const);
303 // Remove the operator from the list of definitions... and delete it.
304 BI = BB->getInstList().erase(BI);
306 // Hey, we just changed something!
314 // Reset state so that the next invocation will have empty data structures
315 BBExecutable.clear();
317 std::vector<Instruction*>().swap(InstWorkList);
318 std::vector<BasicBlock*>().swap(BBWorkList);
324 // getFeasibleSuccessors - Return a vector of booleans to indicate which
325 // successors are reachable from a given terminator instruction.
327 void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
328 assert(Succs.size() == TI.getNumSuccessors() && "Succs vector wrong size!");
329 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
330 if (BI->isUnconditional()) {
333 InstVal &BCValue = getValueState(BI->getCondition());
334 if (BCValue.isOverdefined()) {
335 // Overdefined condition variables mean the branch could go either way.
336 Succs[0] = Succs[1] = true;
337 } else if (BCValue.isConstant()) {
338 // Constant condition variables mean the branch can only go a single way
339 Succs[BCValue.getConstant() == ConstantBool::False] = true;
342 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
343 // Invoke instructions successors are always executable.
344 Succs[0] = Succs[1] = true;
345 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
346 InstVal &SCValue = getValueState(SI->getCondition());
347 if (SCValue.isOverdefined()) { // Overdefined condition?
348 // All destinations are executable!
349 Succs.assign(TI.getNumSuccessors(), true);
350 } else if (SCValue.isConstant()) {
351 Constant *CPV = SCValue.getConstant();
352 // Make sure to skip the "default value" which isn't a value
353 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
354 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
360 // Constant value not equal to any of the branches... must execute
361 // default branch then...
365 cerr << "SCCP: Don't know how to handle: " << TI;
366 Succs.assign(TI.getNumSuccessors(), true);
371 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
372 // block to the 'To' basic block is currently feasible...
374 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
375 assert(BBExecutable.count(To) && "Dest should always be alive!");
377 // Make sure the source basic block is executable!!
378 if (!BBExecutable.count(From)) return false;
380 // Check to make sure this edge itself is actually feasible now...
381 TerminatorInst *FT = From->getTerminator();
382 std::vector<bool> SuccFeasible(FT->getNumSuccessors());
383 getFeasibleSuccessors(*FT, SuccFeasible);
385 // Check all edges from From to To. If any are feasible, return true.
386 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
387 if (FT->getSuccessor(i) == To && SuccFeasible[i])
390 // Otherwise, none of the edges are actually feasible at this time...
394 // visit Implementations - Something changed in this instruction... Either an
395 // operand made a transition, or the instruction is newly executable. Change
396 // the value type of I to reflect these changes if appropriate. This method
397 // makes sure to do the following actions:
399 // 1. If a phi node merges two constants in, and has conflicting value coming
400 // from different branches, or if the PHI node merges in an overdefined
401 // value, then the PHI node becomes overdefined.
402 // 2. If a phi node merges only constants in, and they all agree on value, the
403 // PHI node becomes a constant value equal to that.
404 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
405 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
406 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
407 // 6. If a conditional branch has a value that is constant, make the selected
408 // destination executable
409 // 7. If a conditional branch has a value that is overdefined, make all
410 // successors executable.
413 void SCCP::visitPHINode(PHINode &PN) {
414 unsigned NumValues = PN.getNumIncomingValues(), i;
415 InstVal *OperandIV = 0;
417 // Look at all of the executable operands of the PHI node. If any of them
418 // are overdefined, the PHI becomes overdefined as well. If they are all
419 // constant, and they agree with each other, the PHI becomes the identical
420 // constant. If they are constant and don't agree, the PHI is overdefined.
421 // If there are no executable operands, the PHI remains undefined.
423 for (i = 0; i < NumValues; ++i) {
424 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
425 InstVal &IV = getValueState(PN.getIncomingValue(i));
426 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
427 if (IV.isOverdefined()) { // PHI node becomes overdefined!
428 markOverdefined(&PN);
432 if (OperandIV == 0) { // Grab the first value...
434 } else { // Another value is being merged in!
435 // There is already a reachable operand. If we conflict with it,
436 // then the PHI node becomes overdefined. If we agree with it, we
439 // Check to see if there are two different constants merging...
440 if (IV.getConstant() != OperandIV->getConstant()) {
441 // Yes there is. This means the PHI node is not constant.
442 // You must be overdefined poor PHI.
444 markOverdefined(&PN); // The PHI node now becomes overdefined
445 return; // I'm done analyzing you
451 // If we exited the loop, this means that the PHI node only has constant
452 // arguments that agree with each other(and OperandIV is a pointer to one
453 // of their InstVal's) or OperandIV is null because there are no defined
454 // incoming arguments. If this is the case, the PHI remains undefined.
457 assert(OperandIV->isConstant() && "Should only be here for constants!");
458 markConstant(&PN, OperandIV->getConstant()); // Aquire operand value
462 void SCCP::visitTerminatorInst(TerminatorInst &TI) {
463 std::vector<bool> SuccFeasible(TI.getNumSuccessors());
464 getFeasibleSuccessors(TI, SuccFeasible);
466 // Mark all feasible successors executable...
467 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
468 if (SuccFeasible[i]) {
469 BasicBlock *Succ = TI.getSuccessor(i);
470 markExecutable(Succ);
472 // Visit all of the PHI nodes that merge values from this block...
473 // Because this edge may be new executable, and PHI nodes that used to be
474 // constant now may not be.
476 for (BasicBlock::iterator I = Succ->begin();
477 PHINode *PN = dyn_cast<PHINode>(&*I); ++I)
482 void SCCP::visitCastInst(CastInst &I) {
483 Value *V = I.getOperand(0);
484 InstVal &VState = getValueState(V);
485 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
487 } else if (VState.isConstant()) { // Propagate constant value
489 ConstantFoldCastInstruction(VState.getConstant(), I.getType());
492 // This instruction constant folds!
493 markConstant(&I, Result);
495 markOverdefined(&I); // Don't know how to fold this instruction. :(
500 // Handle BinaryOperators and Shift Instructions...
501 void SCCP::visitBinaryOperator(Instruction &I) {
502 InstVal &V1State = getValueState(I.getOperand(0));
503 InstVal &V2State = getValueState(I.getOperand(1));
504 if (V1State.isOverdefined() || V2State.isOverdefined()) {
506 } else if (V1State.isConstant() && V2State.isConstant()) {
507 Constant *Result = 0;
508 if (isa<BinaryOperator>(I))
509 Result = ConstantFoldBinaryInstruction(I.getOpcode(),
510 V1State.getConstant(),
511 V2State.getConstant());
512 else if (isa<ShiftInst>(I))
513 Result = ConstantFoldShiftInstruction(I.getOpcode(),
514 V1State.getConstant(),
515 V2State.getConstant());
517 markConstant(&I, Result); // This instruction constant folds!
519 markOverdefined(&I); // Don't know how to fold this instruction. :(
523 // Handle getelementptr instructions... if all operands are constants then we
524 // can turn this into a getelementptr ConstantExpr.
526 void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
527 std::vector<Constant*> Operands;
528 Operands.reserve(I.getNumOperands());
530 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
531 InstVal &State = getValueState(I.getOperand(i));
532 if (State.isUndefined())
533 return; // Operands are not resolved yet...
534 else if (State.isOverdefined()) {
538 assert(State.isConstant() && "Unknown state!");
539 Operands.push_back(State.getConstant());
542 Constant *Ptr = Operands[0];
543 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
545 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Operands));