blob: 64ee2a7e5b0015e77cb9447dc46def96db96bd2d [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 Kazantsev8d56be72018-10-16 08:07:14 +000025const DenseMap<BasicBlock *, ColorVector> &
26LoopSafetyInfo::getBlockColors() const {
27 return BlockColors;
28}
29
30void LoopSafetyInfo::copyColors(BasicBlock *New, BasicBlock *Old) {
31 ColorVector &ColorsForNewBlock = BlockColors[New];
32 ColorVector &ColorsForOldBlock = BlockColors[Old];
33 ColorsForNewBlock = ColorsForOldBlock;
34}
35
Max Kazantsev9c90ec22018-10-16 08:31:05 +000036bool SimpleLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
Max Kazantsev6a4f5e22018-10-16 07:50:14 +000037 (void)BB;
38 return anyBlockMayThrow();
39}
40
Max Kazantsev9c90ec22018-10-16 08:31:05 +000041bool SimpleLoopSafetyInfo::anyBlockMayThrow() const {
Max Kazantsev530b8d12018-08-15 05:55:43 +000042 return MayThrow;
43}
44
Max Kazantsev9c90ec22018-10-16 08:31:05 +000045void SimpleLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
Shoaib Meenaia57d7132018-07-19 19:11:29 +000046 assert(CurLoop != nullptr && "CurLoop can't be null");
Philip Reames23aed5e2018-03-20 22:45:23 +000047 BasicBlock *Header = CurLoop->getHeader();
Philip Reames23aed5e2018-03-20 22:45:23 +000048 // Iterate over header and compute safety info.
Max Kazantsev530b8d12018-08-15 05:55:43 +000049 HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
50 MayThrow = HeaderMayThrow;
Philip Reames23aed5e2018-03-20 22:45:23 +000051 // 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();
Max Kazantsev530b8d12018-08-15 05:55:43 +000058 (BB != BBE) && !MayThrow; ++BB)
59 MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
Philip Reames23aed5e2018-03-20 22:45:23 +000060
Max Kazantsev8d56be72018-10-16 08:07:14 +000061 computeBlockColors(CurLoop);
62}
63
Max Kazantsev5f9acd22018-10-16 09:58:09 +000064bool ICFLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
65 return ICF.hasICF(BB);
66}
67
68bool ICFLoopSafetyInfo::anyBlockMayThrow() const {
69 return MayThrow;
70}
71
72void 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
85void ICFLoopSafetyInfo::dropCachedInfo(const BasicBlock *BB) {
86 ICF.invalidateBlock(BB);
87}
88
Max Kazantsev8d56be72018-10-16 08:07:14 +000089void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) {
Philip Reames23aed5e2018-03-20 22:45:23 +000090 // Compute funclet colors if we might sink/hoist in a function with a funclet
91 // personality routine.
92 Function *Fn = CurLoop->getHeader()->getParent();
93 if (Fn->hasPersonalityFn())
94 if (Constant *PersonalityFn = Fn->getPersonalityFn())
Heejin Ahnb4be38f2018-05-17 20:52:03 +000095 if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
Max Kazantsev530b8d12018-08-15 05:55:43 +000096 BlockColors = colorEHFunclets(*Fn);
Philip Reames23aed5e2018-03-20 22:45:23 +000097}
98
99/// Return true if we can prove that the given ExitBlock is not reached on the
100/// first iteration of the given loop. That is, the backedge of the loop must
101/// be executed before the ExitBlock is executed in any dynamic execution trace.
Max Kazantseva7415872018-08-16 06:28:04 +0000102static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
Philip Reames23aed5e2018-03-20 22:45:23 +0000103 const DominatorTree *DT,
104 const Loop *CurLoop) {
105 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
106 if (!CondExitBlock)
107 // expect unique exits
108 return false;
109 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
110 auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
111 if (!BI || !BI->isConditional())
112 return false;
Serguei Katkov50958832018-05-18 04:56:28 +0000113 // If condition is constant and false leads to ExitBlock then we always
114 // execute the true branch.
115 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
116 return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
Philip Reames23aed5e2018-03-20 22:45:23 +0000117 auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
118 if (!Cond)
119 return false;
120 // todo: this would be a lot more powerful if we used scev, but all the
121 // plumbing is currently missing to pass a pointer in from the pass
122 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
123 auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
124 auto *RHS = Cond->getOperand(1);
125 if (!LHS || LHS->getParent() != CurLoop->getHeader())
126 return false;
127 auto DL = ExitBlock->getModule()->getDataLayout();
128 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
129 auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
130 IVStart, RHS,
131 {DL, /*TLI*/ nullptr,
132 DT, /*AC*/ nullptr, BI});
133 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
134 if (!SimpleCst)
135 return false;
136 if (ExitBlock == BI->getSuccessor(0))
137 return SimpleCst->isZeroValue();
138 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
139 return SimpleCst->isAllOnesValue();
140}
141
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000142void LoopSafetyInfo::collectTransitivePredecessors(
143 const Loop *CurLoop, const BasicBlock *BB,
144 SmallPtrSetImpl<const BasicBlock *> &Predecessors) const {
145 assert(Predecessors.empty() && "Garbage in predecessors set?");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000146 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000147 if (BB == CurLoop->getHeader())
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000148 return;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000149 SmallVector<const BasicBlock *, 4> WorkList;
150 for (auto *Pred : predecessors(BB)) {
151 Predecessors.insert(Pred);
152 WorkList.push_back(Pred);
153 }
154 while (!WorkList.empty()) {
155 auto *Pred = WorkList.pop_back_val();
156 assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
157 // We are not interested in backedges and we don't want to leave loop.
158 if (Pred == CurLoop->getHeader())
159 continue;
160 // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
161 // blocks of this inner loop, even those that are always executed AFTER the
162 // BB. It may make our analysis more conservative than it could be, see test
163 // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
164 // We can ignore backedge of all loops containing BB to get a sligtly more
165 // optimistic result.
166 for (auto *PredPred : predecessors(Pred))
167 if (Predecessors.insert(PredPred).second)
168 WorkList.push_back(PredPred);
169 }
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000170}
171
172bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
173 const BasicBlock *BB,
174 const DominatorTree *DT) const {
175 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
176
177 // Fast path: header is always reached once the loop is entered.
178 if (BB == CurLoop->getHeader())
179 return true;
180
181 // Collect all transitive predecessors of BB in the same loop. This set will
182 // be a subset of the blocks within the loop.
183 SmallPtrSet<const BasicBlock *, 4> Predecessors;
184 collectTransitivePredecessors(CurLoop, BB, Predecessors);
Max Kazantsev7b78d392018-08-17 06:19:17 +0000185
186 // Make sure that all successors of all predecessors of BB are either:
187 // 1) BB,
188 // 2) Also predecessors of BB,
189 // 3) Exit blocks which are not taken on 1st iteration.
190 // Memoize blocks we've already checked.
191 SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000192 for (auto *Pred : Predecessors) {
193 // Predecessor block may throw, so it has a side exit.
194 if (blockMayThrow(Pred))
195 return false;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000196 for (auto *Succ : successors(Pred))
197 if (CheckedSuccessors.insert(Succ).second &&
198 Succ != BB && !Predecessors.count(Succ))
199 // By discharging conditions that are not executed on the 1st iteration,
200 // we guarantee that *at least* on the first iteration all paths from
201 // header that *may* execute will lead us to the block of interest. So
202 // that if we had virtually peeled one iteration away, in this peeled
203 // iteration the set of predecessors would contain only paths from
204 // header to BB without any exiting edges that may execute.
205 //
206 // TODO: We only do it for exiting edges currently. We could use the
207 // same function to skip some of the edges within the loop if we know
208 // that they will not be taken on the 1st iteration.
209 //
210 // TODO: If we somehow know the number of iterations in loop, the same
211 // check may be done for any arbitrary N-th iteration as long as N is
212 // not greater than minimum number of iterations in this loop.
213 if (CurLoop->contains(Succ) ||
214 !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
215 return false;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000216 }
Max Kazantsev7b78d392018-08-17 06:19:17 +0000217
218 // All predecessors can only lead us to BB.
219 return true;
220}
221
Philip Reames23aed5e2018-03-20 22:45:23 +0000222/// Returns true if the instruction in a loop is guaranteed to execute at least
223/// once.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000224bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
225 const DominatorTree *DT,
226 const Loop *CurLoop) const {
Philip Reames23aed5e2018-03-20 22:45:23 +0000227 // If the instruction is in the header block for the loop (which is very
228 // common), it is always guaranteed to dominate the exit blocks. Since this
229 // is a common case, and can save some work, check it now.
230 if (Inst.getParent() == CurLoop->getHeader())
231 // If there's a throw in the header block, we can't guarantee we'll reach
Philip Reamese4ec4732018-04-27 20:44:01 +0000232 // Inst unless we can prove that Inst comes before the potential implicit
233 // exit. At the moment, we use a (cheap) hack for the common case where
234 // the instruction of interest is the first one in the block.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000235 return !HeaderMayThrow ||
Max Kazantsevc8466f92018-10-16 06:34:53 +0000236 Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
Philip Reames23aed5e2018-03-20 22:45:23 +0000237
Max Kazantsev7b78d392018-08-17 06:19:17 +0000238 // If there is a path from header to exit or latch that doesn't lead to our
239 // instruction's block, return false.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000240 return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
Philip Reames23aed5e2018-03-20 22:45:23 +0000241}
242
Max Kazantsev5f9acd22018-10-16 09:58:09 +0000243bool ICFLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
244 const DominatorTree *DT,
245 const Loop *CurLoop) const {
246 return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
247 allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
248}
Philip Reames23aed5e2018-03-20 22:45:23 +0000249
Philip Reames89f22412018-03-20 17:09:21 +0000250namespace {
251 struct MustExecutePrinter : public FunctionPass {
Philip Reames89f22412018-03-20 17:09:21 +0000252
253 static char ID; // Pass identification, replacement for typeid
254 MustExecutePrinter() : FunctionPass(ID) {
255 initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
256 }
257 void getAnalysisUsage(AnalysisUsage &AU) const override {
258 AU.setPreservesAll();
259 AU.addRequired<DominatorTreeWrapperPass>();
260 AU.addRequired<LoopInfoWrapperPass>();
261 }
262 bool runOnFunction(Function &F) override;
Philip Reames89f22412018-03-20 17:09:21 +0000263 };
264}
265
266char MustExecutePrinter::ID = 0;
267INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
268 "Instructions which execute on loop entry", false, true)
269INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
270INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
271INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
272 "Instructions which execute on loop entry", false, true)
273
274FunctionPass *llvm::createMustExecutePrinter() {
275 return new MustExecutePrinter();
276}
277
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000278static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
Philip Reames37a1a292018-03-20 23:00:54 +0000279 // TODO: merge these two routines. For the moment, we display the best
280 // result obtained by *either* implementation. This is a bit unfair since no
281 // caller actually gets the full power at the moment.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000282 SimpleLoopSafetyInfo LSI;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000283 LSI.computeLoopSafetyInfo(L);
Max Kazantsevc8466f92018-10-16 06:34:53 +0000284 return LSI.isGuaranteedToExecute(I, DT, L) ||
Philip Reames37a1a292018-03-20 23:00:54 +0000285 isGuaranteedToExecuteForEveryIteration(&I, L);
Philip Reames89f22412018-03-20 17:09:21 +0000286}
287
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000288namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000289/// An assembly annotator class to print must execute information in
Philip Reamesce998ad2018-03-20 18:43:44 +0000290/// comments.
291class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
292 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
Philip Reames89f22412018-03-20 17:09:21 +0000293
Philip Reamesce998ad2018-03-20 18:43:44 +0000294public:
295 MustExecuteAnnotatedWriter(const Function &F,
296 DominatorTree &DT, LoopInfo &LI) {
297 for (auto &I: instructions(F)) {
298 Loop *L = LI.getLoopFor(I.getParent());
299 while (L) {
300 if (isMustExecuteIn(I, L, &DT)) {
301 MustExec[&I].push_back(L);
302 }
303 L = L->getParentLoop();
304 };
305 }
306 }
307 MustExecuteAnnotatedWriter(const Module &M,
308 DominatorTree &DT, LoopInfo &LI) {
309 for (auto &F : M)
310 for (auto &I: instructions(F)) {
311 Loop *L = LI.getLoopFor(I.getParent());
312 while (L) {
313 if (isMustExecuteIn(I, L, &DT)) {
314 MustExec[&I].push_back(L);
315 }
316 L = L->getParentLoop();
317 };
318 }
319 }
320
321
Fangrui Songf78650a2018-07-30 19:41:25 +0000322 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
Philip Reamesce998ad2018-03-20 18:43:44 +0000323 if (!MustExec.count(&V))
324 return;
325
326 const auto &Loops = MustExec.lookup(&V);
327 const auto NumLoops = Loops.size();
Philip Reames89f22412018-03-20 17:09:21 +0000328 if (NumLoops > 1)
Philip Reamesce998ad2018-03-20 18:43:44 +0000329 OS << " ; (mustexec in " << NumLoops << " loops: ";
Philip Reames89f22412018-03-20 17:09:21 +0000330 else
Philip Reamesce998ad2018-03-20 18:43:44 +0000331 OS << " ; (mustexec in: ";
Fangrui Songf78650a2018-07-30 19:41:25 +0000332
Philip Reames89f22412018-03-20 17:09:21 +0000333 bool first = true;
Philip Reamesce998ad2018-03-20 18:43:44 +0000334 for (const Loop *L : Loops) {
Philip Reames89f22412018-03-20 17:09:21 +0000335 if (!first)
336 OS << ", ";
337 first = false;
338 OS << L->getHeader()->getName();
339 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000340 OS << ")";
Philip Reames89f22412018-03-20 17:09:21 +0000341 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000342};
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000343} // namespace
Philip Reamesce998ad2018-03-20 18:43:44 +0000344
345bool MustExecutePrinter::runOnFunction(Function &F) {
346 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
347 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
348
349 MustExecuteAnnotatedWriter Writer(F, DT, LI);
350 F.print(dbgs(), &Writer);
Fangrui Songf78650a2018-07-30 19:41:25 +0000351
Philip Reamesce998ad2018-03-20 18:43:44 +0000352 return false;
Philip Reames89f22412018-03-20 17:09:21 +0000353}