1 //===-- Sink.cpp - Code Sinking -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "sink"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
28 STATISTIC(NumSunk, "Number of instructions sunk");
29 STATISTIC(NumSinkIter, "Number of sinking iterations");
32 class Sinking : public FunctionPass {
38 static char ID; // Pass identification
39 Sinking() : FunctionPass(ID) {
40 initializeSinkingPass(*PassRegistry::getPassRegistry());
43 bool runOnFunction(Function &F) override;
45 void getAnalysisUsage(AnalysisUsage &AU) const override {
47 FunctionPass::getAnalysisUsage(AU);
48 AU.addRequired<AliasAnalysis>();
49 AU.addRequired<DominatorTreeWrapperPass>();
50 AU.addRequired<LoopInfo>();
51 AU.addPreserved<DominatorTreeWrapperPass>();
52 AU.addPreserved<LoopInfo>();
55 bool ProcessBlock(BasicBlock &BB);
56 bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores);
57 bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
58 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
60 } // end anonymous namespace
63 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
64 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
65 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
66 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
67 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
69 FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
71 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
72 /// occur in blocks dominated by the specified block.
73 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
74 BasicBlock *BB) const {
75 // Ignoring debug uses is necessary so debug info doesn't affect the code.
76 // This may leave a referencing dbg_value in the original block, before
77 // the definition of the vreg. Dwarf generator handles this although the
78 // user might not get the right info at runtime.
79 for (Use &U : Inst->uses()) {
80 // Determine the block of the use.
81 Instruction *UseInst = cast<Instruction>(U.getUser());
82 BasicBlock *UseBlock = UseInst->getParent();
83 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
84 // PHI nodes use the operand in the predecessor block, not the block with
86 unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
87 UseBlock = PN->getIncomingBlock(Num);
89 // Check that it dominates.
90 if (!DT->dominates(BB, UseBlock))
96 bool Sinking::runOnFunction(Function &F) {
97 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
98 LI = &getAnalysis<LoopInfo>();
99 AA = &getAnalysis<AliasAnalysis>();
101 bool MadeChange, EverMadeChange = false;
105 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
106 // Process all basic blocks.
107 for (Function::iterator I = F.begin(), E = F.end();
109 MadeChange |= ProcessBlock(*I);
110 EverMadeChange |= MadeChange;
112 } while (MadeChange);
114 return EverMadeChange;
117 bool Sinking::ProcessBlock(BasicBlock &BB) {
118 // Can't sink anything out of a block that has less than two successors.
119 if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
121 // Don't bother sinking code out of unreachable blocks. In addition to being
122 // unprofitable, it can also lead to infinite looping, because in an
123 // unreachable loop there may be nowhere to stop.
124 if (!DT->isReachableFromEntry(&BB)) return false;
126 bool MadeChange = false;
128 // Walk the basic block bottom-up. Remember if we saw a store.
129 BasicBlock::iterator I = BB.end();
131 bool ProcessedBegin = false;
132 SmallPtrSet<Instruction *, 8> Stores;
134 Instruction *Inst = I; // The instruction to sink.
136 // Predecrement I (if it's not begin) so that it isn't invalidated by
138 ProcessedBegin = I == BB.begin();
142 if (isa<DbgInfoIntrinsic>(Inst))
145 if (SinkInstruction(Inst, Stores))
146 ++NumSunk, MadeChange = true;
148 // If we just processed the first instruction in the block, we're done.
149 } while (!ProcessedBegin);
154 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
155 SmallPtrSet<Instruction *, 8> &Stores) {
157 if (Inst->mayWriteToMemory()) {
162 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
163 AliasAnalysis::Location Loc = AA->getLocation(L);
164 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
165 E = Stores.end(); I != E; ++I)
166 if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
170 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
176 /// IsAcceptableTarget - Return true if it is possible to sink the instruction
177 /// in the specified basic block.
178 bool Sinking::IsAcceptableTarget(Instruction *Inst,
179 BasicBlock *SuccToSinkTo) const {
180 assert(Inst && "Instruction to be sunk is null");
181 assert(SuccToSinkTo && "Candidate sink target is null");
183 // It is not possible to sink an instruction into its own block. This can
184 // happen with loops.
185 if (Inst->getParent() == SuccToSinkTo)
188 // If the block has multiple predecessors, this would introduce computation
189 // on different code paths. We could split the critical edge, but for now we
191 // FIXME: Split critical edges if not backedges.
192 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
193 // We cannot sink a load across a critical edge - there may be stores in
195 if (!isSafeToSpeculativelyExecute(Inst))
198 // We don't want to sink across a critical edge if we don't dominate the
199 // successor. We could be introducing calculations to new code paths.
200 if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
203 // Don't sink instructions into a loop.
204 Loop *succ = LI->getLoopFor(SuccToSinkTo);
205 Loop *cur = LI->getLoopFor(Inst->getParent());
206 if (succ != 0 && succ != cur)
210 // Finally, check that all the uses of the instruction are actually
211 // dominated by the candidate
212 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
215 /// SinkInstruction - Determine whether it is safe to sink the specified machine
216 /// instruction out of its current block into a successor.
217 bool Sinking::SinkInstruction(Instruction *Inst,
218 SmallPtrSet<Instruction *, 8> &Stores) {
220 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
221 // entry block are dynamically sized stack objects.
222 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
223 if (AI->isStaticAlloca())
226 // Check if it's safe to move the instruction.
227 if (!isSafeToMove(Inst, AA, Stores))
230 // FIXME: This should include support for sinking instructions within the
231 // block they are currently in to shorten the live ranges. We often get
232 // instructions sunk into the top of a large block, but it would be better to
233 // also sink them down before their first use in the block. This xform has to
234 // be careful not to *increase* register pressure though, e.g. sinking
235 // "x = y + z" down if it kills y and z would increase the live ranges of y
236 // and z and only shrink the live range of x.
238 // SuccToSinkTo - This is the successor to sink this instruction to, once we
240 BasicBlock *SuccToSinkTo = 0;
242 // Instructions can only be sunk if all their uses are in blocks
243 // dominated by one of the successors.
244 // Look at all the postdominators and see if we can sink it in one.
245 DomTreeNode *DTN = DT->getNode(Inst->getParent());
246 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
247 I != E && SuccToSinkTo == 0; ++I) {
248 BasicBlock *Candidate = (*I)->getBlock();
249 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
250 IsAcceptableTarget(Inst, Candidate))
251 SuccToSinkTo = Candidate;
254 // If no suitable postdominator was found, look at all the successors and
255 // decide which one we should sink to, if any.
256 for (succ_iterator I = succ_begin(Inst->getParent()),
257 E = succ_end(Inst->getParent()); I != E && SuccToSinkTo == 0; ++I) {
258 if (IsAcceptableTarget(Inst, *I))
262 // If we couldn't find a block to sink to, ignore this instruction.
263 if (SuccToSinkTo == 0)
266 DEBUG(dbgs() << "Sink" << *Inst << " (";
267 Inst->getParent()->printAsOperand(dbgs(), false);
269 SuccToSinkTo->printAsOperand(dbgs(), false);
272 // Move the instruction.
273 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());