blob: 7f0912de26b6467758d36072315d505beef28661 [file] [log] [blame]
Philip Reames89f22412018-03-20 17:09:21 +00001//===- 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
Philip Reamese4b728e2018-03-29 19:22:12 +000010#include "llvm/Analysis/MustExecute.h"
Philip Reames23aed5e2018-03-20 22:45:23 +000011#include "llvm/Analysis/InstructionSimplify.h"
Philip Reames89f22412018-03-20 17:09:21 +000012#include "llvm/Analysis/LoopInfo.h"
13#include "llvm/Analysis/Passes.h"
14#include "llvm/Analysis/ValueTracking.h"
Philip Reamesce998ad2018-03-20 18:43:44 +000015#include "llvm/IR/AssemblyAnnotationWriter.h"
Philip Reames89f22412018-03-20 17:09:21 +000016#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"
Philip Reamesce998ad2018-03-20 18:43:44 +000021#include "llvm/Support/FormattedStream.h"
Philip Reames89f22412018-03-20 17:09:21 +000022#include "llvm/Support/raw_ostream.h"
Philip Reames89f22412018-03-20 17:09:21 +000023using namespace llvm;
24
Max Kazantsev530b8d12018-08-15 05:55:43 +000025bool LoopSafetyInfo::headerMayThrow() const {
26 return HeaderMayThrow;
27}
28
Max Kazantsev6a4f5e22018-10-16 07:50:14 +000029bool LoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
30 (void)BB;
31 return anyBlockMayThrow();
32}
33
Max Kazantsev530b8d12018-08-15 05:55:43 +000034bool LoopSafetyInfo::anyBlockMayThrow() const {
35 return MayThrow;
36}
37
38void LoopSafetyInfo::computeLoopSafetyInfo(Loop *CurLoop) {
Shoaib Meenaia57d7132018-07-19 19:11:29 +000039 assert(CurLoop != nullptr && "CurLoop can't be null");
Philip Reames23aed5e2018-03-20 22:45:23 +000040 BasicBlock *Header = CurLoop->getHeader();
Philip Reames23aed5e2018-03-20 22:45:23 +000041 // Iterate over header and compute safety info.
Max Kazantsev530b8d12018-08-15 05:55:43 +000042 HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
43 MayThrow = HeaderMayThrow;
Philip Reames23aed5e2018-03-20 22:45:23 +000044 // Iterate over loop instructions and compute safety info.
45 // Skip header as it has been computed and stored in HeaderMayThrow.
46 // The first block in loopinfo.Blocks is guaranteed to be the header.
47 assert(Header == *CurLoop->getBlocks().begin() &&
48 "First block must be header");
49 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
50 BBE = CurLoop->block_end();
Max Kazantsev530b8d12018-08-15 05:55:43 +000051 (BB != BBE) && !MayThrow; ++BB)
52 MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
Philip Reames23aed5e2018-03-20 22:45:23 +000053
54 // Compute funclet colors if we might sink/hoist in a function with a funclet
55 // personality routine.
56 Function *Fn = CurLoop->getHeader()->getParent();
57 if (Fn->hasPersonalityFn())
58 if (Constant *PersonalityFn = Fn->getPersonalityFn())
Heejin Ahnb4be38f2018-05-17 20:52:03 +000059 if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
Max Kazantsev530b8d12018-08-15 05:55:43 +000060 BlockColors = colorEHFunclets(*Fn);
Philip Reames23aed5e2018-03-20 22:45:23 +000061}
62
63/// Return true if we can prove that the given ExitBlock is not reached on the
64/// first iteration of the given loop. That is, the backedge of the loop must
65/// be executed before the ExitBlock is executed in any dynamic execution trace.
Max Kazantseva7415872018-08-16 06:28:04 +000066static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
Philip Reames23aed5e2018-03-20 22:45:23 +000067 const DominatorTree *DT,
68 const Loop *CurLoop) {
69 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
70 if (!CondExitBlock)
71 // expect unique exits
72 return false;
73 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
74 auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
75 if (!BI || !BI->isConditional())
76 return false;
Serguei Katkov50958832018-05-18 04:56:28 +000077 // If condition is constant and false leads to ExitBlock then we always
78 // execute the true branch.
79 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
80 return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
Philip Reames23aed5e2018-03-20 22:45:23 +000081 auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
82 if (!Cond)
83 return false;
84 // todo: this would be a lot more powerful if we used scev, but all the
85 // plumbing is currently missing to pass a pointer in from the pass
86 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
87 auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
88 auto *RHS = Cond->getOperand(1);
89 if (!LHS || LHS->getParent() != CurLoop->getHeader())
90 return false;
91 auto DL = ExitBlock->getModule()->getDataLayout();
92 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
93 auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
94 IVStart, RHS,
95 {DL, /*TLI*/ nullptr,
96 DT, /*AC*/ nullptr, BI});
97 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
98 if (!SimpleCst)
99 return false;
100 if (ExitBlock == BI->getSuccessor(0))
101 return SimpleCst->isZeroValue();
102 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
103 return SimpleCst->isAllOnesValue();
104}
105
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000106void LoopSafetyInfo::collectTransitivePredecessors(
107 const Loop *CurLoop, const BasicBlock *BB,
108 SmallPtrSetImpl<const BasicBlock *> &Predecessors) const {
109 assert(Predecessors.empty() && "Garbage in predecessors set?");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000110 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000111 if (BB == CurLoop->getHeader())
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000112 return;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000113 SmallVector<const BasicBlock *, 4> WorkList;
114 for (auto *Pred : predecessors(BB)) {
115 Predecessors.insert(Pred);
116 WorkList.push_back(Pred);
117 }
118 while (!WorkList.empty()) {
119 auto *Pred = WorkList.pop_back_val();
120 assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
121 // We are not interested in backedges and we don't want to leave loop.
122 if (Pred == CurLoop->getHeader())
123 continue;
124 // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
125 // blocks of this inner loop, even those that are always executed AFTER the
126 // BB. It may make our analysis more conservative than it could be, see test
127 // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
128 // We can ignore backedge of all loops containing BB to get a sligtly more
129 // optimistic result.
130 for (auto *PredPred : predecessors(Pred))
131 if (Predecessors.insert(PredPred).second)
132 WorkList.push_back(PredPred);
133 }
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000134}
135
136bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
137 const BasicBlock *BB,
138 const DominatorTree *DT) const {
139 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
140
141 // Fast path: header is always reached once the loop is entered.
142 if (BB == CurLoop->getHeader())
143 return true;
144
145 // Collect all transitive predecessors of BB in the same loop. This set will
146 // be a subset of the blocks within the loop.
147 SmallPtrSet<const BasicBlock *, 4> Predecessors;
148 collectTransitivePredecessors(CurLoop, BB, Predecessors);
Max Kazantsev7b78d392018-08-17 06:19:17 +0000149
150 // Make sure that all successors of all predecessors of BB are either:
151 // 1) BB,
152 // 2) Also predecessors of BB,
153 // 3) Exit blocks which are not taken on 1st iteration.
154 // Memoize blocks we've already checked.
155 SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000156 for (auto *Pred : Predecessors) {
157 // Predecessor block may throw, so it has a side exit.
158 if (blockMayThrow(Pred))
159 return false;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000160 for (auto *Succ : successors(Pred))
161 if (CheckedSuccessors.insert(Succ).second &&
162 Succ != BB && !Predecessors.count(Succ))
163 // By discharging conditions that are not executed on the 1st iteration,
164 // we guarantee that *at least* on the first iteration all paths from
165 // header that *may* execute will lead us to the block of interest. So
166 // that if we had virtually peeled one iteration away, in this peeled
167 // iteration the set of predecessors would contain only paths from
168 // header to BB without any exiting edges that may execute.
169 //
170 // TODO: We only do it for exiting edges currently. We could use the
171 // same function to skip some of the edges within the loop if we know
172 // that they will not be taken on the 1st iteration.
173 //
174 // TODO: If we somehow know the number of iterations in loop, the same
175 // check may be done for any arbitrary N-th iteration as long as N is
176 // not greater than minimum number of iterations in this loop.
177 if (CurLoop->contains(Succ) ||
178 !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
179 return false;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000180 }
Max Kazantsev7b78d392018-08-17 06:19:17 +0000181
182 // All predecessors can only lead us to BB.
183 return true;
184}
185
Philip Reames23aed5e2018-03-20 22:45:23 +0000186/// Returns true if the instruction in a loop is guaranteed to execute at least
187/// once.
Max Kazantsevc8466f92018-10-16 06:34:53 +0000188bool LoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
189 const DominatorTree *DT,
190 const Loop *CurLoop) const {
Philip Reames23aed5e2018-03-20 22:45:23 +0000191 // We have to check to make sure that the instruction dominates all
192 // of the exit blocks. If it doesn't, then there is a path out of the loop
193 // which does not execute this instruction, so we can't hoist it.
194
195 // If the instruction is in the header block for the loop (which is very
196 // common), it is always guaranteed to dominate the exit blocks. Since this
197 // is a common case, and can save some work, check it now.
198 if (Inst.getParent() == CurLoop->getHeader())
199 // If there's a throw in the header block, we can't guarantee we'll reach
Philip Reamese4ec4732018-04-27 20:44:01 +0000200 // Inst unless we can prove that Inst comes before the potential implicit
201 // exit. At the moment, we use a (cheap) hack for the common case where
202 // the instruction of interest is the first one in the block.
Max Kazantsevc8466f92018-10-16 06:34:53 +0000203 return !headerMayThrow() ||
204 Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
Philip Reames23aed5e2018-03-20 22:45:23 +0000205
Max Kazantsev7b78d392018-08-17 06:19:17 +0000206 // If there is a path from header to exit or latch that doesn't lead to our
207 // instruction's block, return false.
Max Kazantsevc8466f92018-10-16 06:34:53 +0000208 if (!allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT))
Philip Reames23aed5e2018-03-20 22:45:23 +0000209 return false;
210
Philip Reames23aed5e2018-03-20 22:45:23 +0000211 return true;
212}
213
214
Philip Reames89f22412018-03-20 17:09:21 +0000215namespace {
216 struct MustExecutePrinter : public FunctionPass {
Philip Reames89f22412018-03-20 17:09:21 +0000217
218 static char ID; // Pass identification, replacement for typeid
219 MustExecutePrinter() : FunctionPass(ID) {
220 initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
221 }
222 void getAnalysisUsage(AnalysisUsage &AU) const override {
223 AU.setPreservesAll();
224 AU.addRequired<DominatorTreeWrapperPass>();
225 AU.addRequired<LoopInfoWrapperPass>();
226 }
227 bool runOnFunction(Function &F) override;
Philip Reames89f22412018-03-20 17:09:21 +0000228 };
229}
230
231char MustExecutePrinter::ID = 0;
232INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
233 "Instructions which execute on loop entry", false, true)
234INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
235INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
236INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
237 "Instructions which execute on loop entry", false, true)
238
239FunctionPass *llvm::createMustExecutePrinter() {
240 return new MustExecutePrinter();
241}
242
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000243static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
Philip Reames37a1a292018-03-20 23:00:54 +0000244 // TODO: merge these two routines. For the moment, we display the best
245 // result obtained by *either* implementation. This is a bit unfair since no
246 // caller actually gets the full power at the moment.
247 LoopSafetyInfo LSI;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000248 LSI.computeLoopSafetyInfo(L);
Max Kazantsevc8466f92018-10-16 06:34:53 +0000249 return LSI.isGuaranteedToExecute(I, DT, L) ||
Philip Reames37a1a292018-03-20 23:00:54 +0000250 isGuaranteedToExecuteForEveryIteration(&I, L);
Philip Reames89f22412018-03-20 17:09:21 +0000251}
252
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000253namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000254/// An assembly annotator class to print must execute information in
Philip Reamesce998ad2018-03-20 18:43:44 +0000255/// comments.
256class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
257 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
Philip Reames89f22412018-03-20 17:09:21 +0000258
Philip Reamesce998ad2018-03-20 18:43:44 +0000259public:
260 MustExecuteAnnotatedWriter(const Function &F,
261 DominatorTree &DT, LoopInfo &LI) {
262 for (auto &I: instructions(F)) {
263 Loop *L = LI.getLoopFor(I.getParent());
264 while (L) {
265 if (isMustExecuteIn(I, L, &DT)) {
266 MustExec[&I].push_back(L);
267 }
268 L = L->getParentLoop();
269 };
270 }
271 }
272 MustExecuteAnnotatedWriter(const Module &M,
273 DominatorTree &DT, LoopInfo &LI) {
274 for (auto &F : M)
275 for (auto &I: instructions(F)) {
276 Loop *L = LI.getLoopFor(I.getParent());
277 while (L) {
278 if (isMustExecuteIn(I, L, &DT)) {
279 MustExec[&I].push_back(L);
280 }
281 L = L->getParentLoop();
282 };
283 }
284 }
285
286
Fangrui Songf78650a2018-07-30 19:41:25 +0000287 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
Philip Reamesce998ad2018-03-20 18:43:44 +0000288 if (!MustExec.count(&V))
289 return;
290
291 const auto &Loops = MustExec.lookup(&V);
292 const auto NumLoops = Loops.size();
Philip Reames89f22412018-03-20 17:09:21 +0000293 if (NumLoops > 1)
Philip Reamesce998ad2018-03-20 18:43:44 +0000294 OS << " ; (mustexec in " << NumLoops << " loops: ";
Philip Reames89f22412018-03-20 17:09:21 +0000295 else
Philip Reamesce998ad2018-03-20 18:43:44 +0000296 OS << " ; (mustexec in: ";
Fangrui Songf78650a2018-07-30 19:41:25 +0000297
Philip Reames89f22412018-03-20 17:09:21 +0000298 bool first = true;
Philip Reamesce998ad2018-03-20 18:43:44 +0000299 for (const Loop *L : Loops) {
Philip Reames89f22412018-03-20 17:09:21 +0000300 if (!first)
301 OS << ", ";
302 first = false;
303 OS << L->getHeader()->getName();
304 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000305 OS << ")";
Philip Reames89f22412018-03-20 17:09:21 +0000306 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000307};
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000308} // namespace
Philip Reamesce998ad2018-03-20 18:43:44 +0000309
310bool MustExecutePrinter::runOnFunction(Function &F) {
311 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
312 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
313
314 MustExecuteAnnotatedWriter Writer(F, DT, LI);
315 F.print(dbgs(), &Writer);
Fangrui Songf78650a2018-07-30 19:41:25 +0000316
Philip Reamesce998ad2018-03-20 18:43:44 +0000317 return false;
Philip Reames89f22412018-03-20 17:09:21 +0000318}