1 //===- ADCE.cpp - Code to perform dead code elimination -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Aggressive Dead Code Elimination pass. This pass 11 // optimistically assumes that all instructions are dead until proven otherwise, 12 // allowing it to eliminate dead computations that other DCE passes do not 13 // catch, particularly involving loop computations. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/ADCE.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/DepthFirstIterator.h" 20 #include "llvm/ADT/GraphTraits.h" 21 #include "llvm/ADT/PostOrderIterator.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/GlobalsModRef.h" 26 #include "llvm/Analysis/IteratedDominanceFrontier.h" 27 #include "llvm/Analysis/PostDominators.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/DebugInfoMetadata.h" 31 #include "llvm/IR/DebugLoc.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/Function.h" 35 #include "llvm/IR/InstIterator.h" 36 #include "llvm/IR/InstrTypes.h" 37 #include "llvm/IR/Instruction.h" 38 #include "llvm/IR/Instructions.h" 39 #include "llvm/IR/IntrinsicInst.h" 40 #include "llvm/IR/PassManager.h" 41 #include "llvm/IR/Use.h" 42 #include "llvm/IR/Value.h" 43 #include "llvm/Pass.h" 44 #include "llvm/ProfileData/InstrProf.h" 45 #include "llvm/Support/Casting.h" 46 #include "llvm/Support/CommandLine.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include "llvm/Transforms/Scalar.h" 50 #include <cassert> 51 #include <cstddef> 52 #include <utility> 53 54 using namespace llvm; 55 56 #define DEBUG_TYPE "adce" 57 58 STATISTIC(NumRemoved, "Number of instructions removed"); 59 STATISTIC(NumBranchesRemoved, "Number of branch instructions removed"); 60 61 // This is a temporary option until we change the interface to this pass based 62 // on optimization level. 63 static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow", 64 cl::init(true), cl::Hidden); 65 66 // This option enables removing of may-be-infinite loops which have no other 67 // effect. 68 static cl::opt<bool> RemoveLoops("adce-remove-loops", cl::init(false), 69 cl::Hidden); 70 71 namespace { 72 73 /// Information about Instructions 74 struct InstInfoType { 75 /// True if the associated instruction is live. 76 bool Live = false; 77 78 /// Quick access to information for block containing associated Instruction. 79 struct BlockInfoType *Block = nullptr; 80 }; 81 82 /// Information about basic blocks relevant to dead code elimination. 83 struct BlockInfoType { 84 /// True when this block contains a live instructions. 85 bool Live = false; 86 87 /// True when this block ends in an unconditional branch. 88 bool UnconditionalBranch = false; 89 90 /// True when this block is known to have live PHI nodes. 91 bool HasLivePhiNodes = false; 92 93 /// Control dependence sources need to be live for this block. 94 bool CFLive = false; 95 96 /// Quick access to the LiveInfo for the terminator, 97 /// holds the value &InstInfo[Terminator] 98 InstInfoType *TerminatorLiveInfo = nullptr; 99 100 /// Corresponding BasicBlock. 101 BasicBlock *BB = nullptr; 102 103 /// Cache of BB->getTerminator(). 104 TerminatorInst *Terminator = nullptr; 105 106 /// Post-order numbering of reverse control flow graph. 107 unsigned PostOrder; 108 109 bool terminatorIsLive() const { return TerminatorLiveInfo->Live; } 110 }; 111 112 class AggressiveDeadCodeElimination { 113 Function &F; 114 115 // ADCE does not use DominatorTree per se, but it updates it to preserve the 116 // analysis. 117 DominatorTree &DT; 118 PostDominatorTree &PDT; 119 120 /// Mapping of blocks to associated information, an element in BlockInfoVec. 121 DenseMap<BasicBlock *, BlockInfoType> BlockInfo; 122 bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; } 123 124 /// Mapping of instructions to associated information. 125 DenseMap<Instruction *, InstInfoType> InstInfo; 126 bool isLive(Instruction *I) { return InstInfo[I].Live; } 127 128 /// Instructions known to be live where we need to mark 129 /// reaching definitions as live. 130 SmallVector<Instruction *, 128> Worklist; 131 132 /// Debug info scopes around a live instruction. 133 SmallPtrSet<const Metadata *, 32> AliveScopes; 134 135 /// Set of blocks with not known to have live terminators. 136 SmallPtrSet<BasicBlock *, 16> BlocksWithDeadTerminators; 137 138 /// The set of blocks which we have determined whose control 139 /// dependence sources must be live and which have not had 140 /// those dependences analyzed. 141 SmallPtrSet<BasicBlock *, 16> NewLiveBlocks; 142 143 /// Set up auxiliary data structures for Instructions and BasicBlocks and 144 /// initialize the Worklist to the set of must-be-live Instruscions. 145 void initialize(); 146 147 /// Return true for operations which are always treated as live. 148 bool isAlwaysLive(Instruction &I); 149 150 /// Return true for instrumentation instructions for value profiling. 151 bool isInstrumentsConstant(Instruction &I); 152 153 /// Propagate liveness to reaching definitions. 154 void markLiveInstructions(); 155 156 /// Mark an instruction as live. 157 void markLive(Instruction *I); 158 159 /// Mark a block as live. 160 void markLive(BlockInfoType &BB); 161 void markLive(BasicBlock *BB) { markLive(BlockInfo[BB]); } 162 163 /// Mark terminators of control predecessors of a PHI node live. 164 void markPhiLive(PHINode *PN); 165 166 /// Record the Debug Scopes which surround live debug information. 167 void collectLiveScopes(const DILocalScope &LS); 168 void collectLiveScopes(const DILocation &DL); 169 170 /// Analyze dead branches to find those whose branches are the sources 171 /// of control dependences impacting a live block. Those branches are 172 /// marked live. 173 void markLiveBranchesFromControlDependences(); 174 175 /// Remove instructions not marked live, return if any any instruction 176 /// was removed. 177 bool removeDeadInstructions(); 178 179 /// Identify connected sections of the control flow graph which have 180 /// dead terminators and rewrite the control flow graph to remove them. 181 void updateDeadRegions(); 182 183 /// Set the BlockInfo::PostOrder field based on a post-order 184 /// numbering of the reverse control flow graph. 185 void computeReversePostOrder(); 186 187 /// Make the terminator of this block an unconditional branch to \p Target. 188 void makeUnconditional(BasicBlock *BB, BasicBlock *Target); 189 190 public: 191 AggressiveDeadCodeElimination(Function &F, DominatorTree &DT, 192 PostDominatorTree &PDT) 193 : F(F), DT(DT), PDT(PDT) {} 194 195 bool performDeadCodeElimination(); 196 }; 197 198 } // end anonymous namespace 199 200 bool AggressiveDeadCodeElimination::performDeadCodeElimination() { 201 initialize(); 202 markLiveInstructions(); 203 return removeDeadInstructions(); 204 } 205 206 static bool isUnconditionalBranch(TerminatorInst *Term) { 207 auto *BR = dyn_cast<BranchInst>(Term); 208 return BR && BR->isUnconditional(); 209 } 210 211 void AggressiveDeadCodeElimination::initialize() { 212 auto NumBlocks = F.size(); 213 214 // We will have an entry in the map for each block so we grow the 215 // structure to twice that size to keep the load factor low in the hash table. 216 BlockInfo.reserve(NumBlocks); 217 size_t NumInsts = 0; 218 219 // Iterate over blocks and initialize BlockInfoVec entries, count 220 // instructions to size the InstInfo hash table. 221 for (auto &BB : F) { 222 NumInsts += BB.size(); 223 auto &Info = BlockInfo[&BB]; 224 Info.BB = &BB; 225 Info.Terminator = BB.getTerminator(); 226 Info.UnconditionalBranch = isUnconditionalBranch(Info.Terminator); 227 } 228 229 // Initialize instruction map and set pointers to block info. 230 InstInfo.reserve(NumInsts); 231 for (auto &BBInfo : BlockInfo) 232 for (Instruction &I : *BBInfo.second.BB) 233 InstInfo[&I].Block = &BBInfo.second; 234 235 // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not 236 // add any more elements to either after this point. 237 for (auto &BBInfo : BlockInfo) 238 BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator]; 239 240 // Collect the set of "root" instructions that are known live. 241 for (Instruction &I : instructions(F)) 242 if (isAlwaysLive(I)) 243 markLive(&I); 244 245 if (!RemoveControlFlowFlag) 246 return; 247 248 if (!RemoveLoops) { 249 // This stores state for the depth-first iterator. In addition 250 // to recording which nodes have been visited we also record whether 251 // a node is currently on the "stack" of active ancestors of the current 252 // node. 253 using StatusMap = DenseMap<BasicBlock *, bool>; 254 255 class DFState : public StatusMap { 256 public: 257 std::pair<StatusMap::iterator, bool> insert(BasicBlock *BB) { 258 return StatusMap::insert(std::make_pair(BB, true)); 259 } 260 261 // Invoked after we have visited all children of a node. 262 void completed(BasicBlock *BB) { (*this)[BB] = false; } 263 264 // Return true if \p BB is currently on the active stack 265 // of ancestors. 266 bool onStack(BasicBlock *BB) { 267 auto Iter = find(BB); 268 return Iter != end() && Iter->second; 269 } 270 } State; 271 272 State.reserve(F.size()); 273 // Iterate over blocks in depth-first pre-order and 274 // treat all edges to a block already seen as loop back edges 275 // and mark the branch live it if there is a back edge. 276 for (auto *BB: depth_first_ext(&F.getEntryBlock(), State)) { 277 TerminatorInst *Term = BB->getTerminator(); 278 if (isLive(Term)) 279 continue; 280 281 for (auto *Succ : successors(BB)) 282 if (State.onStack(Succ)) { 283 // back edge.... 284 markLive(Term); 285 break; 286 } 287 } 288 } 289 290 // Mark blocks live if there is no path from the block to a 291 // return of the function. 292 // We do this by seeing which of the postdomtree root children exit the 293 // program, and for all others, mark the subtree live. 294 for (auto &PDTChild : children<DomTreeNode *>(PDT.getRootNode())) { 295 auto *BB = PDTChild->getBlock(); 296 auto &Info = BlockInfo[BB]; 297 // Real function return 298 if (isa<ReturnInst>(Info.Terminator)) { 299 DEBUG(dbgs() << "post-dom root child is a return: " << BB->getName() 300 << '\n';); 301 continue; 302 } 303 304 // This child is something else, like an infinite loop. 305 for (auto DFNode : depth_first(PDTChild)) 306 markLive(BlockInfo[DFNode->getBlock()].Terminator); 307 } 308 309 // Treat the entry block as always live 310 auto *BB = &F.getEntryBlock(); 311 auto &EntryInfo = BlockInfo[BB]; 312 EntryInfo.Live = true; 313 if (EntryInfo.UnconditionalBranch) 314 markLive(EntryInfo.Terminator); 315 316 // Build initial collection of blocks with dead terminators 317 for (auto &BBInfo : BlockInfo) 318 if (!BBInfo.second.terminatorIsLive()) 319 BlocksWithDeadTerminators.insert(BBInfo.second.BB); 320 } 321 322 bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) { 323 // TODO -- use llvm::isInstructionTriviallyDead 324 if (I.isEHPad() || I.mayHaveSideEffects()) { 325 // Skip any value profile instrumentation calls if they are 326 // instrumenting constants. 327 if (isInstrumentsConstant(I)) 328 return false; 329 return true; 330 } 331 if (!isa<TerminatorInst>(I)) 332 return false; 333 if (RemoveControlFlowFlag && (isa<BranchInst>(I) || isa<SwitchInst>(I))) 334 return false; 335 return true; 336 } 337 338 // Check if this instruction is a runtime call for value profiling and 339 // if it's instrumenting a constant. 340 bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) { 341 // TODO -- move this test into llvm::isInstructionTriviallyDead 342 if (CallInst *CI = dyn_cast<CallInst>(&I)) 343 if (Function *Callee = CI->getCalledFunction()) 344 if (Callee->getName().equals(getInstrProfValueProfFuncName())) 345 if (isa<Constant>(CI->getArgOperand(0))) 346 return true; 347 return false; 348 } 349 350 void AggressiveDeadCodeElimination::markLiveInstructions() { 351 // Propagate liveness backwards to operands. 352 do { 353 // Worklist holds newly discovered live instructions 354 // where we need to mark the inputs as live. 355 while (!Worklist.empty()) { 356 Instruction *LiveInst = Worklist.pop_back_val(); 357 DEBUG(dbgs() << "work live: "; LiveInst->dump();); 358 359 for (Use &OI : LiveInst->operands()) 360 if (Instruction *Inst = dyn_cast<Instruction>(OI)) 361 markLive(Inst); 362 363 if (auto *PN = dyn_cast<PHINode>(LiveInst)) 364 markPhiLive(PN); 365 } 366 367 // After data flow liveness has been identified, examine which branch 368 // decisions are required to determine live instructions are executed. 369 markLiveBranchesFromControlDependences(); 370 371 } while (!Worklist.empty()); 372 } 373 374 void AggressiveDeadCodeElimination::markLive(Instruction *I) { 375 auto &Info = InstInfo[I]; 376 if (Info.Live) 377 return; 378 379 DEBUG(dbgs() << "mark live: "; I->dump()); 380 Info.Live = true; 381 Worklist.push_back(I); 382 383 // Collect the live debug info scopes attached to this instruction. 384 if (const DILocation *DL = I->getDebugLoc()) 385 collectLiveScopes(*DL); 386 387 // Mark the containing block live 388 auto &BBInfo = *Info.Block; 389 if (BBInfo.Terminator == I) { 390 BlocksWithDeadTerminators.erase(BBInfo.BB); 391 // For live terminators, mark destination blocks 392 // live to preserve this control flow edges. 393 if (!BBInfo.UnconditionalBranch) 394 for (auto *BB : successors(I->getParent())) 395 markLive(BB); 396 } 397 markLive(BBInfo); 398 } 399 400 void AggressiveDeadCodeElimination::markLive(BlockInfoType &BBInfo) { 401 if (BBInfo.Live) 402 return; 403 DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n'); 404 BBInfo.Live = true; 405 if (!BBInfo.CFLive) { 406 BBInfo.CFLive = true; 407 NewLiveBlocks.insert(BBInfo.BB); 408 } 409 410 // Mark unconditional branches at the end of live 411 // blocks as live since there is no work to do for them later 412 if (BBInfo.UnconditionalBranch) 413 markLive(BBInfo.Terminator); 414 } 415 416 void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) { 417 if (!AliveScopes.insert(&LS).second) 418 return; 419 420 if (isa<DISubprogram>(LS)) 421 return; 422 423 // Tail-recurse through the scope chain. 424 collectLiveScopes(cast<DILocalScope>(*LS.getScope())); 425 } 426 427 void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) { 428 // Even though DILocations are not scopes, shove them into AliveScopes so we 429 // don't revisit them. 430 if (!AliveScopes.insert(&DL).second) 431 return; 432 433 // Collect live scopes from the scope chain. 434 collectLiveScopes(*DL.getScope()); 435 436 // Tail-recurse through the inlined-at chain. 437 if (const DILocation *IA = DL.getInlinedAt()) 438 collectLiveScopes(*IA); 439 } 440 441 void AggressiveDeadCodeElimination::markPhiLive(PHINode *PN) { 442 auto &Info = BlockInfo[PN->getParent()]; 443 // Only need to check this once per block. 444 if (Info.HasLivePhiNodes) 445 return; 446 Info.HasLivePhiNodes = true; 447 448 // If a predecessor block is not live, mark it as control-flow live 449 // which will trigger marking live branches upon which 450 // that block is control dependent. 451 for (auto *PredBB : predecessors(Info.BB)) { 452 auto &Info = BlockInfo[PredBB]; 453 if (!Info.CFLive) { 454 Info.CFLive = true; 455 NewLiveBlocks.insert(PredBB); 456 } 457 } 458 } 459 460 void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() { 461 if (BlocksWithDeadTerminators.empty()) 462 return; 463 464 DEBUG({ 465 dbgs() << "new live blocks:\n"; 466 for (auto *BB : NewLiveBlocks) 467 dbgs() << "\t" << BB->getName() << '\n'; 468 dbgs() << "dead terminator blocks:\n"; 469 for (auto *BB : BlocksWithDeadTerminators) 470 dbgs() << "\t" << BB->getName() << '\n'; 471 }); 472 473 // The dominance frontier of a live block X in the reverse 474 // control graph is the set of blocks upon which X is control 475 // dependent. The following sequence computes the set of blocks 476 // which currently have dead terminators that are control 477 // dependence sources of a block which is in NewLiveBlocks. 478 479 SmallVector<BasicBlock *, 32> IDFBlocks; 480 ReverseIDFCalculator IDFs(PDT); 481 IDFs.setDefiningBlocks(NewLiveBlocks); 482 IDFs.setLiveInBlocks(BlocksWithDeadTerminators); 483 IDFs.calculate(IDFBlocks); 484 NewLiveBlocks.clear(); 485 486 // Dead terminators which control live blocks are now marked live. 487 for (auto *BB : IDFBlocks) { 488 DEBUG(dbgs() << "live control in: " << BB->getName() << '\n'); 489 markLive(BB->getTerminator()); 490 } 491 } 492 493 //===----------------------------------------------------------------------===// 494 // 495 // Routines to update the CFG and SSA information before removing dead code. 496 // 497 //===----------------------------------------------------------------------===// 498 bool AggressiveDeadCodeElimination::removeDeadInstructions() { 499 // Updates control and dataflow around dead blocks 500 updateDeadRegions(); 501 502 DEBUG({ 503 for (Instruction &I : instructions(F)) { 504 // Check if the instruction is alive. 505 if (isLive(&I)) 506 continue; 507 508 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) { 509 // Check if the scope of this variable location is alive. 510 if (AliveScopes.count(DII->getDebugLoc()->getScope())) 511 continue; 512 513 // If intrinsic is pointing at a live SSA value, there may be an 514 // earlier optimization bug: if we know the location of the variable, 515 // why isn't the scope of the location alive? 516 if (Value *V = DII->getVariableLocation()) 517 if (Instruction *II = dyn_cast<Instruction>(V)) 518 if (isLive(II)) 519 dbgs() << "Dropping debug info for " << *DII << "\n"; 520 } 521 } 522 }); 523 524 // The inverse of the live set is the dead set. These are those instructions 525 // that have no side effects and do not influence the control flow or return 526 // value of the function, and may therefore be deleted safely. 527 // NOTE: We reuse the Worklist vector here for memory efficiency. 528 for (Instruction &I : instructions(F)) { 529 // Check if the instruction is alive. 530 if (isLive(&I)) 531 continue; 532 533 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) { 534 // Check if the scope of this variable location is alive. 535 if (AliveScopes.count(DII->getDebugLoc()->getScope())) 536 continue; 537 538 // Fallthrough and drop the intrinsic. 539 } 540 541 // Prepare to delete. 542 Worklist.push_back(&I); 543 I.dropAllReferences(); 544 } 545 546 for (Instruction *&I : Worklist) { 547 ++NumRemoved; 548 I->eraseFromParent(); 549 } 550 551 return !Worklist.empty(); 552 } 553 554 // A dead region is the set of dead blocks with a common live post-dominator. 555 void AggressiveDeadCodeElimination::updateDeadRegions() { 556 DEBUG({ 557 dbgs() << "final dead terminator blocks: " << '\n'; 558 for (auto *BB : BlocksWithDeadTerminators) 559 dbgs() << '\t' << BB->getName() 560 << (BlockInfo[BB].Live ? " LIVE\n" : "\n"); 561 }); 562 563 // Don't compute the post ordering unless we needed it. 564 bool HavePostOrder = false; 565 566 for (auto *BB : BlocksWithDeadTerminators) { 567 auto &Info = BlockInfo[BB]; 568 if (Info.UnconditionalBranch) { 569 InstInfo[Info.Terminator].Live = true; 570 continue; 571 } 572 573 if (!HavePostOrder) { 574 computeReversePostOrder(); 575 HavePostOrder = true; 576 } 577 578 // Add an unconditional branch to the successor closest to the 579 // end of the function which insures a path to the exit for each 580 // live edge. 581 BlockInfoType *PreferredSucc = nullptr; 582 for (auto *Succ : successors(BB)) { 583 auto *Info = &BlockInfo[Succ]; 584 if (!PreferredSucc || PreferredSucc->PostOrder < Info->PostOrder) 585 PreferredSucc = Info; 586 } 587 assert((PreferredSucc && PreferredSucc->PostOrder > 0) && 588 "Failed to find safe successor for dead branch"); 589 590 // Collect removed successors to update the (Post)DominatorTrees. 591 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors; 592 bool First = true; 593 for (auto *Succ : successors(BB)) { 594 if (!First || Succ != PreferredSucc->BB) { 595 Succ->removePredecessor(BB); 596 RemovedSuccessors.insert(Succ); 597 } else 598 First = false; 599 } 600 makeUnconditional(BB, PreferredSucc->BB); 601 602 // Inform the dominators about the deleted CFG edges. 603 SmallVector<DominatorTree::UpdateType, 4> DeletedEdges; 604 for (auto *Succ : RemovedSuccessors) { 605 // It might have happened that the same successor appeared multiple times 606 // and the CFG edge wasn't really removed. 607 if (Succ != PreferredSucc->BB) { 608 DEBUG(dbgs() << "ADCE: (Post)DomTree edge enqueued for deletion" 609 << BB->getName() << " -> " << Succ->getName() << "\n"); 610 DeletedEdges.push_back({DominatorTree::Delete, BB, Succ}); 611 } 612 } 613 614 DT.applyUpdates(DeletedEdges); 615 PDT.applyUpdates(DeletedEdges); 616 617 NumBranchesRemoved += 1; 618 } 619 } 620 621 // reverse top-sort order 622 void AggressiveDeadCodeElimination::computeReversePostOrder() { 623 // This provides a post-order numbering of the reverse control flow graph 624 // Note that it is incomplete in the presence of infinite loops but we don't 625 // need numbers blocks which don't reach the end of the functions since 626 // all branches in those blocks are forced live. 627 628 // For each block without successors, extend the DFS from the block 629 // backward through the graph 630 SmallPtrSet<BasicBlock*, 16> Visited; 631 unsigned PostOrder = 0; 632 for (auto &BB : F) { 633 if (succ_begin(&BB) != succ_end(&BB)) 634 continue; 635 for (BasicBlock *Block : inverse_post_order_ext(&BB,Visited)) 636 BlockInfo[Block].PostOrder = PostOrder++; 637 } 638 } 639 640 void AggressiveDeadCodeElimination::makeUnconditional(BasicBlock *BB, 641 BasicBlock *Target) { 642 TerminatorInst *PredTerm = BB->getTerminator(); 643 // Collect the live debug info scopes attached to this instruction. 644 if (const DILocation *DL = PredTerm->getDebugLoc()) 645 collectLiveScopes(*DL); 646 647 // Just mark live an existing unconditional branch 648 if (isUnconditionalBranch(PredTerm)) { 649 PredTerm->setSuccessor(0, Target); 650 InstInfo[PredTerm].Live = true; 651 return; 652 } 653 DEBUG(dbgs() << "making unconditional " << BB->getName() << '\n'); 654 NumBranchesRemoved += 1; 655 IRBuilder<> Builder(PredTerm); 656 auto *NewTerm = Builder.CreateBr(Target); 657 InstInfo[NewTerm].Live = true; 658 if (const DILocation *DL = PredTerm->getDebugLoc()) 659 NewTerm->setDebugLoc(DL); 660 661 InstInfo.erase(PredTerm); 662 PredTerm->eraseFromParent(); 663 } 664 665 //===----------------------------------------------------------------------===// 666 // 667 // Pass Manager integration code 668 // 669 //===----------------------------------------------------------------------===// 670 PreservedAnalyses ADCEPass::run(Function &F, FunctionAnalysisManager &FAM) { 671 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); 672 auto &PDT = FAM.getResult<PostDominatorTreeAnalysis>(F); 673 if (!AggressiveDeadCodeElimination(F, DT, PDT).performDeadCodeElimination()) 674 return PreservedAnalyses::all(); 675 676 PreservedAnalyses PA; 677 PA.preserveSet<CFGAnalyses>(); 678 PA.preserve<GlobalsAA>(); 679 PA.preserve<DominatorTreeAnalysis>(); 680 PA.preserve<PostDominatorTreeAnalysis>(); 681 return PA; 682 } 683 684 namespace { 685 686 struct ADCELegacyPass : public FunctionPass { 687 static char ID; // Pass identification, replacement for typeid 688 689 ADCELegacyPass() : FunctionPass(ID) { 690 initializeADCELegacyPassPass(*PassRegistry::getPassRegistry()); 691 } 692 693 bool runOnFunction(Function &F) override { 694 if (skipFunction(F)) 695 return false; 696 697 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 698 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 699 return AggressiveDeadCodeElimination(F, DT, PDT) 700 .performDeadCodeElimination(); 701 } 702 703 void getAnalysisUsage(AnalysisUsage &AU) const override { 704 // We require DominatorTree here only to update and thus preserve it. 705 AU.addRequired<DominatorTreeWrapperPass>(); 706 AU.addRequired<PostDominatorTreeWrapperPass>(); 707 if (!RemoveControlFlowFlag) 708 AU.setPreservesCFG(); 709 else { 710 AU.addPreserved<DominatorTreeWrapperPass>(); 711 AU.addPreserved<PostDominatorTreeWrapperPass>(); 712 } 713 AU.addPreserved<GlobalsAAWrapperPass>(); 714 } 715 }; 716 717 } // end anonymous namespace 718 719 char ADCELegacyPass::ID = 0; 720 721 INITIALIZE_PASS_BEGIN(ADCELegacyPass, "adce", 722 "Aggressive Dead Code Elimination", false, false) 723 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 724 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 725 INITIALIZE_PASS_END(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination", 726 false, false) 727 728 FunctionPass *llvm::createAggressiveDCEPass() { return new ADCELegacyPass(); } 729