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