LLVM  mainline
DependenceAnalysis.cpp
Go to the documentation of this file.
00001 //===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // DependenceAnalysis is an LLVM pass that analyses dependences between memory
00011 // accesses. Currently, it is an (incomplete) implementation of the approach
00012 // described in
00013 //
00014 //            Practical Dependence Testing
00015 //            Goff, Kennedy, Tseng
00016 //            PLDI 1991
00017 //
00018 // There's a single entry point that analyzes the dependence between a pair
00019 // of memory references in a function, returning either NULL, for no dependence,
00020 // or a more-or-less detailed description of the dependence between them.
00021 //
00022 // Currently, the implementation cannot propagate constraints between
00023 // coupled RDIV subscripts and lacks a multi-subscript MIV test.
00024 // Both of these are conservative weaknesses;
00025 // that is, not a source of correctness problems.
00026 //
00027 // The implementation depends on the GEP instruction to differentiate
00028 // subscripts. Since Clang linearizes some array subscripts, the dependence
00029 // analysis is using SCEV->delinearize to recover the representation of multiple
00030 // subscripts, and thus avoid the more expensive and less precise MIV tests. The
00031 // delinearization is controlled by the flag -da-delinearize.
00032 //
00033 // We should pay some careful attention to the possibility of integer overflow
00034 // in the implementation of the various tests. This could happen with Add,
00035 // Subtract, or Multiply, with both APInt's and SCEV's.
00036 //
00037 // Some non-linear subscript pairs can be handled by the GCD test
00038 // (and perhaps other tests).
00039 // Should explore how often these things occur.
00040 //
00041 // Finally, it seems like certain test cases expose weaknesses in the SCEV
00042 // simplification, especially in the handling of sign and zero extensions.
00043 // It could be useful to spend time exploring these.
00044 //
00045 // Please note that this is work in progress and the interface is subject to
00046 // change.
00047 //
00048 //===----------------------------------------------------------------------===//
00049 //                                                                            //
00050 //                   In memory of Ken Kennedy, 1945 - 2007                    //
00051 //                                                                            //
00052 //===----------------------------------------------------------------------===//
00053 
00054 #include "llvm/Analysis/DependenceAnalysis.h"
00055 #include "llvm/ADT/STLExtras.h"
00056 #include "llvm/ADT/Statistic.h"
00057 #include "llvm/Analysis/AliasAnalysis.h"
00058 #include "llvm/Analysis/LoopInfo.h"
00059 #include "llvm/Analysis/ScalarEvolution.h"
00060 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00061 #include "llvm/Analysis/ValueTracking.h"
00062 #include "llvm/IR/InstIterator.h"
00063 #include "llvm/IR/Module.h"
00064 #include "llvm/IR/Operator.h"
00065 #include "llvm/Support/CommandLine.h"
00066 #include "llvm/Support/Debug.h"
00067 #include "llvm/Support/ErrorHandling.h"
00068 #include "llvm/Support/raw_ostream.h"
00069 
00070 using namespace llvm;
00071 
00072 #define DEBUG_TYPE "da"
00073 
00074 //===----------------------------------------------------------------------===//
00075 // statistics
00076 
00077 STATISTIC(TotalArrayPairs, "Array pairs tested");
00078 STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
00079 STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
00080 STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
00081 STATISTIC(ZIVapplications, "ZIV applications");
00082 STATISTIC(ZIVindependence, "ZIV independence");
00083 STATISTIC(StrongSIVapplications, "Strong SIV applications");
00084 STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
00085 STATISTIC(StrongSIVindependence, "Strong SIV independence");
00086 STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
00087 STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
00088 STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
00089 STATISTIC(ExactSIVapplications, "Exact SIV applications");
00090 STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
00091 STATISTIC(ExactSIVindependence, "Exact SIV independence");
00092 STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
00093 STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
00094 STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
00095 STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
00096 STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
00097 STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
00098 STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
00099 STATISTIC(DeltaApplications, "Delta applications");
00100 STATISTIC(DeltaSuccesses, "Delta successes");
00101 STATISTIC(DeltaIndependence, "Delta independence");
00102 STATISTIC(DeltaPropagations, "Delta propagations");
00103 STATISTIC(GCDapplications, "GCD applications");
00104 STATISTIC(GCDsuccesses, "GCD successes");
00105 STATISTIC(GCDindependence, "GCD independence");
00106 STATISTIC(BanerjeeApplications, "Banerjee applications");
00107 STATISTIC(BanerjeeIndependence, "Banerjee independence");
00108 STATISTIC(BanerjeeSuccesses, "Banerjee successes");
00109 
00110 static cl::opt<bool>
00111 Delinearize("da-delinearize", cl::init(false), cl::Hidden, cl::ZeroOrMore,
00112             cl::desc("Try to delinearize array references."));
00113 
00114 //===----------------------------------------------------------------------===//
00115 // basics
00116 
00117 INITIALIZE_PASS_BEGIN(DependenceAnalysis, "da",
00118                       "Dependence Analysis", true, true)
00119 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00120 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
00121 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00122 INITIALIZE_PASS_END(DependenceAnalysis, "da",
00123                     "Dependence Analysis", true, true)
00124 
00125 char DependenceAnalysis::ID = 0;
00126 
00127 
00128 FunctionPass *llvm::createDependenceAnalysisPass() {
00129   return new DependenceAnalysis();
00130 }
00131 
00132 
00133 bool DependenceAnalysis::runOnFunction(Function &F) {
00134   this->F = &F;
00135   AA = &getAnalysis<AliasAnalysis>();
00136   SE = &getAnalysis<ScalarEvolution>();
00137   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00138   return false;
00139 }
00140 
00141 
00142 void DependenceAnalysis::releaseMemory() {
00143 }
00144 
00145 
00146 void DependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
00147   AU.setPreservesAll();
00148   AU.addRequiredTransitive<AliasAnalysis>();
00149   AU.addRequiredTransitive<ScalarEvolution>();
00150   AU.addRequiredTransitive<LoopInfoWrapperPass>();
00151 }
00152 
00153 
00154 // Used to test the dependence analyzer.
00155 // Looks through the function, noting loads and stores.
00156 // Calls depends() on every possible pair and prints out the result.
00157 // Ignores all other instructions.
00158 static
00159 void dumpExampleDependence(raw_ostream &OS, Function *F,
00160                            DependenceAnalysis *DA) {
00161   for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F);
00162        SrcI != SrcE; ++SrcI) {
00163     if (isa<StoreInst>(*SrcI) || isa<LoadInst>(*SrcI)) {
00164       for (inst_iterator DstI = SrcI, DstE = inst_end(F);
00165            DstI != DstE; ++DstI) {
00166         if (isa<StoreInst>(*DstI) || isa<LoadInst>(*DstI)) {
00167           OS << "da analyze - ";
00168           if (auto D = DA->depends(&*SrcI, &*DstI, true)) {
00169             D->dump(OS);
00170             for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
00171               if (D->isSplitable(Level)) {
00172                 OS << "da analyze - split level = " << Level;
00173                 OS << ", iteration = " << *DA->getSplitIteration(*D, Level);
00174                 OS << "!\n";
00175               }
00176             }
00177           }
00178           else
00179             OS << "none!\n";
00180         }
00181       }
00182     }
00183   }
00184 }
00185 
00186 
00187 void DependenceAnalysis::print(raw_ostream &OS, const Module*) const {
00188   dumpExampleDependence(OS, F, const_cast<DependenceAnalysis *>(this));
00189 }
00190 
00191 //===----------------------------------------------------------------------===//
00192 // Dependence methods
00193 
00194 // Returns true if this is an input dependence.
00195 bool Dependence::isInput() const {
00196   return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
00197 }
00198 
00199 
00200 // Returns true if this is an output dependence.
00201 bool Dependence::isOutput() const {
00202   return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
00203 }
00204 
00205 
00206 // Returns true if this is an flow (aka true)  dependence.
00207 bool Dependence::isFlow() const {
00208   return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
00209 }
00210 
00211 
00212 // Returns true if this is an anti dependence.
00213 bool Dependence::isAnti() const {
00214   return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
00215 }
00216 
00217 
00218 // Returns true if a particular level is scalar; that is,
00219 // if no subscript in the source or destination mention the induction
00220 // variable associated with the loop at this level.
00221 // Leave this out of line, so it will serve as a virtual method anchor
00222 bool Dependence::isScalar(unsigned level) const {
00223   return false;
00224 }
00225 
00226 
00227 //===----------------------------------------------------------------------===//
00228 // FullDependence methods
00229 
00230 FullDependence::FullDependence(Instruction *Source, Instruction *Destination,
00231                                bool PossiblyLoopIndependent,
00232                                unsigned CommonLevels)
00233     : Dependence(Source, Destination), Levels(CommonLevels),
00234       LoopIndependent(PossiblyLoopIndependent) {
00235   Consistent = true;
00236   DV = CommonLevels ? new DVEntry[CommonLevels] : nullptr;
00237 }
00238 
00239 // The rest are simple getters that hide the implementation.
00240 
00241 // getDirection - Returns the direction associated with a particular level.
00242 unsigned FullDependence::getDirection(unsigned Level) const {
00243   assert(0 < Level && Level <= Levels && "Level out of range");
00244   return DV[Level - 1].Direction;
00245 }
00246 
00247 
00248 // Returns the distance (or NULL) associated with a particular level.
00249 const SCEV *FullDependence::getDistance(unsigned Level) const {
00250   assert(0 < Level && Level <= Levels && "Level out of range");
00251   return DV[Level - 1].Distance;
00252 }
00253 
00254 
00255 // Returns true if a particular level is scalar; that is,
00256 // if no subscript in the source or destination mention the induction
00257 // variable associated with the loop at this level.
00258 bool FullDependence::isScalar(unsigned Level) const {
00259   assert(0 < Level && Level <= Levels && "Level out of range");
00260   return DV[Level - 1].Scalar;
00261 }
00262 
00263 
00264 // Returns true if peeling the first iteration from this loop
00265 // will break this dependence.
00266 bool FullDependence::isPeelFirst(unsigned Level) const {
00267   assert(0 < Level && Level <= Levels && "Level out of range");
00268   return DV[Level - 1].PeelFirst;
00269 }
00270 
00271 
00272 // Returns true if peeling the last iteration from this loop
00273 // will break this dependence.
00274 bool FullDependence::isPeelLast(unsigned Level) const {
00275   assert(0 < Level && Level <= Levels && "Level out of range");
00276   return DV[Level - 1].PeelLast;
00277 }
00278 
00279 
00280 // Returns true if splitting this loop will break the dependence.
00281 bool FullDependence::isSplitable(unsigned Level) const {
00282   assert(0 < Level && Level <= Levels && "Level out of range");
00283   return DV[Level - 1].Splitable;
00284 }
00285 
00286 
00287 //===----------------------------------------------------------------------===//
00288 // DependenceAnalysis::Constraint methods
00289 
00290 // If constraint is a point <X, Y>, returns X.
00291 // Otherwise assert.
00292 const SCEV *DependenceAnalysis::Constraint::getX() const {
00293   assert(Kind == Point && "Kind should be Point");
00294   return A;
00295 }
00296 
00297 
00298 // If constraint is a point <X, Y>, returns Y.
00299 // Otherwise assert.
00300 const SCEV *DependenceAnalysis::Constraint::getY() const {
00301   assert(Kind == Point && "Kind should be Point");
00302   return B;
00303 }
00304 
00305 
00306 // If constraint is a line AX + BY = C, returns A.
00307 // Otherwise assert.
00308 const SCEV *DependenceAnalysis::Constraint::getA() const {
00309   assert((Kind == Line || Kind == Distance) &&
00310          "Kind should be Line (or Distance)");
00311   return A;
00312 }
00313 
00314 
00315 // If constraint is a line AX + BY = C, returns B.
00316 // Otherwise assert.
00317 const SCEV *DependenceAnalysis::Constraint::getB() const {
00318   assert((Kind == Line || Kind == Distance) &&
00319          "Kind should be Line (or Distance)");
00320   return B;
00321 }
00322 
00323 
00324 // If constraint is a line AX + BY = C, returns C.
00325 // Otherwise assert.
00326 const SCEV *DependenceAnalysis::Constraint::getC() const {
00327   assert((Kind == Line || Kind == Distance) &&
00328          "Kind should be Line (or Distance)");
00329   return C;
00330 }
00331 
00332 
00333 // If constraint is a distance, returns D.
00334 // Otherwise assert.
00335 const SCEV *DependenceAnalysis::Constraint::getD() const {
00336   assert(Kind == Distance && "Kind should be Distance");
00337   return SE->getNegativeSCEV(C);
00338 }
00339 
00340 
00341 // Returns the loop associated with this constraint.
00342 const Loop *DependenceAnalysis::Constraint::getAssociatedLoop() const {
00343   assert((Kind == Distance || Kind == Line || Kind == Point) &&
00344          "Kind should be Distance, Line, or Point");
00345   return AssociatedLoop;
00346 }
00347 
00348 
00349 void DependenceAnalysis::Constraint::setPoint(const SCEV *X,
00350                                               const SCEV *Y,
00351                                               const Loop *CurLoop) {
00352   Kind = Point;
00353   A = X;
00354   B = Y;
00355   AssociatedLoop = CurLoop;
00356 }
00357 
00358 
00359 void DependenceAnalysis::Constraint::setLine(const SCEV *AA,
00360                                              const SCEV *BB,
00361                                              const SCEV *CC,
00362                                              const Loop *CurLoop) {
00363   Kind = Line;
00364   A = AA;
00365   B = BB;
00366   C = CC;
00367   AssociatedLoop = CurLoop;
00368 }
00369 
00370 
00371 void DependenceAnalysis::Constraint::setDistance(const SCEV *D,
00372                                                  const Loop *CurLoop) {
00373   Kind = Distance;
00374   A = SE->getConstant(D->getType(), 1);
00375   B = SE->getNegativeSCEV(A);
00376   C = SE->getNegativeSCEV(D);
00377   AssociatedLoop = CurLoop;
00378 }
00379 
00380 
00381 void DependenceAnalysis::Constraint::setEmpty() {
00382   Kind = Empty;
00383 }
00384 
00385 
00386 void DependenceAnalysis::Constraint::setAny(ScalarEvolution *NewSE) {
00387   SE = NewSE;
00388   Kind = Any;
00389 }
00390 
00391 
00392 // For debugging purposes. Dumps the constraint out to OS.
00393 void DependenceAnalysis::Constraint::dump(raw_ostream &OS) const {
00394   if (isEmpty())
00395     OS << " Empty\n";
00396   else if (isAny())
00397     OS << " Any\n";
00398   else if (isPoint())
00399     OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
00400   else if (isDistance())
00401     OS << " Distance is " << *getD() <<
00402       " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
00403   else if (isLine())
00404     OS << " Line is " << *getA() << "*X + " <<
00405       *getB() << "*Y = " << *getC() << "\n";
00406   else
00407     llvm_unreachable("unknown constraint type in Constraint::dump");
00408 }
00409 
00410 
00411 // Updates X with the intersection
00412 // of the Constraints X and Y. Returns true if X has changed.
00413 // Corresponds to Figure 4 from the paper
00414 //
00415 //            Practical Dependence Testing
00416 //            Goff, Kennedy, Tseng
00417 //            PLDI 1991
00418 bool DependenceAnalysis::intersectConstraints(Constraint *X,
00419                                               const Constraint *Y) {
00420   ++DeltaApplications;
00421   DEBUG(dbgs() << "\tintersect constraints\n");
00422   DEBUG(dbgs() << "\t    X ="; X->dump(dbgs()));
00423   DEBUG(dbgs() << "\t    Y ="; Y->dump(dbgs()));
00424   assert(!Y->isPoint() && "Y must not be a Point");
00425   if (X->isAny()) {
00426     if (Y->isAny())
00427       return false;
00428     *X = *Y;
00429     return true;
00430   }
00431   if (X->isEmpty())
00432     return false;
00433   if (Y->isEmpty()) {
00434     X->setEmpty();
00435     return true;
00436   }
00437 
00438   if (X->isDistance() && Y->isDistance()) {
00439     DEBUG(dbgs() << "\t    intersect 2 distances\n");
00440     if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
00441       return false;
00442     if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
00443       X->setEmpty();
00444       ++DeltaSuccesses;
00445       return true;
00446     }
00447     // Hmmm, interesting situation.
00448     // I guess if either is constant, keep it and ignore the other.
00449     if (isa<SCEVConstant>(Y->getD())) {
00450       *X = *Y;
00451       return true;
00452     }
00453     return false;
00454   }
00455 
00456   // At this point, the pseudo-code in Figure 4 of the paper
00457   // checks if (X->isPoint() && Y->isPoint()).
00458   // This case can't occur in our implementation,
00459   // since a Point can only arise as the result of intersecting
00460   // two Line constraints, and the right-hand value, Y, is never
00461   // the result of an intersection.
00462   assert(!(X->isPoint() && Y->isPoint()) &&
00463          "We shouldn't ever see X->isPoint() && Y->isPoint()");
00464 
00465   if (X->isLine() && Y->isLine()) {
00466     DEBUG(dbgs() << "\t    intersect 2 lines\n");
00467     const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
00468     const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
00469     if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
00470       // slopes are equal, so lines are parallel
00471       DEBUG(dbgs() << "\t\tsame slope\n");
00472       Prod1 = SE->getMulExpr(X->getC(), Y->getB());
00473       Prod2 = SE->getMulExpr(X->getB(), Y->getC());
00474       if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
00475         return false;
00476       if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
00477         X->setEmpty();
00478         ++DeltaSuccesses;
00479         return true;
00480       }
00481       return false;
00482     }
00483     if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
00484       // slopes differ, so lines intersect
00485       DEBUG(dbgs() << "\t\tdifferent slopes\n");
00486       const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
00487       const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
00488       const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
00489       const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
00490       const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
00491       const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
00492       const SCEVConstant *C1A2_C2A1 =
00493         dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
00494       const SCEVConstant *C1B2_C2B1 =
00495         dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
00496       const SCEVConstant *A1B2_A2B1 =
00497         dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
00498       const SCEVConstant *A2B1_A1B2 =
00499         dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
00500       if (!C1B2_C2B1 || !C1A2_C2A1 ||
00501           !A1B2_A2B1 || !A2B1_A1B2)
00502         return false;
00503       APInt Xtop = C1B2_C2B1->getValue()->getValue();
00504       APInt Xbot = A1B2_A2B1->getValue()->getValue();
00505       APInt Ytop = C1A2_C2A1->getValue()->getValue();
00506       APInt Ybot = A2B1_A1B2->getValue()->getValue();
00507       DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
00508       DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
00509       DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
00510       DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
00511       APInt Xq = Xtop; // these need to be initialized, even
00512       APInt Xr = Xtop; // though they're just going to be overwritten
00513       APInt::sdivrem(Xtop, Xbot, Xq, Xr);
00514       APInt Yq = Ytop;
00515       APInt Yr = Ytop;
00516       APInt::sdivrem(Ytop, Ybot, Yq, Yr);
00517       if (Xr != 0 || Yr != 0) {
00518         X->setEmpty();
00519         ++DeltaSuccesses;
00520         return true;
00521       }
00522       DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
00523       if (Xq.slt(0) || Yq.slt(0)) {
00524         X->setEmpty();
00525         ++DeltaSuccesses;
00526         return true;
00527       }
00528       if (const SCEVConstant *CUB =
00529           collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
00530         APInt UpperBound = CUB->getValue()->getValue();
00531         DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
00532         if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
00533           X->setEmpty();
00534           ++DeltaSuccesses;
00535           return true;
00536         }
00537       }
00538       X->setPoint(SE->getConstant(Xq),
00539                   SE->getConstant(Yq),
00540                   X->getAssociatedLoop());
00541       ++DeltaSuccesses;
00542       return true;
00543     }
00544     return false;
00545   }
00546 
00547   // if (X->isLine() && Y->isPoint()) This case can't occur.
00548   assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
00549 
00550   if (X->isPoint() && Y->isLine()) {
00551     DEBUG(dbgs() << "\t    intersect Point and Line\n");
00552     const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
00553     const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
00554     const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
00555     if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
00556       return false;
00557     if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
00558       X->setEmpty();
00559       ++DeltaSuccesses;
00560       return true;
00561     }
00562     return false;
00563   }
00564 
00565   llvm_unreachable("shouldn't reach the end of Constraint intersection");
00566   return false;
00567 }
00568 
00569 
00570 //===----------------------------------------------------------------------===//
00571 // DependenceAnalysis methods
00572 
00573 // For debugging purposes. Dumps a dependence to OS.
00574 void Dependence::dump(raw_ostream &OS) const {
00575   bool Splitable = false;
00576   if (isConfused())
00577     OS << "confused";
00578   else {
00579     if (isConsistent())
00580       OS << "consistent ";
00581     if (isFlow())
00582       OS << "flow";
00583     else if (isOutput())
00584       OS << "output";
00585     else if (isAnti())
00586       OS << "anti";
00587     else if (isInput())
00588       OS << "input";
00589     unsigned Levels = getLevels();
00590     OS << " [";
00591     for (unsigned II = 1; II <= Levels; ++II) {
00592       if (isSplitable(II))
00593         Splitable = true;
00594       if (isPeelFirst(II))
00595         OS << 'p';
00596       const SCEV *Distance = getDistance(II);
00597       if (Distance)
00598         OS << *Distance;
00599       else if (isScalar(II))
00600         OS << "S";
00601       else {
00602         unsigned Direction = getDirection(II);
00603         if (Direction == DVEntry::ALL)
00604           OS << "*";
00605         else {
00606           if (Direction & DVEntry::LT)
00607             OS << "<";
00608           if (Direction & DVEntry::EQ)
00609             OS << "=";
00610           if (Direction & DVEntry::GT)
00611             OS << ">";
00612         }
00613       }
00614       if (isPeelLast(II))
00615         OS << 'p';
00616       if (II < Levels)
00617         OS << " ";
00618     }
00619     if (isLoopIndependent())
00620       OS << "|<";
00621     OS << "]";
00622     if (Splitable)
00623       OS << " splitable";
00624   }
00625   OS << "!\n";
00626 }
00627 
00628 static AliasResult underlyingObjectsAlias(AliasAnalysis *AA,
00629                                           const DataLayout &DL, const Value *A,
00630                                           const Value *B) {
00631   const Value *AObj = GetUnderlyingObject(A, DL);
00632   const Value *BObj = GetUnderlyingObject(B, DL);
00633   return AA->alias(AObj, AA->getTypeStoreSize(AObj->getType()),
00634                    BObj, AA->getTypeStoreSize(BObj->getType()));
00635 }
00636 
00637 
00638 // Returns true if the load or store can be analyzed. Atomic and volatile
00639 // operations have properties which this analysis does not understand.
00640 static
00641 bool isLoadOrStore(const Instruction *I) {
00642   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
00643     return LI->isUnordered();
00644   else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
00645     return SI->isUnordered();
00646   return false;
00647 }
00648 
00649 
00650 static
00651 Value *getPointerOperand(Instruction *I) {
00652   if (LoadInst *LI = dyn_cast<LoadInst>(I))
00653     return LI->getPointerOperand();
00654   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00655     return SI->getPointerOperand();
00656   llvm_unreachable("Value is not load or store instruction");
00657   return nullptr;
00658 }
00659 
00660 
00661 // Examines the loop nesting of the Src and Dst
00662 // instructions and establishes their shared loops. Sets the variables
00663 // CommonLevels, SrcLevels, and MaxLevels.
00664 // The source and destination instructions needn't be contained in the same
00665 // loop. The routine establishNestingLevels finds the level of most deeply
00666 // nested loop that contains them both, CommonLevels. An instruction that's
00667 // not contained in a loop is at level = 0. MaxLevels is equal to the level
00668 // of the source plus the level of the destination, minus CommonLevels.
00669 // This lets us allocate vectors MaxLevels in length, with room for every
00670 // distinct loop referenced in both the source and destination subscripts.
00671 // The variable SrcLevels is the nesting depth of the source instruction.
00672 // It's used to help calculate distinct loops referenced by the destination.
00673 // Here's the map from loops to levels:
00674 //            0 - unused
00675 //            1 - outermost common loop
00676 //          ... - other common loops
00677 // CommonLevels - innermost common loop
00678 //          ... - loops containing Src but not Dst
00679 //    SrcLevels - innermost loop containing Src but not Dst
00680 //          ... - loops containing Dst but not Src
00681 //    MaxLevels - innermost loops containing Dst but not Src
00682 // Consider the follow code fragment:
00683 //   for (a = ...) {
00684 //     for (b = ...) {
00685 //       for (c = ...) {
00686 //         for (d = ...) {
00687 //           A[] = ...;
00688 //         }
00689 //       }
00690 //       for (e = ...) {
00691 //         for (f = ...) {
00692 //           for (g = ...) {
00693 //             ... = A[];
00694 //           }
00695 //         }
00696 //       }
00697 //     }
00698 //   }
00699 // If we're looking at the possibility of a dependence between the store
00700 // to A (the Src) and the load from A (the Dst), we'll note that they
00701 // have 2 loops in common, so CommonLevels will equal 2 and the direction
00702 // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
00703 // A map from loop names to loop numbers would look like
00704 //     a - 1
00705 //     b - 2 = CommonLevels
00706 //     c - 3
00707 //     d - 4 = SrcLevels
00708 //     e - 5
00709 //     f - 6
00710 //     g - 7 = MaxLevels
00711 void DependenceAnalysis::establishNestingLevels(const Instruction *Src,
00712                                                 const Instruction *Dst) {
00713   const BasicBlock *SrcBlock = Src->getParent();
00714   const BasicBlock *DstBlock = Dst->getParent();
00715   unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
00716   unsigned DstLevel = LI->getLoopDepth(DstBlock);
00717   const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
00718   const Loop *DstLoop = LI->getLoopFor(DstBlock);
00719   SrcLevels = SrcLevel;
00720   MaxLevels = SrcLevel + DstLevel;
00721   while (SrcLevel > DstLevel) {
00722     SrcLoop = SrcLoop->getParentLoop();
00723     SrcLevel--;
00724   }
00725   while (DstLevel > SrcLevel) {
00726     DstLoop = DstLoop->getParentLoop();
00727     DstLevel--;
00728   }
00729   while (SrcLoop != DstLoop) {
00730     SrcLoop = SrcLoop->getParentLoop();
00731     DstLoop = DstLoop->getParentLoop();
00732     SrcLevel--;
00733   }
00734   CommonLevels = SrcLevel;
00735   MaxLevels -= CommonLevels;
00736 }
00737 
00738 
00739 // Given one of the loops containing the source, return
00740 // its level index in our numbering scheme.
00741 unsigned DependenceAnalysis::mapSrcLoop(const Loop *SrcLoop) const {
00742   return SrcLoop->getLoopDepth();
00743 }
00744 
00745 
00746 // Given one of the loops containing the destination,
00747 // return its level index in our numbering scheme.
00748 unsigned DependenceAnalysis::mapDstLoop(const Loop *DstLoop) const {
00749   unsigned D = DstLoop->getLoopDepth();
00750   if (D > CommonLevels)
00751     return D - CommonLevels + SrcLevels;
00752   else
00753     return D;
00754 }
00755 
00756 
00757 // Returns true if Expression is loop invariant in LoopNest.
00758 bool DependenceAnalysis::isLoopInvariant(const SCEV *Expression,
00759                                          const Loop *LoopNest) const {
00760   if (!LoopNest)
00761     return true;
00762   return SE->isLoopInvariant(Expression, LoopNest) &&
00763     isLoopInvariant(Expression, LoopNest->getParentLoop());
00764 }
00765 
00766 
00767 
00768 // Finds the set of loops from the LoopNest that
00769 // have a level <= CommonLevels and are referred to by the SCEV Expression.
00770 void DependenceAnalysis::collectCommonLoops(const SCEV *Expression,
00771                                             const Loop *LoopNest,
00772                                             SmallBitVector &Loops) const {
00773   while (LoopNest) {
00774     unsigned Level = LoopNest->getLoopDepth();
00775     if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
00776       Loops.set(Level);
00777     LoopNest = LoopNest->getParentLoop();
00778   }
00779 }
00780 
00781 void DependenceAnalysis::unifySubscriptType(ArrayRef<Subscript *> Pairs) {
00782 
00783   unsigned widestWidthSeen = 0;
00784   Type *widestType;
00785 
00786   // Go through each pair and find the widest bit to which we need
00787   // to extend all of them.
00788   for (unsigned i = 0; i < Pairs.size(); i++) {
00789     const SCEV *Src = Pairs[i]->Src;
00790     const SCEV *Dst = Pairs[i]->Dst;
00791     IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
00792     IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
00793     if (SrcTy == nullptr || DstTy == nullptr) {
00794       assert(SrcTy == DstTy && "This function only unify integer types and "
00795              "expect Src and Dst share the same type "
00796              "otherwise.");
00797       continue;
00798     }
00799     if (SrcTy->getBitWidth() > widestWidthSeen) {
00800       widestWidthSeen = SrcTy->getBitWidth();
00801       widestType = SrcTy;
00802     }
00803     if (DstTy->getBitWidth() > widestWidthSeen) {
00804       widestWidthSeen = DstTy->getBitWidth();
00805       widestType = DstTy;
00806     }
00807   }
00808 
00809 
00810   assert(widestWidthSeen > 0);
00811 
00812   // Now extend each pair to the widest seen.
00813   for (unsigned i = 0; i < Pairs.size(); i++) {
00814     const SCEV *Src = Pairs[i]->Src;
00815     const SCEV *Dst = Pairs[i]->Dst;
00816     IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
00817     IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
00818     if (SrcTy == nullptr || DstTy == nullptr) {
00819       assert(SrcTy == DstTy && "This function only unify integer types and "
00820              "expect Src and Dst share the same type "
00821              "otherwise.");
00822       continue;
00823     }
00824     if (SrcTy->getBitWidth() < widestWidthSeen)
00825       // Sign-extend Src to widestType
00826       Pairs[i]->Src = SE->getSignExtendExpr(Src, widestType);
00827     if (DstTy->getBitWidth() < widestWidthSeen) {
00828       // Sign-extend Dst to widestType
00829       Pairs[i]->Dst = SE->getSignExtendExpr(Dst, widestType);
00830     }
00831   }
00832 }
00833 
00834 // removeMatchingExtensions - Examines a subscript pair.
00835 // If the source and destination are identically sign (or zero)
00836 // extended, it strips off the extension in an effect to simplify
00837 // the actual analysis.
00838 void DependenceAnalysis::removeMatchingExtensions(Subscript *Pair) {
00839   const SCEV *Src = Pair->Src;
00840   const SCEV *Dst = Pair->Dst;
00841   if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
00842       (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
00843     const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src);
00844     const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst);
00845     const SCEV *SrcCastOp = SrcCast->getOperand();
00846     const SCEV *DstCastOp = DstCast->getOperand();
00847     if (SrcCastOp->getType() == DstCastOp->getType()) {
00848       Pair->Src = SrcCastOp;
00849       Pair->Dst = DstCastOp;
00850     }
00851   }
00852 }
00853 
00854 
00855 // Examine the scev and return true iff it's linear.
00856 // Collect any loops mentioned in the set of "Loops".
00857 bool DependenceAnalysis::checkSrcSubscript(const SCEV *Src,
00858                                            const Loop *LoopNest,
00859                                            SmallBitVector &Loops) {
00860   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Src);
00861   if (!AddRec)
00862     return isLoopInvariant(Src, LoopNest);
00863   const SCEV *Start = AddRec->getStart();
00864   const SCEV *Step = AddRec->getStepRecurrence(*SE);
00865   const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
00866   if (!isa<SCEVCouldNotCompute>(UB)) {
00867     if (SE->getTypeSizeInBits(Start->getType()) <
00868         SE->getTypeSizeInBits(UB->getType())) {
00869       if (!AddRec->getNoWrapFlags())
00870         return false;
00871     }
00872   }
00873   if (!isLoopInvariant(Step, LoopNest))
00874     return false;
00875   Loops.set(mapSrcLoop(AddRec->getLoop()));
00876   return checkSrcSubscript(Start, LoopNest, Loops);
00877 }
00878 
00879 
00880 
00881 // Examine the scev and return true iff it's linear.
00882 // Collect any loops mentioned in the set of "Loops".
00883 bool DependenceAnalysis::checkDstSubscript(const SCEV *Dst,
00884                                            const Loop *LoopNest,
00885                                            SmallBitVector &Loops) {
00886   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Dst);
00887   if (!AddRec)
00888     return isLoopInvariant(Dst, LoopNest);
00889   const SCEV *Start = AddRec->getStart();
00890   const SCEV *Step = AddRec->getStepRecurrence(*SE);
00891   const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
00892   if (!isa<SCEVCouldNotCompute>(UB)) {
00893     if (SE->getTypeSizeInBits(Start->getType()) <
00894         SE->getTypeSizeInBits(UB->getType())) {
00895       if (!AddRec->getNoWrapFlags())
00896         return false;
00897     }
00898   }
00899   if (!isLoopInvariant(Step, LoopNest))
00900     return false;
00901   Loops.set(mapDstLoop(AddRec->getLoop()));
00902   return checkDstSubscript(Start, LoopNest, Loops);
00903 }
00904 
00905 
00906 // Examines the subscript pair (the Src and Dst SCEVs)
00907 // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
00908 // Collects the associated loops in a set.
00909 DependenceAnalysis::Subscript::ClassificationKind
00910 DependenceAnalysis::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
00911                                  const SCEV *Dst, const Loop *DstLoopNest,
00912                                  SmallBitVector &Loops) {
00913   SmallBitVector SrcLoops(MaxLevels + 1);
00914   SmallBitVector DstLoops(MaxLevels + 1);
00915   if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
00916     return Subscript::NonLinear;
00917   if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
00918     return Subscript::NonLinear;
00919   Loops = SrcLoops;
00920   Loops |= DstLoops;
00921   unsigned N = Loops.count();
00922   if (N == 0)
00923     return Subscript::ZIV;
00924   if (N == 1)
00925     return Subscript::SIV;
00926   if (N == 2 && (SrcLoops.count() == 0 ||
00927                  DstLoops.count() == 0 ||
00928                  (SrcLoops.count() == 1 && DstLoops.count() == 1)))
00929     return Subscript::RDIV;
00930   return Subscript::MIV;
00931 }
00932 
00933 
00934 // A wrapper around SCEV::isKnownPredicate.
00935 // Looks for cases where we're interested in comparing for equality.
00936 // If both X and Y have been identically sign or zero extended,
00937 // it strips off the (confusing) extensions before invoking
00938 // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
00939 // will be similarly updated.
00940 //
00941 // If SCEV::isKnownPredicate can't prove the predicate,
00942 // we try simple subtraction, which seems to help in some cases
00943 // involving symbolics.
00944 bool DependenceAnalysis::isKnownPredicate(ICmpInst::Predicate Pred,
00945                                           const SCEV *X,
00946                                           const SCEV *Y) const {
00947   if (Pred == CmpInst::ICMP_EQ ||
00948       Pred == CmpInst::ICMP_NE) {
00949     if ((isa<SCEVSignExtendExpr>(X) &&
00950          isa<SCEVSignExtendExpr>(Y)) ||
00951         (isa<SCEVZeroExtendExpr>(X) &&
00952          isa<SCEVZeroExtendExpr>(Y))) {
00953       const SCEVCastExpr *CX = cast<SCEVCastExpr>(X);
00954       const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y);
00955       const SCEV *Xop = CX->getOperand();
00956       const SCEV *Yop = CY->getOperand();
00957       if (Xop->getType() == Yop->getType()) {
00958         X = Xop;
00959         Y = Yop;
00960       }
00961     }
00962   }
00963   if (SE->isKnownPredicate(Pred, X, Y))
00964     return true;
00965   // If SE->isKnownPredicate can't prove the condition,
00966   // we try the brute-force approach of subtracting
00967   // and testing the difference.
00968   // By testing with SE->isKnownPredicate first, we avoid
00969   // the possibility of overflow when the arguments are constants.
00970   const SCEV *Delta = SE->getMinusSCEV(X, Y);
00971   switch (Pred) {
00972   case CmpInst::ICMP_EQ:
00973     return Delta->isZero();
00974   case CmpInst::ICMP_NE:
00975     return SE->isKnownNonZero(Delta);
00976   case CmpInst::ICMP_SGE:
00977     return SE->isKnownNonNegative(Delta);
00978   case CmpInst::ICMP_SLE:
00979     return SE->isKnownNonPositive(Delta);
00980   case CmpInst::ICMP_SGT:
00981     return SE->isKnownPositive(Delta);
00982   case CmpInst::ICMP_SLT:
00983     return SE->isKnownNegative(Delta);
00984   default:
00985     llvm_unreachable("unexpected predicate in isKnownPredicate");
00986   }
00987 }
00988 
00989 
00990 // All subscripts are all the same type.
00991 // Loop bound may be smaller (e.g., a char).
00992 // Should zero extend loop bound, since it's always >= 0.
00993 // This routine collects upper bound and extends or truncates if needed.
00994 // Truncating is safe when subscripts are known not to wrap. Cases without
00995 // nowrap flags should have been rejected earlier.
00996 // Return null if no bound available.
00997 const SCEV *DependenceAnalysis::collectUpperBound(const Loop *L,
00998                                                   Type *T) const {
00999   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
01000     const SCEV *UB = SE->getBackedgeTakenCount(L);
01001     return SE->getTruncateOrZeroExtend(UB, T);
01002   }
01003   return nullptr;
01004 }
01005 
01006 
01007 // Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
01008 // If the cast fails, returns NULL.
01009 const SCEVConstant *DependenceAnalysis::collectConstantUpperBound(const Loop *L,
01010                                                                   Type *T
01011                                                                   ) const {
01012   if (const SCEV *UB = collectUpperBound(L, T))
01013     return dyn_cast<SCEVConstant>(UB);
01014   return nullptr;
01015 }
01016 
01017 
01018 // testZIV -
01019 // When we have a pair of subscripts of the form [c1] and [c2],
01020 // where c1 and c2 are both loop invariant, we attack it using
01021 // the ZIV test. Basically, we test by comparing the two values,
01022 // but there are actually three possible results:
01023 // 1) the values are equal, so there's a dependence
01024 // 2) the values are different, so there's no dependence
01025 // 3) the values might be equal, so we have to assume a dependence.
01026 //
01027 // Return true if dependence disproved.
01028 bool DependenceAnalysis::testZIV(const SCEV *Src,
01029                                  const SCEV *Dst,
01030                                  FullDependence &Result) const {
01031   DEBUG(dbgs() << "    src = " << *Src << "\n");
01032   DEBUG(dbgs() << "    dst = " << *Dst << "\n");
01033   ++ZIVapplications;
01034   if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
01035     DEBUG(dbgs() << "    provably dependent\n");
01036     return false; // provably dependent
01037   }
01038   if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
01039     DEBUG(dbgs() << "    provably independent\n");
01040     ++ZIVindependence;
01041     return true; // provably independent
01042   }
01043   DEBUG(dbgs() << "    possibly dependent\n");
01044   Result.Consistent = false;
01045   return false; // possibly dependent
01046 }
01047 
01048 
01049 // strongSIVtest -
01050 // From the paper, Practical Dependence Testing, Section 4.2.1
01051 //
01052 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
01053 // where i is an induction variable, c1 and c2 are loop invariant,
01054 //  and a is a constant, we can solve it exactly using the Strong SIV test.
01055 //
01056 // Can prove independence. Failing that, can compute distance (and direction).
01057 // In the presence of symbolic terms, we can sometimes make progress.
01058 //
01059 // If there's a dependence,
01060 //
01061 //    c1 + a*i = c2 + a*i'
01062 //
01063 // The dependence distance is
01064 //
01065 //    d = i' - i = (c1 - c2)/a
01066 //
01067 // A dependence only exists if d is an integer and abs(d) <= U, where U is the
01068 // loop's upper bound. If a dependence exists, the dependence direction is
01069 // defined as
01070 //
01071 //                { < if d > 0
01072 //    direction = { = if d = 0
01073 //                { > if d < 0
01074 //
01075 // Return true if dependence disproved.
01076 bool DependenceAnalysis::strongSIVtest(const SCEV *Coeff,
01077                                        const SCEV *SrcConst,
01078                                        const SCEV *DstConst,
01079                                        const Loop *CurLoop,
01080                                        unsigned Level,
01081                                        FullDependence &Result,
01082                                        Constraint &NewConstraint) const {
01083   DEBUG(dbgs() << "\tStrong SIV test\n");
01084   DEBUG(dbgs() << "\t    Coeff = " << *Coeff);
01085   DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
01086   DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst);
01087   DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
01088   DEBUG(dbgs() << "\t    DstConst = " << *DstConst);
01089   DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
01090   ++StrongSIVapplications;
01091   assert(0 < Level && Level <= CommonLevels && "level out of range");
01092   Level--;
01093 
01094   const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
01095   DEBUG(dbgs() << "\t    Delta = " << *Delta);
01096   DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
01097 
01098   // check that |Delta| < iteration count
01099   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
01100     DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound);
01101     DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
01102     const SCEV *AbsDelta =
01103       SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
01104     const SCEV *AbsCoeff =
01105       SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
01106     const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
01107     if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
01108       // Distance greater than trip count - no dependence
01109       ++StrongSIVindependence;
01110       ++StrongSIVsuccesses;
01111       return true;
01112     }
01113   }
01114 
01115   // Can we compute distance?
01116   if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
01117     APInt ConstDelta = cast<SCEVConstant>(Delta)->getValue()->getValue();
01118     APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getValue()->getValue();
01119     APInt Distance  = ConstDelta; // these need to be initialized
01120     APInt Remainder = ConstDelta;
01121     APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
01122     DEBUG(dbgs() << "\t    Distance = " << Distance << "\n");
01123     DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
01124     // Make sure Coeff divides Delta exactly
01125     if (Remainder != 0) {
01126       // Coeff doesn't divide Distance, no dependence
01127       ++StrongSIVindependence;
01128       ++StrongSIVsuccesses;
01129       return true;
01130     }
01131     Result.DV[Level].Distance = SE->getConstant(Distance);
01132     NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
01133     if (Distance.sgt(0))
01134       Result.DV[Level].Direction &= Dependence::DVEntry::LT;
01135     else if (Distance.slt(0))
01136       Result.DV[Level].Direction &= Dependence::DVEntry::GT;
01137     else
01138       Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
01139     ++StrongSIVsuccesses;
01140   }
01141   else if (Delta->isZero()) {
01142     // since 0/X == 0
01143     Result.DV[Level].Distance = Delta;
01144     NewConstraint.setDistance(Delta, CurLoop);
01145     Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
01146     ++StrongSIVsuccesses;
01147   }
01148   else {
01149     if (Coeff->isOne()) {
01150       DEBUG(dbgs() << "\t    Distance = " << *Delta << "\n");
01151       Result.DV[Level].Distance = Delta; // since X/1 == X
01152       NewConstraint.setDistance(Delta, CurLoop);
01153     }
01154     else {
01155       Result.Consistent = false;
01156       NewConstraint.setLine(Coeff,
01157                             SE->getNegativeSCEV(Coeff),
01158                             SE->getNegativeSCEV(Delta), CurLoop);
01159     }
01160 
01161     // maybe we can get a useful direction
01162     bool DeltaMaybeZero     = !SE->isKnownNonZero(Delta);
01163     bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
01164     bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
01165     bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
01166     bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
01167     // The double negatives above are confusing.
01168     // It helps to read !SE->isKnownNonZero(Delta)
01169     // as "Delta might be Zero"
01170     unsigned NewDirection = Dependence::DVEntry::NONE;
01171     if ((DeltaMaybePositive && CoeffMaybePositive) ||
01172         (DeltaMaybeNegative && CoeffMaybeNegative))
01173       NewDirection = Dependence::DVEntry::LT;
01174     if (DeltaMaybeZero)
01175       NewDirection |= Dependence::DVEntry::EQ;
01176     if ((DeltaMaybeNegative && CoeffMaybePositive) ||
01177         (DeltaMaybePositive && CoeffMaybeNegative))
01178       NewDirection |= Dependence::DVEntry::GT;
01179     if (NewDirection < Result.DV[Level].Direction)
01180       ++StrongSIVsuccesses;
01181     Result.DV[Level].Direction &= NewDirection;
01182   }
01183   return false;
01184 }
01185 
01186 
01187 // weakCrossingSIVtest -
01188 // From the paper, Practical Dependence Testing, Section 4.2.2
01189 //
01190 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
01191 // where i is an induction variable, c1 and c2 are loop invariant,
01192 // and a is a constant, we can solve it exactly using the
01193 // Weak-Crossing SIV test.
01194 //
01195 // Given c1 + a*i = c2 - a*i', we can look for the intersection of
01196 // the two lines, where i = i', yielding
01197 //
01198 //    c1 + a*i = c2 - a*i
01199 //    2a*i = c2 - c1
01200 //    i = (c2 - c1)/2a
01201 //
01202 // If i < 0, there is no dependence.
01203 // If i > upperbound, there is no dependence.
01204 // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
01205 // If i = upperbound, there's a dependence with distance = 0.
01206 // If i is integral, there's a dependence (all directions).
01207 // If the non-integer part = 1/2, there's a dependence (<> directions).
01208 // Otherwise, there's no dependence.
01209 //
01210 // Can prove independence. Failing that,
01211 // can sometimes refine the directions.
01212 // Can determine iteration for splitting.
01213 //
01214 // Return true if dependence disproved.
01215 bool DependenceAnalysis::weakCrossingSIVtest(const SCEV *Coeff,
01216                                              const SCEV *SrcConst,
01217                                              const SCEV *DstConst,
01218                                              const Loop *CurLoop,
01219                                              unsigned Level,
01220                                              FullDependence &Result,
01221                                              Constraint &NewConstraint,
01222                                              const SCEV *&SplitIter) const {
01223   DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
01224   DEBUG(dbgs() << "\t    Coeff = " << *Coeff << "\n");
01225   DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
01226   DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
01227   ++WeakCrossingSIVapplications;
01228   assert(0 < Level && Level <= CommonLevels && "Level out of range");
01229   Level--;
01230   Result.Consistent = false;
01231   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
01232   DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
01233   NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
01234   if (Delta->isZero()) {
01235     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
01236     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
01237     ++WeakCrossingSIVsuccesses;
01238     if (!Result.DV[Level].Direction) {
01239       ++WeakCrossingSIVindependence;
01240       return true;
01241     }
01242     Result.DV[Level].Distance = Delta; // = 0
01243     return false;
01244   }
01245   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
01246   if (!ConstCoeff)
01247     return false;
01248 
01249   Result.DV[Level].Splitable = true;
01250   if (SE->isKnownNegative(ConstCoeff)) {
01251     ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
01252     assert(ConstCoeff &&
01253            "dynamic cast of negative of ConstCoeff should yield constant");
01254     Delta = SE->getNegativeSCEV(Delta);
01255   }
01256   assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
01257 
01258   // compute SplitIter for use by DependenceAnalysis::getSplitIteration()
01259   SplitIter =
01260     SE->getUDivExpr(SE->getSMaxExpr(SE->getConstant(Delta->getType(), 0),
01261                                     Delta),
01262                     SE->getMulExpr(SE->getConstant(Delta->getType(), 2),
01263                                    ConstCoeff));
01264   DEBUG(dbgs() << "\t    Split iter = " << *SplitIter << "\n");
01265 
01266   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
01267   if (!ConstDelta)
01268     return false;
01269 
01270   // We're certain that ConstCoeff > 0; therefore,
01271   // if Delta < 0, then no dependence.
01272   DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
01273   DEBUG(dbgs() << "\t    ConstCoeff = " << *ConstCoeff << "\n");
01274   if (SE->isKnownNegative(Delta)) {
01275     // No dependence, Delta < 0
01276     ++WeakCrossingSIVindependence;
01277     ++WeakCrossingSIVsuccesses;
01278     return true;
01279   }
01280 
01281   // We're certain that Delta > 0 and ConstCoeff > 0.
01282   // Check Delta/(2*ConstCoeff) against upper loop bound
01283   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
01284     DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
01285     const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
01286     const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
01287                                     ConstantTwo);
01288     DEBUG(dbgs() << "\t    ML = " << *ML << "\n");
01289     if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
01290       // Delta too big, no dependence
01291       ++WeakCrossingSIVindependence;
01292       ++WeakCrossingSIVsuccesses;
01293       return true;
01294     }
01295     if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
01296       // i = i' = UB
01297       Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
01298       Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
01299       ++WeakCrossingSIVsuccesses;
01300       if (!Result.DV[Level].Direction) {
01301         ++WeakCrossingSIVindependence;
01302         return true;
01303       }
01304       Result.DV[Level].Splitable = false;
01305       Result.DV[Level].Distance = SE->getConstant(Delta->getType(), 0);
01306       return false;
01307     }
01308   }
01309 
01310   // check that Coeff divides Delta
01311   APInt APDelta = ConstDelta->getValue()->getValue();
01312   APInt APCoeff = ConstCoeff->getValue()->getValue();
01313   APInt Distance = APDelta; // these need to be initialzed
01314   APInt Remainder = APDelta;
01315   APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
01316   DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
01317   if (Remainder != 0) {
01318     // Coeff doesn't divide Delta, no dependence
01319     ++WeakCrossingSIVindependence;
01320     ++WeakCrossingSIVsuccesses;
01321     return true;
01322   }
01323   DEBUG(dbgs() << "\t    Distance = " << Distance << "\n");
01324 
01325   // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
01326   APInt Two = APInt(Distance.getBitWidth(), 2, true);
01327   Remainder = Distance.srem(Two);
01328   DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
01329   if (Remainder != 0) {
01330     // Equal direction isn't possible
01331     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
01332     ++WeakCrossingSIVsuccesses;
01333   }
01334   return false;
01335 }
01336 
01337 
01338 // Kirch's algorithm, from
01339 //
01340 //        Optimizing Supercompilers for Supercomputers
01341 //        Michael Wolfe
01342 //        MIT Press, 1989
01343 //
01344 // Program 2.1, page 29.
01345 // Computes the GCD of AM and BM.
01346 // Also finds a solution to the equation ax - by = gcd(a, b).
01347 // Returns true if dependence disproved; i.e., gcd does not divide Delta.
01348 static
01349 bool findGCD(unsigned Bits, APInt AM, APInt BM, APInt Delta,
01350              APInt &G, APInt &X, APInt &Y) {
01351   APInt A0(Bits, 1, true), A1(Bits, 0, true);
01352   APInt B0(Bits, 0, true), B1(Bits, 1, true);
01353   APInt G0 = AM.abs();
01354   APInt G1 = BM.abs();
01355   APInt Q = G0; // these need to be initialized
01356   APInt R = G0;
01357   APInt::sdivrem(G0, G1, Q, R);
01358   while (R != 0) {
01359     APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
01360     APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
01361     G0 = G1; G1 = R;
01362     APInt::sdivrem(G0, G1, Q, R);
01363   }
01364   G = G1;
01365   DEBUG(dbgs() << "\t    GCD = " << G << "\n");
01366   X = AM.slt(0) ? -A1 : A1;
01367   Y = BM.slt(0) ? B1 : -B1;
01368 
01369   // make sure gcd divides Delta
01370   R = Delta.srem(G);
01371   if (R != 0)
01372     return true; // gcd doesn't divide Delta, no dependence
01373   Q = Delta.sdiv(G);
01374   X *= Q;
01375   Y *= Q;
01376   return false;
01377 }
01378 
01379 
01380 static
01381 APInt floorOfQuotient(APInt A, APInt B) {
01382   APInt Q = A; // these need to be initialized
01383   APInt R = A;
01384   APInt::sdivrem(A, B, Q, R);
01385   if (R == 0)
01386     return Q;
01387   if ((A.sgt(0) && B.sgt(0)) ||
01388       (A.slt(0) && B.slt(0)))
01389     return Q;
01390   else
01391     return Q - 1;
01392 }
01393 
01394 
01395 static
01396 APInt ceilingOfQuotient(APInt A, APInt B) {
01397   APInt Q = A; // these need to be initialized
01398   APInt R = A;
01399   APInt::sdivrem(A, B, Q, R);
01400   if (R == 0)
01401     return Q;
01402   if ((A.sgt(0) && B.sgt(0)) ||
01403       (A.slt(0) && B.slt(0)))
01404     return Q + 1;
01405   else
01406     return Q;
01407 }
01408 
01409 
01410 static
01411 APInt maxAPInt(APInt A, APInt B) {
01412   return A.sgt(B) ? A : B;
01413 }
01414 
01415 
01416 static
01417 APInt minAPInt(APInt A, APInt B) {
01418   return A.slt(B) ? A : B;
01419 }
01420 
01421 
01422 // exactSIVtest -
01423 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
01424 // where i is an induction variable, c1 and c2 are loop invariant, and a1
01425 // and a2 are constant, we can solve it exactly using an algorithm developed
01426 // by Banerjee and Wolfe. See Section 2.5.3 in
01427 //
01428 //        Optimizing Supercompilers for Supercomputers
01429 //        Michael Wolfe
01430 //        MIT Press, 1989
01431 //
01432 // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
01433 // so use them if possible. They're also a bit better with symbolics and,
01434 // in the case of the strong SIV test, can compute Distances.
01435 //
01436 // Return true if dependence disproved.
01437 bool DependenceAnalysis::exactSIVtest(const SCEV *SrcCoeff,
01438                                       const SCEV *DstCoeff,
01439                                       const SCEV *SrcConst,
01440                                       const SCEV *DstConst,
01441                                       const Loop *CurLoop,
01442                                       unsigned Level,
01443                                       FullDependence &Result,
01444                                       Constraint &NewConstraint) const {
01445   DEBUG(dbgs() << "\tExact SIV test\n");
01446   DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << " = AM\n");
01447   DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << " = BM\n");
01448   DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
01449   DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
01450   ++ExactSIVapplications;
01451   assert(0 < Level && Level <= CommonLevels && "Level out of range");
01452   Level--;
01453   Result.Consistent = false;
01454   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
01455   DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
01456   NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff),
01457                         Delta, CurLoop);
01458   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
01459   const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
01460   const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
01461   if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
01462     return false;
01463 
01464   // find gcd
01465   APInt G, X, Y;
01466   APInt AM = ConstSrcCoeff->getValue()->getValue();
01467   APInt BM = ConstDstCoeff->getValue()->getValue();
01468   unsigned Bits = AM.getBitWidth();
01469   if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) {
01470     // gcd doesn't divide Delta, no dependence
01471     ++ExactSIVindependence;
01472     ++ExactSIVsuccesses;
01473     return true;
01474   }
01475 
01476   DEBUG(dbgs() << "\t    X = " << X << ", Y = " << Y << "\n");
01477 
01478   // since SCEV construction normalizes, LM = 0
01479   APInt UM(Bits, 1, true);
01480   bool UMvalid = false;
01481   // UM is perhaps unavailable, let's check
01482   if (const SCEVConstant *CUB =
01483       collectConstantUpperBound(CurLoop, Delta->getType())) {
01484     UM = CUB->getValue()->getValue();
01485     DEBUG(dbgs() << "\t    UM = " << UM << "\n");
01486     UMvalid = true;
01487   }
01488 
01489   APInt TU(APInt::getSignedMaxValue(Bits));
01490   APInt TL(APInt::getSignedMinValue(Bits));
01491 
01492   // test(BM/G, LM-X) and test(-BM/G, X-UM)
01493   APInt TMUL = BM.sdiv(G);
01494   if (TMUL.sgt(0)) {
01495     TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
01496     DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01497     if (UMvalid) {
01498       TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL));
01499       DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01500     }
01501   }
01502   else {
01503     TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
01504     DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01505     if (UMvalid) {
01506       TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL));
01507       DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01508     }
01509   }
01510 
01511   // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
01512   TMUL = AM.sdiv(G);
01513   if (TMUL.sgt(0)) {
01514     TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
01515     DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01516     if (UMvalid) {
01517       TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL));
01518       DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01519     }
01520   }
01521   else {
01522     TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
01523     DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01524     if (UMvalid) {
01525       TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL));
01526       DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01527     }
01528   }
01529   if (TL.sgt(TU)) {
01530     ++ExactSIVindependence;
01531     ++ExactSIVsuccesses;
01532     return true;
01533   }
01534 
01535   // explore directions
01536   unsigned NewDirection = Dependence::DVEntry::NONE;
01537 
01538   // less than
01539   APInt SaveTU(TU); // save these
01540   APInt SaveTL(TL);
01541   DEBUG(dbgs() << "\t    exploring LT direction\n");
01542   TMUL = AM - BM;
01543   if (TMUL.sgt(0)) {
01544     TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL));
01545     DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
01546   }
01547   else {
01548     TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL));
01549     DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
01550   }
01551   if (TL.sle(TU)) {
01552     NewDirection |= Dependence::DVEntry::LT;
01553     ++ExactSIVsuccesses;
01554   }
01555 
01556   // equal
01557   TU = SaveTU; // restore
01558   TL = SaveTL;
01559   DEBUG(dbgs() << "\t    exploring EQ direction\n");
01560   if (TMUL.sgt(0)) {
01561     TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL));
01562     DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
01563   }
01564   else {
01565     TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL));
01566     DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
01567   }
01568   TMUL = BM - AM;
01569   if (TMUL.sgt(0)) {
01570     TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL));
01571     DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
01572   }
01573   else {
01574     TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL));
01575     DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
01576   }
01577   if (TL.sle(TU)) {
01578     NewDirection |= Dependence::DVEntry::EQ;
01579     ++ExactSIVsuccesses;
01580   }
01581 
01582   // greater than
01583   TU = SaveTU; // restore
01584   TL = SaveTL;
01585   DEBUG(dbgs() << "\t    exploring GT direction\n");
01586   if (TMUL.sgt(0)) {
01587     TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL));
01588     DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
01589   }
01590   else {
01591     TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL));
01592     DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
01593   }
01594   if (TL.sle(TU)) {
01595     NewDirection |= Dependence::DVEntry::GT;
01596     ++ExactSIVsuccesses;
01597   }
01598 
01599   // finished
01600   Result.DV[Level].Direction &= NewDirection;
01601   if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
01602     ++ExactSIVindependence;
01603   return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
01604 }
01605 
01606 
01607 
01608 // Return true if the divisor evenly divides the dividend.
01609 static
01610 bool isRemainderZero(const SCEVConstant *Dividend,
01611                      const SCEVConstant *Divisor) {
01612   APInt ConstDividend = Dividend->getValue()->getValue();
01613   APInt ConstDivisor = Divisor->getValue()->getValue();
01614   return ConstDividend.srem(ConstDivisor) == 0;
01615 }
01616 
01617 
01618 // weakZeroSrcSIVtest -
01619 // From the paper, Practical Dependence Testing, Section 4.2.2
01620 //
01621 // When we have a pair of subscripts of the form [c1] and [c2 + a*i],
01622 // where i is an induction variable, c1 and c2 are loop invariant,
01623 // and a is a constant, we can solve it exactly using the
01624 // Weak-Zero SIV test.
01625 //
01626 // Given
01627 //
01628 //    c1 = c2 + a*i
01629 //
01630 // we get
01631 //
01632 //    (c1 - c2)/a = i
01633 //
01634 // If i is not an integer, there's no dependence.
01635 // If i < 0 or > UB, there's no dependence.
01636 // If i = 0, the direction is <= and peeling the
01637 // 1st iteration will break the dependence.
01638 // If i = UB, the direction is >= and peeling the
01639 // last iteration will break the dependence.
01640 // Otherwise, the direction is *.
01641 //
01642 // Can prove independence. Failing that, we can sometimes refine
01643 // the directions. Can sometimes show that first or last
01644 // iteration carries all the dependences (so worth peeling).
01645 //
01646 // (see also weakZeroDstSIVtest)
01647 //
01648 // Return true if dependence disproved.
01649 bool DependenceAnalysis::weakZeroSrcSIVtest(const SCEV *DstCoeff,
01650                                             const SCEV *SrcConst,
01651                                             const SCEV *DstConst,
01652                                             const Loop *CurLoop,
01653                                             unsigned Level,
01654                                             FullDependence &Result,
01655                                             Constraint &NewConstraint) const {
01656   // For the WeakSIV test, it's possible the loop isn't common to
01657   // the Src and Dst loops. If it isn't, then there's no need to
01658   // record a direction.
01659   DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
01660   DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << "\n");
01661   DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
01662   DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
01663   ++WeakZeroSIVapplications;
01664   assert(0 < Level && Level <= MaxLevels && "Level out of range");
01665   Level--;
01666   Result.Consistent = false;
01667   const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
01668   NewConstraint.setLine(SE->getConstant(Delta->getType(), 0),
01669                         DstCoeff, Delta, CurLoop);
01670   DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
01671   if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
01672     if (Level < CommonLevels) {
01673       Result.DV[Level].Direction &= Dependence::DVEntry::LE;
01674       Result.DV[Level].PeelFirst = true;
01675       ++WeakZeroSIVsuccesses;
01676     }
01677     return false; // dependences caused by first iteration
01678   }
01679   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
01680   if (!ConstCoeff)
01681     return false;
01682   const SCEV *AbsCoeff =
01683     SE->isKnownNegative(ConstCoeff) ?
01684     SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
01685   const SCEV *NewDelta =
01686     SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
01687 
01688   // check that Delta/SrcCoeff < iteration count
01689   // really check NewDelta < count*AbsCoeff
01690   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
01691     DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
01692     const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
01693     if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
01694       ++WeakZeroSIVindependence;
01695       ++WeakZeroSIVsuccesses;
01696       return true;
01697     }
01698     if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
01699       // dependences caused by last iteration
01700       if (Level < CommonLevels) {
01701         Result.DV[Level].Direction &= Dependence::DVEntry::GE;
01702         Result.DV[Level].PeelLast = true;
01703         ++WeakZeroSIVsuccesses;
01704       }
01705       return false;
01706     }
01707   }
01708 
01709   // check that Delta/SrcCoeff >= 0
01710   // really check that NewDelta >= 0
01711   if (SE->isKnownNegative(NewDelta)) {
01712     // No dependence, newDelta < 0
01713     ++WeakZeroSIVindependence;
01714     ++WeakZeroSIVsuccesses;
01715     return true;
01716   }
01717 
01718   // if SrcCoeff doesn't divide Delta, then no dependence
01719   if (isa<SCEVConstant>(Delta) &&
01720       !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
01721     ++WeakZeroSIVindependence;
01722     ++WeakZeroSIVsuccesses;
01723     return true;
01724   }
01725   return false;
01726 }
01727 
01728 
01729 // weakZeroDstSIVtest -
01730 // From the paper, Practical Dependence Testing, Section 4.2.2
01731 //
01732 // When we have a pair of subscripts of the form [c1 + a*i] and [c2],
01733 // where i is an induction variable, c1 and c2 are loop invariant,
01734 // and a is a constant, we can solve it exactly using the
01735 // Weak-Zero SIV test.
01736 //
01737 // Given
01738 //
01739 //    c1 + a*i = c2
01740 //
01741 // we get
01742 //
01743 //    i = (c2 - c1)/a
01744 //
01745 // If i is not an integer, there's no dependence.
01746 // If i < 0 or > UB, there's no dependence.
01747 // If i = 0, the direction is <= and peeling the
01748 // 1st iteration will break the dependence.
01749 // If i = UB, the direction is >= and peeling the
01750 // last iteration will break the dependence.
01751 // Otherwise, the direction is *.
01752 //
01753 // Can prove independence. Failing that, we can sometimes refine
01754 // the directions. Can sometimes show that first or last
01755 // iteration carries all the dependences (so worth peeling).
01756 //
01757 // (see also weakZeroSrcSIVtest)
01758 //
01759 // Return true if dependence disproved.
01760 bool DependenceAnalysis::weakZeroDstSIVtest(const SCEV *SrcCoeff,
01761                                             const SCEV *SrcConst,
01762                                             const SCEV *DstConst,
01763                                             const Loop *CurLoop,
01764                                             unsigned Level,
01765                                             FullDependence &Result,
01766                                             Constraint &NewConstraint) const {
01767   // For the WeakSIV test, it's possible the loop isn't common to the
01768   // Src and Dst loops. If it isn't, then there's no need to record a direction.
01769   DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
01770   DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << "\n");
01771   DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
01772   DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
01773   ++WeakZeroSIVapplications;
01774   assert(0 < Level && Level <= SrcLevels && "Level out of range");
01775   Level--;
01776   Result.Consistent = false;
01777   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
01778   NewConstraint.setLine(SrcCoeff, SE->getConstant(Delta->getType(), 0),
01779                         Delta, CurLoop);
01780   DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
01781   if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
01782     if (Level < CommonLevels) {
01783       Result.DV[Level].Direction &= Dependence::DVEntry::LE;
01784       Result.DV[Level].PeelFirst = true;
01785       ++WeakZeroSIVsuccesses;
01786     }
01787     return false; // dependences caused by first iteration
01788   }
01789   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
01790   if (!ConstCoeff)
01791     return false;
01792   const SCEV *AbsCoeff =
01793     SE->isKnownNegative(ConstCoeff) ?
01794     SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
01795   const SCEV *NewDelta =
01796     SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
01797 
01798   // check that Delta/SrcCoeff < iteration count
01799   // really check NewDelta < count*AbsCoeff
01800   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
01801     DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
01802     const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
01803     if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
01804       ++WeakZeroSIVindependence;
01805       ++WeakZeroSIVsuccesses;
01806       return true;
01807     }
01808     if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
01809       // dependences caused by last iteration
01810       if (Level < CommonLevels) {
01811         Result.DV[Level].Direction &= Dependence::DVEntry::GE;
01812         Result.DV[Level].PeelLast = true;
01813         ++WeakZeroSIVsuccesses;
01814       }
01815       return false;
01816     }
01817   }
01818 
01819   // check that Delta/SrcCoeff >= 0
01820   // really check that NewDelta >= 0
01821   if (SE->isKnownNegative(NewDelta)) {
01822     // No dependence, newDelta < 0
01823     ++WeakZeroSIVindependence;
01824     ++WeakZeroSIVsuccesses;
01825     return true;
01826   }
01827 
01828   // if SrcCoeff doesn't divide Delta, then no dependence
01829   if (isa<SCEVConstant>(Delta) &&
01830       !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
01831     ++WeakZeroSIVindependence;
01832     ++WeakZeroSIVsuccesses;
01833     return true;
01834   }
01835   return false;
01836 }
01837 
01838 
01839 // exactRDIVtest - Tests the RDIV subscript pair for dependence.
01840 // Things of the form [c1 + a*i] and [c2 + b*j],
01841 // where i and j are induction variable, c1 and c2 are loop invariant,
01842 // and a and b are constants.
01843 // Returns true if any possible dependence is disproved.
01844 // Marks the result as inconsistent.
01845 // Works in some cases that symbolicRDIVtest doesn't, and vice versa.
01846 bool DependenceAnalysis::exactRDIVtest(const SCEV *SrcCoeff,
01847                                        const SCEV *DstCoeff,
01848                                        const SCEV *SrcConst,
01849                                        const SCEV *DstConst,
01850                                        const Loop *SrcLoop,
01851                                        const Loop *DstLoop,
01852                                        FullDependence &Result) const {
01853   DEBUG(dbgs() << "\tExact RDIV test\n");
01854   DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << " = AM\n");
01855   DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << " = BM\n");
01856   DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
01857   DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
01858   ++ExactRDIVapplications;
01859   Result.Consistent = false;
01860   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
01861   DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
01862   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
01863   const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
01864   const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
01865   if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
01866     return false;
01867 
01868   // find gcd
01869   APInt G, X, Y;
01870   APInt AM = ConstSrcCoeff->getValue()->getValue();
01871   APInt BM = ConstDstCoeff->getValue()->getValue();
01872   unsigned Bits = AM.getBitWidth();
01873   if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) {
01874     // gcd doesn't divide Delta, no dependence
01875     ++ExactRDIVindependence;
01876     return true;
01877   }
01878 
01879   DEBUG(dbgs() << "\t    X = " << X << ", Y = " << Y << "\n");
01880 
01881   // since SCEV construction seems to normalize, LM = 0
01882   APInt SrcUM(Bits, 1, true);
01883   bool SrcUMvalid = false;
01884   // SrcUM is perhaps unavailable, let's check
01885   if (const SCEVConstant *UpperBound =
01886       collectConstantUpperBound(SrcLoop, Delta->getType())) {
01887     SrcUM = UpperBound->getValue()->getValue();
01888     DEBUG(dbgs() << "\t    SrcUM = " << SrcUM << "\n");
01889     SrcUMvalid = true;
01890   }
01891 
01892   APInt DstUM(Bits, 1, true);
01893   bool DstUMvalid = false;
01894   // UM is perhaps unavailable, let's check
01895   if (const SCEVConstant *UpperBound =
01896       collectConstantUpperBound(DstLoop, Delta->getType())) {
01897     DstUM = UpperBound->getValue()->getValue();
01898     DEBUG(dbgs() << "\t    DstUM = " << DstUM << "\n");
01899     DstUMvalid = true;
01900   }
01901 
01902   APInt TU(APInt::getSignedMaxValue(Bits));
01903   APInt TL(APInt::getSignedMinValue(Bits));
01904 
01905   // test(BM/G, LM-X) and test(-BM/G, X-UM)
01906   APInt TMUL = BM.sdiv(G);
01907   if (TMUL.sgt(0)) {
01908     TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
01909     DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01910     if (SrcUMvalid) {
01911       TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL));
01912       DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01913     }
01914   }
01915   else {
01916     TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
01917     DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01918     if (SrcUMvalid) {
01919       TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL));
01920       DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01921     }
01922   }
01923 
01924   // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
01925   TMUL = AM.sdiv(G);
01926   if (TMUL.sgt(0)) {
01927     TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
01928     DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01929     if (DstUMvalid) {
01930       TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL));
01931       DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01932     }
01933   }
01934   else {
01935     TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
01936     DEBUG(dbgs() << "\t    TU = " << TU << "\n");
01937     if (DstUMvalid) {
01938       TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL));
01939       DEBUG(dbgs() << "\t    TL = " << TL << "\n");
01940     }
01941   }
01942   if (TL.sgt(TU))
01943     ++ExactRDIVindependence;
01944   return TL.sgt(TU);
01945 }
01946 
01947 
01948 // symbolicRDIVtest -
01949 // In Section 4.5 of the Practical Dependence Testing paper,the authors
01950 // introduce a special case of Banerjee's Inequalities (also called the
01951 // Extreme-Value Test) that can handle some of the SIV and RDIV cases,
01952 // particularly cases with symbolics. Since it's only able to disprove
01953 // dependence (not compute distances or directions), we'll use it as a
01954 // fall back for the other tests.
01955 //
01956 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
01957 // where i and j are induction variables and c1 and c2 are loop invariants,
01958 // we can use the symbolic tests to disprove some dependences, serving as a
01959 // backup for the RDIV test. Note that i and j can be the same variable,
01960 // letting this test serve as a backup for the various SIV tests.
01961 //
01962 // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
01963 //  0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
01964 // loop bounds for the i and j loops, respectively. So, ...
01965 //
01966 // c1 + a1*i = c2 + a2*j
01967 // a1*i - a2*j = c2 - c1
01968 //
01969 // To test for a dependence, we compute c2 - c1 and make sure it's in the
01970 // range of the maximum and minimum possible values of a1*i - a2*j.
01971 // Considering the signs of a1 and a2, we have 4 possible cases:
01972 //
01973 // 1) If a1 >= 0 and a2 >= 0, then
01974 //        a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
01975 //              -a2*N2 <= c2 - c1 <= a1*N1
01976 //
01977 // 2) If a1 >= 0 and a2 <= 0, then
01978 //        a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
01979 //                  0 <= c2 - c1 <= a1*N1 - a2*N2
01980 //
01981 // 3) If a1 <= 0 and a2 >= 0, then
01982 //        a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
01983 //        a1*N1 - a2*N2 <= c2 - c1 <= 0
01984 //
01985 // 4) If a1 <= 0 and a2 <= 0, then
01986 //        a1*N1 - a2*0  <= c2 - c1 <= a1*0 - a2*N2
01987 //        a1*N1         <= c2 - c1 <=       -a2*N2
01988 //
01989 // return true if dependence disproved
01990 bool DependenceAnalysis::symbolicRDIVtest(const SCEV *A1,
01991                                           const SCEV *A2,
01992                                           const SCEV *C1,
01993                                           const SCEV *C2,
01994                                           const Loop *Loop1,
01995                                           const Loop *Loop2) const {
01996   ++SymbolicRDIVapplications;
01997   DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
01998   DEBUG(dbgs() << "\t    A1 = " << *A1);
01999   DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
02000   DEBUG(dbgs() << "\t    A2 = " << *A2 << "\n");
02001   DEBUG(dbgs() << "\t    C1 = " << *C1 << "\n");
02002   DEBUG(dbgs() << "\t    C2 = " << *C2 << "\n");
02003   const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
02004   const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
02005   DEBUG(if (N1) dbgs() << "\t    N1 = " << *N1 << "\n");
02006   DEBUG(if (N2) dbgs() << "\t    N2 = " << *N2 << "\n");
02007   const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
02008   const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
02009   DEBUG(dbgs() << "\t    C2 - C1 = " << *C2_C1 << "\n");
02010   DEBUG(dbgs() << "\t    C1 - C2 = " << *C1_C2 << "\n");
02011   if (SE->isKnownNonNegative(A1)) {
02012     if (SE->isKnownNonNegative(A2)) {
02013       // A1 >= 0 && A2 >= 0
02014       if (N1) {
02015         // make sure that c2 - c1 <= a1*N1
02016         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
02017         DEBUG(dbgs() << "\t    A1*N1 = " << *A1N1 << "\n");
02018         if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
02019           ++SymbolicRDIVindependence;
02020           return true;
02021         }
02022       }
02023       if (N2) {
02024         // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
02025         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
02026         DEBUG(dbgs() << "\t    A2*N2 = " << *A2N2 << "\n");
02027         if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
02028           ++SymbolicRDIVindependence;
02029           return true;
02030         }
02031       }
02032     }
02033     else if (SE->isKnownNonPositive(A2)) {
02034       // a1 >= 0 && a2 <= 0
02035       if (N1 && N2) {
02036         // make sure that c2 - c1 <= a1*N1 - a2*N2
02037         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
02038         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
02039         const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
02040         DEBUG(dbgs() << "\t    A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
02041         if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
02042           ++SymbolicRDIVindependence;
02043           return true;
02044         }
02045       }
02046       // make sure that 0 <= c2 - c1
02047       if (SE->isKnownNegative(C2_C1)) {
02048         ++SymbolicRDIVindependence;
02049         return true;
02050       }
02051     }
02052   }
02053   else if (SE->isKnownNonPositive(A1)) {
02054     if (SE->isKnownNonNegative(A2)) {
02055       // a1 <= 0 && a2 >= 0
02056       if (N1 && N2) {
02057         // make sure that a1*N1 - a2*N2 <= c2 - c1
02058         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
02059         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
02060         const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
02061         DEBUG(dbgs() << "\t    A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
02062         if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
02063           ++SymbolicRDIVindependence;
02064           return true;
02065         }
02066       }
02067       // make sure that c2 - c1 <= 0
02068       if (SE->isKnownPositive(C2_C1)) {
02069         ++SymbolicRDIVindependence;
02070         return true;
02071       }
02072     }
02073     else if (SE->isKnownNonPositive(A2)) {
02074       // a1 <= 0 && a2 <= 0
02075       if (N1) {
02076         // make sure that a1*N1 <= c2 - c1
02077         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
02078         DEBUG(dbgs() << "\t    A1*N1 = " << *A1N1 << "\n");
02079         if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
02080           ++SymbolicRDIVindependence;
02081           return true;
02082         }
02083       }
02084       if (N2) {
02085         // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
02086         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
02087         DEBUG(dbgs() << "\t    A2*N2 = " << *A2N2 << "\n");
02088         if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
02089           ++SymbolicRDIVindependence;
02090           return true;
02091         }
02092       }
02093     }
02094   }
02095   return false;
02096 }
02097 
02098 
02099 // testSIV -
02100 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
02101 // where i is an induction variable, c1 and c2 are loop invariant, and a1 and
02102 // a2 are constant, we attack it with an SIV test. While they can all be
02103 // solved with the Exact SIV test, it's worthwhile to use simpler tests when
02104 // they apply; they're cheaper and sometimes more precise.
02105 //
02106 // Return true if dependence disproved.
02107 bool DependenceAnalysis::testSIV(const SCEV *Src,
02108                                  const SCEV *Dst,
02109                                  unsigned &Level,
02110                                  FullDependence &Result,
02111                                  Constraint &NewConstraint,
02112                                  const SCEV *&SplitIter) const {
02113   DEBUG(dbgs() << "    src = " << *Src << "\n");
02114   DEBUG(dbgs() << "    dst = " << *Dst << "\n");
02115   const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
02116   const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
02117   if (SrcAddRec && DstAddRec) {
02118     const SCEV *SrcConst = SrcAddRec->getStart();
02119     const SCEV *DstConst = DstAddRec->getStart();
02120     const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
02121     const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
02122     const Loop *CurLoop = SrcAddRec->getLoop();
02123     assert(CurLoop == DstAddRec->getLoop() &&
02124            "both loops in SIV should be same");
02125     Level = mapSrcLoop(CurLoop);
02126     bool disproven;
02127     if (SrcCoeff == DstCoeff)
02128       disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
02129                                 Level, Result, NewConstraint);
02130     else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
02131       disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
02132                                       Level, Result, NewConstraint, SplitIter);
02133     else
02134       disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
02135                                Level, Result, NewConstraint);
02136     return disproven ||
02137       gcdMIVtest(Src, Dst, Result) ||
02138       symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
02139   }
02140   if (SrcAddRec) {
02141     const SCEV *SrcConst = SrcAddRec->getStart();
02142     const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
02143     const SCEV *DstConst = Dst;
02144     const Loop *CurLoop = SrcAddRec->getLoop();
02145     Level = mapSrcLoop(CurLoop);
02146     return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
02147                               Level, Result, NewConstraint) ||
02148       gcdMIVtest(Src, Dst, Result);
02149   }
02150   if (DstAddRec) {
02151     const SCEV *DstConst = DstAddRec->getStart();
02152     const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
02153     const SCEV *SrcConst = Src;
02154     const Loop *CurLoop = DstAddRec->getLoop();
02155     Level = mapDstLoop(CurLoop);
02156     return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
02157                               CurLoop, Level, Result, NewConstraint) ||
02158       gcdMIVtest(Src, Dst, Result);
02159   }
02160   llvm_unreachable("SIV test expected at least one AddRec");
02161   return false;
02162 }
02163 
02164 
02165 // testRDIV -
02166 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
02167 // where i and j are induction variables, c1 and c2 are loop invariant,
02168 // and a1 and a2 are constant, we can solve it exactly with an easy adaptation
02169 // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
02170 // It doesn't make sense to talk about distance or direction in this case,
02171 // so there's no point in making special versions of the Strong SIV test or
02172 // the Weak-crossing SIV test.
02173 //
02174 // With minor algebra, this test can also be used for things like
02175 // [c1 + a1*i + a2*j][c2].
02176 //
02177 // Return true if dependence disproved.
02178 bool DependenceAnalysis::testRDIV(const SCEV *Src,
02179                                   const SCEV *Dst,
02180                                   FullDependence &Result) const {
02181   // we have 3 possible situations here:
02182   //   1) [a*i + b] and [c*j + d]
02183   //   2) [a*i + c*j + b] and [d]
02184   //   3) [b] and [a*i + c*j + d]
02185   // We need to find what we've got and get organized
02186 
02187   const SCEV *SrcConst, *DstConst;
02188   const SCEV *SrcCoeff, *DstCoeff;
02189   const Loop *SrcLoop, *DstLoop;
02190 
02191   DEBUG(dbgs() << "    src = " << *Src << "\n");
02192   DEBUG(dbgs() << "    dst = " << *Dst << "\n");
02193   const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
02194   const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
02195   if (SrcAddRec && DstAddRec) {
02196     SrcConst = SrcAddRec->getStart();
02197     SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
02198     SrcLoop = SrcAddRec->getLoop();
02199     DstConst = DstAddRec->getStart();
02200     DstCoeff = DstAddRec->getStepRecurrence(*SE);
02201     DstLoop = DstAddRec->getLoop();
02202   }
02203   else if (SrcAddRec) {
02204     if (const SCEVAddRecExpr *tmpAddRec =
02205         dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
02206       SrcConst = tmpAddRec->getStart();
02207       SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
02208       SrcLoop = tmpAddRec->getLoop();
02209       DstConst = Dst;
02210       DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
02211       DstLoop = SrcAddRec->getLoop();
02212     }
02213     else
02214       llvm_unreachable("RDIV reached by surprising SCEVs");
02215   }
02216   else if (DstAddRec) {
02217     if (const SCEVAddRecExpr *tmpAddRec =
02218         dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
02219       DstConst = tmpAddRec->getStart();
02220       DstCoeff = tmpAddRec->getStepRecurrence(*SE);
02221       DstLoop = tmpAddRec->getLoop();
02222       SrcConst = Src;
02223       SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
02224       SrcLoop = DstAddRec->getLoop();
02225     }
02226     else
02227       llvm_unreachable("RDIV reached by surprising SCEVs");
02228   }
02229   else
02230     llvm_unreachable("RDIV expected at least one AddRec");
02231   return exactRDIVtest(SrcCoeff, DstCoeff,
02232                        SrcConst, DstConst,
02233                        SrcLoop, DstLoop,
02234                        Result) ||
02235     gcdMIVtest(Src, Dst, Result) ||
02236     symbolicRDIVtest(SrcCoeff, DstCoeff,
02237                      SrcConst, DstConst,
02238                      SrcLoop, DstLoop);
02239 }
02240 
02241 
02242 // Tests the single-subscript MIV pair (Src and Dst) for dependence.
02243 // Return true if dependence disproved.
02244 // Can sometimes refine direction vectors.
02245 bool DependenceAnalysis::testMIV(const SCEV *Src,
02246                                  const SCEV *Dst,
02247                                  const SmallBitVector &Loops,
02248                                  FullDependence &Result) const {
02249   DEBUG(dbgs() << "    src = " << *Src << "\n");
02250   DEBUG(dbgs() << "    dst = " << *Dst << "\n");
02251   Result.Consistent = false;
02252   return gcdMIVtest(Src, Dst, Result) ||
02253     banerjeeMIVtest(Src, Dst, Loops, Result);
02254 }
02255 
02256 
02257 // Given a product, e.g., 10*X*Y, returns the first constant operand,
02258 // in this case 10. If there is no constant part, returns NULL.
02259 static
02260 const SCEVConstant *getConstantPart(const SCEVMulExpr *Product) {
02261   for (unsigned Op = 0, Ops = Product->getNumOperands(); Op < Ops; Op++) {
02262     if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Product->getOperand(Op)))
02263       return Constant;
02264   }
02265   return nullptr;
02266 }
02267 
02268 
02269 //===----------------------------------------------------------------------===//
02270 // gcdMIVtest -
02271 // Tests an MIV subscript pair for dependence.
02272 // Returns true if any possible dependence is disproved.
02273 // Marks the result as inconsistent.
02274 // Can sometimes disprove the equal direction for 1 or more loops,
02275 // as discussed in Michael Wolfe's book,
02276 // High Performance Compilers for Parallel Computing, page 235.
02277 //
02278 // We spend some effort (code!) to handle cases like
02279 // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
02280 // but M and N are just loop-invariant variables.
02281 // This should help us handle linearized subscripts;
02282 // also makes this test a useful backup to the various SIV tests.
02283 //
02284 // It occurs to me that the presence of loop-invariant variables
02285 // changes the nature of the test from "greatest common divisor"
02286 // to "a common divisor".
02287 bool DependenceAnalysis::gcdMIVtest(const SCEV *Src,
02288                                     const SCEV *Dst,
02289                                     FullDependence &Result) const {
02290   DEBUG(dbgs() << "starting gcd\n");
02291   ++GCDapplications;
02292   unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
02293   APInt RunningGCD = APInt::getNullValue(BitWidth);
02294 
02295   // Examine Src coefficients.
02296   // Compute running GCD and record source constant.
02297   // Because we're looking for the constant at the end of the chain,
02298   // we can't quit the loop just because the GCD == 1.
02299   const SCEV *Coefficients = Src;
02300   while (const SCEVAddRecExpr *AddRec =
02301          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
02302     const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
02303     const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
02304     if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
02305       // If the coefficient is the product of a constant and other stuff,
02306       // we can use the constant in the GCD computation.
02307       Constant = getConstantPart(Product);
02308     if (!Constant)
02309       return false;
02310     APInt ConstCoeff = Constant->getValue()->getValue();
02311     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
02312     Coefficients = AddRec->getStart();
02313   }
02314   const SCEV *SrcConst = Coefficients;
02315 
02316   // Examine Dst coefficients.
02317   // Compute running GCD and record destination constant.
02318   // Because we're looking for the constant at the end of the chain,
02319   // we can't quit the loop just because the GCD == 1.
02320   Coefficients = Dst;
02321   while (const SCEVAddRecExpr *AddRec =
02322          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
02323     const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
02324     const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff);
02325     if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
02326       // If the coefficient is the product of a constant and other stuff,
02327       // we can use the constant in the GCD computation.
02328       Constant = getConstantPart(Product);
02329     if (!Constant)
02330       return false;
02331     APInt ConstCoeff = Constant->getValue()->getValue();
02332     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
02333     Coefficients = AddRec->getStart();
02334   }
02335   const SCEV *DstConst = Coefficients;
02336 
02337   APInt ExtraGCD = APInt::getNullValue(BitWidth);
02338   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
02339   DEBUG(dbgs() << "    Delta = " << *Delta << "\n");
02340   const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
02341   if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
02342     // If Delta is a sum of products, we may be able to make further progress.
02343     for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
02344       const SCEV *Operand = Sum->getOperand(Op);
02345       if (isa<SCEVConstant>(Operand)) {
02346         assert(!Constant && "Surprised to find multiple constants");
02347         Constant = cast<SCEVConstant>(Operand);
02348       }
02349       else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
02350         // Search for constant operand to participate in GCD;
02351         // If none found; return false.
02352         const SCEVConstant *ConstOp = getConstantPart(Product);
02353         if (!ConstOp)
02354           return false;
02355         APInt ConstOpValue = ConstOp->getValue()->getValue();
02356         ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
02357                                                    ConstOpValue.abs());
02358       }
02359       else
02360         return false;
02361     }
02362   }
02363   if (!Constant)
02364     return false;
02365   APInt ConstDelta = cast<SCEVConstant>(Constant)->getValue()->getValue();
02366   DEBUG(dbgs() << "    ConstDelta = " << ConstDelta << "\n");
02367   if (ConstDelta == 0)
02368     return false;
02369   RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
02370   DEBUG(dbgs() << "    RunningGCD = " << RunningGCD << "\n");
02371   APInt Remainder = ConstDelta.srem(RunningGCD);
02372   if (Remainder != 0) {
02373     ++GCDindependence;
02374     return true;
02375   }
02376 
02377   // Try to disprove equal directions.
02378   // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
02379   // the code above can't disprove the dependence because the GCD = 1.
02380   // So we consider what happen if i = i' and what happens if j = j'.
02381   // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
02382   // which is infeasible, so we can disallow the = direction for the i level.
02383   // Setting j = j' doesn't help matters, so we end up with a direction vector
02384   // of [<>, *]
02385   //
02386   // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
02387   // we need to remember that the constant part is 5 and the RunningGCD should
02388   // be initialized to ExtraGCD = 30.
02389   DEBUG(dbgs() << "    ExtraGCD = " << ExtraGCD << '\n');
02390 
02391   bool Improved = false;
02392   Coefficients = Src;
02393   while (const SCEVAddRecExpr *AddRec =
02394          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
02395     Coefficients = AddRec->getStart();
02396     const Loop *CurLoop = AddRec->getLoop();
02397     RunningGCD = ExtraGCD;
02398     const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
02399     const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
02400     const SCEV *Inner = Src;
02401     while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
02402       AddRec = cast<SCEVAddRecExpr>(Inner);
02403       const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
02404       if (CurLoop == AddRec->getLoop())
02405         ; // SrcCoeff == Coeff
02406       else {
02407         if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
02408           // If the coefficient is the product of a constant and other stuff,
02409           // we can use the constant in the GCD computation.
02410           Constant = getConstantPart(Product);
02411         else
02412           Constant = cast<SCEVConstant>(Coeff);
02413         APInt ConstCoeff = Constant->getValue()->getValue();
02414         RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
02415       }
02416       Inner = AddRec->getStart();
02417     }
02418     Inner = Dst;
02419     while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
02420       AddRec = cast<SCEVAddRecExpr>(Inner);
02421       const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
02422       if (CurLoop == AddRec->getLoop())
02423         DstCoeff = Coeff;
02424       else {
02425         if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff))
02426           // If the coefficient is the product of a constant and other stuff,
02427           // we can use the constant in the GCD computation.
02428           Constant = getConstantPart(Product);
02429         else
02430           Constant = cast<SCEVConstant>(Coeff);
02431         APInt ConstCoeff = Constant->getValue()->getValue();
02432         RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
02433       }
02434       Inner = AddRec->getStart();
02435     }
02436     Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
02437     if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Delta))
02438       // If the coefficient is the product of a constant and other stuff,
02439       // we can use the constant in the GCD computation.
02440       Constant = getConstantPart(Product);
02441     else if (isa<SCEVConstant>(Delta))
02442       Constant = cast<SCEVConstant>(Delta);
02443     else {
02444       // The difference of the two coefficients might not be a product
02445       // or constant, in which case we give up on this direction.
02446       continue;
02447     }
02448     APInt ConstCoeff = Constant->getValue()->getValue();
02449     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
02450     DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
02451     if (RunningGCD != 0) {
02452       Remainder = ConstDelta.srem(RunningGCD);
02453       DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
02454       if (Remainder != 0) {
02455         unsigned Level = mapSrcLoop(CurLoop);
02456         Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
02457         Improved = true;
02458       }
02459     }
02460   }
02461   if (Improved)
02462     ++GCDsuccesses;
02463   DEBUG(dbgs() << "all done\n");
02464   return false;
02465 }
02466 
02467 
02468 //===----------------------------------------------------------------------===//
02469 // banerjeeMIVtest -
02470 // Use Banerjee's Inequalities to test an MIV subscript pair.
02471 // (Wolfe, in the race-car book, calls this the Extreme Value Test.)
02472 // Generally follows the discussion in Section 2.5.2 of
02473 //
02474 //    Optimizing Supercompilers for Supercomputers
02475 //    Michael Wolfe
02476 //
02477 // The inequalities given on page 25 are simplified in that loops are
02478 // normalized so that the lower bound is always 0 and the stride is always 1.
02479 // For example, Wolfe gives
02480 //
02481 //     LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
02482 //
02483 // where A_k is the coefficient of the kth index in the source subscript,
02484 // B_k is the coefficient of the kth index in the destination subscript,
02485 // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
02486 // index, and N_k is the stride of the kth index. Since all loops are normalized
02487 // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
02488 // equation to
02489 //
02490 //     LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
02491 //            = (A^-_k - B_k)^- (U_k - 1)  - B_k
02492 //
02493 // Similar simplifications are possible for the other equations.
02494 //
02495 // When we can't determine the number of iterations for a loop,
02496 // we use NULL as an indicator for the worst case, infinity.
02497 // When computing the upper bound, NULL denotes +inf;
02498 // for the lower bound, NULL denotes -inf.
02499 //
02500 // Return true if dependence disproved.
02501 bool DependenceAnalysis::banerjeeMIVtest(const SCEV *Src,
02502                                          const SCEV *Dst,
02503                                          const SmallBitVector &Loops,
02504                                          FullDependence &Result) const {
02505   DEBUG(dbgs() << "starting Banerjee\n");
02506   ++BanerjeeApplications;
02507   DEBUG(dbgs() << "    Src = " << *Src << '\n');
02508   const SCEV *A0;
02509   CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
02510   DEBUG(dbgs() << "    Dst = " << *Dst << '\n');
02511   const SCEV *B0;
02512   CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
02513   BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
02514   const SCEV *Delta = SE->getMinusSCEV(B0, A0);
02515   DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
02516 
02517   // Compute bounds for all the * directions.
02518   DEBUG(dbgs() << "\tBounds[*]\n");
02519   for (unsigned K = 1; K <= MaxLevels; ++K) {
02520     Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
02521     Bound[K].Direction = Dependence::DVEntry::ALL;
02522     Bound[K].DirSet = Dependence::DVEntry::NONE;
02523     findBoundsALL(A, B, Bound, K);
02524 #ifndef NDEBUG
02525     DEBUG(dbgs() << "\t    " << K << '\t');
02526     if (Bound[K].Lower[Dependence::DVEntry::ALL])
02527       DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
02528     else
02529       DEBUG(dbgs() << "-inf\t");
02530     if (Bound[K].Upper[Dependence::DVEntry::ALL])
02531       DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
02532     else
02533       DEBUG(dbgs() << "+inf\n");
02534 #endif
02535   }
02536 
02537   // Test the *, *, *, ... case.
02538   bool Disproved = false;
02539   if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
02540     // Explore the direction vector hierarchy.
02541     unsigned DepthExpanded = 0;
02542     unsigned NewDeps = exploreDirections(1, A, B, Bound,
02543                                          Loops, DepthExpanded, Delta);
02544     if (NewDeps > 0) {
02545       bool Improved = false;
02546       for (unsigned K = 1; K <= CommonLevels; ++K) {
02547         if (Loops[K]) {
02548           unsigned Old = Result.DV[K - 1].Direction;
02549           Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
02550           Improved |= Old != Result.DV[K - 1].Direction;
02551           if (!Result.DV[K - 1].Direction) {
02552             Improved = false;
02553             Disproved = true;
02554             break;
02555           }
02556         }
02557       }
02558       if (Improved)
02559         ++BanerjeeSuccesses;
02560     }
02561     else {
02562       ++BanerjeeIndependence;
02563       Disproved = true;
02564     }
02565   }
02566   else {
02567     ++BanerjeeIndependence;
02568     Disproved = true;
02569   }
02570   delete [] Bound;
02571   delete [] A;
02572   delete [] B;
02573   return Disproved;
02574 }
02575 
02576 
02577 // Hierarchically expands the direction vector
02578 // search space, combining the directions of discovered dependences
02579 // in the DirSet field of Bound. Returns the number of distinct
02580 // dependences discovered. If the dependence is disproved,
02581 // it will return 0.
02582 unsigned DependenceAnalysis::exploreDirections(unsigned Level,
02583                                                CoefficientInfo *A,
02584                                                CoefficientInfo *B,
02585                                                BoundInfo *Bound,
02586                                                const SmallBitVector &Loops,
02587                                                unsigned &DepthExpanded,
02588                                                const SCEV *Delta) const {
02589   if (Level > CommonLevels) {
02590     // record result
02591     DEBUG(dbgs() << "\t[");
02592     for (unsigned K = 1; K <= CommonLevels; ++K) {
02593       if (Loops[K]) {
02594         Bound[K].DirSet |= Bound[K].Direction;
02595 #ifndef NDEBUG
02596         switch (Bound[K].Direction) {
02597         case Dependence::DVEntry::LT:
02598           DEBUG(dbgs() << " <");
02599           break;
02600         case Dependence::DVEntry::EQ:
02601           DEBUG(dbgs() << " =");
02602           break;
02603         case Dependence::DVEntry::GT:
02604           DEBUG(dbgs() << " >");
02605           break;
02606         case Dependence::DVEntry::ALL:
02607           DEBUG(dbgs() << " *");
02608           break;
02609         default:
02610           llvm_unreachable("unexpected Bound[K].Direction");
02611         }
02612 #endif
02613       }
02614     }
02615     DEBUG(dbgs() << " ]\n");
02616     return 1;
02617   }
02618   if (Loops[Level]) {
02619     if (Level > DepthExpanded) {
02620       DepthExpanded = Level;
02621       // compute bounds for <, =, > at current level
02622       findBoundsLT(A, B, Bound, Level);
02623       findBoundsGT(A, B, Bound, Level);
02624       findBoundsEQ(A, B, Bound, Level);
02625 #ifndef NDEBUG
02626       DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
02627       DEBUG(dbgs() << "\t    <\t");
02628       if (Bound[Level].Lower[Dependence::DVEntry::LT])
02629         DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT] << '\t');
02630       else
02631         DEBUG(dbgs() << "-inf\t");
02632       if (Bound[Level].Upper[Dependence::DVEntry::LT])
02633         DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT] << '\n');
02634       else
02635         DEBUG(dbgs() << "+inf\n");
02636       DEBUG(dbgs() << "\t    =\t");
02637       if (Bound[Level].Lower[Dependence::DVEntry::EQ])
02638         DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ] << '\t');
02639       else
02640         DEBUG(dbgs() << "-inf\t");
02641       if (Bound[Level].Upper[Dependence::DVEntry::EQ])
02642         DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ] << '\n');
02643       else
02644         DEBUG(dbgs() << "+inf\n");
02645       DEBUG(dbgs() << "\t    >\t");
02646       if (Bound[Level].Lower[Dependence::DVEntry::GT])
02647         DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT] << '\t');
02648       else
02649         DEBUG(dbgs() << "-inf\t");
02650       if (Bound[Level].Upper[Dependence::DVEntry::GT])
02651         DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT] << '\n');
02652       else
02653         DEBUG(dbgs() << "+inf\n");
02654 #endif
02655     }
02656 
02657     unsigned NewDeps = 0;
02658 
02659     // test bounds for <, *, *, ...
02660     if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
02661       NewDeps += exploreDirections(Level + 1, A, B, Bound,
02662                                    Loops, DepthExpanded, Delta);
02663 
02664     // Test bounds for =, *, *, ...
02665     if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
02666       NewDeps += exploreDirections(Level + 1, A, B, Bound,
02667                                    Loops, DepthExpanded, Delta);
02668 
02669     // test bounds for >, *, *, ...
02670     if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
02671       NewDeps += exploreDirections(Level + 1, A, B, Bound,
02672                                    Loops, DepthExpanded, Delta);
02673 
02674     Bound[Level].Direction = Dependence::DVEntry::ALL;
02675     return NewDeps;
02676   }
02677   else
02678     return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
02679 }
02680 
02681 
02682 // Returns true iff the current bounds are plausible.
02683 bool DependenceAnalysis::testBounds(unsigned char DirKind,
02684                                     unsigned Level,
02685                                     BoundInfo *Bound,
02686                                     const SCEV *Delta) const {
02687   Bound[Level].Direction = DirKind;
02688   if (const SCEV *LowerBound = getLowerBound(Bound))
02689     if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
02690       return false;
02691   if (const SCEV *UpperBound = getUpperBound(Bound))
02692     if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
02693       return false;
02694   return true;
02695 }
02696 
02697 
02698 // Computes the upper and lower bounds for level K
02699 // using the * direction. Records them in Bound.
02700 // Wolfe gives the equations
02701 //
02702 //    LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
02703 //    UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
02704 //
02705 // Since we normalize loops, we can simplify these equations to
02706 //
02707 //    LB^*_k = (A^-_k - B^+_k)U_k
02708 //    UB^*_k = (A^+_k - B^-_k)U_k
02709 //
02710 // We must be careful to handle the case where the upper bound is unknown.
02711 // Note that the lower bound is always <= 0
02712 // and the upper bound is always >= 0.
02713 void DependenceAnalysis::findBoundsALL(CoefficientInfo *A,
02714                                        CoefficientInfo *B,
02715                                        BoundInfo *Bound,
02716                                        unsigned K) const {
02717   Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
02718   Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
02719   if (Bound[K].Iterations) {
02720     Bound[K].Lower[Dependence::DVEntry::ALL] =
02721       SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
02722                      Bound[K].Iterations);
02723     Bound[K].Upper[Dependence::DVEntry::ALL] =
02724       SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
02725                      Bound[K].Iterations);
02726   }
02727   else {
02728     // If the difference is 0, we won't need to know the number of iterations.
02729     if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
02730       Bound[K].Lower[Dependence::DVEntry::ALL] =
02731         SE->getConstant(A[K].Coeff->getType(), 0);
02732     if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
02733       Bound[K].Upper[Dependence::DVEntry::ALL] =
02734         SE->getConstant(A[K].Coeff->getType(), 0);
02735   }
02736 }
02737 
02738 
02739 // Computes the upper and lower bounds for level K
02740 // using the = direction. Records them in Bound.
02741 // Wolfe gives the equations
02742 //
02743 //    LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
02744 //    UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
02745 //
02746 // Since we normalize loops, we can simplify these equations to
02747 //
02748 //    LB^=_k = (A_k - B_k)^- U_k
02749 //    UB^=_k = (A_k - B_k)^+ U_k
02750 //
02751 // We must be careful to handle the case where the upper bound is unknown.
02752 // Note that the lower bound is always <= 0
02753 // and the upper bound is always >= 0.
02754 void DependenceAnalysis::findBoundsEQ(CoefficientInfo *A,
02755                                       CoefficientInfo *B,
02756                                       BoundInfo *Bound,
02757                                       unsigned K) const {
02758   Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
02759   Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
02760   if (Bound[K].Iterations) {
02761     const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
02762     const SCEV *NegativePart = getNegativePart(Delta);
02763     Bound[K].Lower[Dependence::DVEntry::EQ] =
02764       SE->getMulExpr(NegativePart, Bound[K].Iterations);
02765     const SCEV *PositivePart = getPositivePart(Delta);
02766     Bound[K].Upper[Dependence::DVEntry::EQ] =
02767       SE->getMulExpr(PositivePart, Bound[K].Iterations);
02768   }
02769   else {
02770     // If the positive/negative part of the difference is 0,
02771     // we won't need to know the number of iterations.
02772     const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
02773     const SCEV *NegativePart = getNegativePart(Delta);
02774     if (NegativePart->isZero())
02775       Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
02776     const SCEV *PositivePart = getPositivePart(Delta);
02777     if (PositivePart->isZero())
02778       Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
02779   }
02780 }
02781 
02782 
02783 // Computes the upper and lower bounds for level K
02784 // using the < direction. Records them in Bound.
02785 // Wolfe gives the equations
02786 //
02787 //    LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
02788 //    UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
02789 //
02790 // Since we normalize loops, we can simplify these equations to
02791 //
02792 //    LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
02793 //    UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
02794 //
02795 // We must be careful to handle the case where the upper bound is unknown.
02796 void DependenceAnalysis::findBoundsLT(CoefficientInfo *A,
02797                                       CoefficientInfo *B,
02798                                       BoundInfo *Bound,
02799                                       unsigned K) const {
02800   Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
02801   Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
02802   if (Bound[K].Iterations) {
02803     const SCEV *Iter_1 =
02804       SE->getMinusSCEV(Bound[K].Iterations,
02805                        SE->getConstant(Bound[K].Iterations->getType(), 1));
02806     const SCEV *NegPart =
02807       getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
02808     Bound[K].Lower[Dependence::DVEntry::LT] =
02809       SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
02810     const SCEV *PosPart =
02811       getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
02812     Bound[K].Upper[Dependence::DVEntry::LT] =
02813       SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
02814   }
02815   else {
02816     // If the positive/negative part of the difference is 0,
02817     // we won't need to know the number of iterations.
02818     const SCEV *NegPart =
02819       getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
02820     if (NegPart->isZero())
02821       Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
02822     const SCEV *PosPart =
02823       getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
02824     if (PosPart->isZero())
02825       Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
02826   }
02827 }
02828 
02829 
02830 // Computes the upper and lower bounds for level K
02831 // using the > direction. Records them in Bound.
02832 // Wolfe gives the equations
02833 //
02834 //    LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
02835 //    UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
02836 //
02837 // Since we normalize loops, we can simplify these equations to
02838 //
02839 //    LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
02840 //    UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
02841 //
02842 // We must be careful to handle the case where the upper bound is unknown.
02843 void DependenceAnalysis::findBoundsGT(CoefficientInfo *A,
02844                                       CoefficientInfo *B,
02845                                       BoundInfo *Bound,
02846                                       unsigned K) const {
02847   Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
02848   Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
02849   if (Bound[K].Iterations) {
02850     const SCEV *Iter_1 =
02851       SE->getMinusSCEV(Bound[K].Iterations,
02852                        SE->getConstant(Bound[K].Iterations->getType(), 1));
02853     const SCEV *NegPart =
02854       getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
02855     Bound[K].Lower[Dependence::DVEntry::GT] =
02856       SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
02857     const SCEV *PosPart =
02858       getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
02859     Bound[K].Upper[Dependence::DVEntry::GT] =
02860       SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
02861   }
02862   else {
02863     // If the positive/negative part of the difference is 0,
02864     // we won't need to know the number of iterations.
02865     const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
02866     if (NegPart->isZero())
02867       Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
02868     const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
02869     if (PosPart->isZero())
02870       Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
02871   }
02872 }
02873 
02874 
02875 // X^+ = max(X, 0)
02876 const SCEV *DependenceAnalysis::getPositivePart(const SCEV *X) const {
02877   return SE->getSMaxExpr(X, SE->getConstant(X->getType(), 0));
02878 }
02879 
02880 
02881 // X^- = min(X, 0)
02882 const SCEV *DependenceAnalysis::getNegativePart(const SCEV *X) const {
02883   return SE->getSMinExpr(X, SE->getConstant(X->getType(), 0));
02884 }
02885 
02886 
02887 // Walks through the subscript,
02888 // collecting each coefficient, the associated loop bounds,
02889 // and recording its positive and negative parts for later use.
02890 DependenceAnalysis::CoefficientInfo *
02891 DependenceAnalysis::collectCoeffInfo(const SCEV *Subscript,
02892                                      bool SrcFlag,
02893                                      const SCEV *&Constant) const {
02894   const SCEV *Zero = SE->getConstant(Subscript->getType(), 0);
02895   CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
02896   for (unsigned K = 1; K <= MaxLevels; ++K) {
02897     CI[K].Coeff = Zero;
02898     CI[K].PosPart = Zero;
02899     CI[K].NegPart = Zero;
02900     CI[K].Iterations = nullptr;
02901   }
02902   while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
02903     const Loop *L = AddRec->getLoop();
02904     unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
02905     CI[K].Coeff = AddRec->getStepRecurrence(*SE);
02906     CI[K].PosPart = getPositivePart(CI[K].Coeff);
02907     CI[K].NegPart = getNegativePart(CI[K].Coeff);
02908     CI[K].Iterations = collectUpperBound(L, Subscript->getType());
02909     Subscript = AddRec->getStart();
02910   }
02911   Constant = Subscript;
02912 #ifndef NDEBUG
02913   DEBUG(dbgs() << "\tCoefficient Info\n");
02914   for (unsigned K = 1; K <= MaxLevels; ++K) {
02915     DEBUG(dbgs() << "\t    " << K << "\t" << *CI[K].Coeff);
02916     DEBUG(dbgs() << "\tPos Part = ");
02917     DEBUG(dbgs() << *CI[K].PosPart);
02918     DEBUG(dbgs() << "\tNeg Part = ");
02919     DEBUG(dbgs() << *CI[K].NegPart);
02920     DEBUG(dbgs() << "\tUpper Bound = ");
02921     if (CI[K].Iterations)
02922       DEBUG(dbgs() << *CI[K].Iterations);
02923     else
02924       DEBUG(dbgs() << "+inf");
02925     DEBUG(dbgs() << '\n');
02926   }
02927   DEBUG(dbgs() << "\t    Constant = " << *Subscript << '\n');
02928 #endif
02929   return CI;
02930 }
02931 
02932 
02933 // Looks through all the bounds info and
02934 // computes the lower bound given the current direction settings
02935 // at each level. If the lower bound for any level is -inf,
02936 // the result is -inf.
02937 const SCEV *DependenceAnalysis::getLowerBound(BoundInfo *Bound) const {
02938   const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
02939   for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
02940     if (Bound[K].Lower[Bound[K].Direction])
02941       Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
02942     else
02943       Sum = nullptr;
02944   }
02945   return Sum;
02946 }
02947 
02948 
02949 // Looks through all the bounds info and
02950 // computes the upper bound given the current direction settings
02951 // at each level. If the upper bound at any level is +inf,
02952 // the result is +inf.
02953 const SCEV *DependenceAnalysis::getUpperBound(BoundInfo *Bound) const {
02954   const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
02955   for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
02956     if (Bound[K].Upper[Bound[K].Direction])
02957       Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
02958     else
02959       Sum = nullptr;
02960   }
02961   return Sum;
02962 }
02963 
02964 
02965 //===----------------------------------------------------------------------===//
02966 // Constraint manipulation for Delta test.
02967 
02968 // Given a linear SCEV,
02969 // return the coefficient (the step)
02970 // corresponding to the specified loop.
02971 // If there isn't one, return 0.
02972 // For example, given a*i + b*j + c*k, finding the coefficient
02973 // corresponding to the j loop would yield b.
02974 const SCEV *DependenceAnalysis::findCoefficient(const SCEV *Expr,
02975                                                 const Loop *TargetLoop)  const {
02976   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
02977   if (!AddRec)
02978     return SE->getConstant(Expr->getType(), 0);
02979   if (AddRec->getLoop() == TargetLoop)
02980     return AddRec->getStepRecurrence(*SE);
02981   return findCoefficient(AddRec->getStart(), TargetLoop);
02982 }
02983 
02984 
02985 // Given a linear SCEV,
02986 // return the SCEV given by zeroing out the coefficient
02987 // corresponding to the specified loop.
02988 // For example, given a*i + b*j + c*k, zeroing the coefficient
02989 // corresponding to the j loop would yield a*i + c*k.
02990 const SCEV *DependenceAnalysis::zeroCoefficient(const SCEV *Expr,
02991                                                 const Loop *TargetLoop)  const {
02992   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
02993   if (!AddRec)
02994     return Expr; // ignore
02995   if (AddRec->getLoop() == TargetLoop)
02996     return AddRec->getStart();
02997   return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
02998                            AddRec->getStepRecurrence(*SE),
02999                            AddRec->getLoop(),
03000                            AddRec->getNoWrapFlags());
03001 }
03002 
03003 
03004 // Given a linear SCEV Expr,
03005 // return the SCEV given by adding some Value to the
03006 // coefficient corresponding to the specified TargetLoop.
03007 // For example, given a*i + b*j + c*k, adding 1 to the coefficient
03008 // corresponding to the j loop would yield a*i + (b+1)*j + c*k.
03009 const SCEV *DependenceAnalysis::addToCoefficient(const SCEV *Expr,
03010                                                  const Loop *TargetLoop,
03011                                                  const SCEV *Value)  const {
03012   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
03013   if (!AddRec) // create a new addRec
03014     return SE->getAddRecExpr(Expr,
03015                              Value,
03016                              TargetLoop,
03017                              SCEV::FlagAnyWrap); // Worst case, with no info.
03018   if (AddRec->getLoop() == TargetLoop) {
03019     const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
03020     if (Sum->isZero())
03021       return AddRec->getStart();
03022     return SE->getAddRecExpr(AddRec->getStart(),
03023                              Sum,
03024                              AddRec->getLoop(),
03025                              AddRec->getNoWrapFlags());
03026   }
03027   if (SE->isLoopInvariant(AddRec, TargetLoop))
03028     return SE->getAddRecExpr(AddRec, Value, TargetLoop, SCEV::FlagAnyWrap);
03029   return SE->getAddRecExpr(
03030       addToCoefficient(AddRec->getStart(), TargetLoop, Value),
03031       AddRec->getStepRecurrence(*SE), AddRec->getLoop(),
03032       AddRec->getNoWrapFlags());
03033 }
03034 
03035 
03036 // Review the constraints, looking for opportunities
03037 // to simplify a subscript pair (Src and Dst).
03038 // Return true if some simplification occurs.
03039 // If the simplification isn't exact (that is, if it is conservative
03040 // in terms of dependence), set consistent to false.
03041 // Corresponds to Figure 5 from the paper
03042 //
03043 //            Practical Dependence Testing
03044 //            Goff, Kennedy, Tseng
03045 //            PLDI 1991
03046 bool DependenceAnalysis::propagate(const SCEV *&Src,
03047                                    const SCEV *&Dst,
03048                                    SmallBitVector &Loops,
03049                                    SmallVectorImpl<Constraint> &Constraints,
03050                                    bool &Consistent) {
03051   bool Result = false;
03052   for (int LI = Loops.find_first(); LI >= 0; LI = Loops.find_next(LI)) {
03053     DEBUG(dbgs() << "\t    Constraint[" << LI << "] is");
03054     DEBUG(Constraints[LI].dump(dbgs()));
03055     if (Constraints[LI].isDistance())
03056       Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
03057     else if (Constraints[LI].isLine())
03058       Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
03059     else if (Constraints[LI].isPoint())
03060       Result |= propagatePoint(Src, Dst, Constraints[LI]);
03061   }
03062   return Result;
03063 }
03064 
03065 
03066 // Attempt to propagate a distance
03067 // constraint into a subscript pair (Src and Dst).
03068 // Return true if some simplification occurs.
03069 // If the simplification isn't exact (that is, if it is conservative
03070 // in terms of dependence), set consistent to false.
03071 bool DependenceAnalysis::propagateDistance(const SCEV *&Src,
03072                                            const SCEV *&Dst,
03073                                            Constraint &CurConstraint,
03074                                            bool &Consistent) {
03075   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
03076   DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
03077   const SCEV *A_K = findCoefficient(Src, CurLoop);
03078   if (A_K->isZero())
03079     return false;
03080   const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
03081   Src = SE->getMinusSCEV(Src, DA_K);
03082   Src = zeroCoefficient(Src, CurLoop);
03083   DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
03084   DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
03085   Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
03086   DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
03087   if (!findCoefficient(Dst, CurLoop)->isZero())
03088     Consistent = false;
03089   return true;
03090 }
03091 
03092 
03093 // Attempt to propagate a line
03094 // constraint into a subscript pair (Src and Dst).
03095 // Return true if some simplification occurs.
03096 // If the simplification isn't exact (that is, if it is conservative
03097 // in terms of dependence), set consistent to false.
03098 bool DependenceAnalysis::propagateLine(const SCEV *&Src,
03099                                        const SCEV *&Dst,
03100                                        Constraint &CurConstraint,
03101                                        bool &Consistent) {
03102   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
03103   const SCEV *A = CurConstraint.getA();
03104   const SCEV *B = CurConstraint.getB();
03105   const SCEV *C = CurConstraint.getC();
03106   DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C << "\n");
03107   DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
03108   DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
03109   if (A->isZero()) {
03110     const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
03111     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
03112     if (!Bconst || !Cconst) return false;
03113     APInt Beta = Bconst->getValue()->getValue();
03114     APInt Charlie = Cconst->getValue()->getValue();
03115     APInt CdivB = Charlie.sdiv(Beta);
03116     assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
03117     const SCEV *AP_K = findCoefficient(Dst, CurLoop);
03118     //    Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
03119     Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
03120     Dst = zeroCoefficient(Dst, CurLoop);
03121     if (!findCoefficient(Src, CurLoop)->isZero())
03122       Consistent = false;
03123   }
03124   else if (B->isZero()) {
03125     const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
03126     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
03127     if (!Aconst || !Cconst) return false;
03128     APInt Alpha = Aconst->getValue()->getValue();
03129     APInt Charlie = Cconst->getValue()->getValue();
03130     APInt CdivA = Charlie.sdiv(Alpha);
03131     assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
03132     const SCEV *A_K = findCoefficient(Src, CurLoop);
03133     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
03134     Src = zeroCoefficient(Src, CurLoop);
03135     if (!findCoefficient(Dst, CurLoop)->isZero())
03136       Consistent = false;
03137   }
03138   else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
03139     const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
03140     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
03141     if (!Aconst || !Cconst) return false;
03142     APInt Alpha = Aconst->getValue()->getValue();
03143     APInt Charlie = Cconst->getValue()->getValue();
03144     APInt CdivA = Charlie.sdiv(Alpha);
03145     assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
03146     const SCEV *A_K = findCoefficient(Src, CurLoop);
03147     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
03148     Src = zeroCoefficient(Src, CurLoop);
03149     Dst = addToCoefficient(Dst, CurLoop, A_K);
03150     if (!findCoefficient(Dst, CurLoop)->isZero())
03151       Consistent = false;
03152   }
03153   else {
03154     // paper is incorrect here, or perhaps just misleading
03155     const SCEV *A_K = findCoefficient(Src, CurLoop);
03156     Src = SE->getMulExpr(Src, A);
03157     Dst = SE->getMulExpr(Dst, A);
03158     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
03159     Src = zeroCoefficient(Src, CurLoop);
03160     Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
03161     if (!findCoefficient(Dst, CurLoop)->isZero())
03162       Consistent = false;
03163   }
03164   DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
03165   DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
03166   return true;
03167 }
03168 
03169 
03170 // Attempt to propagate a point
03171 // constraint into a subscript pair (Src and Dst).
03172 // Return true if some simplification occurs.
03173 bool DependenceAnalysis::propagatePoint(const SCEV *&Src,
03174                                         const SCEV *&Dst,
03175                                         Constraint &CurConstraint) {
03176   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
03177   const SCEV *A_K = findCoefficient(Src, CurLoop);
03178   const SCEV *AP_K = findCoefficient(Dst, CurLoop);
03179   const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
03180   const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
03181   DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
03182   Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
03183   Src = zeroCoefficient(Src, CurLoop);
03184   DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
03185   DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
03186   Dst = zeroCoefficient(Dst, CurLoop);
03187   DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
03188   return true;
03189 }
03190 
03191 
03192 // Update direction vector entry based on the current constraint.
03193 void DependenceAnalysis::updateDirection(Dependence::DVEntry &Level,
03194                                          const Constraint &CurConstraint
03195                                          ) const {
03196   DEBUG(dbgs() << "\tUpdate direction, constraint =");
03197   DEBUG(CurConstraint.dump(dbgs()));
03198   if (CurConstraint.isAny())
03199     ; // use defaults
03200   else if (CurConstraint.isDistance()) {
03201     // this one is consistent, the others aren't
03202     Level.Scalar = false;
03203     Level.Distance = CurConstraint.getD();
03204     unsigned NewDirection = Dependence::DVEntry::NONE;
03205     if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
03206       NewDirection = Dependence::DVEntry::EQ;
03207     if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
03208       NewDirection |= Dependence::DVEntry::LT;
03209     if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
03210       NewDirection |= Dependence::DVEntry::GT;
03211     Level.Direction &= NewDirection;
03212   }
03213   else if (CurConstraint.isLine()) {
03214     Level.Scalar = false;
03215     Level.Distance = nullptr;
03216     // direction should be accurate
03217   }
03218   else if (CurConstraint.isPoint()) {
03219     Level.Scalar = false;
03220     Level.Distance = nullptr;
03221     unsigned NewDirection = Dependence::DVEntry::NONE;
03222     if (!isKnownPredicate(CmpInst::ICMP_NE,
03223                           CurConstraint.getY(),
03224                           CurConstraint.getX()))
03225       // if X may be = Y
03226       NewDirection |= Dependence::DVEntry::EQ;
03227     if (!isKnownPredicate(CmpInst::ICMP_SLE,
03228                           CurConstraint.getY(),
03229                           CurConstraint.getX()))
03230       // if Y may be > X
03231       NewDirection |= Dependence::DVEntry::LT;
03232     if (!isKnownPredicate(CmpInst::ICMP_SGE,
03233                           CurConstraint.getY(),
03234                           CurConstraint.getX()))
03235       // if Y may be < X
03236       NewDirection |= Dependence::DVEntry::GT;
03237     Level.Direction &= NewDirection;
03238   }
03239   else
03240     llvm_unreachable("constraint has unexpected kind");
03241 }
03242 
03243 /// Check if we can delinearize the subscripts. If the SCEVs representing the
03244 /// source and destination array references are recurrences on a nested loop,
03245 /// this function flattens the nested recurrences into separate recurrences
03246 /// for each loop level.
03247 bool DependenceAnalysis::tryDelinearize(const SCEV *SrcSCEV,
03248                                         const SCEV *DstSCEV,
03249                                         SmallVectorImpl<Subscript> &Pair,
03250                                         const SCEV *ElementSize) {
03251   const SCEVUnknown *SrcBase =
03252       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcSCEV));
03253   const SCEVUnknown *DstBase =
03254       dyn_cast<SCEVUnknown>(SE->getPointerBase(DstSCEV));
03255 
03256   if (!SrcBase || !DstBase || SrcBase != DstBase)
03257     return false;
03258 
03259   SrcSCEV = SE->getMinusSCEV(SrcSCEV, SrcBase);
03260   DstSCEV = SE->getMinusSCEV(DstSCEV, DstBase);
03261 
03262   const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
03263   const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
03264   if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
03265     return false;
03266 
03267   // First step: collect parametric terms in both array references.
03268   SmallVector<const SCEV *, 4> Terms;
03269   SrcAR->collectParametricTerms(*SE, Terms);
03270   DstAR->collectParametricTerms(*SE, Terms);
03271 
03272   // Second step: find subscript sizes.
03273   SmallVector<const SCEV *, 4> Sizes;
03274   SE->findArrayDimensions(Terms, Sizes, ElementSize);
03275 
03276   // Third step: compute the access functions for each subscript.
03277   SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
03278   SrcAR->computeAccessFunctions(*SE, SrcSubscripts, Sizes);
03279   DstAR->computeAccessFunctions(*SE, DstSubscripts, Sizes);
03280 
03281   // Fail when there is only a subscript: that's a linearized access function.
03282   if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
03283       SrcSubscripts.size() != DstSubscripts.size())
03284     return false;
03285 
03286   int size = SrcSubscripts.size();
03287 
03288   DEBUG({
03289       dbgs() << "\nSrcSubscripts: ";
03290     for (int i = 0; i < size; i++)
03291       dbgs() << *SrcSubscripts[i];
03292     dbgs() << "\nDstSubscripts: ";
03293     for (int i = 0; i < size; i++)
03294       dbgs() << *DstSubscripts[i];
03295     });
03296 
03297   // The delinearization transforms a single-subscript MIV dependence test into
03298   // a multi-subscript SIV dependence test that is easier to compute. So we
03299   // resize Pair to contain as many pairs of subscripts as the delinearization
03300   // has found, and then initialize the pairs following the delinearization.
03301   Pair.resize(size);
03302   for (int i = 0; i < size; ++i) {
03303     Pair[i].Src = SrcSubscripts[i];
03304     Pair[i].Dst = DstSubscripts[i];
03305     unifySubscriptType(&Pair[i]);
03306 
03307     // FIXME: we should record the bounds SrcSizes[i] and DstSizes[i] that the
03308     // delinearization has found, and add these constraints to the dependence
03309     // check to avoid memory accesses overflow from one dimension into another.
03310     // This is related to the problem of determining the existence of data
03311     // dependences in array accesses using a different number of subscripts: in
03312     // C one can access an array A[100][100]; as A[0][9999], *A[9999], etc.
03313   }
03314 
03315   return true;
03316 }
03317 
03318 //===----------------------------------------------------------------------===//
03319 
03320 #ifndef NDEBUG
03321 // For debugging purposes, dump a small bit vector to dbgs().
03322 static void dumpSmallBitVector(SmallBitVector &BV) {
03323   dbgs() << "{";
03324   for (int VI = BV.find_first(); VI >= 0; VI = BV.find_next(VI)) {
03325     dbgs() << VI;
03326     if (BV.find_next(VI) >= 0)
03327       dbgs() << ' ';
03328   }
03329   dbgs() << "}\n";
03330 }
03331 #endif
03332 
03333 
03334 // depends -
03335 // Returns NULL if there is no dependence.
03336 // Otherwise, return a Dependence with as many details as possible.
03337 // Corresponds to Section 3.1 in the paper
03338 //
03339 //            Practical Dependence Testing
03340 //            Goff, Kennedy, Tseng
03341 //            PLDI 1991
03342 //
03343 // Care is required to keep the routine below, getSplitIteration(),
03344 // up to date with respect to this routine.
03345 std::unique_ptr<Dependence>
03346 DependenceAnalysis::depends(Instruction *Src, Instruction *Dst,
03347                             bool PossiblyLoopIndependent) {
03348   if (Src == Dst)
03349     PossiblyLoopIndependent = false;
03350 
03351   if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
03352       (!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
03353     // if both instructions don't reference memory, there's no dependence
03354     return nullptr;
03355 
03356   if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
03357     // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
03358     DEBUG(dbgs() << "can only handle simple loads and stores\n");
03359     return make_unique<Dependence>(Src, Dst);
03360   }
03361 
03362   Value *SrcPtr = getPointerOperand(Src);
03363   Value *DstPtr = getPointerOperand(Dst);
03364 
03365   switch (underlyingObjectsAlias(AA, F->getParent()->getDataLayout(), DstPtr,
03366                                  SrcPtr)) {
03367   case MayAlias:
03368   case PartialAlias:
03369     // cannot analyse objects if we don't understand their aliasing.
03370     DEBUG(dbgs() << "can't analyze may or partial alias\n");
03371     return make_unique<Dependence>(Src, Dst);
03372   case NoAlias:
03373     // If the objects noalias, they are distinct, accesses are independent.
03374     DEBUG(dbgs() << "no alias\n");
03375     return nullptr;
03376   case MustAlias:
03377     break; // The underlying objects alias; test accesses for dependence.
03378   }
03379 
03380   // establish loop nesting levels
03381   establishNestingLevels(Src, Dst);
03382   DEBUG(dbgs() << "    common nesting levels = " << CommonLevels << "\n");
03383   DEBUG(dbgs() << "    maximum nesting levels = " << MaxLevels << "\n");
03384 
03385   FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
03386   ++TotalArrayPairs;
03387 
03388   // See if there are GEPs we can use.
03389   bool UsefulGEP = false;
03390   GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr);
03391   GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr);
03392   if (SrcGEP && DstGEP &&
03393       SrcGEP->getPointerOperandType() == DstGEP->getPointerOperandType()) {
03394     const SCEV *SrcPtrSCEV = SE->getSCEV(SrcGEP->getPointerOperand());
03395     const SCEV *DstPtrSCEV = SE->getSCEV(DstGEP->getPointerOperand());
03396     DEBUG(dbgs() << "    SrcPtrSCEV = " << *SrcPtrSCEV << "\n");
03397     DEBUG(dbgs() << "    DstPtrSCEV = " << *DstPtrSCEV << "\n");
03398 
03399     UsefulGEP = isLoopInvariant(SrcPtrSCEV, LI->getLoopFor(Src->getParent())) &&
03400                 isLoopInvariant(DstPtrSCEV, LI->getLoopFor(Dst->getParent())) &&
03401                 (SrcGEP->getNumOperands() == DstGEP->getNumOperands());
03402   }
03403   unsigned Pairs = UsefulGEP ? SrcGEP->idx_end() - SrcGEP->idx_begin() : 1;
03404   SmallVector<Subscript, 4> Pair(Pairs);
03405   if (UsefulGEP) {
03406     DEBUG(dbgs() << "    using GEPs\n");
03407     unsigned P = 0;
03408     for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(),
03409            SrcEnd = SrcGEP->idx_end(),
03410            DstIdx = DstGEP->idx_begin();
03411          SrcIdx != SrcEnd;
03412          ++SrcIdx, ++DstIdx, ++P) {
03413       Pair[P].Src = SE->getSCEV(*SrcIdx);
03414       Pair[P].Dst = SE->getSCEV(*DstIdx);
03415       unifySubscriptType(&Pair[P]);
03416     }
03417   }
03418   else {
03419     DEBUG(dbgs() << "    ignoring GEPs\n");
03420     const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
03421     const SCEV *DstSCEV = SE->getSCEV(DstPtr);
03422     DEBUG(dbgs() << "    SrcSCEV = " << *SrcSCEV << "\n");
03423     DEBUG(dbgs() << "    DstSCEV = " << *DstSCEV << "\n");
03424     Pair[0].Src = SrcSCEV;
03425     Pair[0].Dst = DstSCEV;
03426   }
03427 
03428   if (Delinearize && Pairs == 1 && CommonLevels > 1 &&
03429       tryDelinearize(Pair[0].Src, Pair[0].Dst, Pair, SE->getElementSize(Src))) {
03430     DEBUG(dbgs() << "    delinerized GEP\n");
03431     Pairs = Pair.size();
03432   }
03433 
03434   for (unsigned P = 0; P < Pairs; ++P) {
03435     Pair[P].Loops.resize(MaxLevels + 1);
03436     Pair[P].GroupLoops.resize(MaxLevels + 1);
03437     Pair[P].Group.resize(Pairs);
03438     removeMatchingExtensions(&Pair[P]);
03439     Pair[P].Classification =
03440       classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
03441                    Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
03442                    Pair[P].Loops);
03443     Pair[P].GroupLoops = Pair[P].Loops;
03444     Pair[P].Group.set(P);
03445     DEBUG(dbgs() << "    subscript " << P << "\n");
03446     DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
03447     DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
03448     DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
03449     DEBUG(dbgs() << "\tloops = ");
03450     DEBUG(dumpSmallBitVector(Pair[P].Loops));
03451   }
03452 
03453   SmallBitVector Separable(Pairs);
03454   SmallBitVector Coupled(Pairs);
03455 
03456   // Partition subscripts into separable and minimally-coupled groups
03457   // Algorithm in paper is algorithmically better;
03458   // this may be faster in practice. Check someday.
03459   //
03460   // Here's an example of how it works. Consider this code:
03461   //
03462   //   for (i = ...) {
03463   //     for (j = ...) {
03464   //       for (k = ...) {
03465   //         for (l = ...) {
03466   //           for (m = ...) {
03467   //             A[i][j][k][m] = ...;
03468   //             ... = A[0][j][l][i + j];
03469   //           }
03470   //         }
03471   //       }
03472   //     }
03473   //   }
03474   //
03475   // There are 4 subscripts here:
03476   //    0 [i] and [0]
03477   //    1 [j] and [j]
03478   //    2 [k] and [l]
03479   //    3 [m] and [i + j]
03480   //
03481   // We've already classified each subscript pair as ZIV, SIV, etc.,
03482   // and collected all the loops mentioned by pair P in Pair[P].Loops.
03483   // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
03484   // and set Pair[P].Group = {P}.
03485   //
03486   //      Src Dst    Classification Loops  GroupLoops Group
03487   //    0 [i] [0]         SIV       {1}      {1}        {0}
03488   //    1 [j] [j]         SIV       {2}      {2}        {1}
03489   //    2 [k] [l]         RDIV      {3,4}    {3,4}      {2}
03490   //    3 [m] [i + j]     MIV       {1,2,5}  {1,2,5}    {3}
03491   //
03492   // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
03493   // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
03494   //
03495   // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
03496   // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
03497   // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
03498   // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
03499   // to either Separable or Coupled).
03500   //
03501   // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
03502   // Next, 1 and 3. The intersectionof their GroupLoops = {2}, not empty,
03503   // so Pair[3].Group = {0, 1, 3} and Done = false.
03504   //
03505   // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
03506   // Since Done remains true, we add 2 to the set of Separable pairs.
03507   //
03508   // Finally, we consider 3. There's nothing to compare it with,
03509   // so Done remains true and we add it to the Coupled set.
03510   // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
03511   //
03512   // In the end, we've got 1 separable subscript and 1 coupled group.
03513   for (unsigned SI = 0; SI < Pairs; ++SI) {
03514     if (Pair[SI].Classification == Subscript::NonLinear) {
03515       // ignore these, but collect loops for later
03516       ++NonlinearSubscriptPairs;
03517       collectCommonLoops(Pair[SI].Src,
03518                          LI->getLoopFor(Src->getParent()),
03519                          Pair[SI].Loops);
03520       collectCommonLoops(Pair[SI].Dst,
03521                          LI->getLoopFor(Dst->getParent()),
03522                          Pair[SI].Loops);
03523       Result.Consistent = false;
03524     } else if (Pair[SI].Classification == Subscript::ZIV) {
03525       // always separable
03526       Separable.set(SI);
03527     }
03528     else {
03529       // SIV, RDIV, or MIV, so check for coupled group
03530       bool Done = true;
03531       for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
03532         SmallBitVector Intersection = Pair[SI].GroupLoops;
03533         Intersection &= Pair[SJ].GroupLoops;
03534         if (Intersection.any()) {
03535           // accumulate set of all the loops in group
03536           Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
03537           // accumulate set of all subscripts in group
03538           Pair[SJ].Group |= Pair[SI].Group;
03539           Done = false;
03540         }
03541       }
03542       if (Done) {
03543         if (Pair[SI].Group.count() == 1) {
03544           Separable.set(SI);
03545           ++SeparableSubscriptPairs;
03546         }
03547         else {
03548           Coupled.set(SI);
03549           ++CoupledSubscriptPairs;
03550         }
03551       }
03552     }
03553   }
03554 
03555   DEBUG(dbgs() << "    Separable = ");
03556   DEBUG(dumpSmallBitVector(Separable));
03557   DEBUG(dbgs() << "    Coupled = ");
03558   DEBUG(dumpSmallBitVector(Coupled));
03559 
03560   Constraint NewConstraint;
03561   NewConstraint.setAny(SE);
03562 
03563   // test separable subscripts
03564   for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) {
03565     DEBUG(dbgs() << "testing subscript " << SI);
03566     switch (Pair[SI].Classification) {
03567     case Subscript::ZIV:
03568       DEBUG(dbgs() << ", ZIV\n");
03569       if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
03570         return nullptr;
03571       break;
03572     case Subscript::SIV: {
03573       DEBUG(dbgs() << ", SIV\n");
03574       unsigned Level;
03575       const SCEV *SplitIter = nullptr;
03576       if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result, NewConstraint,
03577                   SplitIter))
03578         return nullptr;
03579       break;
03580     }
03581     case Subscript::RDIV:
03582       DEBUG(dbgs() << ", RDIV\n");
03583       if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
03584         return nullptr;
03585       break;
03586     case Subscript::MIV:
03587       DEBUG(dbgs() << ", MIV\n");
03588       if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
03589         return nullptr;
03590       break;
03591     default:
03592       llvm_unreachable("subscript has unexpected classification");
03593     }
03594   }
03595 
03596   if (Coupled.count()) {
03597     // test coupled subscript groups
03598     DEBUG(dbgs() << "starting on coupled subscripts\n");
03599     DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
03600     SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
03601     for (unsigned II = 0; II <= MaxLevels; ++II)
03602       Constraints[II].setAny(SE);
03603     for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) {
03604       DEBUG(dbgs() << "testing subscript group " << SI << " { ");
03605       SmallBitVector Group(Pair[SI].Group);
03606       SmallBitVector Sivs(Pairs);
03607       SmallBitVector Mivs(Pairs);
03608       SmallBitVector ConstrainedLevels(MaxLevels + 1);
03609       SmallVector<Subscript *, 4> PairsInGroup;
03610       for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) {
03611         DEBUG(dbgs() << SJ << " ");
03612         if (Pair[SJ].Classification == Subscript::SIV)
03613           Sivs.set(SJ);
03614         else
03615           Mivs.set(SJ);
03616         PairsInGroup.push_back(&Pair[SJ]);
03617       }
03618       unifySubscriptType(PairsInGroup);
03619       DEBUG(dbgs() << "}\n");
03620       while (Sivs.any()) {
03621         bool Changed = false;
03622         for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
03623           DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
03624           // SJ is an SIV subscript that's part of the current coupled group
03625           unsigned Level;
03626           const SCEV *SplitIter = nullptr;
03627           DEBUG(dbgs() << "SIV\n");
03628           if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, Result, NewConstraint,
03629                       SplitIter))
03630             return nullptr;
03631           ConstrainedLevels.set(Level);
03632           if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
03633             if (Constraints[Level].isEmpty()) {
03634               ++DeltaIndependence;
03635               return nullptr;
03636             }
03637             Changed = true;
03638           }
03639           Sivs.reset(SJ);
03640         }
03641         if (Changed) {
03642           // propagate, possibly creating new SIVs and ZIVs
03643           DEBUG(dbgs() << "    propagating\n");
03644           DEBUG(dbgs() << "\tMivs = ");
03645           DEBUG(dumpSmallBitVector(Mivs));
03646           for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
03647             // SJ is an MIV subscript that's part of the current coupled group
03648             DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
03649             if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
03650                           Constraints, Result.Consistent)) {
03651               DEBUG(dbgs() << "\t    Changed\n");
03652               ++DeltaPropagations;
03653               Pair[SJ].Classification =
03654                 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
03655                              Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
03656                              Pair[SJ].Loops);
03657               switch (Pair[SJ].Classification) {
03658               case Subscript::ZIV:
03659                 DEBUG(dbgs() << "ZIV\n");
03660                 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
03661                   return nullptr;
03662                 Mivs.reset(SJ);
03663                 break;
03664               case Subscript::SIV:
03665                 Sivs.set(SJ);
03666                 Mivs.reset(SJ);
03667                 break;
03668               case Subscript::RDIV:
03669               case Subscript::MIV:
03670                 break;
03671               default:
03672                 llvm_unreachable("bad subscript classification");
03673               }
03674             }
03675           }
03676         }
03677       }
03678 
03679       // test & propagate remaining RDIVs
03680       for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
03681         if (Pair[SJ].Classification == Subscript::RDIV) {
03682           DEBUG(dbgs() << "RDIV test\n");
03683           if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
03684             return nullptr;
03685           // I don't yet understand how to propagate RDIV results
03686           Mivs.reset(SJ);
03687         }
03688       }
03689 
03690       // test remaining MIVs
03691       // This code is temporary.
03692       // Better to somehow test all remaining subscripts simultaneously.
03693       for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
03694         if (Pair[SJ].Classification == Subscript::MIV) {
03695           DEBUG(dbgs() << "MIV test\n");
03696           if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
03697             return nullptr;
03698         }
03699         else
03700           llvm_unreachable("expected only MIV subscripts at this point");
03701       }
03702 
03703       // update Result.DV from constraint vector
03704       DEBUG(dbgs() << "    updating\n");
03705       for (int SJ = ConstrainedLevels.find_first(); SJ >= 0;
03706            SJ = ConstrainedLevels.find_next(SJ)) {
03707         if (SJ > (int)CommonLevels)
03708           break;
03709         updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
03710         if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
03711           return nullptr;
03712       }
03713     }
03714   }
03715 
03716   // Make sure the Scalar flags are set correctly.
03717   SmallBitVector CompleteLoops(MaxLevels + 1);
03718   for (unsigned SI = 0; SI < Pairs; ++SI)
03719     CompleteLoops |= Pair[SI].Loops;
03720   for (unsigned II = 1; II <= CommonLevels; ++II)
03721     if (CompleteLoops[II])
03722       Result.DV[II - 1].Scalar = false;
03723 
03724   if (PossiblyLoopIndependent) {
03725     // Make sure the LoopIndependent flag is set correctly.
03726     // All directions must include equal, otherwise no
03727     // loop-independent dependence is possible.
03728     for (unsigned II = 1; II <= CommonLevels; ++II) {
03729       if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
03730         Result.LoopIndependent = false;
03731         break;
03732       }
03733     }
03734   }
03735   else {
03736     // On the other hand, if all directions are equal and there's no
03737     // loop-independent dependence possible, then no dependence exists.
03738     bool AllEqual = true;
03739     for (unsigned II = 1; II <= CommonLevels; ++II) {
03740       if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
03741         AllEqual = false;
03742         break;
03743       }
03744     }
03745     if (AllEqual)
03746       return nullptr;
03747   }
03748 
03749   auto Final = make_unique<FullDependence>(Result);
03750   Result.DV = nullptr;
03751   return std::move(Final);
03752 }
03753 
03754 
03755 
03756 //===----------------------------------------------------------------------===//
03757 // getSplitIteration -
03758 // Rather than spend rarely-used space recording the splitting iteration
03759 // during the Weak-Crossing SIV test, we re-compute it on demand.
03760 // The re-computation is basically a repeat of the entire dependence test,
03761 // though simplified since we know that the dependence exists.
03762 // It's tedious, since we must go through all propagations, etc.
03763 //
03764 // Care is required to keep this code up to date with respect to the routine
03765 // above, depends().
03766 //
03767 // Generally, the dependence analyzer will be used to build
03768 // a dependence graph for a function (basically a map from instructions
03769 // to dependences). Looking for cycles in the graph shows us loops
03770 // that cannot be trivially vectorized/parallelized.
03771 //
03772 // We can try to improve the situation by examining all the dependences
03773 // that make up the cycle, looking for ones we can break.
03774 // Sometimes, peeling the first or last iteration of a loop will break
03775 // dependences, and we've got flags for those possibilities.
03776 // Sometimes, splitting a loop at some other iteration will do the trick,
03777 // and we've got a flag for that case. Rather than waste the space to
03778 // record the exact iteration (since we rarely know), we provide
03779 // a method that calculates the iteration. It's a drag that it must work
03780 // from scratch, but wonderful in that it's possible.
03781 //
03782 // Here's an example:
03783 //
03784 //    for (i = 0; i < 10; i++)
03785 //        A[i] = ...
03786 //        ... = A[11 - i]
03787 //
03788 // There's a loop-carried flow dependence from the store to the load,
03789 // found by the weak-crossing SIV test. The dependence will have a flag,
03790 // indicating that the dependence can be broken by splitting the loop.
03791 // Calling getSplitIteration will return 5.
03792 // Splitting the loop breaks the dependence, like so:
03793 //
03794 //    for (i = 0; i <= 5; i++)
03795 //        A[i] = ...
03796 //        ... = A[11 - i]
03797 //    for (i = 6; i < 10; i++)
03798 //        A[i] = ...
03799 //        ... = A[11 - i]
03800 //
03801 // breaks the dependence and allows us to vectorize/parallelize
03802 // both loops.
03803 const  SCEV *DependenceAnalysis::getSplitIteration(const Dependence &Dep,
03804                                                    unsigned SplitLevel) {
03805   assert(Dep.isSplitable(SplitLevel) &&
03806          "Dep should be splitable at SplitLevel");
03807   Instruction *Src = Dep.getSrc();
03808   Instruction *Dst = Dep.getDst();
03809   assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
03810   assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
03811   assert(isLoadOrStore(Src));
03812   assert(isLoadOrStore(Dst));
03813   Value *SrcPtr = getPointerOperand(Src);
03814   Value *DstPtr = getPointerOperand(Dst);
03815   assert(underlyingObjectsAlias(AA, F->getParent()->getDataLayout(), DstPtr,
03816                                 SrcPtr) == MustAlias);
03817 
03818   // establish loop nesting levels
03819   establishNestingLevels(Src, Dst);
03820 
03821   FullDependence Result(Src, Dst, false, CommonLevels);
03822 
03823   // See if there are GEPs we can use.
03824   bool UsefulGEP = false;
03825   GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr);
03826   GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr);
03827   if (SrcGEP && DstGEP &&
03828       SrcGEP->getPointerOperandType() == DstGEP->getPointerOperandType()) {
03829     const SCEV *SrcPtrSCEV = SE->getSCEV(SrcGEP->getPointerOperand());
03830     const SCEV *DstPtrSCEV = SE->getSCEV(DstGEP->getPointerOperand());
03831     UsefulGEP = isLoopInvariant(SrcPtrSCEV, LI->getLoopFor(Src->getParent())) &&
03832                 isLoopInvariant(DstPtrSCEV, LI->getLoopFor(Dst->getParent())) &&
03833                 (SrcGEP->getNumOperands() == DstGEP->getNumOperands());
03834   }
03835   unsigned Pairs = UsefulGEP ? SrcGEP->idx_end() - SrcGEP->idx_begin() : 1;
03836   SmallVector<Subscript, 4> Pair(Pairs);
03837   if (UsefulGEP) {
03838     unsigned P = 0;
03839     for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(),
03840            SrcEnd = SrcGEP->idx_end(),
03841            DstIdx = DstGEP->idx_begin();
03842          SrcIdx != SrcEnd;
03843          ++SrcIdx, ++DstIdx, ++P) {
03844       Pair[P].Src = SE->getSCEV(*SrcIdx);
03845       Pair[P].Dst = SE->getSCEV(*DstIdx);
03846     }
03847   }
03848   else {
03849     const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
03850     const SCEV *DstSCEV = SE->getSCEV(DstPtr);
03851     Pair[0].Src = SrcSCEV;
03852     Pair[0].Dst = DstSCEV;
03853   }
03854 
03855   if (Delinearize && Pairs == 1 && CommonLevels > 1 &&
03856       tryDelinearize(Pair[0].Src, Pair[0].Dst, Pair, SE->getElementSize(Src))) {
03857     DEBUG(dbgs() << "    delinerized GEP\n");
03858     Pairs = Pair.size();
03859   }
03860 
03861   for (unsigned P = 0; P < Pairs; ++P) {
03862     Pair[P].Loops.resize(MaxLevels + 1);
03863     Pair[P].GroupLoops.resize(MaxLevels + 1);
03864     Pair[P].Group.resize(Pairs);
03865     removeMatchingExtensions(&Pair[P]);
03866     Pair[P].Classification =
03867       classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
03868                    Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
03869                    Pair[P].Loops);
03870     Pair[P].GroupLoops = Pair[P].Loops;
03871     Pair[P].Group.set(P);
03872   }
03873 
03874   SmallBitVector Separable(Pairs);
03875   SmallBitVector Coupled(Pairs);
03876 
03877   // partition subscripts into separable and minimally-coupled groups
03878   for (unsigned SI = 0; SI < Pairs; ++SI) {
03879     if (Pair[SI].Classification == Subscript::NonLinear) {
03880       // ignore these, but collect loops for later
03881       collectCommonLoops(Pair[SI].Src,
03882                          LI->getLoopFor(Src->getParent()),
03883                          Pair[SI].Loops);
03884       collectCommonLoops(Pair[SI].Dst,
03885                          LI->getLoopFor(Dst->getParent()),
03886                          Pair[SI].Loops);
03887       Result.Consistent = false;
03888     }
03889     else if (Pair[SI].Classification == Subscript::ZIV)
03890       Separable.set(SI);
03891     else {
03892       // SIV, RDIV, or MIV, so check for coupled group
03893       bool Done = true;
03894       for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
03895         SmallBitVector Intersection = Pair[SI].GroupLoops;
03896         Intersection &= Pair[SJ].GroupLoops;
03897         if (Intersection.any()) {
03898           // accumulate set of all the loops in group
03899           Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
03900           // accumulate set of all subscripts in group
03901           Pair[SJ].Group |= Pair[SI].Group;
03902           Done = false;
03903         }
03904       }
03905       if (Done) {
03906         if (Pair[SI].Group.count() == 1)
03907           Separable.set(SI);
03908         else
03909           Coupled.set(SI);
03910       }
03911     }
03912   }
03913 
03914   Constraint NewConstraint;
03915   NewConstraint.setAny(SE);
03916 
03917   // test separable subscripts
03918   for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) {
03919     switch (Pair[SI].Classification) {
03920     case Subscript::SIV: {
03921       unsigned Level;
03922       const SCEV *SplitIter = nullptr;
03923       (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
03924                      Result, NewConstraint, SplitIter);
03925       if (Level == SplitLevel) {
03926         assert(SplitIter != nullptr);
03927         return SplitIter;
03928       }
03929       break;
03930     }
03931     case Subscript::ZIV:
03932     case Subscript::RDIV:
03933     case Subscript::MIV:
03934       break;
03935     default:
03936       llvm_unreachable("subscript has unexpected classification");
03937     }
03938   }
03939 
03940   if (Coupled.count()) {
03941     // test coupled subscript groups
03942     SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
03943     for (unsigned II = 0; II <= MaxLevels; ++II)
03944       Constraints[II].setAny(SE);
03945     for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) {
03946       SmallBitVector Group(Pair[SI].Group);
03947       SmallBitVector Sivs(Pairs);
03948       SmallBitVector Mivs(Pairs);
03949       SmallBitVector ConstrainedLevels(MaxLevels + 1);
03950       for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) {
03951         if (Pair[SJ].Classification == Subscript::SIV)
03952           Sivs.set(SJ);
03953         else
03954           Mivs.set(SJ);
03955       }
03956       while (Sivs.any()) {
03957         bool Changed = false;
03958         for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
03959           // SJ is an SIV subscript that's part of the current coupled group
03960           unsigned Level;
03961           const SCEV *SplitIter = nullptr;
03962           (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
03963                          Result, NewConstraint, SplitIter);
03964           if (Level == SplitLevel && SplitIter)
03965             return SplitIter;
03966           ConstrainedLevels.set(Level);
03967           if (intersectConstraints(&Constraints[Level], &NewConstraint))
03968             Changed = true;
03969           Sivs.reset(SJ);
03970         }
03971         if (Changed) {
03972           // propagate, possibly creating new SIVs and ZIVs
03973           for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) {
03974             // SJ is an MIV subscript that's part of the current coupled group
03975             if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
03976                           Pair[SJ].Loops, Constraints, Result.Consistent)) {
03977               Pair[SJ].Classification =
03978                 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
03979                              Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
03980                              Pair[SJ].Loops);
03981               switch (Pair[SJ].Classification) {
03982               case Subscript::ZIV:
03983                 Mivs.reset(SJ);
03984                 break;
03985               case Subscript::SIV:
03986                 Sivs.set(SJ);
03987                 Mivs.reset(SJ);
03988                 break;
03989               case Subscript::RDIV:
03990               case Subscript::MIV:
03991                 break;
03992               default:
03993                 llvm_unreachable("bad subscript classification");
03994               }
03995             }
03996           }
03997         }
03998       }
03999     }
04000   }
04001   llvm_unreachable("somehow reached end of routine");
04002   return nullptr;
04003 }