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/IntrinsicInst.h"
18 #include "llvm/Analysis/Dominators.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
28 STATISTIC(NumSunk
, "Number of instructions sunk");
31 class Sinking
: public FunctionPass
{
37 static char ID
; // Pass identification
38 Sinking() : FunctionPass(ID
) {
39 initializeSinkingPass(*PassRegistry::getPassRegistry());
42 virtual bool runOnFunction(Function
&F
);
44 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
46 FunctionPass::getAnalysisUsage(AU
);
47 AU
.addRequired
<AliasAnalysis
>();
48 AU
.addRequired
<DominatorTree
>();
49 AU
.addRequired
<LoopInfo
>();
50 AU
.addPreserved
<DominatorTree
>();
51 AU
.addPreserved
<LoopInfo
>();
54 bool ProcessBlock(BasicBlock
&BB
);
55 bool SinkInstruction(Instruction
*I
, SmallPtrSet
<Instruction
*, 8> &Stores
);
56 bool AllUsesDominatedByBlock(Instruction
*Inst
, BasicBlock
*BB
) const;
58 } // end anonymous namespace
61 INITIALIZE_PASS_BEGIN(Sinking
, "sink", "Code sinking", false, false)
62 INITIALIZE_PASS_DEPENDENCY(LoopInfo
)
63 INITIALIZE_PASS_DEPENDENCY(DominatorTree
)
64 INITIALIZE_AG_DEPENDENCY(AliasAnalysis
)
65 INITIALIZE_PASS_END(Sinking
, "sink", "Code sinking", false, false)
67 FunctionPass
*llvm::createSinkingPass() { return new Sinking(); }
69 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
70 /// occur in blocks dominated by the specified block.
71 bool Sinking::AllUsesDominatedByBlock(Instruction
*Inst
,
72 BasicBlock
*BB
) const {
73 // Ignoring debug uses is necessary so debug info doesn't affect the code.
74 // This may leave a referencing dbg_value in the original block, before
75 // the definition of the vreg. Dwarf generator handles this although the
76 // user might not get the right info at runtime.
77 for (Value::use_iterator I
= Inst
->use_begin(),
78 E
= Inst
->use_end(); I
!= E
; ++I
) {
79 // Determine the block of the use.
80 Instruction
*UseInst
= cast
<Instruction
>(*I
);
81 BasicBlock
*UseBlock
= UseInst
->getParent();
82 if (PHINode
*PN
= dyn_cast
<PHINode
>(UseInst
)) {
83 // PHI nodes use the operand in the predecessor block, not the block with
85 unsigned Num
= PHINode::getIncomingValueNumForOperand(I
.getOperandNo());
86 UseBlock
= PN
->getIncomingBlock(Num
);
88 // Check that it dominates.
89 if (!DT
->dominates(BB
, UseBlock
))
95 bool Sinking::runOnFunction(Function
&F
) {
96 DT
= &getAnalysis
<DominatorTree
>();
97 LI
= &getAnalysis
<LoopInfo
>();
98 AA
= &getAnalysis
<AliasAnalysis
>();
100 bool EverMadeChange
= false;
103 bool MadeChange
= false;
105 // Process all basic blocks.
106 for (Function::iterator I
= F
.begin(), E
= F
.end();
108 MadeChange
|= ProcessBlock(*I
);
110 // If this iteration over the code changed anything, keep iterating.
111 if (!MadeChange
) break;
112 EverMadeChange
= true;
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 unreachable
123 // 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
) {
156 if (LoadInst
*L
= dyn_cast
<LoadInst
>(Inst
)) {
157 if (L
->isVolatile()) return false;
159 Value
*Ptr
= L
->getPointerOperand();
160 uint64_t Size
= AA
->getTypeStoreSize(L
->getType());
161 for (SmallPtrSet
<Instruction
*, 8>::iterator I
= Stores
.begin(),
162 E
= Stores
.end(); I
!= E
; ++I
)
163 if (AA
->getModRefInfo(*I
, Ptr
, Size
) & AliasAnalysis::Mod
)
167 if (Inst
->mayWriteToMemory()) {
172 return Inst
->isSafeToSpeculativelyExecute();
175 /// SinkInstruction - Determine whether it is safe to sink the specified machine
176 /// instruction out of its current block into a successor.
177 bool Sinking::SinkInstruction(Instruction
*Inst
,
178 SmallPtrSet
<Instruction
*, 8> &Stores
) {
179 // Check if it's safe to move the instruction.
180 if (!isSafeToMove(Inst
, AA
, Stores
))
183 // FIXME: This should include support for sinking instructions within the
184 // block they are currently in to shorten the live ranges. We often get
185 // instructions sunk into the top of a large block, but it would be better to
186 // also sink them down before their first use in the block. This xform has to
187 // be careful not to *increase* register pressure though, e.g. sinking
188 // "x = y + z" down if it kills y and z would increase the live ranges of y
189 // and z and only shrink the live range of x.
191 // Loop over all the operands of the specified instruction. If there is
192 // anything we can't handle, bail out.
193 BasicBlock
*ParentBlock
= Inst
->getParent();
195 // SuccToSinkTo - This is the successor to sink this instruction to, once we
197 BasicBlock
*SuccToSinkTo
= 0;
199 // FIXME: This picks a successor to sink into based on having one
200 // successor that dominates all the uses. However, there are cases where
201 // sinking can happen but where the sink point isn't a successor. For
206 // the instruction could be sunk over the whole diamond for the
207 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
210 // Instructions can only be sunk if all their uses are in blocks
211 // dominated by one of the successors.
212 // Look at all the successors and decide which one
213 // we should sink to.
214 for (succ_iterator SI
= succ_begin(ParentBlock
),
215 E
= succ_end(ParentBlock
); SI
!= E
; ++SI
) {
216 if (AllUsesDominatedByBlock(Inst
, *SI
)) {
222 // If we couldn't find a block to sink to, ignore this instruction.
223 if (SuccToSinkTo
== 0)
226 // It is not possible to sink an instruction into its own block. This can
227 // happen with loops.
228 if (Inst
->getParent() == SuccToSinkTo
)
231 DEBUG(dbgs() << "Sink instr " << *Inst
);
232 DEBUG(dbgs() << "to block ";
233 WriteAsOperand(dbgs(), SuccToSinkTo
, false));
235 // If the block has multiple predecessors, this would introduce computation on
236 // a path that it doesn't already exist. We could split the critical edge,
237 // but for now we just punt.
238 // FIXME: Split critical edges if not backedges.
239 if (SuccToSinkTo
->getUniquePredecessor() != ParentBlock
) {
240 // We cannot sink a load across a critical edge - there may be stores in
242 if (!Inst
->isSafeToSpeculativelyExecute()) {
243 DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
247 // We don't want to sink across a critical edge if we don't dominate the
248 // successor. We could be introducing calculations to new code paths.
249 if (!DT
->dominates(ParentBlock
, SuccToSinkTo
)) {
250 DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
254 // Don't sink instructions into a loop.
255 if (LI
->isLoopHeader(SuccToSinkTo
)) {
256 DEBUG(dbgs() << " *** PUNTING: Loop header found\n");
260 // Otherwise we are OK with sinking along a critical edge.
261 DEBUG(dbgs() << "Sinking along critical edge.\n");
264 // Determine where to insert into. Skip phi nodes.
265 BasicBlock::iterator InsertPos
= SuccToSinkTo
->begin();
266 while (InsertPos
!= SuccToSinkTo
->end() && isa
<PHINode
>(InsertPos
))
269 // Move the instruction.
270 Inst
->moveBefore(InsertPos
);