LLVM 24.0.0git
LoopInfo.cpp
Go to the documentation of this file.
1//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
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//
9// This file defines the LoopInfo class that is used to identify natural loops
10// and determine the loop depth of various nodes of the CFG. Note that the
11// loops identified may actually be several natural loops that share the same
12// header node... not just a single natural loop.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/ScopeExit.h"
19#include "llvm/Analysis/CFG.h"
27#include "llvm/Config/llvm-config.h"
28#include "llvm/IR/CFG.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/DebugLoc.h"
31#include "llvm/IR/Dominators.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/PassManager.h"
37#include "llvm/IR/PrintPasses.h"
44using namespace llvm;
45
46// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
49
50// Always verify loopinfo if expensive checking is enabled.
51#ifdef EXPENSIVE_CHECKS
52bool llvm::VerifyLoopInfo = true;
53#else
55#endif
58 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
59
60//===----------------------------------------------------------------------===//
61// Loop implementation
62//
63
64bool Loop::isLoopInvariant(const Value *V) const {
65 if (const Instruction *I = dyn_cast<Instruction>(V))
66 return !contains(I);
67 return true; // All non-instructions are loop invariant
68}
69
71 return all_of(I->operands(), [&](Value *V) { return isLoopInvariant(V); });
72}
73
75 MemorySSAUpdater *MSSAU,
76 ScalarEvolution *SE) const {
78 return makeLoopInvariant(I, Changed, InsertPt, MSSAU, SE);
79 return true; // All non-instructions are loop-invariant.
80}
81
84 ScalarEvolution *SE) const {
85 BasicBlock *OriginalParent = I->getParent();
86 // Test if the value is already loop-invariant.
87 if (isLoopInvariant(I))
88 return true;
90 return false;
91 if (I->mayReadFromMemory())
92 return false;
93 // EH block instructions are immobile.
94 if (I->isEHPad())
95 return false;
96 // Determine the insertion point, unless one was given.
97 if (!InsertPt) {
98 BasicBlock *Preheader = getLoopPreheader();
99 // Without a preheader, hoisting is not feasible.
100 if (!Preheader)
101 return false;
102 InsertPt = Preheader->getTerminator();
103 }
104 // Don't hoist instructions with loop-variant operands.
105 for (Value *Operand : I->operands())
106 if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU, SE))
107 return false;
108
109 // Hoist.
110 I->moveBefore(InsertPt->getIterator());
111 if (MSSAU)
112 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
113 MSSAU->moveToPlace(MUD, InsertPt->getParent(),
115
116 // We want to preserve profile metadata if possible. However, we need to
117 // ensure that profile metadata would remain the same outside of the loop.
118 // Given at this point we know the conditional is loop-invariant, we just
119 // need to worry about other control flow in the loop conditioned on values
120 // that are potentially not independent of the condition of the instruction
121 // we are interested in hoisting. Given this is not knowable in the general
122 // case, we only hoist from a loop header (which covers a reasonable number
123 // of cases) where we are guaranteed to not run into problems.
124 SmallVector<unsigned, 1> ProfileMetadataToPreserve;
125 if (OriginalParent == getHeader())
126 ProfileMetadataToPreserve.push_back(LLVMContext::MD_prof);
127
128 // There is possibility of hoisting this instruction above some arbitrary
129 // condition. Any metadata defined on it can be control dependent on this
130 // condition. Conservatively strip it here so that we don't give any wrong
131 // information to the optimizer.
132 I->dropUBImplyingAttrsAndUnknownMetadata(ProfileMetadataToPreserve);
133
134 if (ProfileMetadataToPreserve.empty() && isa<SelectInst>(I))
136
137 if (SE)
139
140 Changed = true;
141 return true;
142}
143
145 BasicBlock *&Backedge) const {
147
148 Incoming = nullptr;
149 Backedge = nullptr;
151 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
152 Backedge = *PI++;
153 if (PI == pred_end(H))
154 return false; // dead loop
155 Incoming = *PI++;
156 if (PI != pred_end(H))
157 return false; // multiple backedges?
158
159 if (contains(Incoming)) {
160 if (contains(Backedge))
161 return false;
162 std::swap(Incoming, Backedge);
163 } else if (!contains(Backedge))
164 return false;
165
166 assert(Incoming && Backedge && "expected non-null incoming and backedges");
167 return true;
168}
169
172
173 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
174 if (!getIncomingAndBackEdge(Incoming, Backedge))
175 return nullptr;
176
177 // Loop over all of the PHI nodes, looking for a canonical indvar.
178 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
179 PHINode *PN = cast<PHINode>(I);
180 if (ConstantInt *CI =
182 if (CI->isZero())
183 if (Instruction *Inc =
185 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
186 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
187 if (CI->isOne())
188 return PN;
189 }
190 return nullptr;
191}
192
193/// Get the latch condition instruction.
195 if (BasicBlock *Latch = getLoopLatch())
196 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator()))
197 return dyn_cast<ICmpInst>(BI->getCondition());
198
199 return nullptr;
200}
201
202/// Return the final value of the loop induction variable if found.
203static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
204 const Instruction &StepInst) {
205 ICmpInst *LatchCmpInst = L.getLatchCmpInst();
206 if (!LatchCmpInst)
207 return nullptr;
208
209 Value *Op0 = LatchCmpInst->getOperand(0);
210 Value *Op1 = LatchCmpInst->getOperand(1);
211 if (Op0 == &IndVar || Op0 == &StepInst)
212 return Op1;
213
214 if (Op1 == &IndVar || Op1 == &StepInst)
215 return Op0;
216
217 return nullptr;
218}
219
220std::optional<Loop::LoopBounds>
222 ScalarEvolution &SE) {
223 InductionDescriptor IndDesc;
224 if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
225 return std::nullopt;
226
227 Value *InitialIVValue = IndDesc.getStartValue();
228 Instruction *StepInst = IndDesc.getInductionBinOp();
229 if (!InitialIVValue || !StepInst)
230 return std::nullopt;
231
232 const SCEV *Step = IndDesc.getStep();
233 Value *StepInstOp1 = StepInst->getOperand(1);
234 Value *StepInstOp0 = StepInst->getOperand(0);
235 Value *StepValue = nullptr;
236 if (SE.getSCEV(StepInstOp1) == Step)
237 StepValue = StepInstOp1;
238 else if (SE.getSCEV(StepInstOp0) == Step)
239 StepValue = StepInstOp0;
240
241 Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
242 if (!FinalIVValue)
243 return std::nullopt;
244
245 return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
246 SE);
247}
248
250
252 BasicBlock *Latch = L.getLoopLatch();
253 assert(Latch && "Expecting valid latch");
254
256
257 ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
258 assert(LatchCmpInst &&
259 "Expecting the latch compare instruction to be a CmpInst");
260
261 // Need to inverse the predicate when first successor is not the loop
262 // header
263 ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
264 ? LatchCmpInst->getPredicate()
265 : LatchCmpInst->getInversePredicate();
266
267 if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
269
270 // Need to flip strictness of the predicate when the latch compare instruction
271 // is not using StepInst
272 if (LatchCmpInst->getOperand(0) == &getStepInst() ||
273 LatchCmpInst->getOperand(1) == &getStepInst())
274 return Pred;
275
276 // Cannot flip strictness of NE and EQ
277 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
279
281 if (D == Direction::Increasing)
282 return ICmpInst::ICMP_SLT;
283
284 if (D == Direction::Decreasing)
285 return ICmpInst::ICMP_SGT;
286
287 // If cannot determine the direction, then unable to find the canonical
288 // predicate
290}
291
293 if (const SCEVAddRecExpr *StepAddRecExpr =
295 if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
296 if (SE.isKnownPositive(StepRecur))
297 return Direction::Increasing;
298 if (SE.isKnownNegative(StepRecur))
299 return Direction::Decreasing;
300 }
301
302 return Direction::Unknown;
303}
304
305std::optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
306 if (PHINode *IndVar = getInductionVariable(SE))
307 return LoopBounds::getBounds(*this, *IndVar, SE);
308
309 return std::nullopt;
310}
311
313 if (!isLoopSimplifyForm())
314 return nullptr;
315
316 BasicBlock *Header = getHeader();
317 assert(Header && "Expected a valid loop header");
319 if (!CmpInst)
320 return nullptr;
321
322 Value *LatchCmpOp0 = CmpInst->getOperand(0);
323 Value *LatchCmpOp1 = CmpInst->getOperand(1);
324
325 for (PHINode &IndVar : Header->phis()) {
326 InductionDescriptor IndDesc;
327 if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
328 continue;
329
330 BasicBlock *Latch = getLoopLatch();
331 Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
332
333 // case 1:
334 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
335 // StepInst = IndVar + step
336 // cmp = StepInst < FinalValue
337 if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
338 return &IndVar;
339
340 // case 2:
341 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
342 // StepInst = IndVar + step
343 // cmp = IndVar < FinalValue
344 if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
345 return &IndVar;
346 }
347
348 return nullptr;
349}
350
352 InductionDescriptor &IndDesc) const {
353 if (PHINode *IndVar = getInductionVariable(SE))
354 return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
355
356 return false;
357}
358
360 ScalarEvolution &SE) const {
361 // Located in the loop header
362 BasicBlock *Header = getHeader();
363 if (AuxIndVar.getParent() != Header)
364 return false;
365
366 // No uses outside of the loop
367 for (Instruction *I : AuxIndVar.users())
368 if (!contains(I))
369 return false;
370
371 InductionDescriptor IndDesc;
372 if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
373 return false;
374
375 // The step instruction opcode should be add or sub.
376 if (IndDesc.getInductionOpcode() != Instruction::Add &&
377 IndDesc.getInductionOpcode() != Instruction::Sub)
378 return false;
379
380 // Incremented by a loop invariant step for each loop iteration
381 return SE.isLoopInvariant(IndDesc.getStep(), this);
382}
383
385 if (!isLoopSimplifyForm())
386 return nullptr;
387
388 BasicBlock *Preheader = getLoopPreheader();
389 assert(Preheader && getLoopLatch() &&
390 "Expecting a loop with valid preheader and latch");
391
392 // Loop should be in rotate form.
393 if (!isRotatedForm())
394 return nullptr;
395
396 // Disallow loops with more than one unique exit block, as we do not verify
397 // that GuardOtherSucc post dominates all exit blocks.
398 BasicBlock *ExitFromLatch = getUniqueExitBlock();
399 if (!ExitFromLatch)
400 return nullptr;
401
402 BasicBlock *GuardBB = Preheader->getUniquePredecessor();
403 if (!GuardBB)
404 return nullptr;
405
406 CondBrInst *GuardBI = dyn_cast<CondBrInst>(GuardBB->getTerminator());
407 if (!GuardBI)
408 return nullptr;
409
410 BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
411 ? GuardBI->getSuccessor(1)
412 : GuardBI->getSuccessor(0);
413
414 // Check if ExitFromLatch (or any BasicBlock which is an empty unique
415 // successor of ExitFromLatch) is equal to GuardOtherSucc. If
416 // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
417 // loop is GuardBI (return GuardBI), otherwise return nullptr.
418 if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
419 /*CheckUniquePred=*/true) ==
420 GuardOtherSucc)
421 return GuardBI;
422 else
423 return nullptr;
424}
425
427 InductionDescriptor IndDesc;
428 if (!getInductionDescriptor(SE, IndDesc))
429 return false;
430
432 if (!Init || !Init->isZero())
433 return false;
434
435 if (IndDesc.getInductionOpcode() != Instruction::Add)
436 return false;
437
438 std::optional<APInt> Step = IndDesc.getConstStepValue();
439 if (!Step || !Step->isOne())
440 return false;
441
442 return true;
443}
444
445// Check whether the use \p U of a value defined in block \p BB (which is part
446// of loop \p L) does not require a live-out phi, i.e. whether it is contained
447// in the loop for LCSSA purposes.
448static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U,
449 const DominatorTree &DT) {
450 const Instruction *UI = cast<Instruction>(U.getUser());
451 const BasicBlock *UserBB = UI->getParent();
452
453 // For practical purposes, we consider that the use in a PHI
454 // occurs in the respective predecessor block. For more info,
455 // see the `phi` doc in LangRef and the LCSSA doc.
456 if (const PHINode *P = dyn_cast<PHINode>(UI))
457 UserBB = P->getIncomingBlock(U);
458
459 // Check the current block, as a fast-path, before checking whether
460 // the use is anywhere in the loop. Most values are used in the same
461 // block they are defined in. Also, blocks not reachable from the
462 // entry are special; uses in them don't need to go through PHIs.
463 if (UserBB != &BB && !L.contains(UserBB) && DT.isReachableFromEntry(UserBB))
464 return false;
465
466 return true;
467}
468
469// Check that 'BB' doesn't have any uses outside of the 'L'
470static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
471 const DominatorTree &DT, bool IgnoreTokens) {
472 for (const Instruction &I : BB) {
473 // Token-like values can't be used in PHI nodes and live-out token-like
474 // values prevent loop optimizations, so for the purposes of considered
475 // LCSSA form, we can ignore them.
476 if (IgnoreTokens && I.getType()->isTokenLikeTy())
477 continue;
478
479 for (const Use &U : I.uses()) {
480 if (!loopContainsUser(L, BB, U, DT))
481 return false;
482 }
483 }
484 return true;
485}
486
487bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
488 // For each block we check that it doesn't have any uses outside of this loop.
489 return all_of(this->blocks(), [&](const BasicBlock *BB) {
490 return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
491 });
492}
493
495 bool IgnoreTokens) const {
496 // For each block we check that it doesn't have any uses outside of its
497 // innermost loop. This process will transitively guarantee that the current
498 // loop and all of the nested loops are in LCSSA form.
499 return all_of(this->blocks(), [&](const BasicBlock *BB) {
500 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
501 });
502}
503
505 // Normal-form loops have a preheader, a single backedge, and all of their
506 // exits have all their predecessors inside the loop.
508}
509
510// Routines that reform the loop CFG and split edges often fail on indirectbr.
512 // Return false if any loop blocks contain indirectbrs, or there are any calls
513 // to noduplicate functions.
514 for (BasicBlock *BB : this->blocks()) {
515 if (isa<IndirectBrInst>(BB->getTerminator()))
516 return false;
517
518 for (Instruction &I : *BB)
519 if (auto *CB = dyn_cast<CallBase>(&I))
520 if (CB->cannotDuplicate())
521 return false;
522 }
523 return true;
524}
525
527 if (!isSafeToClone())
528 return false;
529
530 for (BasicBlock *BB : this->blocks()) {
531 for (Instruction &I : *BB) {
532 // Token-like values cannot be used in PHI nodes, so cloning is only
533 // possible if all their uses are contained in the loop. Uses within
534 // the loop (even across blocks) are fine: cloning only requires
535 // forming phis for values that are live-out of the loop.
536 if (I.getType()->isTokenLikeTy()) {
537 for (const Use &U : I.uses()) {
538 if (!loopContainsUser(*this, *BB, U, DT))
539 return false;
540 }
541 }
542 if (auto *CB = dyn_cast<CallBase>(&I)) {
543 assert(!CB->cannotDuplicate() && "Checked by isSafeToClone().");
544 if (CB->isConvergent())
545 return false;
546 }
547 }
548 }
549 return true;
550}
551
553 MDNode *LoopID = nullptr;
554
555 // Go through the latch blocks and check the terminator for the metadata.
556 SmallVector<BasicBlock *, 4> LatchesBlocks;
557 getLoopLatches(LatchesBlocks);
558 for (BasicBlock *BB : LatchesBlocks) {
559 Instruction *TI = BB->getTerminator();
560 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
561
562 if (!MD)
563 return nullptr;
564
565 if (!LoopID)
566 LoopID = MD;
567 else if (MD != LoopID)
568 return nullptr;
569 }
570 if (!LoopID || LoopID->getNumOperands() == 0 ||
571 LoopID->getOperand(0) != LoopID)
572 return nullptr;
573 return LoopID;
574}
575
576void Loop::setLoopID(MDNode *LoopID) const {
577 assert((!LoopID || LoopID->getNumOperands() > 0) &&
578 "Loop ID needs at least one operand");
579 assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
580 "Loop ID should refer to itself");
581
583 getLoopLatches(LoopLatches);
584 for (BasicBlock *BB : LoopLatches)
585 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
586}
587
589 addStringLoopAttribute("llvm.loop.unroll.disable", {"llvm.loop.unroll."});
590}
591
593 if (findOptionMDForLoop(this, "llvm.loop.mustprogress"))
594 return;
595 addStringLoopAttribute("llvm.loop.mustprogress");
596}
597
599 ArrayRef<StringRef> RemovePrefixes) const {
602 MDNode *LoopID = getLoopID();
603 MDNode *NewLoopID =
604 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
605 setLoopID(NewLoopID);
606}
607
609 ArrayRef<StringRef> RemovePrefixes) const {
611 MDNode *AttrMD = MDNode::get(
612 Context,
613 {MDString::get(Context, Name),
614 ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, Value)))});
615 MDNode *LoopID = getLoopID();
616 MDNode *NewLoopID =
617 makePostTransformationMetadata(Context, LoopID, RemovePrefixes, {AttrMD});
618 setLoopID(NewLoopID);
619}
620
622 MDNode *DesiredLoopIdMetadata = getLoopID();
623
624 if (!DesiredLoopIdMetadata)
625 return false;
626
627 MDNode *ParallelAccesses =
628 findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
630 ParallelAccessGroups; // For scalable 'contains' check.
631 if (ParallelAccesses) {
632 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
633 MDNode *AccGroup = cast<MDNode>(MD.get());
634 assert(isValidAsAccessGroup(AccGroup) &&
635 "List item must be an access group");
636 ParallelAccessGroups.insert(AccGroup);
637 }
638 }
639
640 // The loop branch contains the parallel loop metadata. In order to ensure
641 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
642 // dependencies (thus converted the loop back to a sequential loop), check
643 // that all the memory instructions in the loop belong to an access group that
644 // is parallel to this loop.
645 for (BasicBlock *BB : this->blocks()) {
646 for (Instruction &I : *BB) {
647 if (!I.mayReadOrWriteMemory())
648 continue;
649
650 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
651 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
652 if (AG->getNumOperands() == 0) {
653 assert(isValidAsAccessGroup(AG) && "Item must be an access group");
654 return ParallelAccessGroups.count(AG);
655 }
656
657 for (const MDOperand &AccessListItem : AG->operands()) {
658 MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
659 assert(isValidAsAccessGroup(AccGroup) &&
660 "List item must be an access group");
661 if (ParallelAccessGroups.count(AccGroup))
662 return true;
663 }
664 return false;
665 };
666
667 if (ContainsAccessGroup(AccessGroup))
668 continue;
669 }
670
671 // The memory instruction can refer to the loop identifier metadata
672 // directly or indirectly through another list metadata (in case of
673 // nested parallel loops). The loop identifier metadata refers to
674 // itself so we can check both cases with the same routine.
675 MDNode *LoopIdMD =
676 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
677
678 if (!LoopIdMD)
679 return false;
680
681 if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
682 return false;
683 }
684 }
685 return true;
686}
687
689
691 // If we have a debug location in the loop ID, then use it.
692 if (MDNode *LoopID = getLoopID()) {
693 DebugLoc Start;
694 // We use the first DebugLoc in the header as the start location of the loop
695 // and if there is a second DebugLoc in the header we use it as end location
696 // of the loop.
697 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
698 if (DILocation *L = dyn_cast<DILocation>(MDO)) {
699 if (!Start)
700 Start = DebugLoc(L);
701 else
702 return LocRange(Start, DebugLoc(L));
703 }
704 }
705
706 if (Start)
707 return LocRange(Start);
708 }
709
710 // Try the pre-header first.
711 if (BasicBlock *PHeadBB = getLoopPreheader())
712 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
713 return LocRange(DL);
714
715 // If we have no pre-header or there are no instructions with debug
716 // info in it, try the header.
717 if (BasicBlock *HeadBB = getHeader())
718 return LocRange(HeadBB->getTerminator()->getDebugLoc());
719
720 return LocRange();
721}
722
723std::string Loop::getLocStr() const {
724 std::string Result;
725 raw_string_ostream OS(Result);
726 if (const DebugLoc LoopDbgLoc = getStartLoc())
727 LoopDbgLoc.print(OS);
728 else
729 // Just print the module name.
731 return Result;
732}
733
734#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
736
738 print(dbgs(), /*Verbose=*/true);
739}
740#endif
741
742//===----------------------------------------------------------------------===//
743// UnloopUpdater implementation
744//
745
746namespace {
747/// Find the new parent loop for all blocks within the "unloop" whose last
748/// backedges has just been removed.
749class UnloopUpdater {
750 Loop &Unloop;
751 LoopInfo *LI;
752
753 LoopBlocksDFS DFS;
754
755 // Map unloop's immediate subloops to their nearest reachable parents. Nested
756 // loops within these subloops will not change parents. However, an immediate
757 // subloop's new parent will be the nearest loop reachable from either its own
758 // exits *or* any of its nested loop's exits.
759 DenseMap<Loop *, Loop *> SubloopParents;
760
761 // Flag the presence of an irreducible backedge whose destination is a block
762 // directly contained by the original unloop.
763 bool FoundIB = false;
764
765public:
766 UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
767
768 void updateBlockParents();
769
770 void removeBlocksFromAncestors();
771
772 void updateSubloopParents();
773
774protected:
775 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
776};
777} // end anonymous namespace
778
779/// Update the parent loop for all blocks that are directly contained within the
780/// original "unloop".
781void UnloopUpdater::updateBlockParents() {
782 if (Unloop.getNumBlocks()) {
783 // Perform a post order CFG traversal of all blocks within this loop,
784 // propagating the nearest loop from successors to predecessors.
785 LoopBlocksTraversal Traversal(DFS, LI);
786 for (BasicBlock *POI : Traversal) {
787
788 Loop *L = LI->getLoopFor(POI);
789 Loop *NL = getNearestLoop(POI, L);
790
791 if (NL != L) {
792 // For reducible loops, NL is now an ancestor of Unloop.
793 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
794 "uninitialized successor");
795 LI->changeLoopFor(POI, NL);
796 } else {
797 // Or the current block is part of a subloop, in which case its parent
798 // is unchanged.
799 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
800 }
801 }
802 }
803 // Each irreducible loop within the unloop induces a round of iteration using
804 // the DFS result cached by Traversal.
805 bool Changed = FoundIB;
806 for (unsigned NIters = 0; Changed; ++NIters) {
807 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
808 (void)NIters;
809
810 // Iterate over the postorder list of blocks, propagating the nearest loop
811 // from successors to predecessors as before.
812 Changed = false;
813 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
814 POE = DFS.endPostorder();
815 POI != POE; ++POI) {
816
817 Loop *L = LI->getLoopFor(*POI);
818 Loop *NL = getNearestLoop(*POI, L);
819 if (NL != L) {
820 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
821 "uninitialized successor");
822 LI->changeLoopFor(*POI, NL);
823 Changed = true;
824 }
825 }
826 }
827}
828
829/// Remove unloop's blocks from all ancestors below their new parents.
830void UnloopUpdater::removeBlocksFromAncestors() {
831 // Remove all unloop's blocks (including those in nested subloops) from
832 // ancestors below the new parent loop.
833 for (BasicBlock *BB : Unloop.blocks()) {
834 Loop *OuterParent = LI->getLoopFor(BB);
835 if (Unloop.contains(OuterParent)) {
836 while (OuterParent->getParentLoop() != &Unloop)
837 OuterParent = OuterParent->getParentLoop();
838 OuterParent = SubloopParents[OuterParent];
839 }
840 // Remove blocks from former Ancestors except Unloop itself which will be
841 // deleted.
842 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
843 OldParent = OldParent->getParentLoop()) {
844 assert(OldParent && "new loop is not an ancestor of the original");
845 OldParent->removeBlockFromLoop(BB);
846 }
847 }
848}
849
850/// Update the parent loop for all subloops directly nested within unloop.
851void UnloopUpdater::updateSubloopParents() {
852 while (!Unloop.isInnermost()) {
853 Loop *Subloop = *std::prev(Unloop.end());
854 Unloop.removeChildLoop(std::prev(Unloop.end()));
855
856 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
857 if (Loop *Parent = SubloopParents[Subloop])
858 Parent->addChildLoop(Subloop);
859 else
860 LI->addTopLevelLoop(Subloop);
861 }
862}
863
864/// Return the nearest parent loop among this block's successors. If a successor
865/// is a subloop header, consider its parent to be the nearest parent of the
866/// subloop's exits.
867///
868/// For subloop blocks, simply update SubloopParents and return NULL.
869Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
870
871 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
872 // is considered uninitialized.
873 Loop *NearLoop = BBLoop;
874
875 Loop *Subloop = nullptr;
876 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
877 Subloop = NearLoop;
878 // Find the subloop ancestor that is directly contained within Unloop.
879 while (Subloop->getParentLoop() != &Unloop) {
880 Subloop = Subloop->getParentLoop();
881 assert(Subloop && "subloop is not an ancestor of the original loop");
882 }
883 // Get the current nearest parent of the Subloop exits, initially Unloop.
884 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
885 }
886
887 if (succ_empty(BB)) {
888 assert(!Subloop && "subloop blocks must have a successor");
889 NearLoop = nullptr; // unloop blocks may now exit the function.
890 }
891 for (BasicBlock *Succ : successors(BB)) {
892 if (Succ == BB)
893 continue; // self loops are uninteresting
894
895 Loop *L = LI->getLoopFor(Succ);
896 if (L == &Unloop) {
897 // This successor has not been processed. This path must lead to an
898 // irreducible backedge.
899 assert((FoundIB || !DFS.hasPostorder(Succ)) && "should have seen IB");
900 FoundIB = true;
901 }
902 if (L != &Unloop && Unloop.contains(L)) {
903 // Successor is in a subloop.
904 if (Subloop)
905 continue; // Branching within subloops. Ignore it.
906
907 // BB branches from the original into a subloop header.
908 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
909
910 // Get the current nearest parent of the Subloop's exits.
911 L = SubloopParents[L];
912 // L could be Unloop if the only exit was an irreducible backedge.
913 }
914 if (L == &Unloop) {
915 continue;
916 }
917 // Handle critical edges from Unloop into a sibling loop.
918 if (L && !L->contains(&Unloop)) {
919 L = L->getParentLoop();
920 }
921 // Remember the nearest parent loop among successors or subloop exits.
922 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
923 NearLoop = L;
924 }
925 if (Subloop) {
926 SubloopParents[Subloop] = NearLoop;
927 return BBLoop;
928 }
929 return NearLoop;
930}
931
932LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
933
935 FunctionAnalysisManager::Invalidator &) {
936 // Check whether the analysis, all analyses on functions, or the function's
937 // CFG have been preserved.
938 auto PAC = PA.getChecker<LoopAnalysis>();
939 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
940 PAC.preservedSet<CFGAnalyses>());
941}
942
943void LoopInfo::erase(Loop *Unloop) {
944 assert(!Unloop->isInvalid() && "Loop has already been erased!");
945
946 llvm::scope_exit InvalidateOnExit([&]() { destroy(Unloop); });
947
948 // First handle the special case of no parent loop to simplify the algorithm.
949 if (Unloop->isOutermost()) {
950 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
951 for (BasicBlock *BB : Unloop->blocks()) {
952 // Don't reparent blocks in subloops.
953 if (getLoopFor(BB) != Unloop)
954 continue;
955
956 // Blocks no longer have a parent but are still referenced by Unloop until
957 // the Unloop object is deleted.
958 changeLoopFor(BB, nullptr);
959 }
960
961 // Remove the loop from the top-level LoopInfo object.
962 for (iterator I = begin();; ++I) {
963 assert(I != end() && "Couldn't find loop");
964 if (*I == Unloop) {
965 removeLoop(I);
966 break;
967 }
968 }
969
970 // Move all of the subloops to the top-level.
971 while (!Unloop->isInnermost())
972 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
973
974 return;
975 }
976
977 // Update the parent loop for all blocks within the loop. Blocks within
978 // subloops will not change parents.
979 UnloopUpdater Updater(Unloop, this);
980 Updater.updateBlockParents();
981
982 // Remove blocks from former ancestor loops.
983 Updater.removeBlocksFromAncestors();
984
985 // Add direct subloops as children in their new parent loop.
986 Updater.updateSubloopParents();
987
988 // Remove unloop from its parent loop.
989 Loop *ParentLoop = Unloop->getParentLoop();
990 for (Loop::iterator I = ParentLoop->begin();; ++I) {
991 assert(I != ParentLoop->end() && "Couldn't find loop");
992 if (*I == Unloop) {
993 ParentLoop->removeChildLoop(I);
994 break;
995 }
996 }
997}
998
1000 const Value *V, const BasicBlock *ExitBB) const {
1001 if (V->getType()->isTokenLikeTy())
1002 // We can't form PHIs of token-like type, so the definition of LCSSA
1003 // excludes values of that type.
1004 return false;
1005
1007 if (!I)
1008 return false;
1009 const Loop *L = getLoopFor(I->getParent());
1010 if (!L)
1011 return false;
1012 if (L->contains(ExitBB))
1013 // Could be an exit bb of a subloop and contained in defining loop
1014 return false;
1015
1016 // We found a (new) out-of-loop use location, for a value defined in-loop.
1017 // (Note that because of LCSSA, we don't have to account for values defined
1018 // in sibling loops. Such values will have LCSSA phis of their own in the
1019 // common parent loop.)
1020 return true;
1021}
1022
1023AnalysisKey LoopAnalysis::Key;
1024
1026 // FIXME: Currently we create a LoopInfo from scratch for every function.
1027 // This may prove to be too wasteful due to deallocating and re-allocating
1028 // memory each time for the underlying map and vector datastructures. At some
1029 // point it may prove worthwhile to use a freelist and recycle LoopInfo
1030 // objects. I don't want to add that kind of complexity until the scope of
1031 // the problem is better understood.
1032 LoopInfo LI;
1033 // The dominator tree is needed only for an irreducible CFG.
1034 LI.analyze(&F, [&]() -> const DominatorTree & {
1035 return AM.getResult<DominatorTreeAnalysis>(F);
1036 });
1037 return LI;
1038}
1039
1042 auto &LI = AM.getResult<LoopAnalysis>(F);
1043 OS << "Loop info for function '" << F.getName() << "':\n";
1044 LI.print(OS);
1045 return PreservedAnalyses::all();
1046}
1047
1049 const std::string &Banner) {
1050 if (forcePrintModuleIR()) {
1051 // handling -print-module-scope
1052 OS << Banner << " (loop: ";
1053 L.getHeader()->printAsOperand(OS, false);
1054 OS << ")\n";
1055
1056 // printing whole module
1057 OS << *L.getHeader()->getModule();
1058 return;
1059 }
1060
1061 if (forcePrintFuncIR()) {
1062 // handling -print-loop-func-scope.
1063 // -print-module-scope overrides this.
1064 OS << Banner << " (loop: ";
1065 L.getHeader()->printAsOperand(OS, false);
1066 OS << ")\n";
1067
1068 // printing whole function.
1069 OS << *L.getHeader()->getParent();
1070 return;
1071 }
1072
1073 OS << Banner;
1074
1075 auto *PreHeader = L.getLoopPreheader();
1076 if (PreHeader) {
1077 OS << "\n; Preheader:";
1078 PreHeader->print(OS);
1079 OS << "\n; Loop:";
1080 }
1081
1082 for (auto *Block : L.blocks())
1083 if (Block)
1084 Block->print(OS);
1085 else
1086 OS << "Printing <null> block";
1087
1089 L.getExitBlocks(ExitBlocks);
1090 if (!ExitBlocks.empty()) {
1091 OS << "\n; Exit blocks";
1092 for (auto *Block : ExitBlocks)
1093 if (Block)
1094 Block->print(OS);
1095 else
1096 OS << "Printing <null> block";
1097 }
1098}
1099
1101 // No loop metadata node, no loop properties.
1102 if (!LoopID)
1103 return nullptr;
1104
1105 // First operand should refer to the metadata node itself, for legacy reasons.
1106 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1107 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1108
1109 // Iterate over the metdata node operands and look for MDString metadata.
1110 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1111 MDNode *MD = dyn_cast<MDNode>(MDO);
1112 if (!MD || MD->getNumOperands() < 1)
1113 continue;
1115 if (!S)
1116 continue;
1117 // Return the operand node if MDString holds expected metadata.
1118 if (Name == S->getString())
1119 return MD;
1120 }
1121
1122 // Loop property not found.
1123 return nullptr;
1124}
1125
1127 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
1128}
1129
1130/// Find string metadata for loop
1131///
1132/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1133/// operand or null otherwise. If the string metadata is not found return
1134/// Optional's not-a-value.
1135std::optional<const MDOperand *>
1137 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1138 if (!MD)
1139 return std::nullopt;
1140 switch (MD->getNumOperands()) {
1141 case 1:
1142 return nullptr;
1143 case 2:
1144 return &MD->getOperand(1);
1145 default:
1146 llvm_unreachable("loop metadata has 0 or 1 operand");
1147 }
1148}
1149
1150std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1151 StringRef Name) {
1152 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1153 if (!MD)
1154 return std::nullopt;
1155 switch (MD->getNumOperands()) {
1156 case 1:
1157 // When the value is absent it is interpreted as 'attribute set'.
1158 return true;
1159 case 2:
1160 if (ConstantInt *IntMD =
1162 return IntMD->getZExtValue();
1163 return true;
1164 }
1165 llvm_unreachable("unexpected number of options");
1166}
1167
1169 return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
1170}
1171
1172std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1173 StringRef Name) {
1174 const MDOperand *AttrMD =
1175 findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
1176 if (!AttrMD)
1177 return std::nullopt;
1178
1179 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1180 if (!IntMD)
1181 return std::nullopt;
1182
1183 return IntMD->getSExtValue();
1184}
1185
1187 int Default) {
1188 return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
1189}
1190
1192 BasicBlock *H = TheLoop->getHeader();
1193 for (Instruction &II : *H) {
1194 if (auto *CB = dyn_cast<CallBase>(&II)) {
1195 if (!CB->isConvergent())
1196 continue;
1197 // This is the heart if it uses a token defined outside the loop. The
1198 // verifier has already checked that only the loop intrinsic can use such
1199 // a token.
1200 if (auto *Token = CB->getConvergenceControlToken()) {
1201 auto *TokenDef = cast<Instruction>(Token);
1202 if (!TheLoop->contains(TokenDef->getParent()))
1203 return CB;
1204 }
1205 return nullptr;
1206 }
1207 }
1208 return nullptr;
1209}
1210
1211bool llvm::isFinite(const Loop *L) {
1212 return L->getHeader()->getParent()->willReturn();
1213}
1214
1216 // An assumption on L covers every cycle inside it.
1217 if (SE.loopIsFiniteByAssumption(L))
1218 return true;
1219
1220 // An irreducible cycle has no Loop to prove finite.
1221 LoopBlocksRPO RPOT(L);
1222 RPOT.perform(&LI);
1224 return false;
1225
1226 // Likewise, a sub-loop that is finite by assumption covers its own sub-loops.
1228 return false;
1229 SmallVector<Loop *, 8> WorkList(L->begin(), L->end());
1230 while (!WorkList.empty()) {
1231 Loop *Current = WorkList.pop_back_val();
1232 if (SE.loopIsFiniteByAssumption(Current))
1233 continue;
1235 return false;
1236 WorkList.append(Current->begin(), Current->end());
1237 }
1238
1239 return true;
1240}
1241
1242static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1243
1247
1249 return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1250}
1251
1253 return Node->getNumOperands() == 0 && Node->isDistinct();
1254}
1255
1257 MDNode *OrigLoopID,
1258 ArrayRef<StringRef> RemovePrefixes,
1259 ArrayRef<MDNode *> AddAttrs) {
1260 // First remove any existing loop metadata related to this transformation.
1262
1263 // Reserve first location for self reference to the LoopID metadata node.
1264 MDs.push_back(nullptr);
1265
1266 // Remove metadata for the transformation that has been applied or that became
1267 // outdated.
1268 if (OrigLoopID) {
1269 for (const MDOperand &MDO : llvm::drop_begin(OrigLoopID->operands())) {
1270 bool IsVectorMetadata = false;
1271 Metadata *Op = MDO;
1272 if (MDNode *MD = dyn_cast<MDNode>(Op)) {
1273 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1274 if (S)
1275 IsVectorMetadata =
1276 llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
1277 return S->getString().starts_with(Prefix);
1278 });
1279 }
1280 if (!IsVectorMetadata)
1281 MDs.push_back(Op);
1282 }
1283 }
1284
1285 // Add metadata to avoid reapplying a transformation, such as
1286 // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1287 MDs.append(AddAttrs.begin(), AddAttrs.end());
1288
1289 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1290 // Replace the temporary node with a self-reference.
1291 NewLoopID->replaceOperandWith(0, NewLoopID);
1292 return NewLoopID;
1293}
1294
1295//===----------------------------------------------------------------------===//
1296// LoopInfo implementation
1297//
1298
1300
1302INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1303 true, true)
1305INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1307
1309 releaseMemory();
1311 return false;
1312}
1313
1315 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1316 // function each time verifyAnalysis is called is very expensive. The
1317 // -verify-loop-info option can enable this. In order to perform some
1318 // checking by default, LoopPass has been taught to call verifyLoop manually
1319 // during loop pass sequences.
1320 if (VerifyLoopInfo)
1321 LI.verify();
1322}
1323
1328
1330 LI.print(OS);
1331}
1332
1339
1340//===----------------------------------------------------------------------===//
1341// LoopBlocksDFS implementation
1342//
1343
1344/// Traverse the loop blocks and store the DFS result.
1345/// Useful for clients that just want the final DFS result and don't need to
1346/// visit blocks during the initial traversal.
1348 LoopBlocksTraversal Traversal(*this, LI);
1349 for ([[maybe_unused]] BasicBlock *BB : Traversal)
1350 ;
1351}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:213
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB, const DominatorTree &DT, bool IgnoreTokens)
Definition LoopInfo.cpp:470
static bool loopContainsUser(const Loop &L, const BasicBlock &BB, const Use &U, const DominatorTree &DT)
Definition LoopInfo.cpp:448
static const char * LLVMLoopMustProgress
static Value * findFinalIVValue(const Loop &L, const PHINode &IndVar, const Instruction &StepInst)
Return the final value of the loop induction variable if found.
Definition LoopInfo.cpp:203
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:249
static cl::opt< bool, true > VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), cl::Hidden, cl::desc("Verify loop info (time consuming)"))
This file defines the interface for the loop nest analysis.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains the declarations for profiling metadata utility functions.
static DominatorTree getDomTree(Function &F)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
Class for arbitrary precision integers.
Definition APInt.h:78
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
Definition InstrTypes.h:956
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
This is the shared class of boolean and integer constants.
Definition Constants.h:87
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
A debug info location.
Definition DebugLoc.h:126
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
FunctionPass(char &pid)
Definition Pass.h:314
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
A struct for saving information about induction variables.
BinaryOperator * getInductionBinOp() const
LLVM_ABI std::optional< APInt > getConstStepValue() const
const SCEV * getStep() const
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
Instruction::BinaryOps getInductionOpcode() const
Returns binary opcode of the induction operator.
Value * getStartValue() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM)
Instances of this class are used to represent loops that are detected in the flow graph.
bool contains(const Loop *L) const
typename std::vector< Loop * >::const_iterator iterator
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void getLoopLatches(SmallVectorImpl< BasicBlock * > &LoopLatches) const
void print(raw_ostream &OS, bool Verbose=false, bool PrintNested=true, unsigned Depth=0) const
iterator_range< block_iterator > blocks() const
bool isInvalid() const
Return true if this loop is no longer valid.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
Store the result of a depth first search within basic blocks contained by a single loop.
friend class LoopBlocksTraversal
std::vector< BasicBlock * >::const_iterator POIterator
Postorder list iterators.
LLVM_ABI void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
This class builds and contains all of the top-level loop structures in the specified function.
typename std::vector< Loop * >::const_iterator iterator
void analyze(ParentT F)
Create the loop forest for a function.
Loop * getLoopFor(const BasicBlock *BB) const
void changeLoopFor(const BasicBlock *BB, Loop *L)
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition LoopInfo.h:639
bool runOnFunction(Function &F) override
Calculate the natural loop information for a given function.
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
void print(raw_ostream &O, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
LoopInfo()=default
LLVM_ABI bool wouldBeOutOfLoopUseRequiringLCSSA(const Value *V, const BasicBlock *ExitBB) const
Definition LoopInfo.cpp:999
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
Definition LoopInfo.cpp:934
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:943
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A range representing the start and end location of a loop.
Definition LoopInfo.h:43
const DebugLoc & getStart() const
Definition LoopInfo.h:53
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI bool isCanonical(ScalarEvolution &SE) const
Return true if the loop induction variable starts at zero and increments by one each time through the...
Definition LoopInfo.cpp:426
LLVM_ABI bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition LoopInfo.cpp:487
LLVM_ABI std::optional< LoopBounds > getBounds(ScalarEvolution &SE) const
Return the struct LoopBounds collected if all struct members are found, else std::nullopt.
Definition LoopInfo.cpp:305
LLVM_ABI bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
Definition LoopInfo.cpp:511
LLVM_ABI std::string getLocStr() const
Return a string containing the debug location of the loop (file name + line number if present,...
Definition LoopInfo.cpp:723
LLVM_ABI void dumpVerbose() const
Definition LoopInfo.cpp:737
LLVM_ABI bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition LoopInfo.cpp:70
LLVM_ABI bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Definition LoopInfo.cpp:621
LLVM_ABI DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:688
LLVM_ABI void dump() const
Definition LoopInfo.cpp:735
LLVM_ABI LocRange getLocRange() const
Return the source code span of the loop.
Definition LoopInfo.cpp:690
LLVM_ABI bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:64
LLVM_ABI ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
Definition LoopInfo.cpp:194
LLVM_ABI bool isSafeToCloneConditionally(const DominatorTree &DT) const
Like isSafeToClone, but for transformations where the cloned loop bodies may run conditionally.
Definition LoopInfo.cpp:526
LLVM_ABI bool getInductionDescriptor(ScalarEvolution &SE, InductionDescriptor &IndDesc) const
Get the loop induction descriptor for the loop induction variable.
Definition LoopInfo.cpp:351
LLVM_ABI CondBrInst * getLoopGuardBranch() const
Return the loop guard branch, if it exists.
Definition LoopInfo.cpp:384
LLVM_ABI void addIntLoopAttribute(StringRef Name, unsigned Value, ArrayRef< StringRef > RemovePrefixes={}) const
Add an integer metadata attribute to this loop's loop-ID node.
Definition LoopInfo.cpp:608
bool isRotatedForm() const
Return true if the loop is in rotated form.
Definition LoopInfo.h:303
LLVM_ABI void setLoopMustProgress()
Add llvm.loop.mustprogress to this loop's loop id metadata.
Definition LoopInfo.cpp:592
LLVM_ABI PHINode * getInductionVariable(ScalarEvolution &SE) const
Return the loop induction variable if found, else return nullptr.
Definition LoopInfo.cpp:312
LLVM_ABI bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
Definition LoopInfo.cpp:504
LLVM_ABI void addStringLoopAttribute(StringRef Name, ArrayRef< StringRef > RemovePrefixes={}) const
Add a string-only metadata attribute to this loop's loop-ID node.
Definition LoopInfo.cpp:598
LLVM_ABI bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI, bool IgnoreTokens=true) const
Return true if this Loop and all inner subloops are in LCSSA form.
Definition LoopInfo.cpp:494
LLVM_ABI void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:576
LLVM_ABI void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
Definition LoopInfo.cpp:588
LLVM_ABI bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr, MemorySSAUpdater *MSSAU=nullptr, ScalarEvolution *SE=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
Definition LoopInfo.cpp:74
LLVM_ABI PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition LoopInfo.cpp:170
LLVM_ABI bool getIncomingAndBackEdge(BasicBlock *&Incoming, BasicBlock *&Backedge) const
Obtain the unique incoming and back edge.
Definition LoopInfo.cpp:144
LLVM_ABI MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:552
LLVM_ABI bool isAuxiliaryInductionVariable(PHINode &AuxIndVar, ScalarEvolution &SE) const
Return true if the given PHINode AuxIndVar is.
Definition LoopInfo.cpp:359
Metadata node.
Definition Metadata.h:1087
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1596
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
Metadata * get() const
Definition Metadata.h:937
A single uniqued string.
Definition Metadata.h:734
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:710
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:299
Value * getIncomingValueForBlock(const BasicBlock *BB) const
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
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
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
This node represents a polynomial recurrence on the trip count of the specified loop.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LocationClass< Ty > location(Ty &L)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:695
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:316
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI bool forcePrintModuleIR()
LLVM_ABI std::optional< bool > getOptionalBoolLoopAttribute(const Loop *TheLoop, StringRef Name)
LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name, int Default=0)
Find named metadata for a loop with an integer value.
auto pred_end(const MachineBasicBlock *BB)
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
auto successors(const MachineBasicBlock *BB)
LLVM_ABI MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI bool hasMustProgress(const Loop *L)
Look for the loop attribute that requires progress within the loop.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition CFG.h:154
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:54
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isLoopNestFinite(Loop *L, ScalarEvolution &SE, const LoopInfo &LI)
Return true if every cycle in the loop nest rooted at L is finite.
LLVM_ABI std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode * > AddAttrs)
Create a new LoopID after the loop has been transformed.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
LLVM_ABI bool forcePrintFuncIR()
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static LLVM_ABI std::optional< Loop::LoopBounds > getBounds(const Loop &L, PHINode &IndVar, ScalarEvolution &SE)
Return the LoopBounds object if.
Definition LoopInfo.cpp:221
Direction
An enum for the direction of the loop.
Definition LoopInfo.h:216
Value & getFinalIVValue() const
Get the final value of the loop induction variable.
Definition LoopInfo.h:175
Instruction & getStepInst() const
Get the instruction that updates the loop induction variable.
Definition LoopInfo.h:168
LLVM_ABI ICmpInst::Predicate getCanonicalPredicate() const
Return the canonical predicate for the latch compare instruction, if able to be calcuated.
Definition LoopInfo.cpp:251
LLVM_ABI Direction getDirection() const
Get the direction of the loop.
Definition LoopInfo.cpp:292