xref: /llvm-project/llvm/lib/Transforms/Scalar/Sink.cpp (revision c316332e1789221ec26875d1dc335382b6e68d83)
1 //===-- Sink.cpp - Code Sinking -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass moves instructions into successor blocks, when possible, so that
10 // they aren't executed on paths where their results aren't needed.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/Sink.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/InitializePasses.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Transforms/Scalar.h"
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "sink"
26 
27 STATISTIC(NumSunk, "Number of instructions sunk");
28 STATISTIC(NumSinkIter, "Number of sinking iterations");
29 
30 static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA,
31                          SmallPtrSetImpl<Instruction *> &Stores) {
32 
33   if (Inst->mayWriteToMemory()) {
34     Stores.insert(Inst);
35     return false;
36   }
37 
38   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
39     MemoryLocation Loc = MemoryLocation::get(L);
40     for (Instruction *S : Stores)
41       if (isModSet(AA.getModRefInfo(S, Loc)))
42         return false;
43   }
44 
45   if (Inst->isTerminator() || isa<PHINode>(Inst) || Inst->isEHPad() ||
46       Inst->mayThrow() || !Inst->willReturn())
47     return false;
48 
49   if (auto *Call = dyn_cast<CallBase>(Inst)) {
50     // Convergent operations cannot be made control-dependent on additional
51     // values.
52     if (Call->isConvergent())
53       return false;
54 
55     for (Instruction *S : Stores)
56       if (isModSet(AA.getModRefInfo(S, Call)))
57         return false;
58   }
59 
60   return true;
61 }
62 
63 /// IsAcceptableTarget - Return true if it is possible to sink the instruction
64 /// in the specified basic block.
65 static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
66                                DominatorTree &DT, LoopInfo &LI) {
67   assert(Inst && "Instruction to be sunk is null");
68   assert(SuccToSinkTo && "Candidate sink target is null");
69 
70   // It's never legal to sink an instruction into a block which terminates in an
71   // EH-pad.
72   if (SuccToSinkTo->getTerminator()->isExceptionalTerminator())
73     return false;
74 
75   // If the block has multiple predecessors, this would introduce computation
76   // on different code paths.  We could split the critical edge, but for now we
77   // just punt.
78   // FIXME: Split critical edges if not backedges.
79   if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
80     // We cannot sink a load across a critical edge - there may be stores in
81     // other code paths.
82     if (Inst->mayReadFromMemory() &&
83         !Inst->hasMetadata(LLVMContext::MD_invariant_load))
84       return false;
85 
86     // We don't want to sink across a critical edge if we don't dominate the
87     // successor. We could be introducing calculations to new code paths.
88     if (!DT.dominates(Inst->getParent(), SuccToSinkTo))
89       return false;
90 
91     // Don't sink instructions into a loop.
92     Loop *succ = LI.getLoopFor(SuccToSinkTo);
93     Loop *cur = LI.getLoopFor(Inst->getParent());
94     if (succ != nullptr && succ != cur)
95       return false;
96   }
97 
98   return true;
99 }
100 
101 /// SinkInstruction - Determine whether it is safe to sink the specified machine
102 /// instruction out of its current block into a successor.
103 static bool SinkInstruction(Instruction *Inst,
104                             SmallPtrSetImpl<Instruction *> &Stores,
105                             DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
106 
107   // Don't sink static alloca instructions.  CodeGen assumes allocas outside the
108   // entry block are dynamically sized stack objects.
109   if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
110     if (AI->isStaticAlloca())
111       return false;
112 
113   // Check if it's safe to move the instruction.
114   if (!isSafeToMove(Inst, AA, Stores))
115     return false;
116 
117   // FIXME: This should include support for sinking instructions within the
118   // block they are currently in to shorten the live ranges.  We often get
119   // instructions sunk into the top of a large block, but it would be better to
120   // also sink them down before their first use in the block.  This xform has to
121   // be careful not to *increase* register pressure though, e.g. sinking
122   // "x = y + z" down if it kills y and z would increase the live ranges of y
123   // and z and only shrink the live range of x.
124 
125   // SuccToSinkTo - This is the successor to sink this instruction to, once we
126   // decide.
127   BasicBlock *SuccToSinkTo = nullptr;
128 
129   // Find the nearest common dominator of all users as the candidate.
130   BasicBlock *BB = Inst->getParent();
131   for (Use &U : Inst->uses()) {
132     Instruction *UseInst = cast<Instruction>(U.getUser());
133     BasicBlock *UseBlock = UseInst->getParent();
134     // Don't worry about dead users.
135     if (!DT.isReachableFromEntry(UseBlock))
136       continue;
137     if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
138       // PHI nodes use the operand in the predecessor block, not the block with
139       // the PHI.
140       unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
141       UseBlock = PN->getIncomingBlock(Num);
142     }
143     if (SuccToSinkTo)
144       SuccToSinkTo = DT.findNearestCommonDominator(SuccToSinkTo, UseBlock);
145     else
146       SuccToSinkTo = UseBlock;
147     // The current basic block needs to dominate the candidate.
148     if (!DT.dominates(BB, SuccToSinkTo))
149       return false;
150   }
151 
152   if (SuccToSinkTo) {
153     // The nearest common dominator may be in a parent loop of BB, which may not
154     // be beneficial. Find an ancestor.
155     while (SuccToSinkTo != BB &&
156            !IsAcceptableTarget(Inst, SuccToSinkTo, DT, LI))
157       SuccToSinkTo = DT.getNode(SuccToSinkTo)->getIDom()->getBlock();
158     if (SuccToSinkTo == BB)
159       SuccToSinkTo = nullptr;
160   }
161 
162   // If we couldn't find a block to sink to, ignore this instruction.
163   if (!SuccToSinkTo)
164     return false;
165 
166   LLVM_DEBUG(dbgs() << "Sink" << *Inst << " (";
167              Inst->getParent()->printAsOperand(dbgs(), false); dbgs() << " -> ";
168              SuccToSinkTo->printAsOperand(dbgs(), false); dbgs() << ")\n");
169 
170   // Move the instruction.
171   Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
172   return true;
173 }
174 
175 static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI,
176                          AAResults &AA) {
177   // Can't sink anything out of a block that has less than two successors.
178   if (BB.getTerminator()->getNumSuccessors() <= 1) return false;
179 
180   // Don't bother sinking code out of unreachable blocks. In addition to being
181   // unprofitable, it can also lead to infinite looping, because in an
182   // unreachable loop there may be nowhere to stop.
183   if (!DT.isReachableFromEntry(&BB)) return false;
184 
185   bool MadeChange = false;
186 
187   // Walk the basic block bottom-up.  Remember if we saw a store.
188   BasicBlock::iterator I = BB.end();
189   --I;
190   bool ProcessedBegin = false;
191   SmallPtrSet<Instruction *, 8> Stores;
192   do {
193     Instruction *Inst = &*I; // The instruction to sink.
194 
195     // Predecrement I (if it's not begin) so that it isn't invalidated by
196     // sinking.
197     ProcessedBegin = I == BB.begin();
198     if (!ProcessedBegin)
199       --I;
200 
201     if (Inst->isDebugOrPseudoInst())
202       continue;
203 
204     if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
205       ++NumSunk;
206       MadeChange = true;
207     }
208 
209     // If we just processed the first instruction in the block, we're done.
210   } while (!ProcessedBegin);
211 
212   return MadeChange;
213 }
214 
215 static bool iterativelySinkInstructions(Function &F, DominatorTree &DT,
216                                         LoopInfo &LI, AAResults &AA) {
217   bool MadeChange, EverMadeChange = false;
218 
219   do {
220     MadeChange = false;
221     LLVM_DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
222     // Process all basic blocks.
223     for (BasicBlock &I : F)
224       MadeChange |= ProcessBlock(I, DT, LI, AA);
225     EverMadeChange |= MadeChange;
226     NumSinkIter++;
227   } while (MadeChange);
228 
229   return EverMadeChange;
230 }
231 
232 PreservedAnalyses SinkingPass::run(Function &F, FunctionAnalysisManager &AM) {
233   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
234   auto &LI = AM.getResult<LoopAnalysis>(F);
235   auto &AA = AM.getResult<AAManager>(F);
236 
237   if (!iterativelySinkInstructions(F, DT, LI, AA))
238     return PreservedAnalyses::all();
239 
240   PreservedAnalyses PA;
241   PA.preserveSet<CFGAnalyses>();
242   return PA;
243 }
244 
245 namespace {
246   class SinkingLegacyPass : public FunctionPass {
247   public:
248     static char ID; // Pass identification
249     SinkingLegacyPass() : FunctionPass(ID) {
250       initializeSinkingLegacyPassPass(*PassRegistry::getPassRegistry());
251     }
252 
253     bool runOnFunction(Function &F) override {
254       auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
255       auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
256       auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
257 
258       return iterativelySinkInstructions(F, DT, LI, AA);
259     }
260 
261     void getAnalysisUsage(AnalysisUsage &AU) const override {
262       AU.setPreservesCFG();
263       FunctionPass::getAnalysisUsage(AU);
264       AU.addRequired<AAResultsWrapperPass>();
265       AU.addRequired<DominatorTreeWrapperPass>();
266       AU.addRequired<LoopInfoWrapperPass>();
267       AU.addPreserved<DominatorTreeWrapperPass>();
268       AU.addPreserved<LoopInfoWrapperPass>();
269     }
270   };
271 } // end anonymous namespace
272 
273 char SinkingLegacyPass::ID = 0;
274 INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
275 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
276 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
277 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
278 INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
279 
280 FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }
281