1 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===// 2 // 3 // This file implements "aggressive" 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.h" 10 #include "llvm/Transforms/Utils/Local.h" 11 #include "llvm/Type.h" 12 #include "llvm/Analysis/Dominators.h" 13 #include "llvm/Analysis/Writer.h" 14 #include "llvm/iTerminators.h" 15 #include "llvm/iPHINode.h" 16 #include "llvm/Constant.h" 17 #include "llvm/Support/CFG.h" 18 #include "Support/STLExtras.h" 19 #include "Support/DepthFirstIterator.h" 20 #include "Support/StatisticReporter.h" 21 #include <algorithm> 22 #include <iostream> 23 using std::cerr; 24 using std::vector; 25 26 static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed"); 27 static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed"); 28 29 namespace { 30 31 //===----------------------------------------------------------------------===// 32 // ADCE Class 33 // 34 // This class does all of the work of Aggressive Dead Code Elimination. 35 // It's public interface consists of a constructor and a doADCE() method. 36 // 37 class ADCE : public FunctionPass { 38 Function *Func; // The function that we are working on 39 std::vector<Instruction*> WorkList; // Instructions that just became live 40 std::set<Instruction*> LiveSet; // The set of live instructions 41 42 //===--------------------------------------------------------------------===// 43 // The public interface for this class 44 // 45 public: 46 // Execute the Aggressive Dead Code Elimination Algorithm 47 // 48 virtual bool runOnFunction(Function &F) { 49 Func = &F; 50 bool Changed = doADCE(); 51 assert(WorkList.empty()); 52 LiveSet.clear(); 53 return Changed; 54 } 55 // getAnalysisUsage - We require post dominance frontiers (aka Control 56 // Dependence Graph) 57 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 58 AU.addRequired(PostDominatorTree::ID); 59 AU.addRequired(PostDominanceFrontier::ID); 60 } 61 62 63 //===--------------------------------------------------------------------===// 64 // The implementation of this class 65 // 66 private: 67 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning 68 // true if the function was modified. 69 // 70 bool doADCE(); 71 72 void markBlockAlive(BasicBlock *BB); 73 74 inline void markInstructionLive(Instruction *I) { 75 if (LiveSet.count(I)) return; 76 DEBUG(cerr << "Insn Live: " << I); 77 LiveSet.insert(I); 78 WorkList.push_back(I); 79 } 80 81 inline void markTerminatorLive(const BasicBlock *BB) { 82 DEBUG(cerr << "Terminat Live: " << BB->getTerminator()); 83 markInstructionLive((Instruction*)BB->getTerminator()); 84 } 85 }; 86 87 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination"); 88 } // End of anonymous namespace 89 90 Pass *createAggressiveDCEPass() { return new ADCE(); } 91 92 void ADCE::markBlockAlive(BasicBlock *BB) { 93 // Mark the basic block as being newly ALIVE... and mark all branches that 94 // this block is control dependant on as being alive also... 95 // 96 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>(); 97 98 PostDominanceFrontier::const_iterator It = CDG.find(BB); 99 if (It != CDG.end()) { 100 // Get the blocks that this node is control dependant on... 101 const PostDominanceFrontier::DomSetType &CDB = It->second; 102 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live 103 bind_obj(this, &ADCE::markTerminatorLive)); 104 } 105 106 // If this basic block is live, then the terminator must be as well! 107 markTerminatorLive(BB); 108 } 109 110 111 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning 112 // true if the function was modified. 113 // 114 bool ADCE::doADCE() { 115 bool MadeChanges = false; 116 117 // Iterate over all of the instructions in the function, eliminating trivially 118 // dead instructions, and marking instructions live that are known to be 119 // needed. Perform the walk in depth first order so that we avoid marking any 120 // instructions live in basic blocks that are unreachable. These blocks will 121 // be eliminated later, along with the instructions inside. 122 // 123 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func); 124 BBI != BBE; ++BBI) { 125 BasicBlock *BB = *BBI; 126 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) { 127 if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) { 128 markInstructionLive(II); 129 ++II; // Increment the inst iterator if the inst wasn't deleted 130 } else if (isInstructionTriviallyDead(II)) { 131 // Remove the instruction from it's basic block... 132 II = BB->getInstList().erase(II); 133 ++NumInstRemoved; 134 MadeChanges = true; 135 } else { 136 ++II; // Increment the inst iterator if the inst wasn't deleted 137 } 138 } 139 } 140 141 DEBUG(cerr << "Processing work list\n"); 142 143 // AliveBlocks - Set of basic blocks that we know have instructions that are 144 // alive in them... 145 // 146 std::set<BasicBlock*> AliveBlocks; 147 148 // Process the work list of instructions that just became live... if they 149 // became live, then that means that all of their operands are neccesary as 150 // well... make them live as well. 151 // 152 while (!WorkList.empty()) { 153 Instruction *I = WorkList.back(); // Get an instruction that became live... 154 WorkList.pop_back(); 155 156 BasicBlock *BB = I->getParent(); 157 if (!AliveBlocks.count(BB)) { // Basic block not alive yet... 158 AliveBlocks.insert(BB); // Block is now ALIVE! 159 markBlockAlive(BB); // Make it so now! 160 } 161 162 // PHI nodes are a special case, because the incoming values are actually 163 // defined in the predecessor nodes of this block, meaning that the PHI 164 // makes the predecessors alive. 165 // 166 if (PHINode *PN = dyn_cast<PHINode>(I)) 167 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) 168 if (!AliveBlocks.count(*PI)) { 169 AliveBlocks.insert(BB); // Block is now ALIVE! 170 markBlockAlive(*PI); 171 } 172 173 // Loop over all of the operands of the live instruction, making sure that 174 // they are known to be alive as well... 175 // 176 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) 177 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op))) 178 markInstructionLive(Operand); 179 } 180 181 if (DebugFlag) { 182 cerr << "Current Function: X = Live\n"; 183 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) 184 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){ 185 if (LiveSet.count(BI)) cerr << "X "; 186 cerr << *BI; 187 } 188 } 189 190 // Find the first postdominator of the entry node that is alive. Make it the 191 // new entry node... 192 // 193 PostDominatorTree &DT = getAnalysis<PostDominatorTree>(); 194 195 // If there are some blocks dead... 196 if (AliveBlocks.size() != Func->size()) { 197 // Insert a new entry node to eliminate the entry node as a special case. 198 BasicBlock *NewEntry = new BasicBlock(); 199 NewEntry->getInstList().push_back(new BranchInst(&Func->front())); 200 Func->getBasicBlockList().push_front(NewEntry); 201 AliveBlocks.insert(NewEntry); // This block is always alive! 202 203 // Loop over all of the alive blocks in the function. If any successor 204 // blocks are not alive, we adjust the outgoing branches to branch to the 205 // first live postdominator of the live block, adjusting any PHI nodes in 206 // the block to reflect this. 207 // 208 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) 209 if (AliveBlocks.count(I)) { 210 BasicBlock *BB = I; 211 TerminatorInst *TI = BB->getTerminator(); 212 213 // Loop over all of the successors, looking for ones that are not alive 214 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 215 if (!AliveBlocks.count(TI->getSuccessor(i))) { 216 // Scan up the postdominator tree, looking for the first 217 // postdominator that is alive, and the last postdominator that is 218 // dead... 219 // 220 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)]; 221 PostDominatorTree::Node *NextNode = LastNode->getIDom(); 222 while (!AliveBlocks.count(NextNode->getNode())) { 223 LastNode = NextNode; 224 NextNode = NextNode->getIDom(); 225 } 226 227 // Get the basic blocks that we need... 228 BasicBlock *LastDead = LastNode->getNode(); 229 BasicBlock *NextAlive = NextNode->getNode(); 230 231 // Make the conditional branch now go to the next alive block... 232 TI->getSuccessor(i)->removePredecessor(BB); 233 TI->setSuccessor(i, NextAlive); 234 235 // If there are PHI nodes in NextAlive, we need to add entries to 236 // the PHI nodes for the new incoming edge. The incoming values 237 // should be identical to the incoming values for LastDead. 238 // 239 for (BasicBlock::iterator II = NextAlive->begin(); 240 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) { 241 // Get the incoming value for LastDead... 242 int OldIdx = PN->getBasicBlockIndex(LastDead); 243 assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!"); 244 Value *InVal = PN->getIncomingValue(OldIdx); 245 246 // Add an incoming value for BB now... 247 PN->addIncoming(InVal, BB); 248 } 249 } 250 251 // Now loop over all of the instructions in the basic block, telling 252 // dead instructions to drop their references. This is so that the next 253 // sweep over the program can safely delete dead instructions without 254 // other dead instructions still refering to them. 255 // 256 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I) 257 if (!LiveSet.count(I)) // Is this instruction alive? 258 I->dropAllReferences(); // Nope, drop references... 259 } 260 } 261 262 // Loop over all of the basic blocks in the function, dropping references of 263 // the dead basic blocks 264 // 265 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) { 266 if (!AliveBlocks.count(BB)) { 267 // Remove all outgoing edges from this basic block and convert the 268 // terminator into a return instruction. 269 vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB)); 270 271 if (!Succs.empty()) { 272 // Loop over all of the successors, removing this block from PHI node 273 // entries that might be in the block... 274 while (!Succs.empty()) { 275 Succs.back()->removePredecessor(BB); 276 Succs.pop_back(); 277 } 278 279 // Delete the old terminator instruction... 280 BB->getInstList().pop_back(); 281 const Type *RetTy = Func->getReturnType(); 282 Instruction *New = new ReturnInst(RetTy != Type::VoidTy ? 283 Constant::getNullValue(RetTy) : 0); 284 BB->getInstList().push_back(New); 285 } 286 287 BB->dropAllReferences(); 288 ++NumBlockRemoved; 289 MadeChanges = true; 290 } 291 } 292 293 // Now loop through all of the blocks and delete the dead ones. We can safely 294 // do this now because we know that there are no references to dead blocks 295 // (because they have dropped all of their references... we also remove dead 296 // instructions from alive blocks. 297 // 298 for (Function::iterator BI = Func->begin(); BI != Func->end(); ) 299 if (!AliveBlocks.count(BI)) 300 BI = Func->getBasicBlockList().erase(BI); 301 else { 302 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); ) 303 if (!LiveSet.count(II)) { // Is this instruction alive? 304 // Nope... remove the instruction from it's basic block... 305 II = BI->getInstList().erase(II); 306 ++NumInstRemoved; 307 MadeChanges = true; 308 } else { 309 ++II; 310 } 311 312 ++BI; // Increment iterator... 313 } 314 315 return MadeChanges; 316 } 317