LLVM 23.0.0git
DependenceAnalysis.cpp
Go to the documentation of this file.
1//===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// DependenceAnalysis is an LLVM pass that analyses dependences between memory
10// accesses. Currently, it is an (incomplete) implementation of the approach
11// described in
12//
13// Practical Dependence Testing
14// Goff, Kennedy, Tseng
15// PLDI 1991
16//
17// There's a single entry point that analyzes the dependence between a pair
18// of memory references in a function, returning either NULL, for no dependence,
19// or a more-or-less detailed description of the dependence between them.
20//
21// Since Clang linearizes some array subscripts, the dependence
22// analysis is using SCEV->delinearize to recover the representation of multiple
23// subscripts, and thus avoid the more expensive and less precise MIV tests. The
24// delinearization is controlled by the flag -da-delinearize.
25//
26// We should pay some careful attention to the possibility of integer overflow
27// in the implementation of the various tests. This could happen with Add,
28// Subtract, or Multiply, with both APInt's and SCEV's.
29//
30// Some non-linear subscript pairs can be handled by the GCD test
31// (and perhaps other tests).
32// Should explore how often these things occur.
33//
34// Finally, it seems like certain test cases expose weaknesses in the SCEV
35// simplification, especially in the handling of sign and zero extensions.
36// It could be useful to spend time exploring these.
37//
38// Please note that this is work in progress and the interface is subject to
39// change.
40//
41//===----------------------------------------------------------------------===//
42// //
43// In memory of Ken Kennedy, 1945 - 2007 //
44// //
45//===----------------------------------------------------------------------===//
46
48#include "llvm/ADT/Statistic.h"
56#include "llvm/IR/Module.h"
59#include "llvm/Support/Debug.h"
62
63using namespace llvm;
64
65#define DEBUG_TYPE "da"
66
67//===----------------------------------------------------------------------===//
68// statistics
69
70STATISTIC(TotalArrayPairs, "Array pairs tested");
71STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
72STATISTIC(ZIVapplications, "ZIV applications");
73STATISTIC(ZIVindependence, "ZIV independence");
74STATISTIC(StrongSIVapplications, "Strong SIV applications");
75STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
76STATISTIC(StrongSIVindependence, "Strong SIV independence");
77STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
78STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
79STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
80STATISTIC(ExactSIVapplications, "Exact SIV applications");
81STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
82STATISTIC(ExactSIVindependence, "Exact SIV independence");
83STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
84STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
85STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
86STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
87STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
88STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
89STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
90STATISTIC(GCDapplications, "GCD applications");
91STATISTIC(GCDsuccesses, "GCD successes");
92STATISTIC(GCDindependence, "GCD independence");
93STATISTIC(BanerjeeApplications, "Banerjee applications");
94STATISTIC(BanerjeeIndependence, "Banerjee independence");
95STATISTIC(BanerjeeSuccesses, "Banerjee successes");
96STATISTIC(SameSDLoopsCount, "Loops with Same iteration Space and Depth");
97
98static cl::opt<bool>
99 Delinearize("da-delinearize", cl::init(true), cl::Hidden,
100 cl::desc("Try to delinearize array references."));
102 "da-disable-delinearization-checks", cl::Hidden,
103 cl::desc(
104 "Disable checks that try to statically verify validity of "
105 "delinearized subscripts. Enabling this option may result in incorrect "
106 "dependence vectors for languages that allow the subscript of one "
107 "dimension to underflow or overflow into another dimension."));
108
110 "da-miv-max-level-threshold", cl::init(7), cl::Hidden,
111 cl::desc("Maximum depth allowed for the recursive algorithm used to "
112 "explore MIV direction vectors."));
113
114namespace {
115
116/// Types of dependence test routines.
117enum class DependenceTestType {
118 All,
119 StrongSIV,
120 WeakCrossingSIV,
121 ExactSIV,
122 WeakZeroSIV,
123 ExactRDIV,
124 SymbolicRDIV,
125 GCDMIV,
126 BanerjeeMIV,
127};
128
129} // anonymous namespace
130
132 "da-enable-dependence-test", cl::init(DependenceTestType::All),
134 cl::desc("Run only specified dependence test routine and disable others. "
135 "The purpose is mainly to exclude the influence of other "
136 "dependence test routines in regression tests. If set to All, all "
137 "dependence test routines are enabled."),
138 cl::values(clEnumValN(DependenceTestType::All, "all",
139 "Enable all dependence test routines."),
140 clEnumValN(DependenceTestType::StrongSIV, "strong-siv",
141 "Enable only Strong SIV test."),
142 clEnumValN(DependenceTestType::WeakCrossingSIV,
143 "weak-crossing-siv",
144 "Enable only Weak-Crossing SIV test."),
145 clEnumValN(DependenceTestType::ExactSIV, "exact-siv",
146 "Enable only Exact SIV test."),
147 clEnumValN(DependenceTestType::WeakZeroSIV, "weak-zero-siv",
148 "Enable only Weak-Zero SIV test."),
149 clEnumValN(DependenceTestType::ExactRDIV, "exact-rdiv",
150 "Enable only Exact RDIV test."),
151 clEnumValN(DependenceTestType::SymbolicRDIV, "symbolic-rdiv",
152 "Enable only Symbolic RDIV test."),
153 clEnumValN(DependenceTestType::GCDMIV, "gcd-miv",
154 "Enable only GCD MIV test."),
155 clEnumValN(DependenceTestType::BanerjeeMIV, "banerjee-miv",
156 "Enable only Banerjee MIV test.")));
157
158// TODO: This flag is disabled by default because it is still under development.
159// Enable it or delete this flag when the feature is ready.
161 "da-enable-monotonicity-check", cl::init(false), cl::Hidden,
162 cl::desc("Check if the subscripts are monotonic. If it's not, dependence "
163 "is reported as unknown."));
164
166 "da-dump-monotonicity-report", cl::init(false), cl::Hidden,
167 cl::desc(
168 "When printing analysis, dump the results of monotonicity checks."));
169
170//===----------------------------------------------------------------------===//
171// basics
172
175 auto &AA = FAM.getResult<AAManager>(F);
176 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
177 auto &LI = FAM.getResult<LoopAnalysis>(F);
178 return DependenceInfo(&F, &AA, &SE, &LI);
179}
180
181AnalysisKey DependenceAnalysis::Key;
182
184 "Dependence Analysis", true, true)
190
192
195
199
201 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
202 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
203 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
204 info.reset(new DependenceInfo(&F, &AA, &SE, &LI));
205 return false;
206}
207
209
211
218
219namespace {
220
221/// The property of monotonicity of a SCEV. To define the monotonicity, assume
222/// a SCEV defined within N-nested loops. Let i_k denote the iteration number
223/// of the k-th loop. Then we can regard the SCEV as an N-ary function:
224///
225/// F(i_1, i_2, ..., i_N)
226///
227/// The domain of i_k is the closed range [0, BTC_k], where BTC_k is the
228/// backedge-taken count of the k-th loop.
229///
230/// A function F is said to be "monotonically increasing with respect to the
231/// k-th loop" if x <= y implies the following condition:
232///
233/// F(i_1, ..., i_{k-1}, x, i_{k+1}, ..., i_N) <=
234/// F(i_1, ..., i_{k-1}, y, i_{k+1}, ..., i_N)
235///
236/// where i_1, ..., i_{k-1}, i_{k+1}, ..., i_N, x, and y are elements of their
237/// respective domains.
238///
239/// Likewise F is "monotonically decreasing with respect to the k-th loop"
240/// if x <= y implies
241///
242/// F(i_1, ..., i_{k-1}, x, i_{k+1}, ..., i_N) >=
243/// F(i_1, ..., i_{k-1}, y, i_{k+1}, ..., i_N)
244///
245/// A function F that is monotonically increasing or decreasing with respect to
246/// the k-th loop is simply called "monotonic with respect to k-th loop".
247///
248/// A function F is said to be "multivariate monotonic" when it is monotonic
249/// with respect to all of the N loops.
250///
251/// Since integer comparison can be either signed or unsigned, we need to
252/// distinguish monotonicity in the signed sense from that in the unsigned
253/// sense. Note that the inequality "x <= y" merely indicates loop progression
254/// and is not affected by the difference between signed and unsigned order.
255///
256/// Currently we only consider monotonicity in a signed sense.
257enum class SCEVMonotonicityType {
258 /// We don't know anything about the monotonicity of the SCEV.
259 Unknown,
260
261 /// The SCEV is loop-invariant with respect to the outermost loop. In other
262 /// words, the function F corresponding to the SCEV is a constant function.
263 Invariant,
264
265 /// The function F corresponding to the SCEV is multivariate monotonic in a
266 /// signed sense. Note that the multivariate monotonic function may also be a
267 /// constant function. The order employed in the definition of monotonicity
268 /// is not strict order.
269 MultivariateSignedMonotonic,
270};
271
272struct SCEVMonotonicity {
273 SCEVMonotonicity(SCEVMonotonicityType Type,
274 const SCEV *FailurePoint = nullptr);
275
276 SCEVMonotonicityType getType() const { return Type; }
277
278 const SCEV *getFailurePoint() const { return FailurePoint; }
279
280 bool isUnknown() const { return Type == SCEVMonotonicityType::Unknown; }
281
282 void print(raw_ostream &OS, unsigned Depth) const;
283
284private:
285 SCEVMonotonicityType Type;
286
287 /// The subexpression that caused Unknown. Mainly for debugging purpose.
288 const SCEV *FailurePoint;
289};
290
291/// Check the monotonicity of a SCEV. Since dependence tests (SIV, MIV, etc.)
292/// assume that subscript expressions are (multivariate) monotonic, we need to
293/// verify this property before applying those tests. Violating this assumption
294/// may cause them to produce incorrect results.
295struct SCEVMonotonicityChecker
296 : public SCEVVisitor<SCEVMonotonicityChecker, SCEVMonotonicity> {
297
298 SCEVMonotonicityChecker(ScalarEvolution *SE) : SE(SE) {}
299
300 /// Check the monotonicity of \p Expr. \p Expr must be integer type. If \p
301 /// OutermostLoop is not null, \p Expr must be defined in \p OutermostLoop or
302 /// one of its nested loops.
303 SCEVMonotonicity checkMonotonicity(const SCEV *Expr,
304 const Loop *OutermostLoop);
305
306private:
307 ScalarEvolution *SE;
308
309 /// The outermost loop that DA is analyzing.
310 const Loop *OutermostLoop;
311
312 /// A helper to classify \p Expr as either Invariant or Unknown.
313 SCEVMonotonicity invariantOrUnknown(const SCEV *Expr);
314
315 /// Return true if \p Expr is loop-invariant with respect to the outermost
316 /// loop.
317 bool isLoopInvariant(const SCEV *Expr) const;
318
319 /// A helper to create an Unknown SCEVMonotonicity.
320 SCEVMonotonicity createUnknown(const SCEV *FailurePoint) {
321 return SCEVMonotonicity(SCEVMonotonicityType::Unknown, FailurePoint);
322 }
323
324 SCEVMonotonicity visitAddRecExpr(const SCEVAddRecExpr *Expr);
325
326 SCEVMonotonicity visitConstant(const SCEVConstant *) {
327 return SCEVMonotonicity(SCEVMonotonicityType::Invariant);
328 }
329 SCEVMonotonicity visitVScale(const SCEVVScale *) {
330 return SCEVMonotonicity(SCEVMonotonicityType::Invariant);
331 }
332
333 // TODO: Handle more cases.
334 SCEVMonotonicity visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
335 return invariantOrUnknown(Expr);
336 }
337 SCEVMonotonicity visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
338 return invariantOrUnknown(Expr);
339 }
340 SCEVMonotonicity visitAddExpr(const SCEVAddExpr *Expr) {
341 return invariantOrUnknown(Expr);
342 }
343 SCEVMonotonicity visitMulExpr(const SCEVMulExpr *Expr) {
344 return invariantOrUnknown(Expr);
345 }
346 SCEVMonotonicity visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
347 return invariantOrUnknown(Expr);
348 }
349 SCEVMonotonicity visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) {
350 return invariantOrUnknown(Expr);
351 }
352 SCEVMonotonicity visitTruncateExpr(const SCEVTruncateExpr *Expr) {
353 return invariantOrUnknown(Expr);
354 }
355 SCEVMonotonicity visitUDivExpr(const SCEVUDivExpr *Expr) {
356 return invariantOrUnknown(Expr);
357 }
358 SCEVMonotonicity visitSMaxExpr(const SCEVSMaxExpr *Expr) {
359 return invariantOrUnknown(Expr);
360 }
361 SCEVMonotonicity visitUMaxExpr(const SCEVUMaxExpr *Expr) {
362 return invariantOrUnknown(Expr);
363 }
364 SCEVMonotonicity visitSMinExpr(const SCEVSMinExpr *Expr) {
365 return invariantOrUnknown(Expr);
366 }
367 SCEVMonotonicity visitUMinExpr(const SCEVUMinExpr *Expr) {
368 return invariantOrUnknown(Expr);
369 }
370 SCEVMonotonicity visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
371 return invariantOrUnknown(Expr);
372 }
373 SCEVMonotonicity visitUnknown(const SCEVUnknown *Expr) {
374 return invariantOrUnknown(Expr);
375 }
376 SCEVMonotonicity visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
377 return invariantOrUnknown(Expr);
378 }
379
380 friend struct SCEVVisitor<SCEVMonotonicityChecker, SCEVMonotonicity>;
381};
382
383/// A wrapper class for std::optional<APInt> that provides arithmetic operators
384/// with overflow checking in a signed sense. This allows us to omit inserting
385/// an overflow check at every arithmetic operation, which simplifies the code
386/// if the operations are chained like `a + b + c + ...`.
387///
388/// If an calculation overflows, the result becomes "invalid" which is
389/// internally represented by std::nullopt. If any operand of an arithmetic
390/// operation is "invalid", the result will also be "invalid".
391struct OverflowSafeSignedAPInt {
392 OverflowSafeSignedAPInt() : Value(std::nullopt) {}
393 OverflowSafeSignedAPInt(const APInt &V) : Value(V) {}
394 OverflowSafeSignedAPInt(const std::optional<APInt> &V) : Value(V) {}
395
396 OverflowSafeSignedAPInt operator+(const OverflowSafeSignedAPInt &RHS) const {
397 if (!Value || !RHS.Value)
398 return OverflowSafeSignedAPInt();
399 bool Overflow;
400 APInt Result = Value->sadd_ov(*RHS.Value, Overflow);
401 if (Overflow)
402 return OverflowSafeSignedAPInt();
403 return OverflowSafeSignedAPInt(Result);
404 }
405
406 OverflowSafeSignedAPInt operator+(int RHS) const {
407 if (!Value)
408 return OverflowSafeSignedAPInt();
409 return *this + fromInt(RHS);
410 }
411
412 OverflowSafeSignedAPInt operator-(const OverflowSafeSignedAPInt &RHS) const {
413 if (!Value || !RHS.Value)
414 return OverflowSafeSignedAPInt();
415 bool Overflow;
416 APInt Result = Value->ssub_ov(*RHS.Value, Overflow);
417 if (Overflow)
418 return OverflowSafeSignedAPInt();
419 return OverflowSafeSignedAPInt(Result);
420 }
421
422 OverflowSafeSignedAPInt operator-(int RHS) const {
423 if (!Value)
424 return OverflowSafeSignedAPInt();
425 return *this - fromInt(RHS);
426 }
427
428 OverflowSafeSignedAPInt operator*(const OverflowSafeSignedAPInt &RHS) const {
429 if (!Value || !RHS.Value)
430 return OverflowSafeSignedAPInt();
431 bool Overflow;
432 APInt Result = Value->smul_ov(*RHS.Value, Overflow);
433 if (Overflow)
434 return OverflowSafeSignedAPInt();
435 return OverflowSafeSignedAPInt(Result);
436 }
437
438 OverflowSafeSignedAPInt operator-() const {
439 if (!Value)
440 return OverflowSafeSignedAPInt();
441 if (Value->isMinSignedValue())
442 return OverflowSafeSignedAPInt();
443 return OverflowSafeSignedAPInt(-*Value);
444 }
445
446 operator bool() const { return Value.has_value(); }
447
448 bool operator!() const { return !Value.has_value(); }
449
450 const APInt &operator*() const {
451 assert(Value && "Value is not available.");
452 return *Value;
453 }
454
455 const APInt *operator->() const {
456 assert(Value && "Value is not available.");
457 return &*Value;
458 }
459
460private:
461 /// Underlying value. std::nullopt means "unknown". An arithmetic operation on
462 /// "unknown" always produces "unknown".
463 std::optional<APInt> Value;
464
465 OverflowSafeSignedAPInt fromInt(uint64_t V) const {
466 assert(Value && "Value is not available.");
467 return OverflowSafeSignedAPInt(
468 APInt(Value->getBitWidth(), V, /*isSigned=*/true));
469 }
470};
471
472} // anonymous namespace
473
474// Used to test the dependence analyzer.
475// Looks through the function, noting instructions that may access memory.
476// Calls depends() on every possible pair and prints out the result.
477// Ignores all other instructions.
479 ScalarEvolution &SE, LoopInfo &LI,
480 bool NormalizeResults) {
481 auto *F = DA->getFunction();
482
484 SCEVMonotonicityChecker Checker(&SE);
485 OS << "Monotonicity check:\n";
486 for (Instruction &Inst : instructions(F)) {
487 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
488 continue;
489 Value *Ptr = getLoadStorePointerOperand(&Inst);
490 const Loop *L = LI.getLoopFor(Inst.getParent());
491 const Loop *OutermostLoop = L ? L->getOutermostLoop() : nullptr;
492 const SCEV *PtrSCEV = SE.getSCEVAtScope(Ptr, L);
493 const SCEV *AccessFn = SE.removePointerBase(PtrSCEV);
494 SCEVMonotonicity Mon = Checker.checkMonotonicity(AccessFn, OutermostLoop);
495 OS.indent(2) << "Inst: " << Inst << "\n";
496 OS.indent(4) << "Expr: " << *AccessFn << "\n";
497 Mon.print(OS, 4);
498 }
499 OS << "\n";
500 }
501
502 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
503 ++SrcI) {
504 if (SrcI->mayReadOrWriteMemory()) {
505 for (inst_iterator DstI = SrcI, DstE = inst_end(F); DstI != DstE;
506 ++DstI) {
507 if (DstI->mayReadOrWriteMemory()) {
508 OS << "Src:" << *SrcI << " --> Dst:" << *DstI << "\n";
509 OS << " da analyze - ";
510 if (auto D = DA->depends(&*SrcI, &*DstI,
511 /*UnderRuntimeAssumptions=*/true)) {
512
513#ifndef NDEBUG
514 // Verify that the distance being zero is equivalent to the
515 // direction being EQ.
516 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
517 const SCEV *Distance = D->getDistance(Level);
518 bool IsDistanceZero = Distance && Distance->isZero();
519 bool IsDirectionEQ =
520 D->getDirection(Level) == Dependence::DVEntry::EQ;
521 assert(IsDistanceZero == IsDirectionEQ &&
522 "Inconsistent distance and direction.");
523 }
524#endif
525
526 // Normalize negative direction vectors if required by clients.
527 if (NormalizeResults && D->normalize(&SE))
528 OS << "normalized - ";
529 D->dump(OS);
530 } else
531 OS << "none!\n";
532 }
533 }
534 }
535 }
536}
537
539 const Module *) const {
541 OS, info.get(), getAnalysis<ScalarEvolutionWrapperPass>().getSE(),
542 getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), false);
543}
544
547 OS << "Printing analysis 'Dependence Analysis' for function '" << F.getName()
548 << "':\n";
550 FAM.getResult<ScalarEvolutionAnalysis>(F),
551 FAM.getResult<LoopAnalysis>(F), NormalizeResults);
552 return PreservedAnalyses::all();
553}
554
555//===----------------------------------------------------------------------===//
556// Dependence methods
557
558// Returns true if this is an input dependence.
560 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
561}
562
563// Returns true if this is an output dependence.
565 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
566}
567
568// Returns true if this is an flow (aka true) dependence.
569bool Dependence::isFlow() const {
570 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
571}
572
573// Returns true if this is an anti dependence.
574bool Dependence::isAnti() const {
575 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
576}
577
578// Returns true if a particular level is scalar; that is,
579// if no subscript in the source or destination mention the induction
580// variable associated with the loop at this level.
581// Leave this out of line, so it will serve as a virtual method anchor
582bool Dependence::isScalar(unsigned level, bool IsSameSD) const { return false; }
583
584//===----------------------------------------------------------------------===//
585// FullDependence methods
586
588 const SCEVUnionPredicate &Assumes,
589 bool PossiblyLoopIndependent,
590 unsigned CommonLevels)
591 : Dependence(Source, Destination, Assumes), Levels(CommonLevels),
592 LoopIndependent(PossiblyLoopIndependent) {
593 SameSDLevels = 0;
594 if (CommonLevels)
595 DV = std::make_unique<DVEntry[]>(CommonLevels);
596}
597
598// FIXME: in some cases the meaning of a negative direction vector
599// may not be straightforward, e.g.,
600// for (int i = 0; i < 32; ++i) {
601// Src: A[i] = ...;
602// Dst: use(A[31 - i]);
603// }
604// The dependency is
605// flow { Src[i] -> Dst[31 - i] : when i >= 16 } and
606// anti { Dst[i] -> Src[31 - i] : when i < 16 },
607// -- hence a [<>].
608// As long as a dependence result contains '>' ('<>', '<=>', "*"), it
609// means that a reversed/normalized dependence needs to be considered
610// as well. Nevertheless, current isDirectionNegative() only returns
611// true with a '>' or '>=' dependency for ease of canonicalizing the
612// dependency vector, since the reverse of '<>', '<=>' and "*" is itself.
614 for (unsigned Level = 1; Level <= Levels; ++Level) {
615 unsigned char Direction = DV[Level - 1].Direction;
616 if (Direction == Dependence::DVEntry::EQ)
617 continue;
618 if (Direction == Dependence::DVEntry::GT ||
619 Direction == Dependence::DVEntry::GE)
620 return true;
621 return false;
622 }
623 return false;
624}
625
627 if (!isDirectionNegative())
628 return false;
629
630 LLVM_DEBUG(dbgs() << "Before normalizing negative direction vectors:\n";
631 dump(dbgs()););
632 std::swap(Src, Dst);
633 for (unsigned Level = 1; Level <= Levels; ++Level) {
634 unsigned char Direction = DV[Level - 1].Direction;
635 // Reverse the direction vector, this means LT becomes GT
636 // and GT becomes LT.
637 unsigned char RevDirection = Direction & Dependence::DVEntry::EQ;
638 if (Direction & Dependence::DVEntry::LT)
639 RevDirection |= Dependence::DVEntry::GT;
640 if (Direction & Dependence::DVEntry::GT)
641 RevDirection |= Dependence::DVEntry::LT;
642 DV[Level - 1].Direction = RevDirection;
643 // Reverse the dependence distance as well.
644 if (DV[Level - 1].Distance != nullptr)
645 DV[Level - 1].Distance = SE->getNegativeSCEV(DV[Level - 1].Distance);
646 }
647
648 LLVM_DEBUG(dbgs() << "After normalizing negative direction vectors:\n";
649 dump(dbgs()););
650 return true;
651}
652
653// The rest are simple getters that hide the implementation.
654
655// getDirection - Returns the direction associated with a particular common or
656// SameSD level.
657unsigned FullDependence::getDirection(unsigned Level, bool IsSameSD) const {
658 return getDVEntry(Level, IsSameSD).Direction;
659}
660
661// Returns the distance (or NULL) associated with a particular common or
662// SameSD level.
663const SCEV *FullDependence::getDistance(unsigned Level, bool IsSameSD) const {
664 return getDVEntry(Level, IsSameSD).Distance;
665}
666
667// Returns true if a particular regular or SameSD level is scalar; that is,
668// if no subscript in the source or destination mention the induction variable
669// associated with the loop at this level.
670bool FullDependence::isScalar(unsigned Level, bool IsSameSD) const {
671 return getDVEntry(Level, IsSameSD).Scalar;
672}
673
674// inSameSDLoops - Returns true if this level is an SameSD level, i.e.,
675// performed across two separate loop nests that have the Same iteration space
676// and Depth.
677bool FullDependence::inSameSDLoops(unsigned Level) const {
678 assert(0 < Level && Level <= static_cast<unsigned>(Levels) + SameSDLevels &&
679 "Level out of range");
680 return Level > Levels;
681}
682
683//===----------------------------------------------------------------------===//
684// SCEVMonotonicity
685
686SCEVMonotonicity::SCEVMonotonicity(SCEVMonotonicityType Type,
687 const SCEV *FailurePoint)
688 : Type(Type), FailurePoint(FailurePoint) {
689 assert(
690 ((Type == SCEVMonotonicityType::Unknown) == (FailurePoint != nullptr)) &&
691 "FailurePoint must be provided iff Type is Unknown");
692}
693
694void SCEVMonotonicity::print(raw_ostream &OS, unsigned Depth) const {
695 OS.indent(Depth) << "Monotonicity: ";
696 switch (Type) {
697 case SCEVMonotonicityType::Unknown:
698 assert(FailurePoint && "FailurePoint must be provided for Unknown");
699 OS << "Unknown\n";
700 OS.indent(Depth) << "Reason: " << *FailurePoint << "\n";
701 break;
702 case SCEVMonotonicityType::Invariant:
703 OS << "Invariant\n";
704 break;
705 case SCEVMonotonicityType::MultivariateSignedMonotonic:
706 OS << "MultivariateSignedMonotonic\n";
707 break;
708 }
709}
710
711bool SCEVMonotonicityChecker::isLoopInvariant(const SCEV *Expr) const {
712 return !OutermostLoop || SE->isLoopInvariant(Expr, OutermostLoop);
713}
714
715SCEVMonotonicity SCEVMonotonicityChecker::invariantOrUnknown(const SCEV *Expr) {
716 if (isLoopInvariant(Expr))
717 return SCEVMonotonicity(SCEVMonotonicityType::Invariant);
718 return createUnknown(Expr);
719}
720
721SCEVMonotonicity
722SCEVMonotonicityChecker::checkMonotonicity(const SCEV *Expr,
723 const Loop *OutermostLoop) {
724 assert((!OutermostLoop || OutermostLoop->isOutermost()) &&
725 "OutermostLoop must be outermost");
726 assert(Expr->getType()->isIntegerTy() && "Expr must be integer type");
727 this->OutermostLoop = OutermostLoop;
728 return visit(Expr);
729}
730
731/// We only care about an affine AddRec at the moment. For an affine AddRec,
732/// the monotonicity can be inferred from its nowrap property. For example, let
733/// X and Y be loop-invariant, and assume Y is non-negative. An AddRec
734/// {X,+.Y}<nsw> implies:
735///
736/// X <=s (X + Y) <=s ((X + Y) + Y) <=s ...
737///
738/// Thus, we can conclude that the AddRec is monotonically increasing with
739/// respect to the associated loop in a signed sense. The similar reasoning
740/// applies when Y is non-positive, leading to a monotonically decreasing
741/// AddRec.
742SCEVMonotonicity
743SCEVMonotonicityChecker::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
744 if (!Expr->isAffine() || !Expr->hasNoSignedWrap())
745 return createUnknown(Expr);
746
747 const SCEV *Start = Expr->getStart();
748 const SCEV *Step = Expr->getStepRecurrence(*SE);
749
750 SCEVMonotonicity StartMon = visit(Start);
751 if (StartMon.isUnknown())
752 return StartMon;
753
754 if (!isLoopInvariant(Step))
755 return createUnknown(Expr);
756
757 return SCEVMonotonicity(SCEVMonotonicityType::MultivariateSignedMonotonic);
758}
759
760//===----------------------------------------------------------------------===//
761// DependenceInfo methods
762
763// For debugging purposes. Dumps a dependence to OS.
765 if (isConfused())
766 OS << "confused";
767 else {
768 if (isFlow())
769 OS << "flow";
770 else if (isOutput())
771 OS << "output";
772 else if (isAnti())
773 OS << "anti";
774 else if (isInput())
775 OS << "input";
776 dumpImp(OS);
777 unsigned SameSDLevels = getSameSDLevels();
778 if (SameSDLevels > 0) {
779 OS << " / assuming " << SameSDLevels << " loop level(s) fused: ";
780 dumpImp(OS, true);
781 }
782 }
783 OS << "!\n";
784
786 if (!Assumptions.isAlwaysTrue()) {
787 OS << " Runtime Assumptions:\n";
788 Assumptions.print(OS, 2);
789 }
790}
791
792// For debugging purposes. Dumps a dependence to OS with or without considering
793// the SameSD levels.
794void Dependence::dumpImp(raw_ostream &OS, bool IsSameSD) const {
795 unsigned Levels = getLevels();
796 unsigned SameSDLevels = getSameSDLevels();
797 bool OnSameSD = false;
798 unsigned LevelNum = Levels;
799 if (IsSameSD)
800 LevelNum += SameSDLevels;
801 OS << " [";
802 for (unsigned II = 1; II <= LevelNum; ++II) {
803 if (!OnSameSD && inSameSDLoops(II))
804 OnSameSD = true;
805 const SCEV *Distance = getDistance(II, OnSameSD);
806 if (Distance)
807 OS << *Distance;
808 else if (isScalar(II, OnSameSD))
809 OS << "S";
810 else {
811 unsigned Direction = getDirection(II, OnSameSD);
812 if (Direction == DVEntry::ALL)
813 OS << "*";
814 else {
815 if (Direction & DVEntry::LT)
816 OS << "<";
817 if (Direction & DVEntry::EQ)
818 OS << "=";
819 if (Direction & DVEntry::GT)
820 OS << ">";
821 }
822 }
823 if (II < LevelNum)
824 OS << " ";
825 }
826 if (isLoopIndependent())
827 OS << "|<";
828 OS << "]";
829}
830
831// Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
832// underlaying objects. If LocA and LocB are known to not alias (for any reason:
833// tbaa, non-overlapping regions etc), then it is known there is no dependecy.
834// Otherwise the underlying objects are checked to see if they point to
835// different identifiable objects.
837 const MemoryLocation &LocA,
838 const MemoryLocation &LocB) {
839 // Check the original locations (minus size) for noalias, which can happen for
840 // tbaa, incompatible underlying object locations, etc.
841 MemoryLocation LocAS =
843 MemoryLocation LocBS =
845 BatchAAResults BAA(*AA);
847
848 if (BAA.isNoAlias(LocAS, LocBS))
850
851 // Check the underlying objects are the same
852 const Value *AObj = getUnderlyingObject(LocA.Ptr);
853 const Value *BObj = getUnderlyingObject(LocB.Ptr);
854
855 // If the underlying objects are the same, they must alias
856 if (AObj == BObj)
858
859 // We may have hit the recursion limit for underlying objects, or have
860 // underlying objects where we don't know they will alias.
861 if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
863
864 // Otherwise we know the objects are different and both identified objects so
865 // must not alias.
867}
868
869// Returns true if the load or store can be analyzed. Atomic and volatile
870// operations have properties which this analysis does not understand.
871static bool isLoadOrStore(const Instruction *I) {
872 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
873 return LI->isUnordered();
874 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
875 return SI->isUnordered();
876 return false;
877}
878
879// Returns true if two loops have the Same iteration Space and Depth. To be
880// more specific, two loops have SameSD if they are in the same nesting
881// depth and have the same backedge count. SameSD stands for Same iteration
882// Space and Depth.
883bool DependenceInfo::haveSameSD(const Loop *SrcLoop,
884 const Loop *DstLoop) const {
885 if (SrcLoop == DstLoop)
886 return true;
887
888 if (SrcLoop->getLoopDepth() != DstLoop->getLoopDepth())
889 return false;
890
891 if (!SrcLoop || !SrcLoop->getLoopLatch() || !DstLoop ||
892 !DstLoop->getLoopLatch())
893 return false;
894
895 const SCEV *SrcUB = nullptr, *DstUP = nullptr;
896 if (SE->hasLoopInvariantBackedgeTakenCount(SrcLoop))
897 SrcUB = SE->getBackedgeTakenCount(SrcLoop);
898 if (SE->hasLoopInvariantBackedgeTakenCount(DstLoop))
899 DstUP = SE->getBackedgeTakenCount(DstLoop);
900
901 if (SrcUB != nullptr && DstUP != nullptr) {
902 Type *WiderType = SE->getWiderType(SrcUB->getType(), DstUP->getType());
903 SrcUB = SE->getNoopOrZeroExtend(SrcUB, WiderType);
904 DstUP = SE->getNoopOrZeroExtend(DstUP, WiderType);
905
906 if (SE->isKnownPredicate(ICmpInst::ICMP_EQ, SrcUB, DstUP))
907 return true;
908 }
909
910 return false;
911}
912
913// Examines the loop nesting of the Src and Dst
914// instructions and establishes their shared loops. Sets the variables
915// CommonLevels, SrcLevels, and MaxLevels.
916// The source and destination instructions needn't be contained in the same
917// loop. The routine establishNestingLevels finds the level of most deeply
918// nested loop that contains them both, CommonLevels. An instruction that's
919// not contained in a loop is at level = 0. MaxLevels is equal to the level
920// of the source plus the level of the destination, minus CommonLevels.
921// This lets us allocate vectors MaxLevels in length, with room for every
922// distinct loop referenced in both the source and destination subscripts.
923// The variable SrcLevels is the nesting depth of the source instruction.
924// It's used to help calculate distinct loops referenced by the destination.
925// Here's the map from loops to levels:
926// 0 - unused
927// 1 - outermost common loop
928// ... - other common loops
929// CommonLevels - innermost common loop
930// ... - loops containing Src but not Dst
931// SrcLevels - innermost loop containing Src but not Dst
932// ... - loops containing Dst but not Src
933// MaxLevels - innermost loops containing Dst but not Src
934// Consider the follow code fragment:
935// for (a = ...) {
936// for (b = ...) {
937// for (c = ...) {
938// for (d = ...) {
939// A[] = ...;
940// }
941// }
942// for (e = ...) {
943// for (f = ...) {
944// for (g = ...) {
945// ... = A[];
946// }
947// }
948// }
949// }
950// }
951// If we're looking at the possibility of a dependence between the store
952// to A (the Src) and the load from A (the Dst), we'll note that they
953// have 2 loops in common, so CommonLevels will equal 2 and the direction
954// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
955// A map from loop names to loop numbers would look like
956// a - 1
957// b - 2 = CommonLevels
958// c - 3
959// d - 4 = SrcLevels
960// e - 5
961// f - 6
962// g - 7 = MaxLevels
963// SameSDLevels counts the number of levels after common levels that are
964// not common but have the same iteration space and depth. Internally this
965// is checked using haveSameSD. Assume that in this code fragment, levels c and
966// e have the same iteration space and depth, but levels d and f does not. Then
967// SameSDLevels is set to 1. In that case the level numbers for the previous
968// code look like
969// a - 1
970// b - 2
971// c,e - 3 = CommonLevels
972// d - 4 = SrcLevels
973// f - 5
974// g - 6 = MaxLevels
975void DependenceInfo::establishNestingLevels(const Instruction *Src,
976 const Instruction *Dst) {
977 const BasicBlock *SrcBlock = Src->getParent();
978 const BasicBlock *DstBlock = Dst->getParent();
979 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
980 unsigned DstLevel = LI->getLoopDepth(DstBlock);
981 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
982 const Loop *DstLoop = LI->getLoopFor(DstBlock);
983 SrcLevels = SrcLevel;
984 MaxLevels = SrcLevel + DstLevel;
985 SameSDLevels = 0;
986 while (SrcLevel > DstLevel) {
987 SrcLoop = SrcLoop->getParentLoop();
988 SrcLevel--;
989 }
990 while (DstLevel > SrcLevel) {
991 DstLoop = DstLoop->getParentLoop();
992 DstLevel--;
993 }
994
995 // find the first common level and count the SameSD levels leading to it
996 while (SrcLoop != DstLoop) {
997 SameSDLevels++;
998 if (!haveSameSD(SrcLoop, DstLoop))
999 SameSDLevels = 0;
1000 SrcLoop = SrcLoop->getParentLoop();
1001 DstLoop = DstLoop->getParentLoop();
1002 SrcLevel--;
1003 }
1004 CommonLevels = SrcLevel;
1005 MaxLevels -= CommonLevels;
1006}
1007
1008// Given one of the loops containing the source, return
1009// its level index in our numbering scheme.
1010unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
1011 return SrcLoop->getLoopDepth();
1012}
1013
1014// Given one of the loops containing the destination,
1015// return its level index in our numbering scheme.
1016unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
1017 unsigned D = DstLoop->getLoopDepth();
1018 if (D > CommonLevels)
1019 // This tries to make sure that we assign unique numbers to src and dst when
1020 // the memory accesses reside in different loops that have the same depth.
1021 return D - CommonLevels + SrcLevels;
1022 else
1023 return D;
1024}
1025
1026// Returns true if Expression is loop invariant in LoopNest.
1027bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
1028 const Loop *LoopNest) const {
1029 // Unlike ScalarEvolution::isLoopInvariant() we consider an access outside of
1030 // any loop as invariant, because we only consier expression evaluation at a
1031 // specific position (where the array access takes place), and not across the
1032 // entire function.
1033 if (!LoopNest)
1034 return true;
1035
1036 // If the expression is invariant in the outermost loop of the loop nest, it
1037 // is invariant anywhere in the loop nest.
1038 return SE->isLoopInvariant(Expression, LoopNest->getOutermostLoop());
1039}
1040
1041// Finds the set of loops from the LoopNest that
1042// have a level <= CommonLevels and are referred to by the SCEV Expression.
1043void DependenceInfo::collectCommonLoops(const SCEV *Expression,
1044 const Loop *LoopNest,
1045 SmallBitVector &Loops) const {
1046 while (LoopNest) {
1047 unsigned Level = LoopNest->getLoopDepth();
1048 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
1049 Loops.set(Level);
1050 LoopNest = LoopNest->getParentLoop();
1051 }
1052}
1053
1054// Examine the scev and return true iff it's affine.
1055// Collect any loops mentioned in the set of "Loops".
1056bool DependenceInfo::checkSubscript(const SCEV *Expr, const Loop *LoopNest,
1057 SmallBitVector &Loops, bool IsSrc) {
1058 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
1059 if (!AddRec)
1060 return isLoopInvariant(Expr, LoopNest);
1061
1062 // The AddRec must depend on one of the containing loops. Otherwise,
1063 // mapSrcLoop and mapDstLoop return indices outside the intended range. This
1064 // can happen when a subscript in one loop references an IV from a sibling
1065 // loop that could not be replaced with a concrete exit value by
1066 // getSCEVAtScope.
1067 const Loop *L = LoopNest;
1068 while (L && AddRec->getLoop() != L)
1069 L = L->getParentLoop();
1070 if (!L)
1071 return false;
1072
1073 const SCEV *Start = AddRec->getStart();
1074 const SCEV *Step = AddRec->getStepRecurrence(*SE);
1075 if (!isLoopInvariant(Step, LoopNest))
1076 return false;
1077 if (IsSrc)
1078 Loops.set(mapSrcLoop(AddRec->getLoop()));
1079 else
1080 Loops.set(mapDstLoop(AddRec->getLoop()));
1081 return checkSubscript(Start, LoopNest, Loops, IsSrc);
1082}
1083
1084// Examine the scev and return true iff it's linear.
1085// Collect any loops mentioned in the set of "Loops".
1086bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
1088 return checkSubscript(Src, LoopNest, Loops, true);
1089}
1090
1091// Examine the scev and return true iff it's linear.
1092// Collect any loops mentioned in the set of "Loops".
1093bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
1095 return checkSubscript(Dst, LoopNest, Loops, false);
1096}
1097
1098// Examines the subscript pair (the Src and Dst SCEVs)
1099// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
1100// Collects the associated loops in a set.
1101DependenceInfo::Subscript::ClassificationKind
1102DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
1103 const SCEV *Dst, const Loop *DstLoopNest,
1105 SmallBitVector SrcLoops(MaxLevels + 1);
1106 SmallBitVector DstLoops(MaxLevels + 1);
1107 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
1108 return Subscript::NonLinear;
1109 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
1110 return Subscript::NonLinear;
1111 Loops = SrcLoops;
1112 Loops |= DstLoops;
1113 unsigned N = Loops.count();
1114 if (N == 0)
1115 return Subscript::ZIV;
1116 if (N == 1)
1117 return Subscript::SIV;
1118 if (N == 2 && SrcLoops.count() == 1 && DstLoops.count() == 1)
1119 return Subscript::RDIV;
1120 return Subscript::MIV;
1121}
1122
1123// All subscripts are all the same type.
1124// Loop bound may be smaller (e.g., a char).
1125// Should zero extend loop bound, since it's always >= 0.
1126// This routine collects upper bound and extends or truncates if needed.
1127// Truncating is safe when subscripts are known not to wrap. Cases without
1128// nowrap flags should have been rejected earlier.
1129// Return null if no bound available.
1130const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
1131 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
1132 const SCEV *UB = SE->getBackedgeTakenCount(L);
1133 return SE->getTruncateOrZeroExtend(UB, T);
1134 }
1135 return nullptr;
1136}
1137
1138// Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
1139// If the cast fails, returns NULL.
1140const SCEVConstant *DependenceInfo::collectConstantUpperBound(const Loop *L,
1141 Type *T) const {
1142 if (const SCEV *UB = collectUpperBound(L, T))
1143 return dyn_cast<SCEVConstant>(UB);
1144 return nullptr;
1145}
1146
1147/// Returns \p A - \p B if it guaranteed not to signed wrap. Otherwise returns
1148/// nullptr. \p A and \p B must have the same integer type.
1149static const SCEV *minusSCEVNoSignedOverflow(const SCEV *A, const SCEV *B,
1150 ScalarEvolution &SE) {
1151 if (SE.willNotOverflow(Instruction::Sub, /*Signed=*/true, A, B))
1152 return SE.getMinusSCEV(A, B);
1153 return nullptr;
1154}
1155
1156/// Returns true iff \p Test is enabled.
1157static bool isDependenceTestEnabled(DependenceTestType Test) {
1158 if (EnableDependenceTest == DependenceTestType::All)
1159 return true;
1160 return EnableDependenceTest == Test;
1161}
1162
1163// testZIV -
1164// When we have a pair of subscripts of the form [c1] and [c2],
1165// where c1 and c2 are both loop invariant, we attack it using
1166// the ZIV test. Basically, we test by comparing the two values,
1167// but there are actually three possible results:
1168// 1) the values are equal, so there's a dependence
1169// 2) the values are different, so there's no dependence
1170// 3) the values might be equal, so we have to assume a dependence.
1171//
1172// Return true if dependence disproved.
1173bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
1174 FullDependence &Result) const {
1175 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
1176 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
1177 ++ZIVapplications;
1178 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
1179 LLVM_DEBUG(dbgs() << " provably dependent\n");
1180 return false; // provably dependent
1181 }
1182 if (SE->isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
1183 LLVM_DEBUG(dbgs() << " provably independent\n");
1184 ++ZIVindependence;
1185 return true; // provably independent
1186 }
1187 LLVM_DEBUG(dbgs() << " possibly dependent\n");
1188 return false; // possibly dependent
1189}
1190
1191// strongSIVtest -
1192// From the paper, Practical Dependence Testing, Section 4.2.1
1193//
1194// When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
1195// where i is an induction variable, c1 and c2 are loop invariant,
1196// and a is a constant, we can solve it exactly using the Strong SIV test.
1197//
1198// Can prove independence. Failing that, can compute distance (and direction).
1199// In the presence of symbolic terms, we can sometimes make progress.
1200//
1201// If there's a dependence,
1202//
1203// c1 + a*i = c2 + a*i'
1204//
1205// The dependence distance is
1206//
1207// d = i' - i = (c1 - c2)/a
1208//
1209// A dependence only exists if d is an integer and abs(d) <= U, where U is the
1210// loop's upper bound. If a dependence exists, the dependence direction is
1211// defined as
1212//
1213// { < if d > 0
1214// direction = { = if d = 0
1215// { > if d < 0
1216//
1217// Return true if dependence disproved.
1218bool DependenceInfo::strongSIVtest(const SCEVAddRecExpr *Src,
1219 const SCEVAddRecExpr *Dst, unsigned Level,
1220 FullDependence &Result,
1221 bool UnderRuntimeAssumptions) {
1222 if (!isDependenceTestEnabled(DependenceTestType::StrongSIV))
1223 return false;
1224
1225 if (!Src->hasNoSignedWrap() || !Dst->hasNoSignedWrap())
1226 return false;
1227
1228 const SCEV *Coeff = Src->getStepRecurrence(*SE);
1229 assert(Coeff == Dst->getStepRecurrence(*SE) &&
1230 "Expecting same coefficient in Strong SIV test");
1231 const SCEV *SrcConst = Src->getStart();
1232 const SCEV *DstConst = Dst->getStart();
1233 LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
1234 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff);
1235 LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1236 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
1237 LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1238 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst);
1239 LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
1240 ++StrongSIVapplications;
1241 assert(0 < Level && Level <= CommonLevels && "level out of range");
1242 Level--;
1243
1244 // First try to prove independence based on the ranges of the two subscripts.
1245 ConstantRange SrcRange = SE->getSignedRange(Src);
1246 ConstantRange DstRange = SE->getSignedRange(Dst);
1247 if (SrcRange.intersectWith(DstRange).isEmptySet()) {
1248 ++StrongSIVindependence;
1249 ++StrongSIVsuccesses;
1250 return true;
1251 }
1252
1253 const SCEV *Delta = minusSCEVNoSignedOverflow(SrcConst, DstConst, *SE);
1254 if (!Delta)
1255 return false;
1256 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta);
1257 LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
1258
1259 // Can we compute distance?
1260 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
1261 APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
1262 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
1263 APInt Distance = ConstDelta; // these need to be initialized
1264 APInt Remainder = ConstDelta;
1265 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
1266 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1267 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1268 // Make sure Coeff divides Delta exactly
1269 if (Remainder != 0) {
1270 // Coeff doesn't divide Distance, no dependence
1271 ++StrongSIVindependence;
1272 ++StrongSIVsuccesses;
1273 return true;
1274 }
1275 Result.DV[Level].Distance = SE->getConstant(Distance);
1276 if (Distance.sgt(0))
1277 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1278 else if (Distance.slt(0))
1279 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1280 else
1281 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1282 ++StrongSIVsuccesses;
1283 } else if (Delta->isZero()) {
1284 // Check if coefficient could be zero. If so, 0/0 is undefined and we
1285 // cannot conclude that only same-iteration dependencies exist.
1286 // When coeff=0, all iterations access the same location.
1287 if (SE->isKnownNonZero(Coeff)) {
1288 LLVM_DEBUG(
1289 dbgs() << "\t Coefficient proven non-zero by SCEV analysis\n");
1290 } else {
1291 // Cannot prove at compile time, would need runtime assumption.
1292 if (UnderRuntimeAssumptions) {
1293 const SCEVPredicate *Pred = SE->getComparePredicate(
1294 ICmpInst::ICMP_NE, Coeff, SE->getZero(Coeff->getType()));
1295 Result.Assumptions = Result.Assumptions.getUnionWith(Pred, *SE);
1296 LLVM_DEBUG(dbgs() << "\t Added runtime assumption: " << *Coeff
1297 << " != 0\n");
1298 } else {
1299 // Cannot add runtime assumptions, this test cannot handle this case.
1300 // Let more complex tests try.
1301 LLVM_DEBUG(dbgs() << "\t Would need runtime assumption " << *Coeff
1302 << " != 0, but not allowed. Failing this test.\n");
1303 return false;
1304 }
1305 }
1306 // Since 0/X == 0 (where X is known non-zero or assumed non-zero).
1307 Result.DV[Level].Distance = Delta;
1308 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1309 ++StrongSIVsuccesses;
1310 } else {
1311 if (Coeff->isOne()) {
1312 LLVM_DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
1313 Result.DV[Level].Distance = Delta; // since X/1 == X
1314 }
1315
1316 // maybe we can get a useful direction
1317 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
1318 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1319 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1320 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1321 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1322 // The double negatives above are confusing.
1323 // It helps to read !SE->isKnownNonZero(Delta)
1324 // as "Delta might be Zero"
1325 unsigned NewDirection = Dependence::DVEntry::NONE;
1326 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1327 (DeltaMaybeNegative && CoeffMaybeNegative))
1328 NewDirection = Dependence::DVEntry::LT;
1329 if (DeltaMaybeZero)
1330 NewDirection |= Dependence::DVEntry::EQ;
1331 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1332 (DeltaMaybePositive && CoeffMaybeNegative))
1333 NewDirection |= Dependence::DVEntry::GT;
1334 if (NewDirection < Result.DV[Level].Direction)
1335 ++StrongSIVsuccesses;
1336 Result.DV[Level].Direction &= NewDirection;
1337 }
1338 return false;
1339}
1340
1341// weakCrossingSIVtest -
1342// From the paper, Practical Dependence Testing, Section 4.2.2
1343//
1344// When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1345// where i is an induction variable, c1 and c2 are loop invariant,
1346// and a is a constant, we can solve it exactly using the
1347// Weak-Crossing SIV test.
1348//
1349// Given c1 + a*i = c2 - a*i', we can look for the intersection of
1350// the two lines, where i = i', yielding
1351//
1352// c1 + a*i = c2 - a*i
1353// 2a*i = c2 - c1
1354// i = (c2 - c1)/2a
1355//
1356// If i < 0, there is no dependence.
1357// If i > upperbound, there is no dependence.
1358// If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1359// If i = upperbound, there's a dependence with distance = 0.
1360// If i is integral, there's a dependence (all directions).
1361// If the non-integer part = 1/2, there's a dependence (<> directions).
1362// Otherwise, there's no dependence.
1363//
1364// Can prove independence. Failing that,
1365// can sometimes refine the directions.
1366// Can determine iteration for splitting.
1367//
1368// Return true if dependence disproved.
1369bool DependenceInfo::weakCrossingSIVtest(const SCEV *Coeff,
1370 const SCEV *SrcConst,
1371 const SCEV *DstConst,
1372 const Loop *CurSrcLoop,
1373 const Loop *CurDstLoop, unsigned Level,
1374 FullDependence &Result) const {
1375 if (!isDependenceTestEnabled(DependenceTestType::WeakCrossingSIV))
1376 return false;
1377
1378 LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1379 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1380 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1381 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1382 ++WeakCrossingSIVapplications;
1383 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1384 Level--;
1385 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1386 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1387 if (Delta->isZero()) {
1388 Result.DV[Level].Direction &= ~Dependence::DVEntry::LT;
1389 Result.DV[Level].Direction &= ~Dependence::DVEntry::GT;
1390 ++WeakCrossingSIVsuccesses;
1391 if (!Result.DV[Level].Direction) {
1392 ++WeakCrossingSIVindependence;
1393 return true;
1394 }
1395 Result.DV[Level].Distance = Delta; // = 0
1396 return false;
1397 }
1398 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1399 if (!ConstCoeff)
1400 return false;
1401
1402 if (SE->isKnownNegative(ConstCoeff)) {
1403 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1404 assert(ConstCoeff &&
1405 "dynamic cast of negative of ConstCoeff should yield constant");
1406 Delta = SE->getNegativeSCEV(Delta);
1407 }
1408 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1409
1410 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1411 if (!ConstDelta)
1412 return false;
1413
1414 // We're certain that ConstCoeff > 0; therefore,
1415 // if Delta < 0, then no dependence.
1416 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1417 LLVM_DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
1418 if (SE->isKnownNegative(Delta)) {
1419 // No dependence, Delta < 0
1420 ++WeakCrossingSIVindependence;
1421 ++WeakCrossingSIVsuccesses;
1422 return true;
1423 }
1424
1425 // We're certain that Delta > 0 and ConstCoeff > 0.
1426 // Check Delta/(2*ConstCoeff) against upper loop bound
1427 if (const SCEV *UpperBound =
1428 collectUpperBound(CurSrcLoop, Delta->getType())) {
1429 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1430 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1431 const SCEV *ML =
1432 SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound), ConstantTwo);
1433 LLVM_DEBUG(dbgs() << "\t ML = " << *ML << "\n");
1434 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1435 // Delta too big, no dependence
1436 ++WeakCrossingSIVindependence;
1437 ++WeakCrossingSIVsuccesses;
1438 return true;
1439 }
1440 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1441 // i = i' = UB
1442 Result.DV[Level].Direction &= ~Dependence::DVEntry::LT;
1443 Result.DV[Level].Direction &= ~Dependence::DVEntry::GT;
1444 ++WeakCrossingSIVsuccesses;
1445 if (!Result.DV[Level].Direction) {
1446 ++WeakCrossingSIVindependence;
1447 return true;
1448 }
1449 Result.DV[Level].Distance = SE->getZero(Delta->getType());
1450 return false;
1451 }
1452 }
1453
1454 // check that Coeff divides Delta
1455 APInt APDelta = ConstDelta->getAPInt();
1456 APInt APCoeff = ConstCoeff->getAPInt();
1457 APInt Distance = APDelta; // these need to be initialzed
1458 APInt Remainder = APDelta;
1459 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1460 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1461 if (Remainder != 0) {
1462 // Coeff doesn't divide Delta, no dependence
1463 ++WeakCrossingSIVindependence;
1464 ++WeakCrossingSIVsuccesses;
1465 return true;
1466 }
1467 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1468
1469 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1470 APInt Two = APInt(Distance.getBitWidth(), 2, true);
1471 Remainder = Distance.srem(Two);
1472 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1473 if (Remainder != 0) {
1474 // Equal direction isn't possible
1475 Result.DV[Level].Direction &= ~Dependence::DVEntry::EQ;
1476 ++WeakCrossingSIVsuccesses;
1477 }
1478 return false;
1479}
1480
1481// Kirch's algorithm, from
1482//
1483// Optimizing Supercompilers for Supercomputers
1484// Michael Wolfe
1485// MIT Press, 1989
1486//
1487// Program 2.1, page 29.
1488// Computes the GCD of AM and BM.
1489// Also finds a solution to the equation ax - by = gcd(a, b).
1490// Returns true if dependence disproved; i.e., gcd does not divide Delta.
1491//
1492// We don't use OverflowSafeSignedAPInt here because it's known that this
1493// algorithm doesn't overflow.
1494static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM,
1495 const APInt &Delta, APInt &G, APInt &X, APInt &Y) {
1496 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1497 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1498 APInt G0 = AM.abs();
1499 APInt G1 = BM.abs();
1500 APInt Q = G0; // these need to be initialized
1501 APInt R = G0;
1502 APInt::sdivrem(G0, G1, Q, R);
1503 while (R != 0) {
1504 // clang-format off
1505 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1506 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1507 G0 = G1; G1 = R;
1508 // clang-format on
1509 APInt::sdivrem(G0, G1, Q, R);
1510 }
1511 G = G1;
1512 LLVM_DEBUG(dbgs() << "\t GCD = " << G << "\n");
1513 X = AM.slt(0) ? -A1 : A1;
1514 Y = BM.slt(0) ? B1 : -B1;
1515
1516 // make sure gcd divides Delta
1517 R = Delta.srem(G);
1518 if (R != 0)
1519 return true; // gcd doesn't divide Delta, no dependence
1520 Q = Delta.sdiv(G);
1521 return false;
1522}
1523
1524static OverflowSafeSignedAPInt
1525floorOfQuotient(const OverflowSafeSignedAPInt &OA,
1526 const OverflowSafeSignedAPInt &OB) {
1527 if (!OA || !OB)
1528 return OverflowSafeSignedAPInt();
1529
1530 APInt A = *OA;
1531 APInt B = *OB;
1532 APInt Q = A; // these need to be initialized
1533 APInt R = A;
1534 APInt::sdivrem(A, B, Q, R);
1535 if (R == 0)
1536 return Q;
1537 if ((A.sgt(0) && B.sgt(0)) || (A.slt(0) && B.slt(0)))
1538 return Q;
1539 return OverflowSafeSignedAPInt(Q) - 1;
1540}
1541
1542static OverflowSafeSignedAPInt
1543ceilingOfQuotient(const OverflowSafeSignedAPInt &OA,
1544 const OverflowSafeSignedAPInt &OB) {
1545 if (!OA || !OB)
1546 return OverflowSafeSignedAPInt();
1547
1548 APInt A = *OA;
1549 APInt B = *OB;
1550 APInt Q = A; // these need to be initialized
1551 APInt R = A;
1552 APInt::sdivrem(A, B, Q, R);
1553 if (R == 0)
1554 return Q;
1555 if ((A.sgt(0) && B.sgt(0)) || (A.slt(0) && B.slt(0)))
1556 return OverflowSafeSignedAPInt(Q) + 1;
1557 return Q;
1558}
1559
1560/// Given an affine expression of the form A*k + B, where k is an arbitrary
1561/// integer, infer the possible range of k based on the known range of the
1562/// affine expression. If we know A*k + B is non-negative, i.e.,
1563///
1564/// A*k + B >= 0
1565///
1566/// we can derive the following inequalities for k when A is positive:
1567///
1568/// k >= -B / A
1569///
1570/// Since k is an integer, it means k is greater than or equal to the
1571/// ceil(-B / A).
1572///
1573/// If the upper bound of the affine expression \p UB is passed, the following
1574/// inequality can be derived as well:
1575///
1576/// A*k + B <= UB
1577///
1578/// which leads to:
1579///
1580/// k <= (UB - B) / A
1581///
1582/// Again, as k is an integer, it means k is less than or equal to the
1583/// floor((UB - B) / A).
1584///
1585/// The similar logic applies when A is negative, but the inequalities sign flip
1586/// while working with them.
1587///
1588/// Preconditions: \p A is non-zero, and we know A*k + B is non-negative.
1589static std::pair<OverflowSafeSignedAPInt, OverflowSafeSignedAPInt>
1590inferDomainOfAffine(OverflowSafeSignedAPInt A, OverflowSafeSignedAPInt B,
1591 OverflowSafeSignedAPInt UB) {
1592 assert(A && B && "A and B must be available");
1593 assert(*A != 0 && "A must be non-zero");
1594 OverflowSafeSignedAPInt TL, TU;
1595 if (A->sgt(0)) {
1596 TL = ceilingOfQuotient(-B, A);
1597 LLVM_DEBUG(if (TL) dbgs() << "\t Possible TL = " << *TL << "\n");
1598
1599 // New bound check - modification to Banerjee's e3 check
1600 TU = floorOfQuotient(UB - B, A);
1601 LLVM_DEBUG(if (TU) dbgs() << "\t Possible TU = " << *TU << "\n");
1602 } else {
1603 TU = floorOfQuotient(-B, A);
1604 LLVM_DEBUG(if (TU) dbgs() << "\t Possible TU = " << *TU << "\n");
1605
1606 // New bound check - modification to Banerjee's e3 check
1607 TL = ceilingOfQuotient(UB - B, A);
1608 LLVM_DEBUG(if (TL) dbgs() << "\t Possible TL = " << *TL << "\n");
1609 }
1610 return std::make_pair(TL, TU);
1611}
1612
1613// exactSIVtest -
1614// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1615// where i is an induction variable, c1 and c2 are loop invariant, and a1
1616// and a2 are constant, we can solve it exactly using an algorithm developed
1617// by Banerjee and Wolfe. See Algorithm 6.2.1 (case 2.5) in:
1618//
1619// Dependence Analysis for Supercomputing
1620// Utpal Banerjee
1621// Kluwer Academic Publishers, 1988
1622//
1623// It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1624// so use them if possible. They're also a bit better with symbolics and,
1625// in the case of the strong SIV test, can compute Distances.
1626//
1627// Return true if dependence disproved.
1628//
1629// This is a modified version of the original Banerjee algorithm. The original
1630// only tested whether Dst depends on Src. This algorithm extends that and
1631// returns all the dependencies that exist between Dst and Src.
1632bool DependenceInfo::exactSIVtest(const SCEVAddRecExpr *Src,
1633 const SCEVAddRecExpr *Dst, unsigned Level,
1634 FullDependence &Result) const {
1635 if (!isDependenceTestEnabled(DependenceTestType::ExactSIV))
1636 return false;
1637
1638 const SCEV *SrcCoeff = Src->getStepRecurrence(*SE);
1639 const SCEV *SrcConst = Src->getStart();
1640 const SCEV *DstCoeff = Dst->getStepRecurrence(*SE);
1641 const SCEV *DstConst = Dst->getStart();
1642 LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
1643 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1644 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1645 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1646 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1647 ++ExactSIVapplications;
1648 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1649 Level--;
1650
1651 if (!Src->hasNoSignedWrap() || !Dst->hasNoSignedWrap())
1652 return false;
1653
1654 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
1655 if (!Delta)
1656 return false;
1657 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1658 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1659 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1660 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1661 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1662 return false;
1663
1664 // find gcd
1665 APInt G, X, Y;
1666 APInt AM = ConstSrcCoeff->getAPInt();
1667 APInt BM = ConstDstCoeff->getAPInt();
1668 APInt CM = ConstDelta->getAPInt();
1669 unsigned Bits = AM.getBitWidth();
1670 if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
1671 // gcd doesn't divide Delta, no dependence
1672 ++ExactSIVindependence;
1673 ++ExactSIVsuccesses;
1674 return true;
1675 }
1676
1677 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1678
1679 // since SCEV construction normalizes, LM = 0
1680 std::optional<APInt> UM;
1681 // UM is perhaps unavailable, let's check
1682 if (const SCEVConstant *CUB =
1683 collectConstantUpperBound(Src->getLoop(), Delta->getType())) {
1684 UM = CUB->getAPInt();
1685 LLVM_DEBUG(dbgs() << "\t UM = " << *UM << "\n");
1686 }
1687
1688 APInt TU(APInt::getSignedMaxValue(Bits));
1689 APInt TL(APInt::getSignedMinValue(Bits));
1690 APInt TC = CM.sdiv(G);
1691 APInt TX = X * TC;
1692 APInt TY = Y * TC;
1693 LLVM_DEBUG(dbgs() << "\t TC = " << TC << "\n");
1694 LLVM_DEBUG(dbgs() << "\t TX = " << TX << "\n");
1695 LLVM_DEBUG(dbgs() << "\t TY = " << TY << "\n");
1696
1697 APInt TB = BM.sdiv(G);
1698 APInt TA = AM.sdiv(G);
1699
1700 // At this point, we have the following equations:
1701 //
1702 // TA*i0 - TB*i1 = TC
1703 //
1704 // Also, we know that the all pairs of (i0, i1) can be expressed as:
1705 //
1706 // (TX + k*TB, TY + k*TA)
1707 //
1708 // where k is an arbitrary integer.
1709 auto [TL0, TU0] = inferDomainOfAffine(TB, TX, UM);
1710 auto [TL1, TU1] = inferDomainOfAffine(TA, TY, UM);
1711
1712 auto GetMaxOrMin = [](const OverflowSafeSignedAPInt &V0,
1713 const OverflowSafeSignedAPInt &V1,
1714 bool IsMin) -> std::optional<APInt> {
1715 if (V0 && V1)
1716 return IsMin ? APIntOps::smin(*V0, *V1) : APIntOps::smax(*V0, *V1);
1717 if (V0)
1718 return *V0;
1719 if (V1)
1720 return *V1;
1721 return std::nullopt;
1722 };
1723
1724 LLVM_DEBUG(dbgs() << "\t TA = " << TA << "\n");
1725 LLVM_DEBUG(dbgs() << "\t TB = " << TB << "\n");
1726
1727 std::optional<APInt> OptTL = GetMaxOrMin(TL0, TL1, false);
1728 std::optional<APInt> OptTU = GetMaxOrMin(TU0, TU1, true);
1729 if (!OptTL || !OptTU)
1730 return false;
1731
1732 TL = std::move(*OptTL);
1733 TU = std::move(*OptTU);
1734 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
1735 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
1736
1737 if (TL.sgt(TU)) {
1738 ++ExactSIVindependence;
1739 ++ExactSIVsuccesses;
1740 return true;
1741 }
1742
1743 // explore directions
1744 unsigned NewDirection = Dependence::DVEntry::NONE;
1745 OverflowSafeSignedAPInt LowerDistance, UpperDistance;
1746 OverflowSafeSignedAPInt OTY(TY), OTX(TX), OTA(TA), OTB(TB), OTL(TL), OTU(TU);
1747 // NOTE: It's unclear whether these calculations can overflow. At the moment,
1748 // we conservatively assume they can.
1749 if (TA.sgt(TB)) {
1750 LowerDistance = (OTY - OTX) + (OTA - OTB) * OTL;
1751 UpperDistance = (OTY - OTX) + (OTA - OTB) * OTU;
1752 } else {
1753 LowerDistance = (OTY - OTX) + (OTA - OTB) * OTU;
1754 UpperDistance = (OTY - OTX) + (OTA - OTB) * OTL;
1755 }
1756
1757 if (!LowerDistance || !UpperDistance)
1758 return false;
1759
1760 LLVM_DEBUG(dbgs() << "\t LowerDistance = " << *LowerDistance << "\n");
1761 LLVM_DEBUG(dbgs() << "\t UpperDistance = " << *UpperDistance << "\n");
1762
1763 if (LowerDistance->sle(0) && UpperDistance->sge(0)) {
1764 NewDirection |= Dependence::DVEntry::EQ;
1765 ++ExactSIVsuccesses;
1766 }
1767 if (LowerDistance->slt(0)) {
1768 NewDirection |= Dependence::DVEntry::GT;
1769 ++ExactSIVsuccesses;
1770 }
1771 if (UpperDistance->sgt(0)) {
1772 NewDirection |= Dependence::DVEntry::LT;
1773 ++ExactSIVsuccesses;
1774 }
1775
1776 // finished
1777 Result.DV[Level].Direction &= NewDirection;
1778 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1779 ++ExactSIVindependence;
1780 LLVM_DEBUG(dbgs() << "\t Result = ");
1781 LLVM_DEBUG(Result.dump(dbgs()));
1782 return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1783}
1784
1785// Return true if the divisor evenly divides the dividend.
1786static bool isRemainderZero(const SCEVConstant *Dividend,
1787 const SCEVConstant *Divisor) {
1788 const APInt &ConstDividend = Dividend->getAPInt();
1789 const APInt &ConstDivisor = Divisor->getAPInt();
1790 return ConstDividend.srem(ConstDivisor) == 0;
1791}
1792
1793// weakZeroSrcSIVtest -
1794// From the paper, Practical Dependence Testing, Section 4.2.2
1795//
1796// When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1797// where i is an induction variable, c1 and c2 are loop invariant,
1798// and a is a constant, we can solve it exactly using the
1799// Weak-Zero SIV test.
1800//
1801// Given
1802//
1803// c1 = c2 + a*i
1804//
1805// we get
1806//
1807// (c1 - c2)/a = i
1808//
1809// If i is not an integer, there's no dependence.
1810// If i < 0 or > UB, there's no dependence.
1811// If i = 0, the direction is >=.
1812// If i = UB, the direction is <=.
1813// Otherwise, the direction is *.
1814//
1815// Can prove independence. Failing that, we can sometimes refine
1816// the directions. Can sometimes show that first or last
1817// iteration carries all the dependences (so worth peeling).
1818//
1819// (see also weakZeroDstSIVtest)
1820//
1821// Return true if dependence disproved.
1822bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *SrcConst,
1823 const SCEVAddRecExpr *Dst,
1824 unsigned Level,
1825 FullDependence &Result) const {
1826 if (!isDependenceTestEnabled(DependenceTestType::WeakZeroSIV))
1827 return false;
1828
1829 // For the WeakSIV test, it's possible the loop isn't common to
1830 // the Src and Dst loops. If it isn't, then there's no need to
1831 // record a direction.
1832 const SCEV *DstCoeff = Dst->getStepRecurrence(*SE);
1833 const SCEV *DstConst = Dst->getStart();
1834 LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1835 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1836 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1837 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1838 ++WeakZeroSIVapplications;
1839 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1840 Level--;
1841
1842 ConstantRange SrcRange = SE->getSignedRange(SrcConst);
1843 ConstantRange DstRange = SE->getSignedRange(Dst);
1844 if (SrcRange.intersectWith(DstRange).isEmptySet()) {
1845 ++WeakZeroSIVindependence;
1846 ++WeakZeroSIVsuccesses;
1847 return true;
1848 }
1849
1850 if (SrcConst == DstConst && SE->isKnownNonZero(DstCoeff)) {
1851 if (Level < CommonLevels) {
1852 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1853 ++WeakZeroSIVsuccesses;
1854 }
1855 return false; // dependences caused by first iteration
1856 }
1857 const SCEV *Delta = minusSCEVNoSignedOverflow(SrcConst, DstConst, *SE);
1858 if (!Delta)
1859 return false;
1860 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1861 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1862 if (!ConstCoeff)
1863 return false;
1864
1865 // Since ConstCoeff is constant, !isKnownNegative means it's non-negative.
1866 // TODO: Bail out if it's a signed minimum value.
1867 const SCEV *AbsCoeff = SE->isKnownNegative(ConstCoeff)
1868 ? SE->getNegativeSCEV(ConstCoeff)
1869 : ConstCoeff;
1870 const SCEV *NewDelta =
1871 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1872
1873 if (const SCEV *UpperBound =
1874 collectUpperBound(Dst->getLoop(), Delta->getType())) {
1875 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1876 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1877 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1878 // dependences caused by last iteration
1879 if (Level < CommonLevels) {
1880 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1881 ++WeakZeroSIVsuccesses;
1882 }
1883 return false;
1884 }
1885 }
1886
1887 // check that Delta/SrcCoeff >= 0
1888 // really check that NewDelta >= 0
1889 if (SE->isKnownNegative(NewDelta)) {
1890 // No dependence, newDelta < 0
1891 ++WeakZeroSIVindependence;
1892 ++WeakZeroSIVsuccesses;
1893 return true;
1894 }
1895
1896 // if SrcCoeff doesn't divide Delta, then no dependence
1897 if (isa<SCEVConstant>(Delta) &&
1898 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1899 ++WeakZeroSIVindependence;
1900 ++WeakZeroSIVsuccesses;
1901 return true;
1902 }
1903 return false;
1904}
1905
1906// weakZeroDstSIVtest -
1907// From the paper, Practical Dependence Testing, Section 4.2.2
1908//
1909// When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1910// where i is an induction variable, c1 and c2 are loop invariant,
1911// and a is a constant, we can solve it exactly using the
1912// Weak-Zero SIV test.
1913//
1914// Given
1915//
1916// c1 + a*i = c2
1917//
1918// we get
1919//
1920// i = (c2 - c1)/a
1921//
1922// If i is not an integer, there's no dependence.
1923// If i < 0 or > UB, there's no dependence.
1924// If i = 0, the direction is <=.
1925// If i = UB, the direction is >=.
1926// Otherwise, the direction is *.
1927//
1928// Can prove independence. Failing that, we can sometimes refine
1929// the directions. Can sometimes show that first or last
1930// iteration carries all the dependences (so worth peeling).
1931//
1932// (see also weakZeroSrcSIVtest)
1933//
1934// Return true if dependence disproved.
1935bool DependenceInfo::weakZeroDstSIVtest(const SCEVAddRecExpr *Src,
1936 const SCEV *DstConst, unsigned Level,
1937 FullDependence &Result) const {
1938 if (!isDependenceTestEnabled(DependenceTestType::WeakZeroSIV))
1939 return false;
1940
1941 // For the WeakSIV test, it's possible the loop isn't common to the
1942 // Src and Dst loops. If it isn't, then there's no need to record a direction.
1943 const SCEV *SrcCoeff = Src->getStepRecurrence(*SE);
1944 const SCEV *SrcConst = Src->getStart();
1945 LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1946 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1947 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1948 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1949 ++WeakZeroSIVapplications;
1950 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1951 Level--;
1952
1953 ConstantRange SrcRange = SE->getSignedRange(Src);
1954 ConstantRange DstRange = SE->getSignedRange(DstConst);
1955 if (SrcRange.intersectWith(DstRange).isEmptySet()) {
1956 ++WeakZeroSIVindependence;
1957 ++WeakZeroSIVsuccesses;
1958 return true;
1959 }
1960
1961 if (DstConst == SrcConst && SE->isKnownNonZero(SrcCoeff)) {
1962 if (Level < CommonLevels) {
1963 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1964 ++WeakZeroSIVsuccesses;
1965 }
1966 return false; // dependences caused by first iteration
1967 }
1968 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
1969 if (!Delta)
1970 return false;
1971 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1972 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1973 if (!ConstCoeff)
1974 return false;
1975
1976 // Since ConstCoeff is constant, !isKnownNegative means it's non-negative.
1977 // TODO: Bail out if it's a signed minimum value.
1978 const SCEV *AbsCoeff = SE->isKnownNegative(ConstCoeff)
1979 ? SE->getNegativeSCEV(ConstCoeff)
1980 : ConstCoeff;
1981 const SCEV *NewDelta =
1982 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1983
1984 if (const SCEV *UpperBound =
1985 collectUpperBound(Src->getLoop(), Delta->getType())) {
1986 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1987 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1988 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1989 // dependences caused by last iteration
1990 if (Level < CommonLevels) {
1991 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1992 ++WeakZeroSIVsuccesses;
1993 }
1994 return false;
1995 }
1996 }
1997
1998 // check that Delta/SrcCoeff >= 0
1999 // really check that NewDelta >= 0
2000 if (SE->isKnownNegative(NewDelta)) {
2001 // No dependence, newDelta < 0
2002 ++WeakZeroSIVindependence;
2003 ++WeakZeroSIVsuccesses;
2004 return true;
2005 }
2006
2007 // if SrcCoeff doesn't divide Delta, then no dependence
2008 if (isa<SCEVConstant>(Delta) &&
2009 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
2010 ++WeakZeroSIVindependence;
2011 ++WeakZeroSIVsuccesses;
2012 return true;
2013 }
2014 return false;
2015}
2016
2017// exactRDIVtest - Tests the RDIV subscript pair for dependence.
2018// Things of the form [c1 + a*i] and [c2 + b*j],
2019// where i and j are induction variable, c1 and c2 are loop invariant,
2020// and a and b are constants.
2021// Returns true if any possible dependence is disproved.
2022// Works in some cases that symbolicRDIVtest doesn't, and vice versa.
2023bool DependenceInfo::exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
2024 const SCEV *SrcConst, const SCEV *DstConst,
2025 const Loop *SrcLoop, const Loop *DstLoop,
2026 FullDependence &Result) const {
2027 if (!isDependenceTestEnabled(DependenceTestType::ExactRDIV))
2028 return false;
2029
2030 LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
2031 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
2032 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
2033 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
2034 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
2035 ++ExactRDIVapplications;
2036 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
2037 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
2038 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
2039 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
2040 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
2041 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
2042 return false;
2043
2044 // find gcd
2045 APInt G, X, Y;
2046 APInt AM = ConstSrcCoeff->getAPInt();
2047 APInt BM = ConstDstCoeff->getAPInt();
2048 APInt CM = ConstDelta->getAPInt();
2049 unsigned Bits = AM.getBitWidth();
2050 if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
2051 // gcd doesn't divide Delta, no dependence
2052 ++ExactRDIVindependence;
2053 return true;
2054 }
2055
2056 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
2057
2058 // since SCEV construction seems to normalize, LM = 0
2059 std::optional<APInt> SrcUM;
2060 // SrcUM is perhaps unavailable, let's check
2061 if (const SCEVConstant *UpperBound =
2062 collectConstantUpperBound(SrcLoop, Delta->getType())) {
2063 SrcUM = UpperBound->getAPInt();
2064 LLVM_DEBUG(dbgs() << "\t SrcUM = " << *SrcUM << "\n");
2065 }
2066
2067 std::optional<APInt> DstUM;
2068 // UM is perhaps unavailable, let's check
2069 if (const SCEVConstant *UpperBound =
2070 collectConstantUpperBound(DstLoop, Delta->getType())) {
2071 DstUM = UpperBound->getAPInt();
2072 LLVM_DEBUG(dbgs() << "\t DstUM = " << *DstUM << "\n");
2073 }
2074
2075 APInt TU(APInt::getSignedMaxValue(Bits));
2076 APInt TL(APInt::getSignedMinValue(Bits));
2077 APInt TC = CM.sdiv(G);
2078 APInt TX = X * TC;
2079 APInt TY = Y * TC;
2080 LLVM_DEBUG(dbgs() << "\t TC = " << TC << "\n");
2081 LLVM_DEBUG(dbgs() << "\t TX = " << TX << "\n");
2082 LLVM_DEBUG(dbgs() << "\t TY = " << TY << "\n");
2083
2084 APInt TB = BM.sdiv(G);
2085 APInt TA = AM.sdiv(G);
2086
2087 // At this point, we have the following equations:
2088 //
2089 // TA*i - TB*j = TC
2090 //
2091 // Also, we know that the all pairs of (i, j) can be expressed as:
2092 //
2093 // (TX + k*TB, TY + k*TA)
2094 //
2095 // where k is an arbitrary integer.
2096 auto [TL0, TU0] = inferDomainOfAffine(TB, TX, SrcUM);
2097 auto [TL1, TU1] = inferDomainOfAffine(TA, TY, DstUM);
2098
2099 LLVM_DEBUG(dbgs() << "\t TA = " << TA << "\n");
2100 LLVM_DEBUG(dbgs() << "\t TB = " << TB << "\n");
2101
2102 auto GetMaxOrMin = [](const OverflowSafeSignedAPInt &V0,
2103 const OverflowSafeSignedAPInt &V1,
2104 bool IsMin) -> std::optional<APInt> {
2105 if (V0 && V1)
2106 return IsMin ? APIntOps::smin(*V0, *V1) : APIntOps::smax(*V0, *V1);
2107 if (V0)
2108 return *V0;
2109 if (V1)
2110 return *V1;
2111 return std::nullopt;
2112 };
2113
2114 std::optional<APInt> OptTL = GetMaxOrMin(TL0, TL1, false);
2115 std::optional<APInt> OptTU = GetMaxOrMin(TU0, TU1, true);
2116 if (!OptTL || !OptTU)
2117 return false;
2118
2119 TL = std::move(*OptTL);
2120 TU = std::move(*OptTU);
2121 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
2122 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
2123
2124 if (TL.sgt(TU))
2125 ++ExactRDIVindependence;
2126 return TL.sgt(TU);
2127}
2128
2129// symbolicRDIVtest -
2130// In Section 4.5 of the Practical Dependence Testing paper,the authors
2131// introduce a special case of Banerjee's Inequalities (also called the
2132// Extreme-Value Test) that can handle some of the SIV and RDIV cases,
2133// particularly cases with symbolics. Since it's only able to disprove
2134// dependence (not compute distances or directions), we'll use it as a
2135// fall back for the other tests.
2136//
2137// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2138// where i and j are induction variables and c1 and c2 are loop invariants,
2139// we can use the symbolic tests to disprove some dependences, serving as a
2140// backup for the RDIV test. Note that i and j can be the same variable,
2141// letting this test serve as a backup for the various SIV tests.
2142//
2143// For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
2144// 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
2145// loop bounds for the i and j loops, respectively. So, ...
2146//
2147// c1 + a1*i = c2 + a2*j
2148// a1*i - a2*j = c2 - c1
2149//
2150// To test for a dependence, we compute c2 - c1 and make sure it's in the
2151// range of the maximum and minimum possible values of a1*i - a2*j.
2152// Considering the signs of a1 and a2, we have 4 possible cases:
2153//
2154// 1) If a1 >= 0 and a2 >= 0, then
2155// a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
2156// -a2*N2 <= c2 - c1 <= a1*N1
2157//
2158// 2) If a1 >= 0 and a2 <= 0, then
2159// a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
2160// 0 <= c2 - c1 <= a1*N1 - a2*N2
2161//
2162// 3) If a1 <= 0 and a2 >= 0, then
2163// a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
2164// a1*N1 - a2*N2 <= c2 - c1 <= 0
2165//
2166// 4) If a1 <= 0 and a2 <= 0, then
2167// a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
2168// a1*N1 <= c2 - c1 <= -a2*N2
2169//
2170// return true if dependence disproved
2171bool DependenceInfo::symbolicRDIVtest(const SCEVAddRecExpr *Src,
2172 const SCEVAddRecExpr *Dst) const {
2173 if (!isDependenceTestEnabled(DependenceTestType::SymbolicRDIV))
2174 return false;
2175
2176 ++SymbolicRDIVapplications;
2177 LLVM_DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
2178 ConstantRange SrcRange = SE->getSignedRange(Src);
2179 ConstantRange DstRange = SE->getSignedRange(Dst);
2180 LLVM_DEBUG(dbgs() << "\n SrcRange: " << SrcRange << "\n");
2181 LLVM_DEBUG(dbgs() << "\n DstRange: " << DstRange << "\n");
2182 if (SrcRange.intersectWith(DstRange).isEmptySet()) {
2183 ++SymbolicRDIVindependence;
2184 return true;
2185 }
2186 return false;
2187}
2188
2189// testSIV -
2190// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2191// where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2192// a2 are constant, we attack it with an SIV test. While they can all be
2193// solved with the Exact SIV test, it's worthwhile to use simpler tests when
2194// they apply; they're cheaper and sometimes more precise.
2195//
2196// Return true if dependence disproved.
2197bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
2198 FullDependence &Result,
2199 bool UnderRuntimeAssumptions) {
2200 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2201 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
2202 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2203 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2204 if (SrcAddRec && DstAddRec) {
2205 const SCEV *SrcConst = SrcAddRec->getStart();
2206 const SCEV *DstConst = DstAddRec->getStart();
2207 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2208 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2209 const Loop *CurSrcLoop = SrcAddRec->getLoop();
2210 const Loop *CurDstLoop = DstAddRec->getLoop();
2211 assert(haveSameSD(CurSrcLoop, CurDstLoop) &&
2212 "Loops in the SIV test should have the same iteration space and "
2213 "depth");
2214 Level = mapSrcLoop(CurSrcLoop);
2215 bool disproven;
2216 if (SrcCoeff == DstCoeff)
2217 disproven = strongSIVtest(SrcAddRec, DstAddRec, Level, Result,
2218 UnderRuntimeAssumptions);
2219 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2220 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurSrcLoop,
2221 CurDstLoop, Level, Result);
2222 else
2223 disproven = exactSIVtest(SrcAddRec, DstAddRec, Level, Result);
2224 return disproven || gcdMIVtest(Src, Dst, Result) ||
2225 symbolicRDIVtest(SrcAddRec, DstAddRec);
2226 }
2227 if (SrcAddRec) {
2228 const Loop *CurSrcLoop = SrcAddRec->getLoop();
2229 Level = mapSrcLoop(CurSrcLoop);
2230 return weakZeroDstSIVtest(SrcAddRec, Dst, Level, Result) ||
2231 gcdMIVtest(Src, Dst, Result);
2232 }
2233 if (DstAddRec) {
2234 const Loop *CurDstLoop = DstAddRec->getLoop();
2235 Level = mapDstLoop(CurDstLoop);
2236 return weakZeroSrcSIVtest(Src, DstAddRec, Level, Result) ||
2237 gcdMIVtest(Src, Dst, Result);
2238 }
2239 llvm_unreachable("SIV test expected at least one AddRec");
2240 return false;
2241}
2242
2243// testRDIV -
2244// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2245// where i and j are induction variables, c1 and c2 are loop invariant,
2246// and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2247// of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2248// It doesn't make sense to talk about distance or direction in this case,
2249// so there's no point in making special versions of the Strong SIV test or
2250// the Weak-crossing SIV test.
2251//
2252// Return true if dependence disproved.
2253bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
2254 FullDependence &Result) const {
2255 const SCEV *SrcConst, *DstConst;
2256 const SCEV *SrcCoeff, *DstCoeff;
2257 const Loop *SrcLoop, *DstLoop;
2258
2259 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2260 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
2261 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2262 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2263 if (SrcAddRec && DstAddRec) {
2264 SrcConst = SrcAddRec->getStart();
2265 SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2266 SrcLoop = SrcAddRec->getLoop();
2267 DstConst = DstAddRec->getStart();
2268 DstCoeff = DstAddRec->getStepRecurrence(*SE);
2269 DstLoop = DstAddRec->getLoop();
2270 } else
2271 llvm_unreachable("RDIV expected at least one AddRec");
2272 return exactRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, SrcLoop, DstLoop,
2273 Result) ||
2274 gcdMIVtest(Src, Dst, Result) || symbolicRDIVtest(SrcAddRec, DstAddRec);
2275}
2276
2277// Tests the single-subscript MIV pair (Src and Dst) for dependence.
2278// Return true if dependence disproved.
2279// Can sometimes refine direction vectors.
2280bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
2281 const SmallBitVector &Loops,
2282 FullDependence &Result) const {
2283 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2284 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
2285 return gcdMIVtest(Src, Dst, Result) ||
2286 banerjeeMIVtest(Src, Dst, Loops, Result);
2287}
2288
2289/// Given a SCEVMulExpr, returns its first operand if its first operand is a
2290/// constant and the product doesn't overflow in a signed sense. Otherwise,
2291/// returns std::nullopt. For example, given (10 * X * Y)<nsw>, it returns 10.
2292/// Notably, if it doesn't have nsw, the multiplication may overflow, and if
2293/// so, it may not a multiple of 10.
2294static std::optional<APInt> getConstantCoefficient(const SCEV *Expr) {
2295 if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
2296 return Constant->getAPInt();
2297 if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
2298 if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
2299 if (Product->hasNoSignedWrap())
2300 return Constant->getAPInt();
2301 return std::nullopt;
2302}
2303
2304bool DependenceInfo::accumulateCoefficientsGCD(const SCEV *Expr,
2305 const Loop *CurLoop,
2306 const SCEV *&CurLoopCoeff,
2307 APInt &RunningGCD) const {
2308 // If RunningGCD is already 1, exit early.
2309 // TODO: It might be better to continue the recursion to find CurLoopCoeff.
2310 if (RunningGCD == 1)
2311 return true;
2312
2313 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2314 if (!AddRec) {
2315 assert(isLoopInvariant(Expr, CurLoop) &&
2316 "Expected loop invariant expression");
2317 return true;
2318 }
2319
2320 assert(AddRec->isAffine() && "Unexpected Expr");
2321 const SCEV *Start = AddRec->getStart();
2322 const SCEV *Step = AddRec->getStepRecurrence(*SE);
2323 if (AddRec->getLoop() == CurLoop) {
2324 CurLoopCoeff = Step;
2325 } else {
2326 std::optional<APInt> ConstCoeff = getConstantCoefficient(Step);
2327
2328 // If the coefficient is the product of a constant and other stuff, we can
2329 // use the constant in the GCD computation.
2330 if (!ConstCoeff)
2331 return false;
2332
2333 // TODO: What happens if ConstCoeff is the "most negative" signed number
2334 // (e.g. -128 for 8 bit wide APInt)?
2335 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2336 }
2337
2338 return accumulateCoefficientsGCD(Start, CurLoop, CurLoopCoeff, RunningGCD);
2339}
2340
2341//===----------------------------------------------------------------------===//
2342// gcdMIVtest -
2343// Tests an MIV subscript pair for dependence.
2344// Returns true if any possible dependence is disproved.
2345// Can sometimes disprove the equal direction for 1 or more loops,
2346// as discussed in Michael Wolfe's book,
2347// High Performance Compilers for Parallel Computing, page 235.
2348//
2349// We spend some effort (code!) to handle cases like
2350// [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2351// but M and N are just loop-invariant variables.
2352// This should help us handle linearized subscripts;
2353// also makes this test a useful backup to the various SIV tests.
2354//
2355// It occurs to me that the presence of loop-invariant variables
2356// changes the nature of the test from "greatest common divisor"
2357// to "a common divisor".
2358bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
2359 FullDependence &Result) const {
2360 if (!isDependenceTestEnabled(DependenceTestType::GCDMIV))
2361 return false;
2362
2363 LLVM_DEBUG(dbgs() << "starting gcd\n");
2364 ++GCDapplications;
2365 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
2366 APInt RunningGCD = APInt::getZero(BitWidth);
2367
2368 // Examine Src coefficients.
2369 // Compute running GCD and record source constant.
2370 // Because we're looking for the constant at the end of the chain,
2371 // we can't quit the loop just because the GCD == 1.
2372 const SCEV *Coefficients = Src;
2373 while (const SCEVAddRecExpr *AddRec =
2374 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2375 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2376 // If the coefficient is the product of a constant and other stuff,
2377 // we can use the constant in the GCD computation.
2378 std::optional<APInt> ConstCoeff = getConstantCoefficient(Coeff);
2379 if (!ConstCoeff)
2380 return false;
2381 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2382 Coefficients = AddRec->getStart();
2383 }
2384 const SCEV *SrcConst = Coefficients;
2385
2386 // Examine Dst coefficients.
2387 // Compute running GCD and record destination constant.
2388 // Because we're looking for the constant at the end of the chain,
2389 // we can't quit the loop just because the GCD == 1.
2390 Coefficients = Dst;
2391 while (const SCEVAddRecExpr *AddRec =
2392 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2393 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2394 // If the coefficient is the product of a constant and other stuff,
2395 // we can use the constant in the GCD computation.
2396 std::optional<APInt> ConstCoeff = getConstantCoefficient(Coeff);
2397 if (!ConstCoeff)
2398 return false;
2399 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2400 Coefficients = AddRec->getStart();
2401 }
2402 const SCEV *DstConst = Coefficients;
2403
2404 APInt ExtraGCD = APInt::getZero(BitWidth);
2405 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
2406 if (!Delta)
2407 return false;
2408 LLVM_DEBUG(dbgs() << " Delta = " << *Delta << "\n");
2409 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2410 if (!Constant)
2411 return false;
2412 APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
2413 LLVM_DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
2414 if (ConstDelta == 0)
2415 return false;
2416 LLVM_DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
2417 APInt Remainder = ConstDelta.srem(RunningGCD);
2418 if (Remainder != 0) {
2419 ++GCDindependence;
2420 return true;
2421 }
2422
2423 // Try to disprove equal directions.
2424 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2425 // the code above can't disprove the dependence because the GCD = 1.
2426 // So we consider what happen if i = i' and what happens if j = j'.
2427 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2428 // which is infeasible, so we can disallow the = direction for the i level.
2429 // Setting j = j' doesn't help matters, so we end up with a direction vector
2430 // of [<>, *]
2431 //
2432 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2433 // we need to remember that the constant part is 5 and the RunningGCD should
2434 // be initialized to ExtraGCD = 30.
2435 LLVM_DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
2436
2437 bool Improved = false;
2438 Coefficients = Src;
2439 while (const SCEVAddRecExpr *AddRec =
2440 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2441 Coefficients = AddRec->getStart();
2442 const Loop *CurLoop = AddRec->getLoop();
2443 RunningGCD = ExtraGCD;
2444 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2445 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2446
2447 if (!accumulateCoefficientsGCD(Src, CurLoop, SrcCoeff, RunningGCD) ||
2448 !accumulateCoefficientsGCD(Dst, CurLoop, DstCoeff, RunningGCD))
2449 return false;
2450
2451 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
2452 // If the coefficient is the product of a constant and other stuff,
2453 // we can use the constant in the GCD computation.
2454 std::optional<APInt> ConstCoeff = getConstantCoefficient(Delta);
2455 if (!ConstCoeff)
2456 // The difference of the two coefficients might not be a product
2457 // or constant, in which case we give up on this direction.
2458 continue;
2459 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2460 LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
2461 if (RunningGCD != 0) {
2462 Remainder = ConstDelta.srem(RunningGCD);
2463 LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
2464 if (Remainder != 0) {
2465 unsigned Level = mapSrcLoop(CurLoop);
2466 Result.DV[Level - 1].Direction &= ~Dependence::DVEntry::EQ;
2467 Improved = true;
2468 }
2469 }
2470 }
2471 if (Improved)
2472 ++GCDsuccesses;
2473 LLVM_DEBUG(dbgs() << "all done\n");
2474 return false;
2475}
2476
2477//===----------------------------------------------------------------------===//
2478// banerjeeMIVtest -
2479// Use Banerjee's Inequalities to test an MIV subscript pair.
2480// (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2481// Generally follows the discussion in Section 2.5.2 of
2482//
2483// Optimizing Supercompilers for Supercomputers
2484// Michael Wolfe
2485//
2486// The inequalities given on page 25 are simplified in that loops are
2487// normalized so that the lower bound is always 0 and the stride is always 1.
2488// For example, Wolfe gives
2489//
2490// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2491//
2492// where A_k is the coefficient of the kth index in the source subscript,
2493// B_k is the coefficient of the kth index in the destination subscript,
2494// U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2495// index, and N_k is the stride of the kth index. Since all loops are normalized
2496// by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2497// equation to
2498//
2499// LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2500// = (A^-_k - B_k)^- (U_k - 1) - B_k
2501//
2502// Similar simplifications are possible for the other equations.
2503//
2504// When we can't determine the number of iterations for a loop,
2505// we use NULL as an indicator for the worst case, infinity.
2506// When computing the upper bound, NULL denotes +inf;
2507// for the lower bound, NULL denotes -inf.
2508//
2509// Return true if dependence disproved.
2510bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
2511 const SmallBitVector &Loops,
2512 FullDependence &Result) const {
2513 if (!isDependenceTestEnabled(DependenceTestType::BanerjeeMIV))
2514 return false;
2515
2516 LLVM_DEBUG(dbgs() << "starting Banerjee\n");
2517 ++BanerjeeApplications;
2518 LLVM_DEBUG(dbgs() << " Src = " << *Src << '\n');
2519 const SCEV *A0;
2520 CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
2521 LLVM_DEBUG(dbgs() << " Dst = " << *Dst << '\n');
2522 const SCEV *B0;
2523 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2524 BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
2525 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2526 LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2527
2528 // Compute bounds for all the * directions.
2529 LLVM_DEBUG(dbgs() << "\tBounds[*]\n");
2530 for (unsigned K = 1; K <= MaxLevels; ++K) {
2531 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2532 Bound[K].Direction = Dependence::DVEntry::ALL;
2533 Bound[K].DirSet = Dependence::DVEntry::NONE;
2534 findBoundsALL(A, B, Bound, K);
2535#ifndef NDEBUG
2536 LLVM_DEBUG(dbgs() << "\t " << K << '\t');
2537 if (Bound[K].Lower[Dependence::DVEntry::ALL])
2538 LLVM_DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
2539 else
2540 LLVM_DEBUG(dbgs() << "-inf\t");
2541 if (Bound[K].Upper[Dependence::DVEntry::ALL])
2542 LLVM_DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
2543 else
2544 LLVM_DEBUG(dbgs() << "+inf\n");
2545#endif
2546 }
2547
2548 // Test the *, *, *, ... case.
2549 bool Disproved = false;
2550 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2551 // Explore the direction vector hierarchy.
2552 unsigned DepthExpanded = 0;
2553 unsigned NewDeps =
2554 exploreDirections(1, A, B, Bound, Loops, DepthExpanded, Delta);
2555 if (NewDeps > 0) {
2556 bool Improved = false;
2557 for (unsigned K = 1; K <= CommonLevels; ++K) {
2558 if (Loops[K]) {
2559 unsigned Old = Result.DV[K - 1].Direction;
2560 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2561 Improved |= Old != Result.DV[K - 1].Direction;
2562 if (!Result.DV[K - 1].Direction) {
2563 Improved = false;
2564 Disproved = true;
2565 break;
2566 }
2567 }
2568 }
2569 if (Improved)
2570 ++BanerjeeSuccesses;
2571 } else {
2572 ++BanerjeeIndependence;
2573 Disproved = true;
2574 }
2575 } else {
2576 ++BanerjeeIndependence;
2577 Disproved = true;
2578 }
2579 delete[] Bound;
2580 delete[] A;
2581 delete[] B;
2582 return Disproved;
2583}
2584
2585// Hierarchically expands the direction vector
2586// search space, combining the directions of discovered dependences
2587// in the DirSet field of Bound. Returns the number of distinct
2588// dependences discovered. If the dependence is disproved,
2589// it will return 0.
2590unsigned DependenceInfo::exploreDirections(unsigned Level, CoefficientInfo *A,
2591 CoefficientInfo *B, BoundInfo *Bound,
2592 const SmallBitVector &Loops,
2593 unsigned &DepthExpanded,
2594 const SCEV *Delta) const {
2595 // This algorithm has worst case complexity of O(3^n), where 'n' is the number
2596 // of common loop levels. To avoid excessive compile-time, pessimize all the
2597 // results and immediately return when the number of common levels is beyond
2598 // the given threshold.
2599 if (CommonLevels > MIVMaxLevelThreshold) {
2600 LLVM_DEBUG(dbgs() << "Number of common levels exceeded the threshold. MIV "
2601 "direction exploration is terminated.\n");
2602 for (unsigned K = 1; K <= CommonLevels; ++K)
2603 if (Loops[K])
2604 Bound[K].DirSet = Dependence::DVEntry::ALL;
2605 return 1;
2606 }
2607
2608 if (Level > CommonLevels) {
2609 // record result
2610 LLVM_DEBUG(dbgs() << "\t[");
2611 for (unsigned K = 1; K <= CommonLevels; ++K) {
2612 if (Loops[K]) {
2613 Bound[K].DirSet |= Bound[K].Direction;
2614#ifndef NDEBUG
2615 switch (Bound[K].Direction) {
2617 LLVM_DEBUG(dbgs() << " <");
2618 break;
2620 LLVM_DEBUG(dbgs() << " =");
2621 break;
2623 LLVM_DEBUG(dbgs() << " >");
2624 break;
2626 LLVM_DEBUG(dbgs() << " *");
2627 break;
2628 default:
2629 llvm_unreachable("unexpected Bound[K].Direction");
2630 }
2631#endif
2632 }
2633 }
2634 LLVM_DEBUG(dbgs() << " ]\n");
2635 return 1;
2636 }
2637 if (Loops[Level]) {
2638 if (Level > DepthExpanded) {
2639 DepthExpanded = Level;
2640 // compute bounds for <, =, > at current level
2641 findBoundsLT(A, B, Bound, Level);
2642 findBoundsGT(A, B, Bound, Level);
2643 findBoundsEQ(A, B, Bound, Level);
2644#ifndef NDEBUG
2645 LLVM_DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2646 LLVM_DEBUG(dbgs() << "\t <\t");
2647 if (Bound[Level].Lower[Dependence::DVEntry::LT])
2648 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT]
2649 << '\t');
2650 else
2651 LLVM_DEBUG(dbgs() << "-inf\t");
2652 if (Bound[Level].Upper[Dependence::DVEntry::LT])
2653 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT]
2654 << '\n');
2655 else
2656 LLVM_DEBUG(dbgs() << "+inf\n");
2657 LLVM_DEBUG(dbgs() << "\t =\t");
2658 if (Bound[Level].Lower[Dependence::DVEntry::EQ])
2659 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ]
2660 << '\t');
2661 else
2662 LLVM_DEBUG(dbgs() << "-inf\t");
2663 if (Bound[Level].Upper[Dependence::DVEntry::EQ])
2664 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ]
2665 << '\n');
2666 else
2667 LLVM_DEBUG(dbgs() << "+inf\n");
2668 LLVM_DEBUG(dbgs() << "\t >\t");
2669 if (Bound[Level].Lower[Dependence::DVEntry::GT])
2670 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT]
2671 << '\t');
2672 else
2673 LLVM_DEBUG(dbgs() << "-inf\t");
2674 if (Bound[Level].Upper[Dependence::DVEntry::GT])
2675 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT]
2676 << '\n');
2677 else
2678 LLVM_DEBUG(dbgs() << "+inf\n");
2679#endif
2680 }
2681
2682 unsigned NewDeps = 0;
2683
2684 // test bounds for <, *, *, ...
2685 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2686 NewDeps += exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2687 Delta);
2688
2689 // Test bounds for =, *, *, ...
2690 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2691 NewDeps += exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2692 Delta);
2693
2694 // test bounds for >, *, *, ...
2695 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2696 NewDeps += exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2697 Delta);
2698
2699 Bound[Level].Direction = Dependence::DVEntry::ALL;
2700 return NewDeps;
2701 } else
2702 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2703 Delta);
2704}
2705
2706// Returns true iff the current bounds are plausible.
2707bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
2708 BoundInfo *Bound, const SCEV *Delta) const {
2709 Bound[Level].Direction = DirKind;
2710 if (const SCEV *LowerBound = getLowerBound(Bound))
2711 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2712 return false;
2713 if (const SCEV *UpperBound = getUpperBound(Bound))
2714 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2715 return false;
2716 return true;
2717}
2718
2719// Computes the upper and lower bounds for level K
2720// using the * direction. Records them in Bound.
2721// Wolfe gives the equations
2722//
2723// LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2724// UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2725//
2726// Since we normalize loops, we can simplify these equations to
2727//
2728// LB^*_k = (A^-_k - B^+_k)U_k
2729// UB^*_k = (A^+_k - B^-_k)U_k
2730//
2731// We must be careful to handle the case where the upper bound is unknown.
2732// Note that the lower bound is always <= 0
2733// and the upper bound is always >= 0.
2734void DependenceInfo::findBoundsALL(CoefficientInfo *A, CoefficientInfo *B,
2735 BoundInfo *Bound, unsigned K) const {
2736 Bound[K].Lower[Dependence::DVEntry::ALL] =
2737 nullptr; // Default value = -infinity.
2738 Bound[K].Upper[Dependence::DVEntry::ALL] =
2739 nullptr; // Default value = +infinity.
2740 if (Bound[K].Iterations) {
2741 Bound[K].Lower[Dependence::DVEntry::ALL] = SE->getMulExpr(
2742 SE->getMinusSCEV(A[K].NegPart, B[K].PosPart), Bound[K].Iterations);
2743 Bound[K].Upper[Dependence::DVEntry::ALL] = SE->getMulExpr(
2744 SE->getMinusSCEV(A[K].PosPart, B[K].NegPart), Bound[K].Iterations);
2745 } else {
2746 // If the difference is 0, we won't need to know the number of iterations.
2747 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2748 Bound[K].Lower[Dependence::DVEntry::ALL] =
2749 SE->getZero(A[K].Coeff->getType());
2750 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2751 Bound[K].Upper[Dependence::DVEntry::ALL] =
2752 SE->getZero(A[K].Coeff->getType());
2753 }
2754}
2755
2756// Computes the upper and lower bounds for level K
2757// using the = direction. Records them in Bound.
2758// Wolfe gives the equations
2759//
2760// LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2761// UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2762//
2763// Since we normalize loops, we can simplify these equations to
2764//
2765// LB^=_k = (A_k - B_k)^- U_k
2766// UB^=_k = (A_k - B_k)^+ U_k
2767//
2768// We must be careful to handle the case where the upper bound is unknown.
2769// Note that the lower bound is always <= 0
2770// and the upper bound is always >= 0.
2771void DependenceInfo::findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B,
2772 BoundInfo *Bound, unsigned K) const {
2773 Bound[K].Lower[Dependence::DVEntry::EQ] =
2774 nullptr; // Default value = -infinity.
2775 Bound[K].Upper[Dependence::DVEntry::EQ] =
2776 nullptr; // Default value = +infinity.
2777 if (Bound[K].Iterations) {
2778 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2779 const SCEV *NegativePart = getNegativePart(Delta);
2780 Bound[K].Lower[Dependence::DVEntry::EQ] =
2781 SE->getMulExpr(NegativePart, Bound[K].Iterations);
2782 const SCEV *PositivePart = getPositivePart(Delta);
2783 Bound[K].Upper[Dependence::DVEntry::EQ] =
2784 SE->getMulExpr(PositivePart, Bound[K].Iterations);
2785 } else {
2786 // If the positive/negative part of the difference is 0,
2787 // we won't need to know the number of iterations.
2788 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2789 const SCEV *NegativePart = getNegativePart(Delta);
2790 if (NegativePart->isZero())
2791 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2792 const SCEV *PositivePart = getPositivePart(Delta);
2793 if (PositivePart->isZero())
2794 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2795 }
2796}
2797
2798// Computes the upper and lower bounds for level K
2799// using the < direction. Records them in Bound.
2800// Wolfe gives the equations
2801//
2802// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2803// UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2804//
2805// Since we normalize loops, we can simplify these equations to
2806//
2807// LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2808// UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2809//
2810// We must be careful to handle the case where the upper bound is unknown.
2811void DependenceInfo::findBoundsLT(CoefficientInfo *A, CoefficientInfo *B,
2812 BoundInfo *Bound, unsigned K) const {
2813 Bound[K].Lower[Dependence::DVEntry::LT] =
2814 nullptr; // Default value = -infinity.
2815 Bound[K].Upper[Dependence::DVEntry::LT] =
2816 nullptr; // Default value = +infinity.
2817 if (Bound[K].Iterations) {
2818 const SCEV *Iter_1 = SE->getMinusSCEV(
2819 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2820 const SCEV *NegPart =
2821 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2822 Bound[K].Lower[Dependence::DVEntry::LT] =
2823 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2824 const SCEV *PosPart =
2825 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2826 Bound[K].Upper[Dependence::DVEntry::LT] =
2827 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2828 } else {
2829 // If the positive/negative part of the difference is 0,
2830 // we won't need to know the number of iterations.
2831 const SCEV *NegPart =
2832 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2833 if (NegPart->isZero())
2834 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2835 const SCEV *PosPart =
2836 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2837 if (PosPart->isZero())
2838 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2839 }
2840}
2841
2842// Computes the upper and lower bounds for level K
2843// using the > direction. Records them in Bound.
2844// Wolfe gives the equations
2845//
2846// LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2847// UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2848//
2849// Since we normalize loops, we can simplify these equations to
2850//
2851// LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2852// UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2853//
2854// We must be careful to handle the case where the upper bound is unknown.
2855void DependenceInfo::findBoundsGT(CoefficientInfo *A, CoefficientInfo *B,
2856 BoundInfo *Bound, unsigned K) const {
2857 Bound[K].Lower[Dependence::DVEntry::GT] =
2858 nullptr; // Default value = -infinity.
2859 Bound[K].Upper[Dependence::DVEntry::GT] =
2860 nullptr; // Default value = +infinity.
2861 if (Bound[K].Iterations) {
2862 const SCEV *Iter_1 = SE->getMinusSCEV(
2863 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2864 const SCEV *NegPart =
2865 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2866 Bound[K].Lower[Dependence::DVEntry::GT] =
2867 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2868 const SCEV *PosPart =
2869 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2870 Bound[K].Upper[Dependence::DVEntry::GT] =
2871 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2872 } else {
2873 // If the positive/negative part of the difference is 0,
2874 // we won't need to know the number of iterations.
2875 const SCEV *NegPart =
2876 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2877 if (NegPart->isZero())
2878 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2879 const SCEV *PosPart =
2880 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2881 if (PosPart->isZero())
2882 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2883 }
2884}
2885
2886// X^+ = max(X, 0)
2887const SCEV *DependenceInfo::getPositivePart(const SCEV *X) const {
2888 return SE->getSMaxExpr(X, SE->getZero(X->getType()));
2889}
2890
2891// X^- = min(X, 0)
2892const SCEV *DependenceInfo::getNegativePart(const SCEV *X) const {
2893 return SE->getSMinExpr(X, SE->getZero(X->getType()));
2894}
2895
2896// Walks through the subscript,
2897// collecting each coefficient, the associated loop bounds,
2898// and recording its positive and negative parts for later use.
2899DependenceInfo::CoefficientInfo *
2900DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
2901 const SCEV *&Constant) const {
2902 const SCEV *Zero = SE->getZero(Subscript->getType());
2903 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
2904 for (unsigned K = 1; K <= MaxLevels; ++K) {
2905 CI[K].Coeff = Zero;
2906 CI[K].PosPart = Zero;
2907 CI[K].NegPart = Zero;
2908 CI[K].Iterations = nullptr;
2909 }
2910 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2911 const Loop *L = AddRec->getLoop();
2912 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2913 CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2914 CI[K].PosPart = getPositivePart(CI[K].Coeff);
2915 CI[K].NegPart = getNegativePart(CI[K].Coeff);
2916 CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2917 Subscript = AddRec->getStart();
2918 }
2919 Constant = Subscript;
2920#ifndef NDEBUG
2921 LLVM_DEBUG(dbgs() << "\tCoefficient Info\n");
2922 for (unsigned K = 1; K <= MaxLevels; ++K) {
2923 LLVM_DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
2924 LLVM_DEBUG(dbgs() << "\tPos Part = ");
2925 LLVM_DEBUG(dbgs() << *CI[K].PosPart);
2926 LLVM_DEBUG(dbgs() << "\tNeg Part = ");
2927 LLVM_DEBUG(dbgs() << *CI[K].NegPart);
2928 LLVM_DEBUG(dbgs() << "\tUpper Bound = ");
2929 if (CI[K].Iterations)
2930 LLVM_DEBUG(dbgs() << *CI[K].Iterations);
2931 else
2932 LLVM_DEBUG(dbgs() << "+inf");
2933 LLVM_DEBUG(dbgs() << '\n');
2934 }
2935 LLVM_DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
2936#endif
2937 return CI;
2938}
2939
2940// Looks through all the bounds info and
2941// computes the lower bound given the current direction settings
2942// at each level. If the lower bound for any level is -inf,
2943// the result is -inf.
2944const SCEV *DependenceInfo::getLowerBound(BoundInfo *Bound) const {
2945 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2946 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2947 if (Bound[K].Lower[Bound[K].Direction])
2948 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2949 else
2950 Sum = nullptr;
2951 }
2952 return Sum;
2953}
2954
2955// Looks through all the bounds info and
2956// computes the upper bound given the current direction settings
2957// at each level. If the upper bound at any level is +inf,
2958// the result is +inf.
2959const SCEV *DependenceInfo::getUpperBound(BoundInfo *Bound) const {
2960 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2961 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2962 if (Bound[K].Upper[Bound[K].Direction])
2963 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2964 else
2965 Sum = nullptr;
2966 }
2967 return Sum;
2968}
2969
2970/// Check if we can delinearize the subscripts. If the SCEVs representing the
2971/// source and destination array references are recurrences on a nested loop,
2972/// this function flattens the nested recurrences into separate recurrences
2973/// for each loop level.
2974bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
2976 assert(isLoadOrStore(Src) && "instruction is not load or store");
2977 assert(isLoadOrStore(Dst) && "instruction is not load or store");
2978 Value *SrcPtr = getLoadStorePointerOperand(Src);
2979 Value *DstPtr = getLoadStorePointerOperand(Dst);
2980 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
2981 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
2982 const SCEV *SrcAccessFn = SE->getSCEVAtScope(SrcPtr, SrcLoop);
2983 const SCEV *DstAccessFn = SE->getSCEVAtScope(DstPtr, DstLoop);
2984 const SCEVUnknown *SrcBase =
2985 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
2986 const SCEVUnknown *DstBase =
2987 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
2988
2989 if (!SrcBase || !DstBase || SrcBase != DstBase)
2990 return false;
2991
2992 SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
2993
2994 if (!tryDelinearizeFixedSize(Src, Dst, SrcAccessFn, DstAccessFn,
2995 SrcSubscripts, DstSubscripts) &&
2996 !tryDelinearizeParametricSize(Src, Dst, SrcAccessFn, DstAccessFn,
2997 SrcSubscripts, DstSubscripts))
2998 return false;
2999
3000 assert(isLoopInvariant(SrcBase, SrcLoop) &&
3001 isLoopInvariant(DstBase, DstLoop) &&
3002 "Expected SrcBase and DstBase to be loop invariant");
3003
3004 int Size = SrcSubscripts.size();
3005 LLVM_DEBUG({
3006 dbgs() << "\nSrcSubscripts: ";
3007 for (int I = 0; I < Size; I++)
3008 dbgs() << *SrcSubscripts[I];
3009 dbgs() << "\nDstSubscripts: ";
3010 for (int I = 0; I < Size; I++)
3011 dbgs() << *DstSubscripts[I];
3012 dbgs() << "\n";
3013 });
3014
3015 // The delinearization transforms a single-subscript MIV dependence test into
3016 // a multi-subscript SIV dependence test that is easier to compute. So we
3017 // resize Pair to contain as many pairs of subscripts as the delinearization
3018 // has found, and then initialize the pairs following the delinearization.
3019 Pair.resize(Size);
3020 SCEVMonotonicityChecker MonChecker(SE);
3021 const Loop *OutermostLoop = SrcLoop ? SrcLoop->getOutermostLoop() : nullptr;
3022 for (int I = 0; I < Size; ++I) {
3023 Pair[I].Src = SrcSubscripts[I];
3024 Pair[I].Dst = DstSubscripts[I];
3025
3026 assert(Pair[I].Src->getType() == Pair[I].Dst->getType() &&
3027 "Unexpected different types for the subscripts");
3028
3030 if (MonChecker.checkMonotonicity(Pair[I].Src, OutermostLoop).isUnknown())
3031 return false;
3032 if (MonChecker.checkMonotonicity(Pair[I].Dst, OutermostLoop).isUnknown())
3033 return false;
3034 }
3035 }
3036
3037 return true;
3038}
3039
3040/// Try to delinearize \p SrcAccessFn and \p DstAccessFn if the underlying
3041/// arrays accessed are fixed-size arrays. Return true if delinearization was
3042/// successful.
3043bool DependenceInfo::tryDelinearizeFixedSize(
3044 Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3045 const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3046 SmallVectorImpl<const SCEV *> &DstSubscripts) {
3047 LLVM_DEBUG({
3048 const SCEVUnknown *SrcBase =
3049 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3050 const SCEVUnknown *DstBase =
3051 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3052 assert(SrcBase && DstBase && SrcBase == DstBase &&
3053 "expected src and dst scev unknowns to be equal");
3054 });
3055
3056 const SCEV *ElemSize = SE->getElementSize(Src);
3057 assert(ElemSize == SE->getElementSize(Dst) && "Different element sizes");
3058 SmallVector<const SCEV *, 4> SrcSizes, DstSizes;
3059 if (!delinearizeFixedSizeArray(*SE, SE->removePointerBase(SrcAccessFn),
3060 SrcSubscripts, SrcSizes, ElemSize) ||
3061 !delinearizeFixedSizeArray(*SE, SE->removePointerBase(DstAccessFn),
3062 DstSubscripts, DstSizes, ElemSize))
3063 return false;
3064
3065 // Check that the two size arrays are non-empty and equal in length and
3066 // value. SCEV expressions are uniqued, so we can compare pointers.
3067 if (SrcSizes.size() != DstSizes.size() ||
3068 !std::equal(SrcSizes.begin(), SrcSizes.end(), DstSizes.begin())) {
3069 SrcSubscripts.clear();
3070 DstSubscripts.clear();
3071 return false;
3072 }
3073
3074 assert(SrcSubscripts.size() == DstSubscripts.size() &&
3075 "Expected equal number of entries in the list of SrcSubscripts and "
3076 "DstSubscripts.");
3077
3078 // In general we cannot safely assume that the subscripts recovered from GEPs
3079 // are in the range of values defined for their corresponding array
3080 // dimensions. For example some C language usage/interpretation make it
3081 // impossible to verify this at compile-time. As such we can only delinearize
3082 // iff the subscripts are positive and are less than the range of the
3083 // dimension.
3085 if (!validateDelinearizationResult(*SE, SrcSizes, SrcSubscripts) ||
3086 !validateDelinearizationResult(*SE, DstSizes, DstSubscripts)) {
3087 SrcSubscripts.clear();
3088 DstSubscripts.clear();
3089 return false;
3090 }
3091 }
3092 LLVM_DEBUG({
3093 dbgs() << "Delinearized subscripts of fixed-size array\n"
3094 << "SrcGEP:" << *getLoadStorePointerOperand(Src) << "\n"
3095 << "DstGEP:" << *getLoadStorePointerOperand(Dst) << "\n";
3096 });
3097 return true;
3098}
3099
3100bool DependenceInfo::tryDelinearizeParametricSize(
3101 Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3102 const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3103 SmallVectorImpl<const SCEV *> &DstSubscripts) {
3104
3105 const SCEVUnknown *SrcBase =
3106 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3107 const SCEVUnknown *DstBase =
3108 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3109 assert(SrcBase && DstBase && SrcBase == DstBase &&
3110 "expected src and dst scev unknowns to be equal");
3111
3112 const SCEV *ElementSize = SE->getElementSize(Src);
3113 if (ElementSize != SE->getElementSize(Dst))
3114 return false;
3115
3116 const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
3117 const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
3118
3119 const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
3120 const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
3121 if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
3122 return false;
3123
3124 // First step: collect parametric terms in both array references.
3126 collectParametricTerms(*SE, SrcAR, Terms);
3127 collectParametricTerms(*SE, DstAR, Terms);
3128
3129 // Second step: find subscript sizes.
3131 findArrayDimensions(*SE, Terms, Sizes, ElementSize);
3132
3133 // Third step: compute the access functions for each subscript.
3134 computeAccessFunctions(*SE, SrcAR, SrcSubscripts, Sizes);
3135 computeAccessFunctions(*SE, DstAR, DstSubscripts, Sizes);
3136
3137 // Fail when there is only a subscript: that's a linearized access function.
3138 if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
3139 SrcSubscripts.size() != DstSubscripts.size())
3140 return false;
3141
3142 // Statically check that the array bounds are in-range. The first subscript we
3143 // don't have a size for and it cannot overflow into another subscript, so is
3144 // always safe. The others need to be 0 <= subscript[i] < bound, for both src
3145 // and dst.
3146 // FIXME: It may be better to record these sizes and add them as constraints
3147 // to the dependency checks.
3149 if (!validateDelinearizationResult(*SE, Sizes, SrcSubscripts) ||
3150 !validateDelinearizationResult(*SE, Sizes, DstSubscripts))
3151 return false;
3152
3153 return true;
3154}
3155
3156//===----------------------------------------------------------------------===//
3157
3158#ifndef NDEBUG
3159// For debugging purposes, dump a small bit vector to dbgs().
3161 dbgs() << "{";
3162 for (unsigned VI : BV.set_bits()) {
3163 dbgs() << VI;
3164 if (BV.find_next(VI) >= 0)
3165 dbgs() << ' ';
3166 }
3167 dbgs() << "}\n";
3168}
3169#endif
3170
3172 FunctionAnalysisManager::Invalidator &Inv) {
3173 // Check if the analysis itself has been invalidated.
3174 auto PAC = PA.getChecker<DependenceAnalysis>();
3175 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3176 return true;
3177
3178 // Check transitive dependencies.
3179 return Inv.invalidate<AAManager>(F, PA) ||
3180 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3181 Inv.invalidate<LoopAnalysis>(F, PA);
3182}
3183
3184// depends -
3185// Returns NULL if there is no dependence.
3186// Otherwise, return a Dependence with as many details as possible.
3187// Corresponds to Section 3.1 in the paper
3188//
3189// Practical Dependence Testing
3190// Goff, Kennedy, Tseng
3191// PLDI 1991
3192//
3193std::unique_ptr<Dependence>
3195 bool UnderRuntimeAssumptions) {
3197 bool PossiblyLoopIndependent = true;
3198 if (Src == Dst)
3199 PossiblyLoopIndependent = false;
3200
3201 if (!(Src->mayReadOrWriteMemory() && Dst->mayReadOrWriteMemory()))
3202 // if both instructions don't reference memory, there's no dependence
3203 return nullptr;
3204
3205 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
3206 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
3207 LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
3208 return std::make_unique<Dependence>(Src, Dst,
3209 SCEVUnionPredicate(Assume, *SE));
3210 }
3211
3212 const MemoryLocation &DstLoc = MemoryLocation::get(Dst);
3213 const MemoryLocation &SrcLoc = MemoryLocation::get(Src);
3214
3215 switch (underlyingObjectsAlias(AA, F->getDataLayout(), DstLoc, SrcLoc)) {
3218 // cannot analyse objects if we don't understand their aliasing.
3219 LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
3220 return std::make_unique<Dependence>(Src, Dst,
3221 SCEVUnionPredicate(Assume, *SE));
3223 // If the objects noalias, they are distinct, accesses are independent.
3224 LLVM_DEBUG(dbgs() << "no alias\n");
3225 return nullptr;
3227 break; // The underlying objects alias; test accesses for dependence.
3228 }
3229
3230 if (DstLoc.Size != SrcLoc.Size || !DstLoc.Size.isPrecise() ||
3231 !SrcLoc.Size.isPrecise()) {
3232 // The dependence test gets confused if the size of the memory accesses
3233 // differ.
3234 LLVM_DEBUG(dbgs() << "can't analyze must alias with different sizes\n");
3235 return std::make_unique<Dependence>(Src, Dst,
3236 SCEVUnionPredicate(Assume, *SE));
3237 }
3238
3239 Value *SrcPtr = getLoadStorePointerOperand(Src);
3240 Value *DstPtr = getLoadStorePointerOperand(Dst);
3241 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3242 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3243 LLVM_DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n");
3244 LLVM_DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n");
3245 const SCEV *SrcBase = SE->getPointerBase(SrcSCEV);
3246 const SCEV *DstBase = SE->getPointerBase(DstSCEV);
3247 if (SrcBase != DstBase) {
3248 // If two pointers have different bases, trying to analyze indexes won't
3249 // work; we can't compare them to each other. This can happen, for example,
3250 // if one is produced by an LCSSA PHI node.
3251 //
3252 // We check this upfront so we don't crash in cases where getMinusSCEV()
3253 // returns a SCEVCouldNotCompute.
3254 LLVM_DEBUG(dbgs() << "can't analyze SCEV with different pointer base\n");
3255 return std::make_unique<Dependence>(Src, Dst,
3256 SCEVUnionPredicate(Assume, *SE));
3257 }
3258
3259 // Even if the base pointers are the same, they may not be loop-invariant. It
3260 // could lead to incorrect results, as we're analyzing loop-carried
3261 // dependencies. Src and Dst can be in different loops, so we need to check
3262 // the base pointer is invariant in both loops.
3263 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3264 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3265 if (!isLoopInvariant(SrcBase, SrcLoop) ||
3266 !isLoopInvariant(DstBase, DstLoop)) {
3267 LLVM_DEBUG(dbgs() << "The base pointer is not loop invariant.\n");
3268 return std::make_unique<Dependence>(Src, Dst,
3269 SCEVUnionPredicate(Assume, *SE));
3270 }
3271
3272 uint64_t EltSize = SrcLoc.Size.toRaw();
3273 const SCEV *SrcEv = SE->getMinusSCEV(SrcSCEV, SrcBase);
3274 const SCEV *DstEv = SE->getMinusSCEV(DstSCEV, DstBase);
3275
3276 // Check that memory access offsets are multiples of element sizes.
3277 if (!SE->isKnownMultipleOf(SrcEv, EltSize, Assume) ||
3278 !SE->isKnownMultipleOf(DstEv, EltSize, Assume)) {
3279 LLVM_DEBUG(dbgs() << "can't analyze SCEV with different offsets\n");
3280 return std::make_unique<Dependence>(Src, Dst,
3281 SCEVUnionPredicate(Assume, *SE));
3282 }
3283
3284 // Runtime assumptions needed but not allowed.
3285 if (!Assume.empty() && !UnderRuntimeAssumptions)
3286 return std::make_unique<Dependence>(Src, Dst,
3287 SCEVUnionPredicate(Assume, *SE));
3288
3289 unsigned Pairs = 1;
3290 SmallVector<Subscript, 2> Pair(Pairs);
3291 Pair[0].Src = SrcEv;
3292 Pair[0].Dst = DstEv;
3293
3294 SCEVMonotonicityChecker MonChecker(SE);
3295 const Loop *OutermostLoop = SrcLoop ? SrcLoop->getOutermostLoop() : nullptr;
3297 if (MonChecker.checkMonotonicity(Pair[0].Src, OutermostLoop).isUnknown() ||
3298 MonChecker.checkMonotonicity(Pair[0].Dst, OutermostLoop).isUnknown())
3299 return std::make_unique<Dependence>(Src, Dst,
3300 SCEVUnionPredicate(Assume, *SE));
3301
3302 if (Delinearize) {
3303 if (tryDelinearize(Src, Dst, Pair)) {
3304 LLVM_DEBUG(dbgs() << " delinearized\n");
3305 Pairs = Pair.size();
3306 }
3307 }
3308
3309 // Establish loop nesting levels considering SameSD loops as common
3310 establishNestingLevels(Src, Dst);
3311
3312 LLVM_DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
3313 LLVM_DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
3314 LLVM_DEBUG(dbgs() << " SameSD nesting levels = " << SameSDLevels << "\n");
3315
3316 // Modify common levels to consider the SameSD levels in the tests
3317 CommonLevels += SameSDLevels;
3318 MaxLevels -= SameSDLevels;
3319 if (SameSDLevels > 0) {
3320 // Not all tests are handled yet over SameSD loops
3321 // Revoke if there are any tests other than ZIV, SIV or RDIV
3322 for (unsigned P = 0; P < Pairs; ++P) {
3324 Subscript::ClassificationKind TestClass =
3325 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3326 Pair[P].Dst, LI->getLoopFor(Dst->getParent()), Loops);
3327
3328 if (TestClass != Subscript::ZIV && TestClass != Subscript::SIV &&
3329 TestClass != Subscript::RDIV) {
3330 // Revert the levels to not consider the SameSD levels
3331 CommonLevels -= SameSDLevels;
3332 MaxLevels += SameSDLevels;
3333 SameSDLevels = 0;
3334 break;
3335 }
3336 }
3337 }
3338
3339 if (SameSDLevels > 0)
3340 SameSDLoopsCount++;
3341
3342 FullDependence Result(Src, Dst, SCEVUnionPredicate(Assume, *SE),
3343 PossiblyLoopIndependent, CommonLevels);
3344 ++TotalArrayPairs;
3345
3346 for (unsigned P = 0; P < Pairs; ++P) {
3347 assert(Pair[P].Src->getType()->isIntegerTy() && "Src must be an integer");
3348 assert(Pair[P].Dst->getType()->isIntegerTy() && "Dst must be an integer");
3349 Pair[P].Loops.resize(MaxLevels + 1);
3350 Pair[P].GroupLoops.resize(MaxLevels + 1);
3351 Pair[P].Group.resize(Pairs);
3352 Pair[P].Classification =
3353 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()), Pair[P].Dst,
3354 LI->getLoopFor(Dst->getParent()), Pair[P].Loops);
3355 Pair[P].GroupLoops = Pair[P].Loops;
3356 Pair[P].Group.set(P);
3357 LLVM_DEBUG(dbgs() << " subscript " << P << "\n");
3358 LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
3359 LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
3360 LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
3361 LLVM_DEBUG(dbgs() << "\tloops = ");
3363 }
3364
3365 // Test each subscript individually
3366 for (unsigned SI = 0; SI < Pairs; ++SI) {
3367 LLVM_DEBUG(dbgs() << "testing subscript " << SI);
3368 switch (Pair[SI].Classification) {
3369 case Subscript::NonLinear:
3370 // ignore these, but collect loops for later
3371 ++NonlinearSubscriptPairs;
3372 collectCommonLoops(Pair[SI].Src, LI->getLoopFor(Src->getParent()),
3373 Pair[SI].Loops);
3374 collectCommonLoops(Pair[SI].Dst, LI->getLoopFor(Dst->getParent()),
3375 Pair[SI].Loops);
3376 break;
3377 case Subscript::ZIV:
3378 LLVM_DEBUG(dbgs() << ", ZIV\n");
3379 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
3380 return nullptr;
3381 break;
3382 case Subscript::SIV: {
3383 LLVM_DEBUG(dbgs() << ", SIV\n");
3384 unsigned Level;
3385 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result,
3386 UnderRuntimeAssumptions))
3387 return nullptr;
3388 break;
3389 }
3390 case Subscript::RDIV:
3391 LLVM_DEBUG(dbgs() << ", RDIV\n");
3392 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
3393 return nullptr;
3394 break;
3395 case Subscript::MIV:
3396 LLVM_DEBUG(dbgs() << ", MIV\n");
3397 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
3398 return nullptr;
3399 break;
3400 }
3401 }
3402
3403 // Make sure the Scalar flags are set correctly.
3404 SmallBitVector CompleteLoops(MaxLevels + 1);
3405 for (unsigned SI = 0; SI < Pairs; ++SI)
3406 CompleteLoops |= Pair[SI].Loops;
3407 for (unsigned II = 1; II <= CommonLevels; ++II)
3408 if (CompleteLoops[II])
3409 Result.DV[II - 1].Scalar = false;
3410
3411 // Set the distance to zero if the direction is EQ.
3412 // TODO: Ideally, the distance should be set to 0 immediately simultaneously
3413 // with the corresponding direction being set to EQ.
3414 for (unsigned II = 1; II <= Result.getLevels(); ++II) {
3415 if (Result.getDirection(II) == Dependence::DVEntry::EQ) {
3416 if (Result.DV[II - 1].Distance == nullptr)
3417 Result.DV[II - 1].Distance = SE->getZero(SrcSCEV->getType());
3418 else
3419 assert(Result.DV[II - 1].Distance->isZero() &&
3420 "Inconsistency between distance and direction");
3421 }
3422
3423#ifndef NDEBUG
3424 // Check that the converse (i.e., if the distance is zero, then the
3425 // direction is EQ) holds.
3426 const SCEV *Distance = Result.getDistance(II);
3427 if (Distance && Distance->isZero())
3428 assert(Result.getDirection(II) == Dependence::DVEntry::EQ &&
3429 "Distance is zero, but direction is not EQ");
3430#endif
3431 }
3432
3433 if (SameSDLevels > 0) {
3434 // Extracting SameSD levels from the common levels
3435 // Reverting CommonLevels and MaxLevels to their original values
3436 assert(CommonLevels >= SameSDLevels);
3437 CommonLevels -= SameSDLevels;
3438 MaxLevels += SameSDLevels;
3439 std::unique_ptr<FullDependence::DVEntry[]> DV, DVSameSD;
3440 DV = std::make_unique<FullDependence::DVEntry[]>(CommonLevels);
3441 DVSameSD = std::make_unique<FullDependence::DVEntry[]>(SameSDLevels);
3442 for (unsigned Level = 0; Level < CommonLevels; ++Level)
3443 DV[Level] = Result.DV[Level];
3444 for (unsigned Level = 0; Level < SameSDLevels; ++Level)
3445 DVSameSD[Level] = Result.DV[CommonLevels + Level];
3446 Result.DV = std::move(DV);
3447 Result.DVSameSD = std::move(DVSameSD);
3448 Result.Levels = CommonLevels;
3449 Result.SameSDLevels = SameSDLevels;
3450 }
3451
3452 if (PossiblyLoopIndependent) {
3453 // Make sure the LoopIndependent flag is set correctly.
3454 // All directions must include equal, otherwise no
3455 // loop-independent dependence is possible.
3456 for (unsigned II = 1; II <= CommonLevels; ++II) {
3457 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3458 Result.LoopIndependent = false;
3459 break;
3460 }
3461 }
3462 } else {
3463 // On the other hand, if all directions are equal and there's no
3464 // loop-independent dependence possible, then no dependence exists.
3465 // However, if there are runtime assumptions, we must return the result.
3466 bool AllEqual = true;
3467 for (unsigned II = 1; II <= CommonLevels; ++II) {
3468 if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
3469 AllEqual = false;
3470 break;
3471 }
3472 }
3473 if (AllEqual && Result.Assumptions.getPredicates().empty())
3474 return nullptr;
3475 }
3476
3477 return std::make_unique<FullDependence>(std::move(Result));
3478}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:849
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static cl::opt< DependenceTestType > EnableDependenceTest("da-enable-dependence-test", cl::init(DependenceTestType::All), cl::ReallyHidden, cl::desc("Run only specified dependence test routine and disable others. " "The purpose is mainly to exclude the influence of other " "dependence test routines in regression tests. If set to All, all " "dependence test routines are enabled."), cl::values(clEnumValN(DependenceTestType::All, "all", "Enable all dependence test routines."), clEnumValN(DependenceTestType::StrongSIV, "strong-siv", "Enable only Strong SIV test."), clEnumValN(DependenceTestType::WeakCrossingSIV, "weak-crossing-siv", "Enable only Weak-Crossing SIV test."), clEnumValN(DependenceTestType::ExactSIV, "exact-siv", "Enable only Exact SIV test."), clEnumValN(DependenceTestType::WeakZeroSIV, "weak-zero-siv", "Enable only Weak-Zero SIV test."), clEnumValN(DependenceTestType::ExactRDIV, "exact-rdiv", "Enable only Exact RDIV test."), clEnumValN(DependenceTestType::SymbolicRDIV, "symbolic-rdiv", "Enable only Symbolic RDIV test."), clEnumValN(DependenceTestType::GCDMIV, "gcd-miv", "Enable only GCD MIV test."), clEnumValN(DependenceTestType::BanerjeeMIV, "banerjee-miv", "Enable only Banerjee MIV test.")))
static bool isLoadOrStore(const Instruction *I)
static OverflowSafeSignedAPInt floorOfQuotient(const OverflowSafeSignedAPInt &OA, const OverflowSafeSignedAPInt &OB)
static void dumpExampleDependence(raw_ostream &OS, DependenceInfo *DA, ScalarEvolution &SE, LoopInfo &LI, bool NormalizeResults)
static OverflowSafeSignedAPInt ceilingOfQuotient(const OverflowSafeSignedAPInt &OA, const OverflowSafeSignedAPInt &OB)
static bool isDependenceTestEnabled(DependenceTestType Test)
Returns true iff Test is enabled.
static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM, const APInt &Delta, APInt &G, APInt &X, APInt &Y)
static void dumpSmallBitVector(SmallBitVector &BV)
static std::pair< OverflowSafeSignedAPInt, OverflowSafeSignedAPInt > inferDomainOfAffine(OverflowSafeSignedAPInt A, OverflowSafeSignedAPInt B, OverflowSafeSignedAPInt UB)
Given an affine expression of the form A*k + B, where k is an arbitrary integer, infer the possible r...
static const SCEV * minusSCEVNoSignedOverflow(const SCEV *A, const SCEV *B, ScalarEvolution &SE)
Returns A - B if it guaranteed not to signed wrap.
static AliasResult underlyingObjectsAlias(AAResults *AA, const DataLayout &DL, const MemoryLocation &LocA, const MemoryLocation &LocB)
static std::optional< APInt > getConstantCoefficient(const SCEV *Expr)
Given a SCEVMulExpr, returns its first operand if its first operand is a constant and the product doe...
static bool isRemainderZero(const SCEVConstant *Dividend, const SCEVConstant *Divisor)
static cl::opt< bool > Delinearize("da-delinearize", cl::init(true), cl::Hidden, cl::desc("Try to delinearize array references."))
static cl::opt< bool > EnableMonotonicityCheck("da-enable-monotonicity-check", cl::init(false), cl::Hidden, cl::desc("Check if the subscripts are monotonic. If it's not, dependence " "is reported as unknown."))
static cl::opt< bool > DumpMonotonicityReport("da-dump-monotonicity-report", cl::init(false), cl::Hidden, cl::desc("When printing analysis, dump the results of monotonicity checks."))
static cl::opt< unsigned > MIVMaxLevelThreshold("da-miv-max-level-threshold", cl::init(7), cl::Hidden, cl::desc("Maximum depth allowed for the recursive algorithm used to " "explore MIV direction vectors."))
static cl::opt< bool > DisableDelinearizationChecks("da-disable-delinearization-checks", cl::Hidden, cl::desc("Disable checks that try to statically verify validity of " "delinearized subscripts. Enabling this option may result in incorrect " "dependence vectors for languages that allow the subscript of one " "dimension to underflow or overflow into another dimension."))
Hexagon Hardware Loops
Module.h This file contains the declarations for the Module class.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
Definition APInt.h:78
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1901
APInt abs() const
Get the absolute value.
Definition APInt.h:1810
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1208
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1503
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1655
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1747
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1137
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
The possible results of an alias query.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
void enableCrossIterationMode()
Assume that values may come from different cycle iterations.
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ ICMP_NE
not equal
Definition InstrTypes.h:698
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Legacy pass manager pass to access dependence information.
void getAnalysisUsage(AnalysisUsage &) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void print(raw_ostream &, const Module *=nullptr) const override
print - Print out the internal state of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
AnalysisPass to compute dependence information in a function.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &FAM)
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle transitive invalidation when the cached analysis results go away.
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.
void dumpImp(raw_ostream &OS, bool IsSameSD=false) const
dumpImp - For debugging purposes.
Dependence(Dependence &&)=default
SCEVUnionPredicate getRuntimeAssumptions() const
getRuntimeAssumptions - Returns the runtime assumptions under which this Dependence relation is valid...
virtual bool isConfused() const
isConfused - Returns true if this dependence is confused (the compiler understands nothing and makes ...
virtual unsigned getSameSDLevels() const
getSameSDLevels - Returns the number of separate SameSD loops surrounding the source and destination ...
virtual const SCEV * getDistance(unsigned Level, bool SameSD=false) const
getDistance - Returns the distance (or NULL) associated with a particular common or SameSD level.
virtual unsigned getLevels() const
getLevels - Returns the number of common loops surrounding the source and destination of the dependen...
virtual unsigned getDirection(unsigned Level, bool SameSD=false) const
getDirection - Returns the direction associated with a particular common or SameSD level.
virtual bool isScalar(unsigned Level, bool SameSD=false) const
isScalar - Returns true if a particular regular or SameSD level is scalar; that is,...
bool isFlow() const
isFlow - Returns true if this is a flow (aka true) dependence.
bool isInput() const
isInput - Returns true if this is an input dependence.
bool isAnti() const
isAnti - Returns true if this is an anti dependence.
virtual bool isLoopIndependent() const
isLoopIndependent - Returns true if this is a loop-independent dependence.
bool isOutput() const
isOutput - Returns true if this is an output dependence.
void dump(raw_ostream &OS) const
dump - For debugging purposes, dumps a dependence to OS.
virtual bool inSameSDLoops(unsigned Level) const
inSameSDLoops - Returns true if this level is an SameSD level, i.e., performed across two separate lo...
Class representing an expression and its matching format.
FullDependence - This class represents a dependence between two memory references in a function.
FullDependence(Instruction *Source, Instruction *Destination, const SCEVUnionPredicate &Assumes, bool PossiblyLoopIndependent, unsigned Levels)
unsigned getDirection(unsigned Level, bool SameSD=false) const override
getDirection - Returns the direction associated with a particular common or SameSD level.
bool isScalar(unsigned Level, bool SameSD=false) const override
isScalar - Returns true if a particular regular or SameSD level is scalar; that is,...
bool isDirectionNegative() const override
Check if the direction vector is negative.
const SCEV * getDistance(unsigned Level, bool SameSD=false) const override
getDistance - Returns the distance (or NULL) associated with a particular common or SameSD level.
DVEntry getDVEntry(unsigned Level, bool IsSameSD) const
getDVEntry - Returns the DV entry associated with a regular or a SameSD level.
bool inSameSDLoops(unsigned Level) const override
inSameSDLoops - Returns true if this level is an SameSD level, i.e., performed across two separate lo...
bool normalize(ScalarEvolution *SE) override
If the direction vector is negative, normalize the direction vector to make it non-negative.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
FunctionPass(char &pid)
Definition Pass.h:316
An instruction for reading from memory.
bool isPrecise() const
uint64_t toRaw() const
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:596
This class represents a loop nest and can be used to query its properties.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
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
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
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.
const APInt & getAPInt() const
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
LLVM_ABI 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 const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
iterator_range< const_set_bits_iterator > set_bits() const
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize(size_type N)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:53
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2263
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2268
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition APInt.cpp:798
constexpr bool operator!(E Val)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ TB
TB - TwoByte - Set if this instruction has a two byte opcode, which starts with a 0x0F byte before th...
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
InstIterator< SymbolTableList< BasicBlock >, Function::iterator, BasicBlock::iterator, Instruction > inst_iterator
void collectParametricTerms(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Terms)
Collect parametric terms occurring in step expressions (first step of delinearization).
void findArrayDimensions(ScalarEvolution &SE, SmallVectorImpl< const SCEV * > &Terms, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Compute the array dimensions Sizes from the set of Terms extracted from the memory access function of...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2250
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
inst_iterator inst_begin(Function *F)
bool validateDelinearizationResult(ScalarEvolution &SE, ArrayRef< const SCEV * > Sizes, ArrayRef< const SCEV * > Subscripts)
Check that each subscript in Subscripts is within the corresponding size in Sizes.
void computeAccessFunctions(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes)
Return in Subscripts the access functions for each dimension in Sizes (third step of delinearization)...
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...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
inst_iterator inst_end(Function *F)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
APInt operator-(APInt)
Definition APInt.h:2203
APInt operator+(APInt a, const APInt &b)
Definition APInt.h:2208
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI FunctionPass * createDependenceAnalysisWrapperPass()
createDependenceAnalysisPass - This creates an instance of the DependenceAnalysis wrapper pass.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
Dependence::DVEntry - Each level in the distance/direction vector has a direction (or perhaps a union...
This class defines a simple visitor class that may be used for various SCEV analysis purposes.