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