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