LLVM 17.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"
47#include "llvm/Pass.h"
51#include "llvm/Support/Debug.h"
55#include <cassert>
56#include <cstddef>
57#include <utility>
58
59using namespace llvm;
60
61#define DEBUG_TYPE "adce"
62
63STATISTIC(NumRemoved, "Number of instructions removed");
64STATISTIC(NumBranchesRemoved, "Number of branch instructions removed");
65
66// This is a temporary option until we change the interface to this pass based
67// on optimization level.
68static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow",
69 cl::init(true), cl::Hidden);
70
71// This option enables removing of may-be-infinite loops which have no other
72// effect.
73static cl::opt<bool> RemoveLoops("adce-remove-loops", cl::init(false),
75
76namespace {
77
78/// Information about Instructions
79struct InstInfoType {
80 /// True if the associated instruction is live.
81 bool Live = false;
82
83 /// Quick access to information for block containing associated Instruction.
84 struct BlockInfoType *Block = nullptr;
85};
86
87/// Information about basic blocks relevant to dead code elimination.
88struct BlockInfoType {
89 /// True when this block contains a live instructions.
90 bool Live = false;
91
92 /// True when this block ends in an unconditional branch.
93 bool UnconditionalBranch = false;
94
95 /// True when this block is known to have live PHI nodes.
96 bool HasLivePhiNodes = false;
97
98 /// Control dependence sources need to be live for this block.
99 bool CFLive = false;
100
101 /// Quick access to the LiveInfo for the terminator,
102 /// holds the value &InstInfo[Terminator]
103 InstInfoType *TerminatorLiveInfo = nullptr;
104
105 /// Corresponding BasicBlock.
106 BasicBlock *BB = nullptr;
107
108 /// Cache of BB->getTerminator().
109 Instruction *Terminator = nullptr;
110
111 /// Post-order numbering of reverse control flow graph.
112 unsigned PostOrder;
113
114 bool terminatorIsLive() const { return TerminatorLiveInfo->Live; }
115};
116
117struct ADCEChanged {
118 bool ChangedAnything = false;
119 bool ChangedNonDebugInstr = false;
120 bool ChangedControlFlow = false;
121};
122
123class AggressiveDeadCodeElimination {
124 Function &F;
125
126 // ADCE does not use DominatorTree per se, but it updates it to preserve the
127 // analysis.
128 DominatorTree *DT;
130
131 /// Mapping of blocks to associated information, an element in BlockInfoVec.
132 /// Use MapVector to get deterministic iteration order.
134 bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; }
135
136 /// Mapping of instructions to associated information.
138 bool isLive(Instruction *I) { return InstInfo[I].Live; }
139
140 /// Instructions known to be live where we need to mark
141 /// reaching definitions as live.
143
144 /// Debug info scopes around a live instruction.
146
147 /// Set of blocks with not known to have live terminators.
148 SmallSetVector<BasicBlock *, 16> BlocksWithDeadTerminators;
149
150 /// The set of blocks which we have determined whose control
151 /// dependence sources must be live and which have not had
152 /// those dependences analyzed.
153 SmallPtrSet<BasicBlock *, 16> NewLiveBlocks;
154
155 /// Set up auxiliary data structures for Instructions and BasicBlocks and
156 /// initialize the Worklist to the set of must-be-live Instruscions.
157 void initialize();
158
159 /// Return true for operations which are always treated as live.
161
162 /// Return true for instrumentation instructions for value profiling.
163 bool isInstrumentsConstant(Instruction &I);
164
165 /// Propagate liveness to reaching definitions.
166 void markLiveInstructions();
167
168 /// Mark an instruction as live.
169 void markLive(Instruction *I);
170
171 /// Mark a block as live.
172 void markLive(BlockInfoType &BB);
173 void markLive(BasicBlock *BB) { markLive(BlockInfo[BB]); }
174
175 /// Mark terminators of control predecessors of a PHI node live.
176 void markPhiLive(PHINode *PN);
177
178 /// Record the Debug Scopes which surround live debug information.
179 void collectLiveScopes(const DILocalScope &LS);
180 void collectLiveScopes(const DILocation &DL);
181
182 /// Analyze dead branches to find those whose branches are the sources
183 /// of control dependences impacting a live block. Those branches are
184 /// marked live.
185 void markLiveBranchesFromControlDependences();
186
187 /// Remove instructions not marked live, return if any instruction was
188 /// removed.
189 ADCEChanged removeDeadInstructions();
190
191 /// Identify connected sections of the control flow graph which have
192 /// dead terminators and rewrite the control flow graph to remove them.
193 bool updateDeadRegions();
194
195 /// Set the BlockInfo::PostOrder field based on a post-order
196 /// numbering of the reverse control flow graph.
197 void computeReversePostOrder();
198
199 /// Make the terminator of this block an unconditional branch to \p Target.
200 void makeUnconditional(BasicBlock *BB, BasicBlock *Target);
201
202public:
203 AggressiveDeadCodeElimination(Function &F, DominatorTree *DT,
205 : F(F), DT(DT), PDT(PDT) {}
206
207 ADCEChanged performDeadCodeElimination();
208};
209
210} // end anonymous namespace
211
212ADCEChanged AggressiveDeadCodeElimination::performDeadCodeElimination() {
213 initialize();
214 markLiveInstructions();
215 return removeDeadInstructions();
216}
217
219 auto *BR = dyn_cast<BranchInst>(Term);
220 return BR && BR->isUnconditional();
221}
222
223void AggressiveDeadCodeElimination::initialize() {
224 auto NumBlocks = F.size();
225
226 // We will have an entry in the map for each block so we grow the
227 // structure to twice that size to keep the load factor low in the hash table.
228 BlockInfo.reserve(NumBlocks);
229 size_t NumInsts = 0;
230
231 // Iterate over blocks and initialize BlockInfoVec entries, count
232 // instructions to size the InstInfo hash table.
233 for (auto &BB : F) {
234 NumInsts += BB.size();
235 auto &Info = BlockInfo[&BB];
236 Info.BB = &BB;
237 Info.Terminator = BB.getTerminator();
238 Info.UnconditionalBranch = isUnconditionalBranch(Info.Terminator);
239 }
240
241 // Initialize instruction map and set pointers to block info.
242 InstInfo.reserve(NumInsts);
243 for (auto &BBInfo : BlockInfo)
244 for (Instruction &I : *BBInfo.second.BB)
245 InstInfo[&I].Block = &BBInfo.second;
246
247 // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not
248 // add any more elements to either after this point.
249 for (auto &BBInfo : BlockInfo)
250 BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator];
251
252 // Collect the set of "root" instructions that are known live.
253 for (Instruction &I : instructions(F))
254 if (isAlwaysLive(I))
255 markLive(&I);
256
258 return;
259
260 if (!RemoveLoops) {
261 // This stores state for the depth-first iterator. In addition
262 // to recording which nodes have been visited we also record whether
263 // a node is currently on the "stack" of active ancestors of the current
264 // node.
265 using StatusMap = DenseMap<BasicBlock *, bool>;
266
267 class DFState : public StatusMap {
268 public:
269 std::pair<StatusMap::iterator, bool> insert(BasicBlock *BB) {
270 return StatusMap::insert(std::make_pair(BB, true));
271 }
272
273 // Invoked after we have visited all children of a node.
274 void completed(BasicBlock *BB) { (*this)[BB] = false; }
275
276 // Return true if \p BB is currently on the active stack
277 // of ancestors.
278 bool onStack(BasicBlock *BB) {
279 auto Iter = find(BB);
280 return Iter != end() && Iter->second;
281 }
282 } State;
283
284 State.reserve(F.size());
285 // Iterate over blocks in depth-first pre-order and
286 // treat all edges to a block already seen as loop back edges
287 // and mark the branch live it if there is a back edge.
288 for (auto *BB: depth_first_ext(&F.getEntryBlock(), State)) {
289 Instruction *Term = BB->getTerminator();
290 if (isLive(Term))
291 continue;
292
293 for (auto *Succ : successors(BB))
294 if (State.onStack(Succ)) {
295 // back edge....
296 markLive(Term);
297 break;
298 }
299 }
300 }
301
302 // Mark blocks live if there is no path from the block to a
303 // return of the function.
304 // We do this by seeing which of the postdomtree root children exit the
305 // program, and for all others, mark the subtree live.
306 for (const auto &PDTChild : children<DomTreeNode *>(PDT.getRootNode())) {
307 auto *BB = PDTChild->getBlock();
308 auto &Info = BlockInfo[BB];
309 // Real function return
310 if (isa<ReturnInst>(Info.Terminator)) {
311 LLVM_DEBUG(dbgs() << "post-dom root child is a return: " << BB->getName()
312 << '\n';);
313 continue;
314 }
315
316 // This child is something else, like an infinite loop.
317 for (auto *DFNode : depth_first(PDTChild))
318 markLive(BlockInfo[DFNode->getBlock()].Terminator);
319 }
320
321 // Treat the entry block as always live
322 auto *BB = &F.getEntryBlock();
323 auto &EntryInfo = BlockInfo[BB];
324 EntryInfo.Live = true;
325 if (EntryInfo.UnconditionalBranch)
326 markLive(EntryInfo.Terminator);
327
328 // Build initial collection of blocks with dead terminators
329 for (auto &BBInfo : BlockInfo)
330 if (!BBInfo.second.terminatorIsLive())
331 BlocksWithDeadTerminators.insert(BBInfo.second.BB);
332}
333
334bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) {
335 // TODO -- use llvm::isInstructionTriviallyDead
336 if (I.isEHPad() || I.mayHaveSideEffects()) {
337 // Skip any value profile instrumentation calls if they are
338 // instrumenting constants.
339 if (isInstrumentsConstant(I))
340 return false;
341 return true;
342 }
343 if (!I.isTerminator())
344 return false;
345 if (RemoveControlFlowFlag && (isa<BranchInst>(I) || isa<SwitchInst>(I)))
346 return false;
347 return true;
348}
349
350// Check if this instruction is a runtime call for value profiling and
351// if it's instrumenting a constant.
352bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) {
353 // TODO -- move this test into llvm::isInstructionTriviallyDead
354 if (CallInst *CI = dyn_cast<CallInst>(&I))
355 if (Function *Callee = CI->getCalledFunction())
356 if (Callee->getName().equals(getInstrProfValueProfFuncName()))
357 if (isa<Constant>(CI->getArgOperand(0)))
358 return true;
359 return false;
360}
361
362void AggressiveDeadCodeElimination::markLiveInstructions() {
363 // Propagate liveness backwards to operands.
364 do {
365 // Worklist holds newly discovered live instructions
366 // where we need to mark the inputs as live.
367 while (!Worklist.empty()) {
368 Instruction *LiveInst = Worklist.pop_back_val();
369 LLVM_DEBUG(dbgs() << "work live: "; LiveInst->dump(););
370
371 for (Use &OI : LiveInst->operands())
372 if (Instruction *Inst = dyn_cast<Instruction>(OI))
373 markLive(Inst);
374
375 if (auto *PN = dyn_cast<PHINode>(LiveInst))
376 markPhiLive(PN);
377 }
378
379 // After data flow liveness has been identified, examine which branch
380 // decisions are required to determine live instructions are executed.
381 markLiveBranchesFromControlDependences();
382
383 } while (!Worklist.empty());
384}
385
386void AggressiveDeadCodeElimination::markLive(Instruction *I) {
387 auto &Info = InstInfo[I];
388 if (Info.Live)
389 return;
390
391 LLVM_DEBUG(dbgs() << "mark live: "; I->dump());
392 Info.Live = true;
393 Worklist.push_back(I);
394
395 // Collect the live debug info scopes attached to this instruction.
396 if (const DILocation *DL = I->getDebugLoc())
397 collectLiveScopes(*DL);
398
399 // Mark the containing block live
400 auto &BBInfo = *Info.Block;
401 if (BBInfo.Terminator == I) {
402 BlocksWithDeadTerminators.remove(BBInfo.BB);
403 // For live terminators, mark destination blocks
404 // live to preserve this control flow edges.
405 if (!BBInfo.UnconditionalBranch)
406 for (auto *BB : successors(I->getParent()))
407 markLive(BB);
408 }
409 markLive(BBInfo);
410}
411
412void AggressiveDeadCodeElimination::markLive(BlockInfoType &BBInfo) {
413 if (BBInfo.Live)
414 return;
415 LLVM_DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n');
416 BBInfo.Live = true;
417 if (!BBInfo.CFLive) {
418 BBInfo.CFLive = true;
419 NewLiveBlocks.insert(BBInfo.BB);
420 }
421
422 // Mark unconditional branches at the end of live
423 // blocks as live since there is no work to do for them later
424 if (BBInfo.UnconditionalBranch)
425 markLive(BBInfo.Terminator);
426}
427
428void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) {
429 if (!AliveScopes.insert(&LS).second)
430 return;
431
432 if (isa<DISubprogram>(LS))
433 return;
434
435 // Tail-recurse through the scope chain.
436 collectLiveScopes(cast<DILocalScope>(*LS.getScope()));
437}
438
439void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) {
440 // Even though DILocations are not scopes, shove them into AliveScopes so we
441 // don't revisit them.
442 if (!AliveScopes.insert(&DL).second)
443 return;
444
445 // Collect live scopes from the scope chain.
446 collectLiveScopes(*DL.getScope());
447
448 // Tail-recurse through the inlined-at chain.
449 if (const DILocation *IA = DL.getInlinedAt())
450 collectLiveScopes(*IA);
451}
452
453void AggressiveDeadCodeElimination::markPhiLive(PHINode *PN) {
454 auto &Info = BlockInfo[PN->getParent()];
455 // Only need to check this once per block.
456 if (Info.HasLivePhiNodes)
457 return;
458 Info.HasLivePhiNodes = true;
459
460 // If a predecessor block is not live, mark it as control-flow live
461 // which will trigger marking live branches upon which
462 // that block is control dependent.
463 for (auto *PredBB : predecessors(Info.BB)) {
464 auto &Info = BlockInfo[PredBB];
465 if (!Info.CFLive) {
466 Info.CFLive = true;
467 NewLiveBlocks.insert(PredBB);
468 }
469 }
470}
471
472void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() {
473 if (BlocksWithDeadTerminators.empty())
474 return;
475
476 LLVM_DEBUG({
477 dbgs() << "new live blocks:\n";
478 for (auto *BB : NewLiveBlocks)
479 dbgs() << "\t" << BB->getName() << '\n';
480 dbgs() << "dead terminator blocks:\n";
481 for (auto *BB : BlocksWithDeadTerminators)
482 dbgs() << "\t" << BB->getName() << '\n';
483 });
484
485 // The dominance frontier of a live block X in the reverse
486 // control graph is the set of blocks upon which X is control
487 // dependent. The following sequence computes the set of blocks
488 // which currently have dead terminators that are control
489 // dependence sources of a block which is in NewLiveBlocks.
490
492 BlocksWithDeadTerminators.begin(),
493 BlocksWithDeadTerminators.end()
494 };
496 ReverseIDFCalculator IDFs(PDT);
497 IDFs.setDefiningBlocks(NewLiveBlocks);
498 IDFs.setLiveInBlocks(BWDT);
499 IDFs.calculate(IDFBlocks);
500 NewLiveBlocks.clear();
501
502 // Dead terminators which control live blocks are now marked live.
503 for (auto *BB : IDFBlocks) {
504 LLVM_DEBUG(dbgs() << "live control in: " << BB->getName() << '\n');
505 markLive(BB->getTerminator());
506 }
507}
508
509//===----------------------------------------------------------------------===//
510//
511// Routines to update the CFG and SSA information before removing dead code.
512//
513//===----------------------------------------------------------------------===//
514ADCEChanged AggressiveDeadCodeElimination::removeDeadInstructions() {
515 ADCEChanged Changed;
516 // Updates control and dataflow around dead blocks
517 Changed.ChangedControlFlow = updateDeadRegions();
518
519 LLVM_DEBUG({
520 for (Instruction &I : instructions(F)) {
521 // Check if the instruction is alive.
522 if (isLive(&I))
523 continue;
524
525 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
526 // Check if the scope of this variable location is alive.
527 if (AliveScopes.count(DII->getDebugLoc()->getScope()))
528 continue;
529
530 // If intrinsic is pointing at a live SSA value, there may be an
531 // earlier optimization bug: if we know the location of the variable,
532 // why isn't the scope of the location alive?
533 for (Value *V : DII->location_ops()) {
534 if (Instruction *II = dyn_cast<Instruction>(V)) {
535 if (isLive(II)) {
536 dbgs() << "Dropping debug info for " << *DII << "\n";
537 break;
538 }
539 }
540 }
541 }
542 }
543 });
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.
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 Changed.ChangedNonDebugInstr = true;
567 }
568
569 // Prepare to delete.
570 Worklist.push_back(&I);
572 }
573
574 for (Instruction *&I : Worklist)
575 I->dropAllReferences();
576
577 for (Instruction *&I : Worklist) {
578 ++NumRemoved;
579 I->eraseFromParent();
580 }
581
582 Changed.ChangedAnything = Changed.ChangedControlFlow || !Worklist.empty();
583
584 return Changed;
585}
586
587// A dead region is the set of dead blocks with a common live post-dominator.
588bool AggressiveDeadCodeElimination::updateDeadRegions() {
589 LLVM_DEBUG({
590 dbgs() << "final dead terminator blocks: " << '\n';
591 for (auto *BB : BlocksWithDeadTerminators)
592 dbgs() << '\t' << BB->getName()
593 << (BlockInfo[BB].Live ? " LIVE\n" : "\n");
594 });
595
596 // Don't compute the post ordering unless we needed it.
597 bool HavePostOrder = false;
598 bool Changed = false;
600
601 for (auto *BB : BlocksWithDeadTerminators) {
602 auto &Info = BlockInfo[BB];
603 if (Info.UnconditionalBranch) {
604 InstInfo[Info.Terminator].Live = true;
605 continue;
606 }
607
608 if (!HavePostOrder) {
609 computeReversePostOrder();
610 HavePostOrder = true;
611 }
612
613 // Add an unconditional branch to the successor closest to the
614 // end of the function which insures a path to the exit for each
615 // live edge.
616 BlockInfoType *PreferredSucc = nullptr;
617 for (auto *Succ : successors(BB)) {
618 auto *Info = &BlockInfo[Succ];
619 if (!PreferredSucc || PreferredSucc->PostOrder < Info->PostOrder)
620 PreferredSucc = Info;
621 }
622 assert((PreferredSucc && PreferredSucc->PostOrder > 0) &&
623 "Failed to find safe successor for dead branch");
624
625 // Collect removed successors to update the (Post)DominatorTrees.
626 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
627 bool First = true;
628 for (auto *Succ : successors(BB)) {
629 if (!First || Succ != PreferredSucc->BB) {
630 Succ->removePredecessor(BB);
631 RemovedSuccessors.insert(Succ);
632 } else
633 First = false;
634 }
635 makeUnconditional(BB, PreferredSucc->BB);
636
637 // Inform the dominators about the deleted CFG edges.
638 for (auto *Succ : RemovedSuccessors) {
639 // It might have happened that the same successor appeared multiple times
640 // and the CFG edge wasn't really removed.
641 if (Succ != PreferredSucc->BB) {
642 LLVM_DEBUG(dbgs() << "ADCE: (Post)DomTree edge enqueued for deletion"
643 << BB->getName() << " -> " << Succ->getName()
644 << "\n");
645 DeletedEdges.push_back({DominatorTree::Delete, BB, Succ});
646 }
647 }
648
649 NumBranchesRemoved += 1;
650 Changed = true;
651 }
652
653 if (!DeletedEdges.empty())
654 DomTreeUpdater(DT, &PDT, DomTreeUpdater::UpdateStrategy::Eager)
655 .applyUpdates(DeletedEdges);
656
657 return Changed;
658}
659
660// reverse top-sort order
661void AggressiveDeadCodeElimination::computeReversePostOrder() {
662 // This provides a post-order numbering of the reverse control flow graph
663 // Note that it is incomplete in the presence of infinite loops but we don't
664 // need numbers blocks which don't reach the end of the functions since
665 // all branches in those blocks are forced live.
666
667 // For each block without successors, extend the DFS from the block
668 // backward through the graph
670 unsigned PostOrder = 0;
671 for (auto &BB : F) {
672 if (!succ_empty(&BB))
673 continue;
674 for (BasicBlock *Block : inverse_post_order_ext(&BB,Visited))
675 BlockInfo[Block].PostOrder = PostOrder++;
676 }
677}
678
679void AggressiveDeadCodeElimination::makeUnconditional(BasicBlock *BB,
681 Instruction *PredTerm = BB->getTerminator();
682 // Collect the live debug info scopes attached to this instruction.
683 if (const DILocation *DL = PredTerm->getDebugLoc())
684 collectLiveScopes(*DL);
685
686 // Just mark live an existing unconditional branch
687 if (isUnconditionalBranch(PredTerm)) {
688 PredTerm->setSuccessor(0, Target);
689 InstInfo[PredTerm].Live = true;
690 return;
691 }
692 LLVM_DEBUG(dbgs() << "making unconditional " << BB->getName() << '\n');
693 NumBranchesRemoved += 1;
694 IRBuilder<> Builder(PredTerm);
695 auto *NewTerm = Builder.CreateBr(Target);
696 InstInfo[NewTerm].Live = true;
697 if (const DILocation *DL = PredTerm->getDebugLoc())
698 NewTerm->setDebugLoc(DL);
699
700 InstInfo.erase(PredTerm);
701 PredTerm->eraseFromParent();
702}
703
704//===----------------------------------------------------------------------===//
705//
706// Pass Manager integration code
707//
708//===----------------------------------------------------------------------===//
710 // ADCE does not need DominatorTree, but require DominatorTree here
711 // to update analysis if it is already available.
714 ADCEChanged Changed =
715 AggressiveDeadCodeElimination(F, DT, PDT).performDeadCodeElimination();
716 if (!Changed.ChangedAnything)
717 return PreservedAnalyses::all();
718
720 if (!Changed.ChangedControlFlow) {
722 if (!Changed.ChangedNonDebugInstr) {
723 // Only removing debug instructions does not affect MemorySSA.
724 //
725 // Therefore we preserve MemorySSA when only removing debug instructions
726 // since otherwise later passes may behave differently which then makes
727 // the presence of debug info affect code generation.
729 }
730 }
733
734 return PA;
735}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isUnconditionalBranch(Instruction *Term)
Definition: ADCE.cpp:218
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)
amdgpu Simplify well known AMD library false FunctionCallee Callee
assume Assume Builder
for(auto &MBB :MF)
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is Live
#define LLVM_DEBUG(X)
Definition: Debug.h:101
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...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
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...
print must be executed print the must be executed context for all instructions
FunctionAnalysisManager FAM
This header defines various interfaces for pass management in LLVM.
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:167
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef< StringLiteral > StandardNames)
Initialize the set of available library functions based on the specified target triple.
This defines the Use class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:793
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
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:127
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:113
This class represents a function call, abstracting a target machine's calling convention.
A scope for locals.
Debug location.
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2558
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:358
const BasicBlock * getParent() const
Definition: Instruction.h:90
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:82
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:37
An analysis that produces MemorySSA for a function.
Definition: MemorySSA.h:936
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:188
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:173
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:365
iterator begin() const
Definition: SmallPtrSet.h:403
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:301
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Target - Wrapper for Target specific information.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
LLVM Value Representation.
Definition: Value.h:74
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4941
AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
Definition: DebugInfo.cpp:1729
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
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:1802
bool succ_empty(const Instruction *I)
Definition: CFG.h:255
iterator_range< ipo_ext_iterator< T, SetType > > inverse_post_order_ext(const T &G, SetType &S)
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:1367
auto successors(const MachineBasicBlock *BB)
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:495
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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:79
iterator_range< df_iterator< T > > depth_first(const T &G)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Definition: ADCE.cpp:709