blob: 482c33aa6e0bf6a866fe10a82a02262d1d5565de [file] [log] [blame]
Dan Gohman28a193e2010-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 Gohman28a193e2010-05-07 15:40:13 +000015#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman28a193e2010-05-07 15:40:13 +000018#include "llvm/Analysis/LoopInfo.h"
Dan Gohmanf0426602011-12-14 23:49:11 +000019#include "llvm/Analysis/ValueTracking.h"
Stephen Hines36b56882014-04-23 16:57:46 -070020#include "llvm/IR/CFG.h"
21#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/IntrinsicInst.h"
Dan Gohman28a193e2010-05-07 15:40:13 +000023#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_ostream.h"
25using namespace llvm;
26
Stephen Hinesdce4a402014-05-29 02:49:00 -070027#define DEBUG_TYPE "sink"
28
Dan Gohman28a193e2010-05-07 15:40:13 +000029STATISTIC(NumSunk, "Number of instructions sunk");
Duncan Sands53b41772012-05-31 08:09:49 +000030STATISTIC(NumSinkIter, "Number of sinking iterations");
Dan Gohman28a193e2010-05-07 15:40:13 +000031
32namespace {
33 class Sinking : public FunctionPass {
34 DominatorTree *DT;
35 LoopInfo *LI;
36 AliasAnalysis *AA;
37
38 public:
39 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000040 Sinking() : FunctionPass(ID) {
41 initializeSinkingPass(*PassRegistry::getPassRegistry());
42 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000043
Stephen Hines36b56882014-04-23 16:57:46 -070044 bool runOnFunction(Function &F) override;
Nadav Rotema94d6e82012-07-24 10:51:42 +000045
Stephen Hines36b56882014-04-23 16:57:46 -070046 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman28a193e2010-05-07 15:40:13 +000047 AU.setPreservesCFG();
48 FunctionPass::getAnalysisUsage(AU);
49 AU.addRequired<AliasAnalysis>();
Stephen Hines36b56882014-04-23 16:57:46 -070050 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman28a193e2010-05-07 15:40:13 +000051 AU.addRequired<LoopInfo>();
Stephen Hines36b56882014-04-23 16:57:46 -070052 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohman28a193e2010-05-07 15:40:13 +000053 AU.addPreserved<LoopInfo>();
54 }
55 private:
56 bool ProcessBlock(BasicBlock &BB);
57 bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores);
58 bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
Duncan Sands53b41772012-05-31 08:09:49 +000059 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
Dan Gohman28a193e2010-05-07 15:40:13 +000060 };
61} // end anonymous namespace
Nadav Rotema94d6e82012-07-24 10:51:42 +000062
Dan Gohman28a193e2010-05-07 15:40:13 +000063char Sinking::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000064INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
65INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Stephen Hines36b56882014-04-23 16:57:46 -070066INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson2ab36d32010-10-12 19:48:12 +000067INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
68INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
Dan Gohman28a193e2010-05-07 15:40:13 +000069
70FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
71
72/// AllUsesDominatedByBlock - Return true if all uses of the specified value
73/// occur in blocks dominated by the specified block.
Nadav Rotema94d6e82012-07-24 10:51:42 +000074bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
Dan Gohman28a193e2010-05-07 15:40:13 +000075 BasicBlock *BB) const {
76 // Ignoring debug uses is necessary so debug info doesn't affect the code.
77 // This may leave a referencing dbg_value in the original block, before
78 // the definition of the vreg. Dwarf generator handles this although the
79 // user might not get the right info at runtime.
Stephen Hines36b56882014-04-23 16:57:46 -070080 for (Use &U : Inst->uses()) {
Dan Gohman28a193e2010-05-07 15:40:13 +000081 // Determine the block of the use.
Stephen Hines36b56882014-04-23 16:57:46 -070082 Instruction *UseInst = cast<Instruction>(U.getUser());
Dan Gohman28a193e2010-05-07 15:40:13 +000083 BasicBlock *UseBlock = UseInst->getParent();
84 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
85 // PHI nodes use the operand in the predecessor block, not the block with
86 // the PHI.
Stephen Hines36b56882014-04-23 16:57:46 -070087 unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
Dan Gohman28a193e2010-05-07 15:40:13 +000088 UseBlock = PN->getIncomingBlock(Num);
89 }
90 // Check that it dominates.
91 if (!DT->dominates(BB, UseBlock))
92 return false;
93 }
94 return true;
95}
96
97bool Sinking::runOnFunction(Function &F) {
Stephen Hines36b56882014-04-23 16:57:46 -070098 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Dan Gohman28a193e2010-05-07 15:40:13 +000099 LI = &getAnalysis<LoopInfo>();
100 AA = &getAnalysis<AliasAnalysis>();
101
Duncan Sands53b41772012-05-31 08:09:49 +0000102 bool MadeChange, EverMadeChange = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000103
Duncan Sands53b41772012-05-31 08:09:49 +0000104 do {
105 MadeChange = false;
106 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
Dan Gohman28a193e2010-05-07 15:40:13 +0000107 // Process all basic blocks.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000108 for (Function::iterator I = F.begin(), E = F.end();
Dan Gohman28a193e2010-05-07 15:40:13 +0000109 I != E; ++I)
110 MadeChange |= ProcessBlock(*I);
Duncan Sands53b41772012-05-31 08:09:49 +0000111 EverMadeChange |= MadeChange;
112 NumSinkIter++;
113 } while (MadeChange);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000114
Dan Gohman28a193e2010-05-07 15:40:13 +0000115 return EverMadeChange;
116}
117
118bool Sinking::ProcessBlock(BasicBlock &BB) {
119 // Can't sink anything out of a block that has less than two successors.
120 if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
121
122 // Don't bother sinking code out of unreachable blocks. In addition to being
Nadav Rotema94d6e82012-07-24 10:51:42 +0000123 // unprofitable, it can also lead to infinite looping, because in an
124 // unreachable loop there may be nowhere to stop.
Dan Gohman28a193e2010-05-07 15:40:13 +0000125 if (!DT->isReachableFromEntry(&BB)) return false;
126
127 bool MadeChange = false;
128
129 // Walk the basic block bottom-up. Remember if we saw a store.
130 BasicBlock::iterator I = BB.end();
131 --I;
132 bool ProcessedBegin = false;
133 SmallPtrSet<Instruction *, 8> Stores;
134 do {
135 Instruction *Inst = I; // The instruction to sink.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000136
Dan Gohman28a193e2010-05-07 15:40:13 +0000137 // Predecrement I (if it's not begin) so that it isn't invalidated by
138 // sinking.
139 ProcessedBegin = I == BB.begin();
140 if (!ProcessedBegin)
141 --I;
142
143 if (isa<DbgInfoIntrinsic>(Inst))
144 continue;
145
146 if (SinkInstruction(Inst, Stores))
147 ++NumSunk, MadeChange = true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000148
Dan Gohman28a193e2010-05-07 15:40:13 +0000149 // If we just processed the first instruction in the block, we're done.
150 } while (!ProcessedBegin);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000151
Dan Gohman28a193e2010-05-07 15:40:13 +0000152 return MadeChange;
153}
154
155static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
156 SmallPtrSet<Instruction *, 8> &Stores) {
Dan Gohman28a193e2010-05-07 15:40:13 +0000157
Eli Friedman86b5db82011-09-01 21:21:24 +0000158 if (Inst->mayWriteToMemory()) {
159 Stores.insert(Inst);
160 return false;
161 }
162
163 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
Dan Gohman6d8eb152010-11-11 21:50:19 +0000164 AliasAnalysis::Location Loc = AA->getLocation(L);
Dan Gohman28a193e2010-05-07 15:40:13 +0000165 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
166 E = Stores.end(); I != E; ++I)
Dan Gohman5aae3dc2010-11-11 16:21:47 +0000167 if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
Dan Gohman28a193e2010-05-07 15:40:13 +0000168 return false;
169 }
170
Dan Gohman2c71f182010-11-11 16:20:28 +0000171 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
172 return false;
173
174 return true;
Dan Gohman28a193e2010-05-07 15:40:13 +0000175}
176
Duncan Sands53b41772012-05-31 08:09:49 +0000177/// IsAcceptableTarget - Return true if it is possible to sink the instruction
178/// in the specified basic block.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000179bool Sinking::IsAcceptableTarget(Instruction *Inst,
180 BasicBlock *SuccToSinkTo) const {
Duncan Sands53b41772012-05-31 08:09:49 +0000181 assert(Inst && "Instruction to be sunk is null");
182 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000183
Duncan Sands53b41772012-05-31 08:09:49 +0000184 // It is not possible to sink an instruction into its own block. This can
185 // happen with loops.
186 if (Inst->getParent() == SuccToSinkTo)
187 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000188
189 // If the block has multiple predecessors, this would introduce computation
Duncan Sands53b41772012-05-31 08:09:49 +0000190 // on different code paths. We could split the critical edge, but for now we
191 // just punt.
192 // FIXME: Split critical edges if not backedges.
193 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
194 // We cannot sink a load across a critical edge - there may be stores in
195 // other code paths.
196 if (!isSafeToSpeculativelyExecute(Inst))
197 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000198
Duncan Sands53b41772012-05-31 08:09:49 +0000199 // We don't want to sink across a critical edge if we don't dominate the
200 // successor. We could be introducing calculations to new code paths.
201 if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
202 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000203
Duncan Sands53b41772012-05-31 08:09:49 +0000204 // Don't sink instructions into a loop.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000205 Loop *succ = LI->getLoopFor(SuccToSinkTo);
206 Loop *cur = LI->getLoopFor(Inst->getParent());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700207 if (succ != nullptr && succ != cur)
Duncan Sands53b41772012-05-31 08:09:49 +0000208 return false;
209 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000210
Duncan Sands53b41772012-05-31 08:09:49 +0000211 // Finally, check that all the uses of the instruction are actually
212 // dominated by the candidate
213 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
214}
215
Dan Gohman28a193e2010-05-07 15:40:13 +0000216/// SinkInstruction - Determine whether it is safe to sink the specified machine
217/// instruction out of its current block into a successor.
218bool Sinking::SinkInstruction(Instruction *Inst,
219 SmallPtrSet<Instruction *, 8> &Stores) {
Stephen Hines36b56882014-04-23 16:57:46 -0700220
221 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
222 // entry block are dynamically sized stack objects.
223 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
224 if (AI->isStaticAlloca())
225 return false;
226
Dan Gohman28a193e2010-05-07 15:40:13 +0000227 // Check if it's safe to move the instruction.
228 if (!isSafeToMove(Inst, AA, Stores))
229 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000230
Dan Gohman28a193e2010-05-07 15:40:13 +0000231 // FIXME: This should include support for sinking instructions within the
232 // block they are currently in to shorten the live ranges. We often get
233 // instructions sunk into the top of a large block, but it would be better to
234 // also sink them down before their first use in the block. This xform has to
235 // be careful not to *increase* register pressure though, e.g. sinking
236 // "x = y + z" down if it kills y and z would increase the live ranges of y
237 // and z and only shrink the live range of x.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000238
Dan Gohman28a193e2010-05-07 15:40:13 +0000239 // SuccToSinkTo - This is the successor to sink this instruction to, once we
240 // decide.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700241 BasicBlock *SuccToSinkTo = nullptr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000242
Dan Gohman28a193e2010-05-07 15:40:13 +0000243 // Instructions can only be sunk if all their uses are in blocks
244 // dominated by one of the successors.
Duncan Sands53b41772012-05-31 08:09:49 +0000245 // Look at all the postdominators and see if we can sink it in one.
246 DomTreeNode *DTN = DT->getNode(Inst->getParent());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000247 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700248 I != E && SuccToSinkTo == nullptr; ++I) {
Duncan Sands53b41772012-05-31 08:09:49 +0000249 BasicBlock *Candidate = (*I)->getBlock();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000250 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
Duncan Sands53b41772012-05-31 08:09:49 +0000251 IsAcceptableTarget(Inst, Candidate))
252 SuccToSinkTo = Candidate;
253 }
254
Nadav Rotema94d6e82012-07-24 10:51:42 +0000255 // If no suitable postdominator was found, look at all the successors and
Duncan Sands53b41772012-05-31 08:09:49 +0000256 // decide which one we should sink to, if any.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000257 for (succ_iterator I = succ_begin(Inst->getParent()),
Stephen Hinesdce4a402014-05-29 02:49:00 -0700258 E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
Duncan Sands53b41772012-05-31 08:09:49 +0000259 if (IsAcceptableTarget(Inst, *I))
260 SuccToSinkTo = *I;
Dan Gohman28a193e2010-05-07 15:40:13 +0000261 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000262
Dan Gohman28a193e2010-05-07 15:40:13 +0000263 // If we couldn't find a block to sink to, ignore this instruction.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700264 if (!SuccToSinkTo)
Dan Gohman28a193e2010-05-07 15:40:13 +0000265 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000266
Duncan Sands53b41772012-05-31 08:09:49 +0000267 DEBUG(dbgs() << "Sink" << *Inst << " (";
Stephen Hines36b56882014-04-23 16:57:46 -0700268 Inst->getParent()->printAsOperand(dbgs(), false);
Duncan Sands53b41772012-05-31 08:09:49 +0000269 dbgs() << " -> ";
Stephen Hines36b56882014-04-23 16:57:46 -0700270 SuccToSinkTo->printAsOperand(dbgs(), false);
Duncan Sands53b41772012-05-31 08:09:49 +0000271 dbgs() << ")\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000272
Dan Gohman28a193e2010-05-07 15:40:13 +0000273 // Move the instruction.
Duncan Sands53b41772012-05-31 08:09:49 +0000274 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
Dan Gohman28a193e2010-05-07 15:40:13 +0000275 return true;
276}