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 
17 #include "llvm/Analysis/LoopAnalysisManager.h"
18 #include "llvm/IR/PassManager.h"
19 
20 namespace llvm {
21 
22 class AAResults;
23 class DependenceInfo;
24 class Instruction;
25 class LPMUpdater;
26 class raw_ostream;
27 class LoopInfo;
28 class Loop;
29 class ScalarEvolution;
30 class SCEV;
31 class TargetTransformInfo;
32 
33 using CacheCostTy = int64_t;
34 using LoopVectorTy = SmallVector<Loop *, 8>;
35 
36 /// Represents a memory reference as a base pointer and a set of indexing
37 /// operations. For example given the array reference A[i][2j+1][3k+2] in a
38 /// 3-dim loop nest:
39 ///   for(i=0;i<n;++i)
40 ///     for(j=0;j<m;++j)
41 ///       for(k=0;k<o;++k)
42 ///         ... A[i][2j+1][3k+2] ...
43 /// We expect:
44 ///   BasePointer -> A
45 ///   Subscripts -> [{0,+,1}<%for.i>][{1,+,2}<%for.j>][{2,+,3}<%for.k>]
46 ///   Sizes -> [m][o][4]
47 class IndexedReference {
48   friend raw_ostream &operator<<(raw_ostream &OS, const IndexedReference &R);
49 
50 public:
51   /// Construct an indexed reference given a \p StoreOrLoadInst instruction.
52   IndexedReference(Instruction &StoreOrLoadInst, const LoopInfo &LI,
53                    ScalarEvolution &SE);
54 
55   bool isValid() const { return IsValid; }
56   const SCEV *getBasePointer() const { return BasePointer; }
57   size_t getNumSubscripts() const { return Subscripts.size(); }
58   const SCEV *getSubscript(unsigned SubNum) const {
59     assert(SubNum < getNumSubscripts() && "Invalid subscript number");
60     return Subscripts[SubNum];
61   }
62   const SCEV *getFirstSubscript() const {
63     assert(!Subscripts.empty() && "Expecting non-empty container");
64     return Subscripts.front();
65   }
66   const SCEV *getLastSubscript() const {
67     assert(!Subscripts.empty() && "Expecting non-empty container");
68     return Subscripts.back();
69   }
70 
71   /// Return true/false if the current object and the indexed reference \p Other
72   /// are/aren't in the same cache line of size \p CLS. Two references are in
73   /// the same chace line iff the distance between them in the innermost
74   /// dimension is less than the cache line size. Return None if unsure.
75   Optional<bool> hasSpacialReuse(const IndexedReference &Other, unsigned CLS,
76                                  AAResults &AA) const;
77 
78   /// Return true if the current object and the indexed reference \p Other
79   /// have distance smaller than \p MaxDistance in the dimension associated with
80   /// the given loop \p L. Return false if the distance is not smaller than \p
81   /// MaxDistance and None if unsure.
82   Optional<bool> hasTemporalReuse(const IndexedReference &Other,
83                                   unsigned MaxDistance, const Loop &L,
84                                   DependenceInfo &DI, AAResults &AA) const;
85 
86   /// Compute the cost of the reference w.r.t. the given loop \p L when it is
87   /// considered in the innermost position in the loop nest.
88   /// The cost is defined as:
89   ///   - equal to one if the reference is loop invariant, or
90   ///   - equal to '(TripCount * stride) / cache_line_size' if:
91   ///     + the reference stride is less than the cache line size, and
92   ///     + the coefficient of this loop's index variable used in all other
93   ///       subscripts is zero
94   ///   - or otherwise equal to 'TripCount'.
95   CacheCostTy computeRefCost(const Loop &L, unsigned CLS) const;
96 
97 private:
98   /// Attempt to delinearize the indexed reference.
99   bool delinearize(const LoopInfo &LI);
100 
101   /// Attempt to delinearize \p AccessFn for fixed-size arrays.
102   bool tryDelinearizeFixedSize(const SCEV *AccessFn,
103                                SmallVectorImpl<const SCEV *> &Subscripts);
104 
105   /// Return true if the index reference is invariant with respect to loop \p L.
106   bool isLoopInvariant(const Loop &L) const;
107 
108   /// Return true if the indexed reference is 'consecutive' in loop \p L.
109   /// An indexed reference is 'consecutive' if the only coefficient that uses
110   /// the loop induction variable is the rightmost one, and the access stride is
111   /// smaller than the cache line size \p CLS. Provide a valid \p Stride value
112   /// if the indexed reference is 'consecutive'.
113   bool isConsecutive(const Loop &L, const SCEV *&Stride, unsigned CLS) const;
114 
115   /// Retrieve the index of the subscript corresponding to the given loop \p
116   /// L. Return a zero-based positive index if the subscript index is
117   /// succesfully located and a negative value otherwise. For example given the
118   /// indexed reference 'A[i][2j+1][3k+2]', the call
119   /// 'getSubscriptIndex(loop-k)' would return value 2.
120   int getSubscriptIndex(const Loop &L) const;
121 
122   /// Return the coefficient used in the rightmost dimension.
123   const SCEV *getLastCoefficient() const;
124 
125   /// Return true if the coefficient corresponding to induction variable of
126   /// loop \p L in the given \p Subscript is zero or is loop invariant in \p L.
127   bool isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
128                                      const Loop &L) const;
129 
130   /// Verify that the given \p Subscript is 'well formed' (must be a simple add
131   /// recurrence).
132   bool isSimpleAddRecurrence(const SCEV &Subscript, const Loop &L) const;
133 
134   /// Return true if the given reference \p Other is definetely aliased with
135   /// the indexed reference represented by this class.
136   bool isAliased(const IndexedReference &Other, AAResults &AA) const;
137 
138 private:
139   /// True if the reference can be delinearized, false otherwise.
140   bool IsValid = false;
141 
142   /// Represent the memory reference instruction.
143   Instruction &StoreOrLoadInst;
144 
145   /// The base pointer of the memory reference.
146   const SCEV *BasePointer = nullptr;
147 
148   /// The subscript (indexes) of the memory reference.
149   SmallVector<const SCEV *, 3> Subscripts;
150 
151   /// The dimensions of the memory reference.
152   SmallVector<const SCEV *, 3> Sizes;
153 
154   ScalarEvolution &SE;
155 };
156 
157 /// A reference group represents a set of memory references that exhibit
158 /// temporal or spacial reuse. Two references belong to the same
159 /// reference group with respect to a inner loop L iff:
160 /// 1. they have a loop independent dependency, or
161 /// 2. they have a loop carried dependence with a small dependence distance
162 ///    (e.g. less than 2) carried by the inner loop, or
163 /// 3. they refer to the same array, and the subscript in their innermost
164 ///    dimension is less than or equal to 'd' (where 'd' is less than the cache
165 ///    line size)
166 ///
167 /// Intuitively a reference group represents memory references that access
168 /// the same cache line. Conditions 1,2 above account for temporal reuse, while
169 /// contition 3 accounts for spacial reuse.
170 using ReferenceGroupTy = SmallVector<std::unique_ptr<IndexedReference>, 8>;
171 using ReferenceGroupsTy = SmallVector<ReferenceGroupTy, 8>;
172 
173 /// \c CacheCost represents the estimated cost of a inner loop as the number of
174 /// cache lines used by the memory references it contains.
175 /// The 'cache cost' of a loop 'L' in a loop nest 'LN' is computed as the sum of
176 /// the cache costs of all of its reference groups when the loop is considered
177 /// to be in the innermost position in the nest.
178 /// A reference group represents memory references that fall into the same cache
179 /// line. Each reference group is analysed with respect to the innermost loop in
180 /// a loop nest. The cost of a reference is defined as follow:
181 ///  - one if it is loop invariant w.r.t the innermost loop,
182 ///  - equal to the loop trip count divided by the cache line times the
183 ///    reference stride if the reference stride is less than the cache line
184 ///    size (CLS), and the coefficient of this loop's index variable used in all
185 ///    other subscripts is zero (e.g. RefCost = TripCount/(CLS/RefStride))
186 ///  - equal to the innermost loop trip count if the reference stride is greater
187 ///    or equal to the cache line size CLS.
188 class CacheCost {
189   friend raw_ostream &operator<<(raw_ostream &OS, const CacheCost &CC);
190   using LoopTripCountTy = std::pair<const Loop *, unsigned>;
191   using LoopCacheCostTy = std::pair<const Loop *, CacheCostTy>;
192 
193 public:
194   static CacheCostTy constexpr InvalidCost = -1;
195 
196   /// Construct a CacheCost object for the loop nest described by \p Loops.
197   /// The optional parameter \p TRT can be used to specify the max. distance
198   /// between array elements accessed in a loop so that the elements are
199   /// classified to have temporal reuse.
200   CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI, ScalarEvolution &SE,
201             TargetTransformInfo &TTI, AAResults &AA, DependenceInfo &DI,
202             Optional<unsigned> TRT = None);
203 
204   /// Create a CacheCost for the loop nest rooted by \p Root.
205   /// The optional parameter \p TRT can be used to specify the max. distance
206   /// between array elements accessed in a loop so that the elements are
207   /// classified to have temporal reuse.
208   static std::unique_ptr<CacheCost>
209   getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI,
210                Optional<unsigned> TRT = None);
211 
212   /// Return the estimated cost of loop \p L if the given loop is part of the
213   /// loop nest associated with this object. Return -1 otherwise.
214   CacheCostTy getLoopCost(const Loop &L) const {
215     auto IT = llvm::find_if(LoopCosts, [&L](const LoopCacheCostTy &LCC) {
216       return LCC.first == &L;
217     });
218     return (IT != LoopCosts.end()) ? (*IT).second : -1;
219   }
220 
221   /// Return the estimated ordered loop costs.
222   ArrayRef<LoopCacheCostTy> getLoopCosts() const { return LoopCosts; }
223 
224 private:
225   /// Calculate the cache footprint of each loop in the nest (when it is
226   /// considered to be in the innermost position).
227   void calculateCacheFootprint();
228 
229   /// Partition store/load instructions in the loop nest into reference groups.
230   /// Two or more memory accesses belong in the same reference group if they
231   /// share the same cache line.
232   bool populateReferenceGroups(ReferenceGroupsTy &RefGroups) const;
233 
234   /// Calculate the cost of the given loop \p L assuming it is the innermost
235   /// loop in nest.
236   CacheCostTy computeLoopCacheCost(const Loop &L,
237                                    const ReferenceGroupsTy &RefGroups) const;
238 
239   /// Compute the cost of a representative reference in reference group \p RG
240   /// when the given loop \p L is considered as the innermost loop in the nest.
241   /// The computed cost is an estimate for the number of cache lines used by the
242   /// reference group. The representative reference cost is defined as:
243   ///   - equal to one if the reference is loop invariant, or
244   ///   - equal to '(TripCount * stride) / cache_line_size' if (a) loop \p L's
245   ///     induction variable is used only in the reference subscript associated
246   ///     with loop \p L, and (b) the reference stride is less than the cache
247   ///     line size, or
248   ///   - TripCount otherwise
249   CacheCostTy computeRefGroupCacheCost(const ReferenceGroupTy &RG,
250                                        const Loop &L) const;
251 
252   /// Sort the LoopCosts vector by decreasing cache cost.
253   void sortLoopCosts() {
254     stable_sort(LoopCosts,
255                 [](const LoopCacheCostTy &A, const LoopCacheCostTy &B) {
256                   return A.second > B.second;
257                 });
258   }
259 
260 private:
261   /// Loops in the loop nest associated with this object.
262   LoopVectorTy Loops;
263 
264   /// Trip counts for the loops in the loop nest associated with this object.
265   SmallVector<LoopTripCountTy, 3> TripCounts;
266 
267   /// Cache costs for the loops in the loop nest associated with this object.
268   SmallVector<LoopCacheCostTy, 3> LoopCosts;
269 
270   /// The max. distance between array elements accessed in a loop so that the
271   /// elements are classified to have temporal reuse.
272   Optional<unsigned> TRT;
273 
274   const LoopInfo &LI;
275   ScalarEvolution &SE;
276   TargetTransformInfo &TTI;
277   AAResults &AA;
278   DependenceInfo &DI;
279 };
280 
281 raw_ostream &operator<<(raw_ostream &OS, const IndexedReference &R);
282 raw_ostream &operator<<(raw_ostream &OS, const CacheCost &CC);
283 
284 /// Printer pass for the \c CacheCost results.
285 class LoopCachePrinterPass : public PassInfoMixin<LoopCachePrinterPass> {
286   raw_ostream &OS;
287 
288 public:
289   explicit LoopCachePrinterPass(raw_ostream &OS) : OS(OS) {}
290 
291   PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM,
292                         LoopStandardAnalysisResults &AR, LPMUpdater &U);
293 };
294 
295 } // namespace llvm
296 
297 #endif // LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
298