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 return BlockColors;
32}
33
35 ColorVector &ColorsForNewBlock = BlockColors[New];
36 ColorVector &ColorsForOldBlock = BlockColors[Old];
37 ColorsForNewBlock = ColorsForOldBlock;
38}
39
41 (void)BB;
42 return anyBlockMayThrow();
43}
44
46 return MayThrow;
47}
48
49void SimpleLoopSafetyInfo::computeLoopSafetyInfo() {
50 assert(CurLoop != nullptr && "CurLoop can't be null");
51 BasicBlock *Header = CurLoop->getHeader();
52 // Iterate over header and compute safety info.
53 HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
54 MayThrow = HeaderMayThrow;
55 // Iterate over loop instructions and compute safety info.
56 // Skip header as it has been computed and stored in HeaderMayThrow.
57 // The first block in loopinfo.Blocks is guaranteed to be the header.
58 assert(Header == *CurLoop->getBlocks().begin() &&
59 "First block must be header");
60 for (const BasicBlock *BB : llvm::drop_begin(CurLoop->blocks())) {
62 if (MayThrow)
63 break;
64 }
65
67}
68
70 return ICF.hasICF(BB);
71}
72
74 return MayThrow;
75}
76
77void ICFLoopSafetyInfo::computeLoopSafetyInfo() {
78 assert(CurLoop != nullptr && "CurLoop can't be null");
79 ICF.clear();
80 MW.clear();
81 MayThrow = false;
82 // Figure out the fact that at least one block may throw.
83 for (const auto &BB : CurLoop->blocks())
84 if (ICF.hasICF(&*BB)) {
85 MayThrow = true;
86 break;
87 }
89}
90
92 const BasicBlock *BB) {
93 ICF.insertInstructionTo(Inst, BB);
94 MW.insertInstructionTo(Inst, BB);
95}
96
98 ICF.removeInstruction(Inst);
99 MW.removeInstruction(Inst);
100}
101
103 // Compute funclet colors if we might sink/hoist in a function with a funclet
104 // personality routine.
105 Function *Fn = CurLoop->getHeader()->getParent();
106 if (Fn->hasPersonalityFn())
107 if (Constant *PersonalityFn = Fn->getPersonalityFn())
109 BlockColors = colorEHFunclets(*Fn);
110}
111
112/// Return true if we can prove that the given ExitBlock is not reached on the
113/// first iteration of the given loop. That is, the backedge of the loop must
114/// be executed before the ExitBlock is executed in any dynamic execution trace.
115static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
116 const DominatorTree *DT,
117 const Loop *CurLoop) {
118 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
119 if (!CondExitBlock)
120 // expect unique exits
121 return false;
122 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
123 auto *BI = dyn_cast<CondBrInst>(CondExitBlock->getTerminator());
124 if (!BI)
125 return false;
126 // If condition is constant and false leads to ExitBlock then we always
127 // execute the true branch.
128 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
129 return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
130 auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
131 if (!Cond)
132 return false;
133 // todo: this would be a lot more powerful if we used scev, but all the
134 // plumbing is currently missing to pass a pointer in from the pass
135 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
136 ICmpInst::Predicate Pred = Cond->getPredicate();
137 auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
138 auto *RHS = Cond->getOperand(1);
139 if (!LHS || LHS->getParent() != CurLoop->getHeader()) {
140 Pred = Cond->getSwappedPredicate();
141 LHS = dyn_cast<PHINode>(Cond->getOperand(1));
142 RHS = Cond->getOperand(0);
143 if (!LHS || LHS->getParent() != CurLoop->getHeader())
144 return false;
145 }
146
147 auto DL = ExitBlock->getModule()->getDataLayout();
148 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
149 auto *SimpleValOrNull = simplifyCmpInst(
150 Pred, IVStart, RHS, {DL, /*TLI*/ nullptr, DT, /*AC*/ nullptr, BI});
151 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
152 if (!SimpleCst)
153 return false;
154 if (ExitBlock == BI->getSuccessor(0))
155 return SimpleCst->isNullValue();
156 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
157 return SimpleCst->isAllOnesValue();
158}
159
160/// Collect all blocks from \p CurLoop which lie on all possible paths from
161/// the header of \p CurLoop (inclusive) to BB (exclusive) into the set
162/// \p Predecessors. If \p BB is the header, \p Predecessors will be empty.
163/// Note: It's possible that we encounter Irreducible control flow, due to
164/// which, we may find that a few predecessors of \p BB are not a part of the
165/// \p CurLoop. We only return Predecessors that are a part of \p CurLoop.
167 const Loop *CurLoop, const BasicBlock *BB,
169 assert(Predecessors.empty() && "Garbage in predecessors set?");
170 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
171 if (BB == CurLoop->getHeader())
172 return;
174 for (const auto *Pred : predecessors(BB)) {
175 if (!CurLoop->contains(Pred))
176 continue;
177 Predecessors.insert(Pred);
178 WorkList.push_back(Pred);
179 }
180 while (!WorkList.empty()) {
181 auto *Pred = WorkList.pop_back_val();
182 assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
183 // We are not interested in backedges and we don't want to leave loop.
184 if (Pred == CurLoop->getHeader())
185 continue;
186 // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
187 // blocks of this inner loop, even those that are always executed AFTER the
188 // BB. It may make our analysis more conservative than it could be, see test
189 // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
190 // We can ignore backedge of all loops containing BB to get a sligtly more
191 // optimistic result.
192 for (const auto *PredPred : predecessors(Pred))
193 if (CurLoop->contains(PredPred) && Predecessors.insert(PredPred).second)
194 WorkList.push_back(PredPred);
195 }
196}
197
199 const DominatorTree *DT) const {
200 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
201
202 // Fast path: header is always reached once the loop is entered.
203 if (BB == CurLoop->getHeader())
204 return true;
205
206 auto [It, Inserted] = GuaranteedToExecute.try_emplace(BB, false);
207 if (Inserted)
208 It->second = allLoopPathsLeadToBlockImpl(BB, DT);
209 return It->second;
210}
211
212bool LoopSafetyInfo::allLoopPathsLeadToBlockImpl(
213 const BasicBlock *BB, const DominatorTree *DT) const {
214 // Collect all transitive predecessors of BB in the same loop. This set will
215 // be a subset of the blocks within the loop.
217 collectTransitivePredecessors(CurLoop, BB, Predecessors);
218
219 // Bail out if a latch block is part of the predecessor set. In this case
220 // we may take the backedge to the header and not execute other latch
221 // successors.
222 for (const BasicBlock *Pred : predecessors(CurLoop->getHeader()))
223 // Predecessors only contains loop blocks, so we don't have to worry about
224 // preheader predecessors here.
225 if (Predecessors.contains(Pred))
226 return false;
227
228 // Make sure that all successors of, all predecessors of BB which are not
229 // dominated by BB, are either:
230 // 1) BB,
231 // 2) Also predecessors of BB,
232 // 3) Exit blocks which are not taken on 1st iteration.
233 // Memoize blocks we've already checked.
234 SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
235 for (const auto *Pred : Predecessors) {
236 // Predecessor block may throw, so it has a side exit.
237 if (blockMayThrow(Pred))
238 return false;
239
240 // BB dominates Pred, so if Pred runs, BB must run.
241 // This is true when Pred is a loop latch.
242 if (DT->dominates(BB, Pred))
243 continue;
244
245 for (const auto *Succ : successors(Pred))
246 if (CheckedSuccessors.insert(Succ).second &&
247 Succ != BB && !Predecessors.count(Succ))
248 // By discharging conditions that are not executed on the 1st iteration,
249 // we guarantee that *at least* on the first iteration all paths from
250 // header that *may* execute will lead us to the block of interest. So
251 // that if we had virtually peeled one iteration away, in this peeled
252 // iteration the set of predecessors would contain only paths from
253 // header to BB without any exiting edges that may execute.
254 //
255 // TODO: We only do it for exiting edges currently. We could use the
256 // same function to skip some of the edges within the loop if we know
257 // that they will not be taken on the 1st iteration.
258 //
259 // TODO: If we somehow know the number of iterations in loop, the same
260 // check may be done for any arbitrary N-th iteration as long as N is
261 // not greater than minimum number of iterations in this loop.
262 if (CurLoop->contains(Succ) ||
264 return false;
265 }
266
267 // All predecessors can only lead us to BB.
268 return true;
269}
270
271/// Returns true if the instruction in a loop is guaranteed to execute at least
272/// once.
274 const Instruction &Inst, const DominatorTree *DT) const {
275 // If the instruction is in the header block for the loop (which is very
276 // common), it is always guaranteed to dominate the exit blocks. Since this
277 // is a common case, and can save some work, check it now.
278 if (Inst.getParent() == CurLoop->getHeader())
279 // If there's a throw in the header block, we can't guarantee we'll reach
280 // Inst unless we can prove that Inst comes before the potential implicit
281 // exit. At the moment, we use a (cheap) hack for the common case where
282 // the instruction of interest is the first one in the block.
283 return !HeaderMayThrow ||
284 &*Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
285
286 // If there is a path from header to exit or latch that doesn't lead to our
287 // instruction's block, return false.
288 return allLoopPathsLeadToBlock(Inst.getParent(), DT);
289}
290
292 const DominatorTree *DT) const {
293 return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
295}
296
298 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
299
300 // Fast path: there are no instructions before header.
301 if (BB == CurLoop->getHeader())
302 return true;
303
304 // Collect all transitive predecessors of BB in the same loop. This set will
305 // be a subset of the blocks within the loop.
307 collectTransitivePredecessors(CurLoop, BB, Predecessors);
308 // Find if there any instruction in either predecessor that could write
309 // to memory.
310 for (const auto *Pred : Predecessors)
311 if (MW.mayWriteToMemory(Pred))
312 return false;
313 return true;
314}
315
317 auto *BB = I.getParent();
318 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
319 return !MW.isDominatedByMemoryWriteFromSameBlock(&I) &&
321}
322
323static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
324 // TODO: merge these two routines. For the moment, we display the best
325 // result obtained by *either* implementation. This is a bit unfair since no
326 // caller actually gets the full power at the moment.
328 return LSI.isGuaranteedToExecute(I, DT) ||
330}
331
332namespace {
333/// An assembly annotator class to print must execute information in
334/// comments.
335class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
336 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
337
338public:
339 MustExecuteAnnotatedWriter(const Function &F,
340 DominatorTree &DT, LoopInfo &LI) {
341 for (const auto &I: instructions(F)) {
342 Loop *L = LI.getLoopFor(I.getParent());
343 while (L) {
344 if (isMustExecuteIn(I, L, &DT)) {
345 MustExec[&I].push_back(L);
346 }
347 L = L->getParentLoop();
348 };
349 }
350 }
351 MustExecuteAnnotatedWriter(const Module &M,
352 DominatorTree &DT, LoopInfo &LI) {
353 for (const auto &F : M)
354 for (const auto &I: instructions(F)) {
355 Loop *L = LI.getLoopFor(I.getParent());
356 while (L) {
357 if (isMustExecuteIn(I, L, &DT)) {
358 MustExec[&I].push_back(L);
359 }
360 L = L->getParentLoop();
361 };
362 }
363 }
364
365
366 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
367 if (!MustExec.count(&V))
368 return;
369
370 const auto &Loops = MustExec.lookup(&V);
371 const auto NumLoops = Loops.size();
372 if (NumLoops > 1)
373 OS << " ; (mustexec in " << NumLoops << " loops: ";
374 else
375 OS << " ; (mustexec in: ";
376
377 ListSeparator LS;
378 for (const Loop *L : Loops)
379 OS << LS << L->getHeader()->getName();
380 OS << ")";
381 }
382};
383} // namespace
384
385/// Return true if \p L might be an endless loop.
386static bool maybeEndlessLoop(const Loop &L) {
387 if (L.getHeader()->getParent()->hasFnAttribute(Attribute::WillReturn))
388 return false;
389 // TODO: Actually try to prove it is not.
390 // TODO: If maybeEndlessLoop is going to be expensive, cache it.
391 return true;
392}
393
395 if (!LI)
396 return false;
398 RPOTraversal FuncRPOT(&F);
399 return containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
400 const LoopInfo>(FuncRPOT, *LI);
401}
402
403/// Lookup \p Key in \p Map and return the result, potentially after
404/// initializing the optional through \p Fn(\p args).
405template <typename K, typename V, typename FnTy, typename... ArgsTy>
406static V getOrCreateCachedOptional(K Key, DenseMap<K, std::optional<V>> &Map,
407 FnTy &&Fn, ArgsTy &&...args) {
408 std::optional<V> &OptVal = Map[Key];
409 if (!OptVal)
410 OptVal = Fn(std::forward<ArgsTy>(args)...);
411 return *OptVal;
412}
413
414const BasicBlock *
416 const LoopInfo *LI = LIGetter(*InitBB->getParent());
417 const PostDominatorTree *PDT = PDTGetter(*InitBB->getParent());
418
419 LLVM_DEBUG(dbgs() << "\tFind forward join point for " << InitBB->getName()
420 << (LI ? " [LI]" : "") << (PDT ? " [PDT]" : ""));
421
422 const Function &F = *InitBB->getParent();
423 const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
424 const BasicBlock *HeaderBB = L ? L->getHeader() : InitBB;
425 bool WillReturnAndNoThrow = (F.hasFnAttribute(Attribute::WillReturn) ||
426 (L && !maybeEndlessLoop(*L))) &&
427 F.doesNotThrow();
428 LLVM_DEBUG(dbgs() << (L ? " [in loop]" : "")
429 << (WillReturnAndNoThrow ? " [WillReturn] [NoUnwind]" : "")
430 << "\n");
431
432 // Determine the adjacent blocks in the given direction but exclude (self)
433 // loops under certain circumstances.
435 for (const BasicBlock *SuccBB : successors(InitBB)) {
436 bool IsLatch = SuccBB == HeaderBB;
437 // Loop latches are ignored in forward propagation if the loop cannot be
438 // endless and may not throw: control has to go somewhere.
439 if (!WillReturnAndNoThrow || !IsLatch)
440 Worklist.push_back(SuccBB);
441 }
442 LLVM_DEBUG(dbgs() << "\t\t#Worklist: " << Worklist.size() << "\n");
443
444 // If there are no other adjacent blocks, there is no join point.
445 if (Worklist.empty())
446 return nullptr;
447
448 // If there is one adjacent block, it is the join point.
449 if (Worklist.size() == 1)
450 return Worklist[0];
451
452 // Try to determine a join block through the help of the post-dominance
453 // tree. If no tree was provided, we perform simple pattern matching for one
454 // block conditionals and one block loops only.
455 const BasicBlock *JoinBB = nullptr;
456 if (PDT)
457 if (const auto *InitNode = PDT->getNode(InitBB))
458 if (const auto *IDomNode = InitNode->getIDom())
459 JoinBB = IDomNode->getBlock();
460
461 if (!JoinBB && Worklist.size() == 2) {
462 const BasicBlock *Succ0 = Worklist[0];
463 const BasicBlock *Succ1 = Worklist[1];
464 const BasicBlock *Succ0UniqueSucc = Succ0->getUniqueSuccessor();
465 const BasicBlock *Succ1UniqueSucc = Succ1->getUniqueSuccessor();
466 if (Succ0UniqueSucc == InitBB) {
467 // InitBB -> Succ0 -> InitBB
468 // InitBB -> Succ1 = JoinBB
469 JoinBB = Succ1;
470 } else if (Succ1UniqueSucc == InitBB) {
471 // InitBB -> Succ1 -> InitBB
472 // InitBB -> Succ0 = JoinBB
473 JoinBB = Succ0;
474 } else if (Succ0 == Succ1UniqueSucc) {
475 // InitBB -> Succ0 = JoinBB
476 // InitBB -> Succ1 -> Succ0 = JoinBB
477 JoinBB = Succ0;
478 } else if (Succ1 == Succ0UniqueSucc) {
479 // InitBB -> Succ0 -> Succ1 = JoinBB
480 // InitBB -> Succ1 = JoinBB
481 JoinBB = Succ1;
482 } else if (Succ0UniqueSucc == Succ1UniqueSucc) {
483 // InitBB -> Succ0 -> JoinBB
484 // InitBB -> Succ1 -> JoinBB
485 JoinBB = Succ0UniqueSucc;
486 }
487 }
488
489 if (!JoinBB && L)
490 JoinBB = L->getUniqueExitBlock();
491
492 if (!JoinBB)
493 return nullptr;
494
495 LLVM_DEBUG(dbgs() << "\t\tJoin block candidate: " << JoinBB->getName() << "\n");
496
497 // In forward direction we check if control will for sure reach JoinBB from
498 // InitBB, thus it can not be "stopped" along the way. Ways to "stop" control
499 // are: infinite loops and instructions that do not necessarily transfer
500 // execution to their successor. To check for them we traverse the CFG from
501 // the adjacent blocks to the JoinBB, looking at all intermediate blocks.
502
503 // If we know the function is "will-return" and "no-throw" there is no need
504 // for futher checks.
505 if (!F.hasFnAttribute(Attribute::WillReturn) || !F.doesNotThrow()) {
506
507 auto BlockTransfersExecutionToSuccessor = [](const BasicBlock *BB) {
509 };
510
512 while (!Worklist.empty()) {
513 const BasicBlock *ToBB = Worklist.pop_back_val();
514 if (ToBB == JoinBB)
515 continue;
516
517 // Make sure all loops in-between are finite.
518 if (!Visited.insert(ToBB).second) {
519 if (!F.hasFnAttribute(Attribute::WillReturn)) {
520 if (!LI)
521 return nullptr;
522
523 bool MayContainIrreducibleControl = getOrCreateCachedOptional(
524 &F, IrreducibleControlMap, mayContainIrreducibleControl, F, LI);
525 if (MayContainIrreducibleControl)
526 return nullptr;
527
528 const Loop *L = LI->getLoopFor(ToBB);
529 if (L && maybeEndlessLoop(*L))
530 return nullptr;
531 }
532
533 continue;
534 }
535
536 // Make sure the block has no instructions that could stop control
537 // transfer.
538 bool TransfersExecution = getOrCreateCachedOptional(
539 ToBB, BlockTransferMap, BlockTransfersExecutionToSuccessor, ToBB);
540 if (!TransfersExecution)
541 return nullptr;
542
543 append_range(Worklist, successors(ToBB));
544 }
545 }
546
547 LLVM_DEBUG(dbgs() << "\tJoin block: " << JoinBB->getName() << "\n");
548 return JoinBB;
549}
550const BasicBlock *
552 const LoopInfo *LI = LIGetter(*InitBB->getParent());
553 const DominatorTree *DT = DTGetter(*InitBB->getParent());
554 LLVM_DEBUG(dbgs() << "\tFind backward join point for " << InitBB->getName()
555 << (LI ? " [LI]" : "") << (DT ? " [DT]" : ""));
556
557 // Try to determine a join block through the help of the dominance tree. If no
558 // tree was provided, we perform simple pattern matching for one block
559 // conditionals only.
560 if (DT)
561 if (const auto *InitNode = DT->getNode(InitBB))
562 if (const auto *IDomNode = InitNode->getIDom())
563 return IDomNode->getBlock();
564
565 const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
566 const BasicBlock *HeaderBB = L ? L->getHeader() : nullptr;
567
568 // Determine the predecessor blocks but ignore backedges.
570 for (const BasicBlock *PredBB : predecessors(InitBB)) {
571 bool IsBackedge =
572 (PredBB == InitBB) || (HeaderBB == InitBB && L->contains(PredBB));
573 // Loop backedges are ignored in backwards propagation: control has to come
574 // from somewhere.
575 if (!IsBackedge)
576 Worklist.push_back(PredBB);
577 }
578
579 // If there are no other predecessor blocks, there is no join point.
580 if (Worklist.empty())
581 return nullptr;
582
583 // If there is one predecessor block, it is the join point.
584 if (Worklist.size() == 1)
585 return Worklist[0];
586
587 const BasicBlock *JoinBB = nullptr;
588 if (Worklist.size() == 2) {
589 const BasicBlock *Pred0 = Worklist[0];
590 const BasicBlock *Pred1 = Worklist[1];
591 const BasicBlock *Pred0UniquePred = Pred0->getUniquePredecessor();
592 const BasicBlock *Pred1UniquePred = Pred1->getUniquePredecessor();
593 if (Pred0 == Pred1UniquePred) {
594 // InitBB <- Pred0 = JoinBB
595 // InitBB <- Pred1 <- Pred0 = JoinBB
596 JoinBB = Pred0;
597 } else if (Pred1 == Pred0UniquePred) {
598 // InitBB <- Pred0 <- Pred1 = JoinBB
599 // InitBB <- Pred1 = JoinBB
600 JoinBB = Pred1;
601 } else if (Pred0UniquePred == Pred1UniquePred) {
602 // InitBB <- Pred0 <- JoinBB
603 // InitBB <- Pred1 <- JoinBB
604 JoinBB = Pred0UniquePred;
605 }
606 }
607
608 if (!JoinBB && L)
609 JoinBB = L->getHeader();
610
611 // In backwards direction there is no need to show termination of previous
612 // instructions. If they do not terminate, the code afterward is dead, making
613 // any information/transformation correct anyway.
614 return JoinBB;
615}
616
617const Instruction *
619 MustBeExecutedIterator &It, const Instruction *PP) {
620 if (!PP)
621 return PP;
622 LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP << "\n");
623
624 // If we explore only inside a given basic block we stop at terminators.
625 if (!ExploreInterBlock && PP->isTerminator()) {
626 LLVM_DEBUG(dbgs() << "\tReached terminator in intra-block mode, done\n");
627 return nullptr;
628 }
629
630 // If we do not traverse the call graph we check if we can make progress in
631 // the current function. First, check if the instruction is guaranteed to
632 // transfer execution to the successor.
633 bool TransfersExecution = isGuaranteedToTransferExecutionToSuccessor(PP);
634 if (!TransfersExecution)
635 return nullptr;
636
637 // If this is not a terminator we know that there is a single instruction
638 // after this one that is executed next if control is transfered. If not,
639 // we can try to go back to a call site we entered earlier. If none exists, we
640 // do not know any instruction that has to be executd next.
641 if (!PP->isTerminator()) {
642 const Instruction *NextPP = PP->getNextNode();
643 LLVM_DEBUG(dbgs() << "\tIntermediate instruction does transfer control\n");
644 return NextPP;
645 }
646
647 // Finally, we have to handle terminators, trivial ones first.
648 assert(PP->isTerminator() && "Expected a terminator!");
649
650 // A terminator without a successor is not handled yet.
651 if (PP->getNumSuccessors() == 0) {
652 LLVM_DEBUG(dbgs() << "\tUnhandled terminator\n");
653 return nullptr;
654 }
655
656 // A terminator with a single successor, we will continue at the beginning of
657 // that one.
658 if (PP->getNumSuccessors() == 1) {
660 dbgs() << "\tUnconditional terminator, continue with successor\n");
661 return &PP->getSuccessor(0)->front();
662 }
663
664 // Multiple successors mean we need to find the join point where control flow
665 // converges again. We use the findForwardJoinPoint helper function with
666 // information about the function and helper analyses, if available.
667 if (const BasicBlock *JoinBB = findForwardJoinPoint(PP->getParent()))
668 return &JoinBB->front();
669
670 LLVM_DEBUG(dbgs() << "\tNo join point found\n");
671 return nullptr;
672}
673
674const Instruction *
676 MustBeExecutedIterator &It, const Instruction *PP) {
677 if (!PP)
678 return PP;
679
680 bool IsFirst = !(PP->getPrevNode());
681 LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP
682 << (IsFirst ? " [IsFirst]" : "") << "\n");
683
684 // If we explore only inside a given basic block we stop at the first
685 // instruction.
686 if (!ExploreInterBlock && IsFirst) {
687 LLVM_DEBUG(dbgs() << "\tReached block front in intra-block mode, done\n");
688 return nullptr;
689 }
690
691 // The block and function that contains the current position.
692 const BasicBlock *PPBlock = PP->getParent();
693
694 // If we are inside a block we know what instruction was executed before, the
695 // previous one.
696 if (!IsFirst) {
697 const Instruction *PrevPP = PP->getPrevNode();
699 dbgs() << "\tIntermediate instruction, continue with previous\n");
700 // We did not enter a callee so we simply return the previous instruction.
701 return PrevPP;
702 }
703
704 // Finally, we have to handle the case where the program point is the first in
705 // a block but not in the function. We use the findBackwardJoinPoint helper
706 // function with information about the function and helper analyses, if
707 // available.
708 if (const BasicBlock *JoinBB = findBackwardJoinPoint(PPBlock))
709 return &JoinBB->back();
710
711 LLVM_DEBUG(dbgs() << "\tNo join point found\n");
712 return nullptr;
713}
714
717 : Explorer(Explorer), CurInst(I) {
718 reset(I);
719}
720
721void MustBeExecutedIterator::reset(const Instruction *I) {
722 Visited.clear();
723 resetInstruction(I);
724}
725
726void MustBeExecutedIterator::resetInstruction(const Instruction *I) {
727 CurInst = I;
728 Head = Tail = nullptr;
729 Visited.insert({I, ExplorationDirection::FORWARD});
730 Visited.insert({I, ExplorationDirection::BACKWARD});
731 if (Explorer.ExploreCFGForward)
732 Head = I;
733 if (Explorer.ExploreCFGBackward)
734 Tail = I;
735}
736
737const Instruction *MustBeExecutedIterator::advance() {
738 assert(CurInst && "Cannot advance an end iterator!");
739 Head = Explorer.getMustBeExecutedNextInstruction(*this, Head);
740 if (Head && Visited.insert({Head, ExplorationDirection ::FORWARD}).second)
741 return Head;
742 Head = nullptr;
743
744 Tail = Explorer.getMustBeExecutedPrevInstruction(*this, Tail);
745 if (Tail && Visited.insert({Tail, ExplorationDirection ::BACKWARD}).second)
746 return Tail;
747 Tail = nullptr;
748 return nullptr;
749}
750
753 auto &LI = AM.getResult<LoopAnalysis>(F);
754 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
755
756 MustExecuteAnnotatedWriter Writer(F, DT, LI);
757 F.print(OS, &Writer);
758 return PreservedAnalyses::all();
759}
760
765 GetterTy<const LoopInfo> LIGetter = [&](const Function &F) {
766 return &FAM.getResult<LoopAnalysis>(const_cast<Function &>(F));
767 };
768 GetterTy<const DominatorTree> DTGetter = [&](const Function &F) {
769 return &FAM.getResult<DominatorTreeAnalysis>(const_cast<Function &>(F));
770 };
771 GetterTy<const PostDominatorTree> PDTGetter = [&](const Function &F) {
772 return &FAM.getResult<PostDominatorTreeAnalysis>(const_cast<Function &>(F));
773 };
774
776 /* ExploreInterBlock */ true,
777 /* ExploreCFGForward */ true,
778 /* ExploreCFGBackward */ true, LIGetter, DTGetter, PDTGetter);
779
780 for (Function &F : M) {
781 for (Instruction &I : instructions(F)) {
782 OS << "-- Explore context of: " << I << "\n";
783 for (const Instruction *CI : Explorer.range(&I))
784 OS << " [F: " << CI->getFunction()->getName() << "] " << *CI << "\n";
785 }
786 }
787 return PreservedAnalyses::all();
788}
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:250
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:219
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 void computeBlockColors()
Computes block colors.
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:67
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