1 //===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // DependenceAnalysis is an LLVM pass that analyses dependences between memory
11 // accesses. Currently, it is an (incomplete) implementation of the approach
14 // Practical Dependence Testing
15 // Goff, Kennedy, Tseng
18 // There's a single entry point that analyzes the dependence between a pair
19 // of memory references in a function, returning either NULL, for no dependence,
20 // or a more-or-less detailed description of the dependence between them.
22 // Currently, the implementation cannot propagate constraints between
23 // coupled RDIV subscripts and lacks a multi-subscript MIV test.
24 // Both of these are conservative weaknesses;
25 // that is, not a source of correctness problems.
27 // The implementation depends on the GEP instruction to differentiate
28 // subscripts. Since Clang linearizes some array subscripts, the dependence
29 // analysis is using SCEV->delinearize to recover the representation of multiple
30 // subscripts, and thus avoid the more expensive and less precise MIV tests. The
31 // delinearization is controlled by the flag -da-delinearize.
33 // We should pay some careful attention to the possibility of integer overflow
34 // in the implementation of the various tests. This could happen with Add,
35 // Subtract, or Multiply, with both APInt's and SCEV's.
37 // Some non-linear subscript pairs can be handled by the GCD test
38 // (and perhaps other tests).
39 // Should explore how often these things occur.
41 // Finally, it seems like certain test cases expose weaknesses in the SCEV
42 // simplification, especially in the handling of sign and zero extensions.
43 // It could be useful to spend time exploring these.
45 // Please note that this is work in progress and the interface is subject to
48 //===----------------------------------------------------------------------===//
50 // In memory of Ken Kennedy, 1945 - 2007 //
52 //===----------------------------------------------------------------------===//
54 #include "llvm/Analysis/DependenceAnalysis.h"
55 #include "llvm/ADT/STLExtras.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/Analysis/AliasAnalysis.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/ScalarEvolution.h"
60 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
61 #include "llvm/Analysis/ValueTracking.h"
62 #include "llvm/IR/InstIterator.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/Operator.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/raw_ostream.h"
72 #define DEBUG_TYPE "da"
74 //===----------------------------------------------------------------------===//
77 STATISTIC(TotalArrayPairs, "Array pairs tested");
78 STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
79 STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
80 STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
81 STATISTIC(ZIVapplications, "ZIV applications");
82 STATISTIC(ZIVindependence, "ZIV independence");
83 STATISTIC(StrongSIVapplications, "Strong SIV applications");
84 STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
85 STATISTIC(StrongSIVindependence, "Strong SIV independence");
86 STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
87 STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
88 STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
89 STATISTIC(ExactSIVapplications, "Exact SIV applications");
90 STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
91 STATISTIC(ExactSIVindependence, "Exact SIV independence");
92 STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
93 STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
94 STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
95 STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
96 STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
97 STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
98 STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
99 STATISTIC(DeltaApplications, "Delta applications");
100 STATISTIC(DeltaSuccesses, "Delta successes");
101 STATISTIC(DeltaIndependence, "Delta independence");
102 STATISTIC(DeltaPropagations, "Delta propagations");
103 STATISTIC(GCDapplications, "GCD applications");
104 STATISTIC(GCDsuccesses, "GCD successes");
105 STATISTIC(GCDindependence, "GCD independence");
106 STATISTIC(BanerjeeApplications, "Banerjee applications");
107 STATISTIC(BanerjeeIndependence, "Banerjee independence");
108 STATISTIC(BanerjeeSuccesses, "Banerjee successes");
111 Delinearize("da-delinearize", cl::init(false), cl::Hidden, cl::ZeroOrMore,
112 cl::desc("Try to delinearize array references."));
114 //===----------------------------------------------------------------------===//
117 INITIALIZE_PASS_BEGIN(DependenceAnalysis, "da",
118 "Dependence Analysis", true, true)
119 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
120 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
121 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
122 INITIALIZE_PASS_END(DependenceAnalysis, "da",
123 "Dependence Analysis", true, true)
125 char DependenceAnalysis::ID = 0;
128 FunctionPass *llvm::createDependenceAnalysisPass() {
129 return new DependenceAnalysis();
133 bool DependenceAnalysis::runOnFunction(Function &F) {
135 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
136 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
137 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
142 void DependenceAnalysis::releaseMemory() {
146 void DependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
147 AU.setPreservesAll();
148 AU.addRequiredTransitive<AAResultsWrapperPass>();
149 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
150 AU.addRequiredTransitive<LoopInfoWrapperPass>();
154 // Used to test the dependence analyzer.
155 // Looks through the function, noting loads and stores.
156 // Calls depends() on every possible pair and prints out the result.
157 // Ignores all other instructions.
159 void dumpExampleDependence(raw_ostream &OS, Function *F,
160 DependenceAnalysis *DA) {
161 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F);
162 SrcI != SrcE; ++SrcI) {
163 if (isa<StoreInst>(*SrcI) || isa<LoadInst>(*SrcI)) {
164 for (inst_iterator DstI = SrcI, DstE = inst_end(F);
165 DstI != DstE; ++DstI) {
166 if (isa<StoreInst>(*DstI) || isa<LoadInst>(*DstI)) {
167 OS << "da analyze - ";
168 if (auto D = DA->depends(&*SrcI, &*DstI, true)) {
170 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
171 if (D->isSplitable(Level)) {
172 OS << "da analyze - split level = " << Level;
173 OS << ", iteration = " << *DA->getSplitIteration(*D, Level);
187 void DependenceAnalysis::print(raw_ostream &OS, const Module*) const {
188 dumpExampleDependence(OS, F, const_cast<DependenceAnalysis *>(this));
191 //===----------------------------------------------------------------------===//
192 // Dependence methods
194 // Returns true if this is an input dependence.
195 bool Dependence::isInput() const {
196 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
200 // Returns true if this is an output dependence.
201 bool Dependence::isOutput() const {
202 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
206 // Returns true if this is an flow (aka true) dependence.
207 bool Dependence::isFlow() const {
208 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
212 // Returns true if this is an anti dependence.
213 bool Dependence::isAnti() const {
214 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
218 // Returns true if a particular level is scalar; that is,
219 // if no subscript in the source or destination mention the induction
220 // variable associated with the loop at this level.
221 // Leave this out of line, so it will serve as a virtual method anchor
222 bool Dependence::isScalar(unsigned level) const {
227 //===----------------------------------------------------------------------===//
228 // FullDependence methods
230 FullDependence::FullDependence(Instruction *Source, Instruction *Destination,
231 bool PossiblyLoopIndependent,
232 unsigned CommonLevels)
233 : Dependence(Source, Destination), Levels(CommonLevels),
234 LoopIndependent(PossiblyLoopIndependent) {
237 DV = make_unique<DVEntry[]>(CommonLevels);
240 // The rest are simple getters that hide the implementation.
242 // getDirection - Returns the direction associated with a particular level.
243 unsigned FullDependence::getDirection(unsigned Level) const {
244 assert(0 < Level && Level <= Levels && "Level out of range");
245 return DV[Level - 1].Direction;
249 // Returns the distance (or NULL) associated with a particular level.
250 const SCEV *FullDependence::getDistance(unsigned Level) const {
251 assert(0 < Level && Level <= Levels && "Level out of range");
252 return DV[Level - 1].Distance;
256 // Returns true if a particular level is scalar; that is,
257 // if no subscript in the source or destination mention the induction
258 // variable associated with the loop at this level.
259 bool FullDependence::isScalar(unsigned Level) const {
260 assert(0 < Level && Level <= Levels && "Level out of range");
261 return DV[Level - 1].Scalar;
265 // Returns true if peeling the first iteration from this loop
266 // will break this dependence.
267 bool FullDependence::isPeelFirst(unsigned Level) const {
268 assert(0 < Level && Level <= Levels && "Level out of range");
269 return DV[Level - 1].PeelFirst;
273 // Returns true if peeling the last iteration from this loop
274 // will break this dependence.
275 bool FullDependence::isPeelLast(unsigned Level) const {
276 assert(0 < Level && Level <= Levels && "Level out of range");
277 return DV[Level - 1].PeelLast;
281 // Returns true if splitting this loop will break the dependence.
282 bool FullDependence::isSplitable(unsigned Level) const {
283 assert(0 < Level && Level <= Levels && "Level out of range");
284 return DV[Level - 1].Splitable;
288 //===----------------------------------------------------------------------===//
289 // DependenceAnalysis::Constraint methods
291 // If constraint is a point <X, Y>, returns X.
293 const SCEV *DependenceAnalysis::Constraint::getX() const {
294 assert(Kind == Point && "Kind should be Point");
299 // If constraint is a point <X, Y>, returns Y.
301 const SCEV *DependenceAnalysis::Constraint::getY() const {
302 assert(Kind == Point && "Kind should be Point");
307 // If constraint is a line AX + BY = C, returns A.
309 const SCEV *DependenceAnalysis::Constraint::getA() const {
310 assert((Kind == Line || Kind == Distance) &&
311 "Kind should be Line (or Distance)");
316 // If constraint is a line AX + BY = C, returns B.
318 const SCEV *DependenceAnalysis::Constraint::getB() const {
319 assert((Kind == Line || Kind == Distance) &&
320 "Kind should be Line (or Distance)");
325 // If constraint is a line AX + BY = C, returns C.
327 const SCEV *DependenceAnalysis::Constraint::getC() const {
328 assert((Kind == Line || Kind == Distance) &&
329 "Kind should be Line (or Distance)");
334 // If constraint is a distance, returns D.
336 const SCEV *DependenceAnalysis::Constraint::getD() const {
337 assert(Kind == Distance && "Kind should be Distance");
338 return SE->getNegativeSCEV(C);
342 // Returns the loop associated with this constraint.
343 const Loop *DependenceAnalysis::Constraint::getAssociatedLoop() const {
344 assert((Kind == Distance || Kind == Line || Kind == Point) &&
345 "Kind should be Distance, Line, or Point");
346 return AssociatedLoop;
350 void DependenceAnalysis::Constraint::setPoint(const SCEV *X,
352 const Loop *CurLoop) {
356 AssociatedLoop = CurLoop;
360 void DependenceAnalysis::Constraint::setLine(const SCEV *AA,
363 const Loop *CurLoop) {
368 AssociatedLoop = CurLoop;
372 void DependenceAnalysis::Constraint::setDistance(const SCEV *D,
373 const Loop *CurLoop) {
375 A = SE->getOne(D->getType());
376 B = SE->getNegativeSCEV(A);
377 C = SE->getNegativeSCEV(D);
378 AssociatedLoop = CurLoop;
382 void DependenceAnalysis::Constraint::setEmpty() {
387 void DependenceAnalysis::Constraint::setAny(ScalarEvolution *NewSE) {
393 // For debugging purposes. Dumps the constraint out to OS.
394 void DependenceAnalysis::Constraint::dump(raw_ostream &OS) const {
400 OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
401 else if (isDistance())
402 OS << " Distance is " << *getD() <<
403 " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
405 OS << " Line is " << *getA() << "*X + " <<
406 *getB() << "*Y = " << *getC() << "\n";
408 llvm_unreachable("unknown constraint type in Constraint::dump");
412 // Updates X with the intersection
413 // of the Constraints X and Y. Returns true if X has changed.
414 // Corresponds to Figure 4 from the paper
416 // Practical Dependence Testing
417 // Goff, Kennedy, Tseng
419 bool DependenceAnalysis::intersectConstraints(Constraint *X,
420 const Constraint *Y) {
422 DEBUG(dbgs() << "\tintersect constraints\n");
423 DEBUG(dbgs() << "\t X ="; X->dump(dbgs()));
424 DEBUG(dbgs() << "\t Y ="; Y->dump(dbgs()));
425 assert(!Y->isPoint() && "Y must not be a Point");
439 if (X->isDistance() && Y->isDistance()) {
440 DEBUG(dbgs() << "\t intersect 2 distances\n");
441 if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
443 if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
448 // Hmmm, interesting situation.
449 // I guess if either is constant, keep it and ignore the other.
450 if (isa<SCEVConstant>(Y->getD())) {
457 // At this point, the pseudo-code in Figure 4 of the paper
458 // checks if (X->isPoint() && Y->isPoint()).
459 // This case can't occur in our implementation,
460 // since a Point can only arise as the result of intersecting
461 // two Line constraints, and the right-hand value, Y, is never
462 // the result of an intersection.
463 assert(!(X->isPoint() && Y->isPoint()) &&
464 "We shouldn't ever see X->isPoint() && Y->isPoint()");
466 if (X->isLine() && Y->isLine()) {
467 DEBUG(dbgs() << "\t intersect 2 lines\n");
468 const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
469 const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
470 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
471 // slopes are equal, so lines are parallel
472 DEBUG(dbgs() << "\t\tsame slope\n");
473 Prod1 = SE->getMulExpr(X->getC(), Y->getB());
474 Prod2 = SE->getMulExpr(X->getB(), Y->getC());
475 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
477 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
484 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
485 // slopes differ, so lines intersect
486 DEBUG(dbgs() << "\t\tdifferent slopes\n");
487 const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
488 const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
489 const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
490 const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
491 const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
492 const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
493 const SCEVConstant *C1A2_C2A1 =
494 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
495 const SCEVConstant *C1B2_C2B1 =
496 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
497 const SCEVConstant *A1B2_A2B1 =
498 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
499 const SCEVConstant *A2B1_A1B2 =
500 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
501 if (!C1B2_C2B1 || !C1A2_C2A1 ||
502 !A1B2_A2B1 || !A2B1_A1B2)
504 APInt Xtop = C1B2_C2B1->getAPInt();
505 APInt Xbot = A1B2_A2B1->getAPInt();
506 APInt Ytop = C1A2_C2A1->getAPInt();
507 APInt Ybot = A2B1_A1B2->getAPInt();
508 DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
509 DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
510 DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
511 DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
512 APInt Xq = Xtop; // these need to be initialized, even
513 APInt Xr = Xtop; // though they're just going to be overwritten
514 APInt::sdivrem(Xtop, Xbot, Xq, Xr);
517 APInt::sdivrem(Ytop, Ybot, Yq, Yr);
518 if (Xr != 0 || Yr != 0) {
523 DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
524 if (Xq.slt(0) || Yq.slt(0)) {
529 if (const SCEVConstant *CUB =
530 collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
531 APInt UpperBound = CUB->getAPInt();
532 DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
533 if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
539 X->setPoint(SE->getConstant(Xq),
541 X->getAssociatedLoop());
548 // if (X->isLine() && Y->isPoint()) This case can't occur.
549 assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
551 if (X->isPoint() && Y->isLine()) {
552 DEBUG(dbgs() << "\t intersect Point and Line\n");
553 const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
554 const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
555 const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
556 if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
558 if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
566 llvm_unreachable("shouldn't reach the end of Constraint intersection");
571 //===----------------------------------------------------------------------===//
572 // DependenceAnalysis methods
574 // For debugging purposes. Dumps a dependence to OS.
575 void Dependence::dump(raw_ostream &OS) const {
576 bool Splitable = false;
590 unsigned Levels = getLevels();
592 for (unsigned II = 1; II <= Levels; ++II) {
597 const SCEV *Distance = getDistance(II);
600 else if (isScalar(II))
603 unsigned Direction = getDirection(II);
604 if (Direction == DVEntry::ALL)
607 if (Direction & DVEntry::LT)
609 if (Direction & DVEntry::EQ)
611 if (Direction & DVEntry::GT)
620 if (isLoopIndependent())
629 static AliasResult underlyingObjectsAlias(AliasAnalysis *AA,
630 const DataLayout &DL, const Value *A,
632 const Value *AObj = GetUnderlyingObject(A, DL);
633 const Value *BObj = GetUnderlyingObject(B, DL);
634 return AA->alias(AObj, DL.getTypeStoreSize(AObj->getType()),
635 BObj, DL.getTypeStoreSize(BObj->getType()));
639 // Returns true if the load or store can be analyzed. Atomic and volatile
640 // operations have properties which this analysis does not understand.
642 bool isLoadOrStore(const Instruction *I) {
643 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
644 return LI->isUnordered();
645 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
646 return SI->isUnordered();
652 Value *getPointerOperand(Instruction *I) {
653 if (LoadInst *LI = dyn_cast<LoadInst>(I))
654 return LI->getPointerOperand();
655 if (StoreInst *SI = dyn_cast<StoreInst>(I))
656 return SI->getPointerOperand();
657 llvm_unreachable("Value is not load or store instruction");
662 // Examines the loop nesting of the Src and Dst
663 // instructions and establishes their shared loops. Sets the variables
664 // CommonLevels, SrcLevels, and MaxLevels.
665 // The source and destination instructions needn't be contained in the same
666 // loop. The routine establishNestingLevels finds the level of most deeply
667 // nested loop that contains them both, CommonLevels. An instruction that's
668 // not contained in a loop is at level = 0. MaxLevels is equal to the level
669 // of the source plus the level of the destination, minus CommonLevels.
670 // This lets us allocate vectors MaxLevels in length, with room for every
671 // distinct loop referenced in both the source and destination subscripts.
672 // The variable SrcLevels is the nesting depth of the source instruction.
673 // It's used to help calculate distinct loops referenced by the destination.
674 // Here's the map from loops to levels:
676 // 1 - outermost common loop
677 // ... - other common loops
678 // CommonLevels - innermost common loop
679 // ... - loops containing Src but not Dst
680 // SrcLevels - innermost loop containing Src but not Dst
681 // ... - loops containing Dst but not Src
682 // MaxLevels - innermost loops containing Dst but not Src
683 // Consider the follow code fragment:
700 // If we're looking at the possibility of a dependence between the store
701 // to A (the Src) and the load from A (the Dst), we'll note that they
702 // have 2 loops in common, so CommonLevels will equal 2 and the direction
703 // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
704 // A map from loop names to loop numbers would look like
706 // b - 2 = CommonLevels
712 void DependenceAnalysis::establishNestingLevels(const Instruction *Src,
713 const Instruction *Dst) {
714 const BasicBlock *SrcBlock = Src->getParent();
715 const BasicBlock *DstBlock = Dst->getParent();
716 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
717 unsigned DstLevel = LI->getLoopDepth(DstBlock);
718 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
719 const Loop *DstLoop = LI->getLoopFor(DstBlock);
720 SrcLevels = SrcLevel;
721 MaxLevels = SrcLevel + DstLevel;
722 while (SrcLevel > DstLevel) {
723 SrcLoop = SrcLoop->getParentLoop();
726 while (DstLevel > SrcLevel) {
727 DstLoop = DstLoop->getParentLoop();
730 while (SrcLoop != DstLoop) {
731 SrcLoop = SrcLoop->getParentLoop();
732 DstLoop = DstLoop->getParentLoop();
735 CommonLevels = SrcLevel;
736 MaxLevels -= CommonLevels;
740 // Given one of the loops containing the source, return
741 // its level index in our numbering scheme.
742 unsigned DependenceAnalysis::mapSrcLoop(const Loop *SrcLoop) const {
743 return SrcLoop->getLoopDepth();
747 // Given one of the loops containing the destination,
748 // return its level index in our numbering scheme.
749 unsigned DependenceAnalysis::mapDstLoop(const Loop *DstLoop) const {
750 unsigned D = DstLoop->getLoopDepth();
751 if (D > CommonLevels)
752 return D - CommonLevels + SrcLevels;
758 // Returns true if Expression is loop invariant in LoopNest.
759 bool DependenceAnalysis::isLoopInvariant(const SCEV *Expression,
760 const Loop *LoopNest) const {
763 return SE->isLoopInvariant(Expression, LoopNest) &&
764 isLoopInvariant(Expression, LoopNest->getParentLoop());
769 // Finds the set of loops from the LoopNest that
770 // have a level <= CommonLevels and are referred to by the SCEV Expression.
771 void DependenceAnalysis::collectCommonLoops(const SCEV *Expression,
772 const Loop *LoopNest,
773 SmallBitVector &Loops) const {
775 unsigned Level = LoopNest->getLoopDepth();
776 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
778 LoopNest = LoopNest->getParentLoop();
782 void DependenceAnalysis::unifySubscriptType(ArrayRef<Subscript *> Pairs) {
784 unsigned widestWidthSeen = 0;
787 // Go through each pair and find the widest bit to which we need
788 // to extend all of them.
789 for (unsigned i = 0; i < Pairs.size(); i++) {
790 const SCEV *Src = Pairs[i]->Src;
791 const SCEV *Dst = Pairs[i]->Dst;
792 IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
793 IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
794 if (SrcTy == nullptr || DstTy == nullptr) {
795 assert(SrcTy == DstTy && "This function only unify integer types and "
796 "expect Src and Dst share the same type "
800 if (SrcTy->getBitWidth() > widestWidthSeen) {
801 widestWidthSeen = SrcTy->getBitWidth();
804 if (DstTy->getBitWidth() > widestWidthSeen) {
805 widestWidthSeen = DstTy->getBitWidth();
811 assert(widestWidthSeen > 0);
813 // Now extend each pair to the widest seen.
814 for (unsigned i = 0; i < Pairs.size(); i++) {
815 const SCEV *Src = Pairs[i]->Src;
816 const SCEV *Dst = Pairs[i]->Dst;
817 IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
818 IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
819 if (SrcTy == nullptr || DstTy == nullptr) {
820 assert(SrcTy == DstTy && "This function only unify integer types and "
821 "expect Src and Dst share the same type "
825 if (SrcTy->getBitWidth() < widestWidthSeen)
826 // Sign-extend Src to widestType
827 Pairs[i]->Src = SE->getSignExtendExpr(Src, widestType);
828 if (DstTy->getBitWidth() < widestWidthSeen) {
829 // Sign-extend Dst to widestType
830 Pairs[i]->Dst = SE->getSignExtendExpr(Dst, widestType);
835 // removeMatchingExtensions - Examines a subscript pair.
836 // If the source and destination are identically sign (or zero)
837 // extended, it strips off the extension in an effect to simplify
838 // the actual analysis.
839 void DependenceAnalysis::removeMatchingExtensions(Subscript *Pair) {
840 const SCEV *Src = Pair->Src;
841 const SCEV *Dst = Pair->Dst;
842 if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
843 (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
844 const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src);
845 const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst);
846 const SCEV *SrcCastOp = SrcCast->getOperand();
847 const SCEV *DstCastOp = DstCast->getOperand();
848 if (SrcCastOp->getType() == DstCastOp->getType()) {
849 Pair->Src = SrcCastOp;
850 Pair->Dst = DstCastOp;
856 // Examine the scev and return true iff it's linear.
857 // Collect any loops mentioned in the set of "Loops".
858 bool DependenceAnalysis::checkSrcSubscript(const SCEV *Src,
859 const Loop *LoopNest,
860 SmallBitVector &Loops) {
861 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Src);
863 return isLoopInvariant(Src, LoopNest);
864 const SCEV *Start = AddRec->getStart();
865 const SCEV *Step = AddRec->getStepRecurrence(*SE);
866 const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
867 if (!isa<SCEVCouldNotCompute>(UB)) {
868 if (SE->getTypeSizeInBits(Start->getType()) <
869 SE->getTypeSizeInBits(UB->getType())) {
870 if (!AddRec->getNoWrapFlags())
874 if (!isLoopInvariant(Step, LoopNest))
876 Loops.set(mapSrcLoop(AddRec->getLoop()));
877 return checkSrcSubscript(Start, LoopNest, Loops);
882 // Examine the scev and return true iff it's linear.
883 // Collect any loops mentioned in the set of "Loops".
884 bool DependenceAnalysis::checkDstSubscript(const SCEV *Dst,
885 const Loop *LoopNest,
886 SmallBitVector &Loops) {
887 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Dst);
889 return isLoopInvariant(Dst, LoopNest);
890 const SCEV *Start = AddRec->getStart();
891 const SCEV *Step = AddRec->getStepRecurrence(*SE);
892 const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
893 if (!isa<SCEVCouldNotCompute>(UB)) {
894 if (SE->getTypeSizeInBits(Start->getType()) <
895 SE->getTypeSizeInBits(UB->getType())) {
896 if (!AddRec->getNoWrapFlags())
900 if (!isLoopInvariant(Step, LoopNest))
902 Loops.set(mapDstLoop(AddRec->getLoop()));
903 return checkDstSubscript(Start, LoopNest, Loops);
907 // Examines the subscript pair (the Src and Dst SCEVs)
908 // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
909 // Collects the associated loops in a set.
910 DependenceAnalysis::Subscript::ClassificationKind
911 DependenceAnalysis::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
912 const SCEV *Dst, const Loop *DstLoopNest,
913 SmallBitVector &Loops) {
914 SmallBitVector SrcLoops(MaxLevels + 1);
915 SmallBitVector DstLoops(MaxLevels + 1);
916 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
917 return Subscript::NonLinear;
918 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
919 return Subscript::NonLinear;
922 unsigned N = Loops.count();
924 return Subscript::ZIV;
926 return Subscript::SIV;
927 if (N == 2 && (SrcLoops.count() == 0 ||
928 DstLoops.count() == 0 ||
929 (SrcLoops.count() == 1 && DstLoops.count() == 1)))
930 return Subscript::RDIV;
931 return Subscript::MIV;
935 // A wrapper around SCEV::isKnownPredicate.
936 // Looks for cases where we're interested in comparing for equality.
937 // If both X and Y have been identically sign or zero extended,
938 // it strips off the (confusing) extensions before invoking
939 // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
940 // will be similarly updated.
942 // If SCEV::isKnownPredicate can't prove the predicate,
943 // we try simple subtraction, which seems to help in some cases
944 // involving symbolics.
945 bool DependenceAnalysis::isKnownPredicate(ICmpInst::Predicate Pred,
947 const SCEV *Y) const {
948 if (Pred == CmpInst::ICMP_EQ ||
949 Pred == CmpInst::ICMP_NE) {
950 if ((isa<SCEVSignExtendExpr>(X) &&
951 isa<SCEVSignExtendExpr>(Y)) ||
952 (isa<SCEVZeroExtendExpr>(X) &&
953 isa<SCEVZeroExtendExpr>(Y))) {
954 const SCEVCastExpr *CX = cast<SCEVCastExpr>(X);
955 const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y);
956 const SCEV *Xop = CX->getOperand();
957 const SCEV *Yop = CY->getOperand();
958 if (Xop->getType() == Yop->getType()) {
964 if (SE->isKnownPredicate(Pred, X, Y))
966 // If SE->isKnownPredicate can't prove the condition,
967 // we try the brute-force approach of subtracting
968 // and testing the difference.
969 // By testing with SE->isKnownPredicate first, we avoid
970 // the possibility of overflow when the arguments are constants.
971 const SCEV *Delta = SE->getMinusSCEV(X, Y);
973 case CmpInst::ICMP_EQ:
974 return Delta->isZero();
975 case CmpInst::ICMP_NE:
976 return SE->isKnownNonZero(Delta);
977 case CmpInst::ICMP_SGE:
978 return SE->isKnownNonNegative(Delta);
979 case CmpInst::ICMP_SLE:
980 return SE->isKnownNonPositive(Delta);
981 case CmpInst::ICMP_SGT:
982 return SE->isKnownPositive(Delta);
983 case CmpInst::ICMP_SLT:
984 return SE->isKnownNegative(Delta);
986 llvm_unreachable("unexpected predicate in isKnownPredicate");
991 // All subscripts are all the same type.
992 // Loop bound may be smaller (e.g., a char).
993 // Should zero extend loop bound, since it's always >= 0.
994 // This routine collects upper bound and extends or truncates if needed.
995 // Truncating is safe when subscripts are known not to wrap. Cases without
996 // nowrap flags should have been rejected earlier.
997 // Return null if no bound available.
998 const SCEV *DependenceAnalysis::collectUpperBound(const Loop *L,
1000 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
1001 const SCEV *UB = SE->getBackedgeTakenCount(L);
1002 return SE->getTruncateOrZeroExtend(UB, T);
1008 // Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
1009 // If the cast fails, returns NULL.
1010 const SCEVConstant *DependenceAnalysis::collectConstantUpperBound(const Loop *L,
1013 if (const SCEV *UB = collectUpperBound(L, T))
1014 return dyn_cast<SCEVConstant>(UB);
1020 // When we have a pair of subscripts of the form [c1] and [c2],
1021 // where c1 and c2 are both loop invariant, we attack it using
1022 // the ZIV test. Basically, we test by comparing the two values,
1023 // but there are actually three possible results:
1024 // 1) the values are equal, so there's a dependence
1025 // 2) the values are different, so there's no dependence
1026 // 3) the values might be equal, so we have to assume a dependence.
1028 // Return true if dependence disproved.
1029 bool DependenceAnalysis::testZIV(const SCEV *Src,
1031 FullDependence &Result) const {
1032 DEBUG(dbgs() << " src = " << *Src << "\n");
1033 DEBUG(dbgs() << " dst = " << *Dst << "\n");
1035 if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
1036 DEBUG(dbgs() << " provably dependent\n");
1037 return false; // provably dependent
1039 if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
1040 DEBUG(dbgs() << " provably independent\n");
1042 return true; // provably independent
1044 DEBUG(dbgs() << " possibly dependent\n");
1045 Result.Consistent = false;
1046 return false; // possibly dependent
1051 // From the paper, Practical Dependence Testing, Section 4.2.1
1053 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
1054 // where i is an induction variable, c1 and c2 are loop invariant,
1055 // and a is a constant, we can solve it exactly using the Strong SIV test.
1057 // Can prove independence. Failing that, can compute distance (and direction).
1058 // In the presence of symbolic terms, we can sometimes make progress.
1060 // If there's a dependence,
1062 // c1 + a*i = c2 + a*i'
1064 // The dependence distance is
1066 // d = i' - i = (c1 - c2)/a
1068 // A dependence only exists if d is an integer and abs(d) <= U, where U is the
1069 // loop's upper bound. If a dependence exists, the dependence direction is
1073 // direction = { = if d = 0
1076 // Return true if dependence disproved.
1077 bool DependenceAnalysis::strongSIVtest(const SCEV *Coeff,
1078 const SCEV *SrcConst,
1079 const SCEV *DstConst,
1080 const Loop *CurLoop,
1082 FullDependence &Result,
1083 Constraint &NewConstraint) const {
1084 DEBUG(dbgs() << "\tStrong SIV test\n");
1085 DEBUG(dbgs() << "\t Coeff = " << *Coeff);
1086 DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1087 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
1088 DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1089 DEBUG(dbgs() << "\t DstConst = " << *DstConst);
1090 DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
1091 ++StrongSIVapplications;
1092 assert(0 < Level && Level <= CommonLevels && "level out of range");
1095 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1096 DEBUG(dbgs() << "\t Delta = " << *Delta);
1097 DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
1099 // check that |Delta| < iteration count
1100 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1101 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound);
1102 DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
1103 const SCEV *AbsDelta =
1104 SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
1105 const SCEV *AbsCoeff =
1106 SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
1107 const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
1108 if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
1109 // Distance greater than trip count - no dependence
1110 ++StrongSIVindependence;
1111 ++StrongSIVsuccesses;
1116 // Can we compute distance?
1117 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
1118 APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
1119 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
1120 APInt Distance = ConstDelta; // these need to be initialized
1121 APInt Remainder = ConstDelta;
1122 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
1123 DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1124 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1125 // Make sure Coeff divides Delta exactly
1126 if (Remainder != 0) {
1127 // Coeff doesn't divide Distance, no dependence
1128 ++StrongSIVindependence;
1129 ++StrongSIVsuccesses;
1132 Result.DV[Level].Distance = SE->getConstant(Distance);
1133 NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
1134 if (Distance.sgt(0))
1135 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1136 else if (Distance.slt(0))
1137 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1139 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1140 ++StrongSIVsuccesses;
1142 else if (Delta->isZero()) {
1144 Result.DV[Level].Distance = Delta;
1145 NewConstraint.setDistance(Delta, CurLoop);
1146 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1147 ++StrongSIVsuccesses;
1150 if (Coeff->isOne()) {
1151 DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
1152 Result.DV[Level].Distance = Delta; // since X/1 == X
1153 NewConstraint.setDistance(Delta, CurLoop);
1156 Result.Consistent = false;
1157 NewConstraint.setLine(Coeff,
1158 SE->getNegativeSCEV(Coeff),
1159 SE->getNegativeSCEV(Delta), CurLoop);
1162 // maybe we can get a useful direction
1163 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
1164 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1165 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1166 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1167 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1168 // The double negatives above are confusing.
1169 // It helps to read !SE->isKnownNonZero(Delta)
1170 // as "Delta might be Zero"
1171 unsigned NewDirection = Dependence::DVEntry::NONE;
1172 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1173 (DeltaMaybeNegative && CoeffMaybeNegative))
1174 NewDirection = Dependence::DVEntry::LT;
1176 NewDirection |= Dependence::DVEntry::EQ;
1177 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1178 (DeltaMaybePositive && CoeffMaybeNegative))
1179 NewDirection |= Dependence::DVEntry::GT;
1180 if (NewDirection < Result.DV[Level].Direction)
1181 ++StrongSIVsuccesses;
1182 Result.DV[Level].Direction &= NewDirection;
1188 // weakCrossingSIVtest -
1189 // From the paper, Practical Dependence Testing, Section 4.2.2
1191 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1192 // where i is an induction variable, c1 and c2 are loop invariant,
1193 // and a is a constant, we can solve it exactly using the
1194 // Weak-Crossing SIV test.
1196 // Given c1 + a*i = c2 - a*i', we can look for the intersection of
1197 // the two lines, where i = i', yielding
1199 // c1 + a*i = c2 - a*i
1203 // If i < 0, there is no dependence.
1204 // If i > upperbound, there is no dependence.
1205 // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1206 // If i = upperbound, there's a dependence with distance = 0.
1207 // If i is integral, there's a dependence (all directions).
1208 // If the non-integer part = 1/2, there's a dependence (<> directions).
1209 // Otherwise, there's no dependence.
1211 // Can prove independence. Failing that,
1212 // can sometimes refine the directions.
1213 // Can determine iteration for splitting.
1215 // Return true if dependence disproved.
1216 bool DependenceAnalysis::weakCrossingSIVtest(const SCEV *Coeff,
1217 const SCEV *SrcConst,
1218 const SCEV *DstConst,
1219 const Loop *CurLoop,
1221 FullDependence &Result,
1222 Constraint &NewConstraint,
1223 const SCEV *&SplitIter) const {
1224 DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1225 DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1226 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1227 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1228 ++WeakCrossingSIVapplications;
1229 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1231 Result.Consistent = false;
1232 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1233 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1234 NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
1235 if (Delta->isZero()) {
1236 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1237 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1238 ++WeakCrossingSIVsuccesses;
1239 if (!Result.DV[Level].Direction) {
1240 ++WeakCrossingSIVindependence;
1243 Result.DV[Level].Distance = Delta; // = 0
1246 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1250 Result.DV[Level].Splitable = true;
1251 if (SE->isKnownNegative(ConstCoeff)) {
1252 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1253 assert(ConstCoeff &&
1254 "dynamic cast of negative of ConstCoeff should yield constant");
1255 Delta = SE->getNegativeSCEV(Delta);
1257 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1259 // compute SplitIter for use by DependenceAnalysis::getSplitIteration()
1260 SplitIter = SE->getUDivExpr(
1261 SE->getSMaxExpr(SE->getZero(Delta->getType()), Delta),
1262 SE->getMulExpr(SE->getConstant(Delta->getType(), 2), ConstCoeff));
1263 DEBUG(dbgs() << "\t Split iter = " << *SplitIter << "\n");
1265 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1269 // We're certain that ConstCoeff > 0; therefore,
1270 // if Delta < 0, then no dependence.
1271 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1272 DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
1273 if (SE->isKnownNegative(Delta)) {
1274 // No dependence, Delta < 0
1275 ++WeakCrossingSIVindependence;
1276 ++WeakCrossingSIVsuccesses;
1280 // We're certain that Delta > 0 and ConstCoeff > 0.
1281 // Check Delta/(2*ConstCoeff) against upper loop bound
1282 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1283 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1284 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1285 const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
1287 DEBUG(dbgs() << "\t ML = " << *ML << "\n");
1288 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1289 // Delta too big, no dependence
1290 ++WeakCrossingSIVindependence;
1291 ++WeakCrossingSIVsuccesses;
1294 if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1296 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1297 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1298 ++WeakCrossingSIVsuccesses;
1299 if (!Result.DV[Level].Direction) {
1300 ++WeakCrossingSIVindependence;
1303 Result.DV[Level].Splitable = false;
1304 Result.DV[Level].Distance = SE->getZero(Delta->getType());
1309 // check that Coeff divides Delta
1310 APInt APDelta = ConstDelta->getAPInt();
1311 APInt APCoeff = ConstCoeff->getAPInt();
1312 APInt Distance = APDelta; // these need to be initialzed
1313 APInt Remainder = APDelta;
1314 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1315 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1316 if (Remainder != 0) {
1317 // Coeff doesn't divide Delta, no dependence
1318 ++WeakCrossingSIVindependence;
1319 ++WeakCrossingSIVsuccesses;
1322 DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1324 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1325 APInt Two = APInt(Distance.getBitWidth(), 2, true);
1326 Remainder = Distance.srem(Two);
1327 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1328 if (Remainder != 0) {
1329 // Equal direction isn't possible
1330 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
1331 ++WeakCrossingSIVsuccesses;
1337 // Kirch's algorithm, from
1339 // Optimizing Supercompilers for Supercomputers
1343 // Program 2.1, page 29.
1344 // Computes the GCD of AM and BM.
1345 // Also finds a solution to the equation ax - by = gcd(a, b).
1346 // Returns true if dependence disproved; i.e., gcd does not divide Delta.
1348 bool findGCD(unsigned Bits, APInt AM, APInt BM, APInt Delta,
1349 APInt &G, APInt &X, APInt &Y) {
1350 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1351 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1352 APInt G0 = AM.abs();
1353 APInt G1 = BM.abs();
1354 APInt Q = G0; // these need to be initialized
1356 APInt::sdivrem(G0, G1, Q, R);
1358 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1359 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1361 APInt::sdivrem(G0, G1, Q, R);
1364 DEBUG(dbgs() << "\t GCD = " << G << "\n");
1365 X = AM.slt(0) ? -A1 : A1;
1366 Y = BM.slt(0) ? B1 : -B1;
1368 // make sure gcd divides Delta
1371 return true; // gcd doesn't divide Delta, no dependence
1380 APInt floorOfQuotient(APInt A, APInt B) {
1381 APInt Q = A; // these need to be initialized
1383 APInt::sdivrem(A, B, Q, R);
1386 if ((A.sgt(0) && B.sgt(0)) ||
1387 (A.slt(0) && B.slt(0)))
1395 APInt ceilingOfQuotient(APInt A, APInt B) {
1396 APInt Q = A; // these need to be initialized
1398 APInt::sdivrem(A, B, Q, R);
1401 if ((A.sgt(0) && B.sgt(0)) ||
1402 (A.slt(0) && B.slt(0)))
1410 APInt maxAPInt(APInt A, APInt B) {
1411 return A.sgt(B) ? A : B;
1416 APInt minAPInt(APInt A, APInt B) {
1417 return A.slt(B) ? A : B;
1422 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1423 // where i is an induction variable, c1 and c2 are loop invariant, and a1
1424 // and a2 are constant, we can solve it exactly using an algorithm developed
1425 // by Banerjee and Wolfe. See Section 2.5.3 in
1427 // Optimizing Supercompilers for Supercomputers
1431 // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1432 // so use them if possible. They're also a bit better with symbolics and,
1433 // in the case of the strong SIV test, can compute Distances.
1435 // Return true if dependence disproved.
1436 bool DependenceAnalysis::exactSIVtest(const SCEV *SrcCoeff,
1437 const SCEV *DstCoeff,
1438 const SCEV *SrcConst,
1439 const SCEV *DstConst,
1440 const Loop *CurLoop,
1442 FullDependence &Result,
1443 Constraint &NewConstraint) const {
1444 DEBUG(dbgs() << "\tExact SIV test\n");
1445 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1446 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1447 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1448 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1449 ++ExactSIVapplications;
1450 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1452 Result.Consistent = false;
1453 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1454 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1455 NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff),
1457 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1458 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1459 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1460 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1465 APInt AM = ConstSrcCoeff->getAPInt();
1466 APInt BM = ConstDstCoeff->getAPInt();
1467 unsigned Bits = AM.getBitWidth();
1468 if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
1469 // gcd doesn't divide Delta, no dependence
1470 ++ExactSIVindependence;
1471 ++ExactSIVsuccesses;
1475 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1477 // since SCEV construction normalizes, LM = 0
1478 APInt UM(Bits, 1, true);
1479 bool UMvalid = false;
1480 // UM is perhaps unavailable, let's check
1481 if (const SCEVConstant *CUB =
1482 collectConstantUpperBound(CurLoop, Delta->getType())) {
1483 UM = CUB->getAPInt();
1484 DEBUG(dbgs() << "\t UM = " << UM << "\n");
1488 APInt TU(APInt::getSignedMaxValue(Bits));
1489 APInt TL(APInt::getSignedMinValue(Bits));
1491 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1492 APInt TMUL = BM.sdiv(G);
1494 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1495 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1497 TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL));
1498 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1502 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1503 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1505 TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL));
1506 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1510 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1513 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1514 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1516 TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL));
1517 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1521 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1522 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1524 TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL));
1525 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1529 ++ExactSIVindependence;
1530 ++ExactSIVsuccesses;
1534 // explore directions
1535 unsigned NewDirection = Dependence::DVEntry::NONE;
1538 APInt SaveTU(TU); // save these
1540 DEBUG(dbgs() << "\t exploring LT direction\n");
1543 TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL));
1544 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1547 TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL));
1548 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1551 NewDirection |= Dependence::DVEntry::LT;
1552 ++ExactSIVsuccesses;
1556 TU = SaveTU; // restore
1558 DEBUG(dbgs() << "\t exploring EQ direction\n");
1560 TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL));
1561 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1564 TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL));
1565 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1569 TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL));
1570 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1573 TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL));
1574 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1577 NewDirection |= Dependence::DVEntry::EQ;
1578 ++ExactSIVsuccesses;
1582 TU = SaveTU; // restore
1584 DEBUG(dbgs() << "\t exploring GT direction\n");
1586 TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL));
1587 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1590 TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL));
1591 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1594 NewDirection |= Dependence::DVEntry::GT;
1595 ++ExactSIVsuccesses;
1599 Result.DV[Level].Direction &= NewDirection;
1600 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1601 ++ExactSIVindependence;
1602 return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1607 // Return true if the divisor evenly divides the dividend.
1609 bool isRemainderZero(const SCEVConstant *Dividend,
1610 const SCEVConstant *Divisor) {
1611 APInt ConstDividend = Dividend->getAPInt();
1612 APInt ConstDivisor = Divisor->getAPInt();
1613 return ConstDividend.srem(ConstDivisor) == 0;
1617 // weakZeroSrcSIVtest -
1618 // From the paper, Practical Dependence Testing, Section 4.2.2
1620 // When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1621 // where i is an induction variable, c1 and c2 are loop invariant,
1622 // and a is a constant, we can solve it exactly using the
1623 // Weak-Zero SIV test.
1633 // If i is not an integer, there's no dependence.
1634 // If i < 0 or > UB, there's no dependence.
1635 // If i = 0, the direction is <= and peeling the
1636 // 1st iteration will break the dependence.
1637 // If i = UB, the direction is >= and peeling the
1638 // last iteration will break the dependence.
1639 // Otherwise, the direction is *.
1641 // Can prove independence. Failing that, we can sometimes refine
1642 // the directions. Can sometimes show that first or last
1643 // iteration carries all the dependences (so worth peeling).
1645 // (see also weakZeroDstSIVtest)
1647 // Return true if dependence disproved.
1648 bool DependenceAnalysis::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1649 const SCEV *SrcConst,
1650 const SCEV *DstConst,
1651 const Loop *CurLoop,
1653 FullDependence &Result,
1654 Constraint &NewConstraint) const {
1655 // For the WeakSIV test, it's possible the loop isn't common to
1656 // the Src and Dst loops. If it isn't, then there's no need to
1657 // record a direction.
1658 DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1659 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1660 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1661 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1662 ++WeakZeroSIVapplications;
1663 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1665 Result.Consistent = false;
1666 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1667 NewConstraint.setLine(SE->getZero(Delta->getType()), DstCoeff, Delta,
1669 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1670 if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
1671 if (Level < CommonLevels) {
1672 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1673 Result.DV[Level].PeelFirst = true;
1674 ++WeakZeroSIVsuccesses;
1676 return false; // dependences caused by first iteration
1678 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1681 const SCEV *AbsCoeff =
1682 SE->isKnownNegative(ConstCoeff) ?
1683 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1684 const SCEV *NewDelta =
1685 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1687 // check that Delta/SrcCoeff < iteration count
1688 // really check NewDelta < count*AbsCoeff
1689 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1690 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1691 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1692 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1693 ++WeakZeroSIVindependence;
1694 ++WeakZeroSIVsuccesses;
1697 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1698 // dependences caused by last iteration
1699 if (Level < CommonLevels) {
1700 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1701 Result.DV[Level].PeelLast = true;
1702 ++WeakZeroSIVsuccesses;
1708 // check that Delta/SrcCoeff >= 0
1709 // really check that NewDelta >= 0
1710 if (SE->isKnownNegative(NewDelta)) {
1711 // No dependence, newDelta < 0
1712 ++WeakZeroSIVindependence;
1713 ++WeakZeroSIVsuccesses;
1717 // if SrcCoeff doesn't divide Delta, then no dependence
1718 if (isa<SCEVConstant>(Delta) &&
1719 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1720 ++WeakZeroSIVindependence;
1721 ++WeakZeroSIVsuccesses;
1728 // weakZeroDstSIVtest -
1729 // From the paper, Practical Dependence Testing, Section 4.2.2
1731 // When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1732 // where i is an induction variable, c1 and c2 are loop invariant,
1733 // and a is a constant, we can solve it exactly using the
1734 // Weak-Zero SIV test.
1744 // If i is not an integer, there's no dependence.
1745 // If i < 0 or > UB, there's no dependence.
1746 // If i = 0, the direction is <= and peeling the
1747 // 1st iteration will break the dependence.
1748 // If i = UB, the direction is >= and peeling the
1749 // last iteration will break the dependence.
1750 // Otherwise, the direction is *.
1752 // Can prove independence. Failing that, we can sometimes refine
1753 // the directions. Can sometimes show that first or last
1754 // iteration carries all the dependences (so worth peeling).
1756 // (see also weakZeroSrcSIVtest)
1758 // Return true if dependence disproved.
1759 bool DependenceAnalysis::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1760 const SCEV *SrcConst,
1761 const SCEV *DstConst,
1762 const Loop *CurLoop,
1764 FullDependence &Result,
1765 Constraint &NewConstraint) const {
1766 // For the WeakSIV test, it's possible the loop isn't common to the
1767 // Src and Dst loops. If it isn't, then there's no need to record a direction.
1768 DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1769 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1770 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1771 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1772 ++WeakZeroSIVapplications;
1773 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1775 Result.Consistent = false;
1776 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1777 NewConstraint.setLine(SrcCoeff, SE->getZero(Delta->getType()), Delta,
1779 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1780 if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
1781 if (Level < CommonLevels) {
1782 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1783 Result.DV[Level].PeelFirst = true;
1784 ++WeakZeroSIVsuccesses;
1786 return false; // dependences caused by first iteration
1788 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1791 const SCEV *AbsCoeff =
1792 SE->isKnownNegative(ConstCoeff) ?
1793 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1794 const SCEV *NewDelta =
1795 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1797 // check that Delta/SrcCoeff < iteration count
1798 // really check NewDelta < count*AbsCoeff
1799 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1800 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1801 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1802 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1803 ++WeakZeroSIVindependence;
1804 ++WeakZeroSIVsuccesses;
1807 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1808 // dependences caused by last iteration
1809 if (Level < CommonLevels) {
1810 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1811 Result.DV[Level].PeelLast = true;
1812 ++WeakZeroSIVsuccesses;
1818 // check that Delta/SrcCoeff >= 0
1819 // really check that NewDelta >= 0
1820 if (SE->isKnownNegative(NewDelta)) {
1821 // No dependence, newDelta < 0
1822 ++WeakZeroSIVindependence;
1823 ++WeakZeroSIVsuccesses;
1827 // if SrcCoeff doesn't divide Delta, then no dependence
1828 if (isa<SCEVConstant>(Delta) &&
1829 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1830 ++WeakZeroSIVindependence;
1831 ++WeakZeroSIVsuccesses;
1838 // exactRDIVtest - Tests the RDIV subscript pair for dependence.
1839 // Things of the form [c1 + a*i] and [c2 + b*j],
1840 // where i and j are induction variable, c1 and c2 are loop invariant,
1841 // and a and b are constants.
1842 // Returns true if any possible dependence is disproved.
1843 // Marks the result as inconsistent.
1844 // Works in some cases that symbolicRDIVtest doesn't, and vice versa.
1845 bool DependenceAnalysis::exactRDIVtest(const SCEV *SrcCoeff,
1846 const SCEV *DstCoeff,
1847 const SCEV *SrcConst,
1848 const SCEV *DstConst,
1849 const Loop *SrcLoop,
1850 const Loop *DstLoop,
1851 FullDependence &Result) const {
1852 DEBUG(dbgs() << "\tExact RDIV test\n");
1853 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1854 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1855 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1856 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1857 ++ExactRDIVapplications;
1858 Result.Consistent = false;
1859 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1860 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1861 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1862 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1863 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1864 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1869 APInt AM = ConstSrcCoeff->getAPInt();
1870 APInt BM = ConstDstCoeff->getAPInt();
1871 unsigned Bits = AM.getBitWidth();
1872 if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
1873 // gcd doesn't divide Delta, no dependence
1874 ++ExactRDIVindependence;
1878 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1880 // since SCEV construction seems to normalize, LM = 0
1881 APInt SrcUM(Bits, 1, true);
1882 bool SrcUMvalid = false;
1883 // SrcUM is perhaps unavailable, let's check
1884 if (const SCEVConstant *UpperBound =
1885 collectConstantUpperBound(SrcLoop, Delta->getType())) {
1886 SrcUM = UpperBound->getAPInt();
1887 DEBUG(dbgs() << "\t SrcUM = " << SrcUM << "\n");
1891 APInt DstUM(Bits, 1, true);
1892 bool DstUMvalid = false;
1893 // UM is perhaps unavailable, let's check
1894 if (const SCEVConstant *UpperBound =
1895 collectConstantUpperBound(DstLoop, Delta->getType())) {
1896 DstUM = UpperBound->getAPInt();
1897 DEBUG(dbgs() << "\t DstUM = " << DstUM << "\n");
1901 APInt TU(APInt::getSignedMaxValue(Bits));
1902 APInt TL(APInt::getSignedMinValue(Bits));
1904 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1905 APInt TMUL = BM.sdiv(G);
1907 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1908 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1910 TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL));
1911 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1915 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1916 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1918 TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL));
1919 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1923 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1926 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1927 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1929 TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL));
1930 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1934 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1935 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1937 TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL));
1938 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1942 ++ExactRDIVindependence;
1947 // symbolicRDIVtest -
1948 // In Section 4.5 of the Practical Dependence Testing paper,the authors
1949 // introduce a special case of Banerjee's Inequalities (also called the
1950 // Extreme-Value Test) that can handle some of the SIV and RDIV cases,
1951 // particularly cases with symbolics. Since it's only able to disprove
1952 // dependence (not compute distances or directions), we'll use it as a
1953 // fall back for the other tests.
1955 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
1956 // where i and j are induction variables and c1 and c2 are loop invariants,
1957 // we can use the symbolic tests to disprove some dependences, serving as a
1958 // backup for the RDIV test. Note that i and j can be the same variable,
1959 // letting this test serve as a backup for the various SIV tests.
1961 // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
1962 // 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
1963 // loop bounds for the i and j loops, respectively. So, ...
1965 // c1 + a1*i = c2 + a2*j
1966 // a1*i - a2*j = c2 - c1
1968 // To test for a dependence, we compute c2 - c1 and make sure it's in the
1969 // range of the maximum and minimum possible values of a1*i - a2*j.
1970 // Considering the signs of a1 and a2, we have 4 possible cases:
1972 // 1) If a1 >= 0 and a2 >= 0, then
1973 // a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
1974 // -a2*N2 <= c2 - c1 <= a1*N1
1976 // 2) If a1 >= 0 and a2 <= 0, then
1977 // a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
1978 // 0 <= c2 - c1 <= a1*N1 - a2*N2
1980 // 3) If a1 <= 0 and a2 >= 0, then
1981 // a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
1982 // a1*N1 - a2*N2 <= c2 - c1 <= 0
1984 // 4) If a1 <= 0 and a2 <= 0, then
1985 // a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
1986 // a1*N1 <= c2 - c1 <= -a2*N2
1988 // return true if dependence disproved
1989 bool DependenceAnalysis::symbolicRDIVtest(const SCEV *A1,
1994 const Loop *Loop2) const {
1995 ++SymbolicRDIVapplications;
1996 DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
1997 DEBUG(dbgs() << "\t A1 = " << *A1);
1998 DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
1999 DEBUG(dbgs() << "\t A2 = " << *A2 << "\n");
2000 DEBUG(dbgs() << "\t C1 = " << *C1 << "\n");
2001 DEBUG(dbgs() << "\t C2 = " << *C2 << "\n");
2002 const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
2003 const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
2004 DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n");
2005 DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n");
2006 const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
2007 const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
2008 DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n");
2009 DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n");
2010 if (SE->isKnownNonNegative(A1)) {
2011 if (SE->isKnownNonNegative(A2)) {
2012 // A1 >= 0 && A2 >= 0
2014 // make sure that c2 - c1 <= a1*N1
2015 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2016 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
2017 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
2018 ++SymbolicRDIVindependence;
2023 // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
2024 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2025 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
2026 if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
2027 ++SymbolicRDIVindependence;
2032 else if (SE->isKnownNonPositive(A2)) {
2033 // a1 >= 0 && a2 <= 0
2035 // make sure that c2 - c1 <= a1*N1 - a2*N2
2036 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2037 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2038 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2039 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2040 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
2041 ++SymbolicRDIVindependence;
2045 // make sure that 0 <= c2 - c1
2046 if (SE->isKnownNegative(C2_C1)) {
2047 ++SymbolicRDIVindependence;
2052 else if (SE->isKnownNonPositive(A1)) {
2053 if (SE->isKnownNonNegative(A2)) {
2054 // a1 <= 0 && a2 >= 0
2056 // make sure that a1*N1 - a2*N2 <= c2 - c1
2057 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2058 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2059 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2060 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2061 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
2062 ++SymbolicRDIVindependence;
2066 // make sure that c2 - c1 <= 0
2067 if (SE->isKnownPositive(C2_C1)) {
2068 ++SymbolicRDIVindependence;
2072 else if (SE->isKnownNonPositive(A2)) {
2073 // a1 <= 0 && a2 <= 0
2075 // make sure that a1*N1 <= c2 - c1
2076 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2077 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
2078 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2079 ++SymbolicRDIVindependence;
2084 // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2085 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2086 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
2087 if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2088 ++SymbolicRDIVindependence;
2099 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2100 // where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2101 // a2 are constant, we attack it with an SIV test. While they can all be
2102 // solved with the Exact SIV test, it's worthwhile to use simpler tests when
2103 // they apply; they're cheaper and sometimes more precise.
2105 // Return true if dependence disproved.
2106 bool DependenceAnalysis::testSIV(const SCEV *Src,
2109 FullDependence &Result,
2110 Constraint &NewConstraint,
2111 const SCEV *&SplitIter) const {
2112 DEBUG(dbgs() << " src = " << *Src << "\n");
2113 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2114 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2115 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2116 if (SrcAddRec && DstAddRec) {
2117 const SCEV *SrcConst = SrcAddRec->getStart();
2118 const SCEV *DstConst = DstAddRec->getStart();
2119 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2120 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2121 const Loop *CurLoop = SrcAddRec->getLoop();
2122 assert(CurLoop == DstAddRec->getLoop() &&
2123 "both loops in SIV should be same");
2124 Level = mapSrcLoop(CurLoop);
2126 if (SrcCoeff == DstCoeff)
2127 disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2128 Level, Result, NewConstraint);
2129 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2130 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2131 Level, Result, NewConstraint, SplitIter);
2133 disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
2134 Level, Result, NewConstraint);
2136 gcdMIVtest(Src, Dst, Result) ||
2137 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
2140 const SCEV *SrcConst = SrcAddRec->getStart();
2141 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2142 const SCEV *DstConst = Dst;
2143 const Loop *CurLoop = SrcAddRec->getLoop();
2144 Level = mapSrcLoop(CurLoop);
2145 return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2146 Level, Result, NewConstraint) ||
2147 gcdMIVtest(Src, Dst, Result);
2150 const SCEV *DstConst = DstAddRec->getStart();
2151 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2152 const SCEV *SrcConst = Src;
2153 const Loop *CurLoop = DstAddRec->getLoop();
2154 Level = mapDstLoop(CurLoop);
2155 return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
2156 CurLoop, Level, Result, NewConstraint) ||
2157 gcdMIVtest(Src, Dst, Result);
2159 llvm_unreachable("SIV test expected at least one AddRec");
2165 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2166 // where i and j are induction variables, c1 and c2 are loop invariant,
2167 // and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2168 // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2169 // It doesn't make sense to talk about distance or direction in this case,
2170 // so there's no point in making special versions of the Strong SIV test or
2171 // the Weak-crossing SIV test.
2173 // With minor algebra, this test can also be used for things like
2174 // [c1 + a1*i + a2*j][c2].
2176 // Return true if dependence disproved.
2177 bool DependenceAnalysis::testRDIV(const SCEV *Src,
2179 FullDependence &Result) const {
2180 // we have 3 possible situations here:
2181 // 1) [a*i + b] and [c*j + d]
2182 // 2) [a*i + c*j + b] and [d]
2183 // 3) [b] and [a*i + c*j + d]
2184 // We need to find what we've got and get organized
2186 const SCEV *SrcConst, *DstConst;
2187 const SCEV *SrcCoeff, *DstCoeff;
2188 const Loop *SrcLoop, *DstLoop;
2190 DEBUG(dbgs() << " src = " << *Src << "\n");
2191 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2192 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2193 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2194 if (SrcAddRec && DstAddRec) {
2195 SrcConst = SrcAddRec->getStart();
2196 SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2197 SrcLoop = SrcAddRec->getLoop();
2198 DstConst = DstAddRec->getStart();
2199 DstCoeff = DstAddRec->getStepRecurrence(*SE);
2200 DstLoop = DstAddRec->getLoop();
2202 else if (SrcAddRec) {
2203 if (const SCEVAddRecExpr *tmpAddRec =
2204 dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
2205 SrcConst = tmpAddRec->getStart();
2206 SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
2207 SrcLoop = tmpAddRec->getLoop();
2209 DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
2210 DstLoop = SrcAddRec->getLoop();
2213 llvm_unreachable("RDIV reached by surprising SCEVs");
2215 else if (DstAddRec) {
2216 if (const SCEVAddRecExpr *tmpAddRec =
2217 dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
2218 DstConst = tmpAddRec->getStart();
2219 DstCoeff = tmpAddRec->getStepRecurrence(*SE);
2220 DstLoop = tmpAddRec->getLoop();
2222 SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
2223 SrcLoop = DstAddRec->getLoop();
2226 llvm_unreachable("RDIV reached by surprising SCEVs");
2229 llvm_unreachable("RDIV expected at least one AddRec");
2230 return exactRDIVtest(SrcCoeff, DstCoeff,
2234 gcdMIVtest(Src, Dst, Result) ||
2235 symbolicRDIVtest(SrcCoeff, DstCoeff,
2241 // Tests the single-subscript MIV pair (Src and Dst) for dependence.
2242 // Return true if dependence disproved.
2243 // Can sometimes refine direction vectors.
2244 bool DependenceAnalysis::testMIV(const SCEV *Src,
2246 const SmallBitVector &Loops,
2247 FullDependence &Result) const {
2248 DEBUG(dbgs() << " src = " << *Src << "\n");
2249 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2250 Result.Consistent = false;
2251 return gcdMIVtest(Src, Dst, Result) ||
2252 banerjeeMIVtest(Src, Dst, Loops, Result);
2256 // Given a product, e.g., 10*X*Y, returns the first constant operand,
2257 // in this case 10. If there is no constant part, returns NULL.
2259 const SCEVConstant *getConstantPart(const SCEVMulExpr *Product) {
2260 for (unsigned Op = 0, Ops = Product->getNumOperands(); Op < Ops; Op++) {
2261 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Product->getOperand(Op)))
2268 //===----------------------------------------------------------------------===//
2270 // Tests an MIV subscript pair for dependence.
2271 // Returns true if any possible dependence is disproved.
2272 // Marks the result as inconsistent.
2273 // Can sometimes disprove the equal direction for 1 or more loops,
2274 // as discussed in Michael Wolfe's book,
2275 // High Performance Compilers for Parallel Computing, page 235.
2277 // We spend some effort (code!) to handle cases like
2278 // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2279 // but M and N are just loop-invariant variables.
2280 // This should help us handle linearized subscripts;
2281 // also makes this test a useful backup to the various SIV tests.
2283 // It occurs to me that the presence of loop-invariant variables
2284 // changes the nature of the test from "greatest common divisor"
2285 // to "a common divisor".
2286 bool DependenceAnalysis::gcdMIVtest(const SCEV *Src,
2288 FullDependence &Result) const {
2289 DEBUG(dbgs() << "starting gcd\n");
2291 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
2292 APInt RunningGCD = APInt::getNullValue(BitWidth);
2294 // Examine Src coefficients.
2295 // Compute running GCD and record source constant.
2296 // Because we're looking for the constant at the end of the chain,
2297 // we can't quit the loop just because the GCD == 1.
2298 const SCEV *Coefficients = Src;
2299 while (const SCEVAddRecExpr *AddRec =
2300 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2301 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2302 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
2303 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2304 // If the coefficient is the product of a constant and other stuff,
2305 // we can use the constant in the GCD computation.
2306 Constant = getConstantPart(Product);
2309 APInt ConstCoeff = Constant->getAPInt();
2310 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2311 Coefficients = AddRec->getStart();
2313 const SCEV *SrcConst = Coefficients;
2315 // Examine Dst coefficients.
2316 // Compute running GCD and record destination constant.
2317 // Because we're looking for the constant at the end of the chain,
2318 // we can't quit the loop just because the GCD == 1.
2320 while (const SCEVAddRecExpr *AddRec =
2321 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2322 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2323 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
2324 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2325 // If the coefficient is the product of a constant and other stuff,
2326 // we can use the constant in the GCD computation.
2327 Constant = getConstantPart(Product);
2330 APInt ConstCoeff = Constant->getAPInt();
2331 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2332 Coefficients = AddRec->getStart();
2334 const SCEV *DstConst = Coefficients;
2336 APInt ExtraGCD = APInt::getNullValue(BitWidth);
2337 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
2338 DEBUG(dbgs() << " Delta = " << *Delta << "\n");
2339 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2340 if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
2341 // If Delta is a sum of products, we may be able to make further progress.
2342 for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
2343 const SCEV *Operand = Sum->getOperand(Op);
2344 if (isa<SCEVConstant>(Operand)) {
2345 assert(!Constant && "Surprised to find multiple constants");
2346 Constant = cast<SCEVConstant>(Operand);
2348 else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
2349 // Search for constant operand to participate in GCD;
2350 // If none found; return false.
2351 const SCEVConstant *ConstOp = getConstantPart(Product);
2354 APInt ConstOpValue = ConstOp->getAPInt();
2355 ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
2356 ConstOpValue.abs());
2364 APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
2365 DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
2366 if (ConstDelta == 0)
2368 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
2369 DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
2370 APInt Remainder = ConstDelta.srem(RunningGCD);
2371 if (Remainder != 0) {
2376 // Try to disprove equal directions.
2377 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2378 // the code above can't disprove the dependence because the GCD = 1.
2379 // So we consider what happen if i = i' and what happens if j = j'.
2380 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2381 // which is infeasible, so we can disallow the = direction for the i level.
2382 // Setting j = j' doesn't help matters, so we end up with a direction vector
2385 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2386 // we need to remember that the constant part is 5 and the RunningGCD should
2387 // be initialized to ExtraGCD = 30.
2388 DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
2390 bool Improved = false;
2392 while (const SCEVAddRecExpr *AddRec =
2393 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2394 Coefficients = AddRec->getStart();
2395 const Loop *CurLoop = AddRec->getLoop();
2396 RunningGCD = ExtraGCD;
2397 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2398 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2399 const SCEV *Inner = Src;
2400 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2401 AddRec = cast<SCEVAddRecExpr>(Inner);
2402 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2403 if (CurLoop == AddRec->getLoop())
2404 ; // SrcCoeff == Coeff
2406 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2407 // If the coefficient is the product of a constant and other stuff,
2408 // we can use the constant in the GCD computation.
2409 Constant = getConstantPart(Product);
2411 Constant = cast<SCEVConstant>(Coeff);
2412 APInt ConstCoeff = Constant->getAPInt();
2413 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2415 Inner = AddRec->getStart();
2418 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2419 AddRec = cast<SCEVAddRecExpr>(Inner);
2420 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2421 if (CurLoop == AddRec->getLoop())
2424 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2425 // If the coefficient is the product of a constant and other stuff,
2426 // we can use the constant in the GCD computation.
2427 Constant = getConstantPart(Product);
2429 Constant = cast<SCEVConstant>(Coeff);
2430 APInt ConstCoeff = Constant->getAPInt();
2431 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2433 Inner = AddRec->getStart();
2435 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
2436 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Delta))
2437 // If the coefficient is the product of a constant and other stuff,
2438 // we can use the constant in the GCD computation.
2439 Constant = getConstantPart(Product);
2440 else if (isa<SCEVConstant>(Delta))
2441 Constant = cast<SCEVConstant>(Delta);
2443 // The difference of the two coefficients might not be a product
2444 // or constant, in which case we give up on this direction.
2447 APInt ConstCoeff = Constant->getAPInt();
2448 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2449 DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
2450 if (RunningGCD != 0) {
2451 Remainder = ConstDelta.srem(RunningGCD);
2452 DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
2453 if (Remainder != 0) {
2454 unsigned Level = mapSrcLoop(CurLoop);
2455 Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
2462 DEBUG(dbgs() << "all done\n");
2467 //===----------------------------------------------------------------------===//
2468 // banerjeeMIVtest -
2469 // Use Banerjee's Inequalities to test an MIV subscript pair.
2470 // (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2471 // Generally follows the discussion in Section 2.5.2 of
2473 // Optimizing Supercompilers for Supercomputers
2476 // The inequalities given on page 25 are simplified in that loops are
2477 // normalized so that the lower bound is always 0 and the stride is always 1.
2478 // For example, Wolfe gives
2480 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2482 // where A_k is the coefficient of the kth index in the source subscript,
2483 // B_k is the coefficient of the kth index in the destination subscript,
2484 // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2485 // index, and N_k is the stride of the kth index. Since all loops are normalized
2486 // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2489 // LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2490 // = (A^-_k - B_k)^- (U_k - 1) - B_k
2492 // Similar simplifications are possible for the other equations.
2494 // When we can't determine the number of iterations for a loop,
2495 // we use NULL as an indicator for the worst case, infinity.
2496 // When computing the upper bound, NULL denotes +inf;
2497 // for the lower bound, NULL denotes -inf.
2499 // Return true if dependence disproved.
2500 bool DependenceAnalysis::banerjeeMIVtest(const SCEV *Src,
2502 const SmallBitVector &Loops,
2503 FullDependence &Result) const {
2504 DEBUG(dbgs() << "starting Banerjee\n");
2505 ++BanerjeeApplications;
2506 DEBUG(dbgs() << " Src = " << *Src << '\n');
2508 CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
2509 DEBUG(dbgs() << " Dst = " << *Dst << '\n');
2511 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2512 BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
2513 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2514 DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2516 // Compute bounds for all the * directions.
2517 DEBUG(dbgs() << "\tBounds[*]\n");
2518 for (unsigned K = 1; K <= MaxLevels; ++K) {
2519 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2520 Bound[K].Direction = Dependence::DVEntry::ALL;
2521 Bound[K].DirSet = Dependence::DVEntry::NONE;
2522 findBoundsALL(A, B, Bound, K);
2524 DEBUG(dbgs() << "\t " << K << '\t');
2525 if (Bound[K].Lower[Dependence::DVEntry::ALL])
2526 DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
2528 DEBUG(dbgs() << "-inf\t");
2529 if (Bound[K].Upper[Dependence::DVEntry::ALL])
2530 DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
2532 DEBUG(dbgs() << "+inf\n");
2536 // Test the *, *, *, ... case.
2537 bool Disproved = false;
2538 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2539 // Explore the direction vector hierarchy.
2540 unsigned DepthExpanded = 0;
2541 unsigned NewDeps = exploreDirections(1, A, B, Bound,
2542 Loops, DepthExpanded, Delta);
2544 bool Improved = false;
2545 for (unsigned K = 1; K <= CommonLevels; ++K) {
2547 unsigned Old = Result.DV[K - 1].Direction;
2548 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2549 Improved |= Old != Result.DV[K - 1].Direction;
2550 if (!Result.DV[K - 1].Direction) {
2558 ++BanerjeeSuccesses;
2561 ++BanerjeeIndependence;
2566 ++BanerjeeIndependence;
2576 // Hierarchically expands the direction vector
2577 // search space, combining the directions of discovered dependences
2578 // in the DirSet field of Bound. Returns the number of distinct
2579 // dependences discovered. If the dependence is disproved,
2580 // it will return 0.
2581 unsigned DependenceAnalysis::exploreDirections(unsigned Level,
2585 const SmallBitVector &Loops,
2586 unsigned &DepthExpanded,
2587 const SCEV *Delta) const {
2588 if (Level > CommonLevels) {
2590 DEBUG(dbgs() << "\t[");
2591 for (unsigned K = 1; K <= CommonLevels; ++K) {
2593 Bound[K].DirSet |= Bound[K].Direction;
2595 switch (Bound[K].Direction) {
2596 case Dependence::DVEntry::LT:
2597 DEBUG(dbgs() << " <");
2599 case Dependence::DVEntry::EQ:
2600 DEBUG(dbgs() << " =");
2602 case Dependence::DVEntry::GT:
2603 DEBUG(dbgs() << " >");
2605 case Dependence::DVEntry::ALL:
2606 DEBUG(dbgs() << " *");
2609 llvm_unreachable("unexpected Bound[K].Direction");
2614 DEBUG(dbgs() << " ]\n");
2618 if (Level > DepthExpanded) {
2619 DepthExpanded = Level;
2620 // compute bounds for <, =, > at current level
2621 findBoundsLT(A, B, Bound, Level);
2622 findBoundsGT(A, B, Bound, Level);
2623 findBoundsEQ(A, B, Bound, Level);
2625 DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2626 DEBUG(dbgs() << "\t <\t");
2627 if (Bound[Level].Lower[Dependence::DVEntry::LT])
2628 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT] << '\t');
2630 DEBUG(dbgs() << "-inf\t");
2631 if (Bound[Level].Upper[Dependence::DVEntry::LT])
2632 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT] << '\n');
2634 DEBUG(dbgs() << "+inf\n");
2635 DEBUG(dbgs() << "\t =\t");
2636 if (Bound[Level].Lower[Dependence::DVEntry::EQ])
2637 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ] << '\t');
2639 DEBUG(dbgs() << "-inf\t");
2640 if (Bound[Level].Upper[Dependence::DVEntry::EQ])
2641 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ] << '\n');
2643 DEBUG(dbgs() << "+inf\n");
2644 DEBUG(dbgs() << "\t >\t");
2645 if (Bound[Level].Lower[Dependence::DVEntry::GT])
2646 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT] << '\t');
2648 DEBUG(dbgs() << "-inf\t");
2649 if (Bound[Level].Upper[Dependence::DVEntry::GT])
2650 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT] << '\n');
2652 DEBUG(dbgs() << "+inf\n");
2656 unsigned NewDeps = 0;
2658 // test bounds for <, *, *, ...
2659 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2660 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2661 Loops, DepthExpanded, Delta);
2663 // Test bounds for =, *, *, ...
2664 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2665 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2666 Loops, DepthExpanded, Delta);
2668 // test bounds for >, *, *, ...
2669 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2670 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2671 Loops, DepthExpanded, Delta);
2673 Bound[Level].Direction = Dependence::DVEntry::ALL;
2677 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
2681 // Returns true iff the current bounds are plausible.
2682 bool DependenceAnalysis::testBounds(unsigned char DirKind,
2685 const SCEV *Delta) const {
2686 Bound[Level].Direction = DirKind;
2687 if (const SCEV *LowerBound = getLowerBound(Bound))
2688 if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2690 if (const SCEV *UpperBound = getUpperBound(Bound))
2691 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2697 // Computes the upper and lower bounds for level K
2698 // using the * direction. Records them in Bound.
2699 // Wolfe gives the equations
2701 // LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2702 // UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2704 // Since we normalize loops, we can simplify these equations to
2706 // LB^*_k = (A^-_k - B^+_k)U_k
2707 // UB^*_k = (A^+_k - B^-_k)U_k
2709 // We must be careful to handle the case where the upper bound is unknown.
2710 // Note that the lower bound is always <= 0
2711 // and the upper bound is always >= 0.
2712 void DependenceAnalysis::findBoundsALL(CoefficientInfo *A,
2716 Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
2717 Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
2718 if (Bound[K].Iterations) {
2719 Bound[K].Lower[Dependence::DVEntry::ALL] =
2720 SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
2721 Bound[K].Iterations);
2722 Bound[K].Upper[Dependence::DVEntry::ALL] =
2723 SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
2724 Bound[K].Iterations);
2727 // If the difference is 0, we won't need to know the number of iterations.
2728 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2729 Bound[K].Lower[Dependence::DVEntry::ALL] =
2730 SE->getZero(A[K].Coeff->getType());
2731 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2732 Bound[K].Upper[Dependence::DVEntry::ALL] =
2733 SE->getZero(A[K].Coeff->getType());
2738 // Computes the upper and lower bounds for level K
2739 // using the = direction. Records them in Bound.
2740 // Wolfe gives the equations
2742 // LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2743 // UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2745 // Since we normalize loops, we can simplify these equations to
2747 // LB^=_k = (A_k - B_k)^- U_k
2748 // UB^=_k = (A_k - B_k)^+ U_k
2750 // We must be careful to handle the case where the upper bound is unknown.
2751 // Note that the lower bound is always <= 0
2752 // and the upper bound is always >= 0.
2753 void DependenceAnalysis::findBoundsEQ(CoefficientInfo *A,
2757 Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
2758 Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
2759 if (Bound[K].Iterations) {
2760 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2761 const SCEV *NegativePart = getNegativePart(Delta);
2762 Bound[K].Lower[Dependence::DVEntry::EQ] =
2763 SE->getMulExpr(NegativePart, Bound[K].Iterations);
2764 const SCEV *PositivePart = getPositivePart(Delta);
2765 Bound[K].Upper[Dependence::DVEntry::EQ] =
2766 SE->getMulExpr(PositivePart, Bound[K].Iterations);
2769 // If the positive/negative part of the difference is 0,
2770 // we won't need to know the number of iterations.
2771 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2772 const SCEV *NegativePart = getNegativePart(Delta);
2773 if (NegativePart->isZero())
2774 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2775 const SCEV *PositivePart = getPositivePart(Delta);
2776 if (PositivePart->isZero())
2777 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2782 // Computes the upper and lower bounds for level K
2783 // using the < direction. Records them in Bound.
2784 // Wolfe gives the equations
2786 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2787 // UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2789 // Since we normalize loops, we can simplify these equations to
2791 // LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2792 // UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2794 // We must be careful to handle the case where the upper bound is unknown.
2795 void DependenceAnalysis::findBoundsLT(CoefficientInfo *A,
2799 Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
2800 Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
2801 if (Bound[K].Iterations) {
2802 const SCEV *Iter_1 = SE->getMinusSCEV(
2803 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2804 const SCEV *NegPart =
2805 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2806 Bound[K].Lower[Dependence::DVEntry::LT] =
2807 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2808 const SCEV *PosPart =
2809 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2810 Bound[K].Upper[Dependence::DVEntry::LT] =
2811 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2814 // If the positive/negative part of the difference is 0,
2815 // we won't need to know the number of iterations.
2816 const SCEV *NegPart =
2817 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2818 if (NegPart->isZero())
2819 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2820 const SCEV *PosPart =
2821 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2822 if (PosPart->isZero())
2823 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2828 // Computes the upper and lower bounds for level K
2829 // using the > direction. Records them in Bound.
2830 // Wolfe gives the equations
2832 // LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2833 // UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2835 // Since we normalize loops, we can simplify these equations to
2837 // LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2838 // UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2840 // We must be careful to handle the case where the upper bound is unknown.
2841 void DependenceAnalysis::findBoundsGT(CoefficientInfo *A,
2845 Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
2846 Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
2847 if (Bound[K].Iterations) {
2848 const SCEV *Iter_1 = SE->getMinusSCEV(
2849 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2850 const SCEV *NegPart =
2851 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2852 Bound[K].Lower[Dependence::DVEntry::GT] =
2853 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2854 const SCEV *PosPart =
2855 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2856 Bound[K].Upper[Dependence::DVEntry::GT] =
2857 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2860 // If the positive/negative part of the difference is 0,
2861 // we won't need to know the number of iterations.
2862 const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2863 if (NegPart->isZero())
2864 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2865 const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2866 if (PosPart->isZero())
2867 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2873 const SCEV *DependenceAnalysis::getPositivePart(const SCEV *X) const {
2874 return SE->getSMaxExpr(X, SE->getZero(X->getType()));
2879 const SCEV *DependenceAnalysis::getNegativePart(const SCEV *X) const {
2880 return SE->getSMinExpr(X, SE->getZero(X->getType()));
2884 // Walks through the subscript,
2885 // collecting each coefficient, the associated loop bounds,
2886 // and recording its positive and negative parts for later use.
2887 DependenceAnalysis::CoefficientInfo *
2888 DependenceAnalysis::collectCoeffInfo(const SCEV *Subscript,
2890 const SCEV *&Constant) const {
2891 const SCEV *Zero = SE->getZero(Subscript->getType());
2892 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
2893 for (unsigned K = 1; K <= MaxLevels; ++K) {
2895 CI[K].PosPart = Zero;
2896 CI[K].NegPart = Zero;
2897 CI[K].Iterations = nullptr;
2899 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2900 const Loop *L = AddRec->getLoop();
2901 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2902 CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2903 CI[K].PosPart = getPositivePart(CI[K].Coeff);
2904 CI[K].NegPart = getNegativePart(CI[K].Coeff);
2905 CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2906 Subscript = AddRec->getStart();
2908 Constant = Subscript;
2910 DEBUG(dbgs() << "\tCoefficient Info\n");
2911 for (unsigned K = 1; K <= MaxLevels; ++K) {
2912 DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
2913 DEBUG(dbgs() << "\tPos Part = ");
2914 DEBUG(dbgs() << *CI[K].PosPart);
2915 DEBUG(dbgs() << "\tNeg Part = ");
2916 DEBUG(dbgs() << *CI[K].NegPart);
2917 DEBUG(dbgs() << "\tUpper Bound = ");
2918 if (CI[K].Iterations)
2919 DEBUG(dbgs() << *CI[K].Iterations);
2921 DEBUG(dbgs() << "+inf");
2922 DEBUG(dbgs() << '\n');
2924 DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
2930 // Looks through all the bounds info and
2931 // computes the lower bound given the current direction settings
2932 // at each level. If the lower bound for any level is -inf,
2933 // the result is -inf.
2934 const SCEV *DependenceAnalysis::getLowerBound(BoundInfo *Bound) const {
2935 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2936 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2937 if (Bound[K].Lower[Bound[K].Direction])
2938 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2946 // Looks through all the bounds info and
2947 // computes the upper bound given the current direction settings
2948 // at each level. If the upper bound at any level is +inf,
2949 // the result is +inf.
2950 const SCEV *DependenceAnalysis::getUpperBound(BoundInfo *Bound) const {
2951 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2952 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2953 if (Bound[K].Upper[Bound[K].Direction])
2954 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2962 //===----------------------------------------------------------------------===//
2963 // Constraint manipulation for Delta test.
2965 // Given a linear SCEV,
2966 // return the coefficient (the step)
2967 // corresponding to the specified loop.
2968 // If there isn't one, return 0.
2969 // For example, given a*i + b*j + c*k, finding the coefficient
2970 // corresponding to the j loop would yield b.
2971 const SCEV *DependenceAnalysis::findCoefficient(const SCEV *Expr,
2972 const Loop *TargetLoop) const {
2973 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2975 return SE->getZero(Expr->getType());
2976 if (AddRec->getLoop() == TargetLoop)
2977 return AddRec->getStepRecurrence(*SE);
2978 return findCoefficient(AddRec->getStart(), TargetLoop);
2982 // Given a linear SCEV,
2983 // return the SCEV given by zeroing out the coefficient
2984 // corresponding to the specified loop.
2985 // For example, given a*i + b*j + c*k, zeroing the coefficient
2986 // corresponding to the j loop would yield a*i + c*k.
2987 const SCEV *DependenceAnalysis::zeroCoefficient(const SCEV *Expr,
2988 const Loop *TargetLoop) const {
2989 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2991 return Expr; // ignore
2992 if (AddRec->getLoop() == TargetLoop)
2993 return AddRec->getStart();
2994 return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
2995 AddRec->getStepRecurrence(*SE),
2997 AddRec->getNoWrapFlags());
3001 // Given a linear SCEV Expr,
3002 // return the SCEV given by adding some Value to the
3003 // coefficient corresponding to the specified TargetLoop.
3004 // For example, given a*i + b*j + c*k, adding 1 to the coefficient
3005 // corresponding to the j loop would yield a*i + (b+1)*j + c*k.
3006 const SCEV *DependenceAnalysis::addToCoefficient(const SCEV *Expr,
3007 const Loop *TargetLoop,
3008 const SCEV *Value) const {
3009 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
3010 if (!AddRec) // create a new addRec
3011 return SE->getAddRecExpr(Expr,
3014 SCEV::FlagAnyWrap); // Worst case, with no info.
3015 if (AddRec->getLoop() == TargetLoop) {
3016 const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
3018 return AddRec->getStart();
3019 return SE->getAddRecExpr(AddRec->getStart(),
3022 AddRec->getNoWrapFlags());
3024 if (SE->isLoopInvariant(AddRec, TargetLoop))
3025 return SE->getAddRecExpr(AddRec, Value, TargetLoop, SCEV::FlagAnyWrap);
3026 return SE->getAddRecExpr(
3027 addToCoefficient(AddRec->getStart(), TargetLoop, Value),
3028 AddRec->getStepRecurrence(*SE), AddRec->getLoop(),
3029 AddRec->getNoWrapFlags());
3033 // Review the constraints, looking for opportunities
3034 // to simplify a subscript pair (Src and Dst).
3035 // Return true if some simplification occurs.
3036 // If the simplification isn't exact (that is, if it is conservative
3037 // in terms of dependence), set consistent to false.
3038 // Corresponds to Figure 5 from the paper
3040 // Practical Dependence Testing
3041 // Goff, Kennedy, Tseng
3043 bool DependenceAnalysis::propagate(const SCEV *&Src,
3045 SmallBitVector &Loops,
3046 SmallVectorImpl<Constraint> &Constraints,
3048 bool Result = false;
3049 for (int LI = Loops.find_first(); LI >= 0; LI = Loops.find_next(LI)) {
3050 DEBUG(dbgs() << "\t Constraint[" << LI << "] is");
3051 DEBUG(Constraints[LI].dump(dbgs()));
3052 if (Constraints[LI].isDistance())
3053 Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
3054 else if (Constraints[LI].isLine())
3055 Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
3056 else if (Constraints[LI].isPoint())
3057 Result |= propagatePoint(Src, Dst, Constraints[LI]);
3063 // Attempt to propagate a distance
3064 // constraint into a subscript pair (Src and Dst).
3065 // Return true if some simplification occurs.
3066 // If the simplification isn't exact (that is, if it is conservative
3067 // in terms of dependence), set consistent to false.
3068 bool DependenceAnalysis::propagateDistance(const SCEV *&Src,
3070 Constraint &CurConstraint,
3072 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3073 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3074 const SCEV *A_K = findCoefficient(Src, CurLoop);
3077 const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
3078 Src = SE->getMinusSCEV(Src, DA_K);
3079 Src = zeroCoefficient(Src, CurLoop);
3080 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3081 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3082 Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
3083 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3084 if (!findCoefficient(Dst, CurLoop)->isZero())
3090 // Attempt to propagate a line
3091 // constraint into a subscript pair (Src and Dst).
3092 // Return true if some simplification occurs.
3093 // If the simplification isn't exact (that is, if it is conservative
3094 // in terms of dependence), set consistent to false.
3095 bool DependenceAnalysis::propagateLine(const SCEV *&Src,
3097 Constraint &CurConstraint,
3099 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3100 const SCEV *A = CurConstraint.getA();
3101 const SCEV *B = CurConstraint.getB();
3102 const SCEV *C = CurConstraint.getC();
3103 DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C << "\n");
3104 DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
3105 DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
3107 const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
3108 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3109 if (!Bconst || !Cconst) return false;
3110 APInt Beta = Bconst->getAPInt();
3111 APInt Charlie = Cconst->getAPInt();
3112 APInt CdivB = Charlie.sdiv(Beta);
3113 assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
3114 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3115 // Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3116 Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3117 Dst = zeroCoefficient(Dst, CurLoop);
3118 if (!findCoefficient(Src, CurLoop)->isZero())
3121 else if (B->isZero()) {
3122 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3123 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3124 if (!Aconst || !Cconst) return false;
3125 APInt Alpha = Aconst->getAPInt();
3126 APInt Charlie = Cconst->getAPInt();
3127 APInt CdivA = Charlie.sdiv(Alpha);
3128 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3129 const SCEV *A_K = findCoefficient(Src, CurLoop);
3130 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3131 Src = zeroCoefficient(Src, CurLoop);
3132 if (!findCoefficient(Dst, CurLoop)->isZero())
3135 else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
3136 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3137 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3138 if (!Aconst || !Cconst) return false;
3139 APInt Alpha = Aconst->getAPInt();
3140 APInt Charlie = Cconst->getAPInt();
3141 APInt CdivA = Charlie.sdiv(Alpha);
3142 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3143 const SCEV *A_K = findCoefficient(Src, CurLoop);
3144 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3145 Src = zeroCoefficient(Src, CurLoop);
3146 Dst = addToCoefficient(Dst, CurLoop, A_K);
3147 if (!findCoefficient(Dst, CurLoop)->isZero())
3151 // paper is incorrect here, or perhaps just misleading
3152 const SCEV *A_K = findCoefficient(Src, CurLoop);
3153 Src = SE->getMulExpr(Src, A);
3154 Dst = SE->getMulExpr(Dst, A);
3155 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
3156 Src = zeroCoefficient(Src, CurLoop);
3157 Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
3158 if (!findCoefficient(Dst, CurLoop)->isZero())
3161 DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
3162 DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
3167 // Attempt to propagate a point
3168 // constraint into a subscript pair (Src and Dst).
3169 // Return true if some simplification occurs.
3170 bool DependenceAnalysis::propagatePoint(const SCEV *&Src,
3172 Constraint &CurConstraint) {
3173 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3174 const SCEV *A_K = findCoefficient(Src, CurLoop);
3175 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3176 const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
3177 const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
3178 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3179 Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
3180 Src = zeroCoefficient(Src, CurLoop);
3181 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3182 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3183 Dst = zeroCoefficient(Dst, CurLoop);
3184 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3189 // Update direction vector entry based on the current constraint.
3190 void DependenceAnalysis::updateDirection(Dependence::DVEntry &Level,
3191 const Constraint &CurConstraint
3193 DEBUG(dbgs() << "\tUpdate direction, constraint =");
3194 DEBUG(CurConstraint.dump(dbgs()));
3195 if (CurConstraint.isAny())
3197 else if (CurConstraint.isDistance()) {
3198 // this one is consistent, the others aren't
3199 Level.Scalar = false;
3200 Level.Distance = CurConstraint.getD();
3201 unsigned NewDirection = Dependence::DVEntry::NONE;
3202 if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
3203 NewDirection = Dependence::DVEntry::EQ;
3204 if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
3205 NewDirection |= Dependence::DVEntry::LT;
3206 if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
3207 NewDirection |= Dependence::DVEntry::GT;
3208 Level.Direction &= NewDirection;
3210 else if (CurConstraint.isLine()) {
3211 Level.Scalar = false;
3212 Level.Distance = nullptr;
3213 // direction should be accurate
3215 else if (CurConstraint.isPoint()) {
3216 Level.Scalar = false;
3217 Level.Distance = nullptr;
3218 unsigned NewDirection = Dependence::DVEntry::NONE;
3219 if (!isKnownPredicate(CmpInst::ICMP_NE,
3220 CurConstraint.getY(),
3221 CurConstraint.getX()))
3223 NewDirection |= Dependence::DVEntry::EQ;
3224 if (!isKnownPredicate(CmpInst::ICMP_SLE,
3225 CurConstraint.getY(),
3226 CurConstraint.getX()))
3228 NewDirection |= Dependence::DVEntry::LT;
3229 if (!isKnownPredicate(CmpInst::ICMP_SGE,
3230 CurConstraint.getY(),
3231 CurConstraint.getX()))
3233 NewDirection |= Dependence::DVEntry::GT;
3234 Level.Direction &= NewDirection;
3237 llvm_unreachable("constraint has unexpected kind");
3240 /// Check if we can delinearize the subscripts. If the SCEVs representing the
3241 /// source and destination array references are recurrences on a nested loop,
3242 /// this function flattens the nested recurrences into separate recurrences
3243 /// for each loop level.
3244 bool DependenceAnalysis::tryDelinearize(Instruction *Src,
3246 SmallVectorImpl<Subscript> &Pair)
3248 Value *SrcPtr = getPointerOperand(Src);
3249 Value *DstPtr = getPointerOperand(Dst);
3251 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3252 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3254 // Below code mimics the code in Delinearization.cpp
3255 const SCEV *SrcAccessFn =
3256 SE->getSCEVAtScope(SrcPtr, SrcLoop);
3257 const SCEV *DstAccessFn =
3258 SE->getSCEVAtScope(DstPtr, DstLoop);
3260 const SCEVUnknown *SrcBase =
3261 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3262 const SCEVUnknown *DstBase =
3263 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3265 if (!SrcBase || !DstBase || SrcBase != DstBase)
3268 const SCEV *ElementSize = SE->getElementSize(Src);
3269 if (ElementSize != SE->getElementSize(Dst))
3272 const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
3273 const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
3275 const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
3276 const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
3277 if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
3280 // First step: collect parametric terms in both array references.
3281 SmallVector<const SCEV *, 4> Terms;
3282 SE->collectParametricTerms(SrcAR, Terms);
3283 SE->collectParametricTerms(DstAR, Terms);
3285 // Second step: find subscript sizes.
3286 SmallVector<const SCEV *, 4> Sizes;
3287 SE->findArrayDimensions(Terms, Sizes, ElementSize);
3289 // Third step: compute the access functions for each subscript.
3290 SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
3291 SE->computeAccessFunctions(SrcAR, SrcSubscripts, Sizes);
3292 SE->computeAccessFunctions(DstAR, DstSubscripts, Sizes);
3294 // Fail when there is only a subscript: that's a linearized access function.
3295 if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
3296 SrcSubscripts.size() != DstSubscripts.size())
3299 int size = SrcSubscripts.size();
3302 dbgs() << "\nSrcSubscripts: ";
3303 for (int i = 0; i < size; i++)
3304 dbgs() << *SrcSubscripts[i];
3305 dbgs() << "\nDstSubscripts: ";
3306 for (int i = 0; i < size; i++)
3307 dbgs() << *DstSubscripts[i];
3310 // The delinearization transforms a single-subscript MIV dependence test into
3311 // a multi-subscript SIV dependence test that is easier to compute. So we
3312 // resize Pair to contain as many pairs of subscripts as the delinearization
3313 // has found, and then initialize the pairs following the delinearization.
3315 for (int i = 0; i < size; ++i) {
3316 Pair[i].Src = SrcSubscripts[i];
3317 Pair[i].Dst = DstSubscripts[i];
3318 unifySubscriptType(&Pair[i]);
3320 // FIXME: we should record the bounds SrcSizes[i] and DstSizes[i] that the
3321 // delinearization has found, and add these constraints to the dependence
3322 // check to avoid memory accesses overflow from one dimension into another.
3323 // This is related to the problem of determining the existence of data
3324 // dependences in array accesses using a different number of subscripts: in
3325 // C one can access an array A[100][100]; as A[0][9999], *A[9999], etc.
3331 //===----------------------------------------------------------------------===//
3334 // For debugging purposes, dump a small bit vector to dbgs().
3335 static void dumpSmallBitVector(SmallBitVector &BV) {
3337 for (int VI = BV.find_first(); VI >= 0; VI = BV.find_next(VI)) {
3339 if (BV.find_next(VI) >= 0)
3347 // Returns NULL if there is no dependence.
3348 // Otherwise, return a Dependence with as many details as possible.
3349 // Corresponds to Section 3.1 in the paper
3351 // Practical Dependence Testing
3352 // Goff, Kennedy, Tseng
3355 // Care is required to keep the routine below, getSplitIteration(),
3356 // up to date with respect to this routine.
3357 std::unique_ptr<Dependence>
3358 DependenceAnalysis::depends(Instruction *Src, Instruction *Dst,
3359 bool PossiblyLoopIndependent) {
3361 PossiblyLoopIndependent = false;
3363 if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
3364 (!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
3365 // if both instructions don't reference memory, there's no dependence
3368 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
3369 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
3370 DEBUG(dbgs() << "can only handle simple loads and stores\n");
3371 return make_unique<Dependence>(Src, Dst);