LLVM 23.0.0git
ADCE.cpp
Go to the documentation of this file.
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
17#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/Statistic.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/CFG.h"
33#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/DebugLoc.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/Instruction.h"
43#include "llvm/IR/PassManager.h"
44#include "llvm/IR/Use.h"
45#include "llvm/IR/Value.h"
49#include "llvm/Support/Debug.h"
52#include <cassert>
53#include <cstddef>
54#include <utility>
55
56using namespace llvm;
57
58#define DEBUG_TYPE "adce"
59
60STATISTIC(NumRemoved, "Number of instructions removed");
61STATISTIC(NumBranchesRemoved, "Number of branch instructions removed");
62
63// This is a temporary option until we change the interface to this pass based
64// on optimization level.
65static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow",
66 cl::init(true), cl::Hidden);
67
68// This option enables removing of may-be-infinite loops which have no other
69// effect.
70static cl::opt<bool> RemoveLoops("adce-remove-loops", cl::init(false),
72
73namespace {
74
75/// Information about Instructions
76struct InstInfoType {
77 /// True if the associated instruction is live.
78 bool Live = false;
79
80 /// Quick access to information for block containing associated Instruction.
81 struct BlockInfoType *Block = nullptr;
82};
83
84/// Information about basic blocks relevant to dead code elimination.
85struct BlockInfoType {
86 /// True when this block contains a live instructions.
87 bool Live = false;
88
89 /// True when this block ends in an unconditional branch.
90 bool UnconditionalBranch = false;
91
92 /// True when this block is known to have live PHI nodes.
93 bool HasLivePhiNodes = false;
94
95 /// Control dependence sources need to be live for this block.
96 bool CFLive = false;
97
98 /// Quick access to the LiveInfo for the terminator,
99 /// holds the value &InstInfo[Terminator]
100 InstInfoType *TerminatorLiveInfo = nullptr;
101
102 /// Corresponding BasicBlock.
103 BasicBlock *BB = nullptr;
104
105 /// Cache of BB->getTerminator().
106 Instruction *Terminator = nullptr;
107
108 /// Post-order numbering of reverse control flow graph.
109 unsigned PostOrder;
110
111 bool terminatorIsLive() const { return TerminatorLiveInfo->Live; }
112};
113
114struct ADCEChanged {
115 bool ChangedAnything = false;
116 bool ChangedNonDebugInstr = false;
117 bool ChangedControlFlow = false;
118};
119
120class AggressiveDeadCodeElimination {
121 Function &F;
122
123 // ADCE does not use DominatorTree per se, but it updates it to preserve the
124 // analysis.
125 DominatorTree *DT;
126 PostDominatorTree &PDT;
127
128 /// Mapping of blocks to associated information, an element in BlockInfoVec.
129 /// Use MapVector to get deterministic iteration order.
130 MapVector<BasicBlock *, BlockInfoType> BlockInfo;
131 bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; }
132
133 /// Mapping of instructions to associated information.
134 DenseMap<Instruction *, InstInfoType> InstInfo;
135 bool isLive(Instruction *I) { return InstInfo[I].Live; }
136
137 /// Instructions known to be live where we need to mark
138 /// reaching definitions as live.
140
141 /// Debug info scopes around a live instruction.
142 SmallPtrSet<const Metadata *, 32> AliveScopes;
143
144 /// Set of blocks with not known to have live terminators.
145 SmallSetVector<BasicBlock *, 16> BlocksWithDeadTerminators;
146
147 /// The set of blocks which we have determined whose control
148 /// dependence sources must be live and which have not had
149 /// those dependences analyzed.
150 SmallPtrSet<BasicBlock *, 16> NewLiveBlocks;
151
152 /// Set up auxiliary data structures for Instructions and BasicBlocks and
153 /// initialize the Worklist to the set of must-be-live Instruscions.
154 void initialize();
155
156 /// Return true for operations which are always treated as live.
157 bool isAlwaysLive(Instruction &I);
158
159 /// Return true for instrumentation instructions for value profiling.
160 bool isInstrumentsConstant(Instruction &I);
161
162 /// Propagate liveness to reaching definitions.
163 void markLiveInstructions();
164
165 /// Mark an instruction as live.
166 void markLive(Instruction *I);
167
168 /// Mark a block as live.
169 void markLive(BlockInfoType &BB);
170 void markLive(BasicBlock *BB) { markLive(BlockInfo[BB]); }
171
172 /// Mark terminators of control predecessors of a PHI node live.
173 void markPhiLive(PHINode *PN);
174
175 /// Record the Debug Scopes which surround live debug information.
176 void collectLiveScopes(const DILocalScope &LS);
177 void collectLiveScopes(const DILocation &DL);
178
179 /// Analyze dead branches to find those whose branches are the sources
180 /// of control dependences impacting a live block. Those branches are
181 /// marked live.
182 void markLiveBranchesFromControlDependences();
183
184 /// Remove instructions not marked live, return if any instruction was
185 /// removed.
186 ADCEChanged removeDeadInstructions();
187
188 /// Identify connected sections of the control flow graph which have
189 /// dead terminators and rewrite the control flow graph to remove them.
190 bool updateDeadRegions();
191
192 /// Set the BlockInfo::PostOrder field based on a post-order
193 /// numbering of the reverse control flow graph.
194 void computeReversePostOrder();
195
196 /// Make the terminator of this block an unconditional branch to \p Target.
197 void makeUnconditional(BasicBlock *BB, BasicBlock *Target);
198
199public:
200 AggressiveDeadCodeElimination(Function &F, DominatorTree *DT,
201 PostDominatorTree &PDT)
202 : F(F), DT(DT), PDT(PDT) {}
203
204 ADCEChanged performDeadCodeElimination();
205};
206
207} // end anonymous namespace
208
209ADCEChanged AggressiveDeadCodeElimination::performDeadCodeElimination() {
210 initialize();
211 markLiveInstructions();
212 return removeDeadInstructions();
213}
214
215void AggressiveDeadCodeElimination::initialize() {
216 auto NumBlocks = F.size();
217
218 // We will have an entry in the map for each block so we grow the
219 // structure to twice that size to keep the load factor low in the hash table.
220 BlockInfo.reserve(NumBlocks);
221 size_t NumInsts = 0;
222
223 // Iterate over blocks and initialize BlockInfoVec entries, count
224 // instructions to size the InstInfo hash table.
225 for (auto &BB : F) {
226 NumInsts += BB.size();
227 auto &Info = BlockInfo[&BB];
228 Info.BB = &BB;
229 Info.Terminator = BB.getTerminator();
230 Info.UnconditionalBranch = isa<UncondBrInst>(Info.Terminator);
231 }
232
233 // Initialize instruction map and set pointers to block info.
234 InstInfo.reserve(NumInsts);
235 for (auto &BBInfo : BlockInfo)
236 for (Instruction &I : *BBInfo.second.BB)
237 InstInfo[&I].Block = &BBInfo.second;
238
239 // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not
240 // add any more elements to either after this point.
241 for (auto &BBInfo : BlockInfo)
242 BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator];
243
244 // Collect the set of "root" instructions that are known live.
245 for (Instruction &I : instructions(F))
246 if (isAlwaysLive(I))
247 markLive(&I);
248
250 return;
251
252 if (!RemoveLoops) {
253 // This stores state for the depth-first iterator. In addition
254 // to recording which nodes have been visited we also record whether
255 // a node is currently on the "stack" of active ancestors of the current
256 // node.
257 using StatusMap = DenseMap<BasicBlock *, bool>;
258
259 class DFState : public StatusMap {
260 public:
261 std::pair<StatusMap::iterator, bool> insert(BasicBlock *BB) {
262 return StatusMap::insert(std::make_pair(BB, true));
263 }
264
265 // Invoked after we have visited all children of a node.
266 void completed(BasicBlock *BB) { (*this)[BB] = false; }
267
268 // Return true if \p BB is currently on the active stack
269 // of ancestors.
270 bool onStack(BasicBlock *BB) {
271 auto Iter = find(BB);
272 return Iter != end() && Iter->second;
273 }
274 } State;
275
276 State.reserve(F.size());
277 // Iterate over blocks in depth-first pre-order and
278 // treat all edges to a block already seen as loop back edges
279 // and mark the branch live it if there is a back edge.
280 for (auto *BB: depth_first_ext(&F.getEntryBlock(), State)) {
281 Instruction *Term = BB->getTerminator();
282 if (isLive(Term))
283 continue;
284
285 for (auto *Succ : successors(BB))
286 if (State.onStack(Succ)) {
287 // back edge....
288 markLive(Term);
289 break;
290 }
291 }
292 }
293
294 // Mark blocks live if there is no path from the block to a
295 // return of the function.
296 // We do this by seeing which of the postdomtree root children exit the
297 // program, and for all others, mark the subtree live.
298 for (const auto &PDTChild : children<DomTreeNode *>(PDT.getRootNode())) {
299 auto *BB = PDTChild->getBlock();
300 auto &Info = BlockInfo[BB];
301 // Real function return
302 if (isa<ReturnInst>(Info.Terminator)) {
303 LLVM_DEBUG(dbgs() << "post-dom root child is a return: " << BB->getName()
304 << '\n';);
305 continue;
306 }
307
308 // This child is something else, like an infinite loop.
309 for (auto *DFNode : depth_first(PDTChild))
310 markLive(BlockInfo[DFNode->getBlock()].Terminator);
311 }
312
313 // Treat the entry block as always live
314 auto *BB = &F.getEntryBlock();
315 auto &EntryInfo = BlockInfo[BB];
316 EntryInfo.Live = true;
317 if (EntryInfo.UnconditionalBranch)
318 markLive(EntryInfo.Terminator);
319
320 // Build initial collection of blocks with dead terminators
321 for (auto &BBInfo : BlockInfo)
322 if (!BBInfo.second.terminatorIsLive())
323 BlocksWithDeadTerminators.insert(BBInfo.second.BB);
324}
325
326bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) {
327 // TODO -- use llvm::isInstructionTriviallyDead
328 if (I.isEHPad() || I.mayHaveSideEffects()) {
329 // Skip any value profile instrumentation calls if they are
330 // instrumenting constants.
331 if (isInstrumentsConstant(I))
332 return false;
333 return true;
334 }
335 if (!I.isTerminator())
336 return false;
338 return false;
339 return true;
340}
341
342// Check if this instruction is a runtime call for value profiling and
343// if it's instrumenting a constant.
344bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) {
345 // TODO -- move this test into llvm::isInstructionTriviallyDead
346 if (CallInst *CI = dyn_cast<CallInst>(&I))
347 if (Function *Callee = CI->getCalledFunction())
348 if (Callee->getName() == getInstrProfValueProfFuncName())
349 if (isa<Constant>(CI->getArgOperand(0)))
350 return true;
351 return false;
352}
353
354void AggressiveDeadCodeElimination::markLiveInstructions() {
355 // Propagate liveness backwards to operands.
356 do {
357 // Worklist holds newly discovered live instructions
358 // where we need to mark the inputs as live.
359 while (!Worklist.empty()) {
360 Instruction *LiveInst = Worklist.pop_back_val();
361 LLVM_DEBUG(dbgs() << "work live: "; LiveInst->dump(););
362
363 for (Use &OI : LiveInst->operands())
364 if (Instruction *Inst = dyn_cast<Instruction>(OI))
365 markLive(Inst);
366
367 if (auto *PN = dyn_cast<PHINode>(LiveInst))
368 markPhiLive(PN);
369 }
370
371 // After data flow liveness has been identified, examine which branch
372 // decisions are required to determine live instructions are executed.
373 markLiveBranchesFromControlDependences();
374
375 } while (!Worklist.empty());
376}
377
378void AggressiveDeadCodeElimination::markLive(Instruction *I) {
379 auto &Info = InstInfo[I];
380 if (Info.Live)
381 return;
382
383 LLVM_DEBUG(dbgs() << "mark live: "; I->dump());
384 Info.Live = true;
385 Worklist.push_back(I);
386
387 // Collect the live debug info scopes attached to this instruction.
388 if (const DILocation *DL = I->getDebugLoc())
389 collectLiveScopes(*DL);
390
391 // Mark the containing block live
392 auto &BBInfo = *Info.Block;
393 if (BBInfo.Terminator == I) {
394 BlocksWithDeadTerminators.remove(BBInfo.BB);
395 // For live terminators, mark destination blocks
396 // live to preserve this control flow edges.
397 if (!BBInfo.UnconditionalBranch)
398 for (auto *BB : successors(I->getParent()))
399 markLive(BB);
400 }
401 markLive(BBInfo);
402}
403
404void AggressiveDeadCodeElimination::markLive(BlockInfoType &BBInfo) {
405 if (BBInfo.Live)
406 return;
407 LLVM_DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n');
408 BBInfo.Live = true;
409 if (!BBInfo.CFLive) {
410 BBInfo.CFLive = true;
411 NewLiveBlocks.insert(BBInfo.BB);
412 }
413
414 // Mark unconditional branches at the end of live
415 // blocks as live since there is no work to do for them later
416 if (BBInfo.UnconditionalBranch)
417 markLive(BBInfo.Terminator);
418}
419
420void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) {
421 if (!AliveScopes.insert(&LS).second)
422 return;
423
424 if (isa<DISubprogram>(LS))
425 return;
426
427 // Tail-recurse through the scope chain.
428 collectLiveScopes(cast<DILocalScope>(*LS.getScope()));
429}
430
431void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) {
432 // Even though DILocations are not scopes, shove them into AliveScopes so we
433 // don't revisit them.
434 if (!AliveScopes.insert(&DL).second)
435 return;
436
437 // Collect live scopes from the scope chain.
438 collectLiveScopes(*DL.getScope());
439
440 // Tail-recurse through the inlined-at chain.
441 if (const DILocation *IA = DL.getInlinedAt())
442 collectLiveScopes(*IA);
443}
444
445void AggressiveDeadCodeElimination::markPhiLive(PHINode *PN) {
446 auto &Info = BlockInfo[PN->getParent()];
447 // Only need to check this once per block.
448 if (Info.HasLivePhiNodes)
449 return;
450 Info.HasLivePhiNodes = true;
451
452 // If a predecessor block is not live, mark it as control-flow live
453 // which will trigger marking live branches upon which
454 // that block is control dependent.
455 for (auto *PredBB : predecessors(Info.BB)) {
456 auto &Info = BlockInfo[PredBB];
457 if (!Info.CFLive) {
458 Info.CFLive = true;
459 NewLiveBlocks.insert(PredBB);
460 }
461 }
462}
463
464void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() {
465 if (BlocksWithDeadTerminators.empty())
466 return;
467
468 LLVM_DEBUG({
469 dbgs() << "new live blocks:\n";
470 for (auto *BB : NewLiveBlocks)
471 dbgs() << "\t" << BB->getName() << '\n';
472 dbgs() << "dead terminator blocks:\n";
473 for (auto *BB : BlocksWithDeadTerminators)
474 dbgs() << "\t" << BB->getName() << '\n';
475 });
476
477 // The dominance frontier of a live block X in the reverse
478 // control graph is the set of blocks upon which X is control
479 // dependent. The following sequence computes the set of blocks
480 // which currently have dead terminators that are control
481 // dependence sources of a block which is in NewLiveBlocks.
482
483 const SmallPtrSet<BasicBlock *, 16> BWDT(llvm::from_range,
484 BlocksWithDeadTerminators);
486 ReverseIDFCalculator IDFs(PDT);
487 IDFs.setDefiningBlocks(NewLiveBlocks);
488 IDFs.setLiveInBlocks(BWDT);
489 IDFs.calculate(IDFBlocks);
490 NewLiveBlocks.clear();
491
492 // Dead terminators which control live blocks are now marked live.
493 for (auto *BB : IDFBlocks) {
494 LLVM_DEBUG(dbgs() << "live control in: " << BB->getName() << '\n');
495 markLive(BB->getTerminator());
496 }
497}
498
499//===----------------------------------------------------------------------===//
500//
501// Routines to update the CFG and SSA information before removing dead code.
502//
503//===----------------------------------------------------------------------===//
504ADCEChanged AggressiveDeadCodeElimination::removeDeadInstructions() {
505 ADCEChanged Changed;
506 // Updates control and dataflow around dead blocks
507 Changed.ChangedControlFlow = updateDeadRegions();
508
509 LLVM_DEBUG({
510 for (Instruction &I : instructions(F)) {
511 // Check if the instruction is alive.
512 if (isLive(&I))
513 continue;
514
515 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
516 // Check if the scope of this variable location is alive.
517 if (AliveScopes.count(DII->getDebugLoc()->getScope()))
518 continue;
519
520 // If intrinsic is pointing at a live SSA value, there may be an
521 // earlier optimization bug: if we know the location of the variable,
522 // why isn't the scope of the location alive?
523 for (Value *V : DII->location_ops()) {
524 if (Instruction *II = dyn_cast<Instruction>(V)) {
525 if (isLive(II)) {
526 dbgs() << "Dropping debug info for " << *DII << "\n";
527 break;
528 }
529 }
530 }
531 }
532 }
533 });
534
535 // The inverse of the live set is the dead set. These are those instructions
536 // that have no side effects and do not influence the control flow or return
537 // value of the function, and may therefore be deleted safely.
538 // NOTE: We reuse the Worklist vector here for memory efficiency.
539 for (Instruction &I : llvm::reverse(instructions(F))) {
540 // With "RemoveDIs" debug-info stored in DbgVariableRecord objects,
541 // debug-info attached to this instruction, and drop any for scopes that
542 // aren't alive, like the rest of this loop does. Extending support to
543 // assignment tracking is future work.
544 for (DbgRecord &DR : make_early_inc_range(I.getDbgRecordRange())) {
545 // Avoid removing a DVR that is linked to instructions because it holds
546 // information about an existing store.
547 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
548 DVR && DVR->isDbgAssign())
549 if (!at::getAssignmentInsts(DVR).empty())
550 continue;
551 if (AliveScopes.count(DR.getDebugLoc()->getScope()))
552 continue;
553 I.dropOneDbgRecord(&DR);
554 }
555
556 // Check if the instruction is alive.
557 if (isLive(&I))
558 continue;
559
560 Changed.ChangedNonDebugInstr = true;
561
562 // Prepare to delete.
563 Worklist.push_back(&I);
565 }
566
567 for (Instruction *&I : Worklist)
568 I->dropAllReferences();
569
570 for (Instruction *&I : Worklist) {
571 ++NumRemoved;
572 I->eraseFromParent();
573 }
574
575 Changed.ChangedAnything = Changed.ChangedControlFlow || !Worklist.empty();
576
577 return Changed;
578}
579
580// A dead region is the set of dead blocks with a common live post-dominator.
581bool AggressiveDeadCodeElimination::updateDeadRegions() {
582 LLVM_DEBUG({
583 dbgs() << "final dead terminator blocks: " << '\n';
584 for (auto *BB : BlocksWithDeadTerminators)
585 dbgs() << '\t' << BB->getName()
586 << (BlockInfo[BB].Live ? " LIVE\n" : "\n");
587 });
588
589 // Don't compute the post ordering unless we needed it.
590 bool HavePostOrder = false;
591 bool Changed = false;
593
594 for (auto *BB : BlocksWithDeadTerminators) {
595 auto &Info = BlockInfo[BB];
596 if (Info.UnconditionalBranch) {
597 InstInfo[Info.Terminator].Live = true;
598 continue;
599 }
600
601 if (!HavePostOrder) {
602 computeReversePostOrder();
603 HavePostOrder = true;
604 }
605
606 // Add an unconditional branch to the successor closest to the
607 // end of the function which insures a path to the exit for each
608 // live edge.
609 BlockInfoType *PreferredSucc = nullptr;
610 for (auto *Succ : successors(BB)) {
611 auto *Info = &BlockInfo[Succ];
612 if (!PreferredSucc || PreferredSucc->PostOrder < Info->PostOrder)
613 PreferredSucc = Info;
614 }
615 assert((PreferredSucc && PreferredSucc->PostOrder > 0) &&
616 "Failed to find safe successor for dead branch");
617
618 // Collect removed successors to update the (Post)DominatorTrees.
619 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
620 bool First = true;
621 for (auto *Succ : successors(BB)) {
622 if (!First || Succ != PreferredSucc->BB) {
623 Succ->removePredecessor(BB);
624 RemovedSuccessors.insert(Succ);
625 } else
626 First = false;
627 }
628 makeUnconditional(BB, PreferredSucc->BB);
629
630 // Inform the dominators about the deleted CFG edges.
631 for (auto *Succ : RemovedSuccessors) {
632 // It might have happened that the same successor appeared multiple times
633 // and the CFG edge wasn't really removed.
634 if (Succ != PreferredSucc->BB) {
635 LLVM_DEBUG(dbgs() << "ADCE: (Post)DomTree edge enqueued for deletion"
636 << BB->getName() << " -> " << Succ->getName()
637 << "\n");
638 DeletedEdges.push_back({DominatorTree::Delete, BB, Succ});
639 }
640 }
641
642 NumBranchesRemoved += 1;
643 Changed = true;
644 }
645
646 if (!DeletedEdges.empty())
647 DomTreeUpdater(DT, &PDT, DomTreeUpdater::UpdateStrategy::Eager)
648 .applyUpdates(DeletedEdges);
649
650 return Changed;
651}
652
653// reverse top-sort order
654void AggressiveDeadCodeElimination::computeReversePostOrder() {
655 // This provides a post-order numbering of the reverse control flow graph
656 // Note that it is incomplete in the presence of infinite loops but we don't
657 // need numbers blocks which don't reach the end of the functions since
658 // all branches in those blocks are forced live.
659
660 // For each block without successors, extend the DFS from the block
661 // backward through the graph
662 SmallPtrSet<BasicBlock*, 16> Visited;
663 unsigned PostOrder = 0;
664 for (auto &BB : F) {
665 if (!succ_empty(&BB))
666 continue;
667 for (BasicBlock *Block : inverse_post_order_ext(&BB,Visited))
668 BlockInfo[Block].PostOrder = PostOrder++;
669 }
670}
671
672void AggressiveDeadCodeElimination::makeUnconditional(BasicBlock *BB,
673 BasicBlock *Target) {
674 Instruction *PredTerm = BB->getTerminator();
675 // Collect the live debug info scopes attached to this instruction.
676 if (const DILocation *DL = PredTerm->getDebugLoc())
677 collectLiveScopes(*DL);
678
679 // Just mark live an existing unconditional branch
680 if (auto *BI = dyn_cast<UncondBrInst>(PredTerm)) {
681 BI->setSuccessor(Target);
682 InstInfo[PredTerm].Live = true;
683 return;
684 }
685 LLVM_DEBUG(dbgs() << "making unconditional " << BB->getName() << '\n');
686 NumBranchesRemoved += 1;
687 IRBuilder<> Builder(PredTerm);
688 auto *NewTerm = Builder.CreateBr(Target);
689 InstInfo[NewTerm].Live = true;
690 if (const DILocation *DL = PredTerm->getDebugLoc())
691 NewTerm->setDebugLoc(DL);
692
693 InstInfo.erase(PredTerm);
694 PredTerm->eraseFromParent();
695}
696
697//===----------------------------------------------------------------------===//
698//
699// Pass Manager integration code
700//
701//===----------------------------------------------------------------------===//
703 // ADCE does not need DominatorTree, but require DominatorTree here
704 // to update analysis if it is already available.
705 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
706 auto &PDT = FAM.getResult<PostDominatorTreeAnalysis>(F);
707 ADCEChanged Changed =
708 AggressiveDeadCodeElimination(F, DT, PDT).performDeadCodeElimination();
709 if (!Changed.ChangedAnything)
710 return PreservedAnalyses::all();
711
713 if (!Changed.ChangedControlFlow) {
715 if (!Changed.ChangedNonDebugInstr) {
716 // Only removing debug instructions does not affect MemorySSA.
717 //
718 // Therefore we preserve MemorySSA when only removing debug instructions
719 // since otherwise later passes may behave differently which then makes
720 // the presence of debug info affect code generation.
722 }
723 }
726
727 return PA;
728}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< bool > RemoveLoops("adce-remove-loops", cl::init(false), cl::Hidden)
static cl::opt< bool > RemoveControlFlowFlag("adce-remove-control-flow", cl::init(true), cl::Hidden)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static bool isAlwaysLive(Instruction *I)
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
This is the interface for a simple mod/ref and alias analysis over globals.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Analysis pass which computes a DominatorTree.
Definition Dominators.h:278
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
Analysis pass which computes a PostDominatorTree.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
op_range operands()
Definition User.h:267
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
bool succ_empty(const Instruction *I)
Definition CFG.h:153
iterator_range< ipo_ext_iterator< T, SetType > > inverse_post_order_ext(const T &G, SetType &S)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1725
auto successors(const MachineBasicBlock *BB)
constexpr from_range_t from_range
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
IDFCalculator< true > ReverseIDFCalculator
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition InstrProf.h:112
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Definition ADCE.cpp:702