1 //===- ADCE.cpp - Code to perform agressive dead code elimination ---------===// 2 // 3 // This file implements "agressive" dead code elimination. ADCE is DCe where 4 // values are assumed to be dead until proven otherwise. This is similar to 5 // SCCP, except applied to the liveness of values. 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Transforms/Scalar/DCE.h" 10 #include "llvm/Type.h" 11 #include "llvm/Analysis/Dominators.h" 12 #include "llvm/Analysis/Writer.h" 13 #include "llvm/iTerminators.h" 14 #include "llvm/iPHINode.h" 15 #include "llvm/Support/CFG.h" 16 #include "Support/STLExtras.h" 17 #include "Support/DepthFirstIterator.h" 18 #include <algorithm> 19 #include <iostream> 20 using std::cerr; 21 22 #define DEBUG_ADCE 1 23 24 //===----------------------------------------------------------------------===// 25 // ADCE Class 26 // 27 // This class does all of the work of Agressive Dead Code Elimination. 28 // It's public interface consists of a constructor and a doADCE() method. 29 // 30 class ADCE { 31 Function *M; // The function that we are working on 32 std::vector<Instruction*> WorkList; // Instructions that just became live 33 std::set<Instruction*> LiveSet; // The set of live instructions 34 bool MadeChanges; 35 36 //===--------------------------------------------------------------------===// 37 // The public interface for this class 38 // 39 public: 40 // ADCE Ctor - Save the function to operate on... 41 inline ADCE(Function *f) : M(f), MadeChanges(false) {} 42 43 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning 44 // true if the function was modified. 45 bool doADCE(DominanceFrontier &CDG); 46 47 //===--------------------------------------------------------------------===// 48 // The implementation of this class 49 // 50 private: 51 inline void markInstructionLive(Instruction *I) { 52 if (LiveSet.count(I)) return; 53 #ifdef DEBUG_ADCE 54 cerr << "Insn Live: " << I; 55 #endif 56 LiveSet.insert(I); 57 WorkList.push_back(I); 58 } 59 60 inline void markTerminatorLive(const BasicBlock *BB) { 61 #ifdef DEBUG_ADCE 62 cerr << "Terminat Live: " << BB->getTerminator(); 63 #endif 64 markInstructionLive((Instruction*)BB->getTerminator()); 65 } 66 67 // fixupCFG - Walk the CFG in depth first order, eliminating references to 68 // dead blocks. 69 // 70 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks, 71 const std::set<BasicBlock*> &AliveBlocks); 72 }; 73 74 75 76 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning 77 // true if the function was modified. 78 // 79 bool ADCE::doADCE(DominanceFrontier &CDG) { 80 #ifdef DEBUG_ADCE 81 cerr << "Function: " << M; 82 #endif 83 84 // Iterate over all of the instructions in the function, eliminating trivially 85 // dead instructions, and marking instructions live that are known to be 86 // needed. Perform the walk in depth first order so that we avoid marking any 87 // instructions live in basic blocks that are unreachable. These blocks will 88 // be eliminated later, along with the instructions inside. 89 // 90 for (df_iterator<Function*> BBI = df_begin(M), 91 BBE = df_end(M); 92 BBI != BBE; ++BBI) { 93 BasicBlock *BB = *BBI; 94 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) { 95 Instruction *I = *II; 96 97 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) { 98 markInstructionLive(I); 99 } else { 100 // Check to see if anything is trivially dead 101 if (I->use_size() == 0 && I->getType() != Type::VoidTy) { 102 // Remove the instruction from it's basic block... 103 delete BB->getInstList().remove(II); 104 MadeChanges = true; 105 continue; // Don't increment the iterator past the current slot 106 } 107 } 108 109 ++II; // Increment the inst iterator if the inst wasn't deleted 110 } 111 } 112 113 #ifdef DEBUG_ADCE 114 cerr << "Processing work list\n"; 115 #endif 116 117 // AliveBlocks - Set of basic blocks that we know have instructions that are 118 // alive in them... 119 // 120 std::set<BasicBlock*> AliveBlocks; 121 122 // Process the work list of instructions that just became live... if they 123 // became live, then that means that all of their operands are neccesary as 124 // well... make them live as well. 125 // 126 while (!WorkList.empty()) { 127 Instruction *I = WorkList.back(); // Get an instruction that became live... 128 WorkList.pop_back(); 129 130 BasicBlock *BB = I->getParent(); 131 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet... 132 // Mark the basic block as being newly ALIVE... and mark all branches that 133 // this block is control dependant on as being alive also... 134 // 135 AliveBlocks.insert(BB); // Block is now ALIVE! 136 DominanceFrontier::const_iterator It = CDG.find(BB); 137 if (It != CDG.end()) { 138 // Get the blocks that this node is control dependant on... 139 const DominanceFrontier::DomSetType &CDB = It->second; 140 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live 141 bind_obj(this, &ADCE::markTerminatorLive)); 142 } 143 144 // If this basic block is live, then the terminator must be as well! 145 markTerminatorLive(BB); 146 } 147 148 // Loop over all of the operands of the live instruction, making sure that 149 // they are known to be alive as well... 150 // 151 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) { 152 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op))) 153 markInstructionLive(Operand); 154 } 155 } 156 157 #ifdef DEBUG_ADCE 158 cerr << "Current Function: X = Live\n"; 159 for (Function::iterator I = M->begin(), E = M->end(); I != E; ++I) 160 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); 161 BI != BE; ++BI) { 162 if (LiveSet.count(*BI)) cerr << "X "; 163 cerr << *BI; 164 } 165 #endif 166 167 // After the worklist is processed, recursively walk the CFG in depth first 168 // order, patching up references to dead blocks... 169 // 170 std::set<BasicBlock*> VisitedBlocks; 171 BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks); 172 if (EntryBlock && EntryBlock != M->front()) { 173 if (isa<PHINode>(EntryBlock->front())) { 174 // Cannot make the first block be a block with a PHI node in it! Instead, 175 // strip the first basic block of the function to contain no instructions, 176 // then add a simple branch to the "real" entry node... 177 // 178 BasicBlock *E = M->front(); 179 if (!isa<TerminatorInst>(E->front()) || // Check for an actual change... 180 cast<TerminatorInst>(E->front())->getNumSuccessors() != 1 || 181 cast<TerminatorInst>(E->front())->getSuccessor(0) != EntryBlock) { 182 E->getInstList().delete_all(); // Delete all instructions in block 183 E->getInstList().push_back(new BranchInst(EntryBlock)); 184 MadeChanges = true; 185 } 186 AliveBlocks.insert(E); 187 188 // Next we need to change any PHI nodes in the entry block to refer to the 189 // new predecessor node... 190 191 192 } else { 193 // We need to move the new entry block to be the first bb of the function 194 Function::iterator EBI = find(M->begin(), M->end(), EntryBlock); 195 std::swap(*EBI, *M->begin()); // Exchange old location with start of fn 196 MadeChanges = true; 197 } 198 } 199 200 // Now go through and tell dead blocks to drop all of their references so they 201 // can be safely deleted. 202 // 203 for (Function::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) { 204 BasicBlock *BB = *BI; 205 if (!AliveBlocks.count(BB)) { 206 BB->dropAllReferences(); 207 } 208 } 209 210 // Now loop through all of the blocks and delete them. We can safely do this 211 // now because we know that there are no references to dead blocks (because 212 // they have dropped all of their references... 213 // 214 for (Function::iterator BI = M->begin(); BI != M->end();) { 215 if (!AliveBlocks.count(*BI)) { 216 delete M->getBasicBlocks().remove(BI); 217 MadeChanges = true; 218 continue; // Don't increment iterator 219 } 220 ++BI; // Increment iterator... 221 } 222 223 return MadeChanges; 224 } 225 226 227 // fixupCFG - Walk the CFG in depth first order, eliminating references to 228 // dead blocks: 229 // If the BB is alive (in AliveBlocks): 230 // 1. Eliminate all dead instructions in the BB 231 // 2. Recursively traverse all of the successors of the BB: 232 // - If the returned successor is non-null, update our terminator to 233 // reference the returned BB 234 // 3. Return 0 (no update needed) 235 // 236 // If the BB is dead (not in AliveBlocks): 237 // 1. Add the BB to the dead set 238 // 2. Recursively traverse all of the successors of the block: 239 // - Only one shall return a nonnull value (or else this block should have 240 // been in the alive set). 241 // 3. Return the nonnull child, or 0 if no non-null children. 242 // 243 BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks, 244 const std::set<BasicBlock*> &AliveBlocks) { 245 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update. 246 VisitedBlocks.insert(BB); // We have now visited this node! 247 248 #ifdef DEBUG_ADCE 249 cerr << "Fixing up BB: " << BB; 250 #endif 251 252 if (AliveBlocks.count(BB)) { // Is the block alive? 253 // Yes it's alive: loop through and eliminate all dead instructions in block 254 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) { 255 Instruction *I = *II; 256 if (!LiveSet.count(I)) { // Is this instruction alive? 257 // Nope... remove the instruction from it's basic block... 258 delete BB->getInstList().remove(II); 259 MadeChanges = true; 260 continue; // Don't increment II 261 } 262 ++II; 263 } 264 265 // Recursively traverse successors of this basic block. 266 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) { 267 BasicBlock *Succ = *SI; 268 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks); 269 if (Repl && Repl != Succ) { // We have to replace the successor 270 Succ->replaceAllUsesWith(Repl); 271 MadeChanges = true; 272 } 273 } 274 return BB; 275 } else { // Otherwise the block is dead... 276 BasicBlock *ReturnBB = 0; // Default to nothing live down here 277 278 // Recursively traverse successors of this basic block. 279 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) { 280 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks); 281 if (RetBB) { 282 assert(ReturnBB == 0 && "One one live child allowed!"); 283 ReturnBB = RetBB; 284 } 285 } 286 return ReturnBB; // Return the result of traversal 287 } 288 } 289 290 namespace { 291 struct AgressiveDCE : public FunctionPass { 292 const char *getPassName() const {return "Aggressive Dead Code Elimination";} 293 294 // doADCE - Execute the Agressive Dead Code Elimination Algorithm 295 // 296 virtual bool runOnFunction(Function *F) { 297 return ADCE(F).doADCE( 298 getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID)); 299 } 300 // getAnalysisUsage - We require post dominance frontiers (aka Control 301 // Dependence Graph) 302 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 303 AU.addRequired(DominanceFrontier::PostDomID); 304 } 305 }; 306 } 307 308 Pass *createAgressiveDCEPass() { 309 return new AgressiveDCE(); 310 } 311