1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===// 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 declares a GenericLoopInfo instantiation for LLVM IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_ANALYSIS_LOOPINFO_H 14 #define LLVM_ANALYSIS_LOOPINFO_H 15 16 #include "llvm/ADT/GraphTraits.h" 17 #include "llvm/IR/Instructions.h" 18 #include "llvm/IR/PassManager.h" 19 #include "llvm/Pass.h" 20 #include "llvm/Support/Compiler.h" 21 #include "llvm/Support/GenericLoopInfoImpl.h" 22 #include <optional> 23 #include <utility> 24 25 namespace llvm { 26 27 class DominatorTree; 28 class InductionDescriptor; 29 class LoopInfo; 30 class Loop; 31 class MemorySSAUpdater; 32 class ScalarEvolution; 33 class raw_ostream; 34 35 // Implementation in Support/GenericLoopInfoImpl.h 36 extern template class LLVM_TEMPLATE_ABI LoopBase<BasicBlock, Loop>; 37 38 /// Represents a single loop in the control flow graph. Note that not all SCCs 39 /// in the CFG are necessarily loops. 40 class LLVM_ABI Loop : public LoopBase<BasicBlock, Loop> { 41 public: 42 /// A range representing the start and end location of a loop. 43 class LocRange { 44 DebugLoc Start; 45 DebugLoc End; 46 47 public: 48 LocRange() = default; LocRange(DebugLoc Start)49 LocRange(DebugLoc Start) : Start(Start), End(Start) {} LocRange(DebugLoc Start,DebugLoc End)50 LocRange(DebugLoc Start, DebugLoc End) 51 : Start(std::move(Start)), End(std::move(End)) {} 52 getStart()53 const DebugLoc &getStart() const { return Start; } getEnd()54 const DebugLoc &getEnd() const { return End; } 55 56 /// Check for null. 57 /// 58 explicit operator bool() const { return Start && End; } 59 }; 60 61 /// Return true if the specified value is loop invariant. 62 bool isLoopInvariant(const Value *V) const; 63 64 /// Return true if all the operands of the specified instruction are loop 65 /// invariant. 66 bool hasLoopInvariantOperands(const Instruction *I) const; 67 68 /// If the given value is an instruction inside of the loop and it can be 69 /// hoisted, do so to make it trivially loop-invariant. 70 /// Return true if \c V is already loop-invariant, and false if \c V can't 71 /// be made loop-invariant. If \c V is made loop-invariant, \c Changed is 72 /// set to true. This function can be used as a slightly more aggressive 73 /// replacement for isLoopInvariant. 74 /// 75 /// If InsertPt is specified, it is the point to hoist instructions to. 76 /// If null, the terminator of the loop preheader is used. 77 /// 78 bool makeLoopInvariant(Value *V, bool &Changed, 79 Instruction *InsertPt = nullptr, 80 MemorySSAUpdater *MSSAU = nullptr, 81 ScalarEvolution *SE = nullptr) const; 82 83 /// If the given instruction is inside of the loop and it can be hoisted, do 84 /// so to make it trivially loop-invariant. 85 /// Return true if \c I is already loop-invariant, and false if \c I can't 86 /// be made loop-invariant. If \c I is made loop-invariant, \c Changed is 87 /// set to true. This function can be used as a slightly more aggressive 88 /// replacement for isLoopInvariant. 89 /// 90 /// If InsertPt is specified, it is the point to hoist instructions to. 91 /// If null, the terminator of the loop preheader is used. 92 /// 93 bool makeLoopInvariant(Instruction *I, bool &Changed, 94 Instruction *InsertPt = nullptr, 95 MemorySSAUpdater *MSSAU = nullptr, 96 ScalarEvolution *SE = nullptr) const; 97 98 /// Check to see if the loop has a canonical induction variable: an integer 99 /// recurrence that starts at 0 and increments by one each time through the 100 /// loop. If so, return the phi node that corresponds to it. 101 /// 102 /// The IndVarSimplify pass transforms loops to have a canonical induction 103 /// variable. 104 /// 105 PHINode *getCanonicalInductionVariable() const; 106 107 /// Get the latch condition instruction. 108 ICmpInst *getLatchCmpInst() const; 109 110 /// Obtain the unique incoming and back edge. Return false if they are 111 /// non-unique or the loop is dead; otherwise, return true. 112 bool getIncomingAndBackEdge(BasicBlock *&Incoming, 113 BasicBlock *&Backedge) const; 114 115 /// Below are some utilities to get the loop guard, loop bounds and induction 116 /// variable, and to check if a given phinode is an auxiliary induction 117 /// variable, if the loop is guarded, and if the loop is canonical. 118 /// 119 /// Here is an example: 120 /// \code 121 /// for (int i = lb; i < ub; i+=step) 122 /// <loop body> 123 /// --- pseudo LLVMIR --- 124 /// beforeloop: 125 /// guardcmp = (lb < ub) 126 /// if (guardcmp) goto preheader; else goto afterloop 127 /// preheader: 128 /// loop: 129 /// i_1 = phi[{lb, preheader}, {i_2, latch}] 130 /// <loop body> 131 /// i_2 = i_1 + step 132 /// latch: 133 /// cmp = (i_2 < ub) 134 /// if (cmp) goto loop 135 /// exit: 136 /// afterloop: 137 /// \endcode 138 /// 139 /// - getBounds 140 /// - getInitialIVValue --> lb 141 /// - getStepInst --> i_2 = i_1 + step 142 /// - getStepValue --> step 143 /// - getFinalIVValue --> ub 144 /// - getCanonicalPredicate --> '<' 145 /// - getDirection --> Increasing 146 /// 147 /// - getInductionVariable --> i_1 148 /// - isAuxiliaryInductionVariable(x) --> true if x == i_1 149 /// - getLoopGuardBranch() 150 /// --> `if (guardcmp) goto preheader; else goto afterloop` 151 /// - isGuarded() --> true 152 /// - isCanonical --> false 153 struct LoopBounds { 154 /// Return the LoopBounds object if 155 /// - the given \p IndVar is an induction variable 156 /// - the initial value of the induction variable can be found 157 /// - the step instruction of the induction variable can be found 158 /// - the final value of the induction variable can be found 159 /// 160 /// Else std::nullopt. 161 LLVM_ABI static std::optional<Loop::LoopBounds> 162 getBounds(const Loop &L, PHINode &IndVar, ScalarEvolution &SE); 163 164 /// Get the initial value of the loop induction variable. getInitialIVValueLoopBounds165 Value &getInitialIVValue() const { return InitialIVValue; } 166 167 /// Get the instruction that updates the loop induction variable. getStepInstLoopBounds168 Instruction &getStepInst() const { return StepInst; } 169 170 /// Get the step that the loop induction variable gets updated by in each 171 /// loop iteration. Return nullptr if not found. getStepValueLoopBounds172 Value *getStepValue() const { return StepValue; } 173 174 /// Get the final value of the loop induction variable. getFinalIVValueLoopBounds175 Value &getFinalIVValue() const { return FinalIVValue; } 176 177 /// Return the canonical predicate for the latch compare instruction, if 178 /// able to be calcuated. Else BAD_ICMP_PREDICATE. 179 /// 180 /// A predicate is considered as canonical if requirements below are all 181 /// satisfied: 182 /// 1. The first successor of the latch branch is the loop header 183 /// If not, inverse the predicate. 184 /// 2. One of the operands of the latch comparison is StepInst 185 /// If not, and 186 /// - if the current calcuated predicate is not ne or eq, flip the 187 /// predicate. 188 /// - else if the loop is increasing, return slt 189 /// (notice that it is safe to change from ne or eq to sign compare) 190 /// - else if the loop is decreasing, return sgt 191 /// (notice that it is safe to change from ne or eq to sign compare) 192 /// 193 /// Here is an example when both (1) and (2) are not satisfied: 194 /// \code 195 /// loop.header: 196 /// %iv = phi [%initialiv, %loop.preheader], [%inc, %loop.header] 197 /// %inc = add %iv, %step 198 /// %cmp = slt %iv, %finaliv 199 /// br %cmp, %loop.exit, %loop.header 200 /// loop.exit: 201 /// \endcode 202 /// - The second successor of the latch branch is the loop header instead 203 /// of the first successor (slt -> sge) 204 /// - The first operand of the latch comparison (%cmp) is the IndVar (%iv) 205 /// instead of the StepInst (%inc) (sge -> sgt) 206 /// 207 /// The predicate would be sgt if both (1) and (2) are satisfied. 208 /// getCanonicalPredicate() returns sgt for this example. 209 /// Note: The IR is not changed. 210 LLVM_ABI ICmpInst::Predicate getCanonicalPredicate() const; 211 212 /// An enum for the direction of the loop 213 /// - for (int i = 0; i < ub; ++i) --> Increasing 214 /// - for (int i = ub; i > 0; --i) --> Descresing 215 /// - for (int i = x; i != y; i+=z) --> Unknown 216 enum class Direction { Increasing, Decreasing, Unknown }; 217 218 /// Get the direction of the loop. 219 LLVM_ABI Direction getDirection() const; 220 221 private: LoopBoundsLoopBounds222 LoopBounds(const Loop &Loop, Value &I, Instruction &SI, Value *SV, Value &F, 223 ScalarEvolution &SE) 224 : L(Loop), InitialIVValue(I), StepInst(SI), StepValue(SV), 225 FinalIVValue(F), SE(SE) {} 226 227 const Loop &L; 228 229 // The initial value of the loop induction variable 230 Value &InitialIVValue; 231 232 // The instruction that updates the loop induction variable 233 Instruction &StepInst; 234 235 // The value that the loop induction variable gets updated by in each loop 236 // iteration 237 Value *StepValue; 238 239 // The final value of the loop induction variable 240 Value &FinalIVValue; 241 242 ScalarEvolution &SE; 243 }; 244 245 /// Return the struct LoopBounds collected if all struct members are found, 246 /// else std::nullopt. 247 std::optional<LoopBounds> getBounds(ScalarEvolution &SE) const; 248 249 /// Return the loop induction variable if found, else return nullptr. 250 /// An instruction is considered as the loop induction variable if 251 /// - it is an induction variable of the loop; and 252 /// - it is used to determine the condition of the branch in the loop latch 253 /// 254 /// Note: the induction variable doesn't need to be canonical, i.e. starts at 255 /// zero and increments by one each time through the loop (but it can be). 256 PHINode *getInductionVariable(ScalarEvolution &SE) const; 257 258 /// Get the loop induction descriptor for the loop induction variable. Return 259 /// true if the loop induction variable is found. 260 bool getInductionDescriptor(ScalarEvolution &SE, 261 InductionDescriptor &IndDesc) const; 262 263 /// Return true if the given PHINode \p AuxIndVar is 264 /// - in the loop header 265 /// - not used outside of the loop 266 /// - incremented by a loop invariant step for each loop iteration 267 /// - step instruction opcode should be add or sub 268 /// Note: auxiliary induction variable is not required to be used in the 269 /// conditional branch in the loop latch. (but it can be) 270 bool isAuxiliaryInductionVariable(PHINode &AuxIndVar, 271 ScalarEvolution &SE) const; 272 273 /// Return the loop guard branch, if it exists. 274 /// 275 /// This currently only works on simplified loop, as it requires a preheader 276 /// and a latch to identify the guard. It will work on loops of the form: 277 /// \code 278 /// GuardBB: 279 /// br cond1, Preheader, ExitSucc <== GuardBranch 280 /// Preheader: 281 /// br Header 282 /// Header: 283 /// ... 284 /// br Latch 285 /// Latch: 286 /// br cond2, Header, ExitBlock 287 /// ExitBlock: 288 /// br ExitSucc 289 /// ExitSucc: 290 /// \endcode 291 BranchInst *getLoopGuardBranch() const; 292 293 /// Return true iff the loop is 294 /// - in simplify rotated form, and 295 /// - guarded by a loop guard branch. isGuarded()296 bool isGuarded() const { return (getLoopGuardBranch() != nullptr); } 297 298 /// Return true if the loop is in rotated form. 299 /// 300 /// This does not check if the loop was rotated by loop rotation, instead it 301 /// only checks if the loop is in rotated form (has a valid latch that exists 302 /// the loop). isRotatedForm()303 bool isRotatedForm() const { 304 assert(!isInvalid() && "Loop not in a valid state!"); 305 BasicBlock *Latch = getLoopLatch(); 306 return Latch && isLoopExiting(Latch); 307 } 308 309 /// Return true if the loop induction variable starts at zero and increments 310 /// by one each time through the loop. 311 bool isCanonical(ScalarEvolution &SE) const; 312 313 /// Return true if the Loop is in LCSSA form. If \p IgnoreTokens is set to 314 /// true, token values defined inside loop are allowed to violate LCSSA form. 315 bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens = true) const; 316 317 /// Return true if this Loop and all inner subloops are in LCSSA form. If \p 318 /// IgnoreTokens is set to true, token values defined inside loop are allowed 319 /// to violate LCSSA form. 320 bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI, 321 bool IgnoreTokens = true) const; 322 323 /// Return true if the Loop is in the form that the LoopSimplify form 324 /// transforms loops to, which is sometimes called normal form. 325 bool isLoopSimplifyForm() const; 326 327 /// Return true if the loop body is safe to clone in practice. 328 bool isSafeToClone() const; 329 330 /// Returns true if the loop is annotated parallel. 331 /// 332 /// A parallel loop can be assumed to not contain any dependencies between 333 /// iterations by the compiler. That is, any loop-carried dependency checking 334 /// can be skipped completely when parallelizing the loop on the target 335 /// machine. Thus, if the parallel loop information originates from the 336 /// programmer, e.g. via the OpenMP parallel for pragma, it is the 337 /// programmer's responsibility to ensure there are no loop-carried 338 /// dependencies. The final execution order of the instructions across 339 /// iterations is not guaranteed, thus, the end result might or might not 340 /// implement actual concurrent execution of instructions across multiple 341 /// iterations. 342 bool isAnnotatedParallel() const; 343 344 /// Return the llvm.loop loop id metadata node for this loop if it is present. 345 /// 346 /// If this loop contains the same llvm.loop metadata on each branch to the 347 /// header then the node is returned. If any latch instruction does not 348 /// contain llvm.loop or if multiple latches contain different nodes then 349 /// 0 is returned. 350 MDNode *getLoopID() const; 351 /// Set the llvm.loop loop id metadata for this loop. 352 /// 353 /// The LoopID metadata node will be added to each terminator instruction in 354 /// the loop that branches to the loop header. 355 /// 356 /// The LoopID metadata node should have one or more operands and the first 357 /// operand should be the node itself. 358 void setLoopID(MDNode *LoopID) const; 359 360 /// Add llvm.loop.unroll.disable to this loop's loop id metadata. 361 /// 362 /// Remove existing unroll metadata and add unroll disable metadata to 363 /// indicate the loop has already been unrolled. This prevents a loop 364 /// from being unrolled more than is directed by a pragma if the loop 365 /// unrolling pass is run more than once (which it generally is). 366 void setLoopAlreadyUnrolled(); 367 368 /// Add llvm.loop.mustprogress to this loop's loop id metadata. 369 void setLoopMustProgress(); 370 371 void dump() const; 372 void dumpVerbose() const; 373 374 /// Return the debug location of the start of this loop. 375 /// This looks for a BB terminating instruction with a known debug 376 /// location by looking at the preheader and header blocks. If it 377 /// cannot find a terminating instruction with location information, 378 /// it returns an unknown location. 379 DebugLoc getStartLoc() const; 380 381 /// Return the source code span of the loop. 382 LocRange getLocRange() const; 383 384 /// Return a string containing the debug location of the loop (file name + 385 /// line number if present, otherwise module name). Meant to be used for debug 386 /// printing within LLVM_DEBUG. 387 std::string getLocStr() const; 388 getName()389 StringRef getName() const { 390 if (BasicBlock *Header = getHeader()) 391 if (Header->hasName()) 392 return Header->getName(); 393 return "<unnamed loop>"; 394 } 395 396 private: 397 Loop() = default; 398 399 friend class LoopInfoBase<BasicBlock, Loop>; 400 friend class LoopBase<BasicBlock, Loop>; Loop(BasicBlock * BB)401 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {} 402 ~Loop() = default; 403 }; 404 405 // Implementation in Support/GenericLoopInfoImpl.h 406 extern template class LLVM_TEMPLATE_ABI LoopInfoBase<BasicBlock, Loop>; 407 408 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> { 409 typedef LoopInfoBase<BasicBlock, Loop> BaseT; 410 411 friend class LoopBase<BasicBlock, Loop>; 412 413 void operator=(const LoopInfo &) = delete; 414 LoopInfo(const LoopInfo &) = delete; 415 416 public: 417 LoopInfo() = default; 418 LLVM_ABI explicit LoopInfo( 419 const DominatorTreeBase<BasicBlock, false> &DomTree); 420 LoopInfo(LoopInfo && Arg)421 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {} 422 LoopInfo &operator=(LoopInfo &&RHS) { 423 BaseT::operator=(std::move(static_cast<BaseT &>(RHS))); 424 return *this; 425 } 426 427 /// Handle invalidation explicitly. 428 LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, 429 FunctionAnalysisManager::Invalidator &); 430 431 // Most of the public interface is provided via LoopInfoBase. 432 433 /// Update LoopInfo after removing the last backedge from a loop. This updates 434 /// the loop forest and parent loops for each block so that \c L is no longer 435 /// referenced, but does not actually delete \c L immediately. The pointer 436 /// will remain valid until this LoopInfo's memory is released. 437 LLVM_ABI void erase(Loop *L); 438 439 /// Returns true if replacing From with To everywhere is guaranteed to 440 /// preserve LCSSA form. replacementPreservesLCSSAForm(Instruction * From,Value * To)441 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) { 442 // Preserving LCSSA form is only problematic if the replacing value is an 443 // instruction. 444 Instruction *I = dyn_cast<Instruction>(To); 445 if (!I) 446 return true; 447 // If both instructions are defined in the same basic block then replacement 448 // cannot break LCSSA form. 449 if (I->getParent() == From->getParent()) 450 return true; 451 // If the instruction is not defined in a loop then it can safely replace 452 // anything. 453 Loop *ToLoop = getLoopFor(I->getParent()); 454 if (!ToLoop) 455 return true; 456 // If the replacing instruction is defined in the same loop as the original 457 // instruction, or in a loop that contains it as an inner loop, then using 458 // it as a replacement will not break LCSSA form. 459 return ToLoop->contains(getLoopFor(From->getParent())); 460 } 461 462 /// Checks if moving a specific instruction can break LCSSA in any loop. 463 /// 464 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA, 465 /// assuming that the function containing \p Inst and \p NewLoc is currently 466 /// in LCSSA form. movementPreservesLCSSAForm(Instruction * Inst,Instruction * NewLoc)467 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) { 468 assert(Inst->getFunction() == NewLoc->getFunction() && 469 "Can't reason about IPO!"); 470 471 auto *OldBB = Inst->getParent(); 472 auto *NewBB = NewLoc->getParent(); 473 474 // Movement within the same loop does not break LCSSA (the equality check is 475 // to avoid doing a hashtable lookup in case of intra-block movement). 476 if (OldBB == NewBB) 477 return true; 478 479 auto *OldLoop = getLoopFor(OldBB); 480 auto *NewLoop = getLoopFor(NewBB); 481 482 if (OldLoop == NewLoop) 483 return true; 484 485 // Check if Outer contains Inner; with the null loop counting as the 486 // "outermost" loop. 487 auto Contains = [](const Loop *Outer, const Loop *Inner) { 488 return !Outer || Outer->contains(Inner); 489 }; 490 491 // To check that the movement of Inst to before NewLoc does not break LCSSA, 492 // we need to check two sets of uses for possible LCSSA violations at 493 // NewLoc: the users of NewInst, and the operands of NewInst. 494 495 // If we know we're hoisting Inst out of an inner loop to an outer loop, 496 // then the uses *of* Inst don't need to be checked. 497 498 if (!Contains(NewLoop, OldLoop)) { 499 for (Use &U : Inst->uses()) { 500 auto *UI = cast<Instruction>(U.getUser()); 501 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U) 502 : UI->getParent(); 503 if (UBB != NewBB && getLoopFor(UBB) != NewLoop) 504 return false; 505 } 506 } 507 508 // If we know we're sinking Inst from an outer loop into an inner loop, then 509 // the *operands* of Inst don't need to be checked. 510 511 if (!Contains(OldLoop, NewLoop)) { 512 // See below on why we can't handle phi nodes here. 513 if (isa<PHINode>(Inst)) 514 return false; 515 516 for (Use &U : Inst->operands()) { 517 auto *DefI = dyn_cast<Instruction>(U.get()); 518 if (!DefI) 519 return false; 520 521 // This would need adjustment if we allow Inst to be a phi node -- the 522 // new use block won't simply be NewBB. 523 524 auto *DefBlock = DefI->getParent(); 525 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop) 526 return false; 527 } 528 } 529 530 return true; 531 } 532 533 // Return true if a new use of V added in ExitBB would require an LCSSA PHI 534 // to be inserted at the beginning of the block. Note that V is assumed to 535 // dominate ExitBB, and ExitBB must be the exit block of some loop. The 536 // IR is assumed to be in LCSSA form before the planned insertion. 537 LLVM_ABI bool 538 wouldBeOutOfLoopUseRequiringLCSSA(const Value *V, 539 const BasicBlock *ExitBB) const; 540 }; 541 542 /// Enable verification of loop info. 543 /// 544 /// The flag enables checks which are expensive and are disabled by default 545 /// unless the `EXPENSIVE_CHECKS` macro is defined. The `-verify-loop-info` 546 /// flag allows the checks to be enabled selectively without re-compilation. 547 LLVM_ABI extern bool VerifyLoopInfo; 548 549 // Allow clients to walk the list of nested loops... 550 template <> struct GraphTraits<const Loop *> { 551 typedef const Loop *NodeRef; 552 typedef LoopInfo::iterator ChildIteratorType; 553 554 static NodeRef getEntryNode(const Loop *L) { return L; } 555 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); } 556 static ChildIteratorType child_end(NodeRef N) { return N->end(); } 557 }; 558 559 template <> struct GraphTraits<Loop *> { 560 typedef Loop *NodeRef; 561 typedef LoopInfo::iterator ChildIteratorType; 562 563 static NodeRef getEntryNode(Loop *L) { return L; } 564 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); } 565 static ChildIteratorType child_end(NodeRef N) { return N->end(); } 566 }; 567 568 /// Analysis pass that exposes the \c LoopInfo for a function. 569 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> { 570 friend AnalysisInfoMixin<LoopAnalysis>; 571 LLVM_ABI static AnalysisKey Key; 572 573 public: 574 typedef LoopInfo Result; 575 576 LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM); 577 }; 578 579 /// Printer pass for the \c LoopAnalysis results. 580 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> { 581 raw_ostream &OS; 582 583 public: 584 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {} 585 LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); 586 static bool isRequired() { return true; } 587 }; 588 589 /// Verifier pass for the \c LoopAnalysis results. 590 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> { 591 LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); 592 static bool isRequired() { return true; } 593 }; 594 595 /// The legacy pass manager's analysis pass to compute loop information. 596 class LLVM_ABI LoopInfoWrapperPass : public FunctionPass { 597 LoopInfo LI; 598 599 public: 600 static char ID; // Pass identification, replacement for typeid 601 602 LoopInfoWrapperPass(); 603 604 LoopInfo &getLoopInfo() { return LI; } 605 const LoopInfo &getLoopInfo() const { return LI; } 606 607 /// Calculate the natural loop information for a given function. 608 bool runOnFunction(Function &F) override; 609 610 void verifyAnalysis() const override; 611 612 void releaseMemory() override { LI.releaseMemory(); } 613 614 void print(raw_ostream &O, const Module *M = nullptr) const override; 615 616 void getAnalysisUsage(AnalysisUsage &AU) const override; 617 }; 618 619 /// Function to print a loop's contents as LLVM's text IR assembly. 620 LLVM_ABI void printLoop(Loop &L, raw_ostream &OS, 621 const std::string &Banner = ""); 622 623 /// Find and return the loop attribute node for the attribute @p Name in 624 /// @p LoopID. Return nullptr if there is no such attribute. 625 LLVM_ABI MDNode *findOptionMDForLoopID(MDNode *LoopID, StringRef Name); 626 627 /// Find string metadata for a loop. 628 /// 629 /// Returns the MDNode where the first operand is the metadata's name. The 630 /// following operands are the metadata's values. If no metadata with @p Name is 631 /// found, return nullptr. 632 LLVM_ABI MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name); 633 634 LLVM_ABI std::optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop, 635 StringRef Name); 636 637 /// Returns true if Name is applied to TheLoop and enabled. 638 LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name); 639 640 /// Find named metadata for a loop with an integer value. 641 LLVM_ABI std::optional<int> getOptionalIntLoopAttribute(const Loop *TheLoop, 642 StringRef Name); 643 644 /// Find named metadata for a loop with an integer value. Return \p Default if 645 /// not set. 646 LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name, 647 int Default = 0); 648 649 /// Find string metadata for loop 650 /// 651 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 652 /// operand or null otherwise. If the string metadata is not found return 653 /// Optional's not-a-value. 654 LLVM_ABI std::optional<const MDOperand *> 655 findStringMetadataForLoop(const Loop *TheLoop, StringRef Name); 656 657 /// Find the convergence heart of the loop. 658 LLVM_ABI CallBase *getLoopConvergenceHeart(const Loop *TheLoop); 659 660 /// Look for the loop attribute that requires progress within the loop. 661 /// Note: Most consumers probably want "isMustProgress" which checks 662 /// the containing function attribute too. 663 LLVM_ABI bool hasMustProgress(const Loop *L); 664 665 /// Return true if this loop can be assumed to make progress. (i.e. can't 666 /// be infinite without side effects without also being undefined) 667 LLVM_ABI bool isMustProgress(const Loop *L); 668 669 /// Return true if this loop can be assumed to run for a finite number of 670 /// iterations. 671 LLVM_ABI bool isFinite(const Loop *L); 672 673 /// Return whether an MDNode might represent an access group. 674 /// 675 /// Access group metadata nodes have to be distinct and empty. Being 676 /// always-empty ensures that it never needs to be changed (which -- because 677 /// MDNodes are designed immutable -- would require creating a new MDNode). Note 678 /// that this is not a sufficient condition: not every distinct and empty NDNode 679 /// is representing an access group. 680 LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup); 681 682 /// Create a new LoopID after the loop has been transformed. 683 /// 684 /// This can be used when no follow-up loop attributes are defined 685 /// (llvm::makeFollowupLoopID returning None) to stop transformations to be 686 /// applied again. 687 /// 688 /// @param Context The LLVMContext in which to create the new LoopID. 689 /// @param OrigLoopID The original LoopID; can be nullptr if the original 690 /// loop has no LoopID. 691 /// @param RemovePrefixes Remove all loop attributes that have these prefixes. 692 /// Use to remove metadata of the transformation that has 693 /// been applied. 694 /// @param AddAttrs Add these loop attributes to the new LoopID. 695 /// 696 /// @return A new LoopID that can be applied using Loop::setLoopID(). 697 LLVM_ABI llvm::MDNode * 698 makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, 699 llvm::ArrayRef<llvm::StringRef> RemovePrefixes, 700 llvm::ArrayRef<llvm::MDNode *> AddAttrs); 701 } // namespace llvm 702 703 #endif 704