1 //===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
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 #include "llvm/Analysis/MustExecute.h"
11 #include "llvm/Analysis/InstructionSimplify.h"
12 #include "llvm/Analysis/LoopInfo.h"
13 #include "llvm/Analysis/Passes.h"
14 #include "llvm/Analysis/ValueTracking.h"
15 #include "llvm/IR/AssemblyAnnotationWriter.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/InstIterator.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/FormattedStream.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24 
25 /// Computes loop safety information, checks loop body & header
26 /// for the possibility of may throw exception.
27 ///
computeLoopSafetyInfo(LoopSafetyInfo * SafetyInfo,Loop * CurLoop)28 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
29   assert(CurLoop != nullptr && "CurLoop can't be null");
30   BasicBlock *Header = CurLoop->getHeader();
31   // Setting default safety values.
32   SafetyInfo->MayThrow = false;
33   SafetyInfo->HeaderMayThrow = false;
34   // Iterate over header and compute safety info.
35   SafetyInfo->HeaderMayThrow =
36     !isGuaranteedToTransferExecutionToSuccessor(Header);
37 
38   SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
39   // Iterate over loop instructions and compute safety info.
40   // Skip header as it has been computed and stored in HeaderMayThrow.
41   // The first block in loopinfo.Blocks is guaranteed to be the header.
42   assert(Header == *CurLoop->getBlocks().begin() &&
43          "First block must be header");
44   for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
45                             BBE = CurLoop->block_end();
46        (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
47     SafetyInfo->MayThrow |=
48       !isGuaranteedToTransferExecutionToSuccessor(*BB);
49 
50   // Compute funclet colors if we might sink/hoist in a function with a funclet
51   // personality routine.
52   Function *Fn = CurLoop->getHeader()->getParent();
53   if (Fn->hasPersonalityFn())
54     if (Constant *PersonalityFn = Fn->getPersonalityFn())
55       if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
56         SafetyInfo->BlockColors = colorEHFunclets(*Fn);
57 }
58 
59 /// Return true if we can prove that the given ExitBlock is not reached on the
60 /// first iteration of the given loop.  That is, the backedge of the loop must
61 /// be executed before the ExitBlock is executed in any dynamic execution trace.
CanProveNotTakenFirstIteration(BasicBlock * ExitBlock,const DominatorTree * DT,const Loop * CurLoop)62 static bool CanProveNotTakenFirstIteration(BasicBlock *ExitBlock,
63                                            const DominatorTree *DT,
64                                            const Loop *CurLoop) {
65   auto *CondExitBlock = ExitBlock->getSinglePredecessor();
66   if (!CondExitBlock)
67     // expect unique exits
68     return false;
69   assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
70   auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
71   if (!BI || !BI->isConditional())
72     return false;
73   // If condition is constant and false leads to ExitBlock then we always
74   // execute the true branch.
75   if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
76     return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
77   auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
78   if (!Cond)
79     return false;
80   // todo: this would be a lot more powerful if we used scev, but all the
81   // plumbing is currently missing to pass a pointer in from the pass
82   // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
83   auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
84   auto *RHS = Cond->getOperand(1);
85   if (!LHS || LHS->getParent() != CurLoop->getHeader())
86     return false;
87   auto DL = ExitBlock->getModule()->getDataLayout();
88   auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
89   auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
90                                           IVStart, RHS,
91                                           {DL, /*TLI*/ nullptr,
92                                               DT, /*AC*/ nullptr, BI});
93   auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
94   if (!SimpleCst)
95     return false;
96   if (ExitBlock == BI->getSuccessor(0))
97     return SimpleCst->isZeroValue();
98   assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
99   return SimpleCst->isAllOnesValue();
100 }
101 
102 /// Returns true if the instruction in a loop is guaranteed to execute at least
103 /// once.
isGuaranteedToExecute(const Instruction & Inst,const DominatorTree * DT,const Loop * CurLoop,const LoopSafetyInfo * SafetyInfo)104 bool llvm::isGuaranteedToExecute(const Instruction &Inst,
105                                  const DominatorTree *DT, const Loop *CurLoop,
106                                  const LoopSafetyInfo *SafetyInfo) {
107   // We have to check to make sure that the instruction dominates all
108   // of the exit blocks.  If it doesn't, then there is a path out of the loop
109   // which does not execute this instruction, so we can't hoist it.
110 
111   // If the instruction is in the header block for the loop (which is very
112   // common), it is always guaranteed to dominate the exit blocks.  Since this
113   // is a common case, and can save some work, check it now.
114   if (Inst.getParent() == CurLoop->getHeader())
115     // If there's a throw in the header block, we can't guarantee we'll reach
116     // Inst unless we can prove that Inst comes before the potential implicit
117     // exit.  At the moment, we use a (cheap) hack for the common case where
118     // the instruction of interest is the first one in the block.
119     return !SafetyInfo->HeaderMayThrow ||
120       Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
121 
122   // Somewhere in this loop there is an instruction which may throw and make us
123   // exit the loop.
124   if (SafetyInfo->MayThrow)
125     return false;
126 
127   // Note: There are two styles of reasoning intermixed below for
128   // implementation efficiency reasons.  They are:
129   // 1) If we can prove that the instruction dominates all exit blocks, then we
130   // know the instruction must have executed on *some* iteration before we
131   // exit.  We do not prove *which* iteration the instruction must execute on.
132   // 2) If we can prove that the instruction dominates the latch and all exits
133   // which might be taken on the first iteration, we know the instruction must
134   // execute on the first iteration.  This second style allows a conditional
135   // exit before the instruction of interest which is provably not taken on the
136   // first iteration.  This is a quite common case for range check like
137   // patterns.  TODO: support loops with multiple latches.
138 
139   const bool InstDominatesLatch =
140     CurLoop->getLoopLatch() != nullptr &&
141     DT->dominates(Inst.getParent(), CurLoop->getLoopLatch());
142 
143   // Get the exit blocks for the current loop.
144   SmallVector<BasicBlock *, 8> ExitBlocks;
145   CurLoop->getExitBlocks(ExitBlocks);
146 
147   // Verify that the block dominates each of the exit blocks of the loop.
148   for (BasicBlock *ExitBlock : ExitBlocks)
149     if (!DT->dominates(Inst.getParent(), ExitBlock))
150       if (!InstDominatesLatch ||
151           !CanProveNotTakenFirstIteration(ExitBlock, DT, CurLoop))
152         return false;
153 
154   // As a degenerate case, if the loop is statically infinite then we haven't
155   // proven anything since there are no exit blocks.
156   if (ExitBlocks.empty())
157     return false;
158 
159   // FIXME: In general, we have to prove that the loop isn't an infinite loop.
160   // See http::llvm.org/PR24078 .  (The "ExitBlocks.empty()" check above is
161   // just a special case of this.)
162   return true;
163 }
164 
165 
166 namespace {
167   struct MustExecutePrinter : public FunctionPass {
168 
169     static char ID; // Pass identification, replacement for typeid
MustExecutePrinter__anon7f5155590111::MustExecutePrinter170     MustExecutePrinter() : FunctionPass(ID) {
171       initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
172     }
getAnalysisUsage__anon7f5155590111::MustExecutePrinter173     void getAnalysisUsage(AnalysisUsage &AU) const override {
174       AU.setPreservesAll();
175       AU.addRequired<DominatorTreeWrapperPass>();
176       AU.addRequired<LoopInfoWrapperPass>();
177     }
178     bool runOnFunction(Function &F) override;
179   };
180 }
181 
182 char MustExecutePrinter::ID = 0;
183 INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
184                       "Instructions which execute on loop entry", false, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)185 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
186 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
187 INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
188                     "Instructions which execute on loop entry", false, true)
189 
190 FunctionPass *llvm::createMustExecutePrinter() {
191   return new MustExecutePrinter();
192 }
193 
isMustExecuteIn(const Instruction & I,Loop * L,DominatorTree * DT)194 static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
195   // TODO: merge these two routines.  For the moment, we display the best
196   // result obtained by *either* implementation.  This is a bit unfair since no
197   // caller actually gets the full power at the moment.
198   LoopSafetyInfo LSI;
199   computeLoopSafetyInfo(&LSI, L);
200   return isGuaranteedToExecute(I, DT, L, &LSI) ||
201     isGuaranteedToExecuteForEveryIteration(&I, L);
202 }
203 
204 namespace {
205 /// An assembly annotator class to print must execute information in
206 /// comments.
207 class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
208   DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
209 
210 public:
MustExecuteAnnotatedWriter(const Function & F,DominatorTree & DT,LoopInfo & LI)211   MustExecuteAnnotatedWriter(const Function &F,
212                              DominatorTree &DT, LoopInfo &LI) {
213     for (auto &I: instructions(F)) {
214       Loop *L = LI.getLoopFor(I.getParent());
215       while (L) {
216         if (isMustExecuteIn(I, L, &DT)) {
217           MustExec[&I].push_back(L);
218         }
219         L = L->getParentLoop();
220       };
221     }
222   }
MustExecuteAnnotatedWriter(const Module & M,DominatorTree & DT,LoopInfo & LI)223   MustExecuteAnnotatedWriter(const Module &M,
224                              DominatorTree &DT, LoopInfo &LI) {
225     for (auto &F : M)
226     for (auto &I: instructions(F)) {
227       Loop *L = LI.getLoopFor(I.getParent());
228       while (L) {
229         if (isMustExecuteIn(I, L, &DT)) {
230           MustExec[&I].push_back(L);
231         }
232         L = L->getParentLoop();
233       };
234     }
235   }
236 
237 
printInfoComment(const Value & V,formatted_raw_ostream & OS)238   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
239     if (!MustExec.count(&V))
240       return;
241 
242     const auto &Loops = MustExec.lookup(&V);
243     const auto NumLoops = Loops.size();
244     if (NumLoops > 1)
245       OS << " ; (mustexec in " << NumLoops << " loops: ";
246     else
247       OS << " ; (mustexec in: ";
248 
249     bool first = true;
250     for (const Loop *L : Loops) {
251       if (!first)
252         OS << ", ";
253       first = false;
254       OS << L->getHeader()->getName();
255     }
256     OS << ")";
257   }
258 };
259 } // namespace
260 
runOnFunction(Function & F)261 bool MustExecutePrinter::runOnFunction(Function &F) {
262   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
263   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
264 
265   MustExecuteAnnotatedWriter Writer(F, DT, LI);
266   F.print(dbgs(), &Writer);
267 
268   return false;
269 }
270