blob: 5fa43bda9d09072d58435a92e8d743785d9adebd [file] [log] [blame]
Dan Gohman5d5b8b12010-05-07 15:40:13 +00001//===-- Sink.cpp - Code Sinking -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass moves instructions into successor blocks, when possible, so that
11// they aren't executed on paths where their results aren't needed.
12//
13//===----------------------------------------------------------------------===//
14
Justin Bognerb9394902016-04-22 19:54:10 +000015#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5d5b8b12010-05-07 15:40:13 +000018#include "llvm/Analysis/LoopInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000019#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000020#include "llvm/IR/CFG.h"
Hal Finkel511fea72014-07-10 16:07:11 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
Mehdi Amini46a43552015-03-04 18:43:29 +000024#include "llvm/IR/Module.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)
Justin Bognerb9394902016-04-22 19:54:10 +000071 if (AA.getModRefInfo(S, Loc) & MRI_Mod)
Dan Gohman5d5b8b12010-05-07 15:40:13 +000072 return false;
73 }
74
David Majnemer8a1c45d2015-12-12 05:38:55 +000075 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst) || Inst->isEHPad() ||
76 Inst->mayThrow())
Dan Gohmanc3b4ea72010-11-11 16:20:28 +000077 return false;
78
Owen Andersond95b08a2015-10-09 18:06:13 +000079 // Convergent operations cannot be made control-dependent on additional
80 // values.
Owen Anderson15d18052015-06-01 17:20:31 +000081 if (auto CS = CallSite(Inst)) {
82 if (CS.hasFnAttr(Attribute::Convergent))
83 return false;
84 }
85
Dan Gohmanc3b4ea72010-11-11 16:20:28 +000086 return true;
Dan Gohman5d5b8b12010-05-07 15:40:13 +000087}
88
Duncan Sands339bb612012-05-31 08:09:49 +000089/// IsAcceptableTarget - Return true if it is possible to sink the instruction
90/// in the specified basic block.
Justin Bognerb9394902016-04-22 19:54:10 +000091static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
92 DominatorTree &DT, LoopInfo &LI) {
Duncan Sands339bb612012-05-31 08:09:49 +000093 assert(Inst && "Instruction to be sunk is null");
94 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotem465834c2012-07-24 10:51:42 +000095
Duncan Sands339bb612012-05-31 08:09:49 +000096 // It is not possible to sink an instruction into its own block. This can
97 // happen with loops.
98 if (Inst->getParent() == SuccToSinkTo)
99 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000100
David Majnemer8a1c45d2015-12-12 05:38:55 +0000101 // It's never legal to sink an instruction into a block which terminates in an
102 // EH-pad.
103 if (SuccToSinkTo->getTerminator()->isExceptional())
104 return false;
105
Nadav Rotem465834c2012-07-24 10:51:42 +0000106 // If the block has multiple predecessors, this would introduce computation
Duncan Sands339bb612012-05-31 08:09:49 +0000107 // on different code paths. We could split the critical edge, but for now we
108 // just punt.
109 // FIXME: Split critical edges if not backedges.
110 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
111 // We cannot sink a load across a critical edge - there may be stores in
112 // other code paths.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000113 if (!isSafeToSpeculativelyExecute(Inst))
Duncan Sands339bb612012-05-31 08:09:49 +0000114 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000115
Duncan Sands339bb612012-05-31 08:09:49 +0000116 // We don't want to sink across a critical edge if we don't dominate the
117 // successor. We could be introducing calculations to new code paths.
Justin Bognerb9394902016-04-22 19:54:10 +0000118 if (!DT.dominates(Inst->getParent(), SuccToSinkTo))
Duncan Sands339bb612012-05-31 08:09:49 +0000119 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000120
Duncan Sands339bb612012-05-31 08:09:49 +0000121 // Don't sink instructions into a loop.
Justin Bognerb9394902016-04-22 19:54:10 +0000122 Loop *succ = LI.getLoopFor(SuccToSinkTo);
123 Loop *cur = LI.getLoopFor(Inst->getParent());
Craig Topperf40110f2014-04-25 05:29:35 +0000124 if (succ != nullptr && succ != cur)
Duncan Sands339bb612012-05-31 08:09:49 +0000125 return false;
126 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000127
Duncan Sands339bb612012-05-31 08:09:49 +0000128 // Finally, check that all the uses of the instruction are actually
129 // dominated by the candidate
Justin Bognerb9394902016-04-22 19:54:10 +0000130 return AllUsesDominatedByBlock(Inst, SuccToSinkTo, DT);
Duncan Sands339bb612012-05-31 08:09:49 +0000131}
132
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000133/// SinkInstruction - Determine whether it is safe to sink the specified machine
134/// instruction out of its current block into a successor.
Justin Bognerb9394902016-04-22 19:54:10 +0000135static bool SinkInstruction(Instruction *Inst,
136 SmallPtrSetImpl<Instruction *> &Stores,
137 DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
Tom Stellardedfd81d2014-03-21 15:51:51 +0000138
139 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
140 // entry block are dynamically sized stack objects.
141 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
142 if (AI->isStaticAlloca())
143 return false;
144
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000145 // Check if it's safe to move the instruction.
146 if (!isSafeToMove(Inst, AA, Stores))
147 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000148
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000149 // FIXME: This should include support for sinking instructions within the
150 // block they are currently in to shorten the live ranges. We often get
151 // instructions sunk into the top of a large block, but it would be better to
152 // also sink them down before their first use in the block. This xform has to
153 // be careful not to *increase* register pressure though, e.g. sinking
154 // "x = y + z" down if it kills y and z would increase the live ranges of y
155 // and z and only shrink the live range of x.
Nadav Rotem465834c2012-07-24 10:51:42 +0000156
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000157 // SuccToSinkTo - This is the successor to sink this instruction to, once we
158 // decide.
Craig Topperf40110f2014-04-25 05:29:35 +0000159 BasicBlock *SuccToSinkTo = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000160
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000161 // Instructions can only be sunk if all their uses are in blocks
162 // dominated by one of the successors.
Duncan Sands339bb612012-05-31 08:09:49 +0000163 // Look at all the postdominators and see if we can sink it in one.
Justin Bognerb9394902016-04-22 19:54:10 +0000164 DomTreeNode *DTN = DT.getNode(Inst->getParent());
Nadav Rotem465834c2012-07-24 10:51:42 +0000165 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Craig Topperf40110f2014-04-25 05:29:35 +0000166 I != E && SuccToSinkTo == nullptr; ++I) {
Duncan Sands339bb612012-05-31 08:09:49 +0000167 BasicBlock *Candidate = (*I)->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000168 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
Justin Bognerb9394902016-04-22 19:54:10 +0000169 IsAcceptableTarget(Inst, Candidate, DT, LI))
Duncan Sands339bb612012-05-31 08:09:49 +0000170 SuccToSinkTo = Candidate;
171 }
172
Nadav Rotem465834c2012-07-24 10:51:42 +0000173 // If no suitable postdominator was found, look at all the successors and
Duncan Sands339bb612012-05-31 08:09:49 +0000174 // decide which one we should sink to, if any.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000175 for (succ_iterator I = succ_begin(Inst->getParent()),
176 E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
Justin Bognerb9394902016-04-22 19:54:10 +0000177 if (IsAcceptableTarget(Inst, *I, DT, LI))
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000178 SuccToSinkTo = *I;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000179 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000180
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000181 // If we couldn't find a block to sink to, ignore this instruction.
Craig Topperf40110f2014-04-25 05:29:35 +0000182 if (!SuccToSinkTo)
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000183 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000184
Duncan Sands339bb612012-05-31 08:09:49 +0000185 DEBUG(dbgs() << "Sink" << *Inst << " (";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000186 Inst->getParent()->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000187 dbgs() << " -> ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000188 SuccToSinkTo->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000189 dbgs() << ")\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000190
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000191 // Move the instruction.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000192 Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000193 return true;
194}
Justin Bogner82077c42016-04-22 19:54:04 +0000195
Justin Bognerb9394902016-04-22 19:54:10 +0000196static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI,
197 AAResults &AA) {
Justin Bogner82077c42016-04-22 19:54:04 +0000198 // Can't sink anything out of a block that has less than two successors.
199 if (BB.getTerminator()->getNumSuccessors() <= 1) return false;
200
201 // Don't bother sinking code out of unreachable blocks. In addition to being
202 // unprofitable, it can also lead to infinite looping, because in an
203 // unreachable loop there may be nowhere to stop.
Justin Bognerb9394902016-04-22 19:54:10 +0000204 if (!DT.isReachableFromEntry(&BB)) return false;
Justin Bogner82077c42016-04-22 19:54:04 +0000205
206 bool MadeChange = false;
207
208 // Walk the basic block bottom-up. Remember if we saw a store.
209 BasicBlock::iterator I = BB.end();
210 --I;
211 bool ProcessedBegin = false;
212 SmallPtrSet<Instruction *, 8> Stores;
213 do {
214 Instruction *Inst = &*I; // The instruction to sink.
215
216 // Predecrement I (if it's not begin) so that it isn't invalidated by
217 // sinking.
218 ProcessedBegin = I == BB.begin();
219 if (!ProcessedBegin)
220 --I;
221
222 if (isa<DbgInfoIntrinsic>(Inst))
223 continue;
224
Justin Bognerb9394902016-04-22 19:54:10 +0000225 if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
Justin Bogner82077c42016-04-22 19:54:04 +0000226 ++NumSunk;
227 MadeChange = true;
228 }
229
230 // If we just processed the first instruction in the block, we're done.
231 } while (!ProcessedBegin);
232
233 return MadeChange;
234}
235
Justin Bognerb9394902016-04-22 19:54:10 +0000236static bool iterativelySinkInstructions(Function &F, DominatorTree &DT,
237 LoopInfo &LI, AAResults &AA) {
Justin Bogner82077c42016-04-22 19:54:04 +0000238 bool MadeChange, EverMadeChange = false;
239
240 do {
241 MadeChange = false;
242 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
243 // Process all basic blocks.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000244 for (BasicBlock &I : F)
245 MadeChange |= ProcessBlock(I, DT, LI, AA);
Justin Bogner82077c42016-04-22 19:54:04 +0000246 EverMadeChange |= MadeChange;
247 NumSinkIter++;
248 } while (MadeChange);
249
250 return EverMadeChange;
251}
Justin Bognerb9394902016-04-22 19:54:10 +0000252
253PreservedAnalyses SinkingPass::run(Function &F, AnalysisManager<Function> &AM) {
254 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
255 auto &LI = AM.getResult<LoopAnalysis>(F);
256 auto &AA = AM.getResult<AAManager>(F);
257
258 if (!iterativelySinkInstructions(F, DT, LI, AA))
259 return PreservedAnalyses::all();
260
261 auto PA = PreservedAnalyses();
262 PA.preserve<DominatorTreeAnalysis>();
263 PA.preserve<LoopAnalysis>();
264 return PA;
265}
266
267namespace {
268 class SinkingLegacyPass : public FunctionPass {
269 public:
270 static char ID; // Pass identification
271 SinkingLegacyPass() : FunctionPass(ID) {
272 initializeSinkingLegacyPassPass(*PassRegistry::getPassRegistry());
273 }
274
275 bool runOnFunction(Function &F) override {
276 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
277 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
278 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
279
280 return iterativelySinkInstructions(F, DT, LI, AA);
281 }
282
283 void getAnalysisUsage(AnalysisUsage &AU) const override {
284 AU.setPreservesCFG();
285 FunctionPass::getAnalysisUsage(AU);
286 AU.addRequired<AAResultsWrapperPass>();
287 AU.addRequired<DominatorTreeWrapperPass>();
288 AU.addRequired<LoopInfoWrapperPass>();
289 AU.addPreserved<DominatorTreeWrapperPass>();
290 AU.addPreserved<LoopInfoWrapperPass>();
291 }
292 };
293} // end anonymous namespace
294
295char SinkingLegacyPass::ID = 0;
296INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
297INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
298INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
299INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
300INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
301
302FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }