LLVM 24.0.0git
LoopConstrainer.h
Go to the documentation of this file.
1//===- LoopConstrainer.h ----------------------------------------*- 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#ifndef LLVM_TRANSFORMS_UTILS_LOOP_CONSTRAINER_H
10#define LLVM_TRANSFORMS_UTILS_LOOP_CONSTRAINER_H
11
14#include <optional>
15
16namespace llvm {
17
18class BasicBlock;
19class CondBrInst;
20class DominatorTree;
21class IntegerType;
22class Loop;
23class LoopInfo;
24class PHINode;
25class ScalarEvolution;
26class SCEV;
27class SCEVExpander;
28class Value;
29
30// Keeps track of the structure of a loop. This is similar to llvm::Loop,
31// except that it is more lightweight and can track the state of a loop through
32// changing and potentially invalid IR. This structure also formalizes the
33// kinds of loops we can deal with -- ones that have a single latch that is also
34// an exiting block *and* have a canonical induction variable.
36 const char *Tag = "";
37
38 BasicBlock *Header = nullptr;
39 BasicBlock *Latch = nullptr;
40
41 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
42 // successor is `LatchExit', the exit block of the loop.
43 CondBrInst *LatchBr = nullptr;
45 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
46
47 // The loop represented by this instance of LoopStructure is semantically
48 // equivalent to:
49 //
50 // intN_ty inc = IndVarIncreasing ? 1 : -1;
51 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
52 //
53 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
54 // ... body ...
55
56 Value *IndVarBase = nullptr;
57 Value *IndVarStart = nullptr;
58 Value *IndVarStep = nullptr;
59 Value *LoopExitAt = nullptr;
60 bool IndVarIncreasing = false;
61 bool IsSignedPredicate = true;
63
64 LoopStructure() = default;
65
66 template <typename M> LoopStructure map(M Map) const {
67 LoopStructure Result;
68 Result.Tag = Tag;
69 Result.Header = cast<BasicBlock>(Map(Header));
70 Result.Latch = cast<BasicBlock>(Map(Latch));
71 Result.LatchBr = cast<CondBrInst>(Map(LatchBr));
72 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
73 Result.LatchBrExitIdx = LatchBrExitIdx;
74 Result.IndVarBase = Map(IndVarBase);
75 Result.IndVarStart = Map(IndVarStart);
76 Result.IndVarStep = Map(IndVarStep);
77 Result.LoopExitAt = Map(LoopExitAt);
78 Result.IndVarIncreasing = IndVarIncreasing;
79 Result.IsSignedPredicate = IsSignedPredicate;
80 Result.ExitCountTy = ExitCountTy;
81 return Result;
82 }
83
84 /// Parse \p L and use \p Expander to materialize values needed by the parsed
85 /// structure. This allows the caller to discard speculative expansions with
86 /// a SCEVExpanderCleaner if the transformation is not committed.
87 LLVM_ABI static std::optional<LoopStructure>
89 bool AllowUnsignedLatchCond, const char *&FailureReason);
90};
91
92/// This class is used to constrain loops to run within a given iteration space.
93/// The algorithm this class implements is given a Loop and a range [Begin,
94/// End). The algorithm then tries to break out a "main loop" out of the loop
95/// it is given in a way that the "main loop" runs with the induction variable
96/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
97/// loops to run any remaining iterations. The pre loop runs any iterations in
98/// which the induction variable is < Begin, and the post loop runs any
99/// iterations in which the induction variable is >= End.
101public:
102 // Calculated subranges we restrict the iteration space of the main loop to.
103 // See the implementation of `calculateSubRanges' for more details on how
104 // these fields are computed. `LowLimit` is std::nullopt if there is no
105 // restriction on low end of the restricted iteration space of the main loop.
106 // `HighLimit` is std::nullopt if there is no restriction on high end of the
107 // restricted iteration space of the main loop.
108
109 struct SubRanges {
110 std::optional<const SCEV *> LowLimit;
111 std::optional<const SCEV *> HighLimit;
112 };
113
114private:
115 // The representation of a clone of the original loop we started out with.
116 struct ClonedLoop {
117 // The cloned blocks
118 std::vector<BasicBlock *> Blocks;
119
120 // `Map` maps values in the clonee into values in the cloned version
122
123 // An instance of `LoopStructure` for the cloned loop
124 LoopStructure Structure;
125 };
126
127 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
128 // more details on what these fields mean.
129 struct RewrittenRangeInfo {
130 BasicBlock *PseudoExit = nullptr;
131 BasicBlock *ExitSelector = nullptr;
132 std::vector<PHINode *> PHIValuesAtPseudoExit;
133 PHINode *IndVarEnd = nullptr;
134
135 RewrittenRangeInfo() = default;
136 };
137
138 // Clone `OriginalLoop' and return the result in CLResult. The IR after
139 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
140 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
141 // but there is no such edge.
142 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
143
144 // Create the appropriate loop structure needed to describe a cloned copy of
145 // `Original`. The clone is described by `VM`.
146 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
147 ValueToValueMapTy &VM, bool IsSubloop);
148
149 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
150 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
151 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
152 // `OriginalHeaderCount'.
153 //
154 // If there are iterations left to execute, control is made to jump to
155 // `ContinuationBlock', otherwise they take the normal loop exit. The
156 // returned `RewrittenRangeInfo' object is populated as follows:
157 //
158 // .PseudoExit is a basic block that unconditionally branches to
159 // `ContinuationBlock'.
160 //
161 // .ExitSelector is a basic block that decides, on exit from the loop,
162 // whether to branch to the "true" exit or to `PseudoExit'.
163 //
164 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
165 // for each PHINode in the loop header on taking the pseudo exit.
166 //
167 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
168 // preheader because it is made to branch to the loop header only
169 // conditionally.
170 RewrittenRangeInfo
171 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
172 Value *ExitLoopAt,
173 BasicBlock *ContinuationBlock) const;
174
175 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
176 // function creates a new preheader for `LS' and returns it.
177 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
178 const char *Tag) const;
179
180 // `ContinuationBlockAndPreheader' was the continuation block for some call to
181 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
182 // This function rewrites the PHI nodes in `LS.Header' to start with the
183 // correct value.
184 void rewriteIncomingValuesForPHIs(
185 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
186 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
187
188 // Even though we do not preserve any passes at this time, we at least need to
189 // keep the parent loop structure consistent. The `LPPassManager' seems to
190 // verify this after running a loop pass. This function adds the list of
191 // blocks denoted by BBs to this loops parent loop if required.
192 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
193
194 // Some global state.
195 Function &F;
196 LLVMContext &Ctx;
197 ScalarEvolution &SE;
198 DominatorTree &DT;
199 LoopInfo &LI;
200 function_ref<void(Loop *, bool)> LPMAddNewLoop;
201
202 // Information about the original loop we started out with.
203 Loop &OriginalLoop;
204
205 BasicBlock *OriginalPreheader = nullptr;
206
207 // The preheader of the main loop. This may or may not be different from
208 // `OriginalPreheader'.
209 BasicBlock *MainLoopPreheader = nullptr;
210
211 // Type of the range we need to run the main loop in.
212 Type *RangeTy;
213
214 // The structure of the main loop (see comment at the beginning of this class
215 // for a definition)
216 LoopStructure MainLoopStructure;
217
218 SubRanges SR;
219
220public:
221 LLVM_ABI LoopConstrainer(Loop &L, LoopInfo &LI,
222 function_ref<void(Loop *, bool)> LPMAddNewLoop,
223 const LoopStructure &LS, ScalarEvolution &SE,
224 DominatorTree &DT, Type *T, SubRanges SR);
225
226 // Entry point for the algorithm. Returns true on success.
227 LLVM_ABI bool run();
228};
229} // namespace llvm
230
231#endif // LLVM_TRANSFORMS_UTILS_LOOP_CONSTRAINER_H
#define LLVM_ABI
Definition Compiler.h:215
#define F(x, y, z)
Definition MD5.cpp:54
#define T
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Conditional Branch instruction.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Class to represent integer types.
LLVM_ABI LoopConstrainer(Loop &L, LoopInfo &LI, function_ref< void(Loop *, bool)> LPMAddNewLoop, const LoopStructure &LS, ScalarEvolution &SE, DominatorTree &DT, Type *T, SubRanges SR)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class uses information about analyze scalars to rewrite expressions in canonical form.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
ArrayRef(const T &OneElt) -> ArrayRef< T >
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
std::optional< const SCEV * > LowLimit
std::optional< const SCEV * > HighLimit
LoopStructure map(M Map) const
static LLVM_ABI std::optional< LoopStructure > parseLoopStructure(SCEVExpander &Expander, Loop &L, bool AllowUnsignedLatchCond, const char *&FailureReason)
Parse L and use Expander to materialize values needed by the parsed structure.
IntegerType * ExitCountTy
LoopStructure()=default