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 constant, and unconditionalizes them
10 // * Folds multiple identical constants in the constant pool together
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.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Optimizations/ConstantProp.h"
19 #include "llvm/Optimizations/ConstantHandling.h"
20 #include "llvm/Method.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/ConstPoolVals.h"
23 #include "llvm/ConstantPool.h"
24 #include "llvm/InstrTypes.h"
25 #include "llvm/iOther.h"
26 #include "llvm/iTerminators.h"
27 #include "llvm/Tools/STLExtras.h"
28 //#include "llvm/Assembly/Writer.h"
33 // InstVal class - This class represents the different lattice values that an
34 // instruction may occupy. It is a simple class with value semantics. The
35 // potential constant value that is pointed to is owned by the constant pool
36 // for the method being optimized.
40 Undefined, // This instruction has no known value
41 Constant, // This instruction has a constant value
42 // Range, // This instruction is known to fall within a range
43 Overdefined // This instruction has an unknown value
44 } LatticeValue; // The current lattice position
45 ConstPoolVal *ConstantVal; // If Constant value, the current value
47 inline InstVal() : LatticeValue(Undefined), ConstantVal(0) {}
49 // markOverdefined - Return true if this is a new status to be in...
50 inline bool markOverdefined() {
51 if (LatticeValue != Overdefined) {
52 LatticeValue = Overdefined;
58 // markConstant - Return true if this is a new status for us...
59 inline bool markConstant(ConstPoolVal *V) {
60 if (LatticeValue != Constant) {
61 LatticeValue = Constant;
65 assert(ConstantVal->equals(V) && "Marking constant with different value");
70 inline bool isUndefined() const { return LatticeValue == Undefined; }
71 inline bool isConstant() const { return LatticeValue == Constant; }
72 inline bool isOverdefined() const { return LatticeValue == Overdefined; }
74 inline ConstPoolVal *getConstant() const { return ConstantVal; }
79 //===----------------------------------------------------------------------===//
82 // This class does all of the work of Sparse Conditional Constant Propogation.
83 // It's public interface consists of a constructor and a doSCCP() method.
86 Method *M; // The method that we are working on...
88 set<BasicBlock*> BBExecutable; // The basic blocks that are executable
89 map<Value*, InstVal> ValueState; // The state each value is in...
91 vector<Instruction*> InstWorkList; // The instruction work list
92 vector<BasicBlock*> BBWorkList; // The BasicBlock work list
94 //===--------------------------------------------------------------------===//
95 // The public interface for this class
99 // SCCP Ctor - Save the method to operate on...
100 inline SCCP(Method *m) : M(m) {}
102 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
103 // return true if the method was modified.
106 //===--------------------------------------------------------------------===//
107 // The implementation of this class
111 // markValueOverdefined - Make a value be marked as "constant". If the value
112 // is not already a constant, add it to the instruction work list so that
113 // the users of the instruction are updated later.
115 inline bool markConstant(Instruction *I, ConstPoolVal *V) {
116 //cerr << "markConstant: " << V << " = " << I;
117 if (ValueState[I].markConstant(V)) {
118 InstWorkList.push_back(I);
124 // markValueOverdefined - Make a value be marked as "overdefined". If the
125 // value is not already overdefined, add it to the instruction work list so
126 // that the users of the instruction are updated later.
128 inline bool markOverdefined(Value *V) {
129 if (ValueState[V].markOverdefined()) {
130 if (Instruction *I = V->castInstruction()) {
131 //cerr << "markOverdefined: " << V;
132 InstWorkList.push_back(I); // Only instructions go on the work list
139 // getValueState - Return the InstVal object that corresponds to the value.
140 // This function is neccesary because not all values should start out in the
141 // underdefined state... MethodArgument's should be overdefined, and constants
142 // should be marked as constants. If a value is not known to be an
143 // Instruction object, then use this accessor to get its value from the map.
145 inline InstVal &getValueState(Value *V) {
146 map<Value*, InstVal>::iterator I = ValueState.find(V);
147 if (I != ValueState.end()) return I->second; // Common case, in the map
149 if (ConstPoolVal *CPV = V->castConstant()) { // Constants are constant
150 ValueState[CPV].markConstant(CPV);
151 } else if (V->isMethodArgument()) { // MethodArgs are overdefined
152 ValueState[V].markOverdefined();
154 // All others are underdefined by default...
155 return ValueState[V];
158 // markExecutable - Mark a basic block as executable, adding it to the BB
159 // work list if it is not already executable...
161 void markExecutable(BasicBlock *BB) {
162 if (BBExecutable.count(BB)) return;
163 //cerr << "Marking BB Executable: " << BB;
164 BBExecutable.insert(BB); // Basic block is executable!
165 BBWorkList.push_back(BB); // Add the block to the work list!
169 // UpdateInstruction - Something changed in this instruction... Either an
170 // operand made a transition, or the instruction is newly executable. Change
171 // the value type of I to reflect these changes if appropriate.
173 void UpdateInstruction(Instruction *I);
175 // OperandChangedState - This method is invoked on all of the users of an
176 // instruction that was just changed state somehow.... Based on this
177 // information, we need to update the specified user of this instruction.
179 void OperandChangedState(User *U);
183 //===----------------------------------------------------------------------===//
184 // SCCP Class Implementation
187 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and
188 // return true if the method was modified.
190 bool SCCP::doSCCP() {
191 // Mark the first block of the method as being executable...
192 markExecutable(M->front());
194 // Process the work lists until their are empty!
195 while (!BBWorkList.empty() || !InstWorkList.empty()) {
196 // Process the instruction work list...
197 while (!InstWorkList.empty()) {
198 Instruction *I = InstWorkList.back();
199 InstWorkList.pop_back();
201 //cerr << "\nPopped off I-WL: " << I;
204 // "I" got into the work list because it either made the transition from
205 // bottom to constant, or to Overdefined.
207 // Update all of the users of this instruction's value...
209 for_each(I->use_begin(), I->use_end(),
210 bind_obj(this, &SCCP::OperandChangedState));
213 // Process the basic block work list...
214 while (!BBWorkList.empty()) {
215 BasicBlock *BB = BBWorkList.back();
216 BBWorkList.pop_back();
218 //cerr << "\nPopped off BBWL: " << BB;
220 // If this block only has a single successor, mark it as executable as
221 // well... if not, terminate the do loop.
223 if (BB->getTerminator()->getNumSuccessors() == 1)
224 markExecutable(BB->getTerminator()->getSuccessor(0));
226 // Loop over all of the instructions and notify them that they are newly
228 for_each(BB->begin(), BB->end(),
229 bind_obj(this, &SCCP::UpdateInstruction));
234 for (Method::iterator BBI = M->begin(), BBEnd = M->end(); BBI != BBEnd; ++BBI)
235 if (!BBExecutable.count(*BBI))
236 cerr << "BasicBlock Dead:" << *BBI;
240 // Iterate over all of the instructions in a method, replacing them with
241 // constants if we have found them to be of constant values.
243 bool MadeChanges = false;
244 for (Method::inst_iterator II = M->inst_begin(); II != M->inst_end(); ) {
245 Instruction *Inst = *II;
246 InstVal &IV = ValueState[Inst];
247 if (IV.isConstant()) {
248 ConstPoolVal *Const = IV.getConstant();
249 // cerr << "Constant: " << Inst << " is: " << Const;
251 // Replaces all of the uses of a variable with uses of the constant.
252 Inst->replaceAllUsesWith(Const);
254 // Remove the operator from the list of definitions...
255 Inst->getParent()->getInstList().remove(II.getInstructionIterator());
257 // The new constant inherits the old name of the operator...
258 if (Inst->hasName() && !Const->hasName())
259 Const->setName(Inst->getName());
261 // Delete the operator now...
264 // Incrementing the iterator in an unchecked manner could mess up the
265 // internals of 'II'. To make sure everything is happy, tell it we might
267 II.resyncInstructionIterator();
269 // Hey, we just changed something!
271 continue; // Skip the ++II at the end of the loop here...
272 } else if (Inst->isTerminator()) {
273 MadeChanges |= opt::ConstantFoldTerminator((TerminatorInst*)Inst);
279 // Merge identical constants last: this is important because we may have just
280 // introduced constants that already exist, and we don't want to pollute later
281 // stages with extraneous constants.
283 return MadeChanges | opt::DoConstantPoolMerging(M->getConstantPool());
287 // UpdateInstruction - Something changed in this instruction... Either an
288 // operand made a transition, or the instruction is newly executable. Change
289 // the value type of I to reflect these changes if appropriate. This method
290 // makes sure to do the following actions:
292 // 1. If a phi node merges two constants in, and has conflicting value coming
293 // from different branches, or if the PHI node merges in an overdefined
294 // value, then the PHI node becomes overdefined.
295 // 2. If a phi node merges only constants in, and they all agree on value, the
296 // PHI node becomes a constant value equal to that.
297 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
298 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
299 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
300 // 6. If a conditional branch has a value that is constant, make the selected
301 // destination executable
302 // 7. If a conditional branch has a value that is overdefined, make all
303 // successors executable.
305 void SCCP::UpdateInstruction(Instruction *I) {
306 InstVal &IValue = ValueState[I];
307 if (IValue.isOverdefined())
308 return; // If already overdefined, we aren't going to effect anything
310 switch (I->getOpcode()) {
311 //===-----------------------------------------------------------------===//
312 // Handle PHI nodes...
314 case Instruction::PHINode: {
315 PHINode *PN = (PHINode*)I;
316 unsigned NumValues = PN->getNumIncomingValues(), i;
317 InstVal *OperandIV = 0;
319 // Look at all of the executable operands of the PHI node. If any of them
320 // are overdefined, the PHI becomes overdefined as well. If they are all
321 // constant, and they agree with each other, the PHI becomes the identical
322 // constant. If they are constant and don't agree, the PHI is overdefined.
323 // If there are no executable operands, the PHI remains undefined.
325 for (i = 0; i < NumValues; ++i) {
326 if (BBExecutable.count(PN->getIncomingBlock(i))) {
327 InstVal &IV = getValueState(PN->getIncomingValue(i));
328 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
329 if (IV.isOverdefined()) { // PHI node becomes overdefined!
334 if (OperandIV == 0) { // Grab the first value...
336 } else { // Another value is being merged in!
337 // There is already a reachable operand. If we conflict with it,
338 // then the PHI node becomes overdefined. If we agree with it, we
341 // Check to see if there are two different constants merging...
342 if (!IV.getConstant()->equals(OperandIV->getConstant())) {
343 // Yes there is. This means the PHI node is not constant.
344 // You must be overdefined poor PHI.
346 markOverdefined(I); // The PHI node now becomes overdefined
347 return; // I'm done analyzing you
353 // If we exited the loop, this means that the PHI node only has constant
354 // arguments that agree with each other(and OperandIV is a pointer to one
355 // of their InstVal's) or OperandIV is null because there are no defined
356 // incoming arguments. If this is the case, the PHI remains undefined.
359 assert(OperandIV->isConstant() && "Should only be here for constants!");
360 markConstant(I, OperandIV->getConstant()); // Aquire operand value
365 //===-----------------------------------------------------------------===//
366 // Handle instructions that unconditionally provide overdefined values...
368 case Instruction::Malloc:
369 case Instruction::Free:
370 case Instruction::Alloca:
371 case Instruction::Load:
372 case Instruction::Store:
373 // TODO: getfield/putfield?
374 case Instruction::Call:
375 markOverdefined(I); // Memory and call's are all overdefined
378 //===-----------------------------------------------------------------===//
379 // Handle Terminator instructions...
381 case Instruction::Ret: return; // Method return doesn't affect anything
382 case Instruction::Br: { // Handle conditional branches...
383 BranchInst *BI = (BranchInst*)I;
384 if (BI->isUnconditional())
385 return; // Unconditional branches are already handled!
387 InstVal &BCValue = getValueState(BI->getCondition());
388 if (BCValue.isOverdefined()) {
389 // Overdefined condition variables mean the branch could go either way.
390 markExecutable(BI->getSuccessor(0));
391 markExecutable(BI->getSuccessor(1));
392 } else if (BCValue.isConstant()) {
393 // Constant condition variables mean the branch can only go a single way.
394 ConstPoolBool *CPB = (ConstPoolBool*)BCValue.getConstant();
395 if (CPB->getValue()) // If the branch condition is TRUE...
396 markExecutable(BI->getSuccessor(0));
397 else // Else if the br cond is FALSE...
398 markExecutable(BI->getSuccessor(1));
403 case Instruction::Switch: {
404 SwitchInst *SI = (SwitchInst*)I;
405 InstVal &SCValue = getValueState(SI->getCondition());
406 if (SCValue.isOverdefined()) { // Overdefined condition? All dests are exe
407 for(unsigned i = 0; BasicBlock *Succ = SI->getSuccessor(i); ++i)
408 markExecutable(Succ);
409 } else if (SCValue.isConstant()) {
410 ConstPoolVal *CPV = SCValue.getConstant();
411 // Make sure to skip the "default value" which isn't a value
412 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
413 if (SI->getSuccessorValue(i)->equals(CPV)) {// Found the right branch...
414 markExecutable(SI->getSuccessor(i));
419 // Constant value not equal to any of the branches... must execute
420 // default branch then...
421 markExecutable(SI->getDefaultDest());
426 default: break; // Handle math operators as groups.
427 } // end switch(I->getOpcode())
430 //===-------------------------------------------------------------------===//
431 // Handle Unary instructions...
433 if (I->isUnaryOp()) {
434 Value *V = I->getOperand(0);
435 InstVal &VState = getValueState(V);
436 if (VState.isOverdefined()) { // Inherit overdefinedness of operand
438 } else if (VState.isConstant()) { // Propogate constant value
439 ConstPoolVal *Result =
440 opt::ConstantFoldUnaryInstruction(I->getOpcode(),
441 VState.getConstant());
444 // This instruction constant folds! The only problem is that the value
445 // returned is newly allocated. Make sure to stick it into the methods
447 M->getConstantPool().insert(Result);
448 markConstant(I, Result);
450 markOverdefined(I); // Don't know how to fold this instruction. :(
456 //===-----------------------------------------------------------------===//
457 // Handle Binary instructions...
459 if (I->isBinaryOp()) {
460 Value *V1 = I->getOperand(0);
461 Value *V2 = I->getOperand(1);
463 InstVal &V1State = getValueState(V1);
464 InstVal &V2State = getValueState(V2);
465 if (V1State.isOverdefined() || V2State.isOverdefined()) {
467 } else if (V1State.isConstant() && V2State.isConstant()) {
468 ConstPoolVal *Result =
469 opt::ConstantFoldBinaryInstruction(I->getOpcode(),
470 V1State.getConstant(),
471 V2State.getConstant());
473 // This instruction constant folds! The only problem is that the value
474 // returned is newly allocated. Make sure to stick it into the methods
476 M->getConstantPool().insert(Result);
477 markConstant(I, Result);
479 markOverdefined(I); // Don't know how to fold this instruction. :(
485 // Shouldn't get here... either the switch statement or one of the group
486 // handlers should have kicked in...
488 cerr << "SCCP: Don't know how to handle: " << I;
489 markOverdefined(I); // Just in case
494 // OperandChangedState - This method is invoked on all of the users of an
495 // instruction that was just changed state somehow.... Based on this
496 // information, we need to update the specified user of this instruction.
498 void SCCP::OperandChangedState(User *U) {
499 // Only instructions use other variable values!
500 Instruction *I = U->castInstructionAsserting();
501 if (!BBExecutable.count(I->getParent())) return; // Inst not executable yet!
503 UpdateInstruction(I);
507 // DoSparseConditionalConstantProp - Use Sparse Conditional Constant Propogation
508 // to prove whether a value is constant and whether blocks are used.
510 bool opt::DoSCCP(Method *M) {