xref: /llvm-project/llvm/lib/Analysis/MustExecute.cpp (revision bb84407f3d97da8664e9c3e6aa6eaef6a894ca1e)
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 const DenseMap<BasicBlock *, ColorVector> &
26 LoopSafetyInfo::getBlockColors() const {
27   return BlockColors;
28 }
29 
30 void LoopSafetyInfo::copyColors(BasicBlock *New, BasicBlock *Old) {
31   ColorVector &ColorsForNewBlock = BlockColors[New];
32   ColorVector &ColorsForOldBlock = BlockColors[Old];
33   ColorsForNewBlock = ColorsForOldBlock;
34 }
35 
36 bool SimpleLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
37   (void)BB;
38   return anyBlockMayThrow();
39 }
40 
41 bool SimpleLoopSafetyInfo::anyBlockMayThrow() const {
42   return MayThrow;
43 }
44 
45 void SimpleLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
46   assert(CurLoop != nullptr && "CurLoop can't be null");
47   BasicBlock *Header = CurLoop->getHeader();
48   // Iterate over header and compute safety info.
49   HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
50   MayThrow = HeaderMayThrow;
51   // Iterate over loop instructions and compute safety info.
52   // Skip header as it has been computed and stored in HeaderMayThrow.
53   // The first block in loopinfo.Blocks is guaranteed to be the header.
54   assert(Header == *CurLoop->getBlocks().begin() &&
55          "First block must be header");
56   for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
57                             BBE = CurLoop->block_end();
58        (BB != BBE) && !MayThrow; ++BB)
59     MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
60 
61   computeBlockColors(CurLoop);
62 }
63 
64 bool ICFLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
65   return ICF.hasICF(BB);
66 }
67 
68 bool ICFLoopSafetyInfo::anyBlockMayThrow() const {
69   return MayThrow;
70 }
71 
72 void ICFLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
73   assert(CurLoop != nullptr && "CurLoop can't be null");
74   ICF.clear();
75   MayThrow = false;
76   // Figure out the fact that at least one block may throw.
77   for (auto &BB : CurLoop->blocks())
78     if (ICF.hasICF(&*BB)) {
79       MayThrow = true;
80       break;
81     }
82   computeBlockColors(CurLoop);
83 }
84 
85 void ICFLoopSafetyInfo::insertInstructionTo(const BasicBlock *BB) {
86   ICF.invalidateBlock(BB);
87 }
88 
89 void ICFLoopSafetyInfo::removeInstruction(const Instruction *Inst) {
90   // TODO: So far we just conservatively drop cache, but maybe we can not do it
91   // when Inst is not an ICF instruction. Follow-up on that.
92   ICF.invalidateBlock(Inst->getParent());
93 }
94 
95 void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) {
96   // Compute funclet colors if we might sink/hoist in a function with a funclet
97   // personality routine.
98   Function *Fn = CurLoop->getHeader()->getParent();
99   if (Fn->hasPersonalityFn())
100     if (Constant *PersonalityFn = Fn->getPersonalityFn())
101       if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
102         BlockColors = colorEHFunclets(*Fn);
103 }
104 
105 /// Return true if we can prove that the given ExitBlock is not reached on the
106 /// first iteration of the given loop.  That is, the backedge of the loop must
107 /// be executed before the ExitBlock is executed in any dynamic execution trace.
108 static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
109                                            const DominatorTree *DT,
110                                            const Loop *CurLoop) {
111   auto *CondExitBlock = ExitBlock->getSinglePredecessor();
112   if (!CondExitBlock)
113     // expect unique exits
114     return false;
115   assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
116   auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
117   if (!BI || !BI->isConditional())
118     return false;
119   // If condition is constant and false leads to ExitBlock then we always
120   // execute the true branch.
121   if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
122     return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
123   auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
124   if (!Cond)
125     return false;
126   // todo: this would be a lot more powerful if we used scev, but all the
127   // plumbing is currently missing to pass a pointer in from the pass
128   // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
129   auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
130   auto *RHS = Cond->getOperand(1);
131   if (!LHS || LHS->getParent() != CurLoop->getHeader())
132     return false;
133   auto DL = ExitBlock->getModule()->getDataLayout();
134   auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
135   auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
136                                           IVStart, RHS,
137                                           {DL, /*TLI*/ nullptr,
138                                               DT, /*AC*/ nullptr, BI});
139   auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
140   if (!SimpleCst)
141     return false;
142   if (ExitBlock == BI->getSuccessor(0))
143     return SimpleCst->isZeroValue();
144   assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
145   return SimpleCst->isAllOnesValue();
146 }
147 
148 void LoopSafetyInfo::collectTransitivePredecessors(
149     const Loop *CurLoop, const BasicBlock *BB,
150     SmallPtrSetImpl<const BasicBlock *> &Predecessors) const {
151   assert(Predecessors.empty() && "Garbage in predecessors set?");
152   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
153   if (BB == CurLoop->getHeader())
154     return;
155   SmallVector<const BasicBlock *, 4> WorkList;
156   for (auto *Pred : predecessors(BB)) {
157     Predecessors.insert(Pred);
158     WorkList.push_back(Pred);
159   }
160   while (!WorkList.empty()) {
161     auto *Pred = WorkList.pop_back_val();
162     assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
163     // We are not interested in backedges and we don't want to leave loop.
164     if (Pred == CurLoop->getHeader())
165       continue;
166     // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
167     // blocks of this inner loop, even those that are always executed AFTER the
168     // BB. It may make our analysis more conservative than it could be, see test
169     // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
170     // We can ignore backedge of all loops containing BB to get a sligtly more
171     // optimistic result.
172     for (auto *PredPred : predecessors(Pred))
173       if (Predecessors.insert(PredPred).second)
174         WorkList.push_back(PredPred);
175   }
176 }
177 
178 bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
179                                              const BasicBlock *BB,
180                                              const DominatorTree *DT) const {
181   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
182 
183   // Fast path: header is always reached once the loop is entered.
184   if (BB == CurLoop->getHeader())
185     return true;
186 
187   // Collect all transitive predecessors of BB in the same loop. This set will
188   // be a subset of the blocks within the loop.
189   SmallPtrSet<const BasicBlock *, 4> Predecessors;
190   collectTransitivePredecessors(CurLoop, BB, Predecessors);
191 
192   // Make sure that all successors of all predecessors of BB are either:
193   // 1) BB,
194   // 2) Also predecessors of BB,
195   // 3) Exit blocks which are not taken on 1st iteration.
196   // Memoize blocks we've already checked.
197   SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
198   for (auto *Pred : Predecessors) {
199     // Predecessor block may throw, so it has a side exit.
200     if (blockMayThrow(Pred))
201       return false;
202     for (auto *Succ : successors(Pred))
203       if (CheckedSuccessors.insert(Succ).second &&
204           Succ != BB && !Predecessors.count(Succ))
205         // By discharging conditions that are not executed on the 1st iteration,
206         // we guarantee that *at least* on the first iteration all paths from
207         // header that *may* execute will lead us to the block of interest. So
208         // that if we had virtually peeled one iteration away, in this peeled
209         // iteration the set of predecessors would contain only paths from
210         // header to BB without any exiting edges that may execute.
211         //
212         // TODO: We only do it for exiting edges currently. We could use the
213         // same function to skip some of the edges within the loop if we know
214         // that they will not be taken on the 1st iteration.
215         //
216         // TODO: If we somehow know the number of iterations in loop, the same
217         // check may be done for any arbitrary N-th iteration as long as N is
218         // not greater than minimum number of iterations in this loop.
219         if (CurLoop->contains(Succ) ||
220             !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
221           return false;
222   }
223 
224   // All predecessors can only lead us to BB.
225   return true;
226 }
227 
228 /// Returns true if the instruction in a loop is guaranteed to execute at least
229 /// once.
230 bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
231                                                  const DominatorTree *DT,
232                                                  const Loop *CurLoop) const {
233   // If the instruction is in the header block for the loop (which is very
234   // common), it is always guaranteed to dominate the exit blocks.  Since this
235   // is a common case, and can save some work, check it now.
236   if (Inst.getParent() == CurLoop->getHeader())
237     // If there's a throw in the header block, we can't guarantee we'll reach
238     // Inst unless we can prove that Inst comes before the potential implicit
239     // exit.  At the moment, we use a (cheap) hack for the common case where
240     // the instruction of interest is the first one in the block.
241     return !HeaderMayThrow ||
242            Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
243 
244   // If there is a path from header to exit or latch that doesn't lead to our
245   // instruction's block, return false.
246   return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
247 }
248 
249 bool ICFLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
250                                               const DominatorTree *DT,
251                                               const Loop *CurLoop) const {
252   return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
253          allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
254 }
255 
256 namespace {
257   struct MustExecutePrinter : public FunctionPass {
258 
259     static char ID; // Pass identification, replacement for typeid
260     MustExecutePrinter() : FunctionPass(ID) {
261       initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
262     }
263     void getAnalysisUsage(AnalysisUsage &AU) const override {
264       AU.setPreservesAll();
265       AU.addRequired<DominatorTreeWrapperPass>();
266       AU.addRequired<LoopInfoWrapperPass>();
267     }
268     bool runOnFunction(Function &F) override;
269   };
270 }
271 
272 char MustExecutePrinter::ID = 0;
273 INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
274                       "Instructions which execute on loop entry", false, true)
275 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
276 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
277 INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
278                     "Instructions which execute on loop entry", false, true)
279 
280 FunctionPass *llvm::createMustExecutePrinter() {
281   return new MustExecutePrinter();
282 }
283 
284 static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
285   // TODO: merge these two routines.  For the moment, we display the best
286   // result obtained by *either* implementation.  This is a bit unfair since no
287   // caller actually gets the full power at the moment.
288   SimpleLoopSafetyInfo LSI;
289   LSI.computeLoopSafetyInfo(L);
290   return LSI.isGuaranteedToExecute(I, DT, L) ||
291     isGuaranteedToExecuteForEveryIteration(&I, L);
292 }
293 
294 namespace {
295 /// An assembly annotator class to print must execute information in
296 /// comments.
297 class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
298   DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
299 
300 public:
301   MustExecuteAnnotatedWriter(const Function &F,
302                              DominatorTree &DT, LoopInfo &LI) {
303     for (auto &I: instructions(F)) {
304       Loop *L = LI.getLoopFor(I.getParent());
305       while (L) {
306         if (isMustExecuteIn(I, L, &DT)) {
307           MustExec[&I].push_back(L);
308         }
309         L = L->getParentLoop();
310       };
311     }
312   }
313   MustExecuteAnnotatedWriter(const Module &M,
314                              DominatorTree &DT, LoopInfo &LI) {
315     for (auto &F : M)
316     for (auto &I: instructions(F)) {
317       Loop *L = LI.getLoopFor(I.getParent());
318       while (L) {
319         if (isMustExecuteIn(I, L, &DT)) {
320           MustExec[&I].push_back(L);
321         }
322         L = L->getParentLoop();
323       };
324     }
325   }
326 
327 
328   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
329     if (!MustExec.count(&V))
330       return;
331 
332     const auto &Loops = MustExec.lookup(&V);
333     const auto NumLoops = Loops.size();
334     if (NumLoops > 1)
335       OS << " ; (mustexec in " << NumLoops << " loops: ";
336     else
337       OS << " ; (mustexec in: ";
338 
339     bool first = true;
340     for (const Loop *L : Loops) {
341       if (!first)
342         OS << ", ";
343       first = false;
344       OS << L->getHeader()->getName();
345     }
346     OS << ")";
347   }
348 };
349 } // namespace
350 
351 bool MustExecutePrinter::runOnFunction(Function &F) {
352   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
353   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
354 
355   MustExecuteAnnotatedWriter Writer(F, DT, LI);
356   F.print(dbgs(), &Writer);
357 
358   return false;
359 }
360