Coverage Report

Created: 2024-01-17 10:31

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