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