xref: /llvm-project/llvm/lib/Transforms/Scalar/Sink.cpp (revision 135f735af149e305635ba3886065b493d5c2bf8c)
1 //===-- 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 
15 #include "llvm/Transforms/Scalar/Sink.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Scalar.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "sink"
31 
32 STATISTIC(NumSunk, "Number of instructions sunk");
33 STATISTIC(NumSinkIter, "Number of sinking iterations");
34 
35 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
36 /// occur in blocks dominated by the specified block.
37 static bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB,
38                                     DominatorTree &DT) {
39   // 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.
43   for (Use &U : Inst->uses()) {
44     // Determine the block of the use.
45     Instruction *UseInst = cast<Instruction>(U.getUser());
46     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.
50       unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
51       UseBlock = PN->getIncomingBlock(Num);
52     }
53     // Check that it dominates.
54     if (!DT.dominates(BB, UseBlock))
55       return false;
56   }
57   return true;
58 }
59 
60 static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA,
61                          SmallPtrSetImpl<Instruction *> &Stores) {
62 
63   if (Inst->mayWriteToMemory()) {
64     Stores.insert(Inst);
65     return false;
66   }
67 
68   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
69     MemoryLocation Loc = MemoryLocation::get(L);
70     for (Instruction *S : Stores)
71       if (AA.getModRefInfo(S, Loc) & MRI_Mod)
72         return false;
73   }
74 
75   if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst) || Inst->isEHPad() ||
76       Inst->mayThrow())
77     return false;
78 
79   // Convergent operations cannot be made control-dependent on additional
80   // values.
81   if (auto CS = CallSite(Inst)) {
82     if (CS.hasFnAttr(Attribute::Convergent))
83       return false;
84   }
85 
86   return true;
87 }
88 
89 /// IsAcceptableTarget - Return true if it is possible to sink the instruction
90 /// in the specified basic block.
91 static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
92                                DominatorTree &DT, LoopInfo &LI) {
93   assert(Inst && "Instruction to be sunk is null");
94   assert(SuccToSinkTo && "Candidate sink target is null");
95 
96   // 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;
100 
101   // 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 
106   // If the block has multiple predecessors, this would introduce computation
107   // 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.
113     if (!isSafeToSpeculativelyExecute(Inst))
114       return false;
115 
116     // 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.
118     if (!DT.dominates(Inst->getParent(), SuccToSinkTo))
119       return false;
120 
121     // Don't sink instructions into a loop.
122     Loop *succ = LI.getLoopFor(SuccToSinkTo);
123     Loop *cur = LI.getLoopFor(Inst->getParent());
124     if (succ != nullptr && succ != cur)
125       return false;
126   }
127 
128   // Finally, check that all the uses of the instruction are actually
129   // dominated by the candidate
130   return AllUsesDominatedByBlock(Inst, SuccToSinkTo, DT);
131 }
132 
133 /// SinkInstruction - Determine whether it is safe to sink the specified machine
134 /// instruction out of its current block into a successor.
135 static bool SinkInstruction(Instruction *Inst,
136                             SmallPtrSetImpl<Instruction *> &Stores,
137                             DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
138 
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 
145   // Check if it's safe to move the instruction.
146   if (!isSafeToMove(Inst, AA, Stores))
147     return false;
148 
149   // 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.
156 
157   // SuccToSinkTo - This is the successor to sink this instruction to, once we
158   // decide.
159   BasicBlock *SuccToSinkTo = nullptr;
160 
161   // Instructions can only be sunk if all their uses are in blocks
162   // dominated by one of the successors.
163   // Look at all the postdominators and see if we can sink it in one.
164   DomTreeNode *DTN = DT.getNode(Inst->getParent());
165   for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
166       I != E && SuccToSinkTo == nullptr; ++I) {
167     BasicBlock *Candidate = (*I)->getBlock();
168     if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
169         IsAcceptableTarget(Inst, Candidate, DT, LI))
170       SuccToSinkTo = Candidate;
171   }
172 
173   // If no suitable postdominator was found, look at all the successors and
174   // decide which one we should sink to, if any.
175   for (succ_iterator I = succ_begin(Inst->getParent()),
176       E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
177     if (IsAcceptableTarget(Inst, *I, DT, LI))
178       SuccToSinkTo = *I;
179   }
180 
181   // If we couldn't find a block to sink to, ignore this instruction.
182   if (!SuccToSinkTo)
183     return false;
184 
185   DEBUG(dbgs() << "Sink" << *Inst << " (";
186         Inst->getParent()->printAsOperand(dbgs(), false);
187         dbgs() << " -> ";
188         SuccToSinkTo->printAsOperand(dbgs(), false);
189         dbgs() << ")\n");
190 
191   // Move the instruction.
192   Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
193   return true;
194 }
195 
196 static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI,
197                          AAResults &AA) {
198   // 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.
204   if (!DT.isReachableFromEntry(&BB)) return false;
205 
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 
225     if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
226       ++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 
236 static bool iterativelySinkInstructions(Function &F, DominatorTree &DT,
237                                         LoopInfo &LI, AAResults &AA) {
238   bool MadeChange, EverMadeChange = false;
239 
240   do {
241     MadeChange = false;
242     DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
243     // Process all basic blocks.
244     for (BasicBlock &I : F)
245       MadeChange |= ProcessBlock(I, DT, LI, AA);
246     EverMadeChange |= MadeChange;
247     NumSinkIter++;
248   } while (MadeChange);
249 
250   return EverMadeChange;
251 }
252 
253 PreservedAnalyses 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 
267 namespace {
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 
295 char SinkingLegacyPass::ID = 0;
296 INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
297 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
298 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
299 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
300 INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
301 
302 FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }
303