1 //===- DCE.cpp - Code to perform dead code elimination --------------------===// 2 // 3 // This file implements dead code elimination and basic block merging. 4 // 5 // Specifically, this: 6 // * removes definitions with no uses (including unused constants) 7 // * removes basic blocks with no predecessors 8 // * merges a basic block into its predecessor if there is only one and the 9 // predecessor only has one successor. 10 // * Eliminates PHI nodes for basic blocks with a single predecessor 11 // * Eliminates a basic block that only contains an unconditional branch 12 // 13 // TODO: This should REALLY be recursive instead of iterative. Right now, we 14 // scan linearly through values, removing unused ones as we go. The problem is 15 // that this may cause other earlier values to become unused. To make sure that 16 // we get them all, we iterate until things stop changing. Instead, when 17 // removing a value, recheck all of its operands to see if they are now unused. 18 // Piece of cake, and more efficient as well. 19 // 20 // Note, this is not trivial, because we have to worry about invalidating 21 // iterators. :( 22 // 23 //===----------------------------------------------------------------------===// 24 25 #include "llvm/Module.h" 26 #include "llvm/Method.h" 27 #include "llvm/BasicBlock.h" 28 #include "llvm/iTerminators.h" 29 #include "llvm/iOther.h" 30 #include "llvm/Opt/AllOpts.h" 31 #include "llvm/Assembly/Writer.h" 32 #include "llvm/CFG.h" 33 34 using namespace cfg; 35 36 struct ConstPoolDCE { 37 enum { EndOffs = 0 }; 38 static bool isDCEable(const Value *) { return true; } 39 }; 40 41 struct BasicBlockDCE { 42 enum { EndOffs = 1 }; 43 static bool isDCEable(const Instruction *I) { 44 return !I->hasSideEffects(); 45 } 46 }; 47 48 49 template<class ValueSubclass, class ItemParentType, class DCEController> 50 static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals, 51 DCEController DCEControl) { 52 bool Changed = false; 53 typedef ValueHolder<ValueSubclass, ItemParentType> Container; 54 55 int Offset = DCEController::EndOffs; 56 for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { 57 // Look for un"used" definitions... 58 if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { 59 // Bye bye 60 //cerr << "Removing: " << *DI; 61 delete Vals.remove(DI); 62 Changed = true; 63 } else { 64 DI++; 65 } 66 } 67 return Changed; 68 } 69 70 // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only 71 // a single predecessor. This means that the PHI node must only have a single 72 // RHS value and can be eliminated. 73 // 74 // This routine is very simple because we know that PHI nodes must be the first 75 // things in a basic block, if they are present. 76 // 77 static bool RemoveSingularPHIs(BasicBlock *BB) { 78 pred_iterator PI(pred_begin(BB)); 79 if (PI == pred_end(BB) || ++PI != pred_end(BB)) 80 return false; // More than one predecessor... 81 82 Instruction *I = BB->getInstList().front(); 83 if (I->getInstType() != Instruction::PHINode) return false; // No PHI nodes 84 85 //cerr << "Killing PHIs from " << BB; 86 //cerr << "Pred #0 = " << *pred_begin(BB); 87 88 //cerr << "Method == " << BB->getParent(); 89 90 do { 91 PHINode *PN = (PHINode*)I; 92 assert(PN->getOperand(2) == 0 && "PHI node should only have one value!"); 93 Value *V = PN->getOperand(0); 94 95 PN->replaceAllUsesWith(V); // Replace PHI node with its single value. 96 delete BB->getInstList().remove(BB->getInstList().begin()); 97 98 I = BB->getInstList().front(); 99 } while (I->getInstType() == Instruction::PHINode); 100 101 return true; // Yes, we nuked at least one phi node 102 } 103 104 bool DoRemoveUnusedConstants(SymTabValue *S) { 105 bool Changed = false; 106 ConstantPool &CP = S->getConstantPool(); 107 for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) 108 Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); 109 return Changed; 110 } 111 112 static void ReplaceUsesWithConstant(Instruction *I) { 113 // Get the method level constant pool 114 ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); 115 116 ConstPoolVal *CPV = 0; 117 ConstantPool::PlaneType *P; 118 if (!CP.getPlane(I->getType(), P)) { // Does plane exist? 119 // Yes, is it empty? 120 if (!P->empty()) CPV = P->front(); 121 } 122 123 if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. 124 CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant 125 126 // Add the new value to the constant pool... 127 CP.insert(CPV); 128 } 129 130 // Make all users of this instruction reference the constant instead 131 I->replaceAllUsesWith(CPV); 132 } 133 134 // RemovePredecessorFromBlock - This function is called when we are about 135 // to remove a predecessor from a basic block. This function takes care of 136 // removing the predecessor from the PHI nodes in BB so that after the pred 137 // is removed, the number of PHI slots per bb is equal to the number of 138 // predecessors. 139 // 140 static void RemovePredecessorFromBlock(BasicBlock *BB, BasicBlock *Pred) { 141 pred_iterator PI(pred_begin(BB)), EI(pred_end(BB)); 142 unsigned max_idx; 143 144 //cerr << "RPFB: " << Pred << "From Block: " << BB; 145 146 // Loop over the rest of the predecssors until we run out, or until we find 147 // out that there are more than 2 predecessors. 148 for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/; 149 150 // If there are exactly two predecessors, then we want to nuke the PHI nodes 151 // altogether. 152 bool NukePHIs = max_idx == 2; 153 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!"); 154 155 // Okay, now we know that we need to remove predecessor #pred_idx from all 156 // PHI nodes. Iterate over each PHI node fixing them up 157 BasicBlock::InstListType::iterator II(BB->getInstList().begin()); 158 for (; (*II)->getInstType() == Instruction::PHINode; ++II) { 159 PHINode *PN = (PHINode*)*II; 160 PN->removeIncomingValue(BB); 161 162 if (NukePHIs) { // Destroy the PHI altogether?? 163 assert(PN->getOperand(1) == 0 && "PHI node should only have one value!"); 164 Value *V = PN->getOperand(0); 165 166 PN->replaceAllUsesWith(V); // Replace PHI node with its single value. 167 delete BB->getInstList().remove(II); 168 } 169 } 170 } 171 172 // PropogatePredecessors - This gets "Succ" ready to have the predecessors from 173 // "BB". This is a little tricky because "Succ" has PHI nodes, which need to 174 // have extra slots added to them to hold the merge edges from BB's 175 // predecessors. 176 // 177 // Assumption: BB is the single predecessor of Succ. 178 // 179 static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { 180 assert(BB && Succ && *pred_begin(Succ) == BB && "BB is only pred of Succ" && 181 ++pred_begin(Succ) == pred_end(Succ)); 182 183 // If there is more than one predecessor, and there are PHI nodes in 184 // the successor, then we need to add incoming edges for the PHI nodes 185 pred_iterator PI(pred_begin(BB)); 186 for (; PI != pred_end(BB); ++PI) { 187 // TODO: 188 } 189 } 190 191 static bool DoDCEPass(Method *M) { 192 Method::BasicBlocksType &BBs = M->getBasicBlocks(); 193 Method::BasicBlocksType::iterator BBIt, BBEnd = BBs.end(); 194 if (BBs.begin() == BBEnd) return false; // Nothing to do 195 bool Changed = false; 196 197 // Loop through now and remove instructions that have no uses... 198 for (BBIt = BBs.begin(); BBIt != BBEnd; BBIt++) { 199 Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); 200 Changed |= RemoveSingularPHIs(*BBIt); 201 } 202 203 // Loop over all of the basic blocks (except the first one) and remove them 204 // if they are unneeded... 205 // 206 for (BBIt = BBs.begin(), ++BBIt; BBIt != BBs.end(); ++BBIt) { 207 BasicBlock *BB = *BBIt; 208 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 209 210 #if 0 211 // Remove basic blocks that have no predecessors... which are unreachable. 212 if (pred_begin(BB) == pred_end(BB) && 213 !BB->hasConstantPoolReferences() && 0) { 214 cerr << "Removing BB: \n" << BB; 215 216 // Loop through all of our successors and make sure they know that one 217 // of their predecessors is going away. 218 for (succ_iterator SI = succ_begin(BB), EI = succ_end(BB); SI != EI; ++SI) 219 RemovePredecessorFromBlock(*SI, BB); 220 221 while (!BB->getInstList().empty()) { 222 Instruction *I = BB->getInstList().front(); 223 // If this instruction is used, replace uses with an arbitrary 224 // constant value. Because control flow can't get here, we don't care 225 // what we replace the value with. 226 if (!I->use_empty()) ReplaceUsesWithConstant(I); 227 228 // Remove the instruction from the basic block 229 delete BB->getInstList().remove(BB->getInstList().begin()); 230 } 231 delete BBs.remove(BBIt); 232 --BBIt; // remove puts use on the next block, we want the previous one 233 Changed = true; 234 continue; 235 } 236 237 // Check to see if this block has no instructions and only a single 238 // successor. If so, replace block references with successor. 239 succ_iterator SI(succ_begin(BB)); 240 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? 241 Instruction *I = BB->getInstList().front(); 242 if (I->isTerminator()) { // Terminator is the only instruction! 243 244 if (Succ->getInstList().front()->getInstType() == Instruction::PHINode){ 245 // Add entries to the PHI nodes so that the PHI nodes have the right 246 // number of entries... 247 PropogatePredecessorsForPHIs(BB, Succ); 248 } 249 250 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor 251 BB->replaceAllUsesWith(Succ); 252 cerr << "Killing Trivial BB: \n" << BB; 253 254 BB = BBs.remove(BBIt); 255 --BBIt; // remove puts use on the next block, we want the previous one 256 257 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can 258 Succ->setName(BB->getName()); 259 delete BB; // Delete basic block 260 261 cerr << "Method after removal: \n" << M; 262 Changed = true; 263 continue; 264 } 265 } 266 #endif 267 268 // Merge basic blocks into their predecessor if there is only one pred, 269 // and if there is only one successor of the predecessor. 270 pred_iterator PI(pred_begin(BB)); 271 if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? 272 ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { 273 BasicBlock *Pred = *pred_begin(BB); 274 TerminatorInst *Term = Pred->getTerminator(); 275 assert(Term != 0 && "malformed basic block without terminator!"); 276 277 // Does the predecessor block only have a single successor? 278 succ_iterator SI(succ_begin(Pred)); 279 if (++SI == succ_end(Pred)) { 280 //cerr << "Merging: " << BB << "into: " << Pred; 281 282 // Delete the unconditianal branch from the predecessor... 283 BasicBlock::InstListType::iterator DI = Pred->getInstList().end(); 284 assert(Pred->getTerminator() && 285 "Degenerate basic block encountered!"); // Empty bb??? 286 delete Pred->getInstList().remove(--DI); // Destroy uncond branch 287 288 // Move all definitions in the succecessor to the predecessor... 289 while (!BB->getInstList().empty()) { 290 DI = BB->getInstList().begin(); 291 Instruction *Def = BB->getInstList().remove(DI); // Remove from front 292 Pred->getInstList().push_back(Def); // Add to end... 293 } 294 295 // Remove basic block from the method... and advance iterator to the 296 // next valid block... 297 BB = BBs.remove(BBIt); 298 --BBIt; // remove puts us on the NEXT bb. We want the prev BB 299 Changed = true; 300 301 // Make all PHI nodes that refered to BB now refer to Pred as their 302 // source... 303 BB->replaceAllUsesWith(Pred); 304 305 // Inherit predecessors name if it exists... 306 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); 307 308 // You ARE the weakest link... goodbye 309 delete BB; 310 311 //WriteToVCG(M, "MergedInto"); 312 } 313 } 314 } 315 316 // Remove unused constants 317 Changed |= DoRemoveUnusedConstants(M); 318 return Changed; 319 } 320 321 322 // It is possible that we may require multiple passes over the code to fully 323 // eliminate dead code. Iterate until we are done. 324 // 325 bool DoDeadCodeElimination(Method *M) { 326 bool Changed = false; 327 while (DoDCEPass(M)) Changed = true; 328 return Changed; 329 } 330 331 bool DoDeadCodeElimination(Module *C) { 332 bool Val = ApplyOptToAllMethods(C, DoDeadCodeElimination); 333 while (DoRemoveUnusedConstants(C)) Val = true; 334 return Val; 335 } 336