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