LLVM 24.0.0git
LoopCacheAnalysis.cpp
Go to the documentation of this file.
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
29#include "AnalysisOptions.h"
31#include "llvm/ADT/Sequence.h"
39#include "llvm/Support/Debug.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "loop-cache-cost"
44
45/// Retrieve the innermost loop in the given loop nest \p Loops. It returns a
46/// nullptr if any loops in the loop vector supplied has more than one sibling.
47/// The loop vector is expected to contain loops collected in breadth-first
48/// order.
50 assert(!Loops.empty() && "Expecting a non-empy loop vector");
51
52 Loop *LastLoop = Loops.back();
53 Loop *ParentLoop = LastLoop->getParentLoop();
54
55 if (ParentLoop == nullptr) {
56 assert(Loops.size() == 1 && "Expecting a single loop");
57 return LastLoop;
58 }
59
60 return (llvm::is_sorted(Loops,
61 [](const Loop *L1, const Loop *L2) {
62 return L1->getLoopDepth() < L2->getLoopDepth();
63 }))
64 ? LastLoop
65 : nullptr;
66}
67
68static bool isOneDimensionalArray(const SCEV &AccessFn, const SCEV &ElemSize,
69 const Loop &L, ScalarEvolution &SE) {
70 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(&AccessFn);
71 if (!AR || !AR->isAffine())
72 return false;
73
74 assert(AR->getLoop() && "AR should have a loop");
75
76 // Check that start and increment are not add recurrences.
77 const SCEV *Start = AR->getStart();
78 const SCEV *Step = AR->getStepRecurrence(SE);
79 if (isa<SCEVAddRecExpr>(Start) || isa<SCEVAddRecExpr>(Step))
80 return false;
81
82 // Check that start and increment are both invariant in the loop.
83 if (!SE.isLoopInvariant(Start, &L) || !SE.isLoopInvariant(Step, &L))
84 return false;
85
86 const SCEV *StepRec = AR->getStepRecurrence(SE);
87 if (StepRec && SE.isKnownNegative(StepRec))
88 StepRec = SE.getNegativeSCEV(StepRec);
89
90 return StepRec == &ElemSize;
91}
92
93/// Compute the trip count for the given loop \p L or assume a default value if
94/// it is not a compile time constant. Return the SCEV expression for the trip
95/// count.
96static const SCEV *computeTripCount(const Loop &L, const SCEV &ElemSize,
97 ScalarEvolution &SE) {
98 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(&L);
99 const SCEV *TripCount = (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
100 isa<SCEVConstant>(BackedgeTakenCount))
101 ? SE.getTripCountFromExitCount(BackedgeTakenCount)
102 : nullptr;
103
104 if (!TripCount) {
105 LLVM_DEBUG(dbgs() << "Trip count of loop " << L.getName()
106 << " could not be computed, using DefaultTripCount\n");
107 TripCount = SE.getConstant(ElemSize.getType(),
108 getAnalysisOptions(L).default_trip_count);
109 }
110
111 return TripCount;
112}
113
114//===----------------------------------------------------------------------===//
115// IndexedReference implementation
116//
118 if (!R.IsValid) {
119 OS << R.StoreOrLoadInst;
120 OS << ", IsValid=false.";
121 return OS;
122 }
123
124 OS << *R.BasePointer;
125 for (const SCEV *Subscript : R.Subscripts)
126 OS << "[" << *Subscript << "]";
127
128 OS << ", Sizes: ";
129 for (const SCEV *Size : R.Sizes)
130 OS << "[" << *Size << "]";
131
132 return OS;
133}
134
136 const LoopInfo &LI, ScalarEvolution &SE)
137 : StoreOrLoadInst(StoreOrLoadInst), SE(SE) {
138 assert((isa<StoreInst>(StoreOrLoadInst) || isa<LoadInst>(StoreOrLoadInst)) &&
139 "Expecting a load or store instruction");
140
141 IsValid = delinearize(LI);
142 if (IsValid)
143 LLVM_DEBUG(dbgs().indent(2) << "Succesfully delinearized: " << *this
144 << "\n");
145}
146
147std::optional<bool>
149 AAResults &AA) const {
150 assert(IsValid && "Expecting a valid reference");
151
152 if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
154 << "No spacial reuse: different base pointers\n");
155 return false;
156 }
157
158 unsigned NumSubscripts = getNumSubscripts();
159 if (NumSubscripts != Other.getNumSubscripts()) {
161 << "No spacial reuse: different number of subscripts\n");
162 return false;
163 }
164
165 // all subscripts must be equal, except the leftmost one (the last one).
166 for (auto SubNum : seq<unsigned>(0, NumSubscripts - 1)) {
167 if (getSubscript(SubNum) != Other.getSubscript(SubNum)) {
168 LLVM_DEBUG(dbgs().indent(2) << "No spacial reuse, different subscripts: "
169 << "\n\t" << *getSubscript(SubNum) << "\n\t"
170 << *Other.getSubscript(SubNum) << "\n");
171 return false;
172 }
173 }
174
175 // the difference between the last subscripts must be less than the cache line
176 // size.
177 const SCEV *LastSubscript = getLastSubscript();
178 const SCEV *OtherLastSubscript = Other.getLastSubscript();
180 SE.getMinusSCEV(LastSubscript, OtherLastSubscript));
181
182 if (Diff == nullptr) {
184 << "No spacial reuse, difference between subscript:\n\t"
185 << *LastSubscript << "\n\t" << OtherLastSubscript
186 << "\nis not constant.\n");
187 return std::nullopt;
188 }
189
190 bool InSameCacheLine = (Diff->getValue()->getSExtValue() < CLS);
191
192 LLVM_DEBUG({
193 if (InSameCacheLine)
194 dbgs().indent(2) << "Found spacial reuse.\n";
195 else
196 dbgs().indent(2) << "No spacial reuse.\n";
197 });
198
199 return InSameCacheLine;
200}
201
202std::optional<bool>
204 unsigned MaxDistance, const Loop &L,
205 DependenceInfo &DI, AAResults &AA) const {
206 assert(IsValid && "Expecting a valid reference");
207
208 if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
210 << "No temporal reuse: different base pointer\n");
211 return false;
212 }
213
214 std::unique_ptr<Dependence> D =
215 DI.depends(&StoreOrLoadInst, &Other.StoreOrLoadInst);
216
217 if (D == nullptr) {
218 LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: no dependence\n");
219 return false;
220 }
221
222 if (D->isLoopIndependent()) {
223 LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
224 return true;
225 }
226
227 // Check the dependence distance at every loop level. There is temporal reuse
228 // if the distance at the given loop's depth is small (|d| <= MaxDistance) and
229 // it is zero at every other loop level.
230 int LoopDepth = L.getLoopDepth();
231 int Levels = D->getLevels();
232 for (int Level = 1; Level <= Levels; ++Level) {
233 const SCEV *Distance = D->getDistance(Level);
234 const SCEVConstant *SCEVConst = dyn_cast_or_null<SCEVConstant>(Distance);
235
236 if (SCEVConst == nullptr) {
237 LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: distance unknown\n");
238 return std::nullopt;
239 }
240
241 const ConstantInt &CI = *SCEVConst->getValue();
242 if (Level != LoopDepth && !CI.isZero()) {
244 << "No temporal reuse: distance is not zero at depth=" << Level
245 << "\n");
246 return false;
247 } else if (Level == LoopDepth && CI.getSExtValue() > MaxDistance) {
249 dbgs().indent(2)
250 << "No temporal reuse: distance is greater than MaxDistance at depth="
251 << Level << "\n");
252 return false;
253 }
254 }
255
256 LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
257 return true;
258}
259
261 unsigned CLS) const {
262 assert(IsValid && "Expecting a valid reference");
263 LLVM_DEBUG({
264 dbgs().indent(2) << "Computing cache cost for:\n";
265 dbgs().indent(4) << *this << "\n";
266 });
267
268 // If the indexed reference is loop invariant the cost is one.
269 if (isLoopInvariant(L)) {
270 LLVM_DEBUG(dbgs().indent(4) << "Reference is loop invariant: RefCost=1\n");
271 return 1;
272 }
273
274 const SCEV *TripCount = computeTripCount(L, *Sizes.back(), SE);
275 assert(TripCount && "Expecting valid TripCount");
276 LLVM_DEBUG(dbgs() << "TripCount=" << *TripCount << "\n");
277
278 const SCEV *RefCost = nullptr;
279 const SCEV *Stride = nullptr;
280 if (isConsecutive(L, Stride, CLS)) {
281 // If the indexed reference is 'consecutive' the cost is
282 // (TripCount*Stride)/CLS.
283 assert(Stride != nullptr &&
284 "Stride should not be null for consecutive access!");
285 Type *WiderType = SE.getWiderType(Stride->getType(), TripCount->getType());
286 const SCEV *CacheLineSize = SE.getConstant(WiderType, CLS);
287 Stride = SE.getNoopOrAnyExtend(Stride, WiderType);
288 TripCount = SE.getNoopOrZeroExtend(TripCount, WiderType);
289 const SCEV *Numerator = SE.getMulExpr(Stride, TripCount);
290 // Round the fractional cost up to the nearest integer number.
291 // The impact is the most significant when cost is calculated
292 // to be a number less than one, because it makes more sense
293 // to say one cache line is used rather than zero cache line
294 // is used.
295 RefCost = SE.getUDivCeilSCEV(Numerator, CacheLineSize);
296
298 << "Access is consecutive: RefCost=(TripCount*Stride)/CLS="
299 << *RefCost << "\n");
300 } else {
301 // If the indexed reference is not 'consecutive' the cost is proportional to
302 // the trip count and the depth of the dimension which the subject loop
303 // subscript is accessing. We try to estimate this by multiplying the cost
304 // by the trip counts of loops corresponding to the inner dimensions. For
305 // example, given the indexed reference 'A[i][j][k]', and assuming the
306 // i-loop is in the innermost position, the cost would be equal to the
307 // iterations of the i-loop multiplied by iterations of the j-loop.
308 RefCost = TripCount;
309
310 int Index = getSubscriptIndex(L);
311 assert(Index >= 0 && "Could not locate a valid Index");
312
313 for (unsigned I = Index + 1; I < getNumSubscripts() - 1; ++I) {
315 assert(AR && AR->getLoop() && "Expecting valid loop");
316 const SCEV *TripCount =
317 computeTripCount(*AR->getLoop(), *Sizes.back(), SE);
318 Type *WiderType = SE.getWiderType(RefCost->getType(), TripCount->getType());
319 // For the multiplication result to fit, request a type twice as wide.
320 // Bail out if doubling would exceed MAX_INT_BITS.
321 auto *WiderIntTy = cast<IntegerType>(WiderType);
322 if (WiderIntTy->getBitWidth() > IntegerType::MAX_INT_BITS / 2)
324 WiderType = WiderIntTy->getExtendedType();
325 RefCost = SE.getMulExpr(SE.getNoopOrZeroExtend(RefCost, WiderType),
326 SE.getNoopOrZeroExtend(TripCount, WiderType));
327 }
328
330 << "Access is not consecutive: RefCost=" << *RefCost << "\n");
331 }
332 assert(RefCost && "Expecting a valid RefCost");
333
334 // Attempt to fold RefCost into a constant.
335 // CacheCostTy is a signed integer, but the tripcount value can be large
336 // and may not fit, so saturate/limit the value to the maximum signed
337 // integer value.
338 if (auto ConstantCost = dyn_cast<SCEVConstant>(RefCost))
339 return ConstantCost->getValue()->getLimitedValue(
340 std::numeric_limits<int64_t>::max());
341
343 << "RefCost is not a constant! Setting to RefCost=InvalidCost "
344 "(invalid value).\n");
345
347}
348
349bool IndexedReference::delinearize(const LoopInfo &LI) {
350 assert(Subscripts.empty() && "Subscripts should be empty");
351 assert(Sizes.empty() && "Sizes should be empty");
352 assert(!IsValid && "Should be called once from the constructor");
353 LLVM_DEBUG(dbgs() << "Delinearizing: " << StoreOrLoadInst << "\n");
354
355 const SCEV *ElemSize = SE.getElementSize(&StoreOrLoadInst);
356 const BasicBlock *BB = StoreOrLoadInst.getParent();
357
358 if (Loop *L = LI.getLoopFor(BB)) {
359 const SCEV *AccessFn =
360 SE.getSCEVAtScope(getPointerOperand(&StoreOrLoadInst), L);
361
362 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFn));
363 if (BasePointer == nullptr) {
365 dbgs().indent(2)
366 << "ERROR: failed to delinearize, can't identify base pointer\n");
367 return false;
368 }
369
370 bool IsFixedSize = false;
371 AccessFn = SE.getMinusSCEV(AccessFn, BasePointer);
372
373 // Try to delinearize fixed-size arrays.
374 if (delinearizeFixedSizeArray(SE, AccessFn, Subscripts, Sizes, ElemSize)) {
375 IsFixedSize = true;
376 LLVM_DEBUG(dbgs().indent(2) << "In Loop '" << L->getName()
377 << "', AccessFn: " << *AccessFn << "\n");
378 }
379
380 // Try to delinearize parametric-size arrays.
381 if (!IsFixedSize) {
382 LLVM_DEBUG(dbgs().indent(2) << "In Loop '" << L->getName()
383 << "', AccessFn: " << *AccessFn << "\n");
384 Sizes.clear();
385 llvm::delinearize(SE, AccessFn, Subscripts, Sizes,
386 SE.getElementSize(&StoreOrLoadInst));
387 }
388
389 if (Subscripts.empty() || Sizes.empty() ||
390 Subscripts.size() != Sizes.size()) {
391 // Attempt to determine whether we have a single dimensional array access.
392 // before giving up.
393 if (!isOneDimensionalArray(*AccessFn, *ElemSize, *L, SE)) {
394 LLVM_DEBUG(dbgs().indent(2)
395 << "ERROR: failed to delinearize reference\n");
396 Subscripts.clear();
397 Sizes.clear();
398 return false;
399 }
400
401 // The array may be accessed in reverse, for example:
402 // for (i = N; i > 0; i--)
403 // A[i] = 0;
404 // In this case, reconstruct the access function using the absolute value
405 // of the step recurrence.
406 const SCEVAddRecExpr *AccessFnAR = dyn_cast<SCEVAddRecExpr>(AccessFn);
407 const SCEV *StepRec = AccessFnAR ? AccessFnAR->getStepRecurrence(SE) : nullptr;
408
409 if (StepRec && SE.isKnownNegative(StepRec))
410 AccessFn = SE.getAddRecExpr(AccessFnAR->getStart(),
411 SE.getNegativeSCEV(StepRec),
412 AccessFnAR->getLoop(), SCEVFlags::FlagNone);
413 const SCEV *Div = SE.getUDivExactExpr(AccessFn, ElemSize);
414 Subscripts.push_back(Div);
415 Sizes.push_back(ElemSize);
416 }
417
418 return all_of(Subscripts, [&](const SCEV *Subscript) {
419 return isSimpleAddRecurrence(*Subscript, *L);
420 });
421 }
422
423 return false;
424}
425
426bool IndexedReference::isLoopInvariant(const Loop &L) const {
427 Value *Addr = getPointerOperand(&StoreOrLoadInst);
428 assert(Addr != nullptr && "Expecting either a load or a store instruction");
429 assert(SE.isSCEVable(Addr->getType()) && "Addr should be SCEVable");
430
431 if (SE.isLoopInvariant(SE.getSCEV(Addr), &L))
432 return true;
433
434 // The indexed reference is loop invariant if none of the coefficients use
435 // the loop induction variable.
436 bool allCoeffForLoopAreZero = all_of(Subscripts, [&](const SCEV *Subscript) {
437 return isCoeffForLoopZeroOrInvariant(*Subscript, L);
438 });
439
440 return allCoeffForLoopAreZero;
441}
442
443bool IndexedReference::isConsecutive(const Loop &L, const SCEV *&Stride,
444 unsigned CLS) const {
445 // The indexed reference is 'consecutive' if the only coefficient that uses
446 // the loop induction variable is the last one...
447 const SCEV *LastSubscript = Subscripts.back();
448 for (const SCEV *Subscript : Subscripts) {
449 if (Subscript == LastSubscript)
450 continue;
451 if (!isCoeffForLoopZeroOrInvariant(*Subscript, L))
452 return false;
453 }
454
455 // ...and the access stride is less than the cache line size.
456 const SCEV *Coeff = getLastCoefficient();
457 const SCEV *ElemSize = Sizes.back();
458 Type *WiderType = SE.getWiderType(Coeff->getType(), ElemSize->getType());
459 // FIXME: This assumes that all values are signed integers which may
460 // be incorrect in unusual codes and incorrectly use sext instead of zext.
461 // for (uint32_t i = 0; i < 512; ++i) {
462 // uint8_t trunc = i;
463 // A[trunc] = 42;
464 // }
465 // This consecutively iterates twice over A. If `trunc` is sign-extended,
466 // we would conclude that this may iterate backwards over the array.
467 // However, LoopCacheAnalysis is heuristic anyway and transformations must
468 // not result in wrong optimizations if the heuristic was incorrect.
469 Stride = SE.getMulExpr(SE.getNoopOrSignExtend(Coeff, WiderType),
470 SE.getNoopOrSignExtend(ElemSize, WiderType));
471 const SCEV *CacheLineSize = SE.getConstant(Stride->getType(), CLS);
472
473 Stride = SE.isKnownNegative(Stride) ? SE.getNegativeSCEV(Stride) : Stride;
474 return SE.isKnownPredicate(ICmpInst::ICMP_ULT, Stride, CacheLineSize);
475}
476
477int IndexedReference::getSubscriptIndex(const Loop &L) const {
478 for (auto Idx : seq<int>(0, getNumSubscripts())) {
479 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(getSubscript(Idx));
480 if (AR && AR->getLoop() == &L) {
481 return Idx;
482 }
483 }
484 return -1;
485}
486
487const SCEV *IndexedReference::getLastCoefficient() const {
488 const SCEV *LastSubscript = getLastSubscript();
489 auto *AR = cast<SCEVAddRecExpr>(LastSubscript);
490 return AR->getStepRecurrence(SE);
491}
492
493bool IndexedReference::isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
494 const Loop &L) const {
495 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(&Subscript);
496 return (AR != nullptr) ? AR->getLoop() != &L
497 : SE.isLoopInvariant(&Subscript, &L);
498}
499
500bool IndexedReference::isSimpleAddRecurrence(const SCEV &Subscript,
501 const Loop &L) const {
502 if (!isa<SCEVAddRecExpr>(Subscript))
503 return false;
504
505 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(&Subscript);
506 assert(AR->getLoop() && "AR should have a loop");
507
508 if (!AR->isAffine())
509 return false;
510
511 const SCEV *Start = AR->getStart();
512 const SCEV *Step = AR->getStepRecurrence(SE);
513
514 if (!SE.isLoopInvariant(Start, &L) || !SE.isLoopInvariant(Step, &L))
515 return false;
516
517 return true;
518}
519
520bool IndexedReference::isAliased(const IndexedReference &Other,
521 AAResults &AA) const {
522 const auto &Loc1 = MemoryLocation::get(&StoreOrLoadInst);
523 const auto &Loc2 = MemoryLocation::get(&Other.StoreOrLoadInst);
524 return AA.isMustAlias(Loc1, Loc2);
525}
526
527//===----------------------------------------------------------------------===//
528// CacheCost implementation
529//
531 for (const auto &LC : CC.LoopCosts) {
532 const Loop *L = LC.first;
533 OS << "Loop '" << L->getName() << "' has cost = " << LC.second << "\n";
534 }
535 return OS;
536}
537
540 AAResults &AA, DependenceInfo &DI,
541 std::optional<unsigned> TRT)
542 : Loops(Loops), LI(LI), SE(SE), TTI(TTI), AA(AA), DI(DI) {
543 assert(!Loops.empty() && "Expecting a non-empty loop vector.");
544 const AnalysisOptions &Opts = getAnalysisOptions(*Loops.front());
545 this->TRT = TRT.value_or(Opts.temporal_reuse_threshold);
546
547 for (const Loop *L : Loops) {
548 unsigned TripCount = SE.getSmallConstantTripCount(L);
549 TripCount = (TripCount == 0) ? Opts.default_trip_count : TripCount;
550 TripCounts.push_back({L, TripCount});
551 }
552
553 calculateCacheFootprint();
554}
555
556static std::unique_ptr<CacheCost>
559 std::optional<unsigned> TRT) {
560 if (!Root.isOutermost()) {
561 LLVM_DEBUG(dbgs() << "Expecting the outermost loop in a loop nest\n");
562 return nullptr;
563 }
564
567
568 if (!getInnerMostLoop(Loops)) {
569 LLVM_DEBUG(dbgs() << "Cannot compute cache cost of loop nest with more "
570 "than one innermost loop\n");
571 return nullptr;
572 }
573
574 return std::make_unique<CacheCost>(Loops, LI, SE, TTI, AA, DI, TRT);
575}
576
577std::unique_ptr<CacheCost>
579 DependenceInfo &DI, std::optional<unsigned> TRT) {
580 return getCacheCostImpl(Root, AR.LI, AR.SE, AR.TTI, AR.AA, DI, TRT);
581}
582
583void CacheCost::calculateCacheFootprint() {
584 LLVM_DEBUG(dbgs() << "POPULATING REFERENCE GROUPS\n");
585 ReferenceGroupsTy RefGroups;
586 if (!populateReferenceGroups(RefGroups))
587 return;
588
589 LLVM_DEBUG(dbgs() << "COMPUTING LOOP CACHE COSTS\n");
590 for (const Loop *L : Loops) {
592 LoopCosts,
593 [L](const LoopCacheCostTy &LCC) { return LCC.first == L; }) &&
594 "Should not add duplicate element");
595 CacheCostTy LoopCost = computeLoopCacheCost(*L, RefGroups);
596 LoopCosts.push_back(std::make_pair(L, LoopCost));
597 }
598
599 sortLoopCosts();
600 RefGroups.clear();
601}
602
603bool CacheCost::populateReferenceGroups(ReferenceGroupsTy &RefGroups) const {
604 assert(RefGroups.empty() && "Reference groups should be empty");
605
606 unsigned CLS = TTI.getCacheLineSize();
607 Loop *InnerMostLoop = getInnerMostLoop(Loops);
608 assert(InnerMostLoop != nullptr && "Expecting a valid innermost loop");
609
610 for (BasicBlock *BB : InnerMostLoop->getBlocks()) {
611 for (Instruction &I : *BB) {
612 if (!isa<StoreInst>(I) && !isa<LoadInst>(I))
613 continue;
614
615 std::unique_ptr<IndexedReference> R(new IndexedReference(I, LI, SE));
616 if (!R->isValid())
617 continue;
618
619 bool Added = false;
620 for (ReferenceGroupTy &RefGroup : RefGroups) {
621 const IndexedReference &Representative = *RefGroup.front();
622 LLVM_DEBUG({
623 dbgs() << "References:\n";
624 dbgs().indent(2) << *R << "\n";
625 dbgs().indent(2) << Representative << "\n";
626 });
627
628
629 // FIXME: Both positive and negative access functions will be placed
630 // into the same reference group, resulting in a bi-directional array
631 // access such as:
632 // for (i = N; i > 0; i--)
633 // A[i] = A[N - i];
634 // having the same cost calculation as a single dimention access pattern
635 // for (i = 0; i < N; i++)
636 // A[i] = A[i];
637 // when in actuality, depending on the array size, the first example
638 // should have a cost closer to 2x the second due to the two cache
639 // access per iteration from opposite ends of the array
640 std::optional<bool> HasTemporalReuse =
641 R->hasTemporalReuse(Representative, *TRT, *InnerMostLoop, DI, AA);
642 std::optional<bool> HasSpacialReuse =
643 R->hasSpacialReuse(Representative, CLS, AA);
644
645 if ((HasTemporalReuse && *HasTemporalReuse) ||
646 (HasSpacialReuse && *HasSpacialReuse)) {
647 RefGroup.push_back(std::move(R));
648 Added = true;
649 break;
650 }
651 }
652
653 if (!Added) {
655 RG.push_back(std::move(R));
656 RefGroups.push_back(std::move(RG));
657 }
658 }
659 }
660
661 if (RefGroups.empty())
662 return false;
663
664 LLVM_DEBUG({
665 dbgs() << "\nIDENTIFIED REFERENCE GROUPS:\n";
666 int n = 1;
667 for (const ReferenceGroupTy &RG : RefGroups) {
668 dbgs().indent(2) << "RefGroup " << n << ":\n";
669 for (const auto &IR : RG)
670 dbgs().indent(4) << *IR << "\n";
671 n++;
672 }
673 dbgs() << "\n";
674 });
675
676 return true;
677}
678
680CacheCost::computeLoopCacheCost(const Loop &L,
681 const ReferenceGroupsTy &RefGroups) const {
682 LLVM_DEBUG(dbgs() << "Considering loop '" << L.getName()
683 << "' as innermost loop.\n");
684
685 // Compute the product of the trip counts of each other loop in the nest.
686 CacheCostTy TripCountsProduct = 1;
687 for (const auto &TC : TripCounts) {
688 if (TC.first == &L)
689 continue;
690 TripCountsProduct *= TC.second;
691 }
692
693 CacheCostTy LoopCost = 0;
694 for (const ReferenceGroupTy &RG : RefGroups) {
695 CacheCostTy RefGroupCost = computeRefGroupCacheCost(RG, L);
696 LoopCost += RefGroupCost * TripCountsProduct;
697 }
698
699 LLVM_DEBUG(dbgs().indent(2) << "Loop '" << L.getName()
700 << "' has cost=" << LoopCost << "\n");
701
702 return LoopCost;
703}
704
705CacheCostTy CacheCost::computeRefGroupCacheCost(const ReferenceGroupTy &RG,
706 const Loop &L) const {
707 assert(!RG.empty() && "Reference group should have at least one member.");
708
709 const IndexedReference *Representative = RG.front().get();
710 return Representative->computeRefCost(L, TTI.getCacheLineSize());
711}
712
713//===----------------------------------------------------------------------===//
714// LoopCachePrinterPass implementation
715//
718 OS << "Printing analysis 'Loop Cache Analysis' for function '" << F.getName()
719 << "':\n";
720
721 auto &LI = FAM.getResult<LoopAnalysis>(F);
722 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
723 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
724 auto &AA = FAM.getResult<AAManager>(F);
725 auto &DI = FAM.getResult<DependenceAnalysis>(F);
726 for (Loop *L : LI.getTopLevelLoops())
727 if (std::unique_ptr<CacheCost> CC =
728 getCacheCostImpl(*L, LI, SE, TTI, AA, DI, /*TRT=*/std::nullopt))
729 OS << *CC;
730
731 return PreservedAnalyses::all();
732}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file builds on the ADT/GraphTraits.h file to build a generic breadth first graph iterator.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Hexagon Hardware Loops
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
static bool isOneDimensionalArray(const SCEV &AccessFn, const SCEV &ElemSize, const Loop &L, ScalarEvolution &SE)
static std::unique_ptr< CacheCost > getCacheCostImpl(Loop &Root, LoopInfo &LI, ScalarEvolution &SE, TargetTransformInfo &TTI, AAResults &AA, DependenceInfo &DI, std::optional< unsigned > TRT)
static const SCEV * computeTripCount(const Loop &L, const SCEV &ElemSize, ScalarEvolution &SE)
Compute the trip count for the given loop L or assume a default value if it is not a compile time con...
static Loop * getInnerMostLoop(const LoopVectorTy &Loops)
Retrieve the innermost loop in the given loop nest Loops.
This file defines the interface for the loop cache analysis.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
FunctionAnalysisManager FAM
RISCVCC::CondCode CC
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static cl::opt< unsigned > CacheLineSize("cache-line-size", cl::init(0), cl::Hidden, cl::desc("Use this to override the target cache line size when " "specified by the user."))
This pass exposes codegen information to IR-level passes.
A manager for alias analyses.
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are must-alias.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
CacheCost represents the estimated cost of a inner loop as the number of cache lines used by the memo...
LLVM_ABI CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI, ScalarEvolution &SE, TargetTransformInfo &TTI, AAResults &AA, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Construct a CacheCost object for the loop nest described by Loops.
static LLVM_ABI std::unique_ptr< CacheCost > getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Create a CacheCost for the loop nest rooted by Root.
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
AnalysisPass to compute dependence information in a function.
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool UnderRuntimeAssumptions=false)
depends - Tests for a dependence between the Src and Dst instructions.
Represents a memory reference as a base pointer and a set of indexing operations.
LLVM_ABI CacheCostTy computeRefCost(const Loop &L, unsigned CLS) const
Compute the cost of the reference w.r.t.
const SCEV * getSubscript(unsigned SubNum) const
LLVM_ABI std::optional< bool > hasSpacialReuse(const IndexedReference &Other, unsigned CLS, AAResults &AA) const
Return true/false if the current object and the indexed reference Other are/aren't in the same cache ...
LLVM_ABI std::optional< bool > hasTemporalReuse(const IndexedReference &Other, unsigned MaxDistance, const Loop &L, DependenceInfo &DI, AAResults &AA) const
Return true if the current object and the indexed reference Other have distance smaller than MaxDista...
LLVM_ABI IndexedReference(Instruction &StoreOrLoadInst, const LoopInfo &LI, ScalarEvolution &SE)
Construct an indexed reference given a StoreOrLoadInst instruction.
const SCEV * getLastSubscript() const
size_t getNumSubscripts() const
static InstructionCost getInvalid(CostType Val=0)
@ MAX_INT_BITS
Maximum number of bits that can be specified.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
unsigned getLoopDepth() const
Return the nesting level of this loop.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
const std::vector< LoopT * > & getTopLevelLoops() const
Return the top-level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
ConstantInt * getValue() const
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
void push_back(const T &Elt)
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI Type * getExtendedType() const
Given scalar/vector integer type, returns a type with elements twice as wide as in the original type.
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Abstract Attribute helper functions.
Definition Attributor.h:164
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
InstructionCost CacheCostTy
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
SmallVector< std::unique_ptr< IndexedReference >, 8 > ReferenceGroupTy
A reference group represents a set of memory references that exhibit temporal or spacial reuse.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool delinearizeFixedSizeArray(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Split this SCEVAddRecExpr into two vectors of SCEVs representing the subscripts and sizes of an acces...
SmallVector< Loop *, 8 > LoopVectorTy
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
iterator_range< bf_iterator< T > > breadth_first(const T &G)
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI void delinearize(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Split this SCEVAddRecExpr into two vectors of SCEVs representing the subscripts and sizes of an array...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
SmallVector< ReferenceGroupTy, 8 > ReferenceGroupsTy
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...