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