LoopCacheAnalysis.h 12 KB

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