blob: 8b916347999cd15ca367520950c399273e17a822 [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
Dan Gohman5d5b8b12010-05-07 15:40:13 +000015#include "llvm/Transforms/Scalar.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"
27using namespace llvm;
28
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "sink"
30
Dan Gohman5d5b8b12010-05-07 15:40:13 +000031STATISTIC(NumSunk, "Number of instructions sunk");
Duncan Sands339bb612012-05-31 08:09:49 +000032STATISTIC(NumSinkIter, "Number of sinking iterations");
Dan Gohman5d5b8b12010-05-07 15:40:13 +000033
34namespace {
35 class Sinking : public FunctionPass {
36 DominatorTree *DT;
37 LoopInfo *LI;
38 AliasAnalysis *AA;
39
40 public:
41 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +000042 Sinking() : FunctionPass(ID) {
43 initializeSinkingPass(*PassRegistry::getPassRegistry());
44 }
Nadav Rotem465834c2012-07-24 10:51:42 +000045
Craig Topper3e4c6972014-03-05 09:10:37 +000046 bool runOnFunction(Function &F) override;
Nadav Rotem465834c2012-07-24 10:51:42 +000047
Craig Topper3e4c6972014-03-05 09:10:37 +000048 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000049 AU.setPreservesCFG();
50 FunctionPass::getAnalysisUsage(AU);
Chandler Carruth7b560d42015-09-09 17:55:00 +000051 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +000052 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000053 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +000054 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000055 AU.addPreserved<LoopInfoWrapperPass>();
Dan Gohman5d5b8b12010-05-07 15:40:13 +000056 }
57 private:
58 bool ProcessBlock(BasicBlock &BB);
Craig Topper71b7b682014-08-21 05:55:13 +000059 bool SinkInstruction(Instruction *I, SmallPtrSetImpl<Instruction*> &Stores);
Dan Gohman5d5b8b12010-05-07 15:40:13 +000060 bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
Duncan Sands339bb612012-05-31 08:09:49 +000061 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
Dan Gohman5d5b8b12010-05-07 15:40:13 +000062 };
63} // end anonymous namespace
Nadav Rotem465834c2012-07-24 10:51:42 +000064
Dan Gohman5d5b8b12010-05-07 15:40:13 +000065char Sinking::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000066INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000067INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +000068INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +000069INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000070INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
Dan Gohman5d5b8b12010-05-07 15:40:13 +000071
72FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
73
74/// AllUsesDominatedByBlock - Return true if all uses of the specified value
75/// occur in blocks dominated by the specified block.
Nadav Rotem465834c2012-07-24 10:51:42 +000076bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
Dan Gohman5d5b8b12010-05-07 15:40:13 +000077 BasicBlock *BB) const {
78 // Ignoring debug uses is necessary so debug info doesn't affect the code.
79 // This may leave a referencing dbg_value in the original block, before
80 // the definition of the vreg. Dwarf generator handles this although the
81 // user might not get the right info at runtime.
Chandler Carruthcdf47882014-03-09 03:16:01 +000082 for (Use &U : Inst->uses()) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000083 // Determine the block of the use.
Chandler Carruthcdf47882014-03-09 03:16:01 +000084 Instruction *UseInst = cast<Instruction>(U.getUser());
Dan Gohman5d5b8b12010-05-07 15:40:13 +000085 BasicBlock *UseBlock = UseInst->getParent();
86 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
87 // PHI nodes use the operand in the predecessor block, not the block with
88 // the PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +000089 unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
Dan Gohman5d5b8b12010-05-07 15:40:13 +000090 UseBlock = PN->getIncomingBlock(Num);
91 }
92 // Check that it dominates.
93 if (!DT->dominates(BB, UseBlock))
94 return false;
95 }
96 return true;
97}
98
99bool Sinking::runOnFunction(Function &F) {
Chandler Carruth73523022014-01-13 13:07:17 +0000100 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000101 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000102 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000103
Duncan Sands339bb612012-05-31 08:09:49 +0000104 bool MadeChange, EverMadeChange = false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000105
Duncan Sands339bb612012-05-31 08:09:49 +0000106 do {
107 MadeChange = false;
108 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000109 // Process all basic blocks.
Nadav Rotem465834c2012-07-24 10:51:42 +0000110 for (Function::iterator I = F.begin(), E = F.end();
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000111 I != E; ++I)
112 MadeChange |= ProcessBlock(*I);
Duncan Sands339bb612012-05-31 08:09:49 +0000113 EverMadeChange |= MadeChange;
114 NumSinkIter++;
115 } while (MadeChange);
Nadav Rotem465834c2012-07-24 10:51:42 +0000116
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000117 return EverMadeChange;
118}
119
120bool Sinking::ProcessBlock(BasicBlock &BB) {
121 // Can't sink anything out of a block that has less than two successors.
122 if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
123
124 // Don't bother sinking code out of unreachable blocks. In addition to being
Nadav Rotem465834c2012-07-24 10:51:42 +0000125 // unprofitable, it can also lead to infinite looping, because in an
126 // unreachable loop there may be nowhere to stop.
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000127 if (!DT->isReachableFromEntry(&BB)) return false;
128
129 bool MadeChange = false;
130
131 // Walk the basic block bottom-up. Remember if we saw a store.
132 BasicBlock::iterator I = BB.end();
133 --I;
134 bool ProcessedBegin = false;
135 SmallPtrSet<Instruction *, 8> Stores;
136 do {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000137 Instruction *Inst = &*I; // The instruction to sink.
Nadav Rotem465834c2012-07-24 10:51:42 +0000138
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000139 // Predecrement I (if it's not begin) so that it isn't invalidated by
140 // sinking.
141 ProcessedBegin = I == BB.begin();
142 if (!ProcessedBegin)
143 --I;
144
145 if (isa<DbgInfoIntrinsic>(Inst))
146 continue;
147
148 if (SinkInstruction(Inst, Stores))
149 ++NumSunk, MadeChange = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000150
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000151 // If we just processed the first instruction in the block, we're done.
152 } while (!ProcessedBegin);
Nadav Rotem465834c2012-07-24 10:51:42 +0000153
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000154 return MadeChange;
155}
156
157static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
Craig Topper71b7b682014-08-21 05:55:13 +0000158 SmallPtrSetImpl<Instruction *> &Stores) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000159
Eli Friedman71f5c2f2011-09-01 21:21:24 +0000160 if (Inst->mayWriteToMemory()) {
161 Stores.insert(Inst);
162 return false;
163 }
164
165 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
Chandler Carruthac80dc72015-06-17 07:18:54 +0000166 MemoryLocation Loc = MemoryLocation::get(L);
Craig Topper46276792014-08-24 23:23:06 +0000167 for (Instruction *S : Stores)
Chandler Carruth194f59c2015-07-22 23:15:57 +0000168 if (AA->getModRefInfo(S, Loc) & MRI_Mod)
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000169 return false;
170 }
171
Dan Gohmanc3b4ea72010-11-11 16:20:28 +0000172 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
173 return false;
174
Owen Andersond95b08a2015-10-09 18:06:13 +0000175 // Convergent operations cannot be made control-dependent on additional
176 // values.
Owen Anderson15d18052015-06-01 17:20:31 +0000177 if (auto CS = CallSite(Inst)) {
178 if (CS.hasFnAttr(Attribute::Convergent))
179 return false;
180 }
181
Dan Gohmanc3b4ea72010-11-11 16:20:28 +0000182 return true;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000183}
184
Duncan Sands339bb612012-05-31 08:09:49 +0000185/// IsAcceptableTarget - Return true if it is possible to sink the instruction
186/// in the specified basic block.
Nadav Rotem465834c2012-07-24 10:51:42 +0000187bool Sinking::IsAcceptableTarget(Instruction *Inst,
188 BasicBlock *SuccToSinkTo) const {
Duncan Sands339bb612012-05-31 08:09:49 +0000189 assert(Inst && "Instruction to be sunk is null");
190 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotem465834c2012-07-24 10:51:42 +0000191
Duncan Sands339bb612012-05-31 08:09:49 +0000192 // It is not possible to sink an instruction into its own block. This can
193 // happen with loops.
194 if (Inst->getParent() == SuccToSinkTo)
195 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000196
197 // If the block has multiple predecessors, this would introduce computation
Duncan Sands339bb612012-05-31 08:09:49 +0000198 // on different code paths. We could split the critical edge, but for now we
199 // just punt.
200 // FIXME: Split critical edges if not backedges.
201 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
202 // We cannot sink a load across a critical edge - there may be stores in
203 // other code paths.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000204 if (!isSafeToSpeculativelyExecute(Inst))
Duncan Sands339bb612012-05-31 08:09:49 +0000205 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000206
Duncan Sands339bb612012-05-31 08:09:49 +0000207 // We don't want to sink across a critical edge if we don't dominate the
208 // successor. We could be introducing calculations to new code paths.
209 if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
210 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000211
Duncan Sands339bb612012-05-31 08:09:49 +0000212 // Don't sink instructions into a loop.
Nadav Rotem465834c2012-07-24 10:51:42 +0000213 Loop *succ = LI->getLoopFor(SuccToSinkTo);
214 Loop *cur = LI->getLoopFor(Inst->getParent());
Craig Topperf40110f2014-04-25 05:29:35 +0000215 if (succ != nullptr && succ != cur)
Duncan Sands339bb612012-05-31 08:09:49 +0000216 return false;
217 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000218
Duncan Sands339bb612012-05-31 08:09:49 +0000219 // Finally, check that all the uses of the instruction are actually
220 // dominated by the candidate
221 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
222}
223
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000224/// SinkInstruction - Determine whether it is safe to sink the specified machine
225/// instruction out of its current block into a successor.
226bool Sinking::SinkInstruction(Instruction *Inst,
Craig Topper71b7b682014-08-21 05:55:13 +0000227 SmallPtrSetImpl<Instruction *> &Stores) {
Tom Stellardedfd81d2014-03-21 15:51:51 +0000228
229 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
230 // entry block are dynamically sized stack objects.
231 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
232 if (AI->isStaticAlloca())
233 return false;
234
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000235 // Check if it's safe to move the instruction.
236 if (!isSafeToMove(Inst, AA, Stores))
237 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000238
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000239 // FIXME: This should include support for sinking instructions within the
240 // block they are currently in to shorten the live ranges. We often get
241 // instructions sunk into the top of a large block, but it would be better to
242 // also sink them down before their first use in the block. This xform has to
243 // be careful not to *increase* register pressure though, e.g. sinking
244 // "x = y + z" down if it kills y and z would increase the live ranges of y
245 // and z and only shrink the live range of x.
Nadav Rotem465834c2012-07-24 10:51:42 +0000246
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000247 // SuccToSinkTo - This is the successor to sink this instruction to, once we
248 // decide.
Craig Topperf40110f2014-04-25 05:29:35 +0000249 BasicBlock *SuccToSinkTo = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000250
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000251 // Instructions can only be sunk if all their uses are in blocks
252 // dominated by one of the successors.
Duncan Sands339bb612012-05-31 08:09:49 +0000253 // Look at all the postdominators and see if we can sink it in one.
254 DomTreeNode *DTN = DT->getNode(Inst->getParent());
Nadav Rotem465834c2012-07-24 10:51:42 +0000255 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Craig Topperf40110f2014-04-25 05:29:35 +0000256 I != E && SuccToSinkTo == nullptr; ++I) {
Duncan Sands339bb612012-05-31 08:09:49 +0000257 BasicBlock *Candidate = (*I)->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000258 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
Duncan Sands339bb612012-05-31 08:09:49 +0000259 IsAcceptableTarget(Inst, Candidate))
260 SuccToSinkTo = Candidate;
261 }
262
Nadav Rotem465834c2012-07-24 10:51:42 +0000263 // If no suitable postdominator was found, look at all the successors and
Duncan Sands339bb612012-05-31 08:09:49 +0000264 // decide which one we should sink to, if any.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000265 for (succ_iterator I = succ_begin(Inst->getParent()),
266 E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
267 if (IsAcceptableTarget(Inst, *I))
268 SuccToSinkTo = *I;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000269 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000270
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000271 // If we couldn't find a block to sink to, ignore this instruction.
Craig Topperf40110f2014-04-25 05:29:35 +0000272 if (!SuccToSinkTo)
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000273 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000274
Duncan Sands339bb612012-05-31 08:09:49 +0000275 DEBUG(dbgs() << "Sink" << *Inst << " (";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000276 Inst->getParent()->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000277 dbgs() << " -> ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000278 SuccToSinkTo->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000279 dbgs() << ")\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000280
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000281 // Move the instruction.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000282 Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000283 return true;
284}