LLVM 20.0.0git
MustExecute.cpp
Go to the documentation of this file.
1//===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12#include "llvm/Analysis/CFG.h"
19#include "llvm/IR/Dominators.h"
21#include "llvm/IR/Module.h"
22#include "llvm/IR/PassManager.h"
26
27using namespace llvm;
28
29#define DEBUG_TYPE "must-execute"
30
33 return BlockColors;
34}
35
37 ColorVector &ColorsForNewBlock = BlockColors[New];
38 ColorVector &ColorsForOldBlock = BlockColors[Old];
39 ColorsForNewBlock = ColorsForOldBlock;
40}
41
43 (void)BB;
44 return anyBlockMayThrow();
45}
46
48 return MayThrow;
49}
50
52 assert(CurLoop != nullptr && "CurLoop can't be null");
53 BasicBlock *Header = CurLoop->getHeader();
54 // Iterate over header and compute safety info.
55 HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
56 MayThrow = HeaderMayThrow;
57 // Iterate over loop instructions and compute safety info.
58 // Skip header as it has been computed and stored in HeaderMayThrow.
59 // The first block in loopinfo.Blocks is guaranteed to be the header.
60 assert(Header == *CurLoop->getBlocks().begin() &&
61 "First block must be header");
62 for (const BasicBlock *BB : llvm::drop_begin(CurLoop->blocks())) {
64 if (MayThrow)
65 break;
66 }
67
68 computeBlockColors(CurLoop);
69}
70
72 return ICF.hasICF(BB);
73}
74
76 return MayThrow;
77}
78
80 assert(CurLoop != nullptr && "CurLoop can't be null");
81 ICF.clear();
82 MW.clear();
83 MayThrow = false;
84 // Figure out the fact that at least one block may throw.
85 for (const auto &BB : CurLoop->blocks())
86 if (ICF.hasICF(&*BB)) {
87 MayThrow = true;
88 break;
89 }
90 computeBlockColors(CurLoop);
91}
92
94 const BasicBlock *BB) {
95 ICF.insertInstructionTo(Inst, BB);
96 MW.insertInstructionTo(Inst, BB);
97}
98
100 ICF.removeInstruction(Inst);
101 MW.removeInstruction(Inst);
102}
103
105 // Compute funclet colors if we might sink/hoist in a function with a funclet
106 // personality routine.
107 Function *Fn = CurLoop->getHeader()->getParent();
108 if (Fn->hasPersonalityFn())
109 if (Constant *PersonalityFn = Fn->getPersonalityFn())
111 BlockColors = colorEHFunclets(*Fn);
112}
113
114/// Return true if we can prove that the given ExitBlock is not reached on the
115/// first iteration of the given loop. That is, the backedge of the loop must
116/// be executed before the ExitBlock is executed in any dynamic execution trace.
117static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
118 const DominatorTree *DT,
119 const Loop *CurLoop) {
120 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
121 if (!CondExitBlock)
122 // expect unique exits
123 return false;
124 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
125 auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
126 if (!BI || !BI->isConditional())
127 return false;
128 // If condition is constant and false leads to ExitBlock then we always
129 // execute the true branch.
130 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
131 return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
132 auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
133 if (!Cond)
134 return false;
135 // todo: this would be a lot more powerful if we used scev, but all the
136 // plumbing is currently missing to pass a pointer in from the pass
137 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
138 ICmpInst::Predicate Pred = Cond->getPredicate();
139 auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
140 auto *RHS = Cond->getOperand(1);
141 if (!LHS || LHS->getParent() != CurLoop->getHeader()) {
142 Pred = Cond->getSwappedPredicate();
143 LHS = dyn_cast<PHINode>(Cond->getOperand(1));
144 RHS = Cond->getOperand(0);
145 if (!LHS || LHS->getParent() != CurLoop->getHeader())
146 return false;
147 }
148
149 auto DL = ExitBlock->getModule()->getDataLayout();
150 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
151 auto *SimpleValOrNull = simplifyCmpInst(
152 Pred, IVStart, RHS, {DL, /*TLI*/ nullptr, DT, /*AC*/ nullptr, BI});
153 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
154 if (!SimpleCst)
155 return false;
156 if (ExitBlock == BI->getSuccessor(0))
157 return SimpleCst->isZeroValue();
158 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
159 return SimpleCst->isAllOnesValue();
160}
161
162/// Collect all blocks from \p CurLoop which lie on all possible paths from
163/// the header of \p CurLoop (inclusive) to BB (exclusive) into the set
164/// \p Predecessors. If \p BB is the header, \p Predecessors will be empty.
166 const Loop *CurLoop, const BasicBlock *BB,
168 assert(Predecessors.empty() && "Garbage in predecessors set?");
169 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
170 if (BB == CurLoop->getHeader())
171 return;
173 for (const auto *Pred : predecessors(BB)) {
174 Predecessors.insert(Pred);
175 WorkList.push_back(Pred);
176 }
177 while (!WorkList.empty()) {
178 auto *Pred = WorkList.pop_back_val();
179 assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
180 // We are not interested in backedges and we don't want to leave loop.
181 if (Pred == CurLoop->getHeader())
182 continue;
183 // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
184 // blocks of this inner loop, even those that are always executed AFTER the
185 // BB. It may make our analysis more conservative than it could be, see test
186 // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
187 // We can ignore backedge of all loops containing BB to get a sligtly more
188 // optimistic result.
189 for (const auto *PredPred : predecessors(Pred))
190 if (Predecessors.insert(PredPred).second)
191 WorkList.push_back(PredPred);
192 }
193}
194
196 const BasicBlock *BB,
197 const DominatorTree *DT) const {
198 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
199
200 // Fast path: header is always reached once the loop is entered.
201 if (BB == CurLoop->getHeader())
202 return true;
203
204 // Collect all transitive predecessors of BB in the same loop. This set will
205 // be a subset of the blocks within the loop.
207 collectTransitivePredecessors(CurLoop, BB, Predecessors);
208
209 // Bail out if a latch block is part of the predecessor set. In this case
210 // we may take the backedge to the header and not execute other latch
211 // successors.
212 for (const BasicBlock *Pred : predecessors(CurLoop->getHeader()))
213 // Predecessors only contains loop blocks, so we don't have to worry about
214 // preheader predecessors here.
215 if (Predecessors.contains(Pred))
216 return false;
217
218 // Make sure that all successors of, all predecessors of BB which are not
219 // dominated by BB, are either:
220 // 1) BB,
221 // 2) Also predecessors of BB,
222 // 3) Exit blocks which are not taken on 1st iteration.
223 // Memoize blocks we've already checked.
224 SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
225 for (const auto *Pred : Predecessors) {
226 // Predecessor block may throw, so it has a side exit.
227 if (blockMayThrow(Pred))
228 return false;
229
230 // BB dominates Pred, so if Pred runs, BB must run.
231 // This is true when Pred is a loop latch.
232 if (DT->dominates(BB, Pred))
233 continue;
234
235 for (const auto *Succ : successors(Pred))
236 if (CheckedSuccessors.insert(Succ).second &&
237 Succ != BB && !Predecessors.count(Succ))
238 // By discharging conditions that are not executed on the 1st iteration,
239 // we guarantee that *at least* on the first iteration all paths from
240 // header that *may* execute will lead us to the block of interest. So
241 // that if we had virtually peeled one iteration away, in this peeled
242 // iteration the set of predecessors would contain only paths from
243 // header to BB without any exiting edges that may execute.
244 //
245 // TODO: We only do it for exiting edges currently. We could use the
246 // same function to skip some of the edges within the loop if we know
247 // that they will not be taken on the 1st iteration.
248 //
249 // TODO: If we somehow know the number of iterations in loop, the same
250 // check may be done for any arbitrary N-th iteration as long as N is
251 // not greater than minimum number of iterations in this loop.
252 if (CurLoop->contains(Succ) ||
253 !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
254 return false;
255 }
256
257 // All predecessors can only lead us to BB.
258 return true;
259}
260
261/// Returns true if the instruction in a loop is guaranteed to execute at least
262/// once.
264 const DominatorTree *DT,
265 const Loop *CurLoop) const {
266 // If the instruction is in the header block for the loop (which is very
267 // common), it is always guaranteed to dominate the exit blocks. Since this
268 // is a common case, and can save some work, check it now.
269 if (Inst.getParent() == CurLoop->getHeader())
270 // If there's a throw in the header block, we can't guarantee we'll reach
271 // Inst unless we can prove that Inst comes before the potential implicit
272 // exit. At the moment, we use a (cheap) hack for the common case where
273 // the instruction of interest is the first one in the block.
274 return !HeaderMayThrow ||
275 Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
276
277 // If there is a path from header to exit or latch that doesn't lead to our
278 // instruction's block, return false.
279 return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
280}
281
283 const DominatorTree *DT,
284 const Loop *CurLoop) const {
285 return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
286 allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
287}
288
290 const Loop *CurLoop) const {
291 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
292
293 // Fast path: there are no instructions before header.
294 if (BB == CurLoop->getHeader())
295 return true;
296
297 // Collect all transitive predecessors of BB in the same loop. This set will
298 // be a subset of the blocks within the loop.
300 collectTransitivePredecessors(CurLoop, BB, Predecessors);
301 // Find if there any instruction in either predecessor that could write
302 // to memory.
303 for (const auto *Pred : Predecessors)
304 if (MW.mayWriteToMemory(Pred))
305 return false;
306 return true;
307}
308
310 const Loop *CurLoop) const {
311 auto *BB = I.getParent();
312 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
314 doesNotWriteMemoryBefore(BB, CurLoop);
315}
316
317static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
318 // TODO: merge these two routines. For the moment, we display the best
319 // result obtained by *either* implementation. This is a bit unfair since no
320 // caller actually gets the full power at the moment.
323 return LSI.isGuaranteedToExecute(I, DT, L) ||
325}
326
327namespace {
328/// An assembly annotator class to print must execute information in
329/// comments.
330class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
332
333public:
334 MustExecuteAnnotatedWriter(const Function &F,
335 DominatorTree &DT, LoopInfo &LI) {
336 for (const auto &I: instructions(F)) {
337 Loop *L = LI.getLoopFor(I.getParent());
338 while (L) {
339 if (isMustExecuteIn(I, L, &DT)) {
340 MustExec[&I].push_back(L);
341 }
342 L = L->getParentLoop();
343 };
344 }
345 }
346 MustExecuteAnnotatedWriter(const Module &M,
347 DominatorTree &DT, LoopInfo &LI) {
348 for (const auto &F : M)
349 for (const auto &I: instructions(F)) {
350 Loop *L = LI.getLoopFor(I.getParent());
351 while (L) {
352 if (isMustExecuteIn(I, L, &DT)) {
353 MustExec[&I].push_back(L);
354 }
355 L = L->getParentLoop();
356 };
357 }
358 }
359
360
361 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
362 if (!MustExec.count(&V))
363 return;
364
365 const auto &Loops = MustExec.lookup(&V);
366 const auto NumLoops = Loops.size();
367 if (NumLoops > 1)
368 OS << " ; (mustexec in " << NumLoops << " loops: ";
369 else
370 OS << " ; (mustexec in: ";
371
372 ListSeparator LS;
373 for (const Loop *L : Loops)
374 OS << LS << L->getHeader()->getName();
375 OS << ")";
376 }
377};
378} // namespace
379
380/// Return true if \p L might be an endless loop.
381static bool maybeEndlessLoop(const Loop &L) {
382 if (L.getHeader()->getParent()->hasFnAttribute(Attribute::WillReturn))
383 return false;
384 // TODO: Actually try to prove it is not.
385 // TODO: If maybeEndlessLoop is going to be expensive, cache it.
386 return true;
387}
388
390 if (!LI)
391 return false;
393 RPOTraversal FuncRPOT(&F);
394 return containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
395 const LoopInfo>(FuncRPOT, *LI);
396}
397
398/// Lookup \p Key in \p Map and return the result, potentially after
399/// initializing the optional through \p Fn(\p args).
400template <typename K, typename V, typename FnTy, typename... ArgsTy>
401static V getOrCreateCachedOptional(K Key, DenseMap<K, std::optional<V>> &Map,
402 FnTy &&Fn, ArgsTy &&...args) {
403 std::optional<V> &OptVal = Map[Key];
404 if (!OptVal)
405 OptVal = Fn(std::forward<ArgsTy>(args)...);
406 return *OptVal;
407}
408
409const BasicBlock *
411 const LoopInfo *LI = LIGetter(*InitBB->getParent());
412 const PostDominatorTree *PDT = PDTGetter(*InitBB->getParent());
413
414 LLVM_DEBUG(dbgs() << "\tFind forward join point for " << InitBB->getName()
415 << (LI ? " [LI]" : "") << (PDT ? " [PDT]" : ""));
416
417 const Function &F = *InitBB->getParent();
418 const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
419 const BasicBlock *HeaderBB = L ? L->getHeader() : InitBB;
420 bool WillReturnAndNoThrow = (F.hasFnAttribute(Attribute::WillReturn) ||
421 (L && !maybeEndlessLoop(*L))) &&
422 F.doesNotThrow();
423 LLVM_DEBUG(dbgs() << (L ? " [in loop]" : "")
424 << (WillReturnAndNoThrow ? " [WillReturn] [NoUnwind]" : "")
425 << "\n");
426
427 // Determine the adjacent blocks in the given direction but exclude (self)
428 // loops under certain circumstances.
430 for (const BasicBlock *SuccBB : successors(InitBB)) {
431 bool IsLatch = SuccBB == HeaderBB;
432 // Loop latches are ignored in forward propagation if the loop cannot be
433 // endless and may not throw: control has to go somewhere.
434 if (!WillReturnAndNoThrow || !IsLatch)
435 Worklist.push_back(SuccBB);
436 }
437 LLVM_DEBUG(dbgs() << "\t\t#Worklist: " << Worklist.size() << "\n");
438
439 // If there are no other adjacent blocks, there is no join point.
440 if (Worklist.empty())
441 return nullptr;
442
443 // If there is one adjacent block, it is the join point.
444 if (Worklist.size() == 1)
445 return Worklist[0];
446
447 // Try to determine a join block through the help of the post-dominance
448 // tree. If no tree was provided, we perform simple pattern matching for one
449 // block conditionals and one block loops only.
450 const BasicBlock *JoinBB = nullptr;
451 if (PDT)
452 if (const auto *InitNode = PDT->getNode(InitBB))
453 if (const auto *IDomNode = InitNode->getIDom())
454 JoinBB = IDomNode->getBlock();
455
456 if (!JoinBB && Worklist.size() == 2) {
457 const BasicBlock *Succ0 = Worklist[0];
458 const BasicBlock *Succ1 = Worklist[1];
459 const BasicBlock *Succ0UniqueSucc = Succ0->getUniqueSuccessor();
460 const BasicBlock *Succ1UniqueSucc = Succ1->getUniqueSuccessor();
461 if (Succ0UniqueSucc == InitBB) {
462 // InitBB -> Succ0 -> InitBB
463 // InitBB -> Succ1 = JoinBB
464 JoinBB = Succ1;
465 } else if (Succ1UniqueSucc == InitBB) {
466 // InitBB -> Succ1 -> InitBB
467 // InitBB -> Succ0 = JoinBB
468 JoinBB = Succ0;
469 } else if (Succ0 == Succ1UniqueSucc) {
470 // InitBB -> Succ0 = JoinBB
471 // InitBB -> Succ1 -> Succ0 = JoinBB
472 JoinBB = Succ0;
473 } else if (Succ1 == Succ0UniqueSucc) {
474 // InitBB -> Succ0 -> Succ1 = JoinBB
475 // InitBB -> Succ1 = JoinBB
476 JoinBB = Succ1;
477 } else if (Succ0UniqueSucc == Succ1UniqueSucc) {
478 // InitBB -> Succ0 -> JoinBB
479 // InitBB -> Succ1 -> JoinBB
480 JoinBB = Succ0UniqueSucc;
481 }
482 }
483
484 if (!JoinBB && L)
485 JoinBB = L->getUniqueExitBlock();
486
487 if (!JoinBB)
488 return nullptr;
489
490 LLVM_DEBUG(dbgs() << "\t\tJoin block candidate: " << JoinBB->getName() << "\n");
491
492 // In forward direction we check if control will for sure reach JoinBB from
493 // InitBB, thus it can not be "stopped" along the way. Ways to "stop" control
494 // are: infinite loops and instructions that do not necessarily transfer
495 // execution to their successor. To check for them we traverse the CFG from
496 // the adjacent blocks to the JoinBB, looking at all intermediate blocks.
497
498 // If we know the function is "will-return" and "no-throw" there is no need
499 // for futher checks.
500 if (!F.hasFnAttribute(Attribute::WillReturn) || !F.doesNotThrow()) {
501
502 auto BlockTransfersExecutionToSuccessor = [](const BasicBlock *BB) {
504 };
505
507 while (!Worklist.empty()) {
508 const BasicBlock *ToBB = Worklist.pop_back_val();
509 if (ToBB == JoinBB)
510 continue;
511
512 // Make sure all loops in-between are finite.
513 if (!Visited.insert(ToBB).second) {
514 if (!F.hasFnAttribute(Attribute::WillReturn)) {
515 if (!LI)
516 return nullptr;
517
518 bool MayContainIrreducibleControl = getOrCreateCachedOptional(
519 &F, IrreducibleControlMap, mayContainIrreducibleControl, F, LI);
520 if (MayContainIrreducibleControl)
521 return nullptr;
522
523 const Loop *L = LI->getLoopFor(ToBB);
524 if (L && maybeEndlessLoop(*L))
525 return nullptr;
526 }
527
528 continue;
529 }
530
531 // Make sure the block has no instructions that could stop control
532 // transfer.
533 bool TransfersExecution = getOrCreateCachedOptional(
534 ToBB, BlockTransferMap, BlockTransfersExecutionToSuccessor, ToBB);
535 if (!TransfersExecution)
536 return nullptr;
537
538 append_range(Worklist, successors(ToBB));
539 }
540 }
541
542 LLVM_DEBUG(dbgs() << "\tJoin block: " << JoinBB->getName() << "\n");
543 return JoinBB;
544}
545const BasicBlock *
547 const LoopInfo *LI = LIGetter(*InitBB->getParent());
548 const DominatorTree *DT = DTGetter(*InitBB->getParent());
549 LLVM_DEBUG(dbgs() << "\tFind backward join point for " << InitBB->getName()
550 << (LI ? " [LI]" : "") << (DT ? " [DT]" : ""));
551
552 // Try to determine a join block through the help of the dominance tree. If no
553 // tree was provided, we perform simple pattern matching for one block
554 // conditionals only.
555 if (DT)
556 if (const auto *InitNode = DT->getNode(InitBB))
557 if (const auto *IDomNode = InitNode->getIDom())
558 return IDomNode->getBlock();
559
560 const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
561 const BasicBlock *HeaderBB = L ? L->getHeader() : nullptr;
562
563 // Determine the predecessor blocks but ignore backedges.
565 for (const BasicBlock *PredBB : predecessors(InitBB)) {
566 bool IsBackedge =
567 (PredBB == InitBB) || (HeaderBB == InitBB && L->contains(PredBB));
568 // Loop backedges are ignored in backwards propagation: control has to come
569 // from somewhere.
570 if (!IsBackedge)
571 Worklist.push_back(PredBB);
572 }
573
574 // If there are no other predecessor blocks, there is no join point.
575 if (Worklist.empty())
576 return nullptr;
577
578 // If there is one predecessor block, it is the join point.
579 if (Worklist.size() == 1)
580 return Worklist[0];
581
582 const BasicBlock *JoinBB = nullptr;
583 if (Worklist.size() == 2) {
584 const BasicBlock *Pred0 = Worklist[0];
585 const BasicBlock *Pred1 = Worklist[1];
586 const BasicBlock *Pred0UniquePred = Pred0->getUniquePredecessor();
587 const BasicBlock *Pred1UniquePred = Pred1->getUniquePredecessor();
588 if (Pred0 == Pred1UniquePred) {
589 // InitBB <- Pred0 = JoinBB
590 // InitBB <- Pred1 <- Pred0 = JoinBB
591 JoinBB = Pred0;
592 } else if (Pred1 == Pred0UniquePred) {
593 // InitBB <- Pred0 <- Pred1 = JoinBB
594 // InitBB <- Pred1 = JoinBB
595 JoinBB = Pred1;
596 } else if (Pred0UniquePred == Pred1UniquePred) {
597 // InitBB <- Pred0 <- JoinBB
598 // InitBB <- Pred1 <- JoinBB
599 JoinBB = Pred0UniquePred;
600 }
601 }
602
603 if (!JoinBB && L)
604 JoinBB = L->getHeader();
605
606 // In backwards direction there is no need to show termination of previous
607 // instructions. If they do not terminate, the code afterward is dead, making
608 // any information/transformation correct anyway.
609 return JoinBB;
610}
611
612const Instruction *
614 MustBeExecutedIterator &It, const Instruction *PP) {
615 if (!PP)
616 return PP;
617 LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP << "\n");
618
619 // If we explore only inside a given basic block we stop at terminators.
620 if (!ExploreInterBlock && PP->isTerminator()) {
621 LLVM_DEBUG(dbgs() << "\tReached terminator in intra-block mode, done\n");
622 return nullptr;
623 }
624
625 // If we do not traverse the call graph we check if we can make progress in
626 // the current function. First, check if the instruction is guaranteed to
627 // transfer execution to the successor.
628 bool TransfersExecution = isGuaranteedToTransferExecutionToSuccessor(PP);
629 if (!TransfersExecution)
630 return nullptr;
631
632 // If this is not a terminator we know that there is a single instruction
633 // after this one that is executed next if control is transfered. If not,
634 // we can try to go back to a call site we entered earlier. If none exists, we
635 // do not know any instruction that has to be executd next.
636 if (!PP->isTerminator()) {
637 const Instruction *NextPP = PP->getNextNode();
638 LLVM_DEBUG(dbgs() << "\tIntermediate instruction does transfer control\n");
639 return NextPP;
640 }
641
642 // Finally, we have to handle terminators, trivial ones first.
643 assert(PP->isTerminator() && "Expected a terminator!");
644
645 // A terminator without a successor is not handled yet.
646 if (PP->getNumSuccessors() == 0) {
647 LLVM_DEBUG(dbgs() << "\tUnhandled terminator\n");
648 return nullptr;
649 }
650
651 // A terminator with a single successor, we will continue at the beginning of
652 // that one.
653 if (PP->getNumSuccessors() == 1) {
655 dbgs() << "\tUnconditional terminator, continue with successor\n");
656 return &PP->getSuccessor(0)->front();
657 }
658
659 // Multiple successors mean we need to find the join point where control flow
660 // converges again. We use the findForwardJoinPoint helper function with
661 // information about the function and helper analyses, if available.
662 if (const BasicBlock *JoinBB = findForwardJoinPoint(PP->getParent()))
663 return &JoinBB->front();
664
665 LLVM_DEBUG(dbgs() << "\tNo join point found\n");
666 return nullptr;
667}
668
669const Instruction *
671 MustBeExecutedIterator &It, const Instruction *PP) {
672 if (!PP)
673 return PP;
674
675 bool IsFirst = !(PP->getPrevNode());
676 LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP
677 << (IsFirst ? " [IsFirst]" : "") << "\n");
678
679 // If we explore only inside a given basic block we stop at the first
680 // instruction.
681 if (!ExploreInterBlock && IsFirst) {
682 LLVM_DEBUG(dbgs() << "\tReached block front in intra-block mode, done\n");
683 return nullptr;
684 }
685
686 // The block and function that contains the current position.
687 const BasicBlock *PPBlock = PP->getParent();
688
689 // If we are inside a block we know what instruction was executed before, the
690 // previous one.
691 if (!IsFirst) {
692 const Instruction *PrevPP = PP->getPrevNode();
694 dbgs() << "\tIntermediate instruction, continue with previous\n");
695 // We did not enter a callee so we simply return the previous instruction.
696 return PrevPP;
697 }
698
699 // Finally, we have to handle the case where the program point is the first in
700 // a block but not in the function. We use the findBackwardJoinPoint helper
701 // function with information about the function and helper analyses, if
702 // available.
703 if (const BasicBlock *JoinBB = findBackwardJoinPoint(PPBlock))
704 return &JoinBB->back();
705
706 LLVM_DEBUG(dbgs() << "\tNo join point found\n");
707 return nullptr;
708}
709
712 : Explorer(Explorer), CurInst(I) {
713 reset(I);
714}
715
716void MustBeExecutedIterator::reset(const Instruction *I) {
717 Visited.clear();
718 resetInstruction(I);
719}
720
721void MustBeExecutedIterator::resetInstruction(const Instruction *I) {
722 CurInst = I;
723 Head = Tail = nullptr;
726 if (Explorer.ExploreCFGForward)
727 Head = I;
728 if (Explorer.ExploreCFGBackward)
729 Tail = I;
730}
731
732const Instruction *MustBeExecutedIterator::advance() {
733 assert(CurInst && "Cannot advance an end iterator!");
734 Head = Explorer.getMustBeExecutedNextInstruction(*this, Head);
735 if (Head && Visited.insert({Head, ExplorationDirection ::FORWARD}).second)
736 return Head;
737 Head = nullptr;
738
739 Tail = Explorer.getMustBeExecutedPrevInstruction(*this, Tail);
740 if (Tail && Visited.insert({Tail, ExplorationDirection ::BACKWARD}).second)
741 return Tail;
742 Tail = nullptr;
743 return nullptr;
744}
745
748 auto &LI = AM.getResult<LoopAnalysis>(F);
749 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
750
751 MustExecuteAnnotatedWriter Writer(F, DT, LI);
752 F.print(OS, &Writer);
753 return PreservedAnalyses::all();
754}
755
760 GetterTy<const LoopInfo> LIGetter = [&](const Function &F) {
761 return &FAM.getResult<LoopAnalysis>(const_cast<Function &>(F));
762 };
763 GetterTy<const DominatorTree> DTGetter = [&](const Function &F) {
764 return &FAM.getResult<DominatorTreeAnalysis>(const_cast<Function &>(F));
765 };
766 GetterTy<const PostDominatorTree> PDTGetter = [&](const Function &F) {
767 return &FAM.getResult<PostDominatorTreeAnalysis>(const_cast<Function &>(F));
768 };
769
771 /* ExploreInterBlock */ true,
772 /* ExploreCFGForward */ true,
773 /* ExploreCFGBackward */ true, LIGetter, DTGetter, PDTGetter);
774
775 for (Function &F : M) {
776 for (Instruction &I : instructions(F)) {
777 OS << "-- Explore context of: " << I << "\n";
778 for (const Instruction *CI : Explorer.range(&I))
779 OS << " [F: " << CI->getFunction()->getName() << "] " << *CI << "\n";
780 }
781 }
782 return PreservedAnalyses::all();
783}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Hexagon Hardware Loops
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
static void collectTransitivePredecessors(const Loop *CurLoop, const BasicBlock *BB, SmallPtrSetImpl< const BasicBlock * > &Predecessors)
Collect all blocks from CurLoop which lie on all possible paths from the header of CurLoop (inclusive...
static bool maybeEndlessLoop(const Loop &L)
Return true if L might be an endless loop.
static V getOrCreateCachedOptional(K Key, DenseMap< K, std::optional< V > > &Map, FnTy &&Fn, ArgsTy &&...args)
Lookup Key in Map and return the result, potentially after initializing the optional through Fn(args)...
static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT)
static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock, const DominatorTree *DT, const Loop *CurLoop)
Return true if we can prove that the given ExitBlock is not reached on the first iteration of the giv...
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
nvptx lower args
FunctionAnalysisManager FAM
This header defines various interfaces for pass management in LLVM.
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file contains some functions that are useful when dealing with strings.
Value * RHS
Value * LHS
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const Instruction & front() const
Definition: BasicBlock.h:471
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:497
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:459
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:467
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:292
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:757
This is an important base class in LLVM.
Definition: Constant.h:42
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:194
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:903
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1993
bool blockMayThrow(const BasicBlock *BB) const override
Returns true iff the block BB potentially may throw exception.
Definition: MustExecute.cpp:71
bool doesNotWriteMemoryBefore(const BasicBlock *BB, const Loop *CurLoop) const
Returns true if we could not execute a memory-modifying instruction before we enter BB under assumpti...
void removeInstruction(const Instruction *Inst)
Inform safety info that we are planning to remove the instruction Inst from its block.
Definition: MustExecute.cpp:99
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const override
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
bool anyBlockMayThrow() const override
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
Definition: MustExecute.cpp:75
void computeLoopSafetyInfo(const Loop *CurLoop) override
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Definition: MustExecute.cpp:79
void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Inform the safety info that we are planning to insert a new instruction Inst into the basic block BB.
Definition: MustExecute.cpp:93
bool isDominatedByICFIFromSameBlock(const Instruction *Insn)
Returns true if the first ICFI of Insn's block exists and dominates Insn.
bool hasICF(const BasicBlock *BB)
Returns true if at least one instruction from the given basic block has implicit control flow.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
void clear()
Invalidates all information from this tracking.
void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Notifies this tracking that we are going to insert a new instruction Inst to the basic block BB.
void removeInstruction(const Instruction *Inst)
Notifies this tracking that we are going to remove the instruction Inst It makes all necessary update...
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
bool isTerminator() const
Definition: Instruction.h:277
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool allLoopPathsLeadToBlock(const Loop *CurLoop, const BasicBlock *BB, const DominatorTree *DT) const
Return true if we must reach the block BB under assumption that the loop CurLoop is entered.
void copyColors(BasicBlock *New, BasicBlock *Old)
Copy colors of block Old into the block New.
Definition: MustExecute.cpp:36
void computeBlockColors(const Loop *CurLoop)
Computes block colors.
const DenseMap< BasicBlock *, ColorVector > & getBlockColors() const
Returns block colors map that is used to update funclet operand bundles.
Definition: MustExecute.cpp:32
virtual bool blockMayThrow(const BasicBlock *BB) const =0
Returns true iff the block BB potentially may throw exception.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:39
bool mayWriteToMemory(const BasicBlock *BB)
Returns true if at least one instruction from the given basic block may write memory.
bool isDominatedByMemoryWriteFromSameBlock(const Instruction *Insn)
Returns true if the first memory writing instruction of Insn's block exists and dominates Insn.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:291
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
Definition: MustExecute.h:109
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const override
Returns true if the instruction in a loop is guaranteed to execute at least once.
void computeLoopSafetyInfo(const Loop *CurLoop) override
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Definition: MustExecute.cpp:51
bool anyBlockMayThrow() const override
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
Definition: MustExecute.cpp:47
bool blockMayThrow(const BasicBlock *BB) const override
Returns true iff the block BB potentially may throw exception.
Definition: MustExecute.cpp:42
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:346
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:435
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:367
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:441
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:502
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:29
LLVM Value Representation.
Definition: Value.h:74
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
const ParentTy * getParent() const
Definition: ilist_node.h:32
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:353
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
auto successors(const MachineBasicBlock *BB)
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2098
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition: CFG.h:148
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Value * simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto predecessors(const MachineBasicBlock *BB)
bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI)
A "must be executed context" for a given program point PP is the set of instructions,...
Definition: MustExecute.h:385
const bool ExploreInterBlock
Parameter that limit the performed exploration.
Definition: MustExecute.h:515
const BasicBlock * findBackwardJoinPoint(const BasicBlock *InitBB)
Find the next join point from InitBB in backward direction.
const Instruction * getMustBeExecutedNextInstruction(MustBeExecutedIterator &It, const Instruction *PP)
Return the next instruction that is guaranteed to be executed after PP.
llvm::iterator_range< iterator > range(const Instruction *PP)
}
Definition: MustExecute.h:441
const Instruction * getMustBeExecutedPrevInstruction(MustBeExecutedIterator &It, const Instruction *PP)
Return the previous instr.
const BasicBlock * findForwardJoinPoint(const BasicBlock *InitBB)
Find the next join point from InitBB in forward direction.
Must be executed iterators visit stretches of instructions that are guaranteed to be executed togethe...
Definition: MustExecute.h:271
MustBeExecutedIterator(const MustBeExecutedIterator &Other)=default