LLVM 22.0.0git
LoopInfo.h
Go to the documentation of this file.
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
18#include "llvm/IR/PassManager.h"
19#include "llvm/Pass.h"
22#include <optional>
23#include <utility>
24
25namespace llvm {
26
27class DominatorTree;
29class LoopInfo;
30class Loop;
32class ScalarEvolution;
33class raw_ostream;
34
35// Implementation in Support/GenericLoopInfoImpl.h
37
38/// Represents a single loop in the control flow graph. Note that not all SCCs
39/// in the CFG are necessarily loops.
40class LLVM_ABI Loop : public LoopBase<BasicBlock, Loop> {
41public:
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;
49 LocRange(DebugLoc Start) : Start(Start), End(Start) {}
51 : Start(std::move(Start)), End(std::move(End)) {}
52
53 const DebugLoc &getStart() const { return Start; }
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.
165 Value &getInitialIVValue() const { return InitialIVValue; }
166
167 /// Get the instruction that updates the loop induction variable.
168 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.
172 Value *getStepValue() const { return StepValue; }
173
174 /// Get the final value of the loop induction variable.
175 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
217
218 /// Get the direction of the loop.
219 LLVM_ABI Direction getDirection() const;
220
221 private:
222 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.
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).
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
390 if (BasicBlock *Header = getHeader())
391 if (Header->hasName())
392 return Header->getName();
393 return "<unnamed loop>";
394 }
395
396private:
397 Loop() = default;
398
400 friend class LoopBase<BasicBlock, Loop>;
401 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
402 ~Loop() = default;
403};
404
405// Implementation in Support/GenericLoopInfoImpl.h
407
408class 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
416public:
417 LoopInfo() = default;
420
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.
442 // Preserving LCSSA form is only problematic if the replacing value is an
443 // instruction.
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.
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.
547LLVM_ABI extern bool VerifyLoopInfo;
548
549// Allow clients to walk the list of nested loops...
550template <> struct GraphTraits<const Loop *> {
551 typedef const Loop *NodeRef;
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
559template <> struct GraphTraits<Loop *> {
560 typedef Loop *NodeRef;
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.
578
579/// Printer pass for the \c LoopAnalysis results.
581 raw_ostream &OS;
582
583public:
584 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
586 static bool isRequired() { return true; }
587};
588
589/// Verifier pass for the \c LoopAnalysis results.
594
595/// The legacy pass manager's analysis pass to compute loop information.
597 LoopInfo LI;
598
599public:
600 static char ID; // Pass identification, replacement for typeid
601
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.
620LLVM_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.
625LLVM_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.
632LLVM_ABI MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
633
634LLVM_ABI std::optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
635 StringRef Name);
636
637/// Returns true if Name is applied to TheLoop and enabled.
638LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name);
639
640/// Find named metadata for a loop with an integer value.
641LLVM_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.
646LLVM_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.
654LLVM_ABI std::optional<const MDOperand *>
655findStringMetadataForLoop(const Loop *TheLoop, StringRef Name);
656
657/// Find the convergence heart of the loop.
658LLVM_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.
663LLVM_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)
667LLVM_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.
671LLVM_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.
680LLVM_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().
698makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID,
699 llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
701} // namespace llvm
702
703#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_TEMPLATE_ABI
Definition Compiler.h:214
static bool isCanonical(const MDString *S)
@ Default
static bool runOnFunction(Function &F, bool PostInlining)
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
This header defines various interfaces for pass management in LLVM.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:231
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
static bool Contains(directive::VersionRange V, int P)
Definition Spelling.cpp:18
Value * RHS
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:678
A debug info location.
Definition DebugLoc.h:124
Core dominator tree base class.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
FunctionPass(char &pid)
Definition Pass.h:316
This instruction compares its operands according to the predicate given to the constructor.
A struct for saving information about induction variables.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM)
Definition LoopInfo.cpp:969
Instances of this class are used to represent loops that are detected in the flow graph.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool isLoopExiting(const BasicBlock *BB) const
This class builds and contains all of the top-level loop structures in the specified function.
Loop * getLoopFor(const BasicBlock *BB) const
std::vector< Loop * >::const_iterator iterator
const LoopInfo & getLoopInfo() const
Definition LoopInfo.h:605
LoopInfo & getLoopInfo()
Definition LoopInfo.h:604
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition LoopInfo.h:612
LoopInfo()=default
LoopInfo & operator=(LoopInfo &&RHS)
Definition LoopInfo.h:422
LoopInfo(LoopInfo &&Arg)
Definition LoopInfo.h:421
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:441
LLVM_ABI LoopInfo(const DominatorTreeBase< BasicBlock, false > &DomTree)
bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc)
Checks if moving a specific instruction can break LCSSA in any loop.
Definition LoopInfo.h:467
static bool isRequired()
Definition LoopInfo.h:586
LoopPrinterPass(raw_ostream &OS)
Definition LoopInfo.h:584
LocRange(DebugLoc Start, DebugLoc End)
Definition LoopInfo.h:50
const DebugLoc & getStart() const
Definition LoopInfo.h:53
LocRange(DebugLoc Start)
Definition LoopInfo.h:49
const DebugLoc & getEnd() const
Definition LoopInfo.h:54
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isGuarded() const
Return true iff the loop is.
Definition LoopInfo.h:296
BranchInst * getLoopGuardBranch() const
Return the loop guard branch, if it exists.
Definition LoopInfo.cpp:368
StringRef getName() const
Definition LoopInfo.h:389
bool isRotatedForm() const
Return true if the loop is in rotated form.
Definition LoopInfo.h:303
Metadata node.
Definition Metadata.h:1077
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
The main scalar evolution driver.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:292
LLVM Value Representation.
Definition Value.h:75
iterator_range< use_iterator > uses()
Definition Value.h:380
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI std::optional< bool > getOptionalBoolLoopAttribute(const Loop *TheLoop, StringRef Name)
LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name, int Default=0)
Find named metadata for a loop with an integer value.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
LLVM_ABI std::optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
LLVM_ABI MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
LLVM_ABI bool hasMustProgress(const Loop *L)
Look for the loop attribute that requires progress within the loop.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2110
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:51
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ABI std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1849
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
LLVM_ABI llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode * > AddAttrs)
Create a new LoopID after the loop has been transformed.
template class LLVM_TEMPLATE_ABI LoopInfoBase< BasicBlock, Loop >
Definition LoopInfo.h:399
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI 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:989
LLVM_ABI MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition PassManager.h:93
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static NodeRef getEntryNode(Loop *L)
Definition LoopInfo.h:563
LoopInfo::iterator ChildIteratorType
Definition LoopInfo.h:561
static ChildIteratorType child_begin(NodeRef N)
Definition LoopInfo.h:564
static ChildIteratorType child_end(NodeRef N)
Definition LoopInfo.h:565
static ChildIteratorType child_begin(NodeRef N)
Definition LoopInfo.h:555
static ChildIteratorType child_end(NodeRef N)
Definition LoopInfo.h:556
static NodeRef getEntryNode(const Loop *L)
Definition LoopInfo.h:554
LoopInfo::iterator ChildIteratorType
Definition LoopInfo.h:552
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
Verifier pass for the LoopAnalysis results.
Definition LoopInfo.h:590
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static bool isRequired()
Definition LoopInfo.h:592
Below are some utilities to get the loop guard, loop bounds and induction variable,...
Definition LoopInfo.h:153
static LLVM_ABI std::optional< Loop::LoopBounds > getBounds(const Loop &L, PHINode &IndVar, ScalarEvolution &SE)
Return the LoopBounds object if.
Definition LoopInfo.cpp:203
Direction
An enum for the direction of the loop.
Definition LoopInfo.h:216
Value & getFinalIVValue() const
Get the final value of the loop induction variable.
Definition LoopInfo.h:175
Value * getStepValue() const
Get the step that the loop induction variable gets updated by in each loop iteration.
Definition LoopInfo.h:172
Instruction & getStepInst() const
Get the instruction that updates the loop induction variable.
Definition LoopInfo.h:168
Value & getInitialIVValue() const
Get the initial value of the loop induction variable.
Definition LoopInfo.h:165
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70