LLVM 23.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 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 /// Add a string-only metadata attribute to this loop's loop-ID node.
372 ///
373 /// Creates an MDNode containing just \p Name (no value operand) and appends
374 /// it to the loop metadata via makePostTransformationMetadata. Any existing
375 /// attributes whose key starts with one of \p RemovePrefixes are stripped
376 /// first.
377 LLVM_ABI void
378 addStringLoopAttribute(StringRef Name,
379 ArrayRef<StringRef> RemovePrefixes = {}) const;
380
381 /// Add an integer metadata attribute to this loop's loop-ID node.
382 ///
383 /// Creates an MDNode of the form { Name, ConstantInt(Value) } and appends
384 /// it to the loop metadata via makePostTransformationMetadata. Any existing
385 /// attributes whose key starts with one of \p RemovePrefixes are stripped
386 /// first.
387 LLVM_ABI void
388 addIntLoopAttribute(StringRef Name, unsigned Value,
389 ArrayRef<StringRef> RemovePrefixes = {}) const;
390
391 void dump() const;
392 void dumpVerbose() const;
393
394 /// Return the debug location of the start of this loop.
395 /// This looks for a BB terminating instruction with a known debug
396 /// location by looking at the preheader and header blocks. If it
397 /// cannot find a terminating instruction with location information,
398 /// it returns an unknown location.
399 DebugLoc getStartLoc() const;
400
401 /// Return the source code span of the loop.
402 LocRange getLocRange() const;
403
404 /// Return a string containing the debug location of the loop (file name +
405 /// line number if present, otherwise module name). Meant to be used for debug
406 /// printing within LLVM_DEBUG.
407 std::string getLocStr() const;
408
410 if (BasicBlock *Header = getHeader())
411 if (Header->hasName())
412 return Header->getName();
413 return "<unnamed loop>";
414 }
415
416private:
417 Loop() = default;
418
420 friend class LoopBase<BasicBlock, Loop>;
421 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
422 ~Loop() = default;
423};
424
425// Implementation in Support/GenericLoopInfoImpl.h
427
428class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
429 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
430
431 friend class LoopBase<BasicBlock, Loop>;
432
433 void operator=(const LoopInfo &) = delete;
434 LoopInfo(const LoopInfo &) = delete;
435
436public:
437 LoopInfo() = default;
440
441 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
442 LoopInfo &operator=(LoopInfo &&RHS) {
443 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
444 return *this;
445 }
446
447 /// Handle invalidation explicitly.
448 LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA,
449 FunctionAnalysisManager::Invalidator &);
450
451 // Most of the public interface is provided via LoopInfoBase.
452
453 /// Update LoopInfo after removing the last backedge from a loop. This updates
454 /// the loop forest and parent loops for each block so that \c L is no longer
455 /// referenced, but does not actually delete \c L immediately. The pointer
456 /// will remain valid until this LoopInfo's memory is released.
457 LLVM_ABI void erase(Loop *L);
458
459 /// Returns true if replacing From with To everywhere is guaranteed to
460 /// preserve LCSSA form.
462 // Preserving LCSSA form is only problematic if the replacing value is an
463 // instruction.
465 if (!I)
466 return true;
467 // If both instructions are defined in the same basic block then replacement
468 // cannot break LCSSA form.
469 if (I->getParent() == From->getParent())
470 return true;
471 // If the instruction is not defined in a loop then it can safely replace
472 // anything.
473 Loop *ToLoop = getLoopFor(I->getParent());
474 if (!ToLoop)
475 return true;
476 // If the replacing instruction is defined in the same loop as the original
477 // instruction, or in a loop that contains it as an inner loop, then using
478 // it as a replacement will not break LCSSA form.
479 return ToLoop->contains(getLoopFor(From->getParent()));
480 }
481
482 /// Checks if moving a specific instruction can break LCSSA in any loop.
483 ///
484 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
485 /// assuming that the function containing \p Inst and \p NewLoc is currently
486 /// in LCSSA form.
488 assert(Inst->getFunction() == NewLoc->getFunction() &&
489 "Can't reason about IPO!");
490
491 auto *OldBB = Inst->getParent();
492 auto *NewBB = NewLoc->getParent();
493
494 // Movement within the same loop does not break LCSSA (the equality check is
495 // to avoid doing a hashtable lookup in case of intra-block movement).
496 if (OldBB == NewBB)
497 return true;
498
499 auto *OldLoop = getLoopFor(OldBB);
500 auto *NewLoop = getLoopFor(NewBB);
501
502 if (OldLoop == NewLoop)
503 return true;
504
505 // Check if Outer contains Inner; with the null loop counting as the
506 // "outermost" loop.
507 auto Contains = [](const Loop *Outer, const Loop *Inner) {
508 return !Outer || Outer->contains(Inner);
509 };
510
511 // To check that the movement of Inst to before NewLoc does not break LCSSA,
512 // we need to check two sets of uses for possible LCSSA violations at
513 // NewLoc: the users of NewInst, and the operands of NewInst.
514
515 // If we know we're hoisting Inst out of an inner loop to an outer loop,
516 // then the uses *of* Inst don't need to be checked.
517
518 if (!Contains(NewLoop, OldLoop)) {
519 for (Use &U : Inst->uses()) {
520 auto *UI = cast<Instruction>(U.getUser());
521 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
522 : UI->getParent();
523 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
524 return false;
525 }
526 }
527
528 // If we know we're sinking Inst from an outer loop into an inner loop, then
529 // the *operands* of Inst don't need to be checked.
530
531 if (!Contains(OldLoop, NewLoop)) {
532 // See below on why we can't handle phi nodes here.
533 if (isa<PHINode>(Inst))
534 return false;
535
536 for (Use &U : Inst->operands()) {
537 auto *DefI = dyn_cast<Instruction>(U.get());
538 if (!DefI)
539 return false;
540
541 // This would need adjustment if we allow Inst to be a phi node -- the
542 // new use block won't simply be NewBB.
543
544 auto *DefBlock = DefI->getParent();
545 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
546 return false;
547 }
548 }
549
550 return true;
551 }
552
553 // Return true if a new use of V added in ExitBB would require an LCSSA PHI
554 // to be inserted at the beginning of the block. Note that V is assumed to
555 // dominate ExitBB, and ExitBB must be the exit block of some loop. The
556 // IR is assumed to be in LCSSA form before the planned insertion.
557 LLVM_ABI bool
558 wouldBeOutOfLoopUseRequiringLCSSA(const Value *V,
559 const BasicBlock *ExitBB) const;
560};
561
562/// Enable verification of loop info.
563///
564/// The flag enables checks which are expensive and are disabled by default
565/// unless the `EXPENSIVE_CHECKS` macro is defined. The `-verify-loop-info`
566/// flag allows the checks to be enabled selectively without re-compilation.
567LLVM_ABI extern bool VerifyLoopInfo;
568
569// Allow clients to walk the list of nested loops...
570template <> struct GraphTraits<const Loop *> {
571 typedef const Loop *NodeRef;
573
574 static NodeRef getEntryNode(const Loop *L) { return L; }
575 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
576 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
577};
578
579template <> struct GraphTraits<Loop *> {
580 typedef Loop *NodeRef;
582
583 static NodeRef getEntryNode(Loop *L) { return L; }
584 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
585 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
586};
587
588/// Analysis pass that exposes the \c LoopInfo for a function.
598
599/// Printer pass for the \c LoopAnalysis results.
601 raw_ostream &OS;
602
603public:
604 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
606 static bool isRequired() { return true; }
607};
608
609/// Verifier pass for the \c LoopAnalysis results.
614
615/// The legacy pass manager's analysis pass to compute loop information.
617 LoopInfo LI;
618
619public:
620 static char ID; // Pass identification, replacement for typeid
621
623
624 LoopInfo &getLoopInfo() { return LI; }
625 const LoopInfo &getLoopInfo() const { return LI; }
626
627 /// Calculate the natural loop information for a given function.
628 bool runOnFunction(Function &F) override;
629
630 void verifyAnalysis() const override;
631
632 void releaseMemory() override { LI.releaseMemory(); }
633
634 void print(raw_ostream &O, const Module *M = nullptr) const override;
635
636 void getAnalysisUsage(AnalysisUsage &AU) const override;
637};
638
639/// Function to print a loop's contents as LLVM's text IR assembly.
640LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS,
641 const std::string &Banner = "");
642
643/// Find and return the loop attribute node for the attribute @p Name in
644/// @p LoopID. Return nullptr if there is no such attribute.
645LLVM_ABI MDNode *findOptionMDForLoopID(MDNode *LoopID, StringRef Name);
646
647/// Find string metadata for a loop.
648///
649/// Returns the MDNode where the first operand is the metadata's name. The
650/// following operands are the metadata's values. If no metadata with @p Name is
651/// found, return nullptr.
652LLVM_ABI MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
653
654LLVM_ABI std::optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
655 StringRef Name);
656
657/// Returns true if Name is applied to TheLoop and enabled.
658LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name);
659
660/// Find named metadata for a loop with an integer value.
661LLVM_ABI std::optional<int> getOptionalIntLoopAttribute(const Loop *TheLoop,
662 StringRef Name);
663
664/// Find named metadata for a loop with an integer value. Return \p Default if
665/// not set.
666LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
667 int Default = 0);
668
669/// Find string metadata for loop
670///
671/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
672/// operand or null otherwise. If the string metadata is not found return
673/// Optional's not-a-value.
674LLVM_ABI std::optional<const MDOperand *>
675findStringMetadataForLoop(const Loop *TheLoop, StringRef Name);
676
677/// Find the convergence heart of the loop.
678LLVM_ABI CallBase *getLoopConvergenceHeart(const Loop *TheLoop);
679
680/// Look for the loop attribute that requires progress within the loop.
681/// Note: Most consumers probably want "isMustProgress" which checks
682/// the containing function attribute too.
683LLVM_ABI bool hasMustProgress(const Loop *L);
684
685/// Return true if this loop can be assumed to make progress. (i.e. can't
686/// be infinite without side effects without also being undefined)
687LLVM_ABI bool isMustProgress(const Loop *L);
688
689/// Return true if this loop can be assumed to run for a finite number of
690/// iterations.
691LLVM_ABI bool isFinite(const Loop *L);
692
693/// Return whether an MDNode might represent an access group.
694///
695/// Access group metadata nodes have to be distinct and empty. Being
696/// always-empty ensures that it never needs to be changed (which -- because
697/// MDNodes are designed immutable -- would require creating a new MDNode). Note
698/// that this is not a sufficient condition: not every distinct and empty NDNode
699/// is representing an access group.
700LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup);
701
702/// Create a new LoopID after the loop has been transformed.
703///
704/// This can be used when no follow-up loop attributes are defined
705/// (llvm::makeFollowupLoopID returning None) to stop transformations to be
706/// applied again.
707///
708/// @param Context The LLVMContext in which to create the new LoopID.
709/// @param OrigLoopID The original LoopID; can be nullptr if the original
710/// loop has no LoopID.
711/// @param RemovePrefixes Remove all loop attributes that have these prefixes.
712/// Use to remove metadata of the transformation that has
713/// been applied.
714/// @param AddAttrs Add these loop attributes to the new LoopID.
715///
716/// @return A new LoopID that can be applied using Loop::setLoopID().
718makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID,
719 llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
721} // namespace llvm
722
723#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: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.
ArrayRef - 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:676
A debug info location.
Definition DebugLoc.h:123
Core dominator tree base class.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
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:589
LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM)
Definition LoopInfo.cpp:996
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.
typename std::vector< Loop * >::const_iterator iterator
Loop * getLoopFor(const BasicBlock *BB) const
const LoopInfo & getLoopInfo() const
Definition LoopInfo.h:625
LoopInfo & getLoopInfo()
Definition LoopInfo.h:624
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:632
LoopInfo()=default
LoopInfo & operator=(LoopInfo &&RHS)
Definition LoopInfo.h:442
LoopInfo(LoopInfo &&Arg)
Definition LoopInfo.h:441
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:461
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:487
static bool isRequired()
Definition LoopInfo.h:606
LoopPrinterPass(raw_ostream &OS)
Definition LoopInfo.h:604
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:409
bool isRotatedForm() const
Return true if the loop is in rotated form.
Definition LoopInfo.h:303
Metadata node.
Definition Metadata.h:1080
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:55
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:2199
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:1916
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.
template class LLVM_TEMPLATE_ABI LoopInfoBase< BasicBlock, Loop >
Definition LoopInfo.h:419
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:870
#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:583
LoopInfo::iterator ChildIteratorType
Definition LoopInfo.h:581
static ChildIteratorType child_begin(NodeRef N)
Definition LoopInfo.h:584
static ChildIteratorType child_end(NodeRef N)
Definition LoopInfo.h:585
static ChildIteratorType child_begin(NodeRef N)
Definition LoopInfo.h:575
static ChildIteratorType child_end(NodeRef N)
Definition LoopInfo.h:576
static NodeRef getEntryNode(const Loop *L)
Definition LoopInfo.h:574
LoopInfo::iterator ChildIteratorType
Definition LoopInfo.h:572
Verifier pass for the LoopAnalysis results.
Definition LoopInfo.h:610
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static bool isRequired()
Definition LoopInfo.h:612
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 to automatically provide informational APIs needed for passes.
Definition PassManager.h:70