LLVM 24.0.0git
LoopCacheAnalysis.h
Go to the documentation of this file.
1//===- llvm/Analysis/LoopCacheAnalysis.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/// \file
10/// This file defines the interface for the loop cache analysis.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
15#define LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
16
18#include "llvm/IR/PassManager.h"
20#include <optional>
21
22namespace llvm {
23
24class AAResults;
25class DependenceInfo;
26class Instruction;
27class raw_ostream;
28class LoopInfo;
29class Loop;
30class ScalarEvolution;
31class SCEV;
33
36
37/// Represents a memory reference as a base pointer and a set of indexing
38/// operations. For example given the array reference A[i][2j+1][3k+2] in a
39/// 3-dim loop nest:
40/// for(i=0;i<n;++i)
41/// for(j=0;j<m;++j)
42/// for(k=0;k<o;++k)
43/// ... A[i][2j+1][3k+2] ...
44/// We expect:
45/// BasePointer -> A
46/// Subscripts -> [{0,+,1}<%for.i>][{1,+,2}<%for.j>][{2,+,3}<%for.k>]
47/// Sizes -> [m][o][4]
50 const IndexedReference &R);
51
52public:
53 /// Construct an indexed reference given a \p StoreOrLoadInst instruction.
54 LLVM_ABI IndexedReference(Instruction &StoreOrLoadInst, const LoopInfo &LI,
55 ScalarEvolution &SE);
56
57 bool isValid() const { return IsValid; }
58 const SCEV *getBasePointer() const { return BasePointer; }
59 size_t getNumSubscripts() const { return Subscripts.size(); }
60 const SCEV *getSubscript(unsigned SubNum) const {
61 assert(SubNum < getNumSubscripts() && "Invalid subscript number");
62 return Subscripts[SubNum];
63 }
64 const SCEV *getFirstSubscript() const {
65 assert(!Subscripts.empty() && "Expecting non-empty container");
66 return Subscripts.front();
67 }
68 const SCEV *getLastSubscript() const {
69 assert(!Subscripts.empty() && "Expecting non-empty container");
70 return Subscripts.back();
71 }
72
73 /// Return true/false if the current object and the indexed reference \p Other
74 /// are/aren't in the same cache line of size \p CLS. Two references are in
75 /// the same chace line iff the distance between them in the innermost
76 /// dimension is less than the cache line size. Return std::nullopt if unsure.
77 LLVM_ABI std::optional<bool> hasSpacialReuse(const IndexedReference &Other,
78 unsigned CLS,
79 AAResults &AA) const;
80
81 /// Return true if the current object and the indexed reference \p Other
82 /// have distance smaller than \p MaxDistance in the dimension associated with
83 /// the given loop \p L. Return false if the distance is not smaller than \p
84 /// MaxDistance and std::nullopt if unsure.
85 LLVM_ABI std::optional<bool>
86 hasTemporalReuse(const IndexedReference &Other, unsigned MaxDistance,
87 const Loop &L, DependenceInfo &DI, AAResults &AA) const;
88
89 /// Compute the cost of the reference w.r.t. the given loop \p L when it is
90 /// considered in the innermost position in the loop nest.
91 /// The cost is defined as:
92 /// - equal to one if the reference is loop invariant, or
93 /// - equal to '(TripCount * stride) / cache_line_size' if:
94 /// + the reference stride is less than the cache line size, and
95 /// + the coefficient of this loop's index variable used in all other
96 /// subscripts is zero
97 /// - or otherwise equal to 'TripCount'.
98 LLVM_ABI CacheCostTy computeRefCost(const Loop &L, unsigned CLS) const;
99
100private:
101 /// Attempt to delinearize the indexed reference.
102 bool delinearize(const LoopInfo &LI);
103
104 /// Return true if the index reference is invariant with respect to loop \p L.
105 bool isLoopInvariant(const Loop &L) const;
106
107 /// Return true if the indexed reference is 'consecutive' in loop \p L.
108 /// An indexed reference is 'consecutive' if the only coefficient that uses
109 /// the loop induction variable is the rightmost one, and the access stride is
110 /// smaller than the cache line size \p CLS. Provide a valid \p Stride value
111 /// if the indexed reference is 'consecutive'.
112 bool isConsecutive(const Loop &L, const SCEV *&Stride, unsigned CLS) const;
113
114 /// Retrieve the index of the subscript corresponding to the given loop \p
115 /// L. Return a zero-based positive index if the subscript index is
116 /// succesfully located and a negative value otherwise. For example given the
117 /// indexed reference 'A[i][2j+1][3k+2]', the call
118 /// 'getSubscriptIndex(loop-k)' would return value 2.
119 int getSubscriptIndex(const Loop &L) const;
120
121 /// Return the coefficient used in the rightmost dimension.
122 const SCEV *getLastCoefficient() const;
123
124 /// Return true if the coefficient corresponding to induction variable of
125 /// loop \p L in the given \p Subscript is zero or is loop invariant in \p L.
126 bool isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
127 const Loop &L) const;
128
129 /// Verify that the given \p Subscript is 'well formed' (must be a simple add
130 /// recurrence).
131 bool isSimpleAddRecurrence(const SCEV &Subscript, const Loop &L) const;
132
133 /// Return true if the given reference \p Other is definetely aliased with
134 /// the indexed reference represented by this class.
135 bool isAliased(const IndexedReference &Other, AAResults &AA) const;
136
137private:
138 /// True if the reference can be delinearized, false otherwise.
139 bool IsValid = false;
140
141 /// Represent the memory reference instruction.
142 Instruction &StoreOrLoadInst;
143
144 /// The base pointer of the memory reference.
145 const SCEV *BasePointer = nullptr;
146
147 /// The subscript (indexes) of the memory reference.
149
150 /// The dimensions of the memory reference.
152
153 ScalarEvolution &SE;
154};
155
156/// A reference group represents a set of memory references that exhibit
157/// temporal or spacial reuse. Two references belong to the same
158/// reference group with respect to a inner loop L iff:
159/// 1. they have a loop independent dependency, or
160/// 2. they have a loop carried dependence with a small dependence distance
161/// (e.g. less than 2) carried by the inner loop, or
162/// 3. they refer to the same array, and the subscript in their innermost
163/// dimension is less than or equal to 'd' (where 'd' is less than the cache
164/// line size)
165///
166/// Intuitively a reference group represents memory references that access
167/// the same cache line. Conditions 1,2 above account for temporal reuse, while
168/// contition 3 accounts for spacial reuse.
171
172/// \c CacheCost represents the estimated cost of a inner loop as the number of
173/// cache lines used by the memory references it contains.
174/// The 'cache cost' of a loop 'L' in a loop nest 'LN' is computed as the sum of
175/// the cache costs of all of its reference groups when the loop is considered
176/// to be in the innermost position in the nest.
177/// A reference group represents memory references that fall into the same cache
178/// line. Each reference group is analysed with respect to the innermost loop in
179/// a loop nest. The cost of a reference is defined as follow:
180/// - one if it is loop invariant w.r.t the innermost loop,
181/// - equal to the loop trip count divided by the cache line times the
182/// reference stride if the reference stride is less than the cache line
183/// size (CLS), and the coefficient of this loop's index variable used in all
184/// other subscripts is zero (e.g. RefCost = TripCount/(CLS/RefStride))
185/// - equal to the innermost loop trip count if the reference stride is greater
186/// or equal to the cache line size CLS.
189 using LoopTripCountTy = std::pair<const Loop *, unsigned>;
190 using LoopCacheCostTy = std::pair<const Loop *, CacheCostTy>;
191
192public:
193 /// Construct a CacheCost object for the loop nest described by \p Loops.
194 /// The optional parameter \p TRT can be used to specify the max. distance
195 /// between array elements accessed in a loop so that the elements are
196 /// classified to have temporal reuse.
197 LLVM_ABI CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI,
199 AAResults &AA, DependenceInfo &DI,
200 std::optional<unsigned> TRT = std::nullopt);
201
202 /// Create a CacheCost for the loop nest rooted by \p Root.
203 /// The optional parameter \p TRT can be used to specify the max. distance
204 /// between array elements accessed in a loop so that the elements are
205 /// classified to have temporal reuse.
206 LLVM_ABI static std::unique_ptr<CacheCost>
208 std::optional<unsigned> TRT = std::nullopt);
209
210 /// Return the estimated cost of loop \p L if the given loop is part of the
211 /// loop nest associated with this object. Return -1 otherwise.
212 CacheCostTy getLoopCost(const Loop &L) const {
213 auto IT = llvm::find_if(LoopCosts, [&L](const LoopCacheCostTy &LCC) {
214 return LCC.first == &L;
215 });
216 return (IT != LoopCosts.end()) ? (*IT).second : -1;
217 }
218
219 /// Return the estimated ordered loop costs.
220 ArrayRef<LoopCacheCostTy> getLoopCosts() const { return LoopCosts; }
221
222private:
223 /// Calculate the cache footprint of each loop in the nest (when it is
224 /// considered to be in the innermost position).
225 void calculateCacheFootprint();
226
227 /// Partition store/load instructions in the loop nest into reference groups.
228 /// Two or more memory accesses belong in the same reference group if they
229 /// share the same cache line.
230 bool populateReferenceGroups(ReferenceGroupsTy &RefGroups) const;
231
232 /// Calculate the cost of the given loop \p L assuming it is the innermost
233 /// loop in nest.
234 CacheCostTy computeLoopCacheCost(const Loop &L,
235 const ReferenceGroupsTy &RefGroups) const;
236
237 /// Compute the cost of a representative reference in reference group \p RG
238 /// when the given loop \p L is considered as the innermost loop in the nest.
239 /// The computed cost is an estimate for the number of cache lines used by the
240 /// reference group. The representative reference cost is defined as:
241 /// - equal to one if the reference is loop invariant, or
242 /// - equal to '(TripCount * stride) / cache_line_size' if (a) loop \p L's
243 /// induction variable is used only in the reference subscript associated
244 /// with loop \p L, and (b) the reference stride is less than the cache
245 /// line size, or
246 /// - TripCount otherwise
247 CacheCostTy computeRefGroupCacheCost(const ReferenceGroupTy &RG,
248 const Loop &L) const;
249
250 /// Sort the LoopCosts vector by decreasing cache cost.
251 void sortLoopCosts() {
252 stable_sort(LoopCosts,
253 [](const LoopCacheCostTy &A, const LoopCacheCostTy &B) {
254 return A.second > B.second;
255 });
256 }
257
258private:
259 /// Loops in the loop nest associated with this object.
260 LoopVectorTy Loops;
261
262 /// Trip counts for the loops in the loop nest associated with this object.
263 SmallVector<LoopTripCountTy, 3> TripCounts;
264
265 /// Cache costs for the loops in the loop nest associated with this object.
266 SmallVector<LoopCacheCostTy, 3> LoopCosts;
267
268 /// The max. distance between array elements accessed in a loop so that the
269 /// elements are classified to have temporal reuse.
270 std::optional<unsigned> TRT;
271
272 const LoopInfo &LI;
273 ScalarEvolution &SE;
274 TargetTransformInfo &TTI;
275 AAResults &AA;
276 DependenceInfo &DI;
277};
278
281
282/// Printer pass for the \c CacheCost results.
284 : public RequiredPassInfoMixin<LoopCachePrinterPass> {
285 raw_ostream &OS;
286
287public:
288 explicit LoopCachePrinterPass(raw_ostream &OS) : OS(OS) {}
289
291};
292
293} // namespace llvm
294
295#endif // LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
This header defines various interfaces for pass management in LLVM.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
This header provides classes for managing per-loop analyses.
#define F(x, y, z)
Definition MD5.cpp:54
FunctionAnalysisManager FAM
RISCVCC::CondCode CC
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
CacheCost represents the estimated cost of a inner loop as the number of cache lines used by the memo...
LLVM_ABI CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI, ScalarEvolution &SE, TargetTransformInfo &TTI, AAResults &AA, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Construct a CacheCost object for the loop nest described by Loops.
friend LLVM_ABI raw_ostream & operator<<(raw_ostream &OS, const CacheCost &CC)
ArrayRef< LoopCacheCostTy > getLoopCosts() const
Return the estimated ordered loop costs.
static LLVM_ABI std::unique_ptr< CacheCost > getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Create a CacheCost for the loop nest rooted by Root.
CacheCostTy getLoopCost(const Loop &L) const
Return the estimated cost of loop L if the given loop is part of the loop nest associated with this o...
DependenceInfo - This class is the main dependence-analysis driver.
Represents a memory reference as a base pointer and a set of indexing operations.
const SCEV * getBasePointer() const
LLVM_ABI CacheCostTy computeRefCost(const Loop &L, unsigned CLS) const
Compute the cost of the reference w.r.t.
const SCEV * getSubscript(unsigned SubNum) const
const SCEV * getFirstSubscript() const
LLVM_ABI std::optional< bool > hasSpacialReuse(const IndexedReference &Other, unsigned CLS, AAResults &AA) const
Return true/false if the current object and the indexed reference Other are/aren't in the same cache ...
LLVM_ABI std::optional< bool > hasTemporalReuse(const IndexedReference &Other, unsigned MaxDistance, const Loop &L, DependenceInfo &DI, AAResults &AA) const
Return true if the current object and the indexed reference Other have distance smaller than MaxDista...
LLVM_ABI IndexedReference(Instruction &StoreOrLoadInst, const LoopInfo &LI, ScalarEvolution &SE)
Construct an indexed reference given a StoreOrLoadInst instruction.
const SCEV * getLastSubscript() const
friend LLVM_ABI raw_ostream & operator<<(raw_ostream &OS, const IndexedReference &R)
size_t getNumSubscripts() const
LoopCachePrinterPass(raw_ostream &OS)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
This class represents an analyzed expression in the program.
The main scalar evolution driver.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Abstract Attribute helper functions.
Definition Attributor.h:166
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
InstructionCost CacheCostTy
SmallVector< std::unique_ptr< IndexedReference >, 8 > ReferenceGroupTy
A reference group represents a set of memory references that exhibit temporal or spacial reuse.
SmallVector< Loop *, 8 > LoopVectorTy
@ Other
Any other memory.
Definition ModRef.h:68
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI void delinearize(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Split this SCEVAddRecExpr into two vectors of SCEVs representing the subscripts and sizes of an array...
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
SmallVector< ReferenceGroupTy, 8 > ReferenceGroupsTy
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
A CRTP mix-in for passes that should not be skipped.