SCCP.cpp revision 96c466b06ab0c830b07329c1b16037f585ccbe40
1//===- SCCP.cpp - Sparse Conditional Constant Propogation -----------------===// 2// 3// This file implements sparse conditional constant propogation and merging: 4// 5// Specifically, this: 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 constant, and unconditionalizes them 10// * Folds multiple identical constants in the constant pool together 11// 12// Notice that: 13// * This pass has a habit of making definitions be dead. It is a good idea 14// to to run a DCE pass sometime after running this pass. 15// 16//===----------------------------------------------------------------------===// 17 18#include "llvm/Transforms/Scalar/ConstantProp.h" 19#include "llvm/ConstantHandling.h" 20#include "llvm/Function.h" 21#include "llvm/BasicBlock.h" 22#include "llvm/Constants.h" 23#include "llvm/iPHINode.h" 24#include "llvm/iMemory.h" 25#include "llvm/iTerminators.h" 26#include "llvm/iOther.h" 27#include "llvm/Pass.h" 28#include "llvm/Support/InstVisitor.h" 29#include "Support/STLExtras.h" 30#include <algorithm> 31#include <map> 32#include <set> 33#include <iostream> 34using std::cerr; 35 36// InstVal class - This class represents the different lattice values that an 37// instruction may occupy. It is a simple class with value semantics. 38// 39class InstVal { 40 enum { 41 undefined, // This instruction has no known value 42 constant, // This instruction has a constant value 43 // Range, // This instruction is known to fall within a range 44 overdefined // This instruction has an unknown value 45 } LatticeValue; // The current lattice position 46 Constant *ConstantVal; // If Constant value, the current value 47public: 48 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {} 49 50 // markOverdefined - Return true if this is a new status to be in... 51 inline bool markOverdefined() { 52 if (LatticeValue != overdefined) { 53 LatticeValue = overdefined; 54 return true; 55 } 56 return false; 57 } 58 59 // markConstant - Return true if this is a new status for us... 60 inline bool markConstant(Constant *V) { 61 if (LatticeValue != constant) { 62 LatticeValue = constant; 63 ConstantVal = V; 64 return true; 65 } else { 66 assert(ConstantVal == V && "Marking constant with different value"); 67 } 68 return false; 69 } 70 71 inline bool isUndefined() const { return LatticeValue == undefined; } 72 inline bool isConstant() const { return LatticeValue == constant; } 73 inline bool isOverdefined() const { return LatticeValue == overdefined; } 74 75 inline Constant *getConstant() const { return ConstantVal; } 76}; 77 78 79 80//===----------------------------------------------------------------------===// 81// SCCP Class 82// 83// This class does all of the work of Sparse Conditional Constant Propogation. 84// It's public interface consists of a constructor and a doSCCP() function. 85// 86class SCCP : public InstVisitor<SCCP> { 87 Function *M; // The function that we are working on 88 89 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable 90 std::map<Value*, InstVal> ValueState; // The state each value is in... 91 92 std::vector<Instruction*> InstWorkList;// The instruction work list 93 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list 94 95 //===--------------------------------------------------------------------===// 96 // The public interface for this class 97 // 98public: 99 100 // SCCP Ctor - Save the function to operate on... 101 inline SCCP(Function *f) : M(f) {} 102 103 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 104 // return true if the function was modified. 105 bool doSCCP(); 106 107 //===--------------------------------------------------------------------===// 108 // The implementation of this class 109 // 110private: 111 friend class InstVisitor<SCCP>; // Allow callbacks from visitor 112 113 // markValueOverdefined - Make a value be marked as "constant". If the value 114 // is not already a constant, add it to the instruction work list so that 115 // the users of the instruction are updated later. 116 // 117 inline bool markConstant(Instruction *I, Constant *V) { 118 //cerr << "markConstant: " << V << " = " << I; 119 if (ValueState[I].markConstant(V)) { 120 InstWorkList.push_back(I); 121 return true; 122 } 123 return false; 124 } 125 126 // markValueOverdefined - Make a value be marked as "overdefined". If the 127 // value is not already overdefined, add it to the instruction work list so 128 // that the users of the instruction are updated later. 129 // 130 inline bool markOverdefined(Value *V) { 131 if (ValueState[V].markOverdefined()) { 132 if (Instruction *I = dyn_cast<Instruction>(V)) { 133 //cerr << "markOverdefined: " << V; 134 InstWorkList.push_back(I); // Only instructions go on the work list 135 } 136 return true; 137 } 138 return false; 139 } 140 141 // getValueState - Return the InstVal object that corresponds to the value. 142 // This function is neccesary because not all values should start out in the 143 // underdefined state... Argument's should be overdefined, and 144 // constants should be marked as constants. If a value is not known to be an 145 // Instruction object, then use this accessor to get its value from the map. 146 // 147 inline InstVal &getValueState(Value *V) { 148 std::map<Value*, InstVal>::iterator I = ValueState.find(V); 149 if (I != ValueState.end()) return I->second; // Common case, in the map 150 151 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant 152 ValueState[CPV].markConstant(CPV); 153 } else if (isa<Argument>(V)) { // Arguments are overdefined 154 ValueState[V].markOverdefined(); 155 } 156 // All others are underdefined by default... 157 return ValueState[V]; 158 } 159 160 // markExecutable - Mark a basic block as executable, adding it to the BB 161 // work list if it is not already executable... 162 // 163 void markExecutable(BasicBlock *BB) { 164 if (BBExecutable.count(BB)) return; 165 //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! 168 } 169 170 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. 174 // 175 void visitPHINode(PHINode *I); 176 177 // Terminators 178 void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ } 179 void visitBranchInst(BranchInst *I); 180 void visitSwitchInst(SwitchInst *I); 181 182 void visitUnaryOperator(Instruction *I); 183 void visitCastInst(CastInst *I) { visitUnaryOperator(I); } 184 void visitBinaryOperator(Instruction *I); 185 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); } 186 187 // Instructions that cannot be folded away... 188 void visitMemAccessInst (Instruction *I) { markOverdefined(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) { markOverdefined(I); } 193 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 198 } 199 200 // OperandChangedState - This method is invoked on all of the users of an 201 // instruction that was just changed state somehow.... Based on this 202 // information, we need to update the specified user of this instruction. 203 // 204 void OperandChangedState(User *U); 205}; 206 207 208//===----------------------------------------------------------------------===// 209// SCCP Class Implementation 210 211 212// doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 213// return true if the function was modified. 214// 215bool SCCP::doSCCP() { 216 // Mark the first block of the function as being executable... 217 markExecutable(M->front()); 218 219 // Process the work lists until their are empty! 220 while (!BBWorkList.empty() || !InstWorkList.empty()) { 221 // Process the instruction work list... 222 while (!InstWorkList.empty()) { 223 Instruction *I = InstWorkList.back(); 224 InstWorkList.pop_back(); 225 226 //cerr << "\nPopped off I-WL: " << I; 227 228 229 // "I" got into the work list because it either made the transition from 230 // bottom to constant, or to Overdefined. 231 // 232 // Update all of the users of this instruction's value... 233 // 234 for_each(I->use_begin(), I->use_end(), 235 bind_obj(this, &SCCP::OperandChangedState)); 236 } 237 238 // Process the basic block work list... 239 while (!BBWorkList.empty()) { 240 BasicBlock *BB = BBWorkList.back(); 241 BBWorkList.pop_back(); 242 243 //cerr << "\nPopped off BBWL: " << BB; 244 245 // If this block only has a single successor, mark it as executable as 246 // well... if not, terminate the do loop. 247 // 248 if (BB->getTerminator()->getNumSuccessors() == 1) 249 markExecutable(BB->getTerminator()->getSuccessor(0)); 250 251 // Notify all instructions in this basic block that they are newly 252 // executable. 253 visit(BB); 254 } 255 } 256 257#if 0 258 for (Function::iterator BBI = M->begin(), BBEnd = M->end(); 259 BBI != BBEnd; ++BBI) 260 if (!BBExecutable.count(*BBI)) 261 cerr << "BasicBlock Dead:" << *BBI; 262#endif 263 264 265 // Iterate over all of the instructions in a function, replacing them with 266 // constants if we have found them to be of constant values. 267 // 268 bool MadeChanges = false; 269 for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) { 270 BasicBlock *BB = *MI; 271 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) { 272 Instruction *Inst = *BI; 273 InstVal &IV = ValueState[Inst]; 274 if (IV.isConstant()) { 275 Constant *Const = IV.getConstant(); 276 // cerr << "Constant: " << Inst << " is: " << Const; 277 278 // Replaces all of the uses of a variable with uses of the constant. 279 Inst->replaceAllUsesWith(Const); 280 281 // Remove the operator from the list of definitions... 282 BB->getInstList().remove(BI); 283 284 // The new constant inherits the old name of the operator... 285 if (Inst->hasName() && !Const->hasName()) 286 Const->setName(Inst->getName(), M->getSymbolTableSure()); 287 288 // Delete the operator now... 289 delete Inst; 290 291 // Hey, we just changed something! 292 MadeChanges = true; 293 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) { 294 MadeChanges |= ConstantFoldTerminator(BB, BI, TI); 295 } 296 297 ++BI; 298 } 299 } 300 301 // Merge identical constants last: this is important because we may have just 302 // introduced constants that already exist, and we don't want to pollute later 303 // stages with extraneous constants. 304 // 305 return MadeChanges; 306} 307 308 309// visit Implementations - Something changed in this instruction... Either an 310// operand made a transition, or the instruction is newly executable. Change 311// the value type of I to reflect these changes if appropriate. This method 312// makes sure to do the following actions: 313// 314// 1. If a phi node merges two constants in, and has conflicting value coming 315// from different branches, or if the PHI node merges in an overdefined 316// value, then the PHI node becomes overdefined. 317// 2. If a phi node merges only constants in, and they all agree on value, the 318// PHI node becomes a constant value equal to that. 319// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 320// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 321// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 322// 6. If a conditional branch has a value that is constant, make the selected 323// destination executable 324// 7. If a conditional branch has a value that is overdefined, make all 325// successors executable. 326// 327 328void SCCP::visitPHINode(PHINode *PN) { 329 unsigned NumValues = PN->getNumIncomingValues(), i; 330 InstVal *OperandIV = 0; 331 332 // Look at all of the executable operands of the PHI node. If any of them 333 // are overdefined, the PHI becomes overdefined as well. If they are all 334 // constant, and they agree with each other, the PHI becomes the identical 335 // constant. If they are constant and don't agree, the PHI is overdefined. 336 // If there are no executable operands, the PHI remains undefined. 337 // 338 for (i = 0; i < NumValues; ++i) { 339 if (BBExecutable.count(PN->getIncomingBlock(i))) { 340 InstVal &IV = getValueState(PN->getIncomingValue(i)); 341 if (IV.isUndefined()) continue; // Doesn't influence PHI node. 342 if (IV.isOverdefined()) { // PHI node becomes overdefined! 343 markOverdefined(PN); 344 return; 345 } 346 347 if (OperandIV == 0) { // Grab the first value... 348 OperandIV = &IV; 349 } else { // Another value is being merged in! 350 // There is already a reachable operand. If we conflict with it, 351 // then the PHI node becomes overdefined. If we agree with it, we 352 // can continue on. 353 354 // Check to see if there are two different constants merging... 355 if (IV.getConstant() != OperandIV->getConstant()) { 356 // Yes there is. This means the PHI node is not constant. 357 // You must be overdefined poor PHI. 358 // 359 markOverdefined(PN); // The PHI node now becomes overdefined 360 return; // I'm done analyzing you 361 } 362 } 363 } 364 } 365 366 // If we exited the loop, this means that the PHI node only has constant 367 // arguments that agree with each other(and OperandIV is a pointer to one 368 // of their InstVal's) or OperandIV is null because there are no defined 369 // incoming arguments. If this is the case, the PHI remains undefined. 370 // 371 if (OperandIV) { 372 assert(OperandIV->isConstant() && "Should only be here for constants!"); 373 markConstant(PN, OperandIV->getConstant()); // Aquire operand value 374 } 375} 376 377void SCCP::visitBranchInst(BranchInst *BI) { 378 if (BI->isUnconditional()) 379 return; // Unconditional branches are already handled! 380 381 InstVal &BCValue = getValueState(BI->getCondition()); 382 if (BCValue.isOverdefined()) { 383 // Overdefined condition variables mean the branch could go either way. 384 markExecutable(BI->getSuccessor(0)); 385 markExecutable(BI->getSuccessor(1)); 386 } else if (BCValue.isConstant()) { 387 // Constant condition variables mean the branch can only go a single way. 388 if (BCValue.getConstant() == ConstantBool::True) 389 markExecutable(BI->getSuccessor(0)); 390 else 391 markExecutable(BI->getSuccessor(1)); 392 } 393} 394 395void SCCP::visitSwitchInst(SwitchInst *SI) { 396 InstVal &SCValue = getValueState(SI->getCondition()); 397 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe 398 for(unsigned i = 0, E = SI->getNumSuccessors(); i != E; ++i) 399 markExecutable(SI->getSuccessor(i)); 400 } else if (SCValue.isConstant()) { 401 Constant *CPV = SCValue.getConstant(); 402 // Make sure to skip the "default value" which isn't a value 403 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) { 404 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch... 405 markExecutable(SI->getSuccessor(i)); 406 return; 407 } 408 } 409 410 // Constant value not equal to any of the branches... must execute 411 // default branch then... 412 markExecutable(SI->getDefaultDest()); 413 } 414} 415 416void SCCP::visitUnaryOperator(Instruction *I) { 417 Value *V = I->getOperand(0); 418 InstVal &VState = getValueState(V); 419 if (VState.isOverdefined()) { // Inherit overdefinedness of operand 420 markOverdefined(I); 421 } else if (VState.isConstant()) { // Propogate constant value 422 Constant *Result = isa<CastInst>(I) 423 ? ConstantFoldCastInstruction(VState.getConstant(), I->getType()) 424 : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant()); 425 426 if (Result) { 427 // This instruction constant folds! 428 markConstant(I, Result); 429 } else { 430 markOverdefined(I); // Don't know how to fold this instruction. :( 431 } 432 } 433} 434 435// Handle BinaryOperators and Shift Instructions... 436void SCCP::visitBinaryOperator(Instruction *I) { 437 InstVal &V1State = getValueState(I->getOperand(0)); 438 InstVal &V2State = getValueState(I->getOperand(1)); 439 if (V1State.isOverdefined() || V2State.isOverdefined()) { 440 markOverdefined(I); 441 } else if (V1State.isConstant() && V2State.isConstant()) { 442 Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(), 443 V1State.getConstant(), 444 V2State.getConstant()); 445 if (Result) 446 markConstant(I, Result); // This instruction constant fold!s 447 else 448 markOverdefined(I); // Don't know how to fold this instruction. :( 449 } 450} 451 452// OperandChangedState - This method is invoked on all of the users of an 453// instruction that was just changed state somehow.... Based on this 454// information, we need to update the specified user of this instruction. 455// 456void SCCP::OperandChangedState(User *U) { 457 // Only instructions use other variable values! 458 Instruction *I = cast<Instruction>(U); 459 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet! 460 461 visit(I); 462} 463 464namespace { 465 // SCCPPass - Use Sparse Conditional Constant Propogation 466 // to prove whether a value is constant and whether blocks are used. 467 // 468 struct SCCPPass : public FunctionPass { 469 const char *getPassName() const { 470 return "Sparse Conditional Constant Propogation"; 471 } 472 473 inline bool runOnFunction(Function *F) { 474 SCCP S(F); 475 return S.doSCCP(); 476 } 477 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 478 // FIXME: SCCP does not preserve the CFG because it folds terminators! 479 //AU.preservesCFG(); 480 } 481 }; 482} 483 484Pass *createSCCPPass() { 485 return new SCCPPass(); 486} 487