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
28 // differentiate subscripts. Since Clang linearizes subscripts
29 // for most arrays, we give up some precision (though the existing MIV tests
30 // will help). We trust that the GEP instruction will eventually be extended.
31 // In the meantime, we should explore Maslov's ideas about delinearization.
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 #define DEBUG_TYPE "da"
56 #include "llvm/Analysis/DependenceAnalysis.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/Operator.h"
59 #include "llvm/Analysis/AliasAnalysis.h"
60 #include "llvm/Analysis/LoopInfo.h"
61 #include "llvm/Analysis/ValueTracking.h"
62 #include "llvm/Analysis/ScalarEvolution.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/InstIterator.h"
67 #include "llvm/Support/raw_ostream.h"
71 //===----------------------------------------------------------------------===//
74 STATISTIC(TotalArrayPairs, "Array pairs tested");
75 STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
76 STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
77 STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
78 STATISTIC(ZIVapplications, "ZIV applications");
79 STATISTIC(ZIVindependence, "ZIV independence");
80 STATISTIC(StrongSIVapplications, "Strong SIV applications");
81 STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
82 STATISTIC(StrongSIVindependence, "Strong SIV independence");
83 STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
84 STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
85 STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
86 STATISTIC(ExactSIVapplications, "Exact SIV applications");
87 STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
88 STATISTIC(ExactSIVindependence, "Exact SIV independence");
89 STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
90 STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
91 STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
92 STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
93 STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
94 STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
95 STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
96 STATISTIC(DeltaApplications, "Delta applications");
97 STATISTIC(DeltaSuccesses, "Delta successes");
98 STATISTIC(DeltaIndependence, "Delta independence");
99 STATISTIC(DeltaPropagations, "Delta propagations");
100 STATISTIC(GCDapplications, "GCD applications");
101 STATISTIC(GCDsuccesses, "GCD successes");
102 STATISTIC(GCDindependence, "GCD independence");
103 STATISTIC(BanerjeeApplications, "Banerjee applications");
104 STATISTIC(BanerjeeIndependence, "Banerjee independence");
105 STATISTIC(BanerjeeSuccesses, "Banerjee successes");
107 //===----------------------------------------------------------------------===//
110 INITIALIZE_PASS_BEGIN(DependenceAnalysis, "da",
111 "Dependence Analysis", true, true)
112 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
113 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
114 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
115 INITIALIZE_PASS_END(DependenceAnalysis, "da",
116 "Dependence Analysis", true, true)
118 char DependenceAnalysis::ID = 0;
121 FunctionPass *llvm::createDependenceAnalysisPass() {
122 return new DependenceAnalysis();
126 bool DependenceAnalysis::runOnFunction(Function &F) {
128 AA = &getAnalysis<AliasAnalysis>();
129 SE = &getAnalysis<ScalarEvolution>();
130 LI = &getAnalysis<LoopInfo>();
135 void DependenceAnalysis::releaseMemory() {
139 void DependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
140 AU.setPreservesAll();
141 AU.addRequiredTransitive<AliasAnalysis>();
142 AU.addRequiredTransitive<ScalarEvolution>();
143 AU.addRequiredTransitive<LoopInfo>();
147 // Used to test the dependence analyzer.
148 // Looks through the function, noting the first store instruction
149 // and the first load instruction
150 // (which always follows the first load in our tests).
151 // Calls depends() and prints out the result.
152 // Ignores all other instructions.
154 void dumpExampleDependence(raw_ostream &OS, Function *F,
155 DependenceAnalysis *DA) {
156 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F);
157 SrcI != SrcE; ++SrcI) {
158 if (const StoreInst *Src = dyn_cast<StoreInst>(&*SrcI)) {
159 for (inst_iterator DstI = SrcI, DstE = inst_end(F);
160 DstI != DstE; ++DstI) {
161 if (const LoadInst *Dst = dyn_cast<LoadInst>(&*DstI)) {
162 OS << "da analyze - ";
163 if (Dependence *D = DA->depends(Src, Dst, true)) {
165 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
166 if (D->isSplitable(Level)) {
167 OS << "da analyze - split level = " << Level;
168 OS << ", iteration = " << *DA->getSplitIteration(D, Level);
184 void DependenceAnalysis::print(raw_ostream &OS, const Module*) const {
185 dumpExampleDependence(OS, F, const_cast<DependenceAnalysis *>(this));
188 //===----------------------------------------------------------------------===//
189 // Dependence methods
191 // Returns true if this is an input dependence.
192 bool Dependence::isInput() const {
193 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
197 // Returns true if this is an output dependence.
198 bool Dependence::isOutput() const {
199 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
203 // Returns true if this is an flow (aka true) dependence.
204 bool Dependence::isFlow() const {
205 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
209 // Returns true if this is an anti dependence.
210 bool Dependence::isAnti() const {
211 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
215 // Returns true if a particular level is scalar; that is,
216 // if no subscript in the source or destination mention the induction
217 // variable associated with the loop at this level.
218 // Leave this out of line, so it will serve as a virtual method anchor
219 bool Dependence::isScalar(unsigned level) const {
224 //===----------------------------------------------------------------------===//
225 // FullDependence methods
227 FullDependence::FullDependence(const Instruction *Source,
228 const Instruction *Destination,
229 bool PossiblyLoopIndependent,
230 unsigned CommonLevels) :
231 Dependence(Source, Destination),
232 Levels(CommonLevels),
233 LoopIndependent(PossiblyLoopIndependent) {
235 DV = CommonLevels ? new DVEntry[CommonLevels] : NULL;
238 // The rest are simple getters that hide the implementation.
240 // getDirection - Returns the direction associated with a particular level.
241 unsigned FullDependence::getDirection(unsigned Level) const {
242 assert(0 < Level && Level <= Levels && "Level out of range");
243 return DV[Level - 1].Direction;
247 // Returns the distance (or NULL) associated with a particular level.
248 const SCEV *FullDependence::getDistance(unsigned Level) const {
249 assert(0 < Level && Level <= Levels && "Level out of range");
250 return DV[Level - 1].Distance;
254 // Returns true if a particular level is scalar; that is,
255 // if no subscript in the source or destination mention the induction
256 // variable associated with the loop at this level.
257 bool FullDependence::isScalar(unsigned Level) const {
258 assert(0 < Level && Level <= Levels && "Level out of range");
259 return DV[Level - 1].Scalar;
263 // Returns true if peeling the first iteration from this loop
264 // will break this dependence.
265 bool FullDependence::isPeelFirst(unsigned Level) const {
266 assert(0 < Level && Level <= Levels && "Level out of range");
267 return DV[Level - 1].PeelFirst;
271 // Returns true if peeling the last iteration from this loop
272 // will break this dependence.
273 bool FullDependence::isPeelLast(unsigned Level) const {
274 assert(0 < Level && Level <= Levels && "Level out of range");
275 return DV[Level - 1].PeelLast;
279 // Returns true if splitting this loop will break the dependence.
280 bool FullDependence::isSplitable(unsigned Level) const {
281 assert(0 < Level && Level <= Levels && "Level out of range");
282 return DV[Level - 1].Splitable;
286 //===----------------------------------------------------------------------===//
287 // DependenceAnalysis::Constraint methods
289 // If constraint is a point <X, Y>, returns X.
291 const SCEV *DependenceAnalysis::Constraint::getX() const {
292 assert(Kind == Point && "Kind should be Point");
297 // If constraint is a point <X, Y>, returns Y.
299 const SCEV *DependenceAnalysis::Constraint::getY() const {
300 assert(Kind == Point && "Kind should be Point");
305 // If constraint is a line AX + BY = C, returns A.
307 const SCEV *DependenceAnalysis::Constraint::getA() const {
308 assert((Kind == Line || Kind == Distance) &&
309 "Kind should be Line (or Distance)");
314 // If constraint is a line AX + BY = C, returns B.
316 const SCEV *DependenceAnalysis::Constraint::getB() const {
317 assert((Kind == Line || Kind == Distance) &&
318 "Kind should be Line (or Distance)");
323 // If constraint is a line AX + BY = C, returns C.
325 const SCEV *DependenceAnalysis::Constraint::getC() const {
326 assert((Kind == Line || Kind == Distance) &&
327 "Kind should be Line (or Distance)");
332 // If constraint is a distance, returns D.
334 const SCEV *DependenceAnalysis::Constraint::getD() const {
335 assert(Kind == Distance && "Kind should be Distance");
336 return SE->getNegativeSCEV(C);
340 // Returns the loop associated with this constraint.
341 const Loop *DependenceAnalysis::Constraint::getAssociatedLoop() const {
342 assert((Kind == Distance || Kind == Line || Kind == Point) &&
343 "Kind should be Distance, Line, or Point");
344 return AssociatedLoop;
348 void DependenceAnalysis::Constraint::setPoint(const SCEV *X,
350 const Loop *CurLoop) {
354 AssociatedLoop = CurLoop;
358 void DependenceAnalysis::Constraint::setLine(const SCEV *AA,
361 const Loop *CurLoop) {
366 AssociatedLoop = CurLoop;
370 void DependenceAnalysis::Constraint::setDistance(const SCEV *D,
371 const Loop *CurLoop) {
373 A = SE->getConstant(D->getType(), 1);
374 B = SE->getNegativeSCEV(A);
375 C = SE->getNegativeSCEV(D);
376 AssociatedLoop = CurLoop;
380 void DependenceAnalysis::Constraint::setEmpty() {
385 void DependenceAnalysis::Constraint::setAny(ScalarEvolution *NewSE) {
391 // For debugging purposes. Dumps the constraint out to OS.
392 void DependenceAnalysis::Constraint::dump(raw_ostream &OS) const {
398 OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
399 else if (isDistance())
400 OS << " Distance is " << *getD() <<
401 " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
403 OS << " Line is " << *getA() << "*X + " <<
404 *getB() << "*Y = " << *getC() << "\n";
406 llvm_unreachable("unknown constraint type in Constraint::dump");
410 // Updates X with the intersection
411 // of the Constraints X and Y. Returns true if X has changed.
412 // Corresponds to Figure 4 from the paper
414 // Practical Dependence Testing
415 // Goff, Kennedy, Tseng
417 bool DependenceAnalysis::intersectConstraints(Constraint *X,
418 const Constraint *Y) {
420 DEBUG(dbgs() << "\tintersect constraints\n");
421 DEBUG(dbgs() << "\t X ="; X->dump(dbgs()));
422 DEBUG(dbgs() << "\t Y ="; Y->dump(dbgs()));
423 assert(!Y->isPoint() && "Y must not be a Point");
437 if (X->isDistance() && Y->isDistance()) {
438 DEBUG(dbgs() << "\t intersect 2 distances\n");
439 if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
441 if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
446 // Hmmm, interesting situation.
447 // I guess if either is constant, keep it and ignore the other.
448 if (isa<SCEVConstant>(Y->getD())) {
455 // At this point, the pseudo-code in Figure 4 of the paper
456 // checks if (X->isPoint() && Y->isPoint()).
457 // This case can't occur in our implementation,
458 // since a Point can only arise as the result of intersecting
459 // two Line constraints, and the right-hand value, Y, is never
460 // the result of an intersection.
461 assert(!(X->isPoint() && Y->isPoint()) &&
462 "We shouldn't ever see X->isPoint() && Y->isPoint()");
464 if (X->isLine() && Y->isLine()) {
465 DEBUG(dbgs() << "\t intersect 2 lines\n");
466 const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
467 const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
468 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
469 // slopes are equal, so lines are parallel
470 DEBUG(dbgs() << "\t\tsame slope\n");
471 Prod1 = SE->getMulExpr(X->getC(), Y->getB());
472 Prod2 = SE->getMulExpr(X->getB(), Y->getC());
473 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
475 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
482 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
483 // slopes differ, so lines intersect
484 DEBUG(dbgs() << "\t\tdifferent slopes\n");
485 const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
486 const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
487 const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
488 const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
489 const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
490 const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
491 const SCEVConstant *C1A2_C2A1 =
492 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
493 const SCEVConstant *C1B2_C2B1 =
494 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
495 const SCEVConstant *A1B2_A2B1 =
496 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
497 const SCEVConstant *A2B1_A1B2 =
498 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
499 if (!C1B2_C2B1 || !C1A2_C2A1 ||
500 !A1B2_A2B1 || !A2B1_A1B2)
502 APInt Xtop = C1B2_C2B1->getValue()->getValue();
503 APInt Xbot = A1B2_A2B1->getValue()->getValue();
504 APInt Ytop = C1A2_C2A1->getValue()->getValue();
505 APInt Ybot = A2B1_A1B2->getValue()->getValue();
506 DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
507 DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
508 DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
509 DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
510 APInt Xq = Xtop; // these need to be initialized, even
511 APInt Xr = Xtop; // though they're just going to be overwritten
512 APInt::sdivrem(Xtop, Xbot, Xq, Xr);
515 APInt::sdivrem(Ytop, Ybot, Yq, Yr);
516 if (Xr != 0 || Yr != 0) {
521 DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
522 if (Xq.slt(0) || Yq.slt(0)) {
527 if (const SCEVConstant *CUB =
528 collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
529 APInt UpperBound = CUB->getValue()->getValue();
530 DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
531 if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
537 X->setPoint(SE->getConstant(Xq),
539 X->getAssociatedLoop());
546 // if (X->isLine() && Y->isPoint()) This case can't occur.
547 assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
549 if (X->isPoint() && Y->isLine()) {
550 DEBUG(dbgs() << "\t intersect Point and Line\n");
551 const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
552 const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
553 const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
554 if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
556 if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
564 llvm_unreachable("shouldn't reach the end of Constraint intersection");
569 //===----------------------------------------------------------------------===//
570 // DependenceAnalysis methods
572 // For debugging purposes. Dumps a dependence to OS.
573 void Dependence::dump(raw_ostream &OS) const {
574 bool Splitable = false;
588 unsigned Levels = getLevels();
591 for (unsigned II = 1; II <= Levels; ++II) {
596 const SCEV *Distance = getDistance(II);
599 else if (isScalar(II))
602 unsigned Direction = getDirection(II);
603 if (Direction == DVEntry::ALL)
606 if (Direction & DVEntry::LT)
608 if (Direction & DVEntry::EQ)
610 if (Direction & DVEntry::GT)
619 if (isLoopIndependent())
632 AliasAnalysis::AliasResult underlyingObjectsAlias(AliasAnalysis *AA,
635 const Value *AObj = GetUnderlyingObject(A);
636 const Value *BObj = GetUnderlyingObject(B);
637 return AA->alias(AObj, AA->getTypeStoreSize(AObj->getType()),
638 BObj, AA->getTypeStoreSize(BObj->getType()));
642 // Returns true if the load or store can be analyzed. Atomic and volatile
643 // operations have properties which this analysis does not understand.
645 bool isLoadOrStore(const Instruction *I) {
646 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
647 return LI->isUnordered();
648 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
649 return SI->isUnordered();
655 const Value *getPointerOperand(const Instruction *I) {
656 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
657 return LI->getPointerOperand();
658 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
659 return SI->getPointerOperand();
660 llvm_unreachable("Value is not load or store instruction");
665 // Examines the loop nesting of the Src and Dst
666 // instructions and establishes their shared loops. Sets the variables
667 // CommonLevels, SrcLevels, and MaxLevels.
668 // The source and destination instructions needn't be contained in the same
669 // loop. The routine establishNestingLevels finds the level of most deeply
670 // nested loop that contains them both, CommonLevels. An instruction that's
671 // not contained in a loop is at level = 0. MaxLevels is equal to the level
672 // of the source plus the level of the destination, minus CommonLevels.
673 // This lets us allocate vectors MaxLevels in length, with room for every
674 // distinct loop referenced in both the source and destination subscripts.
675 // The variable SrcLevels is the nesting depth of the source instruction.
676 // It's used to help calculate distinct loops referenced by the destination.
677 // Here's the map from loops to levels:
679 // 1 - outermost common loop
680 // ... - other common loops
681 // CommonLevels - innermost common loop
682 // ... - loops containing Src but not Dst
683 // SrcLevels - innermost loop containing Src but not Dst
684 // ... - loops containing Dst but not Src
685 // MaxLevels - innermost loops containing Dst but not Src
686 // Consider the follow code fragment:
703 // If we're looking at the possibility of a dependence between the store
704 // to A (the Src) and the load from A (the Dst), we'll note that they
705 // have 2 loops in common, so CommonLevels will equal 2 and the direction
706 // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
707 // A map from loop names to loop numbers would look like
709 // b - 2 = CommonLevels
715 void DependenceAnalysis::establishNestingLevels(const Instruction *Src,
716 const Instruction *Dst) {
717 const BasicBlock *SrcBlock = Src->getParent();
718 const BasicBlock *DstBlock = Dst->getParent();
719 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
720 unsigned DstLevel = LI->getLoopDepth(DstBlock);
721 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
722 const Loop *DstLoop = LI->getLoopFor(DstBlock);
723 SrcLevels = SrcLevel;
724 MaxLevels = SrcLevel + DstLevel;
725 while (SrcLevel > DstLevel) {
726 SrcLoop = SrcLoop->getParentLoop();
729 while (DstLevel > SrcLevel) {
730 DstLoop = DstLoop->getParentLoop();
733 while (SrcLoop != DstLoop) {
734 SrcLoop = SrcLoop->getParentLoop();
735 DstLoop = DstLoop->getParentLoop();
738 CommonLevels = SrcLevel;
739 MaxLevels -= CommonLevels;
743 // Given one of the loops containing the source, return
744 // its level index in our numbering scheme.
745 unsigned DependenceAnalysis::mapSrcLoop(const Loop *SrcLoop) const {
746 return SrcLoop->getLoopDepth();
750 // Given one of the loops containing the destination,
751 // return its level index in our numbering scheme.
752 unsigned DependenceAnalysis::mapDstLoop(const Loop *DstLoop) const {
753 unsigned D = DstLoop->getLoopDepth();
754 if (D > CommonLevels)
755 return D - CommonLevels + SrcLevels;
761 // Returns true if Expression is loop invariant in LoopNest.
762 bool DependenceAnalysis::isLoopInvariant(const SCEV *Expression,
763 const Loop *LoopNest) const {
766 return SE->isLoopInvariant(Expression, LoopNest) &&
767 isLoopInvariant(Expression, LoopNest->getParentLoop());
772 // Finds the set of loops from the LoopNest that
773 // have a level <= CommonLevels and are referred to by the SCEV Expression.
774 void DependenceAnalysis::collectCommonLoops(const SCEV *Expression,
775 const Loop *LoopNest,
776 SmallBitVector &Loops) const {
778 unsigned Level = LoopNest->getLoopDepth();
779 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
781 LoopNest = LoopNest->getParentLoop();
786 // removeMatchingExtensions - Examines a subscript pair.
787 // If the source and destination are identically sign (or zero)
788 // extended, it strips off the extension in an effect to simplify
789 // the actual analysis.
790 void DependenceAnalysis::removeMatchingExtensions(Subscript *Pair) {
791 const SCEV *Src = Pair->Src;
792 const SCEV *Dst = Pair->Dst;
793 if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
794 (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
795 const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src);
796 const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst);
797 if (SrcCast->getType() == DstCast->getType()) {
798 Pair->Src = SrcCast->getOperand();
799 Pair->Dst = DstCast->getOperand();
805 // Examine the scev and return true iff it's linear.
806 // Collect any loops mentioned in the set of "Loops".
807 bool DependenceAnalysis::checkSrcSubscript(const SCEV *Src,
808 const Loop *LoopNest,
809 SmallBitVector &Loops) {
810 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Src);
812 return isLoopInvariant(Src, LoopNest);
813 const SCEV *Start = AddRec->getStart();
814 const SCEV *Step = AddRec->getStepRecurrence(*SE);
815 if (!isLoopInvariant(Step, LoopNest))
817 Loops.set(mapSrcLoop(AddRec->getLoop()));
818 return checkSrcSubscript(Start, LoopNest, Loops);
823 // Examine the scev and return true iff it's linear.
824 // Collect any loops mentioned in the set of "Loops".
825 bool DependenceAnalysis::checkDstSubscript(const SCEV *Dst,
826 const Loop *LoopNest,
827 SmallBitVector &Loops) {
828 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Dst);
830 return isLoopInvariant(Dst, LoopNest);
831 const SCEV *Start = AddRec->getStart();
832 const SCEV *Step = AddRec->getStepRecurrence(*SE);
833 if (!isLoopInvariant(Step, LoopNest))
835 Loops.set(mapDstLoop(AddRec->getLoop()));
836 return checkDstSubscript(Start, LoopNest, Loops);
840 // Examines the subscript pair (the Src and Dst SCEVs)
841 // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
842 // Collects the associated loops in a set.
843 DependenceAnalysis::Subscript::ClassificationKind
844 DependenceAnalysis::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
845 const SCEV *Dst, const Loop *DstLoopNest,
846 SmallBitVector &Loops) {
847 SmallBitVector SrcLoops(MaxLevels + 1);
848 SmallBitVector DstLoops(MaxLevels + 1);
849 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
850 return Subscript::NonLinear;
851 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
852 return Subscript::NonLinear;
855 unsigned N = Loops.count();
857 return Subscript::ZIV;
859 return Subscript::SIV;
860 if (N == 2 && (SrcLoops.count() == 0 ||
861 DstLoops.count() == 0 ||
862 (SrcLoops.count() == 1 && DstLoops.count() == 1)))
863 return Subscript::RDIV;
864 return Subscript::MIV;
868 // A wrapper around SCEV::isKnownPredicate.
869 // Looks for cases where we're interested in comparing for equality.
870 // If both X and Y have been identically sign or zero extended,
871 // it strips off the (confusing) extensions before invoking
872 // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
873 // will be similarly updated.
875 // If SCEV::isKnownPredicate can't prove the predicate,
876 // we try simple subtraction, which seems to help in some cases
877 // involving symbolics.
878 bool DependenceAnalysis::isKnownPredicate(ICmpInst::Predicate Pred,
880 const SCEV *Y) const {
881 if (Pred == CmpInst::ICMP_EQ ||
882 Pred == CmpInst::ICMP_NE) {
883 if ((isa<SCEVSignExtendExpr>(X) &&
884 isa<SCEVSignExtendExpr>(Y)) ||
885 (isa<SCEVZeroExtendExpr>(X) &&
886 isa<SCEVZeroExtendExpr>(Y))) {
887 const SCEVCastExpr *CX = cast<SCEVCastExpr>(X);
888 const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y);
889 const SCEV *Xop = CX->getOperand();
890 const SCEV *Yop = CY->getOperand();
891 if (Xop->getType() == Yop->getType()) {
897 if (SE->isKnownPredicate(Pred, X, Y))
899 // If SE->isKnownPredicate can't prove the condition,
900 // we try the brute-force approach of subtracting
901 // and testing the difference.
902 // By testing with SE->isKnownPredicate first, we avoid
903 // the possibility of overflow when the arguments are constants.
904 const SCEV *Delta = SE->getMinusSCEV(X, Y);
906 case CmpInst::ICMP_EQ:
907 return Delta->isZero();
908 case CmpInst::ICMP_NE:
909 return SE->isKnownNonZero(Delta);
910 case CmpInst::ICMP_SGE:
911 return SE->isKnownNonNegative(Delta);
912 case CmpInst::ICMP_SLE:
913 return SE->isKnownNonPositive(Delta);
914 case CmpInst::ICMP_SGT:
915 return SE->isKnownPositive(Delta);
916 case CmpInst::ICMP_SLT:
917 return SE->isKnownNegative(Delta);
919 llvm_unreachable("unexpected predicate in isKnownPredicate");
924 // All subscripts are all the same type.
925 // Loop bound may be smaller (e.g., a char).
926 // Should zero extend loop bound, since it's always >= 0.
927 // This routine collects upper bound and extends if needed.
928 // Return null if no bound available.
929 const SCEV *DependenceAnalysis::collectUpperBound(const Loop *L,
931 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
932 const SCEV *UB = SE->getBackedgeTakenCount(L);
933 return SE->getNoopOrZeroExtend(UB, T);
939 // Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
940 // If the cast fails, returns NULL.
941 const SCEVConstant *DependenceAnalysis::collectConstantUpperBound(const Loop *L,
944 if (const SCEV *UB = collectUpperBound(L, T))
945 return dyn_cast<SCEVConstant>(UB);
951 // When we have a pair of subscripts of the form [c1] and [c2],
952 // where c1 and c2 are both loop invariant, we attack it using
953 // the ZIV test. Basically, we test by comparing the two values,
954 // but there are actually three possible results:
955 // 1) the values are equal, so there's a dependence
956 // 2) the values are different, so there's no dependence
957 // 3) the values might be equal, so we have to assume a dependence.
959 // Return true if dependence disproved.
960 bool DependenceAnalysis::testZIV(const SCEV *Src,
962 FullDependence &Result) const {
963 DEBUG(dbgs() << " src = " << *Src << "\n");
964 DEBUG(dbgs() << " dst = " << *Dst << "\n");
966 if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
967 DEBUG(dbgs() << " provably dependent\n");
968 return false; // provably dependent
970 if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
971 DEBUG(dbgs() << " provably independent\n");
973 return true; // provably independent
975 DEBUG(dbgs() << " possibly dependent\n");
976 Result.Consistent = false;
977 return false; // possibly dependent
982 // From the paper, Practical Dependence Testing, Section 4.2.1
984 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
985 // where i is an induction variable, c1 and c2 are loop invariant,
986 // and a is a constant, we can solve it exactly using the Strong SIV test.
988 // Can prove independence. Failing that, can compute distance (and direction).
989 // In the presence of symbolic terms, we can sometimes make progress.
991 // If there's a dependence,
993 // c1 + a*i = c2 + a*i'
995 // The dependence distance is
997 // d = i' - i = (c1 - c2)/a
999 // A dependence only exists if d is an integer and abs(d) <= U, where U is the
1000 // loop's upper bound. If a dependence exists, the dependence direction is
1004 // direction = { = if d = 0
1007 // Return true if dependence disproved.
1008 bool DependenceAnalysis::strongSIVtest(const SCEV *Coeff,
1009 const SCEV *SrcConst,
1010 const SCEV *DstConst,
1011 const Loop *CurLoop,
1013 FullDependence &Result,
1014 Constraint &NewConstraint) const {
1015 DEBUG(dbgs() << "\tStrong SIV test\n");
1016 DEBUG(dbgs() << "\t Coeff = " << *Coeff);
1017 DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1018 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
1019 DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1020 DEBUG(dbgs() << "\t DstConst = " << *DstConst);
1021 DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
1022 ++StrongSIVapplications;
1023 assert(0 < Level && Level <= CommonLevels && "level out of range");
1026 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1027 DEBUG(dbgs() << "\t Delta = " << *Delta);
1028 DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
1030 // check that |Delta| < iteration count
1031 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1032 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound);
1033 DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
1034 const SCEV *AbsDelta =
1035 SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
1036 const SCEV *AbsCoeff =
1037 SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
1038 const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
1039 if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
1040 // Distance greater than trip count - no dependence
1041 ++StrongSIVindependence;
1042 ++StrongSIVsuccesses;
1047 // Can we compute distance?
1048 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
1049 APInt ConstDelta = cast<SCEVConstant>(Delta)->getValue()->getValue();
1050 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getValue()->getValue();
1051 APInt Distance = ConstDelta; // these need to be initialized
1052 APInt Remainder = ConstDelta;
1053 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
1054 DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1055 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1056 // Make sure Coeff divides Delta exactly
1057 if (Remainder != 0) {
1058 // Coeff doesn't divide Distance, no dependence
1059 ++StrongSIVindependence;
1060 ++StrongSIVsuccesses;
1063 Result.DV[Level].Distance = SE->getConstant(Distance);
1064 NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
1065 if (Distance.sgt(0))
1066 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1067 else if (Distance.slt(0))
1068 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1070 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1071 ++StrongSIVsuccesses;
1073 else if (Delta->isZero()) {
1075 Result.DV[Level].Distance = Delta;
1076 NewConstraint.setDistance(Delta, CurLoop);
1077 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1078 ++StrongSIVsuccesses;
1081 if (Coeff->isOne()) {
1082 DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
1083 Result.DV[Level].Distance = Delta; // since X/1 == X
1084 NewConstraint.setDistance(Delta, CurLoop);
1087 Result.Consistent = false;
1088 NewConstraint.setLine(Coeff,
1089 SE->getNegativeSCEV(Coeff),
1090 SE->getNegativeSCEV(Delta), CurLoop);
1093 // maybe we can get a useful direction
1094 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
1095 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1096 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1097 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1098 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1099 // The double negatives above are confusing.
1100 // It helps to read !SE->isKnownNonZero(Delta)
1101 // as "Delta might be Zero"
1102 unsigned NewDirection = Dependence::DVEntry::NONE;
1103 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1104 (DeltaMaybeNegative && CoeffMaybeNegative))
1105 NewDirection = Dependence::DVEntry::LT;
1107 NewDirection |= Dependence::DVEntry::EQ;
1108 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1109 (DeltaMaybePositive && CoeffMaybeNegative))
1110 NewDirection |= Dependence::DVEntry::GT;
1111 if (NewDirection < Result.DV[Level].Direction)
1112 ++StrongSIVsuccesses;
1113 Result.DV[Level].Direction &= NewDirection;
1119 // weakCrossingSIVtest -
1120 // From the paper, Practical Dependence Testing, Section 4.2.2
1122 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1123 // where i is an induction variable, c1 and c2 are loop invariant,
1124 // and a is a constant, we can solve it exactly using the
1125 // Weak-Crossing SIV test.
1127 // Given c1 + a*i = c2 - a*i', we can look for the intersection of
1128 // the two lines, where i = i', yielding
1130 // c1 + a*i = c2 - a*i
1134 // If i < 0, there is no dependence.
1135 // If i > upperbound, there is no dependence.
1136 // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1137 // If i = upperbound, there's a dependence with distance = 0.
1138 // If i is integral, there's a dependence (all directions).
1139 // If the non-integer part = 1/2, there's a dependence (<> directions).
1140 // Otherwise, there's no dependence.
1142 // Can prove independence. Failing that,
1143 // can sometimes refine the directions.
1144 // Can determine iteration for splitting.
1146 // Return true if dependence disproved.
1147 bool DependenceAnalysis::weakCrossingSIVtest(const SCEV *Coeff,
1148 const SCEV *SrcConst,
1149 const SCEV *DstConst,
1150 const Loop *CurLoop,
1152 FullDependence &Result,
1153 Constraint &NewConstraint,
1154 const SCEV *&SplitIter) const {
1155 DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1156 DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1157 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1158 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1159 ++WeakCrossingSIVapplications;
1160 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1162 Result.Consistent = false;
1163 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1164 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1165 NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
1166 if (Delta->isZero()) {
1167 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1168 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1169 ++WeakCrossingSIVsuccesses;
1170 if (!Result.DV[Level].Direction) {
1171 ++WeakCrossingSIVindependence;
1174 Result.DV[Level].Distance = Delta; // = 0
1177 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1181 Result.DV[Level].Splitable = true;
1182 if (SE->isKnownNegative(ConstCoeff)) {
1183 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1184 assert(ConstCoeff &&
1185 "dynamic cast of negative of ConstCoeff should yield constant");
1186 Delta = SE->getNegativeSCEV(Delta);
1188 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1190 // compute SplitIter for use by DependenceAnalysis::getSplitIteration()
1192 SE->getUDivExpr(SE->getSMaxExpr(SE->getConstant(Delta->getType(), 0),
1194 SE->getMulExpr(SE->getConstant(Delta->getType(), 2),
1196 DEBUG(dbgs() << "\t Split iter = " << *SplitIter << "\n");
1198 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1202 // We're certain that ConstCoeff > 0; therefore,
1203 // if Delta < 0, then no dependence.
1204 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1205 DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
1206 if (SE->isKnownNegative(Delta)) {
1207 // No dependence, Delta < 0
1208 ++WeakCrossingSIVindependence;
1209 ++WeakCrossingSIVsuccesses;
1213 // We're certain that Delta > 0 and ConstCoeff > 0.
1214 // Check Delta/(2*ConstCoeff) against upper loop bound
1215 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1216 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1217 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1218 const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
1220 DEBUG(dbgs() << "\t ML = " << *ML << "\n");
1221 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1222 // Delta too big, no dependence
1223 ++WeakCrossingSIVindependence;
1224 ++WeakCrossingSIVsuccesses;
1227 if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1229 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1230 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1231 ++WeakCrossingSIVsuccesses;
1232 if (!Result.DV[Level].Direction) {
1233 ++WeakCrossingSIVindependence;
1236 Result.DV[Level].Splitable = false;
1237 Result.DV[Level].Distance = SE->getConstant(Delta->getType(), 0);
1242 // check that Coeff divides Delta
1243 APInt APDelta = ConstDelta->getValue()->getValue();
1244 APInt APCoeff = ConstCoeff->getValue()->getValue();
1245 APInt Distance = APDelta; // these need to be initialzed
1246 APInt Remainder = APDelta;
1247 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1248 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1249 if (Remainder != 0) {
1250 // Coeff doesn't divide Delta, no dependence
1251 ++WeakCrossingSIVindependence;
1252 ++WeakCrossingSIVsuccesses;
1255 DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1257 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1258 APInt Two = APInt(Distance.getBitWidth(), 2, true);
1259 Remainder = Distance.srem(Two);
1260 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1261 if (Remainder != 0) {
1262 // Equal direction isn't possible
1263 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
1264 ++WeakCrossingSIVsuccesses;
1270 // Kirch's algorithm, from
1272 // Optimizing Supercompilers for Supercomputers
1276 // Program 2.1, page 29.
1277 // Computes the GCD of AM and BM.
1278 // Also finds a solution to the equation ax - by = gdc(a, b).
1279 // Returns true iff the gcd divides Delta.
1281 bool findGCD(unsigned Bits, APInt AM, APInt BM, APInt Delta,
1282 APInt &G, APInt &X, APInt &Y) {
1283 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1284 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1285 APInt G0 = AM.abs();
1286 APInt G1 = BM.abs();
1287 APInt Q = G0; // these need to be initialized
1289 APInt::sdivrem(G0, G1, Q, R);
1291 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1292 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1294 APInt::sdivrem(G0, G1, Q, R);
1297 DEBUG(dbgs() << "\t GCD = " << G << "\n");
1298 X = AM.slt(0) ? -A1 : A1;
1299 Y = BM.slt(0) ? B1 : -B1;
1301 // make sure gcd divides Delta
1304 return true; // gcd doesn't divide Delta, no dependence
1313 APInt floorOfQuotient(APInt A, APInt B) {
1314 APInt Q = A; // these need to be initialized
1316 APInt::sdivrem(A, B, Q, R);
1319 if ((A.sgt(0) && B.sgt(0)) ||
1320 (A.slt(0) && B.slt(0)))
1328 APInt ceilingOfQuotient(APInt A, APInt B) {
1329 APInt Q = A; // these need to be initialized
1331 APInt::sdivrem(A, B, Q, R);
1334 if ((A.sgt(0) && B.sgt(0)) ||
1335 (A.slt(0) && B.slt(0)))
1343 APInt maxAPInt(APInt A, APInt B) {
1344 return A.sgt(B) ? A : B;
1349 APInt minAPInt(APInt A, APInt B) {
1350 return A.slt(B) ? A : B;
1355 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1356 // where i is an induction variable, c1 and c2 are loop invariant, and a1
1357 // and a2 are constant, we can solve it exactly using an algorithm developed
1358 // by Banerjee and Wolfe. See Section 2.5.3 in
1360 // Optimizing Supercompilers for Supercomputers
1364 // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1365 // so use them if possible. They're also a bit better with symbolics and,
1366 // in the case of the strong SIV test, can compute Distances.
1368 // Return true if dependence disproved.
1369 bool DependenceAnalysis::exactSIVtest(const SCEV *SrcCoeff,
1370 const SCEV *DstCoeff,
1371 const SCEV *SrcConst,
1372 const SCEV *DstConst,
1373 const Loop *CurLoop,
1375 FullDependence &Result,
1376 Constraint &NewConstraint) const {
1377 DEBUG(dbgs() << "\tExact SIV test\n");
1378 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1379 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1380 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1381 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1382 ++ExactSIVapplications;
1383 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1385 Result.Consistent = false;
1386 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1387 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1388 NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff),
1390 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1391 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1392 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1393 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1398 APInt AM = ConstSrcCoeff->getValue()->getValue();
1399 APInt BM = ConstDstCoeff->getValue()->getValue();
1400 unsigned Bits = AM.getBitWidth();
1401 if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) {
1402 // gcd doesn't divide Delta, no dependence
1403 ++ExactSIVindependence;
1404 ++ExactSIVsuccesses;
1408 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1410 // since SCEV construction normalizes, LM = 0
1411 APInt UM(Bits, 1, true);
1412 bool UMvalid = false;
1413 // UM is perhaps unavailable, let's check
1414 if (const SCEVConstant *CUB =
1415 collectConstantUpperBound(CurLoop, Delta->getType())) {
1416 UM = CUB->getValue()->getValue();
1417 DEBUG(dbgs() << "\t UM = " << UM << "\n");
1421 APInt TU(APInt::getSignedMaxValue(Bits));
1422 APInt TL(APInt::getSignedMinValue(Bits));
1424 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1425 APInt TMUL = BM.sdiv(G);
1427 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1428 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1430 TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL));
1431 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1435 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1436 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1438 TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL));
1439 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1443 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1446 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1447 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1449 TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL));
1450 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1454 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1455 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1457 TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL));
1458 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1462 ++ExactSIVindependence;
1463 ++ExactSIVsuccesses;
1467 // explore directions
1468 unsigned NewDirection = Dependence::DVEntry::NONE;
1471 APInt SaveTU(TU); // save these
1473 DEBUG(dbgs() << "\t exploring LT direction\n");
1476 TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL));
1477 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1480 TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL));
1481 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1484 NewDirection |= Dependence::DVEntry::LT;
1485 ++ExactSIVsuccesses;
1489 TU = SaveTU; // restore
1491 DEBUG(dbgs() << "\t exploring EQ direction\n");
1493 TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL));
1494 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1497 TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL));
1498 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1502 TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL));
1503 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1506 TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL));
1507 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1510 NewDirection |= Dependence::DVEntry::EQ;
1511 ++ExactSIVsuccesses;
1515 TU = SaveTU; // restore
1517 DEBUG(dbgs() << "\t exploring GT direction\n");
1519 TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL));
1520 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1523 TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL));
1524 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1527 NewDirection |= Dependence::DVEntry::GT;
1528 ++ExactSIVsuccesses;
1532 Result.DV[Level].Direction &= NewDirection;
1533 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1534 ++ExactSIVindependence;
1535 return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1540 // Return true if the divisor evenly divides the dividend.
1542 bool isRemainderZero(const SCEVConstant *Dividend,
1543 const SCEVConstant *Divisor) {
1544 APInt ConstDividend = Dividend->getValue()->getValue();
1545 APInt ConstDivisor = Divisor->getValue()->getValue();
1546 return ConstDividend.srem(ConstDivisor) == 0;
1550 // weakZeroSrcSIVtest -
1551 // From the paper, Practical Dependence Testing, Section 4.2.2
1553 // When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1554 // where i is an induction variable, c1 and c2 are loop invariant,
1555 // and a is a constant, we can solve it exactly using the
1556 // Weak-Zero SIV test.
1566 // If i is not an integer, there's no dependence.
1567 // If i < 0 or > UB, there's no dependence.
1568 // If i = 0, the direction is <= and peeling the
1569 // 1st iteration will break the dependence.
1570 // If i = UB, the direction is >= and peeling the
1571 // last iteration will break the dependence.
1572 // Otherwise, the direction is *.
1574 // Can prove independence. Failing that, we can sometimes refine
1575 // the directions. Can sometimes show that first or last
1576 // iteration carries all the dependences (so worth peeling).
1578 // (see also weakZeroDstSIVtest)
1580 // Return true if dependence disproved.
1581 bool DependenceAnalysis::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1582 const SCEV *SrcConst,
1583 const SCEV *DstConst,
1584 const Loop *CurLoop,
1586 FullDependence &Result,
1587 Constraint &NewConstraint) const {
1588 // For the WeakSIV test, it's possible the loop isn't common to
1589 // the Src and Dst loops. If it isn't, then there's no need to
1590 // record a direction.
1591 DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1592 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1593 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1594 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1595 ++WeakZeroSIVapplications;
1596 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1598 Result.Consistent = false;
1599 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1600 NewConstraint.setLine(SE->getConstant(Delta->getType(), 0),
1601 DstCoeff, Delta, CurLoop);
1602 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1603 if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
1604 if (Level < CommonLevels) {
1605 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1606 Result.DV[Level].PeelFirst = true;
1607 ++WeakZeroSIVsuccesses;
1609 return false; // dependences caused by first iteration
1611 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1614 const SCEV *AbsCoeff =
1615 SE->isKnownNegative(ConstCoeff) ?
1616 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1617 const SCEV *NewDelta =
1618 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1620 // check that Delta/SrcCoeff < iteration count
1621 // really check NewDelta < count*AbsCoeff
1622 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1623 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1624 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1625 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1626 ++WeakZeroSIVindependence;
1627 ++WeakZeroSIVsuccesses;
1630 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1631 // dependences caused by last iteration
1632 if (Level < CommonLevels) {
1633 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1634 Result.DV[Level].PeelLast = true;
1635 ++WeakZeroSIVsuccesses;
1641 // check that Delta/SrcCoeff >= 0
1642 // really check that NewDelta >= 0
1643 if (SE->isKnownNegative(NewDelta)) {
1644 // No dependence, newDelta < 0
1645 ++WeakZeroSIVindependence;
1646 ++WeakZeroSIVsuccesses;
1650 // if SrcCoeff doesn't divide Delta, then no dependence
1651 if (isa<SCEVConstant>(Delta) &&
1652 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1653 ++WeakZeroSIVindependence;
1654 ++WeakZeroSIVsuccesses;
1661 // weakZeroDstSIVtest -
1662 // From the paper, Practical Dependence Testing, Section 4.2.2
1664 // When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1665 // where i is an induction variable, c1 and c2 are loop invariant,
1666 // and a is a constant, we can solve it exactly using the
1667 // Weak-Zero SIV test.
1677 // If i is not an integer, there's no dependence.
1678 // If i < 0 or > UB, there's no dependence.
1679 // If i = 0, the direction is <= and peeling the
1680 // 1st iteration will break the dependence.
1681 // If i = UB, the direction is >= and peeling the
1682 // last iteration will break the dependence.
1683 // Otherwise, the direction is *.
1685 // Can prove independence. Failing that, we can sometimes refine
1686 // the directions. Can sometimes show that first or last
1687 // iteration carries all the dependences (so worth peeling).
1689 // (see also weakZeroSrcSIVtest)
1691 // Return true if dependence disproved.
1692 bool DependenceAnalysis::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1693 const SCEV *SrcConst,
1694 const SCEV *DstConst,
1695 const Loop *CurLoop,
1697 FullDependence &Result,
1698 Constraint &NewConstraint) const {
1699 // For the WeakSIV test, it's possible the loop isn't common to the
1700 // Src and Dst loops. If it isn't, then there's no need to record a direction.
1701 DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1702 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1703 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1704 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1705 ++WeakZeroSIVapplications;
1706 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1708 Result.Consistent = false;
1709 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1710 NewConstraint.setLine(SrcCoeff, SE->getConstant(Delta->getType(), 0),
1712 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1713 if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
1714 if (Level < CommonLevels) {
1715 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1716 Result.DV[Level].PeelFirst = true;
1717 ++WeakZeroSIVsuccesses;
1719 return false; // dependences caused by first iteration
1721 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1724 const SCEV *AbsCoeff =
1725 SE->isKnownNegative(ConstCoeff) ?
1726 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1727 const SCEV *NewDelta =
1728 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1730 // check that Delta/SrcCoeff < iteration count
1731 // really check NewDelta < count*AbsCoeff
1732 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1733 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1734 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1735 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1736 ++WeakZeroSIVindependence;
1737 ++WeakZeroSIVsuccesses;
1740 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1741 // dependences caused by last iteration
1742 if (Level < CommonLevels) {
1743 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1744 Result.DV[Level].PeelLast = true;
1745 ++WeakZeroSIVsuccesses;
1751 // check that Delta/SrcCoeff >= 0
1752 // really check that NewDelta >= 0
1753 if (SE->isKnownNegative(NewDelta)) {
1754 // No dependence, newDelta < 0
1755 ++WeakZeroSIVindependence;
1756 ++WeakZeroSIVsuccesses;
1760 // if SrcCoeff doesn't divide Delta, then no dependence
1761 if (isa<SCEVConstant>(Delta) &&
1762 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1763 ++WeakZeroSIVindependence;
1764 ++WeakZeroSIVsuccesses;
1771 // exactRDIVtest - Tests the RDIV subscript pair for dependence.
1772 // Things of the form [c1 + a*i] and [c2 + b*j],
1773 // where i and j are induction variable, c1 and c2 are loop invariant,
1774 // and a and b are constants.
1775 // Returns true if any possible dependence is disproved.
1776 // Marks the result as inconsistant.
1777 // Works in some cases that symbolicRDIVtest doesn't, and vice versa.
1778 bool DependenceAnalysis::exactRDIVtest(const SCEV *SrcCoeff,
1779 const SCEV *DstCoeff,
1780 const SCEV *SrcConst,
1781 const SCEV *DstConst,
1782 const Loop *SrcLoop,
1783 const Loop *DstLoop,
1784 FullDependence &Result) const {
1785 DEBUG(dbgs() << "\tExact RDIV test\n");
1786 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1787 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1788 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1789 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1790 ++ExactRDIVapplications;
1791 Result.Consistent = false;
1792 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1793 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1794 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1795 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1796 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1797 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1802 APInt AM = ConstSrcCoeff->getValue()->getValue();
1803 APInt BM = ConstDstCoeff->getValue()->getValue();
1804 unsigned Bits = AM.getBitWidth();
1805 if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) {
1806 // gcd doesn't divide Delta, no dependence
1807 ++ExactRDIVindependence;
1811 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1813 // since SCEV construction seems to normalize, LM = 0
1814 APInt SrcUM(Bits, 1, true);
1815 bool SrcUMvalid = false;
1816 // SrcUM is perhaps unavailable, let's check
1817 if (const SCEVConstant *UpperBound =
1818 collectConstantUpperBound(SrcLoop, Delta->getType())) {
1819 SrcUM = UpperBound->getValue()->getValue();
1820 DEBUG(dbgs() << "\t SrcUM = " << SrcUM << "\n");
1824 APInt DstUM(Bits, 1, true);
1825 bool DstUMvalid = false;
1826 // UM is perhaps unavailable, let's check
1827 if (const SCEVConstant *UpperBound =
1828 collectConstantUpperBound(DstLoop, Delta->getType())) {
1829 DstUM = UpperBound->getValue()->getValue();
1830 DEBUG(dbgs() << "\t DstUM = " << DstUM << "\n");
1834 APInt TU(APInt::getSignedMaxValue(Bits));
1835 APInt TL(APInt::getSignedMinValue(Bits));
1837 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1838 APInt TMUL = BM.sdiv(G);
1840 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1841 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1843 TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL));
1844 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1848 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1849 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1851 TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL));
1852 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1856 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1859 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1860 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1862 TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL));
1863 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1867 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1868 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1870 TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL));
1871 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1875 ++ExactRDIVindependence;
1880 // symbolicRDIVtest -
1881 // In Section 4.5 of the Practical Dependence Testing paper,the authors
1882 // introduce a special case of Banerjee's Inequalities (also called the
1883 // Extreme-Value Test) that can handle some of the SIV and RDIV cases,
1884 // particularly cases with symbolics. Since it's only able to disprove
1885 // dependence (not compute distances or directions), we'll use it as a
1886 // fall back for the other tests.
1888 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
1889 // where i and j are induction variables and c1 and c2 are loop invariants,
1890 // we can use the symbolic tests to disprove some dependences, serving as a
1891 // backup for the RDIV test. Note that i and j can be the same variable,
1892 // letting this test serve as a backup for the various SIV tests.
1894 // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
1895 // 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
1896 // loop bounds for the i and j loops, respectively. So, ...
1898 // c1 + a1*i = c2 + a2*j
1899 // a1*i - a2*j = c2 - c1
1901 // To test for a dependence, we compute c2 - c1 and make sure it's in the
1902 // range of the maximum and minimum possible values of a1*i - a2*j.
1903 // Considering the signs of a1 and a2, we have 4 possible cases:
1905 // 1) If a1 >= 0 and a2 >= 0, then
1906 // a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
1907 // -a2*N2 <= c2 - c1 <= a1*N1
1909 // 2) If a1 >= 0 and a2 <= 0, then
1910 // a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
1911 // 0 <= c2 - c1 <= a1*N1 - a2*N2
1913 // 3) If a1 <= 0 and a2 >= 0, then
1914 // a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
1915 // a1*N1 - a2*N2 <= c2 - c1 <= 0
1917 // 4) If a1 <= 0 and a2 <= 0, then
1918 // a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
1919 // a1*N1 <= c2 - c1 <= -a2*N2
1921 // return true if dependence disproved
1922 bool DependenceAnalysis::symbolicRDIVtest(const SCEV *A1,
1927 const Loop *Loop2) const {
1928 ++SymbolicRDIVapplications;
1929 DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
1930 DEBUG(dbgs() << "\t A1 = " << *A1);
1931 DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
1932 DEBUG(dbgs() << "\t A2 = " << *A2 << "\n");
1933 DEBUG(dbgs() << "\t C1 = " << *C1 << "\n");
1934 DEBUG(dbgs() << "\t C2 = " << *C2 << "\n");
1935 const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
1936 const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
1937 DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n");
1938 DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n");
1939 const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
1940 const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
1941 DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n");
1942 DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n");
1943 if (SE->isKnownNonNegative(A1)) {
1944 if (SE->isKnownNonNegative(A2)) {
1945 // A1 >= 0 && A2 >= 0
1947 // make sure that c2 - c1 <= a1*N1
1948 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
1949 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
1950 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
1951 ++SymbolicRDIVindependence;
1956 // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
1957 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
1958 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
1959 if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
1960 ++SymbolicRDIVindependence;
1965 else if (SE->isKnownNonPositive(A2)) {
1966 // a1 >= 0 && a2 <= 0
1968 // make sure that c2 - c1 <= a1*N1 - a2*N2
1969 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
1970 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
1971 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
1972 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
1973 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
1974 ++SymbolicRDIVindependence;
1978 // make sure that 0 <= c2 - c1
1979 if (SE->isKnownNegative(C2_C1)) {
1980 ++SymbolicRDIVindependence;
1985 else if (SE->isKnownNonPositive(A1)) {
1986 if (SE->isKnownNonNegative(A2)) {
1987 // a1 <= 0 && a2 >= 0
1989 // make sure that a1*N1 - a2*N2 <= c2 - c1
1990 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
1991 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
1992 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
1993 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
1994 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
1995 ++SymbolicRDIVindependence;
1999 // make sure that c2 - c1 <= 0
2000 if (SE->isKnownPositive(C2_C1)) {
2001 ++SymbolicRDIVindependence;
2005 else if (SE->isKnownNonPositive(A2)) {
2006 // a1 <= 0 && a2 <= 0
2008 // make sure that a1*N1 <= c2 - c1
2009 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2010 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
2011 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2012 ++SymbolicRDIVindependence;
2017 // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2018 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2019 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
2020 if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2021 ++SymbolicRDIVindependence;
2032 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2033 // where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2034 // a2 are constant, we attack it with an SIV test. While they can all be
2035 // solved with the Exact SIV test, it's worthwhile to use simpler tests when
2036 // they apply; they're cheaper and sometimes more precise.
2038 // Return true if dependence disproved.
2039 bool DependenceAnalysis::testSIV(const SCEV *Src,
2042 FullDependence &Result,
2043 Constraint &NewConstraint,
2044 const SCEV *&SplitIter) const {
2045 DEBUG(dbgs() << " src = " << *Src << "\n");
2046 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2047 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2048 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2049 if (SrcAddRec && DstAddRec) {
2050 const SCEV *SrcConst = SrcAddRec->getStart();
2051 const SCEV *DstConst = DstAddRec->getStart();
2052 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2053 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2054 const Loop *CurLoop = SrcAddRec->getLoop();
2055 assert(CurLoop == DstAddRec->getLoop() &&
2056 "both loops in SIV should be same");
2057 Level = mapSrcLoop(CurLoop);
2059 if (SrcCoeff == DstCoeff)
2060 disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2061 Level, Result, NewConstraint);
2062 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2063 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2064 Level, Result, NewConstraint, SplitIter);
2066 disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
2067 Level, Result, NewConstraint);
2069 gcdMIVtest(Src, Dst, Result) ||
2070 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
2073 const SCEV *SrcConst = SrcAddRec->getStart();
2074 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2075 const SCEV *DstConst = Dst;
2076 const Loop *CurLoop = SrcAddRec->getLoop();
2077 Level = mapSrcLoop(CurLoop);
2078 return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2079 Level, Result, NewConstraint) ||
2080 gcdMIVtest(Src, Dst, Result);
2083 const SCEV *DstConst = DstAddRec->getStart();
2084 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2085 const SCEV *SrcConst = Src;
2086 const Loop *CurLoop = DstAddRec->getLoop();
2087 Level = mapDstLoop(CurLoop);
2088 return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
2089 CurLoop, Level, Result, NewConstraint) ||
2090 gcdMIVtest(Src, Dst, Result);
2092 llvm_unreachable("SIV test expected at least one AddRec");
2098 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2099 // where i and j are induction variables, c1 and c2 are loop invariant,
2100 // and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2101 // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2102 // It doesn't make sense to talk about distance or direction in this case,
2103 // so there's no point in making special versions of the Strong SIV test or
2104 // the Weak-crossing SIV test.
2106 // With minor algebra, this test can also be used for things like
2107 // [c1 + a1*i + a2*j][c2].
2109 // Return true if dependence disproved.
2110 bool DependenceAnalysis::testRDIV(const SCEV *Src,
2112 FullDependence &Result) const {
2113 // we have 3 possible situations here:
2114 // 1) [a*i + b] and [c*j + d]
2115 // 2) [a*i + c*j + b] and [d]
2116 // 3) [b] and [a*i + c*j + d]
2117 // We need to find what we've got and get organized
2119 const SCEV *SrcConst, *DstConst;
2120 const SCEV *SrcCoeff, *DstCoeff;
2121 const Loop *SrcLoop, *DstLoop;
2123 DEBUG(dbgs() << " src = " << *Src << "\n");
2124 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2125 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2126 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2127 if (SrcAddRec && DstAddRec) {
2128 SrcConst = SrcAddRec->getStart();
2129 SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2130 SrcLoop = SrcAddRec->getLoop();
2131 DstConst = DstAddRec->getStart();
2132 DstCoeff = DstAddRec->getStepRecurrence(*SE);
2133 DstLoop = DstAddRec->getLoop();
2135 else if (SrcAddRec) {
2136 if (const SCEVAddRecExpr *tmpAddRec =
2137 dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
2138 SrcConst = tmpAddRec->getStart();
2139 SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
2140 SrcLoop = tmpAddRec->getLoop();
2142 DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
2143 DstLoop = SrcAddRec->getLoop();
2146 llvm_unreachable("RDIV reached by surprising SCEVs");
2148 else if (DstAddRec) {
2149 if (const SCEVAddRecExpr *tmpAddRec =
2150 dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
2151 DstConst = tmpAddRec->getStart();
2152 DstCoeff = tmpAddRec->getStepRecurrence(*SE);
2153 DstLoop = tmpAddRec->getLoop();
2155 SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
2156 SrcLoop = DstAddRec->getLoop();
2159 llvm_unreachable("RDIV reached by surprising SCEVs");
2162 llvm_unreachable("RDIV expected at least one AddRec");
2163 return exactRDIVtest(SrcCoeff, DstCoeff,
2167 gcdMIVtest(Src, Dst, Result) ||
2168 symbolicRDIVtest(SrcCoeff, DstCoeff,
2174 // Tests the single-subscript MIV pair (Src and Dst) for dependence.
2175 // Return true if dependence disproved.
2176 // Can sometimes refine direction vectors.
2177 bool DependenceAnalysis::testMIV(const SCEV *Src,
2179 const SmallBitVector &Loops,
2180 FullDependence &Result) const {
2181 DEBUG(dbgs() << " src = " << *Src << "\n");
2182 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2183 Result.Consistent = false;
2184 return gcdMIVtest(Src, Dst, Result) ||
2185 banerjeeMIVtest(Src, Dst, Loops, Result);
2189 // Given a product, e.g., 10*X*Y, returns the first constant operand,
2190 // in this case 10. If there is no constant part, returns NULL.
2192 const SCEVConstant *getConstantPart(const SCEVMulExpr *Product) {
2193 for (unsigned Op = 0, Ops = Product->getNumOperands(); Op < Ops; Op++) {
2194 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Product->getOperand(Op)))
2201 //===----------------------------------------------------------------------===//
2203 // Tests an MIV subscript pair for dependence.
2204 // Returns true if any possible dependence is disproved.
2205 // Marks the result as inconsistant.
2206 // Can sometimes disprove the equal direction for 1 or more loops,
2207 // as discussed in Michael Wolfe's book,
2208 // High Performance Compilers for Parallel Computing, page 235.
2210 // We spend some effort (code!) to handle cases like
2211 // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2212 // but M and N are just loop-invariant variables.
2213 // This should help us handle linearized subscripts;
2214 // also makes this test a useful backup to the various SIV tests.
2216 // It occurs to me that the presence of loop-invariant variables
2217 // changes the nature of the test from "greatest common divisor"
2218 // to "a common divisor!"
2219 bool DependenceAnalysis::gcdMIVtest(const SCEV *Src,
2221 FullDependence &Result) const {
2222 DEBUG(dbgs() << "starting gcd\n");
2224 unsigned BitWidth = Src->getType()->getIntegerBitWidth();
2225 APInt RunningGCD = APInt::getNullValue(BitWidth);
2227 // Examine Src coefficients.
2228 // Compute running GCD and record source constant.
2229 // Because we're looking for the constant at the end of the chain,
2230 // we can't quit the loop just because the GCD == 1.
2231 const SCEV *Coefficients = Src;
2232 while (const SCEVAddRecExpr *AddRec =
2233 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2234 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2235 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
2236 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2237 // If the coefficient is the product of a constant and other stuff,
2238 // we can use the constant in the GCD computation.
2239 Constant = getConstantPart(Product);
2242 APInt ConstCoeff = Constant->getValue()->getValue();
2243 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2244 Coefficients = AddRec->getStart();
2246 const SCEV *SrcConst = Coefficients;
2248 // Examine Dst coefficients.
2249 // Compute running GCD and record destination constant.
2250 // Because we're looking for the constant at the end of the chain,
2251 // we can't quit the loop just because the GCD == 1.
2253 while (const SCEVAddRecExpr *AddRec =
2254 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2255 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2256 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
2257 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2258 // If the coefficient is the product of a constant and other stuff,
2259 // we can use the constant in the GCD computation.
2260 Constant = getConstantPart(Product);
2263 APInt ConstCoeff = Constant->getValue()->getValue();
2264 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2265 Coefficients = AddRec->getStart();
2267 const SCEV *DstConst = Coefficients;
2269 APInt ExtraGCD = APInt::getNullValue(BitWidth);
2270 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
2271 DEBUG(dbgs() << " Delta = " << *Delta << "\n");
2272 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2273 if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
2274 // If Delta is a sum of products, we may be able to make further progress.
2275 for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
2276 const SCEV *Operand = Sum->getOperand(Op);
2277 if (isa<SCEVConstant>(Operand)) {
2278 assert(!Constant && "Surprised to find multiple constants");
2279 Constant = cast<SCEVConstant>(Operand);
2281 else if (isa<SCEVMulExpr>(Operand)) {
2282 // Search for constant operand to participate in GCD;
2283 // If none found; return false.
2284 const SCEVConstant *ConstOp =
2285 getConstantPart(cast<SCEVMulExpr>(Operand));
2286 APInt ConstOpValue = ConstOp->getValue()->getValue();
2287 ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
2288 ConstOpValue.abs());
2296 APInt ConstDelta = cast<SCEVConstant>(Constant)->getValue()->getValue();
2297 DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
2298 if (ConstDelta == 0)
2300 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
2301 DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
2302 APInt Remainder = ConstDelta.srem(RunningGCD);
2303 if (Remainder != 0) {
2308 // Try to disprove equal directions.
2309 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2310 // the code above can't disprove the dependence because the GCD = 1.
2311 // So we consider what happen if i = i' and what happens if j = j'.
2312 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2313 // which is infeasible, so we can disallow the = direction for the i level.
2314 // Setting j = j' doesn't help matters, so we end up with a direction vector
2317 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2318 // we need to remember that the constant part is 5 and the RunningGCD should
2319 // be initialized to ExtraGCD = 30.
2320 DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
2322 bool Improved = false;
2324 while (const SCEVAddRecExpr *AddRec =
2325 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2326 Coefficients = AddRec->getStart();
2327 const Loop *CurLoop = AddRec->getLoop();
2328 RunningGCD = ExtraGCD;
2329 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2330 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2331 const SCEV *Inner = Src;
2332 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2333 AddRec = cast<SCEVAddRecExpr>(Inner);
2334 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2335 if (CurLoop == AddRec->getLoop())
2336 ; // SrcCoeff == Coeff
2338 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2339 // If the coefficient is the product of a constant and other stuff,
2340 // we can use the constant in the GCD computation.
2341 Constant = getConstantPart(Product);
2343 Constant = cast<SCEVConstant>(Coeff);
2344 APInt ConstCoeff = Constant->getValue()->getValue();
2345 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2347 Inner = AddRec->getStart();
2350 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2351 AddRec = cast<SCEVAddRecExpr>(Inner);
2352 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2353 if (CurLoop == AddRec->getLoop())
2356 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2357 // If the coefficient is the product of a constant and other stuff,
2358 // we can use the constant in the GCD computation.
2359 Constant = getConstantPart(Product);
2361 Constant = cast<SCEVConstant>(Coeff);
2362 APInt ConstCoeff = Constant->getValue()->getValue();
2363 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2365 Inner = AddRec->getStart();
2367 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
2368 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Delta))
2369 // If the coefficient is the product of a constant and other stuff,
2370 // we can use the constant in the GCD computation.
2371 Constant = getConstantPart(Product);
2372 else if (isa<SCEVConstant>(Delta))
2373 Constant = cast<SCEVConstant>(Delta);
2375 // The difference of the two coefficients might not be a product
2376 // or constant, in which case we give up on this direction.
2379 APInt ConstCoeff = Constant->getValue()->getValue();
2380 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2381 DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
2382 if (RunningGCD != 0) {
2383 Remainder = ConstDelta.srem(RunningGCD);
2384 DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
2385 if (Remainder != 0) {
2386 unsigned Level = mapSrcLoop(CurLoop);
2387 Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
2394 DEBUG(dbgs() << "all done\n");
2399 //===----------------------------------------------------------------------===//
2400 // banerjeeMIVtest -
2401 // Use Banerjee's Inequalities to test an MIV subscript pair.
2402 // (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2403 // Generally follows the discussion in Section 2.5.2 of
2405 // Optimizing Supercompilers for Supercomputers
2408 // The inequalities given on page 25 are simplified in that loops are
2409 // normalized so that the lower bound is always 0 and the stride is always 1.
2410 // For example, Wolfe gives
2412 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2414 // where A_k is the coefficient of the kth index in the source subscript,
2415 // B_k is the coefficient of the kth index in the destination subscript,
2416 // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2417 // index, and N_k is the stride of the kth index. Since all loops are normalized
2418 // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2421 // LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2422 // = (A^-_k - B_k)^- (U_k - 1) - B_k
2424 // Similar simplifications are possible for the other equations.
2426 // When we can't determine the number of iterations for a loop,
2427 // we use NULL as an indicator for the worst case, infinity.
2428 // When computing the upper bound, NULL denotes +inf;
2429 // for the lower bound, NULL denotes -inf.
2431 // Return true if dependence disproved.
2432 bool DependenceAnalysis::banerjeeMIVtest(const SCEV *Src,
2434 const SmallBitVector &Loops,
2435 FullDependence &Result) const {
2436 DEBUG(dbgs() << "starting Banerjee\n");
2437 ++BanerjeeApplications;
2438 DEBUG(dbgs() << " Src = " << *Src << '\n');
2440 CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
2441 DEBUG(dbgs() << " Dst = " << *Dst << '\n');
2443 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2444 BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
2445 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2446 DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2448 // Compute bounds for all the * directions.
2449 DEBUG(dbgs() << "\tBounds[*]\n");
2450 for (unsigned K = 1; K <= MaxLevels; ++K) {
2451 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2452 Bound[K].Direction = Dependence::DVEntry::ALL;
2453 Bound[K].DirSet = Dependence::DVEntry::NONE;
2454 findBoundsALL(A, B, Bound, K);
2456 DEBUG(dbgs() << "\t " << K << '\t');
2457 if (Bound[K].Lower[Dependence::DVEntry::ALL])
2458 DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
2460 DEBUG(dbgs() << "-inf\t");
2461 if (Bound[K].Upper[Dependence::DVEntry::ALL])
2462 DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
2464 DEBUG(dbgs() << "+inf\n");
2468 // Test the *, *, *, ... case.
2469 bool Disproved = false;
2470 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2471 // Explore the direction vector hierarchy.
2472 unsigned DepthExpanded = 0;
2473 unsigned NewDeps = exploreDirections(1, A, B, Bound,
2474 Loops, DepthExpanded, Delta);
2476 bool Improved = false;
2477 for (unsigned K = 1; K <= CommonLevels; ++K) {
2479 unsigned Old = Result.DV[K - 1].Direction;
2480 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2481 Improved |= Old != Result.DV[K - 1].Direction;
2482 if (!Result.DV[K - 1].Direction) {
2490 ++BanerjeeSuccesses;
2493 ++BanerjeeIndependence;
2498 ++BanerjeeIndependence;
2508 // Hierarchically expands the direction vector
2509 // search space, combining the directions of discovered dependences
2510 // in the DirSet field of Bound. Returns the number of distinct
2511 // dependences discovered. If the dependence is disproved,
2512 // it will return 0.
2513 unsigned DependenceAnalysis::exploreDirections(unsigned Level,
2517 const SmallBitVector &Loops,
2518 unsigned &DepthExpanded,
2519 const SCEV *Delta) const {
2520 if (Level > CommonLevels) {
2522 DEBUG(dbgs() << "\t[");
2523 for (unsigned K = 1; K <= CommonLevels; ++K) {
2525 Bound[K].DirSet |= Bound[K].Direction;
2527 switch (Bound[K].Direction) {
2528 case Dependence::DVEntry::LT:
2529 DEBUG(dbgs() << " <");
2531 case Dependence::DVEntry::EQ:
2532 DEBUG(dbgs() << " =");
2534 case Dependence::DVEntry::GT:
2535 DEBUG(dbgs() << " >");
2537 case Dependence::DVEntry::ALL:
2538 DEBUG(dbgs() << " *");
2541 llvm_unreachable("unexpected Bound[K].Direction");
2546 DEBUG(dbgs() << " ]\n");
2550 if (Level > DepthExpanded) {
2551 DepthExpanded = Level;
2552 // compute bounds for <, =, > at current level
2553 findBoundsLT(A, B, Bound, Level);
2554 findBoundsGT(A, B, Bound, Level);
2555 findBoundsEQ(A, B, Bound, Level);
2557 DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2558 DEBUG(dbgs() << "\t <\t");
2559 if (Bound[Level].Lower[Dependence::DVEntry::LT])
2560 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT] << '\t');
2562 DEBUG(dbgs() << "-inf\t");
2563 if (Bound[Level].Upper[Dependence::DVEntry::LT])
2564 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT] << '\n');
2566 DEBUG(dbgs() << "+inf\n");
2567 DEBUG(dbgs() << "\t =\t");
2568 if (Bound[Level].Lower[Dependence::DVEntry::EQ])
2569 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ] << '\t');
2571 DEBUG(dbgs() << "-inf\t");
2572 if (Bound[Level].Upper[Dependence::DVEntry::EQ])
2573 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ] << '\n');
2575 DEBUG(dbgs() << "+inf\n");
2576 DEBUG(dbgs() << "\t >\t");
2577 if (Bound[Level].Lower[Dependence::DVEntry::GT])
2578 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT] << '\t');
2580 DEBUG(dbgs() << "-inf\t");
2581 if (Bound[Level].Upper[Dependence::DVEntry::GT])
2582 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT] << '\n');
2584 DEBUG(dbgs() << "+inf\n");
2588 unsigned NewDeps = 0;
2590 // test bounds for <, *, *, ...
2591 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2592 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2593 Loops, DepthExpanded, Delta);
2595 // Test bounds for =, *, *, ...
2596 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2597 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2598 Loops, DepthExpanded, Delta);
2600 // test bounds for >, *, *, ...
2601 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2602 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2603 Loops, DepthExpanded, Delta);
2605 Bound[Level].Direction = Dependence::DVEntry::ALL;
2609 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
2613 // Returns true iff the current bounds are plausible.
2614 bool DependenceAnalysis::testBounds(unsigned char DirKind,
2617 const SCEV *Delta) const {
2618 Bound[Level].Direction = DirKind;
2619 if (const SCEV *LowerBound = getLowerBound(Bound))
2620 if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2622 if (const SCEV *UpperBound = getUpperBound(Bound))
2623 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2629 // Computes the upper and lower bounds for level K
2630 // using the * direction. Records them in Bound.
2631 // Wolfe gives the equations
2633 // LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2634 // UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2636 // Since we normalize loops, we can simplify these equations to
2638 // LB^*_k = (A^-_k - B^+_k)U_k
2639 // UB^*_k = (A^+_k - B^-_k)U_k
2641 // We must be careful to handle the case where the upper bound is unknown.
2642 // Note that the lower bound is always <= 0
2643 // and the upper bound is always >= 0.
2644 void DependenceAnalysis::findBoundsALL(CoefficientInfo *A,
2648 Bound[K].Lower[Dependence::DVEntry::ALL] = NULL; // Default value = -infinity.
2649 Bound[K].Upper[Dependence::DVEntry::ALL] = NULL; // Default value = +infinity.
2650 if (Bound[K].Iterations) {
2651 Bound[K].Lower[Dependence::DVEntry::ALL] =
2652 SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
2653 Bound[K].Iterations);
2654 Bound[K].Upper[Dependence::DVEntry::ALL] =
2655 SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
2656 Bound[K].Iterations);
2659 // If the difference is 0, we won't need to know the number of iterations.
2660 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2661 Bound[K].Lower[Dependence::DVEntry::ALL] =
2662 SE->getConstant(A[K].Coeff->getType(), 0);
2663 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2664 Bound[K].Upper[Dependence::DVEntry::ALL] =
2665 SE->getConstant(A[K].Coeff->getType(), 0);
2670 // Computes the upper and lower bounds for level K
2671 // using the = direction. Records them in Bound.
2672 // Wolfe gives the equations
2674 // LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2675 // UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2677 // Since we normalize loops, we can simplify these equations to
2679 // LB^=_k = (A_k - B_k)^- U_k
2680 // UB^=_k = (A_k - B_k)^+ U_k
2682 // We must be careful to handle the case where the upper bound is unknown.
2683 // Note that the lower bound is always <= 0
2684 // and the upper bound is always >= 0.
2685 void DependenceAnalysis::findBoundsEQ(CoefficientInfo *A,
2689 Bound[K].Lower[Dependence::DVEntry::EQ] = NULL; // Default value = -infinity.
2690 Bound[K].Upper[Dependence::DVEntry::EQ] = NULL; // Default value = +infinity.
2691 if (Bound[K].Iterations) {
2692 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2693 const SCEV *NegativePart = getNegativePart(Delta);
2694 Bound[K].Lower[Dependence::DVEntry::EQ] =
2695 SE->getMulExpr(NegativePart, Bound[K].Iterations);
2696 const SCEV *PositivePart = getPositivePart(Delta);
2697 Bound[K].Upper[Dependence::DVEntry::EQ] =
2698 SE->getMulExpr(PositivePart, Bound[K].Iterations);
2701 // If the positive/negative part of the difference is 0,
2702 // we won't need to know the number of iterations.
2703 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2704 const SCEV *NegativePart = getNegativePart(Delta);
2705 if (NegativePart->isZero())
2706 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2707 const SCEV *PositivePart = getPositivePart(Delta);
2708 if (PositivePart->isZero())
2709 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2714 // Computes the upper and lower bounds for level K
2715 // using the < direction. Records them in Bound.
2716 // Wolfe gives the equations
2718 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2719 // UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2721 // Since we normalize loops, we can simplify these equations to
2723 // LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2724 // UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2726 // We must be careful to handle the case where the upper bound is unknown.
2727 void DependenceAnalysis::findBoundsLT(CoefficientInfo *A,
2731 Bound[K].Lower[Dependence::DVEntry::LT] = NULL; // Default value = -infinity.
2732 Bound[K].Upper[Dependence::DVEntry::LT] = NULL; // Default value = +infinity.
2733 if (Bound[K].Iterations) {
2734 const SCEV *Iter_1 =
2735 SE->getMinusSCEV(Bound[K].Iterations,
2736 SE->getConstant(Bound[K].Iterations->getType(), 1));
2737 const SCEV *NegPart =
2738 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2739 Bound[K].Lower[Dependence::DVEntry::LT] =
2740 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2741 const SCEV *PosPart =
2742 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2743 Bound[K].Upper[Dependence::DVEntry::LT] =
2744 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2747 // If the positive/negative part of the difference is 0,
2748 // we won't need to know the number of iterations.
2749 const SCEV *NegPart =
2750 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2751 if (NegPart->isZero())
2752 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2753 const SCEV *PosPart =
2754 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2755 if (PosPart->isZero())
2756 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2761 // Computes the upper and lower bounds for level K
2762 // using the > direction. Records them in Bound.
2763 // Wolfe gives the equations
2765 // LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2766 // UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2768 // Since we normalize loops, we can simplify these equations to
2770 // LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2771 // UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2773 // We must be careful to handle the case where the upper bound is unknown.
2774 void DependenceAnalysis::findBoundsGT(CoefficientInfo *A,
2778 Bound[K].Lower[Dependence::DVEntry::GT] = NULL; // Default value = -infinity.
2779 Bound[K].Upper[Dependence::DVEntry::GT] = NULL; // Default value = +infinity.
2780 if (Bound[K].Iterations) {
2781 const SCEV *Iter_1 =
2782 SE->getMinusSCEV(Bound[K].Iterations,
2783 SE->getConstant(Bound[K].Iterations->getType(), 1));
2784 const SCEV *NegPart =
2785 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2786 Bound[K].Lower[Dependence::DVEntry::GT] =
2787 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2788 const SCEV *PosPart =
2789 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2790 Bound[K].Upper[Dependence::DVEntry::GT] =
2791 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2794 // If the positive/negative part of the difference is 0,
2795 // we won't need to know the number of iterations.
2796 const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2797 if (NegPart->isZero())
2798 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2799 const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2800 if (PosPart->isZero())
2801 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2807 const SCEV *DependenceAnalysis::getPositivePart(const SCEV *X) const {
2808 return SE->getSMaxExpr(X, SE->getConstant(X->getType(), 0));
2813 const SCEV *DependenceAnalysis::getNegativePart(const SCEV *X) const {
2814 return SE->getSMinExpr(X, SE->getConstant(X->getType(), 0));
2818 // Walks through the subscript,
2819 // collecting each coefficient, the associated loop bounds,
2820 // and recording its positive and negative parts for later use.
2821 DependenceAnalysis::CoefficientInfo *
2822 DependenceAnalysis::collectCoeffInfo(const SCEV *Subscript,
2824 const SCEV *&Constant) const {
2825 const SCEV *Zero = SE->getConstant(Subscript->getType(), 0);
2826 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
2827 for (unsigned K = 1; K <= MaxLevels; ++K) {
2829 CI[K].PosPart = Zero;
2830 CI[K].NegPart = Zero;
2831 CI[K].Iterations = NULL;
2833 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2834 const Loop *L = AddRec->getLoop();
2835 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2836 CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2837 CI[K].PosPart = getPositivePart(CI[K].Coeff);
2838 CI[K].NegPart = getNegativePart(CI[K].Coeff);
2839 CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2840 Subscript = AddRec->getStart();
2842 Constant = Subscript;
2844 DEBUG(dbgs() << "\tCoefficient Info\n");
2845 for (unsigned K = 1; K <= MaxLevels; ++K) {
2846 DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
2847 DEBUG(dbgs() << "\tPos Part = ");
2848 DEBUG(dbgs() << *CI[K].PosPart);
2849 DEBUG(dbgs() << "\tNeg Part = ");
2850 DEBUG(dbgs() << *CI[K].NegPart);
2851 DEBUG(dbgs() << "\tUpper Bound = ");
2852 if (CI[K].Iterations)
2853 DEBUG(dbgs() << *CI[K].Iterations);
2855 DEBUG(dbgs() << "+inf");
2856 DEBUG(dbgs() << '\n');
2858 DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
2864 // Looks through all the bounds info and
2865 // computes the lower bound given the current direction settings
2866 // at each level. If the lower bound for any level is -inf,
2867 // the result is -inf.
2868 const SCEV *DependenceAnalysis::getLowerBound(BoundInfo *Bound) const {
2869 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2870 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2871 if (Bound[K].Lower[Bound[K].Direction])
2872 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2880 // Looks through all the bounds info and
2881 // computes the upper bound given the current direction settings
2882 // at each level. If the upper bound at any level is +inf,
2883 // the result is +inf.
2884 const SCEV *DependenceAnalysis::getUpperBound(BoundInfo *Bound) const {
2885 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2886 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2887 if (Bound[K].Upper[Bound[K].Direction])
2888 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2896 //===----------------------------------------------------------------------===//
2897 // Constraint manipulation for Delta test.
2899 // Given a linear SCEV,
2900 // return the coefficient (the step)
2901 // corresponding to the specified loop.
2902 // If there isn't one, return 0.
2903 // For example, given a*i + b*j + c*k, zeroing the coefficient
2904 // corresponding to the j loop would yield b.
2905 const SCEV *DependenceAnalysis::findCoefficient(const SCEV *Expr,
2906 const Loop *TargetLoop) const {
2907 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2909 return SE->getConstant(Expr->getType(), 0);
2910 if (AddRec->getLoop() == TargetLoop)
2911 return AddRec->getStepRecurrence(*SE);
2912 return findCoefficient(AddRec->getStart(), TargetLoop);
2916 // Given a linear SCEV,
2917 // return the SCEV given by zeroing out the coefficient
2918 // corresponding to the specified loop.
2919 // For example, given a*i + b*j + c*k, zeroing the coefficient
2920 // corresponding to the j loop would yield a*i + c*k.
2921 const SCEV *DependenceAnalysis::zeroCoefficient(const SCEV *Expr,
2922 const Loop *TargetLoop) const {
2923 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2925 return Expr; // ignore
2926 if (AddRec->getLoop() == TargetLoop)
2927 return AddRec->getStart();
2928 return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
2929 AddRec->getStepRecurrence(*SE),
2931 AddRec->getNoWrapFlags());
2935 // Given a linear SCEV Expr,
2936 // return the SCEV given by adding some Value to the
2937 // coefficient corresponding to the specified TargetLoop.
2938 // For example, given a*i + b*j + c*k, adding 1 to the coefficient
2939 // corresponding to the j loop would yield a*i + (b+1)*j + c*k.
2940 const SCEV *DependenceAnalysis::addToCoefficient(const SCEV *Expr,
2941 const Loop *TargetLoop,
2942 const SCEV *Value) const {
2943 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2944 if (!AddRec) // create a new addRec
2945 return SE->getAddRecExpr(Expr,
2948 SCEV::FlagAnyWrap); // Worst case, with no info.
2949 if (AddRec->getLoop() == TargetLoop) {
2950 const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
2952 return AddRec->getStart();
2953 return SE->getAddRecExpr(AddRec->getStart(),
2956 AddRec->getNoWrapFlags());
2958 return SE->getAddRecExpr(addToCoefficient(AddRec->getStart(),
2960 AddRec->getStepRecurrence(*SE),
2962 AddRec->getNoWrapFlags());
2966 // Review the constraints, looking for opportunities
2967 // to simplify a subscript pair (Src and Dst).
2968 // Return true if some simplification occurs.
2969 // If the simplification isn't exact (that is, if it is conservative
2970 // in terms of dependence), set consistent to false.
2971 // Corresponds to Figure 5 from the paper
2973 // Practical Dependence Testing
2974 // Goff, Kennedy, Tseng
2976 bool DependenceAnalysis::propagate(const SCEV *&Src,
2978 SmallBitVector &Loops,
2979 SmallVector<Constraint, 4> &Constraints,
2981 bool Result = false;
2982 for (int LI = Loops.find_first(); LI >= 0; LI = Loops.find_next(LI)) {
2983 DEBUG(dbgs() << "\t Constraint[" << LI << "] is");
2984 DEBUG(Constraints[LI].dump(dbgs()));
2985 if (Constraints[LI].isDistance())
2986 Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
2987 else if (Constraints[LI].isLine())
2988 Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
2989 else if (Constraints[LI].isPoint())
2990 Result |= propagatePoint(Src, Dst, Constraints[LI]);
2996 // Attempt to propagate a distance
2997 // constraint into a subscript pair (Src and Dst).
2998 // Return true if some simplification occurs.
2999 // If the simplification isn't exact (that is, if it is conservative
3000 // in terms of dependence), set consistent to false.
3001 bool DependenceAnalysis::propagateDistance(const SCEV *&Src,
3003 Constraint &CurConstraint,
3005 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3006 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3007 const SCEV *A_K = findCoefficient(Src, CurLoop);
3010 const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
3011 Src = SE->getMinusSCEV(Src, DA_K);
3012 Src = zeroCoefficient(Src, CurLoop);
3013 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3014 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3015 Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
3016 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3017 if (!findCoefficient(Dst, CurLoop)->isZero())
3023 // Attempt to propagate a line
3024 // constraint into a subscript pair (Src and Dst).
3025 // Return true if some simplification occurs.
3026 // If the simplification isn't exact (that is, if it is conservative
3027 // in terms of dependence), set consistent to false.
3028 bool DependenceAnalysis::propagateLine(const SCEV *&Src,
3030 Constraint &CurConstraint,
3032 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3033 const SCEV *A = CurConstraint.getA();
3034 const SCEV *B = CurConstraint.getB();
3035 const SCEV *C = CurConstraint.getC();
3036 DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C << "\n");
3037 DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
3038 DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
3040 const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
3041 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3042 if (!Bconst || !Cconst) return false;
3043 APInt Beta = Bconst->getValue()->getValue();
3044 APInt Charlie = Cconst->getValue()->getValue();
3045 APInt CdivB = Charlie.sdiv(Beta);
3046 assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
3047 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3048 // Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3049 Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3050 Dst = zeroCoefficient(Dst, CurLoop);
3051 if (!findCoefficient(Src, CurLoop)->isZero())
3054 else if (B->isZero()) {
3055 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3056 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3057 if (!Aconst || !Cconst) return false;
3058 APInt Alpha = Aconst->getValue()->getValue();
3059 APInt Charlie = Cconst->getValue()->getValue();
3060 APInt CdivA = Charlie.sdiv(Alpha);
3061 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3062 const SCEV *A_K = findCoefficient(Src, CurLoop);
3063 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3064 Src = zeroCoefficient(Src, CurLoop);
3065 if (!findCoefficient(Dst, CurLoop)->isZero())
3068 else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
3069 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3070 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3071 if (!Aconst || !Cconst) return false;
3072 APInt Alpha = Aconst->getValue()->getValue();
3073 APInt Charlie = Cconst->getValue()->getValue();
3074 APInt CdivA = Charlie.sdiv(Alpha);
3075 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3076 const SCEV *A_K = findCoefficient(Src, CurLoop);
3077 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3078 Src = zeroCoefficient(Src, CurLoop);
3079 Dst = addToCoefficient(Dst, CurLoop, A_K);
3080 if (!findCoefficient(Dst, CurLoop)->isZero())
3084 // paper is incorrect here, or perhaps just misleading
3085 const SCEV *A_K = findCoefficient(Src, CurLoop);
3086 Src = SE->getMulExpr(Src, A);
3087 Dst = SE->getMulExpr(Dst, A);
3088 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
3089 Src = zeroCoefficient(Src, CurLoop);
3090 Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
3091 if (!findCoefficient(Dst, CurLoop)->isZero())
3094 DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
3095 DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
3100 // Attempt to propagate a point
3101 // constraint into a subscript pair (Src and Dst).
3102 // Return true if some simplification occurs.
3103 bool DependenceAnalysis::propagatePoint(const SCEV *&Src,
3105 Constraint &CurConstraint) {
3106 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3107 const SCEV *A_K = findCoefficient(Src, CurLoop);
3108 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3109 const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
3110 const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
3111 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3112 Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
3113 Src = zeroCoefficient(Src, CurLoop);
3114 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3115 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3116 Dst = zeroCoefficient(Dst, CurLoop);
3117 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3122 // Update direction vector entry based on the current constraint.
3123 void DependenceAnalysis::updateDirection(Dependence::DVEntry &Level,
3124 const Constraint &CurConstraint
3126 DEBUG(dbgs() << "\tUpdate direction, constraint =");
3127 DEBUG(CurConstraint.dump(dbgs()));
3128 if (CurConstraint.isAny())
3130 else if (CurConstraint.isDistance()) {
3131 // this one is consistent, the others aren't
3132 Level.Scalar = false;
3133 Level.Distance = CurConstraint.getD();
3134 unsigned NewDirection = Dependence::DVEntry::NONE;
3135 if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
3136 NewDirection = Dependence::DVEntry::EQ;
3137 if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
3138 NewDirection |= Dependence::DVEntry::LT;
3139 if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
3140 NewDirection |= Dependence::DVEntry::GT;
3141 Level.Direction &= NewDirection;
3143 else if (CurConstraint.isLine()) {
3144 Level.Scalar = false;
3145 Level.Distance = NULL;
3146 // direction should be accurate
3148 else if (CurConstraint.isPoint()) {
3149 Level.Scalar = false;
3150 Level.Distance = NULL;
3151 unsigned NewDirection = Dependence::DVEntry::NONE;
3152 if (!isKnownPredicate(CmpInst::ICMP_NE,
3153 CurConstraint.getY(),
3154 CurConstraint.getX()))
3156 NewDirection |= Dependence::DVEntry::EQ;
3157 if (!isKnownPredicate(CmpInst::ICMP_SLE,
3158 CurConstraint.getY(),
3159 CurConstraint.getX()))
3161 NewDirection |= Dependence::DVEntry::LT;
3162 if (!isKnownPredicate(CmpInst::ICMP_SGE,
3163 CurConstraint.getY(),
3164 CurConstraint.getX()))
3166 NewDirection |= Dependence::DVEntry::GT;
3167 Level.Direction &= NewDirection;
3170 llvm_unreachable("constraint has unexpected kind");
3174 //===----------------------------------------------------------------------===//
3177 // For debugging purposes, dump a small bit vector to dbgs().
3178 static void dumpSmallBitVector(SmallBitVector &BV) {
3180 for (int VI = BV.find_first(); VI >= 0; VI = BV.find_next(VI)) {
3182 if (BV.find_next(VI) >= 0)
3191 // Returns NULL if there is no dependence.
3192 // Otherwise, return a Dependence with as many details as possible.
3193 // Corresponds to Section 3.1 in the paper
3195 // Practical Dependence Testing
3196 // Goff, Kennedy, Tseng
3199 // Care is required to keep the code below up to date w.r.t. this routine.
3200 Dependence *DependenceAnalysis::depends(const Instruction *Src,
3201 const Instruction *Dst,
3202 bool PossiblyLoopIndependent) {
3203 if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
3204 (!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
3205 // if both instructions don't reference memory, there's no dependence
3208 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst))
3209 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
3210 return new Dependence(Src, Dst);
3212 const Value *SrcPtr = getPointerOperand(Src);
3213 const Value *DstPtr = getPointerOperand(Dst);
3215 switch (underlyingObjectsAlias(AA, DstPtr, SrcPtr)) {
3216 case AliasAnalysis::MayAlias:
3217 case AliasAnalysis::PartialAlias:
3218 // cannot analyse objects if we don't understand their aliasing.
3219 return new Dependence(Src, Dst);
3220 case AliasAnalysis::NoAlias:
3221 // If the objects noalias, they are distinct, accesses are independent.
3223 case AliasAnalysis::MustAlias:
3224 break; // The underlying objects alias; test accesses for dependence.
3227 const GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr);
3228 const GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr);
3229 if (!SrcGEP || !DstGEP)
3230 return new Dependence(Src, Dst); // missing GEP, assume dependence
3232 if (SrcGEP->getPointerOperandType() != DstGEP->getPointerOperandType())
3233 return new Dependence(Src, Dst); // different types, assume dependence
3235 // establish loop nesting levels
3236 establishNestingLevels(Src, Dst);
3237 DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
3238 DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
3240 FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
3243 // classify subscript pairs
3244 unsigned Pairs = SrcGEP->idx_end() - SrcGEP->idx_begin();
3245 SmallVector<Subscript, 4> Pair(Pairs);
3246 for (unsigned SI = 0; SI < Pairs; ++SI) {
3247 Pair[SI].Loops.resize(MaxLevels + 1);
3248 Pair[SI].GroupLoops.resize(MaxLevels + 1);
3249 Pair[SI].Group.resize(Pairs);
3252 for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(),
3253 SrcEnd = SrcGEP->idx_end(),
3254 DstIdx = DstGEP->idx_begin(),
3255 DstEnd = DstGEP->idx_end();
3256 SrcIdx != SrcEnd && DstIdx != DstEnd;
3257 ++SrcIdx, ++DstIdx, ++Pairs) {
3258 Pair[Pairs].Src = SE->getSCEV(*SrcIdx);
3259 Pair[Pairs].Dst = SE->getSCEV(*DstIdx);
3260 removeMatchingExtensions(&Pair[Pairs]);
3261 Pair[Pairs].Classification =
3262 classifyPair(Pair[Pairs].Src, LI->getLoopFor(Src->getParent()),
3263 Pair[Pairs].Dst, LI->getLoopFor(Dst->getParent()),
3265 Pair[Pairs].GroupLoops = Pair[Pairs].Loops;
3266 Pair[Pairs].Group.set(Pairs);
3267 DEBUG(dbgs() << " subscript " << Pairs << "\n");
3268 DEBUG(dbgs() << "\tsrc = " << *Pair[Pairs].Src << "\n");
3269 DEBUG(dbgs() << "\tdst = " << *Pair[Pairs].Dst << "\n");
3270 DEBUG(dbgs() << "\tclass = " << Pair[Pairs].Classification << "\n");
3271 DEBUG(dbgs() << "\tloops = ");
3272 DEBUG(dumpSmallBitVector(Pair[Pairs].Loops));
3275 SmallBitVector Separable(Pairs);
3276 SmallBitVector Coupled(Pairs);
3278 // Partition subscripts into separable and minimally-coupled groups
3279 // Algorithm in paper is algorithmically better;
3280 // this may be faster in practice. Check someday.
3282 // Here's an example of how it works. Consider this code:
3289 // A[i][j][k][m] = ...;
3290 // ... = A[0][j][l][i + j];
3297 // There are 4 subscripts here:
3301 // 3 [m] and [i + j]
3303 // We've already classified each subscript pair as ZIV, SIV, etc.,
3304 // and collected all the loops mentioned by pair P in Pair[P].Loops.
3305 // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
3306 // and set Pair[P].Group = {P}.
3308 // Src Dst Classification Loops GroupLoops Group
3309 // 0 [i] [0] SIV {1} {1} {0}
3310 // 1 [j] [j] SIV {2} {2} {1}
3311 // 2 [k] [l] RDIV {3,4} {3,4} {2}
3312 // 3 [m] [i + j] MIV {1,2,5} {1,2,5} {3}
3314 // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
3315 // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
3317 // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
3318 // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
3319 // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
3320 // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
3321 // to either Separable or Coupled).
3323 // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
3324 // Next, 1 and 3. The intersectionof their GroupLoops = {2}, not empty,
3325 // so Pair[3].Group = {0, 1, 3} and Done = false.
3327 // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
3328 // Since Done remains true, we add 2 to the set of Separable pairs.
3330 // Finally, we consider 3. There's nothing to compare it with,
3331 // so Done remains true and we add it to the Coupled set.
3332 // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
3334 // In the end, we've got 1 separable subscript and 1 coupled group.
3335 for (unsigned SI = 0; SI < Pairs; ++SI) {
3336 if (Pair[SI].Classification == Subscript::NonLinear) {
3337 // ignore these, but collect loops for later
3338 ++NonlinearSubscriptPairs;
3339 collectCommonLoops(Pair[SI].Src,
3340 LI->getLoopFor(Src->getParent()),
3342 collectCommonLoops(Pair[SI].Dst,
3343 LI->getLoopFor(Dst->getParent()),
3345 Result.Consistent = false;
3347 else if (Pair[SI].Classification == Subscript::ZIV) {
3352 // SIV, RDIV, or MIV, so check for coupled group
3354 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3355 SmallBitVector Intersection = Pair[SI].GroupLoops;
3356 Intersection &= Pair[SJ].GroupLoops;
3357 if (Intersection.any()) {
3358 // accumulate set of all the loops in group
3359 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3360 // accumulate set of all subscripts in group
3361 Pair[SJ].Group |= Pair[SI].Group;
3366 if (Pair[SI].Group.count() == 1) {
3368 ++SeparableSubscriptPairs;
3372 ++CoupledSubscriptPairs;
3378 DEBUG(dbgs() << " Separable = ");
3379 DEBUG(dumpSmallBitVector(Separable));
3380 DEBUG(dbgs() << " Coupled = ");
3381 DEBUG(dumpSmallBitVector(Coupled));
3383 Constraint NewConstraint;
3384 NewConstraint.setAny(SE);
3386 // test separable subscripts
3387 for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) {
3388 DEBUG(dbgs() << "testing subscript " << SI);
3389 switch (Pair[SI].Classification) {
3390 case Subscript::ZIV:
3391 DEBUG(dbgs() << ", ZIV\n");
3392 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
3395 case Subscript::SIV: {
3396 DEBUG(dbgs() << ", SIV\n");
3398 const SCEV *SplitIter = NULL;
3399 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
3400 Result, NewConstraint, SplitIter))
3404 case Subscript::RDIV:
3405 DEBUG(dbgs() << ", RDIV\n");
3406 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
3409 case Subscript::MIV:
3410 DEBUG(dbgs() << ", MIV\n");
3411 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
3415 llvm_unreachable("subscript has unexpected classification");
3419 if (Coupled.count()) {
3420 // test coupled subscript groups
3421 DEBUG(dbgs() << "starting on coupled subscripts\n");
3422 DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
3423 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3424 for (unsigned II = 0; II <= MaxLevels; ++II)
3425 Constraints[II].setAny(SE);
3426 for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) {
3427 DEBUG(dbgs() << "testing subscript group " << SI << " { ");
3428 SmallBitVector Group(Pair[SI].Group);
3429 SmallBitVector Sivs(Pairs);
3430 SmallBitVector Mivs(Pairs);
3431 SmallBitVector ConstrainedLevels(MaxLevels + 1);
3432 for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) {
3433 DEBUG(dbgs() << SJ << " ");
3434 if (Pair[SJ].Classification == Subscript::SIV)
3439 DEBUG(dbgs() << "}\n");
3440 while (Sivs.any()) {
3441 bool Changed = false;
3442 for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
3443 DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
3444 // SJ is an SIV subscript that's part of the current coupled group
3446 const SCEV *SplitIter = NULL;
3447 DEBUG(dbgs() << "SIV\n");
3448 if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
3449 Result, NewConstraint, SplitIter))
3451 ConstrainedLevels.set(Level);
3452 if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
3453 if (Constraints[Level].isEmpty()) {
3454 ++DeltaIndependence;
3462 // propagate, possibly creating new SIVs and ZIVs
3463 DEBUG(dbgs() << " propagating\n");
3464 DEBUG(dbgs() << "\tMivs = ");
3465 DEBUG(dumpSmallBitVector(Mivs));
3466 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3467 // SJ is an MIV subscript that's part of the current coupled group
3468 DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
3469 if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
3470 Constraints, Result.Consistent)) {
3471 DEBUG(dbgs() << "\t Changed\n");
3472 ++DeltaPropagations;
3473 Pair[SJ].Classification =
3474 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3475 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3477 switch (Pair[SJ].Classification) {
3478 case Subscript::ZIV:
3479 DEBUG(dbgs() << "ZIV\n");
3480 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3484 case Subscript::SIV:
3488 case Subscript::RDIV:
3489 case Subscript::MIV:
3492 llvm_unreachable("bad subscript classification");
3499 // test & propagate remaining RDIVs
3500 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3501 if (Pair[SJ].Classification == Subscript::RDIV) {
3502 DEBUG(dbgs() << "RDIV test\n");
3503 if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3505 // I don't yet understand how to propagate RDIV results
3510 // test remaining MIVs
3511 // This code is temporary.
3512 // Better to somehow test all remaining subscripts simultaneously.
3513 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3514 if (Pair[SJ].Classification == Subscript::MIV) {
3515 DEBUG(dbgs() << "MIV test\n");
3516 if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
3520 llvm_unreachable("expected only MIV subscripts at this point");
3523 // update Result.DV from constraint vector
3524 DEBUG(dbgs() << " updating\n");
3525 for (int SJ = ConstrainedLevels.find_first();
3526 SJ >= 0; SJ = ConstrainedLevels.find_next(SJ)) {
3527 updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
3528 if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
3534 // make sure Scalar flags are set correctly
3535 SmallBitVector CompleteLoops(MaxLevels + 1);
3536 for (unsigned SI = 0; SI < Pairs; ++SI)
3537 CompleteLoops |= Pair[SI].Loops;
3538 for (unsigned II = 1; II <= CommonLevels; ++II)
3539 if (CompleteLoops[II])
3540 Result.DV[II - 1].Scalar = false;
3542 // make sure loopIndepent flag is set correctly
3543 if (PossiblyLoopIndependent) {
3544 for (unsigned II = 1; II <= CommonLevels; ++II) {
3545 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3546 Result.LoopIndependent = false;
3552 FullDependence *Final = new FullDependence(Result);
3559 //===----------------------------------------------------------------------===//
3560 // getSplitIteration -
3561 // Rather than spend rarely-used space recording the splitting iteration
3562 // during the Weak-Crossing SIV test, we re-compute it on demand.
3563 // The re-computation is basically a repeat of the entire dependence test,
3564 // though simplified since we know that the dependence exists.
3565 // It's tedious, since we must go through all propagations, etc.
3567 // Care is required to keep this code up to date w.r.t. the code above.
3569 // Generally, the dependence analyzer will be used to build
3570 // a dependence graph for a function (basically a map from instructions
3571 // to dependences). Looking for cycles in the graph shows us loops
3572 // that cannot be trivially vectorized/parallelized.
3574 // We can try to improve the situation by examining all the dependences
3575 // that make up the cycle, looking for ones we can break.
3576 // Sometimes, peeling the first or last iteration of a loop will break
3577 // dependences, and we've got flags for those possibilities.
3578 // Sometimes, splitting a loop at some other iteration will do the trick,
3579 // and we've got a flag for that case. Rather than waste the space to
3580 // record the exact iteration (since we rarely know), we provide
3581 // a method that calculates the iteration. It's a drag that it must work
3582 // from scratch, but wonderful in that it's possible.
3584 // Here's an example:
3586 // for (i = 0; i < 10; i++)
3590 // There's a loop-carried flow dependence from the store to the load,
3591 // found by the weak-crossing SIV test. The dependence will have a flag,
3592 // indicating that the dependence can be broken by splitting the loop.
3593 // Calling getSplitIteration will return 5.
3594 // Splitting the loop breaks the dependence, like so:
3596 // for (i = 0; i <= 5; i++)
3599 // for (i = 6; i < 10; i++)
3603 // breaks the dependence and allows us to vectorize/parallelize
3605 const SCEV *DependenceAnalysis::getSplitIteration(const Dependence *Dep,
3606 unsigned SplitLevel) {
3607 assert(Dep && "expected a pointer to a Dependence");
3608 assert(Dep->isSplitable(SplitLevel) &&
3609 "Dep should be splitable at SplitLevel");
3610 const Instruction *Src = Dep->getSrc();
3611 const Instruction *Dst = Dep->getDst();
3612 assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
3613 assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
3614 assert(isLoadOrStore(Src));
3615 assert(isLoadOrStore(Dst));
3616 const Value *SrcPtr = getPointerOperand(Src);
3617 const Value *DstPtr = getPointerOperand(Dst);
3618 assert(underlyingObjectsAlias(AA, DstPtr, SrcPtr) ==
3619 AliasAnalysis::MustAlias);
3620 const GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr);
3621 const GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr);
3624 assert(SrcGEP->getPointerOperandType() == DstGEP->getPointerOperandType());
3626 // establish loop nesting levels
3627 establishNestingLevels(Src, Dst);
3629 FullDependence Result(Src, Dst, false, CommonLevels);
3631 // classify subscript pairs
3632 unsigned Pairs = SrcGEP->idx_end() - SrcGEP->idx_begin();
3633 SmallVector<Subscript, 4> Pair(Pairs);
3634 for (unsigned SI = 0; SI < Pairs; ++SI) {
3635 Pair[SI].Loops.resize(MaxLevels + 1);
3636 Pair[SI].GroupLoops.resize(MaxLevels + 1);
3637 Pair[SI].Group.resize(Pairs);
3640 for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(),
3641 SrcEnd = SrcGEP->idx_end(),
3642 DstIdx = DstGEP->idx_begin(),
3643 DstEnd = DstGEP->idx_end();
3644 SrcIdx != SrcEnd && DstIdx != DstEnd;
3645 ++SrcIdx, ++DstIdx, ++Pairs) {
3646 Pair[Pairs].Src = SE->getSCEV(*SrcIdx);
3647 Pair[Pairs].Dst = SE->getSCEV(*DstIdx);
3648 Pair[Pairs].Classification =
3649 classifyPair(Pair[Pairs].Src, LI->getLoopFor(Src->getParent()),
3650 Pair[Pairs].Dst, LI->getLoopFor(Dst->getParent()),
3652 Pair[Pairs].GroupLoops = Pair[Pairs].Loops;
3653 Pair[Pairs].Group.set(Pairs);
3656 SmallBitVector Separable(Pairs);
3657 SmallBitVector Coupled(Pairs);
3659 // partition subscripts into separable and minimally-coupled groups
3660 for (unsigned SI = 0; SI < Pairs; ++SI) {
3661 if (Pair[SI].Classification == Subscript::NonLinear) {
3662 // ignore these, but collect loops for later
3663 collectCommonLoops(Pair[SI].Src,
3664 LI->getLoopFor(Src->getParent()),
3666 collectCommonLoops(Pair[SI].Dst,
3667 LI->getLoopFor(Dst->getParent()),
3669 Result.Consistent = false;
3671 else if (Pair[SI].Classification == Subscript::ZIV)
3674 // SIV, RDIV, or MIV, so check for coupled group
3676 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3677 SmallBitVector Intersection = Pair[SI].GroupLoops;
3678 Intersection &= Pair[SJ].GroupLoops;
3679 if (Intersection.any()) {
3680 // accumulate set of all the loops in group
3681 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3682 // accumulate set of all subscripts in group
3683 Pair[SJ].Group |= Pair[SI].Group;
3688 if (Pair[SI].Group.count() == 1)
3696 Constraint NewConstraint;
3697 NewConstraint.setAny(SE);
3699 // test separable subscripts
3700 for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) {
3701 switch (Pair[SI].Classification) {
3702 case Subscript::SIV: {
3704 const SCEV *SplitIter = NULL;
3705 (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
3706 Result, NewConstraint, SplitIter);
3707 if (Level == SplitLevel) {
3708 assert(SplitIter != NULL);
3713 case Subscript::ZIV:
3714 case Subscript::RDIV:
3715 case Subscript::MIV:
3718 llvm_unreachable("subscript has unexpected classification");
3722 if (Coupled.count()) {
3723 // test coupled subscript groups
3724 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3725 for (unsigned II = 0; II <= MaxLevels; ++II)
3726 Constraints[II].setAny(SE);
3727 for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) {
3728 SmallBitVector Group(Pair[SI].Group);
3729 SmallBitVector Sivs(Pairs);
3730 SmallBitVector Mivs(Pairs);
3731 SmallBitVector ConstrainedLevels(MaxLevels + 1);
3732 for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) {
3733 if (Pair[SJ].Classification == Subscript::SIV)
3738 while (Sivs.any()) {
3739 bool Changed = false;
3740 for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
3741 // SJ is an SIV subscript that's part of the current coupled group
3743 const SCEV *SplitIter = NULL;
3744 (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
3745 Result, NewConstraint, SplitIter);
3746 if (Level == SplitLevel && SplitIter)
3748 ConstrainedLevels.set(Level);
3749 if (intersectConstraints(&Constraints[Level], &NewConstraint))
3754 // propagate, possibly creating new SIVs and ZIVs
3755 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3756 // SJ is an MIV subscript that's part of the current coupled group
3757 if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
3758 Pair[SJ].Loops, Constraints, Result.Consistent)) {
3759 Pair[SJ].Classification =
3760 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3761 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3763 switch (Pair[SJ].Classification) {
3764 case Subscript::ZIV:
3767 case Subscript::SIV:
3771 case Subscript::RDIV:
3772 case Subscript::MIV:
3775 llvm_unreachable("bad subscript classification");
3783 llvm_unreachable("somehow reached end of routine");