Sink.cpp revision 36b56886974eae4f9c5ebc96befd3e7bfe5de338
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#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"
26using namespace llvm;
27
28STATISTIC(NumSunk, "Number of instructions sunk");
29STATISTIC(NumSinkIter, "Number of sinking iterations");
30
31namespace {
32  class Sinking : public FunctionPass {
33    DominatorTree *DT;
34    LoopInfo *LI;
35    AliasAnalysis *AA;
36
37  public:
38    static char ID; // Pass identification
39    Sinking() : FunctionPass(ID) {
40      initializeSinkingPass(*PassRegistry::getPassRegistry());
41    }
42
43    bool runOnFunction(Function &F) override;
44
45    void getAnalysisUsage(AnalysisUsage &AU) const override {
46      AU.setPreservesCFG();
47      FunctionPass::getAnalysisUsage(AU);
48      AU.addRequired<AliasAnalysis>();
49      AU.addRequired<DominatorTreeWrapperPass>();
50      AU.addRequired<LoopInfo>();
51      AU.addPreserved<DominatorTreeWrapperPass>();
52      AU.addPreserved<LoopInfo>();
53    }
54  private:
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;
59  };
60} // end anonymous namespace
61
62char Sinking::ID = 0;
63INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
64INITIALIZE_PASS_DEPENDENCY(LoopInfo)
65INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
66INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
67INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
68
69FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
70
71/// AllUsesDominatedByBlock - Return true if all uses of the specified value
72/// occur in blocks dominated by the specified block.
73bool 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
85      // the PHI.
86      unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
87      UseBlock = PN->getIncomingBlock(Num);
88    }
89    // Check that it dominates.
90    if (!DT->dominates(BB, UseBlock))
91      return false;
92  }
93  return true;
94}
95
96bool Sinking::runOnFunction(Function &F) {
97  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
98  LI = &getAnalysis<LoopInfo>();
99  AA = &getAnalysis<AliasAnalysis>();
100
101  bool MadeChange, EverMadeChange = false;
102
103  do {
104    MadeChange = false;
105    DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
106    // Process all basic blocks.
107    for (Function::iterator I = F.begin(), E = F.end();
108         I != E; ++I)
109      MadeChange |= ProcessBlock(*I);
110    EverMadeChange |= MadeChange;
111    NumSinkIter++;
112  } while (MadeChange);
113
114  return EverMadeChange;
115}
116
117bool 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;
120
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;
125
126  bool MadeChange = false;
127
128  // Walk the basic block bottom-up.  Remember if we saw a store.
129  BasicBlock::iterator I = BB.end();
130  --I;
131  bool ProcessedBegin = false;
132  SmallPtrSet<Instruction *, 8> Stores;
133  do {
134    Instruction *Inst = I;  // The instruction to sink.
135
136    // Predecrement I (if it's not begin) so that it isn't invalidated by
137    // sinking.
138    ProcessedBegin = I == BB.begin();
139    if (!ProcessedBegin)
140      --I;
141
142    if (isa<DbgInfoIntrinsic>(Inst))
143      continue;
144
145    if (SinkInstruction(Inst, Stores))
146      ++NumSunk, MadeChange = true;
147
148    // If we just processed the first instruction in the block, we're done.
149  } while (!ProcessedBegin);
150
151  return MadeChange;
152}
153
154static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
155                         SmallPtrSet<Instruction *, 8> &Stores) {
156
157  if (Inst->mayWriteToMemory()) {
158    Stores.insert(Inst);
159    return false;
160  }
161
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)
167        return false;
168  }
169
170  if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
171    return false;
172
173  return true;
174}
175
176/// IsAcceptableTarget - Return true if it is possible to sink the instruction
177/// in the specified basic block.
178bool 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");
182
183  // It is not possible to sink an instruction into its own block.  This can
184  // happen with loops.
185  if (Inst->getParent() == SuccToSinkTo)
186    return false;
187
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
190  // just punt.
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
194    // other code paths.
195    if (!isSafeToSpeculativelyExecute(Inst))
196      return false;
197
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))
201      return false;
202
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)
207      return false;
208  }
209
210  // Finally, check that all the uses of the instruction are actually
211  // dominated by the candidate
212  return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
213}
214
215/// SinkInstruction - Determine whether it is safe to sink the specified machine
216/// instruction out of its current block into a successor.
217bool Sinking::SinkInstruction(Instruction *Inst,
218                              SmallPtrSet<Instruction *, 8> &Stores) {
219
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())
224      return false;
225
226  // Check if it's safe to move the instruction.
227  if (!isSafeToMove(Inst, AA, Stores))
228    return false;
229
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.
237
238  // SuccToSinkTo - This is the successor to sink this instruction to, once we
239  // decide.
240  BasicBlock *SuccToSinkTo = 0;
241
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;
252  }
253
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))
259      SuccToSinkTo = *I;
260  }
261
262  // If we couldn't find a block to sink to, ignore this instruction.
263  if (SuccToSinkTo == 0)
264    return false;
265
266  DEBUG(dbgs() << "Sink" << *Inst << " (";
267        Inst->getParent()->printAsOperand(dbgs(), false);
268        dbgs() << " -> ";
269        SuccToSinkTo->printAsOperand(dbgs(), false);
270        dbgs() << ")\n");
271
272  // Move the instruction.
273  Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
274  return true;
275}
276