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