blob: 23e012626e244df2957531a18510132acc6c4bce [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 Kazantsev4855b742018-11-06 09:07:03 +0000148/// Collect all blocks from \p CurLoop which lie on all possible paths from
149/// the header of \p CurLoop (inclusive) to BB (exclusive) into the set
150/// \p Predecessors. If \p BB is the header, \p Predecessors will be empty.
151static void collectTransitivePredecessors(
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000152 const Loop *CurLoop, const BasicBlock *BB,
Max Kazantsev4855b742018-11-06 09:07:03 +0000153 SmallPtrSetImpl<const BasicBlock *> &Predecessors) {
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000154 assert(Predecessors.empty() && "Garbage in predecessors set?");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000155 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000156 if (BB == CurLoop->getHeader())
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000157 return;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000158 SmallVector<const BasicBlock *, 4> WorkList;
159 for (auto *Pred : predecessors(BB)) {
160 Predecessors.insert(Pred);
161 WorkList.push_back(Pred);
162 }
163 while (!WorkList.empty()) {
164 auto *Pred = WorkList.pop_back_val();
165 assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
166 // We are not interested in backedges and we don't want to leave loop.
167 if (Pred == CurLoop->getHeader())
168 continue;
169 // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
170 // blocks of this inner loop, even those that are always executed AFTER the
171 // BB. It may make our analysis more conservative than it could be, see test
172 // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
173 // We can ignore backedge of all loops containing BB to get a sligtly more
174 // optimistic result.
175 for (auto *PredPred : predecessors(Pred))
176 if (Predecessors.insert(PredPred).second)
177 WorkList.push_back(PredPred);
178 }
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000179}
180
181bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
182 const BasicBlock *BB,
183 const DominatorTree *DT) const {
184 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
185
186 // Fast path: header is always reached once the loop is entered.
187 if (BB == CurLoop->getHeader())
188 return true;
189
190 // Collect all transitive predecessors of BB in the same loop. This set will
191 // be a subset of the blocks within the loop.
192 SmallPtrSet<const BasicBlock *, 4> Predecessors;
193 collectTransitivePredecessors(CurLoop, BB, Predecessors);
Max Kazantsev7b78d392018-08-17 06:19:17 +0000194
195 // Make sure that all successors of all predecessors of BB are either:
196 // 1) BB,
197 // 2) Also predecessors of BB,
198 // 3) Exit blocks which are not taken on 1st iteration.
199 // Memoize blocks we've already checked.
200 SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000201 for (auto *Pred : Predecessors) {
202 // Predecessor block may throw, so it has a side exit.
203 if (blockMayThrow(Pred))
204 return false;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000205 for (auto *Succ : successors(Pred))
206 if (CheckedSuccessors.insert(Succ).second &&
207 Succ != BB && !Predecessors.count(Succ))
208 // By discharging conditions that are not executed on the 1st iteration,
209 // we guarantee that *at least* on the first iteration all paths from
210 // header that *may* execute will lead us to the block of interest. So
211 // that if we had virtually peeled one iteration away, in this peeled
212 // iteration the set of predecessors would contain only paths from
213 // header to BB without any exiting edges that may execute.
214 //
215 // TODO: We only do it for exiting edges currently. We could use the
216 // same function to skip some of the edges within the loop if we know
217 // that they will not be taken on the 1st iteration.
218 //
219 // TODO: If we somehow know the number of iterations in loop, the same
220 // check may be done for any arbitrary N-th iteration as long as N is
221 // not greater than minimum number of iterations in this loop.
222 if (CurLoop->contains(Succ) ||
223 !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
224 return false;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000225 }
Max Kazantsev7b78d392018-08-17 06:19:17 +0000226
227 // All predecessors can only lead us to BB.
228 return true;
229}
230
Philip Reames23aed5e2018-03-20 22:45:23 +0000231/// Returns true if the instruction in a loop is guaranteed to execute at least
232/// once.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000233bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
234 const DominatorTree *DT,
235 const Loop *CurLoop) const {
Philip Reames23aed5e2018-03-20 22:45:23 +0000236 // If the instruction is in the header block for the loop (which is very
237 // common), it is always guaranteed to dominate the exit blocks. Since this
238 // is a common case, and can save some work, check it now.
239 if (Inst.getParent() == CurLoop->getHeader())
240 // If there's a throw in the header block, we can't guarantee we'll reach
Philip Reamese4ec4732018-04-27 20:44:01 +0000241 // Inst unless we can prove that Inst comes before the potential implicit
242 // exit. At the moment, we use a (cheap) hack for the common case where
243 // the instruction of interest is the first one in the block.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000244 return !HeaderMayThrow ||
Max Kazantsevc8466f92018-10-16 06:34:53 +0000245 Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
Philip Reames23aed5e2018-03-20 22:45:23 +0000246
Max Kazantsev7b78d392018-08-17 06:19:17 +0000247 // If there is a path from header to exit or latch that doesn't lead to our
248 // instruction's block, return false.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000249 return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
Philip Reames23aed5e2018-03-20 22:45:23 +0000250}
251
Max Kazantsev5f9acd22018-10-16 09:58:09 +0000252bool ICFLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
253 const DominatorTree *DT,
254 const Loop *CurLoop) const {
255 return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
256 allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
257}
Philip Reames23aed5e2018-03-20 22:45:23 +0000258
Philip Reames89f22412018-03-20 17:09:21 +0000259namespace {
260 struct MustExecutePrinter : public FunctionPass {
Philip Reames89f22412018-03-20 17:09:21 +0000261
262 static char ID; // Pass identification, replacement for typeid
263 MustExecutePrinter() : FunctionPass(ID) {
264 initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
265 }
266 void getAnalysisUsage(AnalysisUsage &AU) const override {
267 AU.setPreservesAll();
268 AU.addRequired<DominatorTreeWrapperPass>();
269 AU.addRequired<LoopInfoWrapperPass>();
270 }
271 bool runOnFunction(Function &F) override;
Philip Reames89f22412018-03-20 17:09:21 +0000272 };
273}
274
275char MustExecutePrinter::ID = 0;
276INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
277 "Instructions which execute on loop entry", false, true)
278INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
279INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
280INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
281 "Instructions which execute on loop entry", false, true)
282
283FunctionPass *llvm::createMustExecutePrinter() {
284 return new MustExecutePrinter();
285}
286
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000287static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
Philip Reames37a1a292018-03-20 23:00:54 +0000288 // TODO: merge these two routines. For the moment, we display the best
289 // result obtained by *either* implementation. This is a bit unfair since no
290 // caller actually gets the full power at the moment.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000291 SimpleLoopSafetyInfo LSI;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000292 LSI.computeLoopSafetyInfo(L);
Max Kazantsevc8466f92018-10-16 06:34:53 +0000293 return LSI.isGuaranteedToExecute(I, DT, L) ||
Philip Reames37a1a292018-03-20 23:00:54 +0000294 isGuaranteedToExecuteForEveryIteration(&I, L);
Philip Reames89f22412018-03-20 17:09:21 +0000295}
296
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000297namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298/// An assembly annotator class to print must execute information in
Philip Reamesce998ad2018-03-20 18:43:44 +0000299/// comments.
300class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
301 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
Philip Reames89f22412018-03-20 17:09:21 +0000302
Philip Reamesce998ad2018-03-20 18:43:44 +0000303public:
304 MustExecuteAnnotatedWriter(const Function &F,
305 DominatorTree &DT, LoopInfo &LI) {
306 for (auto &I: instructions(F)) {
307 Loop *L = LI.getLoopFor(I.getParent());
308 while (L) {
309 if (isMustExecuteIn(I, L, &DT)) {
310 MustExec[&I].push_back(L);
311 }
312 L = L->getParentLoop();
313 };
314 }
315 }
316 MustExecuteAnnotatedWriter(const Module &M,
317 DominatorTree &DT, LoopInfo &LI) {
318 for (auto &F : M)
319 for (auto &I: instructions(F)) {
320 Loop *L = LI.getLoopFor(I.getParent());
321 while (L) {
322 if (isMustExecuteIn(I, L, &DT)) {
323 MustExec[&I].push_back(L);
324 }
325 L = L->getParentLoop();
326 };
327 }
328 }
329
330
Fangrui Songf78650a2018-07-30 19:41:25 +0000331 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
Philip Reamesce998ad2018-03-20 18:43:44 +0000332 if (!MustExec.count(&V))
333 return;
334
335 const auto &Loops = MustExec.lookup(&V);
336 const auto NumLoops = Loops.size();
Philip Reames89f22412018-03-20 17:09:21 +0000337 if (NumLoops > 1)
Philip Reamesce998ad2018-03-20 18:43:44 +0000338 OS << " ; (mustexec in " << NumLoops << " loops: ";
Philip Reames89f22412018-03-20 17:09:21 +0000339 else
Philip Reamesce998ad2018-03-20 18:43:44 +0000340 OS << " ; (mustexec in: ";
Fangrui Songf78650a2018-07-30 19:41:25 +0000341
Philip Reames89f22412018-03-20 17:09:21 +0000342 bool first = true;
Philip Reamesce998ad2018-03-20 18:43:44 +0000343 for (const Loop *L : Loops) {
Philip Reames89f22412018-03-20 17:09:21 +0000344 if (!first)
345 OS << ", ";
346 first = false;
347 OS << L->getHeader()->getName();
348 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000349 OS << ")";
Philip Reames89f22412018-03-20 17:09:21 +0000350 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000351};
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000352} // namespace
Philip Reamesce998ad2018-03-20 18:43:44 +0000353
354bool MustExecutePrinter::runOnFunction(Function &F) {
355 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
356 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
357
358 MustExecuteAnnotatedWriter Writer(F, DT, LI);
359 F.print(dbgs(), &Writer);
Fangrui Songf78650a2018-07-30 19:41:25 +0000360
Philip Reamesce998ad2018-03-20 18:43:44 +0000361 return false;
Philip Reames89f22412018-03-20 17:09:21 +0000362}