blob: 7507aebb527ef35d58b60879d0f4f468132c3613 [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
Max Kazantsevbb844072018-11-01 10:16:06 +000085void ICFLoopSafetyInfo::insertInstructionTo(const BasicBlock *BB) {
Max Kazantsev5f9acd22018-10-16 09:58:09 +000086 ICF.invalidateBlock(BB);
87}
88
Max Kazantsevbb844072018-11-01 10:16:06 +000089void 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
Max Kazantsev8d56be72018-10-16 08:07:14 +000095void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) {
Philip Reames23aed5e2018-03-20 22:45:23 +000096 // 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())
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000101 if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
Max Kazantsev530b8d12018-08-15 05:55:43 +0000102 BlockColors = colorEHFunclets(*Fn);
Philip Reames23aed5e2018-03-20 22:45:23 +0000103}
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.
Max Kazantseva7415872018-08-16 06:28:04 +0000108static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
Philip Reames23aed5e2018-03-20 22:45:23 +0000109 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;
Serguei Katkov50958832018-05-18 04:56:28 +0000119 // 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;
Philip Reames23aed5e2018-03-20 22:45:23 +0000123 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
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000148void LoopSafetyInfo::collectTransitivePredecessors(
149 const Loop *CurLoop, const BasicBlock *BB,
150 SmallPtrSetImpl<const BasicBlock *> &Predecessors) const {
151 assert(Predecessors.empty() && "Garbage in predecessors set?");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000152 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000153 if (BB == CurLoop->getHeader())
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000154 return;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000155 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 }
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000176}
177
178bool 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);
Max Kazantsev7b78d392018-08-17 06:19:17 +0000191
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;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000198 for (auto *Pred : Predecessors) {
199 // Predecessor block may throw, so it has a side exit.
200 if (blockMayThrow(Pred))
201 return false;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000202 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;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000222 }
Max Kazantsev7b78d392018-08-17 06:19:17 +0000223
224 // All predecessors can only lead us to BB.
225 return true;
226}
227
Philip Reames23aed5e2018-03-20 22:45:23 +0000228/// Returns true if the instruction in a loop is guaranteed to execute at least
229/// once.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000230bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
231 const DominatorTree *DT,
232 const Loop *CurLoop) const {
Philip Reames23aed5e2018-03-20 22:45:23 +0000233 // 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
Philip Reamese4ec4732018-04-27 20:44:01 +0000238 // 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.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000241 return !HeaderMayThrow ||
Max Kazantsevc8466f92018-10-16 06:34:53 +0000242 Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
Philip Reames23aed5e2018-03-20 22:45:23 +0000243
Max Kazantsev7b78d392018-08-17 06:19:17 +0000244 // If there is a path from header to exit or latch that doesn't lead to our
245 // instruction's block, return false.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000246 return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
Philip Reames23aed5e2018-03-20 22:45:23 +0000247}
248
Max Kazantsev5f9acd22018-10-16 09:58:09 +0000249bool 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}
Philip Reames23aed5e2018-03-20 22:45:23 +0000255
Philip Reames89f22412018-03-20 17:09:21 +0000256namespace {
257 struct MustExecutePrinter : public FunctionPass {
Philip Reames89f22412018-03-20 17:09:21 +0000258
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;
Philip Reames89f22412018-03-20 17:09:21 +0000269 };
270}
271
272char MustExecutePrinter::ID = 0;
273INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
274 "Instructions which execute on loop entry", false, true)
275INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
276INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
277INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
278 "Instructions which execute on loop entry", false, true)
279
280FunctionPass *llvm::createMustExecutePrinter() {
281 return new MustExecutePrinter();
282}
283
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000284static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
Philip Reames37a1a292018-03-20 23:00:54 +0000285 // 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.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000288 SimpleLoopSafetyInfo LSI;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000289 LSI.computeLoopSafetyInfo(L);
Max Kazantsevc8466f92018-10-16 06:34:53 +0000290 return LSI.isGuaranteedToExecute(I, DT, L) ||
Philip Reames37a1a292018-03-20 23:00:54 +0000291 isGuaranteedToExecuteForEveryIteration(&I, L);
Philip Reames89f22412018-03-20 17:09:21 +0000292}
293
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000294namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295/// An assembly annotator class to print must execute information in
Philip Reamesce998ad2018-03-20 18:43:44 +0000296/// comments.
297class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
298 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
Philip Reames89f22412018-03-20 17:09:21 +0000299
Philip Reamesce998ad2018-03-20 18:43:44 +0000300public:
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
Fangrui Songf78650a2018-07-30 19:41:25 +0000328 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
Philip Reamesce998ad2018-03-20 18:43:44 +0000329 if (!MustExec.count(&V))
330 return;
331
332 const auto &Loops = MustExec.lookup(&V);
333 const auto NumLoops = Loops.size();
Philip Reames89f22412018-03-20 17:09:21 +0000334 if (NumLoops > 1)
Philip Reamesce998ad2018-03-20 18:43:44 +0000335 OS << " ; (mustexec in " << NumLoops << " loops: ";
Philip Reames89f22412018-03-20 17:09:21 +0000336 else
Philip Reamesce998ad2018-03-20 18:43:44 +0000337 OS << " ; (mustexec in: ";
Fangrui Songf78650a2018-07-30 19:41:25 +0000338
Philip Reames89f22412018-03-20 17:09:21 +0000339 bool first = true;
Philip Reamesce998ad2018-03-20 18:43:44 +0000340 for (const Loop *L : Loops) {
Philip Reames89f22412018-03-20 17:09:21 +0000341 if (!first)
342 OS << ", ";
343 first = false;
344 OS << L->getHeader()->getName();
345 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000346 OS << ")";
Philip Reames89f22412018-03-20 17:09:21 +0000347 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000348};
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000349} // namespace
Philip Reamesce998ad2018-03-20 18:43:44 +0000350
351bool 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);
Fangrui Songf78650a2018-07-30 19:41:25 +0000357
Philip Reamesce998ad2018-03-20 18:43:44 +0000358 return false;
Philip Reames89f22412018-03-20 17:09:21 +0000359}