xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/LoopCacheAnalysis.cpp (revision 3c4ba5f55438f7afd4f4b0b56f88f2bb505fd6a6)
1 //===- LoopCacheAnalysis.cpp - Loop Cache Analysis -------------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6 // See https://llvm.org/LICENSE.txt for license information.
7 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //
9 //===----------------------------------------------------------------------===//
10 ///
11 /// \file
12 /// This file defines the implementation for the loop cache analysis.
13 /// The implementation is largely based on the following paper:
14 ///
15 ///       Compiler Optimizations for Improving Data Locality
16 ///       By: Steve Carr, Katherine S. McKinley, Chau-Wen Tseng
17 ///       http://www.cs.utexas.edu/users/mckinley/papers/asplos-1994.pdf
18 ///
19 /// The general approach taken to estimate the number of cache lines used by the
20 /// memory references in an inner loop is:
21 ///    1. Partition memory references that exhibit temporal or spacial reuse
22 ///       into reference groups.
23 ///    2. For each loop L in the a loop nest LN:
24 ///       a. Compute the cost of the reference group
25 ///       b. Compute the loop cost by summing up the reference groups costs
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/Analysis/LoopCacheAnalysis.h"
29 #include "llvm/ADT/BreadthFirstIterator.h"
30 #include "llvm/ADT/Sequence.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/Delinearization.h"
34 #include "llvm/Analysis/DependenceAnalysis.h"
35 #include "llvm/Analysis/LoopInfo.h"
36 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
37 #include "llvm/Analysis/TargetTransformInfo.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "loop-cache-cost"
44 
45 static cl::opt<unsigned> DefaultTripCount(
46     "default-trip-count", cl::init(100), cl::Hidden,
47     cl::desc("Use this to specify the default trip count of a loop"));
48 
49 // In this analysis two array references are considered to exhibit temporal
50 // reuse if they access either the same memory location, or a memory location
51 // with distance smaller than a configurable threshold.
52 static cl::opt<unsigned> TemporalReuseThreshold(
53     "temporal-reuse-threshold", cl::init(2), cl::Hidden,
54     cl::desc("Use this to specify the max. distance between array elements "
55              "accessed in a loop so that the elements are classified to have "
56              "temporal reuse"));
57 
58 /// Retrieve the innermost loop in the given loop nest \p Loops. It returns a
59 /// nullptr if any loops in the loop vector supplied has more than one sibling.
60 /// The loop vector is expected to contain loops collected in breadth-first
61 /// order.
62 static Loop *getInnerMostLoop(const LoopVectorTy &Loops) {
63   assert(!Loops.empty() && "Expecting a non-empy loop vector");
64 
65   Loop *LastLoop = Loops.back();
66   Loop *ParentLoop = LastLoop->getParentLoop();
67 
68   if (ParentLoop == nullptr) {
69     assert(Loops.size() == 1 && "Expecting a single loop");
70     return LastLoop;
71   }
72 
73   return (llvm::is_sorted(Loops,
74                           [](const Loop *L1, const Loop *L2) {
75                             return L1->getLoopDepth() < L2->getLoopDepth();
76                           }))
77              ? LastLoop
78              : nullptr;
79 }
80 
81 static bool isOneDimensionalArray(const SCEV &AccessFn, const SCEV &ElemSize,
82                                   const Loop &L, ScalarEvolution &SE) {
83   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(&AccessFn);
84   if (!AR || !AR->isAffine())
85     return false;
86 
87   assert(AR->getLoop() && "AR should have a loop");
88 
89   // Check that start and increment are not add recurrences.
90   const SCEV *Start = AR->getStart();
91   const SCEV *Step = AR->getStepRecurrence(SE);
92   if (isa<SCEVAddRecExpr>(Start) || isa<SCEVAddRecExpr>(Step))
93     return false;
94 
95   // Check that start and increment are both invariant in the loop.
96   if (!SE.isLoopInvariant(Start, &L) || !SE.isLoopInvariant(Step, &L))
97     return false;
98 
99   const SCEV *StepRec = AR->getStepRecurrence(SE);
100   if (StepRec && SE.isKnownNegative(StepRec))
101     StepRec = SE.getNegativeSCEV(StepRec);
102 
103   return StepRec == &ElemSize;
104 }
105 
106 /// Compute the trip count for the given loop \p L or assume a default value if
107 /// it is not a compile time constant. Return the SCEV expression for the trip
108 /// count.
109 static const SCEV *computeTripCount(const Loop &L, const SCEV &ElemSize,
110                                     ScalarEvolution &SE) {
111   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(&L);
112   const SCEV *TripCount = (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
113                            isa<SCEVConstant>(BackedgeTakenCount))
114                               ? SE.getTripCountFromExitCount(BackedgeTakenCount)
115                               : nullptr;
116 
117   if (!TripCount) {
118     LLVM_DEBUG(dbgs() << "Trip count of loop " << L.getName()
119                << " could not be computed, using DefaultTripCount\n");
120     TripCount = SE.getConstant(ElemSize.getType(), DefaultTripCount);
121   }
122 
123   return TripCount;
124 }
125 
126 //===----------------------------------------------------------------------===//
127 // IndexedReference implementation
128 //
129 raw_ostream &llvm::operator<<(raw_ostream &OS, const IndexedReference &R) {
130   if (!R.IsValid) {
131     OS << R.StoreOrLoadInst;
132     OS << ", IsValid=false.";
133     return OS;
134   }
135 
136   OS << *R.BasePointer;
137   for (const SCEV *Subscript : R.Subscripts)
138     OS << "[" << *Subscript << "]";
139 
140   OS << ", Sizes: ";
141   for (const SCEV *Size : R.Sizes)
142     OS << "[" << *Size << "]";
143 
144   return OS;
145 }
146 
147 IndexedReference::IndexedReference(Instruction &StoreOrLoadInst,
148                                    const LoopInfo &LI, ScalarEvolution &SE)
149     : StoreOrLoadInst(StoreOrLoadInst), SE(SE) {
150   assert((isa<StoreInst>(StoreOrLoadInst) || isa<LoadInst>(StoreOrLoadInst)) &&
151          "Expecting a load or store instruction");
152 
153   IsValid = delinearize(LI);
154   if (IsValid)
155     LLVM_DEBUG(dbgs().indent(2) << "Succesfully delinearized: " << *this
156                                 << "\n");
157 }
158 
159 Optional<bool> IndexedReference::hasSpacialReuse(const IndexedReference &Other,
160                                                  unsigned CLS,
161                                                  AAResults &AA) const {
162   assert(IsValid && "Expecting a valid reference");
163 
164   if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
165     LLVM_DEBUG(dbgs().indent(2)
166                << "No spacial reuse: different base pointers\n");
167     return false;
168   }
169 
170   unsigned NumSubscripts = getNumSubscripts();
171   if (NumSubscripts != Other.getNumSubscripts()) {
172     LLVM_DEBUG(dbgs().indent(2)
173                << "No spacial reuse: different number of subscripts\n");
174     return false;
175   }
176 
177   // all subscripts must be equal, except the leftmost one (the last one).
178   for (auto SubNum : seq<unsigned>(0, NumSubscripts - 1)) {
179     if (getSubscript(SubNum) != Other.getSubscript(SubNum)) {
180       LLVM_DEBUG(dbgs().indent(2) << "No spacial reuse, different subscripts: "
181                                   << "\n\t" << *getSubscript(SubNum) << "\n\t"
182                                   << *Other.getSubscript(SubNum) << "\n");
183       return false;
184     }
185   }
186 
187   // the difference between the last subscripts must be less than the cache line
188   // size.
189   const SCEV *LastSubscript = getLastSubscript();
190   const SCEV *OtherLastSubscript = Other.getLastSubscript();
191   const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
192       SE.getMinusSCEV(LastSubscript, OtherLastSubscript));
193 
194   if (Diff == nullptr) {
195     LLVM_DEBUG(dbgs().indent(2)
196                << "No spacial reuse, difference between subscript:\n\t"
197                << *LastSubscript << "\n\t" << OtherLastSubscript
198                << "\nis not constant.\n");
199     return None;
200   }
201 
202   bool InSameCacheLine = (Diff->getValue()->getSExtValue() < CLS);
203 
204   LLVM_DEBUG({
205     if (InSameCacheLine)
206       dbgs().indent(2) << "Found spacial reuse.\n";
207     else
208       dbgs().indent(2) << "No spacial reuse.\n";
209   });
210 
211   return InSameCacheLine;
212 }
213 
214 Optional<bool> IndexedReference::hasTemporalReuse(const IndexedReference &Other,
215                                                   unsigned MaxDistance,
216                                                   const Loop &L,
217                                                   DependenceInfo &DI,
218                                                   AAResults &AA) const {
219   assert(IsValid && "Expecting a valid reference");
220 
221   if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
222     LLVM_DEBUG(dbgs().indent(2)
223                << "No temporal reuse: different base pointer\n");
224     return false;
225   }
226 
227   std::unique_ptr<Dependence> D =
228       DI.depends(&StoreOrLoadInst, &Other.StoreOrLoadInst, true);
229 
230   if (D == nullptr) {
231     LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: no dependence\n");
232     return false;
233   }
234 
235   if (D->isLoopIndependent()) {
236     LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
237     return true;
238   }
239 
240   // Check the dependence distance at every loop level. There is temporal reuse
241   // if the distance at the given loop's depth is small (|d| <= MaxDistance) and
242   // it is zero at every other loop level.
243   int LoopDepth = L.getLoopDepth();
244   int Levels = D->getLevels();
245   for (int Level = 1; Level <= Levels; ++Level) {
246     const SCEV *Distance = D->getDistance(Level);
247     const SCEVConstant *SCEVConst = dyn_cast_or_null<SCEVConstant>(Distance);
248 
249     if (SCEVConst == nullptr) {
250       LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: distance unknown\n");
251       return None;
252     }
253 
254     const ConstantInt &CI = *SCEVConst->getValue();
255     if (Level != LoopDepth && !CI.isZero()) {
256       LLVM_DEBUG(dbgs().indent(2)
257                  << "No temporal reuse: distance is not zero at depth=" << Level
258                  << "\n");
259       return false;
260     } else if (Level == LoopDepth && CI.getSExtValue() > MaxDistance) {
261       LLVM_DEBUG(
262           dbgs().indent(2)
263           << "No temporal reuse: distance is greater than MaxDistance at depth="
264           << Level << "\n");
265       return false;
266     }
267   }
268 
269   LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
270   return true;
271 }
272 
273 CacheCostTy IndexedReference::computeRefCost(const Loop &L,
274                                              unsigned CLS) const {
275   assert(IsValid && "Expecting a valid reference");
276   LLVM_DEBUG({
277     dbgs().indent(2) << "Computing cache cost for:\n";
278     dbgs().indent(4) << *this << "\n";
279   });
280 
281   // If the indexed reference is loop invariant the cost is one.
282   if (isLoopInvariant(L)) {
283     LLVM_DEBUG(dbgs().indent(4) << "Reference is loop invariant: RefCost=1\n");
284     return 1;
285   }
286 
287   const SCEV *TripCount = computeTripCount(L, *Sizes.back(), SE);
288   assert(TripCount && "Expecting valid TripCount");
289   LLVM_DEBUG(dbgs() << "TripCount=" << *TripCount << "\n");
290 
291   const SCEV *RefCost = nullptr;
292   const SCEV *Stride = nullptr;
293   if (isConsecutive(L, Stride, CLS)) {
294     // If the indexed reference is 'consecutive' the cost is
295     // (TripCount*Stride)/CLS.
296     assert(Stride != nullptr &&
297            "Stride should not be null for consecutive access!");
298     Type *WiderType = SE.getWiderType(Stride->getType(), TripCount->getType());
299     const SCEV *CacheLineSize = SE.getConstant(WiderType, CLS);
300     Stride = SE.getNoopOrAnyExtend(Stride, WiderType);
301     TripCount = SE.getNoopOrAnyExtend(TripCount, WiderType);
302     const SCEV *Numerator = SE.getMulExpr(Stride, TripCount);
303     RefCost = SE.getUDivExpr(Numerator, CacheLineSize);
304 
305     LLVM_DEBUG(dbgs().indent(4)
306                << "Access is consecutive: RefCost=(TripCount*Stride)/CLS="
307                << *RefCost << "\n");
308   } else {
309     // If the indexed reference is not 'consecutive' the cost is proportional to
310     // the trip count and the depth of the dimension which the subject loop
311     // subscript is accessing. We try to estimate this by multiplying the cost
312     // by the trip counts of loops corresponding to the inner dimensions. For
313     // example, given the indexed reference 'A[i][j][k]', and assuming the
314     // i-loop is in the innermost position, the cost would be equal to the
315     // iterations of the i-loop multiplied by iterations of the j-loop.
316     RefCost = TripCount;
317 
318     int Index = getSubscriptIndex(L);
319     assert(Index >= 0 && "Cound not locate a valid Index");
320 
321     for (unsigned I = Index + 1; I < getNumSubscripts() - 1; ++I) {
322       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(getSubscript(I));
323       assert(AR && AR->getLoop() && "Expecting valid loop");
324       const SCEV *TripCount =
325           computeTripCount(*AR->getLoop(), *Sizes.back(), SE);
326       Type *WiderType = SE.getWiderType(RefCost->getType(), TripCount->getType());
327       RefCost = SE.getMulExpr(SE.getNoopOrAnyExtend(RefCost, WiderType),
328                               SE.getNoopOrAnyExtend(TripCount, WiderType));
329     }
330 
331     LLVM_DEBUG(dbgs().indent(4)
332                << "Access is not consecutive: RefCost=" << *RefCost << "\n");
333   }
334   assert(RefCost && "Expecting a valid RefCost");
335 
336   // Attempt to fold RefCost into a constant.
337   if (auto ConstantCost = dyn_cast<SCEVConstant>(RefCost))
338     return ConstantCost->getValue()->getSExtValue();
339 
340   LLVM_DEBUG(dbgs().indent(4)
341              << "RefCost is not a constant! Setting to RefCost=InvalidCost "
342                 "(invalid value).\n");
343 
344   return CacheCost::InvalidCost;
345 }
346 
347 bool IndexedReference::tryDelinearizeFixedSize(
348     const SCEV *AccessFn, SmallVectorImpl<const SCEV *> &Subscripts) {
349   SmallVector<int, 4> ArraySizes;
350   if (!tryDelinearizeFixedSizeImpl(&SE, &StoreOrLoadInst, AccessFn, Subscripts,
351                                    ArraySizes))
352     return false;
353 
354   // Populate Sizes with scev expressions to be used in calculations later.
355   for (auto Idx : seq<unsigned>(1, Subscripts.size()))
356     Sizes.push_back(
357         SE.getConstant(Subscripts[Idx]->getType(), ArraySizes[Idx - 1]));
358 
359   LLVM_DEBUG({
360     dbgs() << "Delinearized subscripts of fixed-size array\n"
361            << "GEP:" << *getLoadStorePointerOperand(&StoreOrLoadInst)
362            << "\n";
363   });
364   return true;
365 }
366 
367 bool IndexedReference::delinearize(const LoopInfo &LI) {
368   assert(Subscripts.empty() && "Subscripts should be empty");
369   assert(Sizes.empty() && "Sizes should be empty");
370   assert(!IsValid && "Should be called once from the constructor");
371   LLVM_DEBUG(dbgs() << "Delinearizing: " << StoreOrLoadInst << "\n");
372 
373   const SCEV *ElemSize = SE.getElementSize(&StoreOrLoadInst);
374   const BasicBlock *BB = StoreOrLoadInst.getParent();
375 
376   if (Loop *L = LI.getLoopFor(BB)) {
377     const SCEV *AccessFn =
378         SE.getSCEVAtScope(getPointerOperand(&StoreOrLoadInst), L);
379 
380     BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFn));
381     if (BasePointer == nullptr) {
382       LLVM_DEBUG(
383           dbgs().indent(2)
384           << "ERROR: failed to delinearize, can't identify base pointer\n");
385       return false;
386     }
387 
388     bool IsFixedSize = false;
389     // Try to delinearize fixed-size arrays.
390     if (tryDelinearizeFixedSize(AccessFn, Subscripts)) {
391       IsFixedSize = true;
392       // The last element of Sizes is the element size.
393       Sizes.push_back(ElemSize);
394       LLVM_DEBUG(dbgs().indent(2) << "In Loop '" << L->getName()
395                                   << "', AccessFn: " << *AccessFn << "\n");
396     }
397 
398     AccessFn = SE.getMinusSCEV(AccessFn, BasePointer);
399 
400     // Try to delinearize parametric-size arrays.
401     if (!IsFixedSize) {
402       LLVM_DEBUG(dbgs().indent(2) << "In Loop '" << L->getName()
403                                   << "', AccessFn: " << *AccessFn << "\n");
404       llvm::delinearize(SE, AccessFn, Subscripts, Sizes,
405                         SE.getElementSize(&StoreOrLoadInst));
406     }
407 
408     if (Subscripts.empty() || Sizes.empty() ||
409         Subscripts.size() != Sizes.size()) {
410       // Attempt to determine whether we have a single dimensional array access.
411       // before giving up.
412       if (!isOneDimensionalArray(*AccessFn, *ElemSize, *L, SE)) {
413         LLVM_DEBUG(dbgs().indent(2)
414                    << "ERROR: failed to delinearize reference\n");
415         Subscripts.clear();
416         Sizes.clear();
417         return false;
418       }
419 
420       // The array may be accessed in reverse, for example:
421       //   for (i = N; i > 0; i--)
422       //     A[i] = 0;
423       // In this case, reconstruct the access function using the absolute value
424       // of the step recurrence.
425       const SCEVAddRecExpr *AccessFnAR = dyn_cast<SCEVAddRecExpr>(AccessFn);
426       const SCEV *StepRec = AccessFnAR ? AccessFnAR->getStepRecurrence(SE) : nullptr;
427 
428       if (StepRec && SE.isKnownNegative(StepRec))
429         AccessFn = SE.getAddRecExpr(AccessFnAR->getStart(),
430                                     SE.getNegativeSCEV(StepRec),
431                                     AccessFnAR->getLoop(),
432                                     AccessFnAR->getNoWrapFlags());
433       const SCEV *Div = SE.getUDivExactExpr(AccessFn, ElemSize);
434       Subscripts.push_back(Div);
435       Sizes.push_back(ElemSize);
436     }
437 
438     return all_of(Subscripts, [&](const SCEV *Subscript) {
439       return isSimpleAddRecurrence(*Subscript, *L);
440     });
441   }
442 
443   return false;
444 }
445 
446 bool IndexedReference::isLoopInvariant(const Loop &L) const {
447   Value *Addr = getPointerOperand(&StoreOrLoadInst);
448   assert(Addr != nullptr && "Expecting either a load or a store instruction");
449   assert(SE.isSCEVable(Addr->getType()) && "Addr should be SCEVable");
450 
451   if (SE.isLoopInvariant(SE.getSCEV(Addr), &L))
452     return true;
453 
454   // The indexed reference is loop invariant if none of the coefficients use
455   // the loop induction variable.
456   bool allCoeffForLoopAreZero = all_of(Subscripts, [&](const SCEV *Subscript) {
457     return isCoeffForLoopZeroOrInvariant(*Subscript, L);
458   });
459 
460   return allCoeffForLoopAreZero;
461 }
462 
463 bool IndexedReference::isConsecutive(const Loop &L, const SCEV *&Stride,
464                                      unsigned CLS) const {
465   // The indexed reference is 'consecutive' if the only coefficient that uses
466   // the loop induction variable is the last one...
467   const SCEV *LastSubscript = Subscripts.back();
468   for (const SCEV *Subscript : Subscripts) {
469     if (Subscript == LastSubscript)
470       continue;
471     if (!isCoeffForLoopZeroOrInvariant(*Subscript, L))
472       return false;
473   }
474 
475   // ...and the access stride is less than the cache line size.
476   const SCEV *Coeff = getLastCoefficient();
477   const SCEV *ElemSize = Sizes.back();
478   Type *WiderType = SE.getWiderType(Coeff->getType(), ElemSize->getType());
479   // FIXME: This assumes that all values are signed integers which may
480   // be incorrect in unusual codes and incorrectly use sext instead of zext.
481   // for (uint32_t i = 0; i < 512; ++i) {
482   //   uint8_t trunc = i;
483   //   A[trunc] = 42;
484   // }
485   // This consecutively iterates twice over A. If `trunc` is sign-extended,
486   // we would conclude that this may iterate backwards over the array.
487   // However, LoopCacheAnalysis is heuristic anyway and transformations must
488   // not result in wrong optimizations if the heuristic was incorrect.
489   Stride = SE.getMulExpr(SE.getNoopOrSignExtend(Coeff, WiderType),
490                          SE.getNoopOrSignExtend(ElemSize, WiderType));
491   const SCEV *CacheLineSize = SE.getConstant(Stride->getType(), CLS);
492 
493   Stride = SE.isKnownNegative(Stride) ? SE.getNegativeSCEV(Stride) : Stride;
494   return SE.isKnownPredicate(ICmpInst::ICMP_ULT, Stride, CacheLineSize);
495 }
496 
497 int IndexedReference::getSubscriptIndex(const Loop &L) const {
498   for (auto Idx : seq<int>(0, getNumSubscripts())) {
499     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(getSubscript(Idx));
500     if (AR && AR->getLoop() == &L) {
501       return Idx;
502     }
503   }
504   return -1;
505 }
506 
507 const SCEV *IndexedReference::getLastCoefficient() const {
508   const SCEV *LastSubscript = getLastSubscript();
509   auto *AR = cast<SCEVAddRecExpr>(LastSubscript);
510   return AR->getStepRecurrence(SE);
511 }
512 
513 bool IndexedReference::isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
514                                                      const Loop &L) const {
515   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(&Subscript);
516   return (AR != nullptr) ? AR->getLoop() != &L
517                          : SE.isLoopInvariant(&Subscript, &L);
518 }
519 
520 bool IndexedReference::isSimpleAddRecurrence(const SCEV &Subscript,
521                                              const Loop &L) const {
522   if (!isa<SCEVAddRecExpr>(Subscript))
523     return false;
524 
525   const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(&Subscript);
526   assert(AR->getLoop() && "AR should have a loop");
527 
528   if (!AR->isAffine())
529     return false;
530 
531   const SCEV *Start = AR->getStart();
532   const SCEV *Step = AR->getStepRecurrence(SE);
533 
534   if (!SE.isLoopInvariant(Start, &L) || !SE.isLoopInvariant(Step, &L))
535     return false;
536 
537   return true;
538 }
539 
540 bool IndexedReference::isAliased(const IndexedReference &Other,
541                                  AAResults &AA) const {
542   const auto &Loc1 = MemoryLocation::get(&StoreOrLoadInst);
543   const auto &Loc2 = MemoryLocation::get(&Other.StoreOrLoadInst);
544   return AA.isMustAlias(Loc1, Loc2);
545 }
546 
547 //===----------------------------------------------------------------------===//
548 // CacheCost implementation
549 //
550 raw_ostream &llvm::operator<<(raw_ostream &OS, const CacheCost &CC) {
551   for (const auto &LC : CC.LoopCosts) {
552     const Loop *L = LC.first;
553     OS << "Loop '" << L->getName() << "' has cost = " << LC.second << "\n";
554   }
555   return OS;
556 }
557 
558 CacheCost::CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI,
559                      ScalarEvolution &SE, TargetTransformInfo &TTI,
560                      AAResults &AA, DependenceInfo &DI, Optional<unsigned> TRT)
561     : Loops(Loops),
562       TRT((TRT == None) ? Optional<unsigned>(TemporalReuseThreshold) : TRT),
563       LI(LI), SE(SE), TTI(TTI), AA(AA), DI(DI) {
564   assert(!Loops.empty() && "Expecting a non-empty loop vector.");
565 
566   for (const Loop *L : Loops) {
567     unsigned TripCount = SE.getSmallConstantTripCount(L);
568     TripCount = (TripCount == 0) ? DefaultTripCount : TripCount;
569     TripCounts.push_back({L, TripCount});
570   }
571 
572   calculateCacheFootprint();
573 }
574 
575 std::unique_ptr<CacheCost>
576 CacheCost::getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR,
577                         DependenceInfo &DI, Optional<unsigned> TRT) {
578   if (!Root.isOutermost()) {
579     LLVM_DEBUG(dbgs() << "Expecting the outermost loop in a loop nest\n");
580     return nullptr;
581   }
582 
583   LoopVectorTy Loops;
584   append_range(Loops, breadth_first(&Root));
585 
586   if (!getInnerMostLoop(Loops)) {
587     LLVM_DEBUG(dbgs() << "Cannot compute cache cost of loop nest with more "
588                          "than one innermost loop\n");
589     return nullptr;
590   }
591 
592   return std::make_unique<CacheCost>(Loops, AR.LI, AR.SE, AR.TTI, AR.AA, DI, TRT);
593 }
594 
595 void CacheCost::calculateCacheFootprint() {
596   LLVM_DEBUG(dbgs() << "POPULATING REFERENCE GROUPS\n");
597   ReferenceGroupsTy RefGroups;
598   if (!populateReferenceGroups(RefGroups))
599     return;
600 
601   LLVM_DEBUG(dbgs() << "COMPUTING LOOP CACHE COSTS\n");
602   for (const Loop *L : Loops) {
603     assert(llvm::none_of(
604                LoopCosts,
605                [L](const LoopCacheCostTy &LCC) { return LCC.first == L; }) &&
606            "Should not add duplicate element");
607     CacheCostTy LoopCost = computeLoopCacheCost(*L, RefGroups);
608     LoopCosts.push_back(std::make_pair(L, LoopCost));
609   }
610 
611   sortLoopCosts();
612   RefGroups.clear();
613 }
614 
615 bool CacheCost::populateReferenceGroups(ReferenceGroupsTy &RefGroups) const {
616   assert(RefGroups.empty() && "Reference groups should be empty");
617 
618   unsigned CLS = TTI.getCacheLineSize();
619   Loop *InnerMostLoop = getInnerMostLoop(Loops);
620   assert(InnerMostLoop != nullptr && "Expecting a valid innermost loop");
621 
622   for (BasicBlock *BB : InnerMostLoop->getBlocks()) {
623     for (Instruction &I : *BB) {
624       if (!isa<StoreInst>(I) && !isa<LoadInst>(I))
625         continue;
626 
627       std::unique_ptr<IndexedReference> R(new IndexedReference(I, LI, SE));
628       if (!R->isValid())
629         continue;
630 
631       bool Added = false;
632       for (ReferenceGroupTy &RefGroup : RefGroups) {
633         const IndexedReference &Representative = *RefGroup.front();
634         LLVM_DEBUG({
635           dbgs() << "References:\n";
636           dbgs().indent(2) << *R << "\n";
637           dbgs().indent(2) << Representative << "\n";
638         });
639 
640 
641        // FIXME: Both positive and negative access functions will be placed
642        // into the same reference group, resulting in a bi-directional array
643        // access such as:
644        //   for (i = N; i > 0; i--)
645        //     A[i] = A[N - i];
646        // having the same cost calculation as a single dimention access pattern
647        //   for (i = 0; i < N; i++)
648        //     A[i] = A[i];
649        // when in actuality, depending on the array size, the first example
650        // should have a cost closer to 2x the second due to the two cache
651        // access per iteration from opposite ends of the array
652         Optional<bool> HasTemporalReuse =
653             R->hasTemporalReuse(Representative, *TRT, *InnerMostLoop, DI, AA);
654         Optional<bool> HasSpacialReuse =
655             R->hasSpacialReuse(Representative, CLS, AA);
656 
657         if ((HasTemporalReuse && *HasTemporalReuse) ||
658             (HasSpacialReuse && *HasSpacialReuse)) {
659           RefGroup.push_back(std::move(R));
660           Added = true;
661           break;
662         }
663       }
664 
665       if (!Added) {
666         ReferenceGroupTy RG;
667         RG.push_back(std::move(R));
668         RefGroups.push_back(std::move(RG));
669       }
670     }
671   }
672 
673   if (RefGroups.empty())
674     return false;
675 
676   LLVM_DEBUG({
677     dbgs() << "\nIDENTIFIED REFERENCE GROUPS:\n";
678     int n = 1;
679     for (const ReferenceGroupTy &RG : RefGroups) {
680       dbgs().indent(2) << "RefGroup " << n << ":\n";
681       for (const auto &IR : RG)
682         dbgs().indent(4) << *IR << "\n";
683       n++;
684     }
685     dbgs() << "\n";
686   });
687 
688   return true;
689 }
690 
691 CacheCostTy
692 CacheCost::computeLoopCacheCost(const Loop &L,
693                                 const ReferenceGroupsTy &RefGroups) const {
694   if (!L.isLoopSimplifyForm())
695     return InvalidCost;
696 
697   LLVM_DEBUG(dbgs() << "Considering loop '" << L.getName()
698                     << "' as innermost loop.\n");
699 
700   // Compute the product of the trip counts of each other loop in the nest.
701   CacheCostTy TripCountsProduct = 1;
702   for (const auto &TC : TripCounts) {
703     if (TC.first == &L)
704       continue;
705     TripCountsProduct *= TC.second;
706   }
707 
708   CacheCostTy LoopCost = 0;
709   for (const ReferenceGroupTy &RG : RefGroups) {
710     CacheCostTy RefGroupCost = computeRefGroupCacheCost(RG, L);
711     LoopCost += RefGroupCost * TripCountsProduct;
712   }
713 
714   LLVM_DEBUG(dbgs().indent(2) << "Loop '" << L.getName()
715                               << "' has cost=" << LoopCost << "\n");
716 
717   return LoopCost;
718 }
719 
720 CacheCostTy CacheCost::computeRefGroupCacheCost(const ReferenceGroupTy &RG,
721                                                 const Loop &L) const {
722   assert(!RG.empty() && "Reference group should have at least one member.");
723 
724   const IndexedReference *Representative = RG.front().get();
725   return Representative->computeRefCost(L, TTI.getCacheLineSize());
726 }
727 
728 //===----------------------------------------------------------------------===//
729 // LoopCachePrinterPass implementation
730 //
731 PreservedAnalyses LoopCachePrinterPass::run(Loop &L, LoopAnalysisManager &AM,
732                                             LoopStandardAnalysisResults &AR,
733                                             LPMUpdater &U) {
734   Function *F = L.getHeader()->getParent();
735   DependenceInfo DI(F, &AR.AA, &AR.SE, &AR.LI);
736 
737   if (auto CC = CacheCost::getCacheCost(L, AR, DI))
738     OS << *CC;
739 
740   return PreservedAnalyses::all();
741 }
742