1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements sparse conditional constant propagation and merging:
12 // Specifically, this:
13 // * Assumes values are constant unless proven otherwise
14 // * Assumes BasicBlocks are dead unless proven otherwise
15 // * Proves values to be constant, and replaces them with constants
16 // * Proves conditional branches to be unconditional
19 // * This pass has a habit of making definitions be dead. It is a good idea
20 // to to run a DCE pass sometime after running this pass.
22 //===----------------------------------------------------------------------===//
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/ConstantHandling.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/InstVisitor.h"
30 #include "Support/Debug.h"
31 #include "Support/Statistic.h"
32 #include "Support/STLExtras.h"
38 // InstVal class - This class represents the different lattice values that an
39 // instruction may occupy. It is a simple class with value semantics.
42 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
46 undefined, // This instruction has no known value
47 constant, // This instruction has a constant value
48 overdefined // This instruction has an unknown value
49 } LatticeValue; // The current lattice position
50 Constant *ConstantVal; // If Constant value, the current value
52 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
54 // markOverdefined - Return true if this is a new status to be in...
55 inline bool markOverdefined() {
56 if (LatticeValue != overdefined) {
57 LatticeValue = overdefined;
63 // markConstant - Return true if this is a new status for us...
64 inline bool markConstant(Constant *V) {
65 if (LatticeValue != constant) {
66 LatticeValue = constant;
70 assert(ConstantVal == V && "Marking constant with different value");
75 inline bool isUndefined() const { return LatticeValue == undefined; }
76 inline bool isConstant() const { return LatticeValue == constant; }
77 inline bool isOverdefined() const { return LatticeValue == overdefined; }
79 inline Constant *getConstant() const { return ConstantVal; }
82 } // end anonymous namespace
85 //===----------------------------------------------------------------------===//
88 // This class does all of the work of Sparse Conditional Constant Propagation.
91 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
92 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
93 std::map<Value*, InstVal> ValueState; // The state each value is in...
95 std::vector<Instruction*> InstWorkList;// The instruction work list
96 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
98 /// KnownFeasibleEdges - Entries in this set are edges which have already had
99 /// PHI nodes retriggered.
100 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
101 std::set<Edge> KnownFeasibleEdges;
104 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
105 // and return true if the function was modified.
107 bool runOnFunction(Function &F);
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.setPreservesCFG();
114 //===--------------------------------------------------------------------===//
115 // The implementation of this class
118 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
120 // markValueOverdefined - Make a value be marked as "constant". If the value
121 // is not already a constant, add it to the instruction work list so that
122 // the users of the instruction are updated later.
124 inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
125 if (IV.markConstant(C)) {
126 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
127 InstWorkList.push_back(I);
130 inline void markConstant(Instruction *I, Constant *C) {
131 markConstant(ValueState[I], I, C);
134 // markValueOverdefined - Make a value be marked as "overdefined". If the
135 // value is not already overdefined, add it to the instruction work list so
136 // that the users of the instruction are updated later.
138 inline void markOverdefined(InstVal &IV, Instruction *I) {
139 if (IV.markOverdefined()) {
140 DEBUG(std::cerr << "markOverdefined: " << *I);
141 InstWorkList.push_back(I); // Only instructions go on the work list
144 inline void markOverdefined(Instruction *I) {
145 markOverdefined(ValueState[I], I);
148 // getValueState - Return the InstVal object that corresponds to the value.
149 // This function is necessary because not all values should start out in the
150 // underdefined state... Argument's should be overdefined, and
151 // constants should be marked as constants. If a value is not known to be an
152 // Instruction object, then use this accessor to get its value from the map.
154 inline InstVal &getValueState(Value *V) {
155 std::map<Value*, InstVal>::iterator I = ValueState.find(V);
156 if (I != ValueState.end()) return I->second; // Common case, in the map
158 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
159 ValueState[CPV].markConstant(CPV);
160 } else if (isa<Argument>(V)) { // Arguments are overdefined
161 ValueState[V].markOverdefined();
162 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
163 // The address of a global is a constant...
164 ValueState[V].markConstant(ConstantPointerRef::get(GV));
166 // All others are underdefined by default...
167 return ValueState[V];
170 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
171 // work list if it is not already executable...
173 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
174 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
175 return; // This edge is already known to be executable!
177 if (BBExecutable.count(Dest)) {
178 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
179 << " -> " << Dest->getName() << "\n");
181 // The destination is already executable, but we just made an edge
182 // feasible that wasn't before. Revisit the PHI nodes in the block
183 // because they have potentially new operands.
184 for (BasicBlock::iterator I = Dest->begin();
185 PHINode *PN = dyn_cast<PHINode>(I); ++I)
189 DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
190 BBExecutable.insert(Dest); // Basic block is executable!
191 BBWorkList.push_back(Dest); // Add the block to the work list!
196 // visit implementations - Something changed in this instruction... Either an
197 // operand made a transition, or the instruction is newly executable. Change
198 // the value type of I to reflect these changes if appropriate.
200 void visitPHINode(PHINode &I);
203 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
204 void visitTerminatorInst(TerminatorInst &TI);
206 void visitCastInst(CastInst &I);
207 void visitBinaryOperator(Instruction &I);
208 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
210 // Instructions that cannot be folded away...
211 void visitStoreInst (Instruction &I) { /*returns void*/ }
212 void visitLoadInst (Instruction &I) { markOverdefined(&I); }
213 void visitGetElementPtrInst(GetElementPtrInst &I);
214 void visitCallInst (Instruction &I) { markOverdefined(&I); }
215 void visitInvokeInst (TerminatorInst &I) {
216 if (I.getType() != Type::VoidTy) markOverdefined(&I);
217 visitTerminatorInst(I);
219 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
220 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
221 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
222 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
223 void visitFreeInst (Instruction &I) { /*returns void*/ }
225 void visitInstruction(Instruction &I) {
226 // If a new instruction is added to LLVM that we don't handle...
227 std::cerr << "SCCP: Don't know how to handle: " << I;
228 markOverdefined(&I); // Just in case
231 // getFeasibleSuccessors - Return a vector of booleans to indicate which
232 // successors are reachable from a given terminator instruction.
234 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
236 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
237 // block to the 'To' basic block is currently feasible...
239 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
241 // OperandChangedState - This method is invoked on all of the users of an
242 // instruction that was just changed state somehow.... Based on this
243 // information, we need to update the specified user of this instruction.
245 void OperandChangedState(User *U) {
246 // Only instructions use other variable values!
247 Instruction &I = cast<Instruction>(*U);
248 if (BBExecutable.count(I.getParent())) // Inst is executable?
253 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
254 } // end anonymous namespace
257 // createSCCPPass - This is the public interface to this file...
258 Pass *createSCCPPass() {
263 //===----------------------------------------------------------------------===//
264 // SCCP Class Implementation
267 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
268 // and return true if the function was modified.
270 bool SCCP::runOnFunction(Function &F) {
271 // Mark the first block of the function as being executable...
272 BBExecutable.insert(F.begin()); // Basic block is executable!
273 BBWorkList.push_back(F.begin()); // Add the block to the work list!
275 // Process the work lists until their are empty!
276 while (!BBWorkList.empty() || !InstWorkList.empty()) {
277 // Process the instruction work list...
278 while (!InstWorkList.empty()) {
279 Instruction *I = InstWorkList.back();
280 InstWorkList.pop_back();
282 DEBUG(std::cerr << "\nPopped off I-WL: " << I);
284 // "I" got into the work list because it either made the transition from
285 // bottom to constant, or to Overdefined.
287 // Update all of the users of this instruction's value...
289 for_each(I->use_begin(), I->use_end(),
290 bind_obj(this, &SCCP::OperandChangedState));
293 // Process the basic block work list...
294 while (!BBWorkList.empty()) {
295 BasicBlock *BB = BBWorkList.back();
296 BBWorkList.pop_back();
298 DEBUG(std::cerr << "\nPopped off BBWL: " << BB);
300 // Notify all instructions in this basic block that they are newly
307 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
308 if (!BBExecutable.count(I))
309 std::cerr << "BasicBlock Dead:" << *I;
312 // Iterate over all of the instructions in a function, replacing them with
313 // constants if we have found them to be of constant values.
315 bool MadeChanges = false;
316 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
317 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
318 Instruction &Inst = *BI;
319 InstVal &IV = ValueState[&Inst];
320 if (IV.isConstant()) {
321 Constant *Const = IV.getConstant();
322 DEBUG(std::cerr << "Constant: " << Const << " = " << Inst);
324 // Replaces all of the uses of a variable with uses of the constant.
325 Inst.replaceAllUsesWith(Const);
327 // Remove the operator from the list of definitions... and delete it.
328 BI = BB->getInstList().erase(BI);
330 // Hey, we just changed something!
338 // Reset state so that the next invocation will have empty data structures
339 BBExecutable.clear();
341 std::vector<Instruction*>().swap(InstWorkList);
342 std::vector<BasicBlock*>().swap(BBWorkList);
348 // getFeasibleSuccessors - Return a vector of booleans to indicate which
349 // successors are reachable from a given terminator instruction.
351 void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
352 Succs.resize(TI.getNumSuccessors());
353 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
354 if (BI->isUnconditional()) {
357 InstVal &BCValue = getValueState(BI->getCondition());
358 if (BCValue.isOverdefined()) {
359 // Overdefined condition variables mean the branch could go either way.
360 Succs[0] = Succs[1] = true;
361 } else if (BCValue.isConstant()) {
362 // Constant condition variables mean the branch can only go a single way
363 Succs[BCValue.getConstant() == ConstantBool::False] = true;
366 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
367 // Invoke instructions successors are always executable.
368 Succs[0] = Succs[1] = true;
369 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
370 InstVal &SCValue = getValueState(SI->getCondition());
371 if (SCValue.isOverdefined()) { // Overdefined condition?
372 // All destinations are executable!
373 Succs.assign(TI.getNumSuccessors(), true);
374 } else if (SCValue.isConstant()) {
375 Constant *CPV = SCValue.getConstant();
376 // Make sure to skip the "default value" which isn't a value
377 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
378 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
384 // Constant value not equal to any of the branches... must execute
385 // default branch then...
389 std::cerr << "SCCP: Don't know how to handle: " << TI;
390 Succs.assign(TI.getNumSuccessors(), true);
395 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
396 // block to the 'To' basic block is currently feasible...
398 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
399 assert(BBExecutable.count(To) && "Dest should always be alive!");
401 // Make sure the source basic block is executable!!
402 if (!BBExecutable.count(From)) return false;
404 // Check to make sure this edge itself is actually feasible now...
405 TerminatorInst *TI = From->getTerminator();
406 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
407 if (BI->isUnconditional())
410 InstVal &BCValue = getValueState(BI->getCondition());
411 if (BCValue.isOverdefined()) {
412 // Overdefined condition variables mean the branch could go either way.
414 } else if (BCValue.isConstant()) {
415 // Constant condition variables mean the branch can only go a single way
416 return BI->getSuccessor(BCValue.getConstant() ==
417 ConstantBool::False) == To;
421 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
422 // Invoke instructions successors are always executable.
424 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
425 InstVal &SCValue = getValueState(SI->getCondition());
426 if (SCValue.isOverdefined()) { // Overdefined condition?
427 // All destinations are executable!
429 } else if (SCValue.isConstant()) {
430 Constant *CPV = SCValue.getConstant();
431 // Make sure to skip the "default value" which isn't a value
432 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
433 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
434 return SI->getSuccessor(i) == To;
436 // Constant value not equal to any of the branches... must execute
437 // default branch then...
438 return SI->getDefaultDest() == To;
442 std::cerr << "Unknown terminator instruction: " << *TI;
447 // visit Implementations - Something changed in this instruction... Either an
448 // operand made a transition, or the instruction is newly executable. Change
449 // the value type of I to reflect these changes if appropriate. This method
450 // makes sure to do the following actions:
452 // 1. If a phi node merges two constants in, and has conflicting value coming
453 // from different branches, or if the PHI node merges in an overdefined
454 // value, then the PHI node becomes overdefined.
455 // 2. If a phi node merges only constants in, and they all agree on value, the
456 // PHI node becomes a constant value equal to that.
457 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
458 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
459 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
460 // 6. If a conditional branch has a value that is constant, make the selected
461 // destination executable
462 // 7. If a conditional branch has a value that is overdefined, make all
463 // successors executable.
465 void SCCP::visitPHINode(PHINode &PN) {
466 InstVal &PNIV = getValueState(&PN);
467 if (PNIV.isOverdefined()) return; // Quick exit
469 // Look at all of the executable operands of the PHI node. If any of them
470 // are overdefined, the PHI becomes overdefined as well. If they are all
471 // constant, and they agree with each other, the PHI becomes the identical
472 // constant. If they are constant and don't agree, the PHI is overdefined.
473 // If there are no executable operands, the PHI remains undefined.
475 Constant *OperandVal = 0;
476 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
477 InstVal &IV = getValueState(PN.getIncomingValue(i));
478 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
480 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
481 if (IV.isOverdefined()) { // PHI node becomes overdefined!
482 markOverdefined(PNIV, &PN);
486 if (OperandVal == 0) { // Grab the first value...
487 OperandVal = IV.getConstant();
488 } else { // Another value is being merged in!
489 // There is already a reachable operand. If we conflict with it,
490 // then the PHI node becomes overdefined. If we agree with it, we
493 // Check to see if there are two different constants merging...
494 if (IV.getConstant() != OperandVal) {
495 // Yes there is. This means the PHI node is not constant.
496 // You must be overdefined poor PHI.
498 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
499 return; // I'm done analyzing you
505 // If we exited the loop, this means that the PHI node only has constant
506 // arguments that agree with each other(and OperandVal is the constant) or
507 // OperandVal is null because there are no defined incoming arguments. If
508 // this is the case, the PHI remains undefined.
511 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
514 void SCCP::visitTerminatorInst(TerminatorInst &TI) {
515 std::vector<bool> SuccFeasible;
516 getFeasibleSuccessors(TI, SuccFeasible);
518 BasicBlock *BB = TI.getParent();
520 // Mark all feasible successors executable...
521 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
523 markEdgeExecutable(BB, TI.getSuccessor(i));
526 void SCCP::visitCastInst(CastInst &I) {
527 Value *V = I.getOperand(0);
528 InstVal &VState = getValueState(V);
529 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
531 } else if (VState.isConstant()) { // Propagate constant value
533 ConstantFoldCastInstruction(VState.getConstant(), I.getType());
535 if (Result) // If this instruction constant folds!
536 markConstant(&I, Result);
538 markOverdefined(&I); // Don't know how to fold this instruction. :(
542 // Handle BinaryOperators and Shift Instructions...
543 void SCCP::visitBinaryOperator(Instruction &I) {
544 InstVal &V1State = getValueState(I.getOperand(0));
545 InstVal &V2State = getValueState(I.getOperand(1));
546 if (V1State.isOverdefined() || V2State.isOverdefined()) {
548 } else if (V1State.isConstant() && V2State.isConstant()) {
549 Constant *Result = 0;
550 if (isa<BinaryOperator>(I))
551 Result = ConstantFoldBinaryInstruction(I.getOpcode(),
552 V1State.getConstant(),
553 V2State.getConstant());
554 else if (isa<ShiftInst>(I))
555 Result = ConstantFoldShiftInstruction(I.getOpcode(),
556 V1State.getConstant(),
557 V2State.getConstant());
559 markConstant(&I, Result); // This instruction constant folds!
561 markOverdefined(&I); // Don't know how to fold this instruction. :(
565 // Handle getelementptr instructions... if all operands are constants then we
566 // can turn this into a getelementptr ConstantExpr.
568 void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
569 std::vector<Constant*> Operands;
570 Operands.reserve(I.getNumOperands());
572 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
573 InstVal &State = getValueState(I.getOperand(i));
574 if (State.isUndefined())
575 return; // Operands are not resolved yet...
576 else if (State.isOverdefined()) {
580 assert(State.isConstant() && "Unknown state!");
581 Operands.push_back(State.getConstant());
584 Constant *Ptr = Operands[0];
585 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
587 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Operands));
590 } // End llvm namespace