blob: c64aacbb8db2045358b410402c776fe8725c5d9a [file] [log] [blame]
Justin Bogner0638b7ba2015-09-25 21:03:46 +00001//===- ADCE.cpp - Code to perform dead code elimination -------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerb28986f2001-06-30 06:39:11 +00009//
Owen Anderson7686b552008-05-29 08:45:13 +000010// This file implements the Aggressive Dead Code Elimination pass. This pass
11// optimistically assumes that all instructions are dead until proven otherwise,
Nadav Rotem465834c2012-07-24 10:51:42 +000012// allowing it to eliminate dead computations that other DCE passes do not
Owen Anderson7686b552008-05-29 08:45:13 +000013// catch, particularly involving loop computations.
Chris Lattnerb28986f2001-06-30 06:39:11 +000014//
15//===----------------------------------------------------------------------===//
16
Justin Bogner19b67992015-10-30 23:13:18 +000017#include "llvm/Transforms/Scalar/ADCE.h"
David Callahancc5cd4d2016-08-03 04:28:39 +000018
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/DepthFirstIterator.h"
David Callahanebcf9162016-12-13 16:42:18 +000020#include "llvm/ADT/PostOrderIterator.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
James Molloyefbba722015-09-10 10:22:12 +000024#include "llvm/Analysis/GlobalsModRef.h"
David Callahan012d1c02016-08-24 00:10:06 +000025#include "llvm/Analysis/IteratedDominanceFrontier.h"
26#include "llvm/Analysis/PostDominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000028#include "llvm/IR/CFG.h"
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +000029#include "llvm/IR/DebugInfoMetadata.h"
David Callahanebcf9162016-12-13 16:42:18 +000030#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000031#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
Owen Anderson7686b552008-05-29 08:45:13 +000034#include "llvm/Pass.h"
Betul Buyukkurtbf8554c2016-04-13 18:52:19 +000035#include "llvm/ProfileData/InstrProf.h"
Justin Bogner19b67992015-10-30 23:13:18 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattnerfc7bdac2003-12-19 09:08:34 +000037using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000038
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "adce"
40
Owen Anderson7686b552008-05-29 08:45:13 +000041STATISTIC(NumRemoved, "Number of instructions removed");
David Callahanebcf9162016-12-13 16:42:18 +000042STATISTIC(NumBranchesRemoved, "Number of branch instructions removed");
Chris Lattner019f3642002-05-06 17:27:57 +000043
Tobias Grosser335b6bf2017-03-14 10:18:11 +000044// This is a temporary option until we change the interface to this pass based
45// on optimization level.
David Callahan947be0f2016-08-16 14:31:51 +000046static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow",
David Callahanebcf9162016-12-13 16:42:18 +000047 cl::init(true), cl::Hidden);
48
49// This option enables removing of may-be-infinite loops which have no other
50// effect.
51static cl::opt<bool> RemoveLoops("adce-remove-loops", cl::init(false),
52 cl::Hidden);
David Callahan947be0f2016-08-16 14:31:51 +000053
David Callahancc5cd4d2016-08-03 04:28:39 +000054namespace {
David Callahan947be0f2016-08-16 14:31:51 +000055/// Information about Instructions
56struct InstInfoType {
57 /// True if the associated instruction is live.
58 bool Live = false;
59 /// Quick access to information for block containing associated Instruction.
60 struct BlockInfoType *Block = nullptr;
61};
62
63/// Information about basic blocks relevant to dead code elimination.
64struct BlockInfoType {
65 /// True when this block contains a live instructions.
66 bool Live = false;
67 /// True when this block ends in an unconditional branch.
68 bool UnconditionalBranch = false;
David Callahanc165a4e2016-09-19 23:17:58 +000069 /// True when this block is known to have live PHI nodes.
70 bool HasLivePhiNodes = false;
71 /// Control dependence sources need to be live for this block.
72 bool CFLive = false;
David Callahan947be0f2016-08-16 14:31:51 +000073
74 /// Quick access to the LiveInfo for the terminator,
75 /// holds the value &InstInfo[Terminator]
76 InstInfoType *TerminatorLiveInfo = nullptr;
77
78 bool terminatorIsLive() const { return TerminatorLiveInfo->Live; }
79
80 /// Corresponding BasicBlock.
81 BasicBlock *BB = nullptr;
82
David Callahanebcf9162016-12-13 16:42:18 +000083 /// Cache of BB->getTerminator().
David Callahan947be0f2016-08-16 14:31:51 +000084 TerminatorInst *Terminator = nullptr;
David Callahanebcf9162016-12-13 16:42:18 +000085
86 /// Post-order numbering of reverse control flow graph.
87 unsigned PostOrder;
David Callahan947be0f2016-08-16 14:31:51 +000088};
89
David Callahan45e442e2016-08-05 19:38:11 +000090class AggressiveDeadCodeElimination {
David Callahancc5cd4d2016-08-03 04:28:39 +000091 Function &F;
David Callahan012d1c02016-08-24 00:10:06 +000092 PostDominatorTree &PDT;
David Callahan947be0f2016-08-16 14:31:51 +000093
94 /// Mapping of blocks to associated information, an element in BlockInfoVec.
95 DenseMap<BasicBlock *, BlockInfoType> BlockInfo;
96 bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; }
97
98 /// Mapping of instructions to associated information.
99 DenseMap<Instruction *, InstInfoType> InstInfo;
100 bool isLive(Instruction *I) { return InstInfo[I].Live; }
101
David Callahan45e442e2016-08-05 19:38:11 +0000102 /// Instructions known to be live where we need to mark
103 /// reaching definitions as live.
David Callahancc5cd4d2016-08-03 04:28:39 +0000104 SmallVector<Instruction *, 128> Worklist;
David Callahan45e442e2016-08-05 19:38:11 +0000105 /// Debug info scopes around a live instruction.
David Callahancc5cd4d2016-08-03 04:28:39 +0000106 SmallPtrSet<const Metadata *, 32> AliveScopes;
David Callahan45e442e2016-08-05 19:38:11 +0000107
David Callahan947be0f2016-08-16 14:31:51 +0000108 /// Set of blocks with not known to have live terminators.
109 SmallPtrSet<BasicBlock *, 16> BlocksWithDeadTerminators;
110
David Callahanebcf9162016-12-13 16:42:18 +0000111 /// The set of blocks which we have determined whose control
112 /// dependence sources must be live and which have not had
Tobias Grosser335b6bf2017-03-14 10:18:11 +0000113 /// those dependences analyzed.
David Callahan947be0f2016-08-16 14:31:51 +0000114 SmallPtrSet<BasicBlock *, 16> NewLiveBlocks;
115
116 /// Set up auxiliary data structures for Instructions and BasicBlocks and
117 /// initialize the Worklist to the set of must-be-live Instruscions.
David Callahan45e442e2016-08-05 19:38:11 +0000118 void initialize();
David Callahan947be0f2016-08-16 14:31:51 +0000119 /// Return true for operations which are always treated as live.
David Callahan45e442e2016-08-05 19:38:11 +0000120 bool isAlwaysLive(Instruction &I);
David Callahan947be0f2016-08-16 14:31:51 +0000121 /// Return true for instrumentation instructions for value profiling.
David Callahan45e442e2016-08-05 19:38:11 +0000122 bool isInstrumentsConstant(Instruction &I);
David Callahan45e442e2016-08-05 19:38:11 +0000123
124 /// Propagate liveness to reaching definitions.
125 void markLiveInstructions();
126 /// Mark an instruction as live.
David Callahan947be0f2016-08-16 14:31:51 +0000127 void markLive(Instruction *I);
David Callahanebcf9162016-12-13 16:42:18 +0000128 /// Mark a block as live.
129 void markLive(BlockInfoType &BB);
130 void markLive(BasicBlock *BB) { markLive(BlockInfo[BB]); }
131
David Callahanc165a4e2016-09-19 23:17:58 +0000132 /// Mark terminators of control predecessors of a PHI node live.
133 void markPhiLive(PHINode *PN);
David Callahan947be0f2016-08-16 14:31:51 +0000134
135 /// Record the Debug Scopes which surround live debug information.
David Callahancc5cd4d2016-08-03 04:28:39 +0000136 void collectLiveScopes(const DILocalScope &LS);
137 void collectLiveScopes(const DILocation &DL);
David Callahan947be0f2016-08-16 14:31:51 +0000138
139 /// Analyze dead branches to find those whose branches are the sources
140 /// of control dependences impacting a live block. Those branches are
141 /// marked live.
142 void markLiveBranchesFromControlDependences();
David Callahan45e442e2016-08-05 19:38:11 +0000143
144 /// Remove instructions not marked live, return if any any instruction
145 /// was removed.
146 bool removeDeadInstructions();
147
Tobias Grosser335b6bf2017-03-14 10:18:11 +0000148 /// Identify connected sections of the control flow graph which have
David Callahanebcf9162016-12-13 16:42:18 +0000149 /// dead terminators and rewrite the control flow graph to remove them.
150 void updateDeadRegions();
151
152 /// Set the BlockInfo::PostOrder field based on a post-order
153 /// numbering of the reverse control flow graph.
154 void computeReversePostOrder();
155
156 /// Make the terminator of this block an unconditional branch to \p Target.
157 void makeUnconditional(BasicBlock *BB, BasicBlock *Target);
158
David Callahancc5cd4d2016-08-03 04:28:39 +0000159public:
David Callahan012d1c02016-08-24 00:10:06 +0000160 AggressiveDeadCodeElimination(Function &F, PostDominatorTree &PDT)
161 : F(F), PDT(PDT) {}
David Callahan45e442e2016-08-05 19:38:11 +0000162 bool performDeadCodeElimination();
David Callahancc5cd4d2016-08-03 04:28:39 +0000163};
164}
165
David Callahan45e442e2016-08-05 19:38:11 +0000166bool AggressiveDeadCodeElimination::performDeadCodeElimination() {
167 initialize();
168 markLiveInstructions();
169 return removeDeadInstructions();
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000170}
171
David Callahan947be0f2016-08-16 14:31:51 +0000172static bool isUnconditionalBranch(TerminatorInst *Term) {
David Callahanebcf9162016-12-13 16:42:18 +0000173 auto *BR = dyn_cast<BranchInst>(Term);
David Callahan947be0f2016-08-16 14:31:51 +0000174 return BR && BR->isUnconditional();
175}
176
David Callahan45e442e2016-08-05 19:38:11 +0000177void AggressiveDeadCodeElimination::initialize() {
David Callahan947be0f2016-08-16 14:31:51 +0000178
179 auto NumBlocks = F.size();
180
181 // We will have an entry in the map for each block so we grow the
182 // structure to twice that size to keep the load factor low in the hash table.
183 BlockInfo.reserve(NumBlocks);
184 size_t NumInsts = 0;
David Callahan012d1c02016-08-24 00:10:06 +0000185
David Callahan947be0f2016-08-16 14:31:51 +0000186 // Iterate over blocks and initialize BlockInfoVec entries, count
187 // instructions to size the InstInfo hash table.
188 for (auto &BB : F) {
189 NumInsts += BB.size();
190 auto &Info = BlockInfo[&BB];
191 Info.BB = &BB;
192 Info.Terminator = BB.getTerminator();
193 Info.UnconditionalBranch = isUnconditionalBranch(Info.Terminator);
194 }
195
196 // Initialize instruction map and set pointers to block info.
197 InstInfo.reserve(NumInsts);
198 for (auto &BBInfo : BlockInfo)
199 for (Instruction &I : *BBInfo.second.BB)
200 InstInfo[&I].Block = &BBInfo.second;
201
202 // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not
203 // add any more elements to either after this point.
204 for (auto &BBInfo : BlockInfo)
205 BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator];
206
David Callahan45e442e2016-08-05 19:38:11 +0000207 // Collect the set of "root" instructions that are known live.
208 for (Instruction &I : instructions(F))
209 if (isAlwaysLive(I))
David Callahan947be0f2016-08-16 14:31:51 +0000210 markLive(&I);
211
212 if (!RemoveControlFlowFlag)
213 return;
214
David Callahanebcf9162016-12-13 16:42:18 +0000215 if (!RemoveLoops) {
216 // This stores state for the depth-first iterator. In addition
217 // to recording which nodes have been visited we also record whether
218 // a node is currently on the "stack" of active ancestors of the current
219 // node.
220 typedef DenseMap<BasicBlock *, bool> StatusMap ;
221 class DFState : public StatusMap {
222 public:
223 std::pair<StatusMap::iterator, bool> insert(BasicBlock *BB) {
224 return StatusMap::insert(std::make_pair(BB, true));
225 }
David Callahan947be0f2016-08-16 14:31:51 +0000226
David Callahanebcf9162016-12-13 16:42:18 +0000227 // Invoked after we have visited all children of a node.
228 void completed(BasicBlock *BB) { (*this)[BB] = false; }
229
230 // Return true if \p BB is currently on the active stack
231 // of ancestors.
232 bool onStack(BasicBlock *BB) {
233 auto Iter = find(BB);
234 return Iter != end() && Iter->second;
235 }
236 } State;
Taewook Ohd3f1ec92017-01-26 04:32:40 +0000237
David Callahanebcf9162016-12-13 16:42:18 +0000238 State.reserve(F.size());
239 // Iterate over blocks in depth-first pre-order and
240 // treat all edges to a block already seen as loop back edges
241 // and mark the branch live it if there is a back edge.
242 for (auto *BB: depth_first_ext(&F.getEntryBlock(), State)) {
243 TerminatorInst *Term = BB->getTerminator();
244 if (isLive(Term))
245 continue;
246
247 for (auto *Succ : successors(BB))
248 if (State.onStack(Succ)) {
249 // back edge....
250 markLive(Term);
251 break;
252 }
253 }
254 }
255
Tobias Grosserf818c332017-03-02 21:08:37 +0000256 // Mark blocks live if there is no path from the block to the
257 // return of the function or a successor for which this is true.
258 // This protects IDFCalculator which cannot handle such blocks.
259 for (auto &BBInfoPair : BlockInfo) {
260 auto &BBInfo = BBInfoPair.second;
261 if (BBInfo.terminatorIsLive())
262 continue;
263 auto *BB = BBInfo.BB;
264 if (!PDT.getNode(BB)) {
265 markLive(BBInfo.Terminator);
David Callahan012d1c02016-08-24 00:10:06 +0000266 continue;
267 }
Tobias Grosserf818c332017-03-02 21:08:37 +0000268 for (auto *Succ : successors(BB))
269 if (!PDT.getNode(Succ)) {
270 markLive(BBInfo.Terminator);
271 break;
272 }
273 }
Daniel Berlin03f69382017-02-28 22:57:50 +0000274
Tobias Grosserf818c332017-03-02 21:08:37 +0000275 // Mark blocks live if there is no path from the block to the
276 // return of the function or a successor for which this is true.
277 // This protects IDFCalculator which cannot handle such blocks.
278 for (auto &BBInfoPair : BlockInfo) {
279 auto &BBInfo = BBInfoPair.second;
280 if (BBInfo.terminatorIsLive())
281 continue;
282 auto *BB = BBInfo.BB;
283 if (!PDT.getNode(BB)) {
284 DEBUG(dbgs() << "Not post-dominated by return: " << BB->getName()
285 << '\n';);
286 markLive(BBInfo.Terminator);
287 continue;
288 }
289 for (auto *Succ : successors(BB))
290 if (!PDT.getNode(Succ)) {
291 DEBUG(dbgs() << "Successor not post-dominated by return: "
292 << BB->getName() << '\n';);
293 markLive(BBInfo.Terminator);
294 break;
295 }
David Callahan012d1c02016-08-24 00:10:06 +0000296 }
David Callahan947be0f2016-08-16 14:31:51 +0000297
298 // Treat the entry block as always live
299 auto *BB = &F.getEntryBlock();
300 auto &EntryInfo = BlockInfo[BB];
301 EntryInfo.Live = true;
302 if (EntryInfo.UnconditionalBranch)
303 markLive(EntryInfo.Terminator);
304
305 // Build initial collection of blocks with dead terminators
306 for (auto &BBInfo : BlockInfo)
307 if (!BBInfo.second.terminatorIsLive())
308 BlocksWithDeadTerminators.insert(BBInfo.second.BB);
David Callahan45e442e2016-08-05 19:38:11 +0000309}
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000310
David Callahan45e442e2016-08-05 19:38:11 +0000311bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) {
David Callahan45e442e2016-08-05 19:38:11 +0000312 // TODO -- use llvm::isInstructionTriviallyDead
David Callahan947be0f2016-08-16 14:31:51 +0000313 if (I.isEHPad() || I.mayHaveSideEffects()) {
David Callahan45e442e2016-08-05 19:38:11 +0000314 // Skip any value profile instrumentation calls if they are
315 // instrumenting constants.
David Callahan947be0f2016-08-16 14:31:51 +0000316 if (isInstrumentsConstant(I))
317 return false;
318 return true;
David Callahan45e442e2016-08-05 19:38:11 +0000319 }
David Callahan947be0f2016-08-16 14:31:51 +0000320 if (!isa<TerminatorInst>(I))
321 return false;
322 if (RemoveControlFlowFlag && (isa<BranchInst>(I) || isa<SwitchInst>(I)))
323 return false;
324 return true;
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000325}
326
Betul Buyukkurtbf8554c2016-04-13 18:52:19 +0000327// Check if this instruction is a runtime call for value profiling and
328// if it's instrumenting a constant.
David Callahan45e442e2016-08-05 19:38:11 +0000329bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) {
330 // TODO -- move this test into llvm::isInstructionTriviallyDead
Betul Buyukkurtbf8554c2016-04-13 18:52:19 +0000331 if (CallInst *CI = dyn_cast<CallInst>(&I))
332 if (Function *Callee = CI->getCalledFunction())
333 if (Callee->getName().equals(getInstrProfValueProfFuncName()))
334 if (isa<Constant>(CI->getArgOperand(0)))
335 return true;
336 return false;
337}
338
David Callahan45e442e2016-08-05 19:38:11 +0000339void AggressiveDeadCodeElimination::markLiveInstructions() {
Nadav Rotem465834c2012-07-24 10:51:42 +0000340
David Callahan947be0f2016-08-16 14:31:51 +0000341 // Propagate liveness backwards to operands.
342 do {
343 // Worklist holds newly discovered live instructions
344 // where we need to mark the inputs as live.
345 while (!Worklist.empty()) {
346 Instruction *LiveInst = Worklist.pop_back_val();
David Callahanc165a4e2016-09-19 23:17:58 +0000347 DEBUG(dbgs() << "work live: "; LiveInst->dump(););
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000348
David Callahan947be0f2016-08-16 14:31:51 +0000349 for (Use &OI : LiveInst->operands())
350 if (Instruction *Inst = dyn_cast<Instruction>(OI))
351 markLive(Inst);
David Callahanebcf9162016-12-13 16:42:18 +0000352
David Callahanc165a4e2016-09-19 23:17:58 +0000353 if (auto *PN = dyn_cast<PHINode>(LiveInst))
354 markPhiLive(PN);
Hal Finkel8626ed22015-02-15 15:51:25 +0000355 }
David Callahanebcf9162016-12-13 16:42:18 +0000356
357 // After data flow liveness has been identified, examine which branch
358 // decisions are required to determine live instructions are executed.
David Callahan947be0f2016-08-16 14:31:51 +0000359 markLiveBranchesFromControlDependences();
David Callahan012d1c02016-08-24 00:10:06 +0000360
David Callahan947be0f2016-08-16 14:31:51 +0000361 } while (!Worklist.empty());
David Callahan947be0f2016-08-16 14:31:51 +0000362}
363
364void AggressiveDeadCodeElimination::markLive(Instruction *I) {
365
366 auto &Info = InstInfo[I];
367 if (Info.Live)
368 return;
369
370 DEBUG(dbgs() << "mark live: "; I->dump());
371 Info.Live = true;
372 Worklist.push_back(I);
373
David Callahanebcf9162016-12-13 16:42:18 +0000374 // Collect the live debug info scopes attached to this instruction.
375 if (const DILocation *DL = I->getDebugLoc())
376 collectLiveScopes(*DL);
377
David Callahan947be0f2016-08-16 14:31:51 +0000378 // Mark the containing block live
379 auto &BBInfo = *Info.Block;
David Callahanebcf9162016-12-13 16:42:18 +0000380 if (BBInfo.Terminator == I) {
David Callahan947be0f2016-08-16 14:31:51 +0000381 BlocksWithDeadTerminators.erase(BBInfo.BB);
David Callahanebcf9162016-12-13 16:42:18 +0000382 // For live terminators, mark destination blocks
383 // live to preserve this control flow edges.
384 if (!BBInfo.UnconditionalBranch)
385 for (auto *BB : successors(I->getParent()))
386 markLive(BB);
387 }
388 markLive(BBInfo);
389}
390
391void AggressiveDeadCodeElimination::markLive(BlockInfoType &BBInfo) {
David Callahan947be0f2016-08-16 14:31:51 +0000392 if (BBInfo.Live)
393 return;
David Callahan947be0f2016-08-16 14:31:51 +0000394 DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n');
395 BBInfo.Live = true;
David Callahanc165a4e2016-09-19 23:17:58 +0000396 if (!BBInfo.CFLive) {
397 BBInfo.CFLive = true;
398 NewLiveBlocks.insert(BBInfo.BB);
399 }
David Callahan947be0f2016-08-16 14:31:51 +0000400
401 // Mark unconditional branches at the end of live
402 // blocks as live since there is no work to do for them later
David Callahanebcf9162016-12-13 16:42:18 +0000403 if (BBInfo.UnconditionalBranch)
David Callahan012d1c02016-08-24 00:10:06 +0000404 markLive(BBInfo.Terminator);
David Callahan45e442e2016-08-05 19:38:11 +0000405}
406
407void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) {
408 if (!AliveScopes.insert(&LS).second)
409 return;
David Callahan947be0f2016-08-16 14:31:51 +0000410
David Callahan45e442e2016-08-05 19:38:11 +0000411 if (isa<DISubprogram>(LS))
412 return;
David Callahan947be0f2016-08-16 14:31:51 +0000413
David Callahan45e442e2016-08-05 19:38:11 +0000414 // Tail-recurse through the scope chain.
415 collectLiveScopes(cast<DILocalScope>(*LS.getScope()));
416}
417
418void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) {
419 // Even though DILocations are not scopes, shove them into AliveScopes so we
420 // don't revisit them.
421 if (!AliveScopes.insert(&DL).second)
422 return;
David Callahan947be0f2016-08-16 14:31:51 +0000423
David Callahan45e442e2016-08-05 19:38:11 +0000424 // Collect live scopes from the scope chain.
425 collectLiveScopes(*DL.getScope());
David Callahan947be0f2016-08-16 14:31:51 +0000426
David Callahan45e442e2016-08-05 19:38:11 +0000427 // Tail-recurse through the inlined-at chain.
428 if (const DILocation *IA = DL.getInlinedAt())
429 collectLiveScopes(*IA);
430}
431
David Callahanc165a4e2016-09-19 23:17:58 +0000432void AggressiveDeadCodeElimination::markPhiLive(PHINode *PN) {
433 auto &Info = BlockInfo[PN->getParent()];
434 // Only need to check this once per block.
435 if (Info.HasLivePhiNodes)
436 return;
437 Info.HasLivePhiNodes = true;
438
439 // If a predecessor block is not live, mark it as control-flow live
440 // which will trigger marking live branches upon which
441 // that block is control dependent.
442 for (auto *PredBB : predecessors(Info.BB)) {
443 auto &Info = BlockInfo[PredBB];
444 if (!Info.CFLive) {
445 Info.CFLive = true;
446 NewLiveBlocks.insert(PredBB);
447 }
448 }
449}
450
David Callahan947be0f2016-08-16 14:31:51 +0000451void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() {
452
David Callahan012d1c02016-08-24 00:10:06 +0000453 if (BlocksWithDeadTerminators.empty())
454 return;
455
456 DEBUG({
457 dbgs() << "new live blocks:\n";
458 for (auto *BB : NewLiveBlocks)
459 dbgs() << "\t" << BB->getName() << '\n';
460 dbgs() << "dead terminator blocks:\n";
461 for (auto *BB : BlocksWithDeadTerminators)
462 dbgs() << "\t" << BB->getName() << '\n';
463 });
464
465 // The dominance frontier of a live block X in the reverse
466 // control graph is the set of blocks upon which X is control
467 // dependent. The following sequence computes the set of blocks
468 // which currently have dead terminators that are control
469 // dependence sources of a block which is in NewLiveBlocks.
470
471 SmallVector<BasicBlock *, 32> IDFBlocks;
472 ReverseIDFCalculator IDFs(PDT);
473 IDFs.setDefiningBlocks(NewLiveBlocks);
474 IDFs.setLiveInBlocks(BlocksWithDeadTerminators);
475 IDFs.calculate(IDFBlocks);
David Callahan947be0f2016-08-16 14:31:51 +0000476 NewLiveBlocks.clear();
David Callahan012d1c02016-08-24 00:10:06 +0000477
478 // Dead terminators which control live blocks are now marked live.
David Callahanebcf9162016-12-13 16:42:18 +0000479 for (auto *BB : IDFBlocks) {
David Callahan012d1c02016-08-24 00:10:06 +0000480 DEBUG(dbgs() << "live control in: " << BB->getName() << '\n');
481 markLive(BB->getTerminator());
482 }
David Callahan45e442e2016-08-05 19:38:11 +0000483}
484
David Callahanc165a4e2016-09-19 23:17:58 +0000485//===----------------------------------------------------------------------===//
486//
487// Routines to update the CFG and SSA information before removing dead code.
488//
489//===----------------------------------------------------------------------===//
David Callahan45e442e2016-08-05 19:38:11 +0000490bool AggressiveDeadCodeElimination::removeDeadInstructions() {
Nadav Rotem465834c2012-07-24 10:51:42 +0000491
David Callahanebcf9162016-12-13 16:42:18 +0000492 // Updates control and dataflow around dead blocks
493 updateDeadRegions();
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000494
David Callahanebcf9162016-12-13 16:42:18 +0000495 DEBUG({
496 for (Instruction &I : instructions(F)) {
497 // Check if the instruction is alive.
498 if (isLive(&I))
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000499 continue;
500
David Callahanebcf9162016-12-13 16:42:18 +0000501 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) {
502 // Check if the scope of this variable location is alive.
503 if (AliveScopes.count(DII->getDebugLoc()->getScope()))
504 continue;
505
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000506 // If intrinsic is pointing at a live SSA value, there may be an
507 // earlier optimization bug: if we know the location of the variable,
508 // why isn't the scope of the location alive?
509 if (Value *V = DII->getVariableLocation())
510 if (Instruction *II = dyn_cast<Instruction>(V))
David Callahan947be0f2016-08-16 14:31:51 +0000511 if (isLive(II))
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000512 dbgs() << "Dropping debug info for " << *DII << "\n";
David Callahanebcf9162016-12-13 16:42:18 +0000513 }
514 }
515 });
516
517 // The inverse of the live set is the dead set. These are those instructions
518 // that have no side effects and do not influence the control flow or return
519 // value of the function, and may therefore be deleted safely.
520 // NOTE: We reuse the Worklist vector here for memory efficiency.
521 for (Instruction &I : instructions(F)) {
522 // Check if the instruction is alive.
523 if (isLive(&I))
524 continue;
525
526 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) {
527 // Check if the scope of this variable location is alive.
528 if (AliveScopes.count(DII->getDebugLoc()->getScope()))
529 continue;
530
531 // Fallthrough and drop the intrinsic.
Chris Lattneracfd27d2001-09-09 22:26:47 +0000532 }
Duncan P. N. Exon Smithe8eb94a2016-03-29 22:57:12 +0000533
534 // Prepare to delete.
535 Worklist.push_back(&I);
536 I.dropAllReferences();
Hal Finkel92fb2d32015-02-15 15:51:23 +0000537 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000538
Hal Finkel92fb2d32015-02-15 15:51:23 +0000539 for (Instruction *&I : Worklist) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000540 ++NumRemoved;
Hal Finkel92fb2d32015-02-15 15:51:23 +0000541 I->eraseFromParent();
Chris Lattneracfd27d2001-09-09 22:26:47 +0000542 }
Devang Patel53b39b52008-11-11 00:54:10 +0000543
Hal Finkel75901292015-02-15 15:45:28 +0000544 return !Worklist.empty();
Chris Lattnerb28986f2001-06-30 06:39:11 +0000545}
Owen Anderson7686b552008-05-29 08:45:13 +0000546
David Callahanebcf9162016-12-13 16:42:18 +0000547// A dead region is the set of dead blocks with a common live post-dominator.
548void AggressiveDeadCodeElimination::updateDeadRegions() {
549
550 DEBUG({
551 dbgs() << "final dead terminator blocks: " << '\n';
552 for (auto *BB : BlocksWithDeadTerminators)
553 dbgs() << '\t' << BB->getName()
554 << (BlockInfo[BB].Live ? " LIVE\n" : "\n");
555 });
556
557 // Don't compute the post ordering unless we needed it.
558 bool HavePostOrder = false;
559
560 for (auto *BB : BlocksWithDeadTerminators) {
561 auto &Info = BlockInfo[BB];
562 if (Info.UnconditionalBranch) {
563 InstInfo[Info.Terminator].Live = true;
564 continue;
565 }
566
567 if (!HavePostOrder) {
568 computeReversePostOrder();
569 HavePostOrder = true;
570 }
571
572 // Add an unconditional branch to the successor closest to the
573 // end of the function which insures a path to the exit for each
574 // live edge.
575 BlockInfoType *PreferredSucc = nullptr;
576 for (auto *Succ : successors(BB)) {
577 auto *Info = &BlockInfo[Succ];
578 if (!PreferredSucc || PreferredSucc->PostOrder < Info->PostOrder)
579 PreferredSucc = Info;
580 }
581 assert((PreferredSucc && PreferredSucc->PostOrder > 0) &&
Tobias Grosser335b6bf2017-03-14 10:18:11 +0000582 "Failed to find safe successor for dead branch");
David Callahanebcf9162016-12-13 16:42:18 +0000583 bool First = true;
584 for (auto *Succ : successors(BB)) {
585 if (!First || Succ != PreferredSucc->BB)
586 Succ->removePredecessor(BB);
587 else
588 First = false;
589 }
590 makeUnconditional(BB, PreferredSucc->BB);
591 NumBranchesRemoved += 1;
592 }
593}
594
595// reverse top-sort order
596void AggressiveDeadCodeElimination::computeReversePostOrder() {
Taewook Ohd3f1ec92017-01-26 04:32:40 +0000597
Tobias Grosser335b6bf2017-03-14 10:18:11 +0000598 // This provides a post-order numbering of the reverse control flow graph
David Callahanebcf9162016-12-13 16:42:18 +0000599 // Note that it is incomplete in the presence of infinite loops but we don't
600 // need numbers blocks which don't reach the end of the functions since
601 // all branches in those blocks are forced live.
Taewook Ohd3f1ec92017-01-26 04:32:40 +0000602
Tobias Grosser335b6bf2017-03-14 10:18:11 +0000603 // For each block without successors, extend the DFS from the block
David Callahanebcf9162016-12-13 16:42:18 +0000604 // backward through the graph
605 SmallPtrSet<BasicBlock*, 16> Visited;
606 unsigned PostOrder = 0;
607 for (auto &BB : F) {
608 if (succ_begin(&BB) != succ_end(&BB))
609 continue;
610 for (BasicBlock *Block : inverse_post_order_ext(&BB,Visited))
611 BlockInfo[Block].PostOrder = PostOrder++;
612 }
613}
614
615void AggressiveDeadCodeElimination::makeUnconditional(BasicBlock *BB,
616 BasicBlock *Target) {
617 TerminatorInst *PredTerm = BB->getTerminator();
618 // Collect the live debug info scopes attached to this instruction.
619 if (const DILocation *DL = PredTerm->getDebugLoc())
620 collectLiveScopes(*DL);
621
622 // Just mark live an existing unconditional branch
623 if (isUnconditionalBranch(PredTerm)) {
624 PredTerm->setSuccessor(0, Target);
625 InstInfo[PredTerm].Live = true;
626 return;
627 }
628 DEBUG(dbgs() << "making unconditional " << BB->getName() << '\n');
629 NumBranchesRemoved += 1;
630 IRBuilder<> Builder(PredTerm);
631 auto *NewTerm = Builder.CreateBr(Target);
632 InstInfo[NewTerm].Live = true;
633 if (const DILocation *DL = PredTerm->getDebugLoc())
634 NewTerm->setDebugLoc(DL);
635}
636
David Callahan012d1c02016-08-24 00:10:06 +0000637//===----------------------------------------------------------------------===//
638//
639// Pass Manager integration code
640//
641//===----------------------------------------------------------------------===//
642PreservedAnalyses ADCEPass::run(Function &F, FunctionAnalysisManager &FAM) {
643 auto &PDT = FAM.getResult<PostDominatorTreeAnalysis>(F);
644 if (!AggressiveDeadCodeElimination(F, PDT).performDeadCodeElimination())
Davide Italiano688616f2016-05-31 17:39:39 +0000645 return PreservedAnalyses::all();
646
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000647 PreservedAnalyses PA;
648 PA.preserveSet<CFGAnalyses>();
Davide Italiano688616f2016-05-31 17:39:39 +0000649 PA.preserve<GlobalsAA>();
650 return PA;
Duncan Sands9e064a22008-05-29 14:38:23 +0000651}
Justin Bogner19b67992015-10-30 23:13:18 +0000652
653namespace {
654struct ADCELegacyPass : public FunctionPass {
655 static char ID; // Pass identification, replacement for typeid
656 ADCELegacyPass() : FunctionPass(ID) {
657 initializeADCELegacyPassPass(*PassRegistry::getPassRegistry());
658 }
659
David Callahancc5cd4d2016-08-03 04:28:39 +0000660 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000661 if (skipFunction(F))
Justin Bogner19b67992015-10-30 23:13:18 +0000662 return false;
David Callahan012d1c02016-08-24 00:10:06 +0000663 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
664 return AggressiveDeadCodeElimination(F, PDT).performDeadCodeElimination();
Justin Bogner19b67992015-10-30 23:13:18 +0000665 }
666
David Callahancc5cd4d2016-08-03 04:28:39 +0000667 void getAnalysisUsage(AnalysisUsage &AU) const override {
David Callahan012d1c02016-08-24 00:10:06 +0000668 AU.addRequired<PostDominatorTreeWrapperPass>();
David Callahanebcf9162016-12-13 16:42:18 +0000669 if (!RemoveControlFlowFlag)
670 AU.setPreservesCFG();
Justin Bogner19b67992015-10-30 23:13:18 +0000671 AU.addPreserved<GlobalsAAWrapperPass>();
672 }
673};
674}
675
676char ADCELegacyPass::ID = 0;
David Callahan012d1c02016-08-24 00:10:06 +0000677INITIALIZE_PASS_BEGIN(ADCELegacyPass, "adce",
678 "Aggressive Dead Code Elimination", false, false)
679INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
680INITIALIZE_PASS_END(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination",
681 false, false)
Justin Bogner19b67992015-10-30 23:13:18 +0000682
683FunctionPass *llvm::createAggressiveDCEPass() { return new ADCELegacyPass(); }