LLVM 24.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 CondBrInst *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-like values defined inside loop are allowed to violate LCSSA
315 /// form.
316 bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens = true) const;
317
318 /// Return true if this Loop and all inner subloops are in LCSSA form. If \p
319 /// IgnoreTokens is set to true, token-like values defined inside loop are
320 /// allowed to violate LCSSA form.
321 bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
322 bool IgnoreTokens = true) const;
323
324 /// Return true if the Loop is in the form that the LoopSimplify form
325 /// transforms loops to, which is sometimes called normal form.
326 bool isLoopSimplifyForm() const;
327
328 /// Return true if the loop body is safe to clone in practice.
329 bool isSafeToClone() const;
330
331 /// Like `isSafeToClone`, but for transformations where the cloned loop
332 /// bodies may run conditionally. This additionally checks that we may form
333 /// phis for all values that are live-out from the loop (in particular that
334 /// no token-like values are live-out) and that there are no convergent calls
335 /// (which must not gain new control dependencies).
336 bool isSafeToCloneConditionally(const DominatorTree &DT) const;
337
338 /// Returns true if the loop is annotated parallel.
339 ///
340 /// A parallel loop can be assumed to not contain any dependencies between
341 /// iterations by the compiler. That is, any loop-carried dependency checking
342 /// can be skipped completely when parallelizing the loop on the target
343 /// machine. Thus, if the parallel loop information originates from the
344 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
345 /// programmer's responsibility to ensure there are no loop-carried
346 /// dependencies. The final execution order of the instructions across
347 /// iterations is not guaranteed, thus, the end result might or might not
348 /// implement actual concurrent execution of instructions across multiple
349 /// iterations.
350 bool isAnnotatedParallel() const;
351
352 /// Return the llvm.loop loop id metadata node for this loop if it is present.
353 ///
354 /// If this loop contains the same llvm.loop metadata on each branch to the
355 /// header then the node is returned. If any latch instruction does not
356 /// contain llvm.loop or if multiple latches contain different nodes then
357 /// 0 is returned.
358 MDNode *getLoopID() const;
359 /// Set the llvm.loop loop id metadata for this loop.
360 ///
361 /// The LoopID metadata node will be added to each terminator instruction in
362 /// the loop that branches to the loop header.
363 ///
364 /// The LoopID metadata node should have one or more operands and the first
365 /// operand should be the node itself.
366 void setLoopID(MDNode *LoopID) const;
367
368 /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
369 ///
370 /// Remove existing unroll metadata and add unroll disable metadata to
371 /// indicate the loop has already been unrolled. This prevents a loop
372 /// from being unrolled more than is directed by a pragma if the loop
373 /// unrolling pass is run more than once (which it generally is).
374 void setLoopAlreadyUnrolled();
375
376 /// Add llvm.loop.mustprogress to this loop's loop id metadata.
377 void setLoopMustProgress();
378
379 /// Add a string-only metadata attribute to this loop's loop-ID node.
380 ///
381 /// Creates an MDNode containing just \p Name (no value operand) and appends
382 /// it to the loop metadata via makePostTransformationMetadata. Any existing
383 /// attributes whose key starts with one of \p RemovePrefixes are stripped
384 /// first.
385 void addStringLoopAttribute(StringRef Name,
386 ArrayRef<StringRef> RemovePrefixes = {}) const;
387
388 /// Add an integer metadata attribute to this loop's loop-ID node.
389 ///
390 /// Creates an MDNode of the form { Name, ConstantInt(Value) } and appends
391 /// it to the loop metadata via makePostTransformationMetadata. Any existing
392 /// attributes whose key starts with one of \p RemovePrefixes are stripped
393 /// first.
394 void addIntLoopAttribute(StringRef Name, unsigned Value,
395 ArrayRef<StringRef> RemovePrefixes = {}) const;
396
397 void dump() const;
398 void dumpVerbose() const;
399
400 /// Return the debug location of the start of this loop.
401 /// This looks for a BB terminating instruction with a known debug
402 /// location by looking at the preheader and header blocks. If it
403 /// cannot find a terminating instruction with location information,
404 /// it returns an unknown location.
405 DebugLoc getStartLoc() const;
406
407 /// Return the source code span of the loop.
408 LocRange getLocRange() const;
409
410 /// Return a string containing the debug location of the loop (file name +
411 /// line number if present, otherwise module name). Meant to be used for debug
412 /// printing within LLVM_DEBUG.
413 std::string getLocStr() const;
414
416 if (BasicBlock *Header = getHeader())
417 if (Header->hasName())
418 return Header->getName();
419 return "<unnamed loop>";
420 }
421
422private:
423 Loop() = default;
424
426 friend class LoopBase<BasicBlock, Loop>;
427 ~Loop() = default;
428};
429
430// Implementation in Support/GenericLoopInfoImpl.h
432
433class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
434 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
435
436 friend class LoopBase<BasicBlock, Loop>;
437
438 void operator=(const LoopInfo &) = delete;
439 LoopInfo(const LoopInfo &) = delete;
440
441public:
442 LoopInfo() = default;
445
446 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
447 LoopInfo &operator=(LoopInfo &&RHS) {
448 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
449 return *this;
450 }
451
452 /// Handle invalidation explicitly.
453 LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA,
454 FunctionAnalysisManager::Invalidator &);
455
456 // Most of the public interface is provided via LoopInfoBase.
457
458 /// Update LoopInfo after removing the last backedge from a loop. This updates
459 /// the loop forest and parent loops for each block so that \c L is no longer
460 /// referenced, but does not actually delete \c L immediately. The pointer
461 /// will remain valid until this LoopInfo's memory is released.
462 LLVM_ABI void erase(Loop *L);
463
464 /// Returns true if replacing From with To everywhere is guaranteed to
465 /// preserve LCSSA form.
467 // Preserving LCSSA form is only problematic if the replacing value is an
468 // instruction.
470 if (!I)
471 return true;
472 // If both instructions are defined in the same basic block then replacement
473 // cannot break LCSSA form.
474 if (I->getParent() == From->getParent())
475 return true;
476 // If the instruction is not defined in a loop then it can safely replace
477 // anything.
478 Loop *ToLoop = getLoopFor(I->getParent());
479 if (!ToLoop)
480 return true;
481 // If the replacing instruction is defined in the same loop as the original
482 // instruction, or in a loop that contains it as an inner loop, then using
483 // it as a replacement will not break LCSSA form.
484 return ToLoop->contains(getLoopFor(From->getParent()));
485 }
486
487 /// Checks if moving a specific instruction can break LCSSA in any loop.
488 ///
489 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
490 /// assuming that the function containing \p Inst and \p NewLoc is currently
491 /// in LCSSA form.
493 assert(Inst->getFunction() == NewLoc->getFunction() &&
494 "Can't reason about IPO!");
495
496 auto *OldBB = Inst->getParent();
497 auto *NewBB = NewLoc->getParent();
498
499 // Movement within the same loop does not break LCSSA (the equality check is
500 // to avoid doing a hashtable lookup in case of intra-block movement).
501 if (OldBB == NewBB)
502 return true;
503
504 auto *OldLoop = getLoopFor(OldBB);
505 auto *NewLoop = getLoopFor(NewBB);
506
507 if (OldLoop == NewLoop)
508 return true;
509
510 // Check if Outer contains Inner; with the null loop counting as the
511 // "outermost" loop.
512 auto Contains = [](const Loop *Outer, const Loop *Inner) {
513 return !Outer || Outer->contains(Inner);
514 };
515
516 // To check that the movement of Inst to before NewLoc does not break LCSSA,
517 // we need to check two sets of uses for possible LCSSA violations at
518 // NewLoc: the users of NewInst, and the operands of NewInst.
519
520 // If we know we're hoisting Inst out of an inner loop to an outer loop,
521 // then the uses *of* Inst don't need to be checked.
522
523 if (!Contains(NewLoop, OldLoop)) {
524 for (Use &U : Inst->uses()) {
525 auto *UI = cast<Instruction>(U.getUser());
526 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
527 : UI->getParent();
528 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
529 return false;
530 }
531 }
532
533 // If we know we're sinking Inst from an outer loop into an inner loop, then
534 // the *operands* of Inst don't need to be checked.
535
536 if (!Contains(OldLoop, NewLoop)) {
537 // See below on why we can't handle phi nodes here.
538 if (isa<PHINode>(Inst))
539 return false;
540
541 for (Use &U : Inst->operands()) {
542 auto *DefI = dyn_cast<Instruction>(U.get());
543 if (!DefI)
544 return false;
545
546 // This would need adjustment if we allow Inst to be a phi node -- the
547 // new use block won't simply be NewBB.
548
549 auto *DefBlock = DefI->getParent();
550 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
551 return false;
552 }
553 }
554
555 return true;
556 }
557
558 // Return true if a new use of V added in ExitBB would require an LCSSA PHI
559 // to be inserted at the beginning of the block. Note that V is assumed to
560 // dominate ExitBB, and ExitBB must be the exit block of some loop. The
561 // IR is assumed to be in LCSSA form before the planned insertion.
562 LLVM_ABI bool
563 wouldBeOutOfLoopUseRequiringLCSSA(const Value *V,
564 const BasicBlock *ExitBB) const;
565};
566
567/// Enable verification of loop info.
568///
569/// The flag enables checks which are expensive and are disabled by default
570/// unless the `EXPENSIVE_CHECKS` macro is defined. The `-verify-loop-info`
571/// flag allows the checks to be enabled selectively without re-compilation.
572LLVM_ABI extern bool VerifyLoopInfo;
573
574// Allow clients to walk the list of nested loops...
575template <> struct GraphTraits<const Loop *> {
576 typedef const Loop *NodeRef;
578
579 static NodeRef getEntryNode(const Loop *L) { return L; }
580 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
581 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
582};
583
584template <> struct GraphTraits<Loop *> {
585 typedef Loop *NodeRef;
587
588 static NodeRef getEntryNode(Loop *L) { return L; }
589 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
590 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
591};
592
593/// Analysis pass that exposes the \c LoopInfo for a function.
603
604/// Printer pass for the \c LoopAnalysis results.
612
613/// Verifier pass for the \c LoopAnalysis results.
617
618/// The legacy pass manager's analysis pass to compute loop information.
620 LoopInfo LI;
621
622public:
623 static char ID; // Pass identification, replacement for typeid
624
626
627 LoopInfo &getLoopInfo() { return LI; }
628 const LoopInfo &getLoopInfo() const { return LI; }
629
630 /// Calculate the natural loop information for a given function.
631 bool runOnFunction(Function &F) override;
632
633 void verifyAnalysis() const override;
634
635 void releaseMemory() override { LI.releaseMemory(); }
636
637 void print(raw_ostream &O, const Module *M = nullptr) const override;
638
639 void getAnalysisUsage(AnalysisUsage &AU) const override;
640};
641
642/// Function to print a loop's contents as LLVM's text IR assembly.
643LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS,
644 const std::string &Banner = "");
645
646/// Find and return the loop attribute node for the attribute @p Name in
647/// @p LoopID. Return nullptr if there is no such attribute.
648LLVM_ABI MDNode *findOptionMDForLoopID(MDNode *LoopID, StringRef Name);
649
650/// Find string metadata for a loop.
651///
652/// Returns the MDNode where the first operand is the metadata's name. The
653/// following operands are the metadata's values. If no metadata with @p Name is
654/// found, return nullptr.
655LLVM_ABI MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
656
657LLVM_ABI std::optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
658 StringRef Name);
659
660/// Returns true if Name is applied to TheLoop and enabled.
661LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name);
662
663/// Find named metadata for a loop with an integer value.
664LLVM_ABI std::optional<int> getOptionalIntLoopAttribute(const Loop *TheLoop,
665 StringRef Name);
666
667/// Find named metadata for a loop with an integer value. Return \p Default if
668/// not set.
669LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
670 int Default = 0);
671
672/// Find string metadata for loop
673///
674/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
675/// operand or null otherwise. If the string metadata is not found return
676/// Optional's not-a-value.
677LLVM_ABI std::optional<const MDOperand *>
678findStringMetadataForLoop(const Loop *TheLoop, StringRef Name);
679
680/// Find the convergence heart of the loop.
681LLVM_ABI CallBase *getLoopConvergenceHeart(const Loop *TheLoop);
682
683/// Look for the loop attribute that requires progress within the loop.
684/// Note: Most consumers probably want "isMustProgress" which checks
685/// the containing function attribute too.
686LLVM_ABI bool hasMustProgress(const Loop *L);
687
688/// Return true if this loop can be assumed to make progress. (i.e. can't
689/// be infinite without side effects without also being undefined)
690LLVM_ABI bool isMustProgress(const Loop *L);
691
692/// Return true if this loop can be assumed to run for a finite number of
693/// iterations.
694LLVM_ABI bool isFinite(const Loop *L);
695
696/// Return whether an MDNode might represent an access group.
697///
698/// Access group metadata nodes have to be distinct and empty. Being
699/// always-empty ensures that it never needs to be changed (which -- because
700/// MDNodes are designed immutable -- would require creating a new MDNode). Note
701/// that this is not a sufficient condition: not every distinct and empty NDNode
702/// is representing an access group.
703LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup);
704
705/// Create a new LoopID after the loop has been transformed.
706///
707/// This can be used when no follow-up loop attributes are defined
708/// (llvm::makeFollowupLoopID returning None) to stop transformations to be
709/// applied again.
710///
711/// @param Context The LLVMContext in which to create the new LoopID.
712/// @param OrigLoopID The original LoopID; can be nullptr if the original
713/// loop has no LoopID.
714/// @param RemovePrefixes Remove all loop attributes that have these prefixes.
715/// Use to remove metadata of the transformation that has
716/// been applied.
717/// @param AddAttrs Add these loop attributes to the new LoopID.
718///
719/// @return A new LoopID that can be applied using Loop::setLoopID().
721makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID,
722 llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
724} // namespace llvm
725
726#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_TEMPLATE_ABI
Definition Compiler.h:216
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:253
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool Contains(directive::VersionRange V, int P)
Definition Spelling.cpp:18
Value * RHS
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
A debug info location.
Definition DebugLoc.h:126
Core dominator tree base class.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
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:594
LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM)
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 this loop.
bool isLoopExiting(const BasicBlock *BB) const
This class builds and contains all of the top-level loop structures in the specified function.
typename std::vector< Loop * >::const_iterator iterator
Loop * getLoopFor(const BasicBlock *BB) const
const LoopInfo & getLoopInfo() const
Definition LoopInfo.h:628
LoopInfo & getLoopInfo()
Definition LoopInfo.h:627
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:635
LoopInfo()=default
LoopInfo & operator=(LoopInfo &&RHS)
Definition LoopInfo.h:447
LoopInfo(LoopInfo &&Arg)
Definition LoopInfo.h:446
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:466
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:492
LoopPrinterPass(raw_ostream &OS)
Definition LoopInfo.h:609
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
CondBrInst * getLoopGuardBranch() const
Return the loop guard branch, if it exists.
Definition LoopInfo.cpp:389
StringRef getName() const
Definition LoopInfo.h:415
bool isRotatedForm() const
Return true if the loop is in rotated form.
Definition LoopInfo.h:303
Metadata node.
Definition Metadata.h:1069
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
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:643
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:2200
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:53
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
ArrayRef(const T &OneElt) -> ArrayRef< T >
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:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode * > AddAttrs)
Create a new LoopID after the loop has been transformed.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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:878
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
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:588
LoopInfo::iterator ChildIteratorType
Definition LoopInfo.h:586
static ChildIteratorType child_begin(NodeRef N)
Definition LoopInfo.h:589
static ChildIteratorType child_end(NodeRef N)
Definition LoopInfo.h:590
static ChildIteratorType child_begin(NodeRef N)
Definition LoopInfo.h:580
static ChildIteratorType child_end(NodeRef N)
Definition LoopInfo.h:581
static NodeRef getEntryNode(const Loop *L)
Definition LoopInfo.h:579
LoopInfo::iterator ChildIteratorType
Definition LoopInfo.h:577
Verifier pass for the LoopAnalysis results.
Definition LoopInfo.h:614
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
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:225
Direction
An enum for the direction of the loop.
Definition LoopInfo.h:216
Value & getFinalIVValue() const
Get the final value of the loop induction variable.
Definition LoopInfo.h:175
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 for passes that should not be skipped.