blob: 677d86f8c7b48182e22d79018d8804fc118e9a51 [file] [log] [blame]
Dan Gohman5d5b8b12010-05-07 15:40:13 +00001//===-- Sink.cpp - Code Sinking -------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dan Gohman5d5b8b12010-05-07 15:40:13 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass moves instructions into successor blocks, when possible, so that
10// they aren't executed on paths where their results aren't needed.
11//
12//===----------------------------------------------------------------------===//
13
Justin Bognerb9394902016-04-22 19:54:10 +000014#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
16#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5d5b8b12010-05-07 15:40:13 +000017#include "llvm/Analysis/LoopInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000018#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000019#include "llvm/IR/CFG.h"
Hal Finkel511fea72014-07-10 16:07:11 +000020#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000021#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/IntrinsicInst.h"
Mehdi Amini46a43552015-03-04 18:43:29 +000023#include "llvm/IR/Module.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080024#include "llvm/InitializePasses.h"
Dan Gohman5d5b8b12010-05-07 15:40:13 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/raw_ostream.h"
Justin Bognerb9394902016-04-22 19:54:10 +000027#include "llvm/Transforms/Scalar.h"
Dan Gohman5d5b8b12010-05-07 15:40:13 +000028using namespace llvm;
29
Chandler Carruth964daaa2014-04-22 02:55:47 +000030#define DEBUG_TYPE "sink"
31
Dan Gohman5d5b8b12010-05-07 15:40:13 +000032STATISTIC(NumSunk, "Number of instructions sunk");
Duncan Sands339bb612012-05-31 08:09:49 +000033STATISTIC(NumSinkIter, "Number of sinking iterations");
Dan Gohman5d5b8b12010-05-07 15:40:13 +000034
Dan Gohman5d5b8b12010-05-07 15:40:13 +000035/// AllUsesDominatedByBlock - Return true if all uses of the specified value
36/// occur in blocks dominated by the specified block.
Justin Bognerb9394902016-04-22 19:54:10 +000037static bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB,
38 DominatorTree &DT) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000039 // Ignoring debug uses is necessary so debug info doesn't affect the code.
40 // This may leave a referencing dbg_value in the original block, before
41 // the definition of the vreg. Dwarf generator handles this although the
42 // user might not get the right info at runtime.
Chandler Carruthcdf47882014-03-09 03:16:01 +000043 for (Use &U : Inst->uses()) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000044 // Determine the block of the use.
Chandler Carruthcdf47882014-03-09 03:16:01 +000045 Instruction *UseInst = cast<Instruction>(U.getUser());
Dan Gohman5d5b8b12010-05-07 15:40:13 +000046 BasicBlock *UseBlock = UseInst->getParent();
47 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
48 // PHI nodes use the operand in the predecessor block, not the block with
49 // the PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +000050 unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
Dan Gohman5d5b8b12010-05-07 15:40:13 +000051 UseBlock = PN->getIncomingBlock(Num);
52 }
53 // Check that it dominates.
Justin Bognerb9394902016-04-22 19:54:10 +000054 if (!DT.dominates(BB, UseBlock))
Dan Gohman5d5b8b12010-05-07 15:40:13 +000055 return false;
56 }
57 return true;
58}
59
Justin Bognerb9394902016-04-22 19:54:10 +000060static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA,
Craig Topper71b7b682014-08-21 05:55:13 +000061 SmallPtrSetImpl<Instruction *> &Stores) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000062
Eli Friedman71f5c2f2011-09-01 21:21:24 +000063 if (Inst->mayWriteToMemory()) {
64 Stores.insert(Inst);
65 return false;
66 }
67
68 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
Chandler Carruthac80dc72015-06-17 07:18:54 +000069 MemoryLocation Loc = MemoryLocation::get(L);
Craig Topper46276792014-08-24 23:23:06 +000070 for (Instruction *S : Stores)
Alina Sbirlea63d22502017-12-05 20:12:23 +000071 if (isModSet(AA.getModRefInfo(S, Loc)))
Dan Gohman5d5b8b12010-05-07 15:40:13 +000072 return false;
73 }
74
Chandler Carruth9ae926b2018-08-26 09:51:22 +000075 if (Inst->isTerminator() || isa<PHINode>(Inst) || Inst->isEHPad() ||
David Majnemer8a1c45d2015-12-12 05:38:55 +000076 Inst->mayThrow())
Dan Gohmanc3b4ea72010-11-11 16:20:28 +000077 return false;
78
Chandler Carruth363ac682019-01-07 05:42:51 +000079 if (auto *Call = dyn_cast<CallBase>(Inst)) {
Nicolai Haehnle889a20c2016-07-11 14:11:51 +000080 // Convergent operations cannot be made control-dependent on additional
81 // values.
Matt Arsenault9b0b6262019-10-27 19:37:45 -070082 if (Call->isConvergent())
Owen Anderson15d18052015-06-01 17:20:31 +000083 return false;
Nicolai Haehnle889a20c2016-07-11 14:11:51 +000084
85 for (Instruction *S : Stores)
Chandler Carruth363ac682019-01-07 05:42:51 +000086 if (isModSet(AA.getModRefInfo(S, Call)))
Nicolai Haehnle889a20c2016-07-11 14:11:51 +000087 return false;
Owen Anderson15d18052015-06-01 17:20:31 +000088 }
89
Dan Gohmanc3b4ea72010-11-11 16:20:28 +000090 return true;
Dan Gohman5d5b8b12010-05-07 15:40:13 +000091}
92
Duncan Sands339bb612012-05-31 08:09:49 +000093/// IsAcceptableTarget - Return true if it is possible to sink the instruction
94/// in the specified basic block.
Justin Bognerb9394902016-04-22 19:54:10 +000095static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
96 DominatorTree &DT, LoopInfo &LI) {
Duncan Sands339bb612012-05-31 08:09:49 +000097 assert(Inst && "Instruction to be sunk is null");
98 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotem465834c2012-07-24 10:51:42 +000099
Duncan Sands339bb612012-05-31 08:09:49 +0000100 // It is not possible to sink an instruction into its own block. This can
101 // happen with loops.
102 if (Inst->getParent() == SuccToSinkTo)
103 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000104
David Majnemer8a1c45d2015-12-12 05:38:55 +0000105 // It's never legal to sink an instruction into a block which terminates in an
106 // EH-pad.
Chandler Carruth698fbe72018-08-26 08:56:42 +0000107 if (SuccToSinkTo->getTerminator()->isExceptionalTerminator())
David Majnemer8a1c45d2015-12-12 05:38:55 +0000108 return false;
109
Nadav Rotem465834c2012-07-24 10:51:42 +0000110 // If the block has multiple predecessors, this would introduce computation
Duncan Sands339bb612012-05-31 08:09:49 +0000111 // on different code paths. We could split the critical edge, but for now we
112 // just punt.
113 // FIXME: Split critical edges if not backedges.
114 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
115 // We cannot sink a load across a critical edge - there may be stores in
116 // other code paths.
Fiona Glaserefe6a842018-01-11 21:28:57 +0000117 if (Inst->mayReadFromMemory())
Duncan Sands339bb612012-05-31 08:09:49 +0000118 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000119
Duncan Sands339bb612012-05-31 08:09:49 +0000120 // We don't want to sink across a critical edge if we don't dominate the
121 // successor. We could be introducing calculations to new code paths.
Justin Bognerb9394902016-04-22 19:54:10 +0000122 if (!DT.dominates(Inst->getParent(), SuccToSinkTo))
Duncan Sands339bb612012-05-31 08:09:49 +0000123 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000124
Duncan Sands339bb612012-05-31 08:09:49 +0000125 // Don't sink instructions into a loop.
Justin Bognerb9394902016-04-22 19:54:10 +0000126 Loop *succ = LI.getLoopFor(SuccToSinkTo);
127 Loop *cur = LI.getLoopFor(Inst->getParent());
Craig Topperf40110f2014-04-25 05:29:35 +0000128 if (succ != nullptr && succ != cur)
Duncan Sands339bb612012-05-31 08:09:49 +0000129 return false;
130 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000131
Duncan Sands339bb612012-05-31 08:09:49 +0000132 // Finally, check that all the uses of the instruction are actually
133 // dominated by the candidate
Justin Bognerb9394902016-04-22 19:54:10 +0000134 return AllUsesDominatedByBlock(Inst, SuccToSinkTo, DT);
Duncan Sands339bb612012-05-31 08:09:49 +0000135}
136
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000137/// SinkInstruction - Determine whether it is safe to sink the specified machine
138/// instruction out of its current block into a successor.
Justin Bognerb9394902016-04-22 19:54:10 +0000139static bool SinkInstruction(Instruction *Inst,
140 SmallPtrSetImpl<Instruction *> &Stores,
141 DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
Tom Stellardedfd81d2014-03-21 15:51:51 +0000142
143 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
144 // entry block are dynamically sized stack objects.
145 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
146 if (AI->isStaticAlloca())
147 return false;
148
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000149 // Check if it's safe to move the instruction.
150 if (!isSafeToMove(Inst, AA, Stores))
151 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000152
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000153 // FIXME: This should include support for sinking instructions within the
154 // block they are currently in to shorten the live ranges. We often get
155 // instructions sunk into the top of a large block, but it would be better to
156 // also sink them down before their first use in the block. This xform has to
157 // be careful not to *increase* register pressure though, e.g. sinking
158 // "x = y + z" down if it kills y and z would increase the live ranges of y
159 // and z and only shrink the live range of x.
Nadav Rotem465834c2012-07-24 10:51:42 +0000160
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000161 // SuccToSinkTo - This is the successor to sink this instruction to, once we
162 // decide.
Craig Topperf40110f2014-04-25 05:29:35 +0000163 BasicBlock *SuccToSinkTo = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000164
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000165 // Instructions can only be sunk if all their uses are in blocks
166 // dominated by one of the successors.
Xin Tongcbf04d92017-03-20 00:30:19 +0000167 // Look at all the dominated blocks and see if we can sink it in one.
Justin Bognerb9394902016-04-22 19:54:10 +0000168 DomTreeNode *DTN = DT.getNode(Inst->getParent());
Nadav Rotem465834c2012-07-24 10:51:42 +0000169 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Craig Topperf40110f2014-04-25 05:29:35 +0000170 I != E && SuccToSinkTo == nullptr; ++I) {
Duncan Sands339bb612012-05-31 08:09:49 +0000171 BasicBlock *Candidate = (*I)->getBlock();
Xin Tongcbf04d92017-03-20 00:30:19 +0000172 // A node always immediate-dominates its children on the dominator
173 // tree.
174 if (IsAcceptableTarget(Inst, Candidate, DT, LI))
Duncan Sands339bb612012-05-31 08:09:49 +0000175 SuccToSinkTo = Candidate;
176 }
177
Nadav Rotem465834c2012-07-24 10:51:42 +0000178 // If no suitable postdominator was found, look at all the successors and
Duncan Sands339bb612012-05-31 08:09:49 +0000179 // decide which one we should sink to, if any.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000180 for (succ_iterator I = succ_begin(Inst->getParent()),
181 E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
Justin Bognerb9394902016-04-22 19:54:10 +0000182 if (IsAcceptableTarget(Inst, *I, DT, LI))
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000183 SuccToSinkTo = *I;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000184 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000185
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000186 // If we couldn't find a block to sink to, ignore this instruction.
Craig Topperf40110f2014-04-25 05:29:35 +0000187 if (!SuccToSinkTo)
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000188 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000189
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000190 LLVM_DEBUG(dbgs() << "Sink" << *Inst << " (";
191 Inst->getParent()->printAsOperand(dbgs(), false); dbgs() << " -> ";
192 SuccToSinkTo->printAsOperand(dbgs(), false); dbgs() << ")\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000193
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000194 // Move the instruction.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000195 Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000196 return true;
197}
Justin Bogner82077c42016-04-22 19:54:04 +0000198
Justin Bognerb9394902016-04-22 19:54:10 +0000199static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI,
200 AAResults &AA) {
Justin Bogner82077c42016-04-22 19:54:04 +0000201 // Can't sink anything out of a block that has less than two successors.
202 if (BB.getTerminator()->getNumSuccessors() <= 1) return false;
203
204 // Don't bother sinking code out of unreachable blocks. In addition to being
205 // unprofitable, it can also lead to infinite looping, because in an
206 // unreachable loop there may be nowhere to stop.
Justin Bognerb9394902016-04-22 19:54:10 +0000207 if (!DT.isReachableFromEntry(&BB)) return false;
Justin Bogner82077c42016-04-22 19:54:04 +0000208
209 bool MadeChange = false;
210
211 // Walk the basic block bottom-up. Remember if we saw a store.
212 BasicBlock::iterator I = BB.end();
213 --I;
214 bool ProcessedBegin = false;
215 SmallPtrSet<Instruction *, 8> Stores;
216 do {
217 Instruction *Inst = &*I; // The instruction to sink.
218
219 // Predecrement I (if it's not begin) so that it isn't invalidated by
220 // sinking.
221 ProcessedBegin = I == BB.begin();
222 if (!ProcessedBegin)
223 --I;
224
225 if (isa<DbgInfoIntrinsic>(Inst))
226 continue;
227
Justin Bognerb9394902016-04-22 19:54:10 +0000228 if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
Justin Bogner82077c42016-04-22 19:54:04 +0000229 ++NumSunk;
230 MadeChange = true;
231 }
232
233 // If we just processed the first instruction in the block, we're done.
234 } while (!ProcessedBegin);
235
236 return MadeChange;
237}
238
Justin Bognerb9394902016-04-22 19:54:10 +0000239static bool iterativelySinkInstructions(Function &F, DominatorTree &DT,
240 LoopInfo &LI, AAResults &AA) {
Justin Bogner82077c42016-04-22 19:54:04 +0000241 bool MadeChange, EverMadeChange = false;
242
243 do {
244 MadeChange = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000245 LLVM_DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
Justin Bogner82077c42016-04-22 19:54:04 +0000246 // Process all basic blocks.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000247 for (BasicBlock &I : F)
248 MadeChange |= ProcessBlock(I, DT, LI, AA);
Justin Bogner82077c42016-04-22 19:54:04 +0000249 EverMadeChange |= MadeChange;
250 NumSinkIter++;
251 } while (MadeChange);
252
253 return EverMadeChange;
254}
Justin Bognerb9394902016-04-22 19:54:10 +0000255
Sean Silva36e0d012016-08-09 00:28:15 +0000256PreservedAnalyses SinkingPass::run(Function &F, FunctionAnalysisManager &AM) {
Justin Bognerb9394902016-04-22 19:54:10 +0000257 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
258 auto &LI = AM.getResult<LoopAnalysis>(F);
259 auto &AA = AM.getResult<AAManager>(F);
260
261 if (!iterativelySinkInstructions(F, DT, LI, AA))
262 return PreservedAnalyses::all();
263
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000264 PreservedAnalyses PA;
265 PA.preserveSet<CFGAnalyses>();
Justin Bognerb9394902016-04-22 19:54:10 +0000266 return PA;
267}
268
269namespace {
270 class SinkingLegacyPass : public FunctionPass {
271 public:
272 static char ID; // Pass identification
273 SinkingLegacyPass() : FunctionPass(ID) {
274 initializeSinkingLegacyPassPass(*PassRegistry::getPassRegistry());
275 }
276
277 bool runOnFunction(Function &F) override {
278 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
279 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
280 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
281
282 return iterativelySinkInstructions(F, DT, LI, AA);
283 }
284
285 void getAnalysisUsage(AnalysisUsage &AU) const override {
286 AU.setPreservesCFG();
287 FunctionPass::getAnalysisUsage(AU);
288 AU.addRequired<AAResultsWrapperPass>();
289 AU.addRequired<DominatorTreeWrapperPass>();
290 AU.addRequired<LoopInfoWrapperPass>();
291 AU.addPreserved<DominatorTreeWrapperPass>();
292 AU.addPreserved<LoopInfoWrapperPass>();
293 }
294 };
295} // end anonymous namespace
296
297char SinkingLegacyPass::ID = 0;
298INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
299INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
300INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
301INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
302INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
303
304FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }