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 loads and stores.
149 // Calls depends() on every possible pair and prints out the result.
150 // Ignores all other instructions.
152 void dumpExampleDependence(raw_ostream &OS, Function *F,
153 DependenceAnalysis *DA) {
154 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F);
155 SrcI != SrcE; ++SrcI) {
156 if (isa<StoreInst>(*SrcI) || isa<LoadInst>(*SrcI)) {
157 for (inst_iterator DstI = SrcI, DstE = inst_end(F);
158 DstI != DstE; ++DstI) {
159 if (isa<StoreInst>(*DstI) || isa<LoadInst>(*DstI)) {
160 OS << "da analyze - ";
161 if (Dependence *D = DA->depends(&*SrcI, &*DstI, true)) {
163 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
164 if (D->isSplitable(Level)) {
165 OS << "da analyze - split level = " << Level;
166 OS << ", iteration = " << *DA->getSplitIteration(D, Level);
181 void DependenceAnalysis::print(raw_ostream &OS, const Module*) const {
182 dumpExampleDependence(OS, F, const_cast<DependenceAnalysis *>(this));
185 //===----------------------------------------------------------------------===//
186 // Dependence methods
188 // Returns true if this is an input dependence.
189 bool Dependence::isInput() const {
190 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
194 // Returns true if this is an output dependence.
195 bool Dependence::isOutput() const {
196 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
200 // Returns true if this is an flow (aka true) dependence.
201 bool Dependence::isFlow() const {
202 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
206 // Returns true if this is an anti dependence.
207 bool Dependence::isAnti() const {
208 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
212 // Returns true if a particular level is scalar; that is,
213 // if no subscript in the source or destination mention the induction
214 // variable associated with the loop at this level.
215 // Leave this out of line, so it will serve as a virtual method anchor
216 bool Dependence::isScalar(unsigned level) const {
221 //===----------------------------------------------------------------------===//
222 // FullDependence methods
224 FullDependence::FullDependence(Instruction *Source,
225 Instruction *Destination,
226 bool PossiblyLoopIndependent,
227 unsigned CommonLevels) :
228 Dependence(Source, Destination),
229 Levels(CommonLevels),
230 LoopIndependent(PossiblyLoopIndependent) {
232 DV = CommonLevels ? new DVEntry[CommonLevels] : NULL;
235 // The rest are simple getters that hide the implementation.
237 // getDirection - Returns the direction associated with a particular level.
238 unsigned FullDependence::getDirection(unsigned Level) const {
239 assert(0 < Level && Level <= Levels && "Level out of range");
240 return DV[Level - 1].Direction;
244 // Returns the distance (or NULL) associated with a particular level.
245 const SCEV *FullDependence::getDistance(unsigned Level) const {
246 assert(0 < Level && Level <= Levels && "Level out of range");
247 return DV[Level - 1].Distance;
251 // Returns true if a particular level is scalar; that is,
252 // if no subscript in the source or destination mention the induction
253 // variable associated with the loop at this level.
254 bool FullDependence::isScalar(unsigned Level) const {
255 assert(0 < Level && Level <= Levels && "Level out of range");
256 return DV[Level - 1].Scalar;
260 // Returns true if peeling the first iteration from this loop
261 // will break this dependence.
262 bool FullDependence::isPeelFirst(unsigned Level) const {
263 assert(0 < Level && Level <= Levels && "Level out of range");
264 return DV[Level - 1].PeelFirst;
268 // Returns true if peeling the last iteration from this loop
269 // will break this dependence.
270 bool FullDependence::isPeelLast(unsigned Level) const {
271 assert(0 < Level && Level <= Levels && "Level out of range");
272 return DV[Level - 1].PeelLast;
276 // Returns true if splitting this loop will break the dependence.
277 bool FullDependence::isSplitable(unsigned Level) const {
278 assert(0 < Level && Level <= Levels && "Level out of range");
279 return DV[Level - 1].Splitable;
283 //===----------------------------------------------------------------------===//
284 // DependenceAnalysis::Constraint methods
286 // If constraint is a point <X, Y>, returns X.
288 const SCEV *DependenceAnalysis::Constraint::getX() const {
289 assert(Kind == Point && "Kind should be Point");
294 // If constraint is a point <X, Y>, returns Y.
296 const SCEV *DependenceAnalysis::Constraint::getY() const {
297 assert(Kind == Point && "Kind should be Point");
302 // If constraint is a line AX + BY = C, returns A.
304 const SCEV *DependenceAnalysis::Constraint::getA() const {
305 assert((Kind == Line || Kind == Distance) &&
306 "Kind should be Line (or Distance)");
311 // If constraint is a line AX + BY = C, returns B.
313 const SCEV *DependenceAnalysis::Constraint::getB() const {
314 assert((Kind == Line || Kind == Distance) &&
315 "Kind should be Line (or Distance)");
320 // If constraint is a line AX + BY = C, returns C.
322 const SCEV *DependenceAnalysis::Constraint::getC() const {
323 assert((Kind == Line || Kind == Distance) &&
324 "Kind should be Line (or Distance)");
329 // If constraint is a distance, returns D.
331 const SCEV *DependenceAnalysis::Constraint::getD() const {
332 assert(Kind == Distance && "Kind should be Distance");
333 return SE->getNegativeSCEV(C);
337 // Returns the loop associated with this constraint.
338 const Loop *DependenceAnalysis::Constraint::getAssociatedLoop() const {
339 assert((Kind == Distance || Kind == Line || Kind == Point) &&
340 "Kind should be Distance, Line, or Point");
341 return AssociatedLoop;
345 void DependenceAnalysis::Constraint::setPoint(const SCEV *X,
347 const Loop *CurLoop) {
351 AssociatedLoop = CurLoop;
355 void DependenceAnalysis::Constraint::setLine(const SCEV *AA,
358 const Loop *CurLoop) {
363 AssociatedLoop = CurLoop;
367 void DependenceAnalysis::Constraint::setDistance(const SCEV *D,
368 const Loop *CurLoop) {
370 A = SE->getConstant(D->getType(), 1);
371 B = SE->getNegativeSCEV(A);
372 C = SE->getNegativeSCEV(D);
373 AssociatedLoop = CurLoop;
377 void DependenceAnalysis::Constraint::setEmpty() {
382 void DependenceAnalysis::Constraint::setAny(ScalarEvolution *NewSE) {
388 // For debugging purposes. Dumps the constraint out to OS.
389 void DependenceAnalysis::Constraint::dump(raw_ostream &OS) const {
395 OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
396 else if (isDistance())
397 OS << " Distance is " << *getD() <<
398 " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
400 OS << " Line is " << *getA() << "*X + " <<
401 *getB() << "*Y = " << *getC() << "\n";
403 llvm_unreachable("unknown constraint type in Constraint::dump");
407 // Updates X with the intersection
408 // of the Constraints X and Y. Returns true if X has changed.
409 // Corresponds to Figure 4 from the paper
411 // Practical Dependence Testing
412 // Goff, Kennedy, Tseng
414 bool DependenceAnalysis::intersectConstraints(Constraint *X,
415 const Constraint *Y) {
417 DEBUG(dbgs() << "\tintersect constraints\n");
418 DEBUG(dbgs() << "\t X ="; X->dump(dbgs()));
419 DEBUG(dbgs() << "\t Y ="; Y->dump(dbgs()));
420 assert(!Y->isPoint() && "Y must not be a Point");
434 if (X->isDistance() && Y->isDistance()) {
435 DEBUG(dbgs() << "\t intersect 2 distances\n");
436 if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
438 if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
443 // Hmmm, interesting situation.
444 // I guess if either is constant, keep it and ignore the other.
445 if (isa<SCEVConstant>(Y->getD())) {
452 // At this point, the pseudo-code in Figure 4 of the paper
453 // checks if (X->isPoint() && Y->isPoint()).
454 // This case can't occur in our implementation,
455 // since a Point can only arise as the result of intersecting
456 // two Line constraints, and the right-hand value, Y, is never
457 // the result of an intersection.
458 assert(!(X->isPoint() && Y->isPoint()) &&
459 "We shouldn't ever see X->isPoint() && Y->isPoint()");
461 if (X->isLine() && Y->isLine()) {
462 DEBUG(dbgs() << "\t intersect 2 lines\n");
463 const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
464 const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
465 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
466 // slopes are equal, so lines are parallel
467 DEBUG(dbgs() << "\t\tsame slope\n");
468 Prod1 = SE->getMulExpr(X->getC(), Y->getB());
469 Prod2 = SE->getMulExpr(X->getB(), Y->getC());
470 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
472 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
479 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
480 // slopes differ, so lines intersect
481 DEBUG(dbgs() << "\t\tdifferent slopes\n");
482 const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
483 const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
484 const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
485 const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
486 const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
487 const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
488 const SCEVConstant *C1A2_C2A1 =
489 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
490 const SCEVConstant *C1B2_C2B1 =
491 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
492 const SCEVConstant *A1B2_A2B1 =
493 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
494 const SCEVConstant *A2B1_A1B2 =
495 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
496 if (!C1B2_C2B1 || !C1A2_C2A1 ||
497 !A1B2_A2B1 || !A2B1_A1B2)
499 APInt Xtop = C1B2_C2B1->getValue()->getValue();
500 APInt Xbot = A1B2_A2B1->getValue()->getValue();
501 APInt Ytop = C1A2_C2A1->getValue()->getValue();
502 APInt Ybot = A2B1_A1B2->getValue()->getValue();
503 DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
504 DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
505 DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
506 DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
507 APInt Xq = Xtop; // these need to be initialized, even
508 APInt Xr = Xtop; // though they're just going to be overwritten
509 APInt::sdivrem(Xtop, Xbot, Xq, Xr);
512 APInt::sdivrem(Ytop, Ybot, Yq, Yr);
513 if (Xr != 0 || Yr != 0) {
518 DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
519 if (Xq.slt(0) || Yq.slt(0)) {
524 if (const SCEVConstant *CUB =
525 collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
526 APInt UpperBound = CUB->getValue()->getValue();
527 DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
528 if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
534 X->setPoint(SE->getConstant(Xq),
536 X->getAssociatedLoop());
543 // if (X->isLine() && Y->isPoint()) This case can't occur.
544 assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
546 if (X->isPoint() && Y->isLine()) {
547 DEBUG(dbgs() << "\t intersect Point and Line\n");
548 const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
549 const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
550 const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
551 if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
553 if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
561 llvm_unreachable("shouldn't reach the end of Constraint intersection");
566 //===----------------------------------------------------------------------===//
567 // DependenceAnalysis methods
569 // For debugging purposes. Dumps a dependence to OS.
570 void Dependence::dump(raw_ostream &OS) const {
571 bool Splitable = false;
585 unsigned Levels = getLevels();
588 for (unsigned II = 1; II <= Levels; ++II) {
593 const SCEV *Distance = getDistance(II);
596 else if (isScalar(II))
599 unsigned Direction = getDirection(II);
600 if (Direction == DVEntry::ALL)
603 if (Direction & DVEntry::LT)
605 if (Direction & DVEntry::EQ)
607 if (Direction & DVEntry::GT)
616 if (isLoopIndependent())
629 AliasAnalysis::AliasResult underlyingObjectsAlias(AliasAnalysis *AA,
632 const Value *AObj = GetUnderlyingObject(A);
633 const Value *BObj = GetUnderlyingObject(B);
634 return AA->alias(AObj, AA->getTypeStoreSize(AObj->getType()),
635 BObj, AA->getTypeStoreSize(BObj->getType()));
639 // Returns true if the load or store can be analyzed. Atomic and volatile
640 // operations have properties which this analysis does not understand.
642 bool isLoadOrStore(const Instruction *I) {
643 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
644 return LI->isUnordered();
645 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
646 return SI->isUnordered();
652 Value *getPointerOperand(Instruction *I) {
653 if (LoadInst *LI = dyn_cast<LoadInst>(I))
654 return LI->getPointerOperand();
655 if (StoreInst *SI = dyn_cast<StoreInst>(I))
656 return SI->getPointerOperand();
657 llvm_unreachable("Value is not load or store instruction");
662 // Examines the loop nesting of the Src and Dst
663 // instructions and establishes their shared loops. Sets the variables
664 // CommonLevels, SrcLevels, and MaxLevels.
665 // The source and destination instructions needn't be contained in the same
666 // loop. The routine establishNestingLevels finds the level of most deeply
667 // nested loop that contains them both, CommonLevels. An instruction that's
668 // not contained in a loop is at level = 0. MaxLevels is equal to the level
669 // of the source plus the level of the destination, minus CommonLevels.
670 // This lets us allocate vectors MaxLevels in length, with room for every
671 // distinct loop referenced in both the source and destination subscripts.
672 // The variable SrcLevels is the nesting depth of the source instruction.
673 // It's used to help calculate distinct loops referenced by the destination.
674 // Here's the map from loops to levels:
676 // 1 - outermost common loop
677 // ... - other common loops
678 // CommonLevels - innermost common loop
679 // ... - loops containing Src but not Dst
680 // SrcLevels - innermost loop containing Src but not Dst
681 // ... - loops containing Dst but not Src
682 // MaxLevels - innermost loops containing Dst but not Src
683 // Consider the follow code fragment:
700 // If we're looking at the possibility of a dependence between the store
701 // to A (the Src) and the load from A (the Dst), we'll note that they
702 // have 2 loops in common, so CommonLevels will equal 2 and the direction
703 // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
704 // A map from loop names to loop numbers would look like
706 // b - 2 = CommonLevels
712 void DependenceAnalysis::establishNestingLevels(const Instruction *Src,
713 const Instruction *Dst) {
714 const BasicBlock *SrcBlock = Src->getParent();
715 const BasicBlock *DstBlock = Dst->getParent();
716 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
717 unsigned DstLevel = LI->getLoopDepth(DstBlock);
718 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
719 const Loop *DstLoop = LI->getLoopFor(DstBlock);
720 SrcLevels = SrcLevel;
721 MaxLevels = SrcLevel + DstLevel;
722 while (SrcLevel > DstLevel) {
723 SrcLoop = SrcLoop->getParentLoop();
726 while (DstLevel > SrcLevel) {
727 DstLoop = DstLoop->getParentLoop();
730 while (SrcLoop != DstLoop) {
731 SrcLoop = SrcLoop->getParentLoop();
732 DstLoop = DstLoop->getParentLoop();
735 CommonLevels = SrcLevel;
736 MaxLevels -= CommonLevels;
740 // Given one of the loops containing the source, return
741 // its level index in our numbering scheme.
742 unsigned DependenceAnalysis::mapSrcLoop(const Loop *SrcLoop) const {
743 return SrcLoop->getLoopDepth();
747 // Given one of the loops containing the destination,
748 // return its level index in our numbering scheme.
749 unsigned DependenceAnalysis::mapDstLoop(const Loop *DstLoop) const {
750 unsigned D = DstLoop->getLoopDepth();
751 if (D > CommonLevels)
752 return D - CommonLevels + SrcLevels;
758 // Returns true if Expression is loop invariant in LoopNest.
759 bool DependenceAnalysis::isLoopInvariant(const SCEV *Expression,
760 const Loop *LoopNest) const {
763 return SE->isLoopInvariant(Expression, LoopNest) &&
764 isLoopInvariant(Expression, LoopNest->getParentLoop());
769 // Finds the set of loops from the LoopNest that
770 // have a level <= CommonLevels and are referred to by the SCEV Expression.
771 void DependenceAnalysis::collectCommonLoops(const SCEV *Expression,
772 const Loop *LoopNest,
773 SmallBitVector &Loops) const {
775 unsigned Level = LoopNest->getLoopDepth();
776 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
778 LoopNest = LoopNest->getParentLoop();
783 // removeMatchingExtensions - Examines a subscript pair.
784 // If the source and destination are identically sign (or zero)
785 // extended, it strips off the extension in an effect to simplify
786 // the actual analysis.
787 void DependenceAnalysis::removeMatchingExtensions(Subscript *Pair) {
788 const SCEV *Src = Pair->Src;
789 const SCEV *Dst = Pair->Dst;
790 if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
791 (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
792 const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src);
793 const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst);
794 if (SrcCast->getType() == DstCast->getType()) {
795 Pair->Src = SrcCast->getOperand();
796 Pair->Dst = DstCast->getOperand();
802 // Examine the scev and return true iff it's linear.
803 // Collect any loops mentioned in the set of "Loops".
804 bool DependenceAnalysis::checkSrcSubscript(const SCEV *Src,
805 const Loop *LoopNest,
806 SmallBitVector &Loops) {
807 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Src);
809 return isLoopInvariant(Src, LoopNest);
810 const SCEV *Start = AddRec->getStart();
811 const SCEV *Step = AddRec->getStepRecurrence(*SE);
812 if (!isLoopInvariant(Step, LoopNest))
814 Loops.set(mapSrcLoop(AddRec->getLoop()));
815 return checkSrcSubscript(Start, LoopNest, Loops);
820 // Examine the scev and return true iff it's linear.
821 // Collect any loops mentioned in the set of "Loops".
822 bool DependenceAnalysis::checkDstSubscript(const SCEV *Dst,
823 const Loop *LoopNest,
824 SmallBitVector &Loops) {
825 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Dst);
827 return isLoopInvariant(Dst, LoopNest);
828 const SCEV *Start = AddRec->getStart();
829 const SCEV *Step = AddRec->getStepRecurrence(*SE);
830 if (!isLoopInvariant(Step, LoopNest))
832 Loops.set(mapDstLoop(AddRec->getLoop()));
833 return checkDstSubscript(Start, LoopNest, Loops);
837 // Examines the subscript pair (the Src and Dst SCEVs)
838 // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
839 // Collects the associated loops in a set.
840 DependenceAnalysis::Subscript::ClassificationKind
841 DependenceAnalysis::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
842 const SCEV *Dst, const Loop *DstLoopNest,
843 SmallBitVector &Loops) {
844 SmallBitVector SrcLoops(MaxLevels + 1);
845 SmallBitVector DstLoops(MaxLevels + 1);
846 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
847 return Subscript::NonLinear;
848 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
849 return Subscript::NonLinear;
852 unsigned N = Loops.count();
854 return Subscript::ZIV;
856 return Subscript::SIV;
857 if (N == 2 && (SrcLoops.count() == 0 ||
858 DstLoops.count() == 0 ||
859 (SrcLoops.count() == 1 && DstLoops.count() == 1)))
860 return Subscript::RDIV;
861 return Subscript::MIV;
865 // A wrapper around SCEV::isKnownPredicate.
866 // Looks for cases where we're interested in comparing for equality.
867 // If both X and Y have been identically sign or zero extended,
868 // it strips off the (confusing) extensions before invoking
869 // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
870 // will be similarly updated.
872 // If SCEV::isKnownPredicate can't prove the predicate,
873 // we try simple subtraction, which seems to help in some cases
874 // involving symbolics.
875 bool DependenceAnalysis::isKnownPredicate(ICmpInst::Predicate Pred,
877 const SCEV *Y) const {
878 if (Pred == CmpInst::ICMP_EQ ||
879 Pred == CmpInst::ICMP_NE) {
880 if ((isa<SCEVSignExtendExpr>(X) &&
881 isa<SCEVSignExtendExpr>(Y)) ||
882 (isa<SCEVZeroExtendExpr>(X) &&
883 isa<SCEVZeroExtendExpr>(Y))) {
884 const SCEVCastExpr *CX = cast<SCEVCastExpr>(X);
885 const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y);
886 const SCEV *Xop = CX->getOperand();
887 const SCEV *Yop = CY->getOperand();
888 if (Xop->getType() == Yop->getType()) {
894 if (SE->isKnownPredicate(Pred, X, Y))
896 // If SE->isKnownPredicate can't prove the condition,
897 // we try the brute-force approach of subtracting
898 // and testing the difference.
899 // By testing with SE->isKnownPredicate first, we avoid
900 // the possibility of overflow when the arguments are constants.
901 const SCEV *Delta = SE->getMinusSCEV(X, Y);
903 case CmpInst::ICMP_EQ:
904 return Delta->isZero();
905 case CmpInst::ICMP_NE:
906 return SE->isKnownNonZero(Delta);
907 case CmpInst::ICMP_SGE:
908 return SE->isKnownNonNegative(Delta);
909 case CmpInst::ICMP_SLE:
910 return SE->isKnownNonPositive(Delta);
911 case CmpInst::ICMP_SGT:
912 return SE->isKnownPositive(Delta);
913 case CmpInst::ICMP_SLT:
914 return SE->isKnownNegative(Delta);
916 llvm_unreachable("unexpected predicate in isKnownPredicate");
921 // All subscripts are all the same type.
922 // Loop bound may be smaller (e.g., a char).
923 // Should zero extend loop bound, since it's always >= 0.
924 // This routine collects upper bound and extends if needed.
925 // Return null if no bound available.
926 const SCEV *DependenceAnalysis::collectUpperBound(const Loop *L,
928 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
929 const SCEV *UB = SE->getBackedgeTakenCount(L);
930 return SE->getNoopOrZeroExtend(UB, T);
936 // Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
937 // If the cast fails, returns NULL.
938 const SCEVConstant *DependenceAnalysis::collectConstantUpperBound(const Loop *L,
941 if (const SCEV *UB = collectUpperBound(L, T))
942 return dyn_cast<SCEVConstant>(UB);
948 // When we have a pair of subscripts of the form [c1] and [c2],
949 // where c1 and c2 are both loop invariant, we attack it using
950 // the ZIV test. Basically, we test by comparing the two values,
951 // but there are actually three possible results:
952 // 1) the values are equal, so there's a dependence
953 // 2) the values are different, so there's no dependence
954 // 3) the values might be equal, so we have to assume a dependence.
956 // Return true if dependence disproved.
957 bool DependenceAnalysis::testZIV(const SCEV *Src,
959 FullDependence &Result) const {
960 DEBUG(dbgs() << " src = " << *Src << "\n");
961 DEBUG(dbgs() << " dst = " << *Dst << "\n");
963 if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
964 DEBUG(dbgs() << " provably dependent\n");
965 return false; // provably dependent
967 if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
968 DEBUG(dbgs() << " provably independent\n");
970 return true; // provably independent
972 DEBUG(dbgs() << " possibly dependent\n");
973 Result.Consistent = false;
974 return false; // possibly dependent
979 // From the paper, Practical Dependence Testing, Section 4.2.1
981 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
982 // where i is an induction variable, c1 and c2 are loop invariant,
983 // and a is a constant, we can solve it exactly using the Strong SIV test.
985 // Can prove independence. Failing that, can compute distance (and direction).
986 // In the presence of symbolic terms, we can sometimes make progress.
988 // If there's a dependence,
990 // c1 + a*i = c2 + a*i'
992 // The dependence distance is
994 // d = i' - i = (c1 - c2)/a
996 // A dependence only exists if d is an integer and abs(d) <= U, where U is the
997 // loop's upper bound. If a dependence exists, the dependence direction is
1001 // direction = { = if d = 0
1004 // Return true if dependence disproved.
1005 bool DependenceAnalysis::strongSIVtest(const SCEV *Coeff,
1006 const SCEV *SrcConst,
1007 const SCEV *DstConst,
1008 const Loop *CurLoop,
1010 FullDependence &Result,
1011 Constraint &NewConstraint) const {
1012 DEBUG(dbgs() << "\tStrong SIV test\n");
1013 DEBUG(dbgs() << "\t Coeff = " << *Coeff);
1014 DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1015 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
1016 DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1017 DEBUG(dbgs() << "\t DstConst = " << *DstConst);
1018 DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
1019 ++StrongSIVapplications;
1020 assert(0 < Level && Level <= CommonLevels && "level out of range");
1023 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1024 DEBUG(dbgs() << "\t Delta = " << *Delta);
1025 DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
1027 // check that |Delta| < iteration count
1028 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1029 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound);
1030 DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
1031 const SCEV *AbsDelta =
1032 SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
1033 const SCEV *AbsCoeff =
1034 SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
1035 const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
1036 if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
1037 // Distance greater than trip count - no dependence
1038 ++StrongSIVindependence;
1039 ++StrongSIVsuccesses;
1044 // Can we compute distance?
1045 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
1046 APInt ConstDelta = cast<SCEVConstant>(Delta)->getValue()->getValue();
1047 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getValue()->getValue();
1048 APInt Distance = ConstDelta; // these need to be initialized
1049 APInt Remainder = ConstDelta;
1050 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
1051 DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1052 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1053 // Make sure Coeff divides Delta exactly
1054 if (Remainder != 0) {
1055 // Coeff doesn't divide Distance, no dependence
1056 ++StrongSIVindependence;
1057 ++StrongSIVsuccesses;
1060 Result.DV[Level].Distance = SE->getConstant(Distance);
1061 NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
1062 if (Distance.sgt(0))
1063 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1064 else if (Distance.slt(0))
1065 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1067 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1068 ++StrongSIVsuccesses;
1070 else if (Delta->isZero()) {
1072 Result.DV[Level].Distance = Delta;
1073 NewConstraint.setDistance(Delta, CurLoop);
1074 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1075 ++StrongSIVsuccesses;
1078 if (Coeff->isOne()) {
1079 DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
1080 Result.DV[Level].Distance = Delta; // since X/1 == X
1081 NewConstraint.setDistance(Delta, CurLoop);
1084 Result.Consistent = false;
1085 NewConstraint.setLine(Coeff,
1086 SE->getNegativeSCEV(Coeff),
1087 SE->getNegativeSCEV(Delta), CurLoop);
1090 // maybe we can get a useful direction
1091 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
1092 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1093 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1094 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1095 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1096 // The double negatives above are confusing.
1097 // It helps to read !SE->isKnownNonZero(Delta)
1098 // as "Delta might be Zero"
1099 unsigned NewDirection = Dependence::DVEntry::NONE;
1100 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1101 (DeltaMaybeNegative && CoeffMaybeNegative))
1102 NewDirection = Dependence::DVEntry::LT;
1104 NewDirection |= Dependence::DVEntry::EQ;
1105 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1106 (DeltaMaybePositive && CoeffMaybeNegative))
1107 NewDirection |= Dependence::DVEntry::GT;
1108 if (NewDirection < Result.DV[Level].Direction)
1109 ++StrongSIVsuccesses;
1110 Result.DV[Level].Direction &= NewDirection;
1116 // weakCrossingSIVtest -
1117 // From the paper, Practical Dependence Testing, Section 4.2.2
1119 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1120 // where i is an induction variable, c1 and c2 are loop invariant,
1121 // and a is a constant, we can solve it exactly using the
1122 // Weak-Crossing SIV test.
1124 // Given c1 + a*i = c2 - a*i', we can look for the intersection of
1125 // the two lines, where i = i', yielding
1127 // c1 + a*i = c2 - a*i
1131 // If i < 0, there is no dependence.
1132 // If i > upperbound, there is no dependence.
1133 // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1134 // If i = upperbound, there's a dependence with distance = 0.
1135 // If i is integral, there's a dependence (all directions).
1136 // If the non-integer part = 1/2, there's a dependence (<> directions).
1137 // Otherwise, there's no dependence.
1139 // Can prove independence. Failing that,
1140 // can sometimes refine the directions.
1141 // Can determine iteration for splitting.
1143 // Return true if dependence disproved.
1144 bool DependenceAnalysis::weakCrossingSIVtest(const SCEV *Coeff,
1145 const SCEV *SrcConst,
1146 const SCEV *DstConst,
1147 const Loop *CurLoop,
1149 FullDependence &Result,
1150 Constraint &NewConstraint,
1151 const SCEV *&SplitIter) const {
1152 DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1153 DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1154 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1155 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1156 ++WeakCrossingSIVapplications;
1157 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1159 Result.Consistent = false;
1160 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1161 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1162 NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
1163 if (Delta->isZero()) {
1164 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1165 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1166 ++WeakCrossingSIVsuccesses;
1167 if (!Result.DV[Level].Direction) {
1168 ++WeakCrossingSIVindependence;
1171 Result.DV[Level].Distance = Delta; // = 0
1174 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1178 Result.DV[Level].Splitable = true;
1179 if (SE->isKnownNegative(ConstCoeff)) {
1180 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1181 assert(ConstCoeff &&
1182 "dynamic cast of negative of ConstCoeff should yield constant");
1183 Delta = SE->getNegativeSCEV(Delta);
1185 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1187 // compute SplitIter for use by DependenceAnalysis::getSplitIteration()
1189 SE->getUDivExpr(SE->getSMaxExpr(SE->getConstant(Delta->getType(), 0),
1191 SE->getMulExpr(SE->getConstant(Delta->getType(), 2),
1193 DEBUG(dbgs() << "\t Split iter = " << *SplitIter << "\n");
1195 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1199 // We're certain that ConstCoeff > 0; therefore,
1200 // if Delta < 0, then no dependence.
1201 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1202 DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
1203 if (SE->isKnownNegative(Delta)) {
1204 // No dependence, Delta < 0
1205 ++WeakCrossingSIVindependence;
1206 ++WeakCrossingSIVsuccesses;
1210 // We're certain that Delta > 0 and ConstCoeff > 0.
1211 // Check Delta/(2*ConstCoeff) against upper loop bound
1212 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1213 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1214 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1215 const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
1217 DEBUG(dbgs() << "\t ML = " << *ML << "\n");
1218 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1219 // Delta too big, no dependence
1220 ++WeakCrossingSIVindependence;
1221 ++WeakCrossingSIVsuccesses;
1224 if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1226 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1227 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1228 ++WeakCrossingSIVsuccesses;
1229 if (!Result.DV[Level].Direction) {
1230 ++WeakCrossingSIVindependence;
1233 Result.DV[Level].Splitable = false;
1234 Result.DV[Level].Distance = SE->getConstant(Delta->getType(), 0);
1239 // check that Coeff divides Delta
1240 APInt APDelta = ConstDelta->getValue()->getValue();
1241 APInt APCoeff = ConstCoeff->getValue()->getValue();
1242 APInt Distance = APDelta; // these need to be initialzed
1243 APInt Remainder = APDelta;
1244 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1245 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1246 if (Remainder != 0) {
1247 // Coeff doesn't divide Delta, no dependence
1248 ++WeakCrossingSIVindependence;
1249 ++WeakCrossingSIVsuccesses;
1252 DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1254 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1255 APInt Two = APInt(Distance.getBitWidth(), 2, true);
1256 Remainder = Distance.srem(Two);
1257 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1258 if (Remainder != 0) {
1259 // Equal direction isn't possible
1260 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
1261 ++WeakCrossingSIVsuccesses;
1267 // Kirch's algorithm, from
1269 // Optimizing Supercompilers for Supercomputers
1273 // Program 2.1, page 29.
1274 // Computes the GCD of AM and BM.
1275 // Also finds a solution to the equation ax - by = gdc(a, b).
1276 // Returns true iff the gcd divides Delta.
1278 bool findGCD(unsigned Bits, APInt AM, APInt BM, APInt Delta,
1279 APInt &G, APInt &X, APInt &Y) {
1280 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1281 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1282 APInt G0 = AM.abs();
1283 APInt G1 = BM.abs();
1284 APInt Q = G0; // these need to be initialized
1286 APInt::sdivrem(G0, G1, Q, R);
1288 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1289 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1291 APInt::sdivrem(G0, G1, Q, R);
1294 DEBUG(dbgs() << "\t GCD = " << G << "\n");
1295 X = AM.slt(0) ? -A1 : A1;
1296 Y = BM.slt(0) ? B1 : -B1;
1298 // make sure gcd divides Delta
1301 return true; // gcd doesn't divide Delta, no dependence
1310 APInt floorOfQuotient(APInt A, APInt B) {
1311 APInt Q = A; // these need to be initialized
1313 APInt::sdivrem(A, B, Q, R);
1316 if ((A.sgt(0) && B.sgt(0)) ||
1317 (A.slt(0) && B.slt(0)))
1325 APInt ceilingOfQuotient(APInt A, APInt B) {
1326 APInt Q = A; // these need to be initialized
1328 APInt::sdivrem(A, B, Q, R);
1331 if ((A.sgt(0) && B.sgt(0)) ||
1332 (A.slt(0) && B.slt(0)))
1340 APInt maxAPInt(APInt A, APInt B) {
1341 return A.sgt(B) ? A : B;
1346 APInt minAPInt(APInt A, APInt B) {
1347 return A.slt(B) ? A : B;
1352 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1353 // where i is an induction variable, c1 and c2 are loop invariant, and a1
1354 // and a2 are constant, we can solve it exactly using an algorithm developed
1355 // by Banerjee and Wolfe. See Section 2.5.3 in
1357 // Optimizing Supercompilers for Supercomputers
1361 // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1362 // so use them if possible. They're also a bit better with symbolics and,
1363 // in the case of the strong SIV test, can compute Distances.
1365 // Return true if dependence disproved.
1366 bool DependenceAnalysis::exactSIVtest(const SCEV *SrcCoeff,
1367 const SCEV *DstCoeff,
1368 const SCEV *SrcConst,
1369 const SCEV *DstConst,
1370 const Loop *CurLoop,
1372 FullDependence &Result,
1373 Constraint &NewConstraint) const {
1374 DEBUG(dbgs() << "\tExact SIV test\n");
1375 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1376 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1377 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1378 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1379 ++ExactSIVapplications;
1380 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1382 Result.Consistent = false;
1383 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1384 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1385 NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff),
1387 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1388 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1389 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1390 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1395 APInt AM = ConstSrcCoeff->getValue()->getValue();
1396 APInt BM = ConstDstCoeff->getValue()->getValue();
1397 unsigned Bits = AM.getBitWidth();
1398 if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) {
1399 // gcd doesn't divide Delta, no dependence
1400 ++ExactSIVindependence;
1401 ++ExactSIVsuccesses;
1405 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1407 // since SCEV construction normalizes, LM = 0
1408 APInt UM(Bits, 1, true);
1409 bool UMvalid = false;
1410 // UM is perhaps unavailable, let's check
1411 if (const SCEVConstant *CUB =
1412 collectConstantUpperBound(CurLoop, Delta->getType())) {
1413 UM = CUB->getValue()->getValue();
1414 DEBUG(dbgs() << "\t UM = " << UM << "\n");
1418 APInt TU(APInt::getSignedMaxValue(Bits));
1419 APInt TL(APInt::getSignedMinValue(Bits));
1421 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1422 APInt TMUL = BM.sdiv(G);
1424 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1425 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1427 TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL));
1428 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1432 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1433 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1435 TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL));
1436 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1440 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1443 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1444 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1446 TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL));
1447 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1451 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1452 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1454 TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL));
1455 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1459 ++ExactSIVindependence;
1460 ++ExactSIVsuccesses;
1464 // explore directions
1465 unsigned NewDirection = Dependence::DVEntry::NONE;
1468 APInt SaveTU(TU); // save these
1470 DEBUG(dbgs() << "\t exploring LT direction\n");
1473 TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL));
1474 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1477 TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL));
1478 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1481 NewDirection |= Dependence::DVEntry::LT;
1482 ++ExactSIVsuccesses;
1486 TU = SaveTU; // restore
1488 DEBUG(dbgs() << "\t exploring EQ direction\n");
1490 TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL));
1491 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1494 TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL));
1495 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1499 TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL));
1500 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1503 TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL));
1504 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1507 NewDirection |= Dependence::DVEntry::EQ;
1508 ++ExactSIVsuccesses;
1512 TU = SaveTU; // restore
1514 DEBUG(dbgs() << "\t exploring GT direction\n");
1516 TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL));
1517 DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
1520 TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL));
1521 DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
1524 NewDirection |= Dependence::DVEntry::GT;
1525 ++ExactSIVsuccesses;
1529 Result.DV[Level].Direction &= NewDirection;
1530 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1531 ++ExactSIVindependence;
1532 return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1537 // Return true if the divisor evenly divides the dividend.
1539 bool isRemainderZero(const SCEVConstant *Dividend,
1540 const SCEVConstant *Divisor) {
1541 APInt ConstDividend = Dividend->getValue()->getValue();
1542 APInt ConstDivisor = Divisor->getValue()->getValue();
1543 return ConstDividend.srem(ConstDivisor) == 0;
1547 // weakZeroSrcSIVtest -
1548 // From the paper, Practical Dependence Testing, Section 4.2.2
1550 // When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1551 // where i is an induction variable, c1 and c2 are loop invariant,
1552 // and a is a constant, we can solve it exactly using the
1553 // Weak-Zero SIV test.
1563 // If i is not an integer, there's no dependence.
1564 // If i < 0 or > UB, there's no dependence.
1565 // If i = 0, the direction is <= and peeling the
1566 // 1st iteration will break the dependence.
1567 // If i = UB, the direction is >= and peeling the
1568 // last iteration will break the dependence.
1569 // Otherwise, the direction is *.
1571 // Can prove independence. Failing that, we can sometimes refine
1572 // the directions. Can sometimes show that first or last
1573 // iteration carries all the dependences (so worth peeling).
1575 // (see also weakZeroDstSIVtest)
1577 // Return true if dependence disproved.
1578 bool DependenceAnalysis::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1579 const SCEV *SrcConst,
1580 const SCEV *DstConst,
1581 const Loop *CurLoop,
1583 FullDependence &Result,
1584 Constraint &NewConstraint) const {
1585 // For the WeakSIV test, it's possible the loop isn't common to
1586 // the Src and Dst loops. If it isn't, then there's no need to
1587 // record a direction.
1588 DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1589 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1590 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1591 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1592 ++WeakZeroSIVapplications;
1593 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1595 Result.Consistent = false;
1596 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1597 NewConstraint.setLine(SE->getConstant(Delta->getType(), 0),
1598 DstCoeff, Delta, CurLoop);
1599 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1600 if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
1601 if (Level < CommonLevels) {
1602 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1603 Result.DV[Level].PeelFirst = true;
1604 ++WeakZeroSIVsuccesses;
1606 return false; // dependences caused by first iteration
1608 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1611 const SCEV *AbsCoeff =
1612 SE->isKnownNegative(ConstCoeff) ?
1613 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1614 const SCEV *NewDelta =
1615 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1617 // check that Delta/SrcCoeff < iteration count
1618 // really check NewDelta < count*AbsCoeff
1619 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1620 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1621 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1622 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1623 ++WeakZeroSIVindependence;
1624 ++WeakZeroSIVsuccesses;
1627 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1628 // dependences caused by last iteration
1629 if (Level < CommonLevels) {
1630 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1631 Result.DV[Level].PeelLast = true;
1632 ++WeakZeroSIVsuccesses;
1638 // check that Delta/SrcCoeff >= 0
1639 // really check that NewDelta >= 0
1640 if (SE->isKnownNegative(NewDelta)) {
1641 // No dependence, newDelta < 0
1642 ++WeakZeroSIVindependence;
1643 ++WeakZeroSIVsuccesses;
1647 // if SrcCoeff doesn't divide Delta, then no dependence
1648 if (isa<SCEVConstant>(Delta) &&
1649 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1650 ++WeakZeroSIVindependence;
1651 ++WeakZeroSIVsuccesses;
1658 // weakZeroDstSIVtest -
1659 // From the paper, Practical Dependence Testing, Section 4.2.2
1661 // When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1662 // where i is an induction variable, c1 and c2 are loop invariant,
1663 // and a is a constant, we can solve it exactly using the
1664 // Weak-Zero SIV test.
1674 // If i is not an integer, there's no dependence.
1675 // If i < 0 or > UB, there's no dependence.
1676 // If i = 0, the direction is <= and peeling the
1677 // 1st iteration will break the dependence.
1678 // If i = UB, the direction is >= and peeling the
1679 // last iteration will break the dependence.
1680 // Otherwise, the direction is *.
1682 // Can prove independence. Failing that, we can sometimes refine
1683 // the directions. Can sometimes show that first or last
1684 // iteration carries all the dependences (so worth peeling).
1686 // (see also weakZeroSrcSIVtest)
1688 // Return true if dependence disproved.
1689 bool DependenceAnalysis::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1690 const SCEV *SrcConst,
1691 const SCEV *DstConst,
1692 const Loop *CurLoop,
1694 FullDependence &Result,
1695 Constraint &NewConstraint) const {
1696 // For the WeakSIV test, it's possible the loop isn't common to the
1697 // Src and Dst loops. If it isn't, then there's no need to record a direction.
1698 DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1699 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1700 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1701 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1702 ++WeakZeroSIVapplications;
1703 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1705 Result.Consistent = false;
1706 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1707 NewConstraint.setLine(SrcCoeff, SE->getConstant(Delta->getType(), 0),
1709 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1710 if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
1711 if (Level < CommonLevels) {
1712 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1713 Result.DV[Level].PeelFirst = true;
1714 ++WeakZeroSIVsuccesses;
1716 return false; // dependences caused by first iteration
1718 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1721 const SCEV *AbsCoeff =
1722 SE->isKnownNegative(ConstCoeff) ?
1723 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1724 const SCEV *NewDelta =
1725 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1727 // check that Delta/SrcCoeff < iteration count
1728 // really check NewDelta < count*AbsCoeff
1729 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1730 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1731 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1732 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1733 ++WeakZeroSIVindependence;
1734 ++WeakZeroSIVsuccesses;
1737 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1738 // dependences caused by last iteration
1739 if (Level < CommonLevels) {
1740 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1741 Result.DV[Level].PeelLast = true;
1742 ++WeakZeroSIVsuccesses;
1748 // check that Delta/SrcCoeff >= 0
1749 // really check that NewDelta >= 0
1750 if (SE->isKnownNegative(NewDelta)) {
1751 // No dependence, newDelta < 0
1752 ++WeakZeroSIVindependence;
1753 ++WeakZeroSIVsuccesses;
1757 // if SrcCoeff doesn't divide Delta, then no dependence
1758 if (isa<SCEVConstant>(Delta) &&
1759 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1760 ++WeakZeroSIVindependence;
1761 ++WeakZeroSIVsuccesses;
1768 // exactRDIVtest - Tests the RDIV subscript pair for dependence.
1769 // Things of the form [c1 + a*i] and [c2 + b*j],
1770 // where i and j are induction variable, c1 and c2 are loop invariant,
1771 // and a and b are constants.
1772 // Returns true if any possible dependence is disproved.
1773 // Marks the result as inconsistent.
1774 // Works in some cases that symbolicRDIVtest doesn't, and vice versa.
1775 bool DependenceAnalysis::exactRDIVtest(const SCEV *SrcCoeff,
1776 const SCEV *DstCoeff,
1777 const SCEV *SrcConst,
1778 const SCEV *DstConst,
1779 const Loop *SrcLoop,
1780 const Loop *DstLoop,
1781 FullDependence &Result) const {
1782 DEBUG(dbgs() << "\tExact RDIV test\n");
1783 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1784 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1785 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1786 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1787 ++ExactRDIVapplications;
1788 Result.Consistent = false;
1789 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1790 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1791 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1792 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1793 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1794 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1799 APInt AM = ConstSrcCoeff->getValue()->getValue();
1800 APInt BM = ConstDstCoeff->getValue()->getValue();
1801 unsigned Bits = AM.getBitWidth();
1802 if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) {
1803 // gcd doesn't divide Delta, no dependence
1804 ++ExactRDIVindependence;
1808 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1810 // since SCEV construction seems to normalize, LM = 0
1811 APInt SrcUM(Bits, 1, true);
1812 bool SrcUMvalid = false;
1813 // SrcUM is perhaps unavailable, let's check
1814 if (const SCEVConstant *UpperBound =
1815 collectConstantUpperBound(SrcLoop, Delta->getType())) {
1816 SrcUM = UpperBound->getValue()->getValue();
1817 DEBUG(dbgs() << "\t SrcUM = " << SrcUM << "\n");
1821 APInt DstUM(Bits, 1, true);
1822 bool DstUMvalid = false;
1823 // UM is perhaps unavailable, let's check
1824 if (const SCEVConstant *UpperBound =
1825 collectConstantUpperBound(DstLoop, Delta->getType())) {
1826 DstUM = UpperBound->getValue()->getValue();
1827 DEBUG(dbgs() << "\t DstUM = " << DstUM << "\n");
1831 APInt TU(APInt::getSignedMaxValue(Bits));
1832 APInt TL(APInt::getSignedMinValue(Bits));
1834 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1835 APInt TMUL = BM.sdiv(G);
1837 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1838 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1840 TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL));
1841 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1845 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1846 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1848 TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL));
1849 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1853 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1856 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1857 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1859 TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL));
1860 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1864 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1865 DEBUG(dbgs() << "\t TU = " << TU << "\n");
1867 TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL));
1868 DEBUG(dbgs() << "\t TL = " << TL << "\n");
1872 ++ExactRDIVindependence;
1877 // symbolicRDIVtest -
1878 // In Section 4.5 of the Practical Dependence Testing paper,the authors
1879 // introduce a special case of Banerjee's Inequalities (also called the
1880 // Extreme-Value Test) that can handle some of the SIV and RDIV cases,
1881 // particularly cases with symbolics. Since it's only able to disprove
1882 // dependence (not compute distances or directions), we'll use it as a
1883 // fall back for the other tests.
1885 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
1886 // where i and j are induction variables and c1 and c2 are loop invariants,
1887 // we can use the symbolic tests to disprove some dependences, serving as a
1888 // backup for the RDIV test. Note that i and j can be the same variable,
1889 // letting this test serve as a backup for the various SIV tests.
1891 // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
1892 // 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
1893 // loop bounds for the i and j loops, respectively. So, ...
1895 // c1 + a1*i = c2 + a2*j
1896 // a1*i - a2*j = c2 - c1
1898 // To test for a dependence, we compute c2 - c1 and make sure it's in the
1899 // range of the maximum and minimum possible values of a1*i - a2*j.
1900 // Considering the signs of a1 and a2, we have 4 possible cases:
1902 // 1) If a1 >= 0 and a2 >= 0, then
1903 // a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
1904 // -a2*N2 <= c2 - c1 <= a1*N1
1906 // 2) If a1 >= 0 and a2 <= 0, then
1907 // a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
1908 // 0 <= c2 - c1 <= a1*N1 - a2*N2
1910 // 3) If a1 <= 0 and a2 >= 0, then
1911 // a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
1912 // a1*N1 - a2*N2 <= c2 - c1 <= 0
1914 // 4) If a1 <= 0 and a2 <= 0, then
1915 // a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
1916 // a1*N1 <= c2 - c1 <= -a2*N2
1918 // return true if dependence disproved
1919 bool DependenceAnalysis::symbolicRDIVtest(const SCEV *A1,
1924 const Loop *Loop2) const {
1925 ++SymbolicRDIVapplications;
1926 DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
1927 DEBUG(dbgs() << "\t A1 = " << *A1);
1928 DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
1929 DEBUG(dbgs() << "\t A2 = " << *A2 << "\n");
1930 DEBUG(dbgs() << "\t C1 = " << *C1 << "\n");
1931 DEBUG(dbgs() << "\t C2 = " << *C2 << "\n");
1932 const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
1933 const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
1934 DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n");
1935 DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n");
1936 const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
1937 const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
1938 DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n");
1939 DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n");
1940 if (SE->isKnownNonNegative(A1)) {
1941 if (SE->isKnownNonNegative(A2)) {
1942 // A1 >= 0 && A2 >= 0
1944 // make sure that c2 - c1 <= a1*N1
1945 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
1946 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
1947 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
1948 ++SymbolicRDIVindependence;
1953 // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
1954 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
1955 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
1956 if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
1957 ++SymbolicRDIVindependence;
1962 else if (SE->isKnownNonPositive(A2)) {
1963 // a1 >= 0 && a2 <= 0
1965 // make sure that c2 - c1 <= a1*N1 - a2*N2
1966 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
1967 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
1968 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
1969 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
1970 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
1971 ++SymbolicRDIVindependence;
1975 // make sure that 0 <= c2 - c1
1976 if (SE->isKnownNegative(C2_C1)) {
1977 ++SymbolicRDIVindependence;
1982 else if (SE->isKnownNonPositive(A1)) {
1983 if (SE->isKnownNonNegative(A2)) {
1984 // a1 <= 0 && a2 >= 0
1986 // make sure that a1*N1 - a2*N2 <= c2 - c1
1987 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
1988 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
1989 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
1990 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
1991 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
1992 ++SymbolicRDIVindependence;
1996 // make sure that c2 - c1 <= 0
1997 if (SE->isKnownPositive(C2_C1)) {
1998 ++SymbolicRDIVindependence;
2002 else if (SE->isKnownNonPositive(A2)) {
2003 // a1 <= 0 && a2 <= 0
2005 // make sure that a1*N1 <= c2 - c1
2006 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2007 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
2008 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2009 ++SymbolicRDIVindependence;
2014 // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2015 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2016 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
2017 if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2018 ++SymbolicRDIVindependence;
2029 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2030 // where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2031 // a2 are constant, we attack it with an SIV test. While they can all be
2032 // solved with the Exact SIV test, it's worthwhile to use simpler tests when
2033 // they apply; they're cheaper and sometimes more precise.
2035 // Return true if dependence disproved.
2036 bool DependenceAnalysis::testSIV(const SCEV *Src,
2039 FullDependence &Result,
2040 Constraint &NewConstraint,
2041 const SCEV *&SplitIter) const {
2042 DEBUG(dbgs() << " src = " << *Src << "\n");
2043 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2044 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2045 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2046 if (SrcAddRec && DstAddRec) {
2047 const SCEV *SrcConst = SrcAddRec->getStart();
2048 const SCEV *DstConst = DstAddRec->getStart();
2049 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2050 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2051 const Loop *CurLoop = SrcAddRec->getLoop();
2052 assert(CurLoop == DstAddRec->getLoop() &&
2053 "both loops in SIV should be same");
2054 Level = mapSrcLoop(CurLoop);
2056 if (SrcCoeff == DstCoeff)
2057 disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2058 Level, Result, NewConstraint);
2059 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2060 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2061 Level, Result, NewConstraint, SplitIter);
2063 disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
2064 Level, Result, NewConstraint);
2066 gcdMIVtest(Src, Dst, Result) ||
2067 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
2070 const SCEV *SrcConst = SrcAddRec->getStart();
2071 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2072 const SCEV *DstConst = Dst;
2073 const Loop *CurLoop = SrcAddRec->getLoop();
2074 Level = mapSrcLoop(CurLoop);
2075 return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2076 Level, Result, NewConstraint) ||
2077 gcdMIVtest(Src, Dst, Result);
2080 const SCEV *DstConst = DstAddRec->getStart();
2081 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2082 const SCEV *SrcConst = Src;
2083 const Loop *CurLoop = DstAddRec->getLoop();
2084 Level = mapDstLoop(CurLoop);
2085 return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
2086 CurLoop, Level, Result, NewConstraint) ||
2087 gcdMIVtest(Src, Dst, Result);
2089 llvm_unreachable("SIV test expected at least one AddRec");
2095 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2096 // where i and j are induction variables, c1 and c2 are loop invariant,
2097 // and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2098 // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2099 // It doesn't make sense to talk about distance or direction in this case,
2100 // so there's no point in making special versions of the Strong SIV test or
2101 // the Weak-crossing SIV test.
2103 // With minor algebra, this test can also be used for things like
2104 // [c1 + a1*i + a2*j][c2].
2106 // Return true if dependence disproved.
2107 bool DependenceAnalysis::testRDIV(const SCEV *Src,
2109 FullDependence &Result) const {
2110 // we have 3 possible situations here:
2111 // 1) [a*i + b] and [c*j + d]
2112 // 2) [a*i + c*j + b] and [d]
2113 // 3) [b] and [a*i + c*j + d]
2114 // We need to find what we've got and get organized
2116 const SCEV *SrcConst, *DstConst;
2117 const SCEV *SrcCoeff, *DstCoeff;
2118 const Loop *SrcLoop, *DstLoop;
2120 DEBUG(dbgs() << " src = " << *Src << "\n");
2121 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2122 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2123 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2124 if (SrcAddRec && DstAddRec) {
2125 SrcConst = SrcAddRec->getStart();
2126 SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2127 SrcLoop = SrcAddRec->getLoop();
2128 DstConst = DstAddRec->getStart();
2129 DstCoeff = DstAddRec->getStepRecurrence(*SE);
2130 DstLoop = DstAddRec->getLoop();
2132 else if (SrcAddRec) {
2133 if (const SCEVAddRecExpr *tmpAddRec =
2134 dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
2135 SrcConst = tmpAddRec->getStart();
2136 SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
2137 SrcLoop = tmpAddRec->getLoop();
2139 DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
2140 DstLoop = SrcAddRec->getLoop();
2143 llvm_unreachable("RDIV reached by surprising SCEVs");
2145 else if (DstAddRec) {
2146 if (const SCEVAddRecExpr *tmpAddRec =
2147 dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
2148 DstConst = tmpAddRec->getStart();
2149 DstCoeff = tmpAddRec->getStepRecurrence(*SE);
2150 DstLoop = tmpAddRec->getLoop();
2152 SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
2153 SrcLoop = DstAddRec->getLoop();
2156 llvm_unreachable("RDIV reached by surprising SCEVs");
2159 llvm_unreachable("RDIV expected at least one AddRec");
2160 return exactRDIVtest(SrcCoeff, DstCoeff,
2164 gcdMIVtest(Src, Dst, Result) ||
2165 symbolicRDIVtest(SrcCoeff, DstCoeff,
2171 // Tests the single-subscript MIV pair (Src and Dst) for dependence.
2172 // Return true if dependence disproved.
2173 // Can sometimes refine direction vectors.
2174 bool DependenceAnalysis::testMIV(const SCEV *Src,
2176 const SmallBitVector &Loops,
2177 FullDependence &Result) const {
2178 DEBUG(dbgs() << " src = " << *Src << "\n");
2179 DEBUG(dbgs() << " dst = " << *Dst << "\n");
2180 Result.Consistent = false;
2181 return gcdMIVtest(Src, Dst, Result) ||
2182 banerjeeMIVtest(Src, Dst, Loops, Result);
2186 // Given a product, e.g., 10*X*Y, returns the first constant operand,
2187 // in this case 10. If there is no constant part, returns NULL.
2189 const SCEVConstant *getConstantPart(const SCEVMulExpr *Product) {
2190 for (unsigned Op = 0, Ops = Product->getNumOperands(); Op < Ops; Op++) {
2191 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Product->getOperand(Op)))
2198 //===----------------------------------------------------------------------===//
2200 // Tests an MIV subscript pair for dependence.
2201 // Returns true if any possible dependence is disproved.
2202 // Marks the result as inconsistent.
2203 // Can sometimes disprove the equal direction for 1 or more loops,
2204 // as discussed in Michael Wolfe's book,
2205 // High Performance Compilers for Parallel Computing, page 235.
2207 // We spend some effort (code!) to handle cases like
2208 // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2209 // but M and N are just loop-invariant variables.
2210 // This should help us handle linearized subscripts;
2211 // also makes this test a useful backup to the various SIV tests.
2213 // It occurs to me that the presence of loop-invariant variables
2214 // changes the nature of the test from "greatest common divisor"
2215 // to "a common divisor!"
2216 bool DependenceAnalysis::gcdMIVtest(const SCEV *Src,
2218 FullDependence &Result) const {
2219 DEBUG(dbgs() << "starting gcd\n");
2221 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
2222 APInt RunningGCD = APInt::getNullValue(BitWidth);
2224 // Examine Src coefficients.
2225 // Compute running GCD and record source constant.
2226 // Because we're looking for the constant at the end of the chain,
2227 // we can't quit the loop just because the GCD == 1.
2228 const SCEV *Coefficients = Src;
2229 while (const SCEVAddRecExpr *AddRec =
2230 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2231 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2232 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
2233 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2234 // If the coefficient is the product of a constant and other stuff,
2235 // we can use the constant in the GCD computation.
2236 Constant = getConstantPart(Product);
2239 APInt ConstCoeff = Constant->getValue()->getValue();
2240 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2241 Coefficients = AddRec->getStart();
2243 const SCEV *SrcConst = Coefficients;
2245 // Examine Dst coefficients.
2246 // Compute running GCD and record destination constant.
2247 // Because we're looking for the constant at the end of the chain,
2248 // we can't quit the loop just because the GCD == 1.
2250 while (const SCEVAddRecExpr *AddRec =
2251 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2252 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2253 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
2254 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2255 // If the coefficient is the product of a constant and other stuff,
2256 // we can use the constant in the GCD computation.
2257 Constant = getConstantPart(Product);
2260 APInt ConstCoeff = Constant->getValue()->getValue();
2261 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2262 Coefficients = AddRec->getStart();
2264 const SCEV *DstConst = Coefficients;
2266 APInt ExtraGCD = APInt::getNullValue(BitWidth);
2267 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
2268 DEBUG(dbgs() << " Delta = " << *Delta << "\n");
2269 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2270 if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
2271 // If Delta is a sum of products, we may be able to make further progress.
2272 for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
2273 const SCEV *Operand = Sum->getOperand(Op);
2274 if (isa<SCEVConstant>(Operand)) {
2275 assert(!Constant && "Surprised to find multiple constants");
2276 Constant = cast<SCEVConstant>(Operand);
2278 else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
2279 // Search for constant operand to participate in GCD;
2280 // If none found; return false.
2281 const SCEVConstant *ConstOp = getConstantPart(Product);
2284 APInt ConstOpValue = ConstOp->getValue()->getValue();
2285 ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
2286 ConstOpValue.abs());
2294 APInt ConstDelta = cast<SCEVConstant>(Constant)->getValue()->getValue();
2295 DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
2296 if (ConstDelta == 0)
2298 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
2299 DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
2300 APInt Remainder = ConstDelta.srem(RunningGCD);
2301 if (Remainder != 0) {
2306 // Try to disprove equal directions.
2307 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2308 // the code above can't disprove the dependence because the GCD = 1.
2309 // So we consider what happen if i = i' and what happens if j = j'.
2310 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2311 // which is infeasible, so we can disallow the = direction for the i level.
2312 // Setting j = j' doesn't help matters, so we end up with a direction vector
2315 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2316 // we need to remember that the constant part is 5 and the RunningGCD should
2317 // be initialized to ExtraGCD = 30.
2318 DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
2320 bool Improved = false;
2322 while (const SCEVAddRecExpr *AddRec =
2323 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2324 Coefficients = AddRec->getStart();
2325 const Loop *CurLoop = AddRec->getLoop();
2326 RunningGCD = ExtraGCD;
2327 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2328 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2329 const SCEV *Inner = Src;
2330 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2331 AddRec = cast<SCEVAddRecExpr>(Inner);
2332 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2333 if (CurLoop == AddRec->getLoop())
2334 ; // SrcCoeff == Coeff
2336 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2337 // If the coefficient is the product of a constant and other stuff,
2338 // we can use the constant in the GCD computation.
2339 Constant = getConstantPart(Product);
2341 Constant = cast<SCEVConstant>(Coeff);
2342 APInt ConstCoeff = Constant->getValue()->getValue();
2343 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2345 Inner = AddRec->getStart();
2348 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2349 AddRec = cast<SCEVAddRecExpr>(Inner);
2350 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2351 if (CurLoop == AddRec->getLoop())
2354 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
2355 // If the coefficient is the product of a constant and other stuff,
2356 // we can use the constant in the GCD computation.
2357 Constant = getConstantPart(Product);
2359 Constant = cast<SCEVConstant>(Coeff);
2360 APInt ConstCoeff = Constant->getValue()->getValue();
2361 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2363 Inner = AddRec->getStart();
2365 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
2366 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Delta))
2367 // If the coefficient is the product of a constant and other stuff,
2368 // we can use the constant in the GCD computation.
2369 Constant = getConstantPart(Product);
2370 else if (isa<SCEVConstant>(Delta))
2371 Constant = cast<SCEVConstant>(Delta);
2373 // The difference of the two coefficients might not be a product
2374 // or constant, in which case we give up on this direction.
2377 APInt ConstCoeff = Constant->getValue()->getValue();
2378 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2379 DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
2380 if (RunningGCD != 0) {
2381 Remainder = ConstDelta.srem(RunningGCD);
2382 DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
2383 if (Remainder != 0) {
2384 unsigned Level = mapSrcLoop(CurLoop);
2385 Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
2392 DEBUG(dbgs() << "all done\n");
2397 //===----------------------------------------------------------------------===//
2398 // banerjeeMIVtest -
2399 // Use Banerjee's Inequalities to test an MIV subscript pair.
2400 // (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2401 // Generally follows the discussion in Section 2.5.2 of
2403 // Optimizing Supercompilers for Supercomputers
2406 // The inequalities given on page 25 are simplified in that loops are
2407 // normalized so that the lower bound is always 0 and the stride is always 1.
2408 // For example, Wolfe gives
2410 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2412 // where A_k is the coefficient of the kth index in the source subscript,
2413 // B_k is the coefficient of the kth index in the destination subscript,
2414 // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2415 // index, and N_k is the stride of the kth index. Since all loops are normalized
2416 // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2419 // LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2420 // = (A^-_k - B_k)^- (U_k - 1) - B_k
2422 // Similar simplifications are possible for the other equations.
2424 // When we can't determine the number of iterations for a loop,
2425 // we use NULL as an indicator for the worst case, infinity.
2426 // When computing the upper bound, NULL denotes +inf;
2427 // for the lower bound, NULL denotes -inf.
2429 // Return true if dependence disproved.
2430 bool DependenceAnalysis::banerjeeMIVtest(const SCEV *Src,
2432 const SmallBitVector &Loops,
2433 FullDependence &Result) const {
2434 DEBUG(dbgs() << "starting Banerjee\n");
2435 ++BanerjeeApplications;
2436 DEBUG(dbgs() << " Src = " << *Src << '\n');
2438 CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
2439 DEBUG(dbgs() << " Dst = " << *Dst << '\n');
2441 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2442 BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
2443 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2444 DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2446 // Compute bounds for all the * directions.
2447 DEBUG(dbgs() << "\tBounds[*]\n");
2448 for (unsigned K = 1; K <= MaxLevels; ++K) {
2449 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2450 Bound[K].Direction = Dependence::DVEntry::ALL;
2451 Bound[K].DirSet = Dependence::DVEntry::NONE;
2452 findBoundsALL(A, B, Bound, K);
2454 DEBUG(dbgs() << "\t " << K << '\t');
2455 if (Bound[K].Lower[Dependence::DVEntry::ALL])
2456 DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
2458 DEBUG(dbgs() << "-inf\t");
2459 if (Bound[K].Upper[Dependence::DVEntry::ALL])
2460 DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
2462 DEBUG(dbgs() << "+inf\n");
2466 // Test the *, *, *, ... case.
2467 bool Disproved = false;
2468 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2469 // Explore the direction vector hierarchy.
2470 unsigned DepthExpanded = 0;
2471 unsigned NewDeps = exploreDirections(1, A, B, Bound,
2472 Loops, DepthExpanded, Delta);
2474 bool Improved = false;
2475 for (unsigned K = 1; K <= CommonLevels; ++K) {
2477 unsigned Old = Result.DV[K - 1].Direction;
2478 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2479 Improved |= Old != Result.DV[K - 1].Direction;
2480 if (!Result.DV[K - 1].Direction) {
2488 ++BanerjeeSuccesses;
2491 ++BanerjeeIndependence;
2496 ++BanerjeeIndependence;
2506 // Hierarchically expands the direction vector
2507 // search space, combining the directions of discovered dependences
2508 // in the DirSet field of Bound. Returns the number of distinct
2509 // dependences discovered. If the dependence is disproved,
2510 // it will return 0.
2511 unsigned DependenceAnalysis::exploreDirections(unsigned Level,
2515 const SmallBitVector &Loops,
2516 unsigned &DepthExpanded,
2517 const SCEV *Delta) const {
2518 if (Level > CommonLevels) {
2520 DEBUG(dbgs() << "\t[");
2521 for (unsigned K = 1; K <= CommonLevels; ++K) {
2523 Bound[K].DirSet |= Bound[K].Direction;
2525 switch (Bound[K].Direction) {
2526 case Dependence::DVEntry::LT:
2527 DEBUG(dbgs() << " <");
2529 case Dependence::DVEntry::EQ:
2530 DEBUG(dbgs() << " =");
2532 case Dependence::DVEntry::GT:
2533 DEBUG(dbgs() << " >");
2535 case Dependence::DVEntry::ALL:
2536 DEBUG(dbgs() << " *");
2539 llvm_unreachable("unexpected Bound[K].Direction");
2544 DEBUG(dbgs() << " ]\n");
2548 if (Level > DepthExpanded) {
2549 DepthExpanded = Level;
2550 // compute bounds for <, =, > at current level
2551 findBoundsLT(A, B, Bound, Level);
2552 findBoundsGT(A, B, Bound, Level);
2553 findBoundsEQ(A, B, Bound, Level);
2555 DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2556 DEBUG(dbgs() << "\t <\t");
2557 if (Bound[Level].Lower[Dependence::DVEntry::LT])
2558 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT] << '\t');
2560 DEBUG(dbgs() << "-inf\t");
2561 if (Bound[Level].Upper[Dependence::DVEntry::LT])
2562 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT] << '\n');
2564 DEBUG(dbgs() << "+inf\n");
2565 DEBUG(dbgs() << "\t =\t");
2566 if (Bound[Level].Lower[Dependence::DVEntry::EQ])
2567 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ] << '\t');
2569 DEBUG(dbgs() << "-inf\t");
2570 if (Bound[Level].Upper[Dependence::DVEntry::EQ])
2571 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ] << '\n');
2573 DEBUG(dbgs() << "+inf\n");
2574 DEBUG(dbgs() << "\t >\t");
2575 if (Bound[Level].Lower[Dependence::DVEntry::GT])
2576 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT] << '\t');
2578 DEBUG(dbgs() << "-inf\t");
2579 if (Bound[Level].Upper[Dependence::DVEntry::GT])
2580 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT] << '\n');
2582 DEBUG(dbgs() << "+inf\n");
2586 unsigned NewDeps = 0;
2588 // test bounds for <, *, *, ...
2589 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2590 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2591 Loops, DepthExpanded, Delta);
2593 // Test bounds for =, *, *, ...
2594 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2595 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2596 Loops, DepthExpanded, Delta);
2598 // test bounds for >, *, *, ...
2599 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2600 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2601 Loops, DepthExpanded, Delta);
2603 Bound[Level].Direction = Dependence::DVEntry::ALL;
2607 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
2611 // Returns true iff the current bounds are plausible.
2612 bool DependenceAnalysis::testBounds(unsigned char DirKind,
2615 const SCEV *Delta) const {
2616 Bound[Level].Direction = DirKind;
2617 if (const SCEV *LowerBound = getLowerBound(Bound))
2618 if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2620 if (const SCEV *UpperBound = getUpperBound(Bound))
2621 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2627 // Computes the upper and lower bounds for level K
2628 // using the * direction. Records them in Bound.
2629 // Wolfe gives the equations
2631 // LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2632 // UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2634 // Since we normalize loops, we can simplify these equations to
2636 // LB^*_k = (A^-_k - B^+_k)U_k
2637 // UB^*_k = (A^+_k - B^-_k)U_k
2639 // We must be careful to handle the case where the upper bound is unknown.
2640 // Note that the lower bound is always <= 0
2641 // and the upper bound is always >= 0.
2642 void DependenceAnalysis::findBoundsALL(CoefficientInfo *A,
2646 Bound[K].Lower[Dependence::DVEntry::ALL] = NULL; // Default value = -infinity.
2647 Bound[K].Upper[Dependence::DVEntry::ALL] = NULL; // Default value = +infinity.
2648 if (Bound[K].Iterations) {
2649 Bound[K].Lower[Dependence::DVEntry::ALL] =
2650 SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
2651 Bound[K].Iterations);
2652 Bound[K].Upper[Dependence::DVEntry::ALL] =
2653 SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
2654 Bound[K].Iterations);
2657 // If the difference is 0, we won't need to know the number of iterations.
2658 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2659 Bound[K].Lower[Dependence::DVEntry::ALL] =
2660 SE->getConstant(A[K].Coeff->getType(), 0);
2661 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2662 Bound[K].Upper[Dependence::DVEntry::ALL] =
2663 SE->getConstant(A[K].Coeff->getType(), 0);
2668 // Computes the upper and lower bounds for level K
2669 // using the = direction. Records them in Bound.
2670 // Wolfe gives the equations
2672 // LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2673 // UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2675 // Since we normalize loops, we can simplify these equations to
2677 // LB^=_k = (A_k - B_k)^- U_k
2678 // UB^=_k = (A_k - B_k)^+ U_k
2680 // We must be careful to handle the case where the upper bound is unknown.
2681 // Note that the lower bound is always <= 0
2682 // and the upper bound is always >= 0.
2683 void DependenceAnalysis::findBoundsEQ(CoefficientInfo *A,
2687 Bound[K].Lower[Dependence::DVEntry::EQ] = NULL; // Default value = -infinity.
2688 Bound[K].Upper[Dependence::DVEntry::EQ] = NULL; // Default value = +infinity.
2689 if (Bound[K].Iterations) {
2690 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2691 const SCEV *NegativePart = getNegativePart(Delta);
2692 Bound[K].Lower[Dependence::DVEntry::EQ] =
2693 SE->getMulExpr(NegativePart, Bound[K].Iterations);
2694 const SCEV *PositivePart = getPositivePart(Delta);
2695 Bound[K].Upper[Dependence::DVEntry::EQ] =
2696 SE->getMulExpr(PositivePart, Bound[K].Iterations);
2699 // If the positive/negative part of the difference is 0,
2700 // we won't need to know the number of iterations.
2701 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2702 const SCEV *NegativePart = getNegativePart(Delta);
2703 if (NegativePart->isZero())
2704 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2705 const SCEV *PositivePart = getPositivePart(Delta);
2706 if (PositivePart->isZero())
2707 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2712 // Computes the upper and lower bounds for level K
2713 // using the < direction. Records them in Bound.
2714 // Wolfe gives the equations
2716 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2717 // UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2719 // Since we normalize loops, we can simplify these equations to
2721 // LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2722 // UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2724 // We must be careful to handle the case where the upper bound is unknown.
2725 void DependenceAnalysis::findBoundsLT(CoefficientInfo *A,
2729 Bound[K].Lower[Dependence::DVEntry::LT] = NULL; // Default value = -infinity.
2730 Bound[K].Upper[Dependence::DVEntry::LT] = NULL; // Default value = +infinity.
2731 if (Bound[K].Iterations) {
2732 const SCEV *Iter_1 =
2733 SE->getMinusSCEV(Bound[K].Iterations,
2734 SE->getConstant(Bound[K].Iterations->getType(), 1));
2735 const SCEV *NegPart =
2736 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2737 Bound[K].Lower[Dependence::DVEntry::LT] =
2738 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2739 const SCEV *PosPart =
2740 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2741 Bound[K].Upper[Dependence::DVEntry::LT] =
2742 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2745 // If the positive/negative part of the difference is 0,
2746 // we won't need to know the number of iterations.
2747 const SCEV *NegPart =
2748 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2749 if (NegPart->isZero())
2750 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2751 const SCEV *PosPart =
2752 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2753 if (PosPart->isZero())
2754 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2759 // Computes the upper and lower bounds for level K
2760 // using the > direction. Records them in Bound.
2761 // Wolfe gives the equations
2763 // LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2764 // UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2766 // Since we normalize loops, we can simplify these equations to
2768 // LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2769 // UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2771 // We must be careful to handle the case where the upper bound is unknown.
2772 void DependenceAnalysis::findBoundsGT(CoefficientInfo *A,
2776 Bound[K].Lower[Dependence::DVEntry::GT] = NULL; // Default value = -infinity.
2777 Bound[K].Upper[Dependence::DVEntry::GT] = NULL; // Default value = +infinity.
2778 if (Bound[K].Iterations) {
2779 const SCEV *Iter_1 =
2780 SE->getMinusSCEV(Bound[K].Iterations,
2781 SE->getConstant(Bound[K].Iterations->getType(), 1));
2782 const SCEV *NegPart =
2783 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2784 Bound[K].Lower[Dependence::DVEntry::GT] =
2785 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2786 const SCEV *PosPart =
2787 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2788 Bound[K].Upper[Dependence::DVEntry::GT] =
2789 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2792 // If the positive/negative part of the difference is 0,
2793 // we won't need to know the number of iterations.
2794 const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2795 if (NegPart->isZero())
2796 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2797 const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2798 if (PosPart->isZero())
2799 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2805 const SCEV *DependenceAnalysis::getPositivePart(const SCEV *X) const {
2806 return SE->getSMaxExpr(X, SE->getConstant(X->getType(), 0));
2811 const SCEV *DependenceAnalysis::getNegativePart(const SCEV *X) const {
2812 return SE->getSMinExpr(X, SE->getConstant(X->getType(), 0));
2816 // Walks through the subscript,
2817 // collecting each coefficient, the associated loop bounds,
2818 // and recording its positive and negative parts for later use.
2819 DependenceAnalysis::CoefficientInfo *
2820 DependenceAnalysis::collectCoeffInfo(const SCEV *Subscript,
2822 const SCEV *&Constant) const {
2823 const SCEV *Zero = SE->getConstant(Subscript->getType(), 0);
2824 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
2825 for (unsigned K = 1; K <= MaxLevels; ++K) {
2827 CI[K].PosPart = Zero;
2828 CI[K].NegPart = Zero;
2829 CI[K].Iterations = NULL;
2831 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2832 const Loop *L = AddRec->getLoop();
2833 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2834 CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2835 CI[K].PosPart = getPositivePart(CI[K].Coeff);
2836 CI[K].NegPart = getNegativePart(CI[K].Coeff);
2837 CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2838 Subscript = AddRec->getStart();
2840 Constant = Subscript;
2842 DEBUG(dbgs() << "\tCoefficient Info\n");
2843 for (unsigned K = 1; K <= MaxLevels; ++K) {
2844 DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
2845 DEBUG(dbgs() << "\tPos Part = ");
2846 DEBUG(dbgs() << *CI[K].PosPart);
2847 DEBUG(dbgs() << "\tNeg Part = ");
2848 DEBUG(dbgs() << *CI[K].NegPart);
2849 DEBUG(dbgs() << "\tUpper Bound = ");
2850 if (CI[K].Iterations)
2851 DEBUG(dbgs() << *CI[K].Iterations);
2853 DEBUG(dbgs() << "+inf");
2854 DEBUG(dbgs() << '\n');
2856 DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
2862 // Looks through all the bounds info and
2863 // computes the lower bound given the current direction settings
2864 // at each level. If the lower bound for any level is -inf,
2865 // the result is -inf.
2866 const SCEV *DependenceAnalysis::getLowerBound(BoundInfo *Bound) const {
2867 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2868 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2869 if (Bound[K].Lower[Bound[K].Direction])
2870 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2878 // Looks through all the bounds info and
2879 // computes the upper bound given the current direction settings
2880 // at each level. If the upper bound at any level is +inf,
2881 // the result is +inf.
2882 const SCEV *DependenceAnalysis::getUpperBound(BoundInfo *Bound) const {
2883 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2884 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2885 if (Bound[K].Upper[Bound[K].Direction])
2886 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2894 //===----------------------------------------------------------------------===//
2895 // Constraint manipulation for Delta test.
2897 // Given a linear SCEV,
2898 // return the coefficient (the step)
2899 // corresponding to the specified loop.
2900 // If there isn't one, return 0.
2901 // For example, given a*i + b*j + c*k, zeroing the coefficient
2902 // corresponding to the j loop would yield b.
2903 const SCEV *DependenceAnalysis::findCoefficient(const SCEV *Expr,
2904 const Loop *TargetLoop) const {
2905 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2907 return SE->getConstant(Expr->getType(), 0);
2908 if (AddRec->getLoop() == TargetLoop)
2909 return AddRec->getStepRecurrence(*SE);
2910 return findCoefficient(AddRec->getStart(), TargetLoop);
2914 // Given a linear SCEV,
2915 // return the SCEV given by zeroing out the coefficient
2916 // corresponding to the specified loop.
2917 // For example, given a*i + b*j + c*k, zeroing the coefficient
2918 // corresponding to the j loop would yield a*i + c*k.
2919 const SCEV *DependenceAnalysis::zeroCoefficient(const SCEV *Expr,
2920 const Loop *TargetLoop) const {
2921 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2923 return Expr; // ignore
2924 if (AddRec->getLoop() == TargetLoop)
2925 return AddRec->getStart();
2926 return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
2927 AddRec->getStepRecurrence(*SE),
2929 AddRec->getNoWrapFlags());
2933 // Given a linear SCEV Expr,
2934 // return the SCEV given by adding some Value to the
2935 // coefficient corresponding to the specified TargetLoop.
2936 // For example, given a*i + b*j + c*k, adding 1 to the coefficient
2937 // corresponding to the j loop would yield a*i + (b+1)*j + c*k.
2938 const SCEV *DependenceAnalysis::addToCoefficient(const SCEV *Expr,
2939 const Loop *TargetLoop,
2940 const SCEV *Value) const {
2941 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2942 if (!AddRec) // create a new addRec
2943 return SE->getAddRecExpr(Expr,
2946 SCEV::FlagAnyWrap); // Worst case, with no info.
2947 if (AddRec->getLoop() == TargetLoop) {
2948 const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
2950 return AddRec->getStart();
2951 return SE->getAddRecExpr(AddRec->getStart(),
2954 AddRec->getNoWrapFlags());
2956 return SE->getAddRecExpr(addToCoefficient(AddRec->getStart(),
2958 AddRec->getStepRecurrence(*SE),
2960 AddRec->getNoWrapFlags());
2964 // Review the constraints, looking for opportunities
2965 // to simplify a subscript pair (Src and Dst).
2966 // Return true if some simplification occurs.
2967 // If the simplification isn't exact (that is, if it is conservative
2968 // in terms of dependence), set consistent to false.
2969 // Corresponds to Figure 5 from the paper
2971 // Practical Dependence Testing
2972 // Goff, Kennedy, Tseng
2974 bool DependenceAnalysis::propagate(const SCEV *&Src,
2976 SmallBitVector &Loops,
2977 SmallVector<Constraint, 4> &Constraints,
2979 bool Result = false;
2980 for (int LI = Loops.find_first(); LI >= 0; LI = Loops.find_next(LI)) {
2981 DEBUG(dbgs() << "\t Constraint[" << LI << "] is");
2982 DEBUG(Constraints[LI].dump(dbgs()));
2983 if (Constraints[LI].isDistance())
2984 Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
2985 else if (Constraints[LI].isLine())
2986 Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
2987 else if (Constraints[LI].isPoint())
2988 Result |= propagatePoint(Src, Dst, Constraints[LI]);
2994 // Attempt to propagate a distance
2995 // constraint into a subscript pair (Src and Dst).
2996 // Return true if some simplification occurs.
2997 // If the simplification isn't exact (that is, if it is conservative
2998 // in terms of dependence), set consistent to false.
2999 bool DependenceAnalysis::propagateDistance(const SCEV *&Src,
3001 Constraint &CurConstraint,
3003 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3004 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3005 const SCEV *A_K = findCoefficient(Src, CurLoop);
3008 const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
3009 Src = SE->getMinusSCEV(Src, DA_K);
3010 Src = zeroCoefficient(Src, CurLoop);
3011 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3012 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3013 Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
3014 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3015 if (!findCoefficient(Dst, CurLoop)->isZero())
3021 // Attempt to propagate a line
3022 // constraint into a subscript pair (Src and Dst).
3023 // Return true if some simplification occurs.
3024 // If the simplification isn't exact (that is, if it is conservative
3025 // in terms of dependence), set consistent to false.
3026 bool DependenceAnalysis::propagateLine(const SCEV *&Src,
3028 Constraint &CurConstraint,
3030 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3031 const SCEV *A = CurConstraint.getA();
3032 const SCEV *B = CurConstraint.getB();
3033 const SCEV *C = CurConstraint.getC();
3034 DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C << "\n");
3035 DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
3036 DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
3038 const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
3039 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3040 if (!Bconst || !Cconst) return false;
3041 APInt Beta = Bconst->getValue()->getValue();
3042 APInt Charlie = Cconst->getValue()->getValue();
3043 APInt CdivB = Charlie.sdiv(Beta);
3044 assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
3045 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3046 // Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3047 Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3048 Dst = zeroCoefficient(Dst, CurLoop);
3049 if (!findCoefficient(Src, CurLoop)->isZero())
3052 else if (B->isZero()) {
3053 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3054 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3055 if (!Aconst || !Cconst) return false;
3056 APInt Alpha = Aconst->getValue()->getValue();
3057 APInt Charlie = Cconst->getValue()->getValue();
3058 APInt CdivA = Charlie.sdiv(Alpha);
3059 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3060 const SCEV *A_K = findCoefficient(Src, CurLoop);
3061 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3062 Src = zeroCoefficient(Src, CurLoop);
3063 if (!findCoefficient(Dst, CurLoop)->isZero())
3066 else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
3067 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3068 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3069 if (!Aconst || !Cconst) return false;
3070 APInt Alpha = Aconst->getValue()->getValue();
3071 APInt Charlie = Cconst->getValue()->getValue();
3072 APInt CdivA = Charlie.sdiv(Alpha);
3073 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3074 const SCEV *A_K = findCoefficient(Src, CurLoop);
3075 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3076 Src = zeroCoefficient(Src, CurLoop);
3077 Dst = addToCoefficient(Dst, CurLoop, A_K);
3078 if (!findCoefficient(Dst, CurLoop)->isZero())
3082 // paper is incorrect here, or perhaps just misleading
3083 const SCEV *A_K = findCoefficient(Src, CurLoop);
3084 Src = SE->getMulExpr(Src, A);
3085 Dst = SE->getMulExpr(Dst, A);
3086 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
3087 Src = zeroCoefficient(Src, CurLoop);
3088 Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
3089 if (!findCoefficient(Dst, CurLoop)->isZero())
3092 DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
3093 DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
3098 // Attempt to propagate a point
3099 // constraint into a subscript pair (Src and Dst).
3100 // Return true if some simplification occurs.
3101 bool DependenceAnalysis::propagatePoint(const SCEV *&Src,
3103 Constraint &CurConstraint) {
3104 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3105 const SCEV *A_K = findCoefficient(Src, CurLoop);
3106 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3107 const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
3108 const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
3109 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3110 Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
3111 Src = zeroCoefficient(Src, CurLoop);
3112 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3113 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3114 Dst = zeroCoefficient(Dst, CurLoop);
3115 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3120 // Update direction vector entry based on the current constraint.
3121 void DependenceAnalysis::updateDirection(Dependence::DVEntry &Level,
3122 const Constraint &CurConstraint
3124 DEBUG(dbgs() << "\tUpdate direction, constraint =");
3125 DEBUG(CurConstraint.dump(dbgs()));
3126 if (CurConstraint.isAny())
3128 else if (CurConstraint.isDistance()) {
3129 // this one is consistent, the others aren't
3130 Level.Scalar = false;
3131 Level.Distance = CurConstraint.getD();
3132 unsigned NewDirection = Dependence::DVEntry::NONE;
3133 if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
3134 NewDirection = Dependence::DVEntry::EQ;
3135 if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
3136 NewDirection |= Dependence::DVEntry::LT;
3137 if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
3138 NewDirection |= Dependence::DVEntry::GT;
3139 Level.Direction &= NewDirection;
3141 else if (CurConstraint.isLine()) {
3142 Level.Scalar = false;
3143 Level.Distance = NULL;
3144 // direction should be accurate
3146 else if (CurConstraint.isPoint()) {
3147 Level.Scalar = false;
3148 Level.Distance = NULL;
3149 unsigned NewDirection = Dependence::DVEntry::NONE;
3150 if (!isKnownPredicate(CmpInst::ICMP_NE,
3151 CurConstraint.getY(),
3152 CurConstraint.getX()))
3154 NewDirection |= Dependence::DVEntry::EQ;
3155 if (!isKnownPredicate(CmpInst::ICMP_SLE,
3156 CurConstraint.getY(),
3157 CurConstraint.getX()))
3159 NewDirection |= Dependence::DVEntry::LT;
3160 if (!isKnownPredicate(CmpInst::ICMP_SGE,
3161 CurConstraint.getY(),
3162 CurConstraint.getX()))
3164 NewDirection |= Dependence::DVEntry::GT;
3165 Level.Direction &= NewDirection;
3168 llvm_unreachable("constraint has unexpected kind");
3172 //===----------------------------------------------------------------------===//
3175 // For debugging purposes, dump a small bit vector to dbgs().
3176 static void dumpSmallBitVector(SmallBitVector &BV) {
3178 for (int VI = BV.find_first(); VI >= 0; VI = BV.find_next(VI)) {
3180 if (BV.find_next(VI) >= 0)
3189 // Returns NULL if there is no dependence.
3190 // Otherwise, return a Dependence with as many details as possible.
3191 // Corresponds to Section 3.1 in the paper
3193 // Practical Dependence Testing
3194 // Goff, Kennedy, Tseng
3197 // Care is required to keep the routine below, getSplitIteration(),
3198 // up to date with respect to this routine.
3199 Dependence *DependenceAnalysis::depends(Instruction *Src,
3201 bool PossiblyLoopIndependent) {
3202 if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
3203 (!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
3204 // if both instructions don't reference memory, there's no dependence
3207 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
3208 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
3209 DEBUG(dbgs() << "can only handle simple loads and stores\n");
3210 return new Dependence(Src, Dst);
3213 Value *SrcPtr = getPointerOperand(Src);
3214 Value *DstPtr = getPointerOperand(Dst);
3216 switch (underlyingObjectsAlias(AA, DstPtr, SrcPtr)) {
3217 case AliasAnalysis::MayAlias:
3218 case AliasAnalysis::PartialAlias:
3219 // cannot analyse objects if we don't understand their aliasing.
3220 DEBUG(dbgs() << "can't analyze may or partial alias\n");
3221 return new Dependence(Src, Dst);
3222 case AliasAnalysis::NoAlias:
3223 // If the objects noalias, they are distinct, accesses are independent.
3224 DEBUG(dbgs() << "no alias\n");
3226 case AliasAnalysis::MustAlias:
3227 break; // The underlying objects alias; test accesses for dependence.
3230 // establish loop nesting levels
3231 establishNestingLevels(Src, Dst);
3232 DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
3233 DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
3235 FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
3238 // See if there are GEPs we can use.
3239 bool UsefulGEP = false;
3240 GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr);
3241 GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr);
3242 if (SrcGEP && DstGEP &&
3243 SrcGEP->getPointerOperandType() == DstGEP->getPointerOperandType()) {
3244 const SCEV *SrcPtrSCEV = SE->getSCEV(SrcGEP->getPointerOperand());
3245 const SCEV *DstPtrSCEV = SE->getSCEV(DstGEP->getPointerOperand());
3246 DEBUG(dbgs() << " SrcPtrSCEV = " << *SrcPtrSCEV << "\n");
3247 DEBUG(dbgs() << " DstPtrSCEV = " << *DstPtrSCEV << "\n");
3250 isLoopInvariant(SrcPtrSCEV, LI->getLoopFor(Src->getParent())) &&
3251 isLoopInvariant(DstPtrSCEV, LI->getLoopFor(Dst->getParent()));
3253 unsigned Pairs = UsefulGEP ? SrcGEP->idx_end() - SrcGEP->idx_begin() : 1;
3254 SmallVector<Subscript, 4> Pair(Pairs);
3256 DEBUG(dbgs() << " using GEPs\n");
3258 for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(),
3259 SrcEnd = SrcGEP->idx_end(),
3260 DstIdx = DstGEP->idx_begin();
3262 ++SrcIdx, ++DstIdx, ++P) {
3263 Pair[P].Src = SE->getSCEV(*SrcIdx);
3264 Pair[P].Dst = SE->getSCEV(*DstIdx);
3268 DEBUG(dbgs() << " ignoring GEPs\n");
3269 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3270 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3271 DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n");
3272 DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n");
3273 Pair[0].Src = SrcSCEV;
3274 Pair[0].Dst = DstSCEV;
3277 for (unsigned P = 0; P < Pairs; ++P) {
3278 Pair[P].Loops.resize(MaxLevels + 1);
3279 Pair[P].GroupLoops.resize(MaxLevels + 1);
3280 Pair[P].Group.resize(Pairs);
3281 removeMatchingExtensions(&Pair[P]);
3282 Pair[P].Classification =
3283 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3284 Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3286 Pair[P].GroupLoops = Pair[P].Loops;
3287 Pair[P].Group.set(P);
3288 DEBUG(dbgs() << " subscript " << P << "\n");
3289 DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
3290 DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
3291 DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
3292 DEBUG(dbgs() << "\tloops = ");
3293 DEBUG(dumpSmallBitVector(Pair[P].Loops));
3296 SmallBitVector Separable(Pairs);
3297 SmallBitVector Coupled(Pairs);
3299 // Partition subscripts into separable and minimally-coupled groups
3300 // Algorithm in paper is algorithmically better;
3301 // this may be faster in practice. Check someday.
3303 // Here's an example of how it works. Consider this code:
3310 // A[i][j][k][m] = ...;
3311 // ... = A[0][j][l][i + j];
3318 // There are 4 subscripts here:
3322 // 3 [m] and [i + j]
3324 // We've already classified each subscript pair as ZIV, SIV, etc.,
3325 // and collected all the loops mentioned by pair P in Pair[P].Loops.
3326 // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
3327 // and set Pair[P].Group = {P}.
3329 // Src Dst Classification Loops GroupLoops Group
3330 // 0 [i] [0] SIV {1} {1} {0}
3331 // 1 [j] [j] SIV {2} {2} {1}
3332 // 2 [k] [l] RDIV {3,4} {3,4} {2}
3333 // 3 [m] [i + j] MIV {1,2,5} {1,2,5} {3}
3335 // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
3336 // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
3338 // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
3339 // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
3340 // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
3341 // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
3342 // to either Separable or Coupled).
3344 // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
3345 // Next, 1 and 3. The intersectionof their GroupLoops = {2}, not empty,
3346 // so Pair[3].Group = {0, 1, 3} and Done = false.
3348 // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
3349 // Since Done remains true, we add 2 to the set of Separable pairs.
3351 // Finally, we consider 3. There's nothing to compare it with,
3352 // so Done remains true and we add it to the Coupled set.
3353 // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
3355 // In the end, we've got 1 separable subscript and 1 coupled group.
3356 for (unsigned SI = 0; SI < Pairs; ++SI) {
3357 if (Pair[SI].Classification == Subscript::NonLinear) {
3358 // ignore these, but collect loops for later
3359 ++NonlinearSubscriptPairs;
3360 collectCommonLoops(Pair[SI].Src,
3361 LI->getLoopFor(Src->getParent()),
3363 collectCommonLoops(Pair[SI].Dst,
3364 LI->getLoopFor(Dst->getParent()),
3366 Result.Consistent = false;
3368 else if (Pair[SI].Classification == Subscript::ZIV) {
3373 // SIV, RDIV, or MIV, so check for coupled group
3375 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3376 SmallBitVector Intersection = Pair[SI].GroupLoops;
3377 Intersection &= Pair[SJ].GroupLoops;
3378 if (Intersection.any()) {
3379 // accumulate set of all the loops in group
3380 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3381 // accumulate set of all subscripts in group
3382 Pair[SJ].Group |= Pair[SI].Group;
3387 if (Pair[SI].Group.count() == 1) {
3389 ++SeparableSubscriptPairs;
3393 ++CoupledSubscriptPairs;
3399 DEBUG(dbgs() << " Separable = ");
3400 DEBUG(dumpSmallBitVector(Separable));
3401 DEBUG(dbgs() << " Coupled = ");
3402 DEBUG(dumpSmallBitVector(Coupled));
3404 Constraint NewConstraint;
3405 NewConstraint.setAny(SE);
3407 // test separable subscripts
3408 for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) {
3409 DEBUG(dbgs() << "testing subscript " << SI);
3410 switch (Pair[SI].Classification) {
3411 case Subscript::ZIV:
3412 DEBUG(dbgs() << ", ZIV\n");
3413 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
3416 case Subscript::SIV: {
3417 DEBUG(dbgs() << ", SIV\n");
3419 const SCEV *SplitIter = NULL;
3420 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
3421 Result, NewConstraint, SplitIter))
3425 case Subscript::RDIV:
3426 DEBUG(dbgs() << ", RDIV\n");
3427 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
3430 case Subscript::MIV:
3431 DEBUG(dbgs() << ", MIV\n");
3432 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
3436 llvm_unreachable("subscript has unexpected classification");
3440 if (Coupled.count()) {
3441 // test coupled subscript groups
3442 DEBUG(dbgs() << "starting on coupled subscripts\n");
3443 DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
3444 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3445 for (unsigned II = 0; II <= MaxLevels; ++II)
3446 Constraints[II].setAny(SE);
3447 for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) {
3448 DEBUG(dbgs() << "testing subscript group " << SI << " { ");
3449 SmallBitVector Group(Pair[SI].Group);
3450 SmallBitVector Sivs(Pairs);
3451 SmallBitVector Mivs(Pairs);
3452 SmallBitVector ConstrainedLevels(MaxLevels + 1);
3453 for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) {
3454 DEBUG(dbgs() << SJ << " ");
3455 if (Pair[SJ].Classification == Subscript::SIV)
3460 DEBUG(dbgs() << "}\n");
3461 while (Sivs.any()) {
3462 bool Changed = false;
3463 for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
3464 DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
3465 // SJ is an SIV subscript that's part of the current coupled group
3467 const SCEV *SplitIter = NULL;
3468 DEBUG(dbgs() << "SIV\n");
3469 if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
3470 Result, NewConstraint, SplitIter))
3472 ConstrainedLevels.set(Level);
3473 if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
3474 if (Constraints[Level].isEmpty()) {
3475 ++DeltaIndependence;
3483 // propagate, possibly creating new SIVs and ZIVs
3484 DEBUG(dbgs() << " propagating\n");
3485 DEBUG(dbgs() << "\tMivs = ");
3486 DEBUG(dumpSmallBitVector(Mivs));
3487 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3488 // SJ is an MIV subscript that's part of the current coupled group
3489 DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
3490 if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
3491 Constraints, Result.Consistent)) {
3492 DEBUG(dbgs() << "\t Changed\n");
3493 ++DeltaPropagations;
3494 Pair[SJ].Classification =
3495 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3496 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3498 switch (Pair[SJ].Classification) {
3499 case Subscript::ZIV:
3500 DEBUG(dbgs() << "ZIV\n");
3501 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3505 case Subscript::SIV:
3509 case Subscript::RDIV:
3510 case Subscript::MIV:
3513 llvm_unreachable("bad subscript classification");
3520 // test & propagate remaining RDIVs
3521 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3522 if (Pair[SJ].Classification == Subscript::RDIV) {
3523 DEBUG(dbgs() << "RDIV test\n");
3524 if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3526 // I don't yet understand how to propagate RDIV results
3531 // test remaining MIVs
3532 // This code is temporary.
3533 // Better to somehow test all remaining subscripts simultaneously.
3534 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3535 if (Pair[SJ].Classification == Subscript::MIV) {
3536 DEBUG(dbgs() << "MIV test\n");
3537 if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
3541 llvm_unreachable("expected only MIV subscripts at this point");
3544 // update Result.DV from constraint vector
3545 DEBUG(dbgs() << " updating\n");
3546 for (int SJ = ConstrainedLevels.find_first();
3547 SJ >= 0; SJ = ConstrainedLevels.find_next(SJ)) {
3548 updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
3549 if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
3555 // make sure Scalar flags are set correctly
3556 SmallBitVector CompleteLoops(MaxLevels + 1);
3557 for (unsigned SI = 0; SI < Pairs; ++SI)
3558 CompleteLoops |= Pair[SI].Loops;
3559 for (unsigned II = 1; II <= CommonLevels; ++II)
3560 if (CompleteLoops[II])
3561 Result.DV[II - 1].Scalar = false;
3563 // make sure loopIndepent flag is set correctly
3564 if (PossiblyLoopIndependent) {
3565 for (unsigned II = 1; II <= CommonLevels; ++II) {
3566 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3567 Result.LoopIndependent = false;
3573 FullDependence *Final = new FullDependence(Result);
3580 //===----------------------------------------------------------------------===//
3581 // getSplitIteration -
3582 // Rather than spend rarely-used space recording the splitting iteration
3583 // during the Weak-Crossing SIV test, we re-compute it on demand.
3584 // The re-computation is basically a repeat of the entire dependence test,
3585 // though simplified since we know that the dependence exists.
3586 // It's tedious, since we must go through all propagations, etc.
3588 // Care is required to keep this code up to date with respect to the routine
3589 // above, depends().
3591 // Generally, the dependence analyzer will be used to build
3592 // a dependence graph for a function (basically a map from instructions
3593 // to dependences). Looking for cycles in the graph shows us loops
3594 // that cannot be trivially vectorized/parallelized.
3596 // We can try to improve the situation by examining all the dependences
3597 // that make up the cycle, looking for ones we can break.
3598 // Sometimes, peeling the first or last iteration of a loop will break
3599 // dependences, and we've got flags for those possibilities.
3600 // Sometimes, splitting a loop at some other iteration will do the trick,
3601 // and we've got a flag for that case. Rather than waste the space to
3602 // record the exact iteration (since we rarely know), we provide
3603 // a method that calculates the iteration. It's a drag that it must work
3604 // from scratch, but wonderful in that it's possible.
3606 // Here's an example:
3608 // for (i = 0; i < 10; i++)
3612 // There's a loop-carried flow dependence from the store to the load,
3613 // found by the weak-crossing SIV test. The dependence will have a flag,
3614 // indicating that the dependence can be broken by splitting the loop.
3615 // Calling getSplitIteration will return 5.
3616 // Splitting the loop breaks the dependence, like so:
3618 // for (i = 0; i <= 5; i++)
3621 // for (i = 6; i < 10; i++)
3625 // breaks the dependence and allows us to vectorize/parallelize
3627 const SCEV *DependenceAnalysis::getSplitIteration(const Dependence *Dep,
3628 unsigned SplitLevel) {
3629 assert(Dep && "expected a pointer to a Dependence");
3630 assert(Dep->isSplitable(SplitLevel) &&
3631 "Dep should be splitable at SplitLevel");
3632 Instruction *Src = Dep->getSrc();
3633 Instruction *Dst = Dep->getDst();
3634 assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
3635 assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
3636 assert(isLoadOrStore(Src));
3637 assert(isLoadOrStore(Dst));
3638 Value *SrcPtr = getPointerOperand(Src);
3639 Value *DstPtr = getPointerOperand(Dst);
3640 assert(underlyingObjectsAlias(AA, DstPtr, SrcPtr) ==
3641 AliasAnalysis::MustAlias);
3643 // establish loop nesting levels
3644 establishNestingLevels(Src, Dst);
3646 FullDependence Result(Src, Dst, false, CommonLevels);
3648 // See if there are GEPs we can use.
3649 bool UsefulGEP = false;
3650 GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr);
3651 GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr);
3652 if (SrcGEP && DstGEP &&
3653 SrcGEP->getPointerOperandType() == DstGEP->getPointerOperandType()) {
3654 const SCEV *SrcPtrSCEV = SE->getSCEV(SrcGEP->getPointerOperand());
3655 const SCEV *DstPtrSCEV = SE->getSCEV(DstGEP->getPointerOperand());
3657 isLoopInvariant(SrcPtrSCEV, LI->getLoopFor(Src->getParent())) &&
3658 isLoopInvariant(DstPtrSCEV, LI->getLoopFor(Dst->getParent()));
3660 unsigned Pairs = UsefulGEP ? SrcGEP->idx_end() - SrcGEP->idx_begin() : 1;
3661 SmallVector<Subscript, 4> Pair(Pairs);
3664 for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(),
3665 SrcEnd = SrcGEP->idx_end(),
3666 DstIdx = DstGEP->idx_begin();
3668 ++SrcIdx, ++DstIdx, ++P) {
3669 Pair[P].Src = SE->getSCEV(*SrcIdx);
3670 Pair[P].Dst = SE->getSCEV(*DstIdx);
3674 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3675 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3676 Pair[0].Src = SrcSCEV;
3677 Pair[0].Dst = DstSCEV;
3680 for (unsigned P = 0; P < Pairs; ++P) {
3681 Pair[P].Loops.resize(MaxLevels + 1);
3682 Pair[P].GroupLoops.resize(MaxLevels + 1);
3683 Pair[P].Group.resize(Pairs);
3684 removeMatchingExtensions(&Pair[P]);
3685 Pair[P].Classification =
3686 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3687 Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3689 Pair[P].GroupLoops = Pair[P].Loops;
3690 Pair[P].Group.set(P);
3693 SmallBitVector Separable(Pairs);
3694 SmallBitVector Coupled(Pairs);
3696 // partition subscripts into separable and minimally-coupled groups
3697 for (unsigned SI = 0; SI < Pairs; ++SI) {
3698 if (Pair[SI].Classification == Subscript::NonLinear) {
3699 // ignore these, but collect loops for later
3700 collectCommonLoops(Pair[SI].Src,
3701 LI->getLoopFor(Src->getParent()),
3703 collectCommonLoops(Pair[SI].Dst,
3704 LI->getLoopFor(Dst->getParent()),
3706 Result.Consistent = false;
3708 else if (Pair[SI].Classification == Subscript::ZIV)
3711 // SIV, RDIV, or MIV, so check for coupled group
3713 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3714 SmallBitVector Intersection = Pair[SI].GroupLoops;
3715 Intersection &= Pair[SJ].GroupLoops;
3716 if (Intersection.any()) {
3717 // accumulate set of all the loops in group
3718 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3719 // accumulate set of all subscripts in group
3720 Pair[SJ].Group |= Pair[SI].Group;
3725 if (Pair[SI].Group.count() == 1)
3733 Constraint NewConstraint;
3734 NewConstraint.setAny(SE);
3736 // test separable subscripts
3737 for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) {
3738 switch (Pair[SI].Classification) {
3739 case Subscript::SIV: {
3741 const SCEV *SplitIter = NULL;
3742 (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
3743 Result, NewConstraint, SplitIter);
3744 if (Level == SplitLevel) {
3745 assert(SplitIter != NULL);
3750 case Subscript::ZIV:
3751 case Subscript::RDIV:
3752 case Subscript::MIV:
3755 llvm_unreachable("subscript has unexpected classification");
3759 if (Coupled.count()) {
3760 // test coupled subscript groups
3761 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3762 for (unsigned II = 0; II <= MaxLevels; ++II)
3763 Constraints[II].setAny(SE);
3764 for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) {
3765 SmallBitVector Group(Pair[SI].Group);
3766 SmallBitVector Sivs(Pairs);
3767 SmallBitVector Mivs(Pairs);
3768 SmallBitVector ConstrainedLevels(MaxLevels + 1);
3769 for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) {
3770 if (Pair[SJ].Classification == Subscript::SIV)
3775 while (Sivs.any()) {
3776 bool Changed = false;
3777 for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
3778 // SJ is an SIV subscript that's part of the current coupled group
3780 const SCEV *SplitIter = NULL;
3781 (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
3782 Result, NewConstraint, SplitIter);
3783 if (Level == SplitLevel && SplitIter)
3785 ConstrainedLevels.set(Level);
3786 if (intersectConstraints(&Constraints[Level], &NewConstraint))
3791 // propagate, possibly creating new SIVs and ZIVs
3792 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
3793 // SJ is an MIV subscript that's part of the current coupled group
3794 if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
3795 Pair[SJ].Loops, Constraints, Result.Consistent)) {
3796 Pair[SJ].Classification =
3797 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3798 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3800 switch (Pair[SJ].Classification) {
3801 case Subscript::ZIV:
3804 case Subscript::SIV:
3808 case Subscript::RDIV:
3809 case Subscript::MIV:
3812 llvm_unreachable("bad subscript classification");
3820 llvm_unreachable("somehow reached end of routine");