xref: /llvm-project/llvm/lib/Analysis/LoopCacheAnalysis.cpp (revision c428a3d2a09e2d144911290920b1fa59953d7898)
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. Return the SCEV expression
107 /// for the trip count or nullptr if it cannot be computed.
108 static const SCEV *computeTripCount(const Loop &L, ScalarEvolution &SE) {
109   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(&L);
110   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
111       !isa<SCEVConstant>(BackedgeTakenCount))
112     return nullptr;
113   return SE.getTripCountFromExitCount(BackedgeTakenCount);
114 }
115 
116 //===----------------------------------------------------------------------===//
117 // IndexedReference implementation
118 //
119 raw_ostream &llvm::operator<<(raw_ostream &OS, const IndexedReference &R) {
120   if (!R.IsValid) {
121     OS << R.StoreOrLoadInst;
122     OS << ", IsValid=false.";
123     return OS;
124   }
125 
126   OS << *R.BasePointer;
127   for (const SCEV *Subscript : R.Subscripts)
128     OS << "[" << *Subscript << "]";
129 
130   OS << ", Sizes: ";
131   for (const SCEV *Size : R.Sizes)
132     OS << "[" << *Size << "]";
133 
134   return OS;
135 }
136 
137 IndexedReference::IndexedReference(Instruction &StoreOrLoadInst,
138                                    const LoopInfo &LI, ScalarEvolution &SE)
139     : StoreOrLoadInst(StoreOrLoadInst), SE(SE) {
140   assert((isa<StoreInst>(StoreOrLoadInst) || isa<LoadInst>(StoreOrLoadInst)) &&
141          "Expecting a load or store instruction");
142 
143   IsValid = delinearize(LI);
144   if (IsValid)
145     LLVM_DEBUG(dbgs().indent(2) << "Succesfully delinearized: " << *this
146                                 << "\n");
147 }
148 
149 Optional<bool> IndexedReference::hasSpacialReuse(const IndexedReference &Other,
150                                                  unsigned CLS,
151                                                  AAResults &AA) const {
152   assert(IsValid && "Expecting a valid reference");
153 
154   if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
155     LLVM_DEBUG(dbgs().indent(2)
156                << "No spacial reuse: different base pointers\n");
157     return false;
158   }
159 
160   unsigned NumSubscripts = getNumSubscripts();
161   if (NumSubscripts != Other.getNumSubscripts()) {
162     LLVM_DEBUG(dbgs().indent(2)
163                << "No spacial reuse: different number of subscripts\n");
164     return false;
165   }
166 
167   // all subscripts must be equal, except the leftmost one (the last one).
168   for (auto SubNum : seq<unsigned>(0, NumSubscripts - 1)) {
169     if (getSubscript(SubNum) != Other.getSubscript(SubNum)) {
170       LLVM_DEBUG(dbgs().indent(2) << "No spacial reuse, different subscripts: "
171                                   << "\n\t" << *getSubscript(SubNum) << "\n\t"
172                                   << *Other.getSubscript(SubNum) << "\n");
173       return false;
174     }
175   }
176 
177   // the difference between the last subscripts must be less than the cache line
178   // size.
179   const SCEV *LastSubscript = getLastSubscript();
180   const SCEV *OtherLastSubscript = Other.getLastSubscript();
181   const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
182       SE.getMinusSCEV(LastSubscript, OtherLastSubscript));
183 
184   if (Diff == nullptr) {
185     LLVM_DEBUG(dbgs().indent(2)
186                << "No spacial reuse, difference between subscript:\n\t"
187                << *LastSubscript << "\n\t" << OtherLastSubscript
188                << "\nis not constant.\n");
189     return None;
190   }
191 
192   bool InSameCacheLine = (Diff->getValue()->getSExtValue() < CLS);
193 
194   LLVM_DEBUG({
195     if (InSameCacheLine)
196       dbgs().indent(2) << "Found spacial reuse.\n";
197     else
198       dbgs().indent(2) << "No spacial reuse.\n";
199   });
200 
201   return InSameCacheLine;
202 }
203 
204 Optional<bool> IndexedReference::hasTemporalReuse(const IndexedReference &Other,
205                                                   unsigned MaxDistance,
206                                                   const Loop &L,
207                                                   DependenceInfo &DI,
208                                                   AAResults &AA) const {
209   assert(IsValid && "Expecting a valid reference");
210 
211   if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
212     LLVM_DEBUG(dbgs().indent(2)
213                << "No temporal reuse: different base pointer\n");
214     return false;
215   }
216 
217   std::unique_ptr<Dependence> D =
218       DI.depends(&StoreOrLoadInst, &Other.StoreOrLoadInst, true);
219 
220   if (D == nullptr) {
221     LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: no dependence\n");
222     return false;
223   }
224 
225   if (D->isLoopIndependent()) {
226     LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
227     return true;
228   }
229 
230   // Check the dependence distance at every loop level. There is temporal reuse
231   // if the distance at the given loop's depth is small (|d| <= MaxDistance) and
232   // it is zero at every other loop level.
233   int LoopDepth = L.getLoopDepth();
234   int Levels = D->getLevels();
235   for (int Level = 1; Level <= Levels; ++Level) {
236     const SCEV *Distance = D->getDistance(Level);
237     const SCEVConstant *SCEVConst = dyn_cast_or_null<SCEVConstant>(Distance);
238 
239     if (SCEVConst == nullptr) {
240       LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: distance unknown\n");
241       return None;
242     }
243 
244     const ConstantInt &CI = *SCEVConst->getValue();
245     if (Level != LoopDepth && !CI.isZero()) {
246       LLVM_DEBUG(dbgs().indent(2)
247                  << "No temporal reuse: distance is not zero at depth=" << Level
248                  << "\n");
249       return false;
250     } else if (Level == LoopDepth && CI.getSExtValue() > MaxDistance) {
251       LLVM_DEBUG(
252           dbgs().indent(2)
253           << "No temporal reuse: distance is greater than MaxDistance at depth="
254           << Level << "\n");
255       return false;
256     }
257   }
258 
259   LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
260   return true;
261 }
262 
263 CacheCostTy IndexedReference::computeRefCost(const Loop &L,
264                                              unsigned CLS) const {
265   assert(IsValid && "Expecting a valid reference");
266   LLVM_DEBUG({
267     dbgs().indent(2) << "Computing cache cost for:\n";
268     dbgs().indent(4) << *this << "\n";
269   });
270 
271   // If the indexed reference is loop invariant the cost is one.
272   if (isLoopInvariant(L)) {
273     LLVM_DEBUG(dbgs().indent(4) << "Reference is loop invariant: RefCost=1\n");
274     return 1;
275   }
276 
277   const SCEV *TripCount = computeTripCount(L, SE);
278   if (!TripCount) {
279     LLVM_DEBUG(dbgs() << "Trip count of loop " << L.getName()
280                       << " could not be computed, using DefaultTripCount\n");
281     const SCEV *ElemSize = Sizes.back();
282     TripCount = SE.getConstant(ElemSize->getType(), DefaultTripCount);
283   }
284   LLVM_DEBUG(dbgs() << "TripCount=" << *TripCount << "\n");
285 
286   // If the indexed reference is 'consecutive' the cost is
287   // (TripCount*Stride)/CLS, otherwise the cost is TripCount.
288   const SCEV *RefCost = TripCount;
289 
290   if (isConsecutive(L, CLS)) {
291     const SCEV *Coeff = getLastCoefficient();
292     const SCEV *ElemSize = Sizes.back();
293     const SCEV *Stride = SE.getMulExpr(Coeff, ElemSize);
294     Type *WiderType = SE.getWiderType(Stride->getType(), TripCount->getType());
295     const SCEV *CacheLineSize = SE.getConstant(WiderType, CLS);
296     if (SE.isKnownNegative(Stride))
297       Stride = SE.getNegativeSCEV(Stride);
298     Stride = SE.getNoopOrAnyExtend(Stride, WiderType);
299     TripCount = SE.getNoopOrAnyExtend(TripCount, WiderType);
300     const SCEV *Numerator = SE.getMulExpr(Stride, TripCount);
301     RefCost = SE.getUDivExpr(Numerator, CacheLineSize);
302 
303     LLVM_DEBUG(dbgs().indent(4)
304                << "Access is consecutive: RefCost=(TripCount*Stride)/CLS="
305                << *RefCost << "\n");
306   } else
307     LLVM_DEBUG(dbgs().indent(4)
308                << "Access is not consecutive: RefCost=TripCount=" << *RefCost
309                << "\n");
310 
311   // Attempt to fold RefCost into a constant.
312   if (auto ConstantCost = dyn_cast<SCEVConstant>(RefCost))
313     return ConstantCost->getValue()->getSExtValue();
314 
315   LLVM_DEBUG(dbgs().indent(4)
316              << "RefCost is not a constant! Setting to RefCost=InvalidCost "
317                 "(invalid value).\n");
318 
319   return CacheCost::InvalidCost;
320 }
321 
322 bool IndexedReference::tryDelinearizeFixedSize(
323     ScalarEvolution *SE, Instruction *Src, const SCEV *SrcAccessFn,
324     SmallVectorImpl<const SCEV *> &SrcSubscripts) {
325   Value *SrcPtr = getLoadStorePointerOperand(Src);
326   const SCEVUnknown *SrcBase =
327       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
328 
329   // Check the simple case where the array dimensions are fixed size.
330   auto *SrcGEP = dyn_cast<GetElementPtrInst>(SrcPtr);
331   if (!SrcGEP)
332     return false;
333 
334   SmallVector<int, 4> SrcSizes;
335   getIndexExpressionsFromGEP(*SE, SrcGEP, SrcSubscripts, SrcSizes);
336 
337   // Check that the two size arrays are non-empty and equal in length and
338   // value.
339   if (SrcSizes.empty() || SrcSubscripts.size() <= 1) {
340     SrcSubscripts.clear();
341     return false;
342   }
343 
344   Value *SrcBasePtr = SrcGEP->getOperand(0)->stripPointerCasts();
345 
346   // Check that for identical base pointers we do not miss index offsets
347   // that have been added before this GEP is applied.
348   if (SrcBasePtr != SrcBase->getValue()) {
349     SrcSubscripts.clear();
350     return false;
351   }
352 
353   assert(SrcSubscripts.size() == SrcSizes.size() + 1 &&
354          "Expected equal number of entries in the list of size and "
355          "subscript.");
356 
357   for (auto Idx : seq<unsigned>(1, Subscripts.size()))
358     Sizes.push_back(SE->getConstant(Subscripts[Idx]->getType(), SrcSizes[Idx - 1]));
359 
360   LLVM_DEBUG({
361     dbgs() << "Delinearized subscripts of fixed-size array\n"
362            << "SrcGEP:" << *SrcGEP << "\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(&SE, &StoreOrLoadInst, AccessFn, Subscripts)) {
391       IsFixedSize = true;
392       /// The last element of \p 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, unsigned CLS) const {
464   // The indexed reference is 'consecutive' if the only coefficient that uses
465   // the loop induction variable is the last one...
466   const SCEV *LastSubscript = Subscripts.back();
467   for (const SCEV *Subscript : Subscripts) {
468     if (Subscript == LastSubscript)
469       continue;
470     if (!isCoeffForLoopZeroOrInvariant(*Subscript, L))
471       return false;
472   }
473 
474   // ...and the access stride is less than the cache line size.
475   const SCEV *Coeff = getLastCoefficient();
476   const SCEV *ElemSize = Sizes.back();
477   const SCEV *Stride = SE.getMulExpr(Coeff, ElemSize);
478   const SCEV *CacheLineSize = SE.getConstant(Stride->getType(), CLS);
479 
480   Stride = SE.isKnownNegative(Stride) ? SE.getNegativeSCEV(Stride) : Stride;
481   return SE.isKnownPredicate(ICmpInst::ICMP_ULT, Stride, CacheLineSize);
482 }
483 
484 const SCEV *IndexedReference::getLastCoefficient() const {
485   const SCEV *LastSubscript = getLastSubscript();
486   auto *AR = cast<SCEVAddRecExpr>(LastSubscript);
487   return AR->getStepRecurrence(SE);
488 }
489 
490 bool IndexedReference::isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
491                                                      const Loop &L) const {
492   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(&Subscript);
493   return (AR != nullptr) ? AR->getLoop() != &L
494                          : SE.isLoopInvariant(&Subscript, &L);
495 }
496 
497 bool IndexedReference::isSimpleAddRecurrence(const SCEV &Subscript,
498                                              const Loop &L) const {
499   if (!isa<SCEVAddRecExpr>(Subscript))
500     return false;
501 
502   const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(&Subscript);
503   assert(AR->getLoop() && "AR should have a loop");
504 
505   if (!AR->isAffine())
506     return false;
507 
508   const SCEV *Start = AR->getStart();
509   const SCEV *Step = AR->getStepRecurrence(SE);
510 
511   if (!SE.isLoopInvariant(Start, &L) || !SE.isLoopInvariant(Step, &L))
512     return false;
513 
514   return true;
515 }
516 
517 bool IndexedReference::isAliased(const IndexedReference &Other,
518                                  AAResults &AA) const {
519   const auto &Loc1 = MemoryLocation::get(&StoreOrLoadInst);
520   const auto &Loc2 = MemoryLocation::get(&Other.StoreOrLoadInst);
521   return AA.isMustAlias(Loc1, Loc2);
522 }
523 
524 //===----------------------------------------------------------------------===//
525 // CacheCost implementation
526 //
527 raw_ostream &llvm::operator<<(raw_ostream &OS, const CacheCost &CC) {
528   for (const auto &LC : CC.LoopCosts) {
529     const Loop *L = LC.first;
530     OS << "Loop '" << L->getName() << "' has cost = " << LC.second << "\n";
531   }
532   return OS;
533 }
534 
535 CacheCost::CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI,
536                      ScalarEvolution &SE, TargetTransformInfo &TTI,
537                      AAResults &AA, DependenceInfo &DI, Optional<unsigned> TRT)
538     : Loops(Loops),
539       TRT((TRT == None) ? Optional<unsigned>(TemporalReuseThreshold) : TRT),
540       LI(LI), SE(SE), TTI(TTI), AA(AA), DI(DI) {
541   assert(!Loops.empty() && "Expecting a non-empty loop vector.");
542 
543   for (const Loop *L : Loops) {
544     unsigned TripCount = SE.getSmallConstantTripCount(L);
545     TripCount = (TripCount == 0) ? DefaultTripCount : TripCount;
546     TripCounts.push_back({L, TripCount});
547   }
548 
549   calculateCacheFootprint();
550 }
551 
552 std::unique_ptr<CacheCost>
553 CacheCost::getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR,
554                         DependenceInfo &DI, Optional<unsigned> TRT) {
555   if (!Root.isOutermost()) {
556     LLVM_DEBUG(dbgs() << "Expecting the outermost loop in a loop nest\n");
557     return nullptr;
558   }
559 
560   LoopVectorTy Loops;
561   append_range(Loops, breadth_first(&Root));
562 
563   if (!getInnerMostLoop(Loops)) {
564     LLVM_DEBUG(dbgs() << "Cannot compute cache cost of loop nest with more "
565                          "than one innermost loop\n");
566     return nullptr;
567   }
568 
569   return std::make_unique<CacheCost>(Loops, AR.LI, AR.SE, AR.TTI, AR.AA, DI, TRT);
570 }
571 
572 void CacheCost::calculateCacheFootprint() {
573   LLVM_DEBUG(dbgs() << "POPULATING REFERENCE GROUPS\n");
574   ReferenceGroupsTy RefGroups;
575   if (!populateReferenceGroups(RefGroups))
576     return;
577 
578   LLVM_DEBUG(dbgs() << "COMPUTING LOOP CACHE COSTS\n");
579   for (const Loop *L : Loops) {
580     assert(llvm::none_of(
581                LoopCosts,
582                [L](const LoopCacheCostTy &LCC) { return LCC.first == L; }) &&
583            "Should not add duplicate element");
584     CacheCostTy LoopCost = computeLoopCacheCost(*L, RefGroups);
585     LoopCosts.push_back(std::make_pair(L, LoopCost));
586   }
587 
588   sortLoopCosts();
589   RefGroups.clear();
590 }
591 
592 bool CacheCost::populateReferenceGroups(ReferenceGroupsTy &RefGroups) const {
593   assert(RefGroups.empty() && "Reference groups should be empty");
594 
595   unsigned CLS = TTI.getCacheLineSize();
596   Loop *InnerMostLoop = getInnerMostLoop(Loops);
597   assert(InnerMostLoop != nullptr && "Expecting a valid innermost loop");
598 
599   for (BasicBlock *BB : InnerMostLoop->getBlocks()) {
600     for (Instruction &I : *BB) {
601       if (!isa<StoreInst>(I) && !isa<LoadInst>(I))
602         continue;
603 
604       std::unique_ptr<IndexedReference> R(new IndexedReference(I, LI, SE));
605       if (!R->isValid())
606         continue;
607 
608       bool Added = false;
609       for (ReferenceGroupTy &RefGroup : RefGroups) {
610         const IndexedReference &Representative = *RefGroup.front();
611         LLVM_DEBUG({
612           dbgs() << "References:\n";
613           dbgs().indent(2) << *R << "\n";
614           dbgs().indent(2) << Representative << "\n";
615         });
616 
617 
618        // FIXME: Both positive and negative access functions will be placed
619        // into the same reference group, resulting in a bi-directional array
620        // access such as:
621        //   for (i = N; i > 0; i--)
622        //     A[i] = A[N - i];
623        // having the same cost calculation as a single dimention access pattern
624        //   for (i = 0; i < N; i++)
625        //     A[i] = A[i];
626        // when in actuality, depending on the array size, the first example
627        // should have a cost closer to 2x the second due to the two cache
628        // access per iteration from opposite ends of the array
629         Optional<bool> HasTemporalReuse =
630             R->hasTemporalReuse(Representative, *TRT, *InnerMostLoop, DI, AA);
631         Optional<bool> HasSpacialReuse =
632             R->hasSpacialReuse(Representative, CLS, AA);
633 
634         if ((HasTemporalReuse.hasValue() && *HasTemporalReuse) ||
635             (HasSpacialReuse.hasValue() && *HasSpacialReuse)) {
636           RefGroup.push_back(std::move(R));
637           Added = true;
638           break;
639         }
640       }
641 
642       if (!Added) {
643         ReferenceGroupTy RG;
644         RG.push_back(std::move(R));
645         RefGroups.push_back(std::move(RG));
646       }
647     }
648   }
649 
650   if (RefGroups.empty())
651     return false;
652 
653   LLVM_DEBUG({
654     dbgs() << "\nIDENTIFIED REFERENCE GROUPS:\n";
655     int n = 1;
656     for (const ReferenceGroupTy &RG : RefGroups) {
657       dbgs().indent(2) << "RefGroup " << n << ":\n";
658       for (const auto &IR : RG)
659         dbgs().indent(4) << *IR << "\n";
660       n++;
661     }
662     dbgs() << "\n";
663   });
664 
665   return true;
666 }
667 
668 CacheCostTy
669 CacheCost::computeLoopCacheCost(const Loop &L,
670                                 const ReferenceGroupsTy &RefGroups) const {
671   if (!L.isLoopSimplifyForm())
672     return InvalidCost;
673 
674   LLVM_DEBUG(dbgs() << "Considering loop '" << L.getName()
675                     << "' as innermost loop.\n");
676 
677   // Compute the product of the trip counts of each other loop in the nest.
678   CacheCostTy TripCountsProduct = 1;
679   for (const auto &TC : TripCounts) {
680     if (TC.first == &L)
681       continue;
682     TripCountsProduct *= TC.second;
683   }
684 
685   CacheCostTy LoopCost = 0;
686   for (const ReferenceGroupTy &RG : RefGroups) {
687     CacheCostTy RefGroupCost = computeRefGroupCacheCost(RG, L);
688     LoopCost += RefGroupCost * TripCountsProduct;
689   }
690 
691   LLVM_DEBUG(dbgs().indent(2) << "Loop '" << L.getName()
692                               << "' has cost=" << LoopCost << "\n");
693 
694   return LoopCost;
695 }
696 
697 CacheCostTy CacheCost::computeRefGroupCacheCost(const ReferenceGroupTy &RG,
698                                                 const Loop &L) const {
699   assert(!RG.empty() && "Reference group should have at least one member.");
700 
701   const IndexedReference *Representative = RG.front().get();
702   return Representative->computeRefCost(L, TTI.getCacheLineSize());
703 }
704 
705 //===----------------------------------------------------------------------===//
706 // LoopCachePrinterPass implementation
707 //
708 PreservedAnalyses LoopCachePrinterPass::run(Loop &L, LoopAnalysisManager &AM,
709                                             LoopStandardAnalysisResults &AR,
710                                             LPMUpdater &U) {
711   Function *F = L.getHeader()->getParent();
712   DependenceInfo DI(F, &AR.AA, &AR.SE, &AR.LI);
713 
714   if (auto CC = CacheCost::getCacheCost(L, AR, DI))
715     OS << *CC;
716 
717   return PreservedAnalyses::all();
718 }
719