109467b48Spatrick //===-- Sink.cpp - Code Sinking -------------------------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This pass moves instructions into successor blocks, when possible, so that
1009467b48Spatrick // they aren't executed on paths where their results aren't needed.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick 
1409467b48Spatrick #include "llvm/Transforms/Scalar/Sink.h"
1509467b48Spatrick #include "llvm/ADT/Statistic.h"
1609467b48Spatrick #include "llvm/Analysis/AliasAnalysis.h"
1709467b48Spatrick #include "llvm/Analysis/LoopInfo.h"
1809467b48Spatrick #include "llvm/IR/Dominators.h"
1909467b48Spatrick #include "llvm/InitializePasses.h"
2009467b48Spatrick #include "llvm/Support/Debug.h"
2109467b48Spatrick #include "llvm/Support/raw_ostream.h"
2209467b48Spatrick #include "llvm/Transforms/Scalar.h"
2309467b48Spatrick using namespace llvm;
2409467b48Spatrick 
2509467b48Spatrick #define DEBUG_TYPE "sink"
2609467b48Spatrick 
2709467b48Spatrick STATISTIC(NumSunk, "Number of instructions sunk");
2809467b48Spatrick STATISTIC(NumSinkIter, "Number of sinking iterations");
2909467b48Spatrick 
isSafeToMove(Instruction * Inst,AliasAnalysis & AA,SmallPtrSetImpl<Instruction * > & Stores)3009467b48Spatrick static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA,
3109467b48Spatrick                          SmallPtrSetImpl<Instruction *> &Stores) {
3209467b48Spatrick 
3309467b48Spatrick   if (Inst->mayWriteToMemory()) {
3409467b48Spatrick     Stores.insert(Inst);
3509467b48Spatrick     return false;
3609467b48Spatrick   }
3709467b48Spatrick 
3809467b48Spatrick   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
3909467b48Spatrick     MemoryLocation Loc = MemoryLocation::get(L);
4009467b48Spatrick     for (Instruction *S : Stores)
4109467b48Spatrick       if (isModSet(AA.getModRefInfo(S, Loc)))
4209467b48Spatrick         return false;
4309467b48Spatrick   }
4409467b48Spatrick 
4509467b48Spatrick   if (Inst->isTerminator() || isa<PHINode>(Inst) || Inst->isEHPad() ||
46*d415bd75Srobert       Inst->mayThrow() || !Inst->willReturn())
4709467b48Spatrick     return false;
4809467b48Spatrick 
4909467b48Spatrick   if (auto *Call = dyn_cast<CallBase>(Inst)) {
5009467b48Spatrick     // Convergent operations cannot be made control-dependent on additional
5109467b48Spatrick     // values.
5209467b48Spatrick     if (Call->isConvergent())
5309467b48Spatrick       return false;
5409467b48Spatrick 
5509467b48Spatrick     for (Instruction *S : Stores)
5609467b48Spatrick       if (isModSet(AA.getModRefInfo(S, Call)))
5709467b48Spatrick         return false;
5809467b48Spatrick   }
5909467b48Spatrick 
6009467b48Spatrick   return true;
6109467b48Spatrick }
6209467b48Spatrick 
6309467b48Spatrick /// IsAcceptableTarget - Return true if it is possible to sink the instruction
6409467b48Spatrick /// in the specified basic block.
IsAcceptableTarget(Instruction * Inst,BasicBlock * SuccToSinkTo,DominatorTree & DT,LoopInfo & LI)6509467b48Spatrick static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
6609467b48Spatrick                                DominatorTree &DT, LoopInfo &LI) {
6709467b48Spatrick   assert(Inst && "Instruction to be sunk is null");
6809467b48Spatrick   assert(SuccToSinkTo && "Candidate sink target is null");
6909467b48Spatrick 
7009467b48Spatrick   // It's never legal to sink an instruction into a block which terminates in an
7109467b48Spatrick   // EH-pad.
7209467b48Spatrick   if (SuccToSinkTo->getTerminator()->isExceptionalTerminator())
7309467b48Spatrick     return false;
7409467b48Spatrick 
7509467b48Spatrick   // If the block has multiple predecessors, this would introduce computation
7609467b48Spatrick   // on different code paths.  We could split the critical edge, but for now we
7709467b48Spatrick   // just punt.
7809467b48Spatrick   // FIXME: Split critical edges if not backedges.
7909467b48Spatrick   if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
8009467b48Spatrick     // We cannot sink a load across a critical edge - there may be stores in
8109467b48Spatrick     // other code paths.
82*d415bd75Srobert     if (Inst->mayReadFromMemory() &&
83*d415bd75Srobert         !Inst->hasMetadata(LLVMContext::MD_invariant_load))
8409467b48Spatrick       return false;
8509467b48Spatrick 
8609467b48Spatrick     // We don't want to sink across a critical edge if we don't dominate the
8709467b48Spatrick     // successor. We could be introducing calculations to new code paths.
8809467b48Spatrick     if (!DT.dominates(Inst->getParent(), SuccToSinkTo))
8909467b48Spatrick       return false;
9009467b48Spatrick 
9109467b48Spatrick     // Don't sink instructions into a loop.
9209467b48Spatrick     Loop *succ = LI.getLoopFor(SuccToSinkTo);
9309467b48Spatrick     Loop *cur = LI.getLoopFor(Inst->getParent());
9409467b48Spatrick     if (succ != nullptr && succ != cur)
9509467b48Spatrick       return false;
9609467b48Spatrick   }
9709467b48Spatrick 
9873471bf0Spatrick   return true;
9909467b48Spatrick }
10009467b48Spatrick 
10109467b48Spatrick /// SinkInstruction - Determine whether it is safe to sink the specified machine
10209467b48Spatrick /// instruction out of its current block into a successor.
SinkInstruction(Instruction * Inst,SmallPtrSetImpl<Instruction * > & Stores,DominatorTree & DT,LoopInfo & LI,AAResults & AA)10309467b48Spatrick static bool SinkInstruction(Instruction *Inst,
10409467b48Spatrick                             SmallPtrSetImpl<Instruction *> &Stores,
10509467b48Spatrick                             DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
10609467b48Spatrick 
10709467b48Spatrick   // Don't sink static alloca instructions.  CodeGen assumes allocas outside the
10809467b48Spatrick   // entry block are dynamically sized stack objects.
10909467b48Spatrick   if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
11009467b48Spatrick     if (AI->isStaticAlloca())
11109467b48Spatrick       return false;
11209467b48Spatrick 
11309467b48Spatrick   // Check if it's safe to move the instruction.
11409467b48Spatrick   if (!isSafeToMove(Inst, AA, Stores))
11509467b48Spatrick     return false;
11609467b48Spatrick 
11709467b48Spatrick   // FIXME: This should include support for sinking instructions within the
11809467b48Spatrick   // block they are currently in to shorten the live ranges.  We often get
11909467b48Spatrick   // instructions sunk into the top of a large block, but it would be better to
12009467b48Spatrick   // also sink them down before their first use in the block.  This xform has to
12109467b48Spatrick   // be careful not to *increase* register pressure though, e.g. sinking
12209467b48Spatrick   // "x = y + z" down if it kills y and z would increase the live ranges of y
12309467b48Spatrick   // and z and only shrink the live range of x.
12409467b48Spatrick 
12509467b48Spatrick   // SuccToSinkTo - This is the successor to sink this instruction to, once we
12609467b48Spatrick   // decide.
12709467b48Spatrick   BasicBlock *SuccToSinkTo = nullptr;
12809467b48Spatrick 
12973471bf0Spatrick   // Find the nearest common dominator of all users as the candidate.
13073471bf0Spatrick   BasicBlock *BB = Inst->getParent();
13173471bf0Spatrick   for (Use &U : Inst->uses()) {
13273471bf0Spatrick     Instruction *UseInst = cast<Instruction>(U.getUser());
13373471bf0Spatrick     BasicBlock *UseBlock = UseInst->getParent();
13473471bf0Spatrick     // Don't worry about dead users.
13573471bf0Spatrick     if (!DT.isReachableFromEntry(UseBlock))
13673471bf0Spatrick       continue;
13773471bf0Spatrick     if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
13873471bf0Spatrick       // PHI nodes use the operand in the predecessor block, not the block with
13973471bf0Spatrick       // the PHI.
14073471bf0Spatrick       unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
14173471bf0Spatrick       UseBlock = PN->getIncomingBlock(Num);
14273471bf0Spatrick     }
14373471bf0Spatrick     if (SuccToSinkTo)
14473471bf0Spatrick       SuccToSinkTo = DT.findNearestCommonDominator(SuccToSinkTo, UseBlock);
14573471bf0Spatrick     else
14673471bf0Spatrick       SuccToSinkTo = UseBlock;
14773471bf0Spatrick     // The current basic block needs to dominate the candidate.
14873471bf0Spatrick     if (!DT.dominates(BB, SuccToSinkTo))
14973471bf0Spatrick       return false;
15009467b48Spatrick   }
15109467b48Spatrick 
15273471bf0Spatrick   if (SuccToSinkTo) {
15373471bf0Spatrick     // The nearest common dominator may be in a parent loop of BB, which may not
15473471bf0Spatrick     // be beneficial. Find an ancestor.
15573471bf0Spatrick     while (SuccToSinkTo != BB &&
15673471bf0Spatrick            !IsAcceptableTarget(Inst, SuccToSinkTo, DT, LI))
15773471bf0Spatrick       SuccToSinkTo = DT.getNode(SuccToSinkTo)->getIDom()->getBlock();
15873471bf0Spatrick     if (SuccToSinkTo == BB)
15973471bf0Spatrick       SuccToSinkTo = nullptr;
16009467b48Spatrick   }
16109467b48Spatrick 
16209467b48Spatrick   // If we couldn't find a block to sink to, ignore this instruction.
16309467b48Spatrick   if (!SuccToSinkTo)
16409467b48Spatrick     return false;
16509467b48Spatrick 
16609467b48Spatrick   LLVM_DEBUG(dbgs() << "Sink" << *Inst << " (";
16709467b48Spatrick              Inst->getParent()->printAsOperand(dbgs(), false); dbgs() << " -> ";
16809467b48Spatrick              SuccToSinkTo->printAsOperand(dbgs(), false); dbgs() << ")\n");
16909467b48Spatrick 
17009467b48Spatrick   // Move the instruction.
17109467b48Spatrick   Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
17209467b48Spatrick   return true;
17309467b48Spatrick }
17409467b48Spatrick 
ProcessBlock(BasicBlock & BB,DominatorTree & DT,LoopInfo & LI,AAResults & AA)17509467b48Spatrick static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI,
17609467b48Spatrick                          AAResults &AA) {
17709467b48Spatrick   // Don't bother sinking code out of unreachable blocks. In addition to being
17809467b48Spatrick   // unprofitable, it can also lead to infinite looping, because in an
17909467b48Spatrick   // unreachable loop there may be nowhere to stop.
18009467b48Spatrick   if (!DT.isReachableFromEntry(&BB)) return false;
18109467b48Spatrick 
18209467b48Spatrick   bool MadeChange = false;
18309467b48Spatrick 
18409467b48Spatrick   // Walk the basic block bottom-up.  Remember if we saw a store.
18509467b48Spatrick   BasicBlock::iterator I = BB.end();
18609467b48Spatrick   --I;
18709467b48Spatrick   bool ProcessedBegin = false;
18809467b48Spatrick   SmallPtrSet<Instruction *, 8> Stores;
18909467b48Spatrick   do {
19009467b48Spatrick     Instruction *Inst = &*I; // The instruction to sink.
19109467b48Spatrick 
19209467b48Spatrick     // Predecrement I (if it's not begin) so that it isn't invalidated by
19309467b48Spatrick     // sinking.
19409467b48Spatrick     ProcessedBegin = I == BB.begin();
19509467b48Spatrick     if (!ProcessedBegin)
19609467b48Spatrick       --I;
19709467b48Spatrick 
19873471bf0Spatrick     if (Inst->isDebugOrPseudoInst())
19909467b48Spatrick       continue;
20009467b48Spatrick 
20109467b48Spatrick     if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
20209467b48Spatrick       ++NumSunk;
20309467b48Spatrick       MadeChange = true;
20409467b48Spatrick     }
20509467b48Spatrick 
20609467b48Spatrick     // If we just processed the first instruction in the block, we're done.
20709467b48Spatrick   } while (!ProcessedBegin);
20809467b48Spatrick 
20909467b48Spatrick   return MadeChange;
21009467b48Spatrick }
21109467b48Spatrick 
iterativelySinkInstructions(Function & F,DominatorTree & DT,LoopInfo & LI,AAResults & AA)21209467b48Spatrick static bool iterativelySinkInstructions(Function &F, DominatorTree &DT,
21309467b48Spatrick                                         LoopInfo &LI, AAResults &AA) {
21409467b48Spatrick   bool MadeChange, EverMadeChange = false;
21509467b48Spatrick 
21609467b48Spatrick   do {
21709467b48Spatrick     MadeChange = false;
21809467b48Spatrick     LLVM_DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
21909467b48Spatrick     // Process all basic blocks.
22009467b48Spatrick     for (BasicBlock &I : F)
22109467b48Spatrick       MadeChange |= ProcessBlock(I, DT, LI, AA);
22209467b48Spatrick     EverMadeChange |= MadeChange;
22309467b48Spatrick     NumSinkIter++;
22409467b48Spatrick   } while (MadeChange);
22509467b48Spatrick 
22609467b48Spatrick   return EverMadeChange;
22709467b48Spatrick }
22809467b48Spatrick 
run(Function & F,FunctionAnalysisManager & AM)22909467b48Spatrick PreservedAnalyses SinkingPass::run(Function &F, FunctionAnalysisManager &AM) {
23009467b48Spatrick   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
23109467b48Spatrick   auto &LI = AM.getResult<LoopAnalysis>(F);
23209467b48Spatrick   auto &AA = AM.getResult<AAManager>(F);
23309467b48Spatrick 
23409467b48Spatrick   if (!iterativelySinkInstructions(F, DT, LI, AA))
23509467b48Spatrick     return PreservedAnalyses::all();
23609467b48Spatrick 
23709467b48Spatrick   PreservedAnalyses PA;
23809467b48Spatrick   PA.preserveSet<CFGAnalyses>();
23909467b48Spatrick   return PA;
24009467b48Spatrick }
24109467b48Spatrick 
24209467b48Spatrick namespace {
24309467b48Spatrick   class SinkingLegacyPass : public FunctionPass {
24409467b48Spatrick   public:
24509467b48Spatrick     static char ID; // Pass identification
SinkingLegacyPass()24609467b48Spatrick     SinkingLegacyPass() : FunctionPass(ID) {
24709467b48Spatrick       initializeSinkingLegacyPassPass(*PassRegistry::getPassRegistry());
24809467b48Spatrick     }
24909467b48Spatrick 
runOnFunction(Function & F)25009467b48Spatrick     bool runOnFunction(Function &F) override {
25109467b48Spatrick       auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
25209467b48Spatrick       auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
25309467b48Spatrick       auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
25409467b48Spatrick 
25509467b48Spatrick       return iterativelySinkInstructions(F, DT, LI, AA);
25609467b48Spatrick     }
25709467b48Spatrick 
getAnalysisUsage(AnalysisUsage & AU) const25809467b48Spatrick     void getAnalysisUsage(AnalysisUsage &AU) const override {
25909467b48Spatrick       AU.setPreservesCFG();
26009467b48Spatrick       FunctionPass::getAnalysisUsage(AU);
26109467b48Spatrick       AU.addRequired<AAResultsWrapperPass>();
26209467b48Spatrick       AU.addRequired<DominatorTreeWrapperPass>();
26309467b48Spatrick       AU.addRequired<LoopInfoWrapperPass>();
26409467b48Spatrick       AU.addPreserved<DominatorTreeWrapperPass>();
26509467b48Spatrick       AU.addPreserved<LoopInfoWrapperPass>();
26609467b48Spatrick     }
26709467b48Spatrick   };
26809467b48Spatrick } // end anonymous namespace
26909467b48Spatrick 
27009467b48Spatrick char SinkingLegacyPass::ID = 0;
27109467b48Spatrick INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)27209467b48Spatrick INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
27309467b48Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
27409467b48Spatrick INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
27509467b48Spatrick INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
27609467b48Spatrick 
27709467b48Spatrick FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }
278