1 //===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // DependenceAnalysis is an LLVM pass that analyses dependences between memory
10 // accesses. Currently, it is an (incomplete) implementation of the approach
11 // described in
12 //
13 //            Practical Dependence Testing
14 //            Goff, Kennedy, Tseng
15 //            PLDI 1991
16 //
17 // There's a single entry point that analyzes the dependence between a pair
18 // of memory references in a function, returning either NULL, for no dependence,
19 // or a more-or-less detailed description of the dependence between them.
20 //
21 // Currently, the implementation cannot propagate constraints between
22 // coupled RDIV subscripts and lacks a multi-subscript MIV test.
23 // Both of these are conservative weaknesses;
24 // that is, not a source of correctness problems.
25 //
26 // Since Clang linearizes some array subscripts, the dependence
27 // analysis is using SCEV->delinearize to recover the representation of multiple
28 // subscripts, and thus avoid the more expensive and less precise MIV tests. The
29 // delinearization is controlled by the flag -da-delinearize.
30 //
31 // We should pay some careful attention to the possibility of integer overflow
32 // in the implementation of the various tests. This could happen with Add,
33 // Subtract, or Multiply, with both APInt's and SCEV's.
34 //
35 // Some non-linear subscript pairs can be handled by the GCD test
36 // (and perhaps other tests).
37 // Should explore how often these things occur.
38 //
39 // Finally, it seems like certain test cases expose weaknesses in the SCEV
40 // simplification, especially in the handling of sign and zero extensions.
41 // It could be useful to spend time exploring these.
42 //
43 // Please note that this is work in progress and the interface is subject to
44 // change.
45 //
46 //===----------------------------------------------------------------------===//
47 //                                                                            //
48 //                   In memory of Ken Kennedy, 1945 - 2007                    //
49 //                                                                            //
50 //===----------------------------------------------------------------------===//
51 
52 #include "llvm/Analysis/DependenceAnalysis.h"
53 #include "llvm/ADT/Statistic.h"
54 #include "llvm/Analysis/AliasAnalysis.h"
55 #include "llvm/Analysis/Delinearization.h"
56 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/Analysis/ScalarEvolution.h"
58 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
59 #include "llvm/Analysis/ValueTracking.h"
60 #include "llvm/IR/InstIterator.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/InitializePasses.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "da"
71 
72 //===----------------------------------------------------------------------===//
73 // statistics
74 
75 STATISTIC(TotalArrayPairs, "Array pairs tested");
76 STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
77 STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
78 STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
79 STATISTIC(ZIVapplications, "ZIV applications");
80 STATISTIC(ZIVindependence, "ZIV independence");
81 STATISTIC(StrongSIVapplications, "Strong SIV applications");
82 STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
83 STATISTIC(StrongSIVindependence, "Strong SIV independence");
84 STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
85 STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
86 STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
87 STATISTIC(ExactSIVapplications, "Exact SIV applications");
88 STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
89 STATISTIC(ExactSIVindependence, "Exact SIV independence");
90 STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
91 STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
92 STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
93 STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
94 STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
95 STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
96 STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
97 STATISTIC(DeltaApplications, "Delta applications");
98 STATISTIC(DeltaSuccesses, "Delta successes");
99 STATISTIC(DeltaIndependence, "Delta independence");
100 STATISTIC(DeltaPropagations, "Delta propagations");
101 STATISTIC(GCDapplications, "GCD applications");
102 STATISTIC(GCDsuccesses, "GCD successes");
103 STATISTIC(GCDindependence, "GCD independence");
104 STATISTIC(BanerjeeApplications, "Banerjee applications");
105 STATISTIC(BanerjeeIndependence, "Banerjee independence");
106 STATISTIC(BanerjeeSuccesses, "Banerjee successes");
107 
108 static cl::opt<bool>
109     Delinearize("da-delinearize", cl::init(true), cl::Hidden,
110                 cl::desc("Try to delinearize array references."));
111 static cl::opt<bool> DisableDelinearizationChecks(
112     "da-disable-delinearization-checks", cl::Hidden,
113     cl::desc(
114         "Disable checks that try to statically verify validity of "
115         "delinearized subscripts. Enabling this option may result in incorrect "
116         "dependence vectors for languages that allow the subscript of one "
117         "dimension to underflow or overflow into another dimension."));
118 
119 static cl::opt<unsigned> MIVMaxLevelThreshold(
120     "da-miv-max-level-threshold", cl::init(7), cl::Hidden,
121     cl::desc("Maximum depth allowed for the recursive algorithm used to "
122              "explore MIV direction vectors."));
123 
124 //===----------------------------------------------------------------------===//
125 // basics
126 
127 DependenceAnalysis::Result
128 DependenceAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
129   auto &AA = FAM.getResult<AAManager>(F);
130   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
131   auto &LI = FAM.getResult<LoopAnalysis>(F);
132   return DependenceInfo(&F, &AA, &SE, &LI);
133 }
134 
135 AnalysisKey DependenceAnalysis::Key;
136 
137 INITIALIZE_PASS_BEGIN(DependenceAnalysisWrapperPass, "da",
138                       "Dependence Analysis", true, true)
139 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
140 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
141 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
142 INITIALIZE_PASS_END(DependenceAnalysisWrapperPass, "da", "Dependence Analysis",
143                     true, true)
144 
145 char DependenceAnalysisWrapperPass::ID = 0;
146 
147 DependenceAnalysisWrapperPass::DependenceAnalysisWrapperPass()
148     : FunctionPass(ID) {
149   initializeDependenceAnalysisWrapperPassPass(*PassRegistry::getPassRegistry());
150 }
151 
152 FunctionPass *llvm::createDependenceAnalysisWrapperPass() {
153   return new DependenceAnalysisWrapperPass();
154 }
155 
156 bool DependenceAnalysisWrapperPass::runOnFunction(Function &F) {
157   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
158   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
159   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
160   info.reset(new DependenceInfo(&F, &AA, &SE, &LI));
161   return false;
162 }
163 
164 DependenceInfo &DependenceAnalysisWrapperPass::getDI() const { return *info; }
165 
166 void DependenceAnalysisWrapperPass::releaseMemory() { info.reset(); }
167 
168 void DependenceAnalysisWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
169   AU.setPreservesAll();
170   AU.addRequiredTransitive<AAResultsWrapperPass>();
171   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
172   AU.addRequiredTransitive<LoopInfoWrapperPass>();
173 }
174 
175 // Used to test the dependence analyzer.
176 // Looks through the function, noting instructions that may access memory.
177 // Calls depends() on every possible pair and prints out the result.
178 // Ignores all other instructions.
179 static void dumpExampleDependence(raw_ostream &OS, DependenceInfo *DA) {
180   auto *F = DA->getFunction();
181   for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
182        ++SrcI) {
183     if (SrcI->mayReadOrWriteMemory()) {
184       for (inst_iterator DstI = SrcI, DstE = inst_end(F);
185            DstI != DstE; ++DstI) {
186         if (DstI->mayReadOrWriteMemory()) {
187           OS << "Src:" << *SrcI << " --> Dst:" << *DstI << "\n";
188           OS << "  da analyze - ";
189           if (auto D = DA->depends(&*SrcI, &*DstI, true)) {
190             D->dump(OS);
191             for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
192               if (D->isSplitable(Level)) {
193                 OS << "  da analyze - split level = " << Level;
194                 OS << ", iteration = " << *DA->getSplitIteration(*D, Level);
195                 OS << "!\n";
196               }
197             }
198           }
199           else
200             OS << "none!\n";
201         }
202       }
203     }
204   }
205 }
206 
207 void DependenceAnalysisWrapperPass::print(raw_ostream &OS,
208                                           const Module *) const {
209   dumpExampleDependence(OS, info.get());
210 }
211 
212 PreservedAnalyses
213 DependenceAnalysisPrinterPass::run(Function &F, FunctionAnalysisManager &FAM) {
214   OS << "'Dependence Analysis' for function '" << F.getName() << "':\n";
215   dumpExampleDependence(OS, &FAM.getResult<DependenceAnalysis>(F));
216   return PreservedAnalyses::all();
217 }
218 
219 //===----------------------------------------------------------------------===//
220 // Dependence methods
221 
222 // Returns true if this is an input dependence.
223 bool Dependence::isInput() const {
224   return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
225 }
226 
227 
228 // Returns true if this is an output dependence.
229 bool Dependence::isOutput() const {
230   return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
231 }
232 
233 
234 // Returns true if this is an flow (aka true)  dependence.
235 bool Dependence::isFlow() const {
236   return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
237 }
238 
239 
240 // Returns true if this is an anti dependence.
241 bool Dependence::isAnti() const {
242   return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
243 }
244 
245 
246 // Returns true if a particular level is scalar; that is,
247 // if no subscript in the source or destination mention the induction
248 // variable associated with the loop at this level.
249 // Leave this out of line, so it will serve as a virtual method anchor
250 bool Dependence::isScalar(unsigned level) const {
251   return false;
252 }
253 
254 
255 //===----------------------------------------------------------------------===//
256 // FullDependence methods
257 
258 FullDependence::FullDependence(Instruction *Source, Instruction *Destination,
259                                bool PossiblyLoopIndependent,
260                                unsigned CommonLevels)
261     : Dependence(Source, Destination), Levels(CommonLevels),
262       LoopIndependent(PossiblyLoopIndependent) {
263   Consistent = true;
264   if (CommonLevels)
265     DV = std::make_unique<DVEntry[]>(CommonLevels);
266 }
267 
268 // The rest are simple getters that hide the implementation.
269 
270 // getDirection - Returns the direction associated with a particular level.
271 unsigned FullDependence::getDirection(unsigned Level) const {
272   assert(0 < Level && Level <= Levels && "Level out of range");
273   return DV[Level - 1].Direction;
274 }
275 
276 
277 // Returns the distance (or NULL) associated with a particular level.
278 const SCEV *FullDependence::getDistance(unsigned Level) const {
279   assert(0 < Level && Level <= Levels && "Level out of range");
280   return DV[Level - 1].Distance;
281 }
282 
283 
284 // Returns true if a particular level is scalar; that is,
285 // if no subscript in the source or destination mention the induction
286 // variable associated with the loop at this level.
287 bool FullDependence::isScalar(unsigned Level) const {
288   assert(0 < Level && Level <= Levels && "Level out of range");
289   return DV[Level - 1].Scalar;
290 }
291 
292 
293 // Returns true if peeling the first iteration from this loop
294 // will break this dependence.
295 bool FullDependence::isPeelFirst(unsigned Level) const {
296   assert(0 < Level && Level <= Levels && "Level out of range");
297   return DV[Level - 1].PeelFirst;
298 }
299 
300 
301 // Returns true if peeling the last iteration from this loop
302 // will break this dependence.
303 bool FullDependence::isPeelLast(unsigned Level) const {
304   assert(0 < Level && Level <= Levels && "Level out of range");
305   return DV[Level - 1].PeelLast;
306 }
307 
308 
309 // Returns true if splitting this loop will break the dependence.
310 bool FullDependence::isSplitable(unsigned Level) const {
311   assert(0 < Level && Level <= Levels && "Level out of range");
312   return DV[Level - 1].Splitable;
313 }
314 
315 
316 //===----------------------------------------------------------------------===//
317 // DependenceInfo::Constraint methods
318 
319 // If constraint is a point <X, Y>, returns X.
320 // Otherwise assert.
321 const SCEV *DependenceInfo::Constraint::getX() const {
322   assert(Kind == Point && "Kind should be Point");
323   return A;
324 }
325 
326 
327 // If constraint is a point <X, Y>, returns Y.
328 // Otherwise assert.
329 const SCEV *DependenceInfo::Constraint::getY() const {
330   assert(Kind == Point && "Kind should be Point");
331   return B;
332 }
333 
334 
335 // If constraint is a line AX + BY = C, returns A.
336 // Otherwise assert.
337 const SCEV *DependenceInfo::Constraint::getA() const {
338   assert((Kind == Line || Kind == Distance) &&
339          "Kind should be Line (or Distance)");
340   return A;
341 }
342 
343 
344 // If constraint is a line AX + BY = C, returns B.
345 // Otherwise assert.
346 const SCEV *DependenceInfo::Constraint::getB() const {
347   assert((Kind == Line || Kind == Distance) &&
348          "Kind should be Line (or Distance)");
349   return B;
350 }
351 
352 
353 // If constraint is a line AX + BY = C, returns C.
354 // Otherwise assert.
355 const SCEV *DependenceInfo::Constraint::getC() const {
356   assert((Kind == Line || Kind == Distance) &&
357          "Kind should be Line (or Distance)");
358   return C;
359 }
360 
361 
362 // If constraint is a distance, returns D.
363 // Otherwise assert.
364 const SCEV *DependenceInfo::Constraint::getD() const {
365   assert(Kind == Distance && "Kind should be Distance");
366   return SE->getNegativeSCEV(C);
367 }
368 
369 
370 // Returns the loop associated with this constraint.
371 const Loop *DependenceInfo::Constraint::getAssociatedLoop() const {
372   assert((Kind == Distance || Kind == Line || Kind == Point) &&
373          "Kind should be Distance, Line, or Point");
374   return AssociatedLoop;
375 }
376 
377 void DependenceInfo::Constraint::setPoint(const SCEV *X, const SCEV *Y,
378                                           const Loop *CurLoop) {
379   Kind = Point;
380   A = X;
381   B = Y;
382   AssociatedLoop = CurLoop;
383 }
384 
385 void DependenceInfo::Constraint::setLine(const SCEV *AA, const SCEV *BB,
386                                          const SCEV *CC, const Loop *CurLoop) {
387   Kind = Line;
388   A = AA;
389   B = BB;
390   C = CC;
391   AssociatedLoop = CurLoop;
392 }
393 
394 void DependenceInfo::Constraint::setDistance(const SCEV *D,
395                                              const Loop *CurLoop) {
396   Kind = Distance;
397   A = SE->getOne(D->getType());
398   B = SE->getNegativeSCEV(A);
399   C = SE->getNegativeSCEV(D);
400   AssociatedLoop = CurLoop;
401 }
402 
403 void DependenceInfo::Constraint::setEmpty() { Kind = Empty; }
404 
405 void DependenceInfo::Constraint::setAny(ScalarEvolution *NewSE) {
406   SE = NewSE;
407   Kind = Any;
408 }
409 
410 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
411 // For debugging purposes. Dumps the constraint out to OS.
412 LLVM_DUMP_METHOD void DependenceInfo::Constraint::dump(raw_ostream &OS) const {
413   if (isEmpty())
414     OS << " Empty\n";
415   else if (isAny())
416     OS << " Any\n";
417   else if (isPoint())
418     OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
419   else if (isDistance())
420     OS << " Distance is " << *getD() <<
421       " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
422   else if (isLine())
423     OS << " Line is " << *getA() << "*X + " <<
424       *getB() << "*Y = " << *getC() << "\n";
425   else
426     llvm_unreachable("unknown constraint type in Constraint::dump");
427 }
428 #endif
429 
430 
431 // Updates X with the intersection
432 // of the Constraints X and Y. Returns true if X has changed.
433 // Corresponds to Figure 4 from the paper
434 //
435 //            Practical Dependence Testing
436 //            Goff, Kennedy, Tseng
437 //            PLDI 1991
438 bool DependenceInfo::intersectConstraints(Constraint *X, const Constraint *Y) {
439   ++DeltaApplications;
440   LLVM_DEBUG(dbgs() << "\tintersect constraints\n");
441   LLVM_DEBUG(dbgs() << "\t    X ="; X->dump(dbgs()));
442   LLVM_DEBUG(dbgs() << "\t    Y ="; Y->dump(dbgs()));
443   assert(!Y->isPoint() && "Y must not be a Point");
444   if (X->isAny()) {
445     if (Y->isAny())
446       return false;
447     *X = *Y;
448     return true;
449   }
450   if (X->isEmpty())
451     return false;
452   if (Y->isEmpty()) {
453     X->setEmpty();
454     return true;
455   }
456 
457   if (X->isDistance() && Y->isDistance()) {
458     LLVM_DEBUG(dbgs() << "\t    intersect 2 distances\n");
459     if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
460       return false;
461     if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
462       X->setEmpty();
463       ++DeltaSuccesses;
464       return true;
465     }
466     // Hmmm, interesting situation.
467     // I guess if either is constant, keep it and ignore the other.
468     if (isa<SCEVConstant>(Y->getD())) {
469       *X = *Y;
470       return true;
471     }
472     return false;
473   }
474 
475   // At this point, the pseudo-code in Figure 4 of the paper
476   // checks if (X->isPoint() && Y->isPoint()).
477   // This case can't occur in our implementation,
478   // since a Point can only arise as the result of intersecting
479   // two Line constraints, and the right-hand value, Y, is never
480   // the result of an intersection.
481   assert(!(X->isPoint() && Y->isPoint()) &&
482          "We shouldn't ever see X->isPoint() && Y->isPoint()");
483 
484   if (X->isLine() && Y->isLine()) {
485     LLVM_DEBUG(dbgs() << "\t    intersect 2 lines\n");
486     const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
487     const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
488     if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
489       // slopes are equal, so lines are parallel
490       LLVM_DEBUG(dbgs() << "\t\tsame slope\n");
491       Prod1 = SE->getMulExpr(X->getC(), Y->getB());
492       Prod2 = SE->getMulExpr(X->getB(), Y->getC());
493       if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
494         return false;
495       if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
496         X->setEmpty();
497         ++DeltaSuccesses;
498         return true;
499       }
500       return false;
501     }
502     if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
503       // slopes differ, so lines intersect
504       LLVM_DEBUG(dbgs() << "\t\tdifferent slopes\n");
505       const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
506       const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
507       const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
508       const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
509       const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
510       const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
511       const SCEVConstant *C1A2_C2A1 =
512         dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
513       const SCEVConstant *C1B2_C2B1 =
514         dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
515       const SCEVConstant *A1B2_A2B1 =
516         dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
517       const SCEVConstant *A2B1_A1B2 =
518         dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
519       if (!C1B2_C2B1 || !C1A2_C2A1 ||
520           !A1B2_A2B1 || !A2B1_A1B2)
521         return false;
522       APInt Xtop = C1B2_C2B1->getAPInt();
523       APInt Xbot = A1B2_A2B1->getAPInt();
524       APInt Ytop = C1A2_C2A1->getAPInt();
525       APInt Ybot = A2B1_A1B2->getAPInt();
526       LLVM_DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
527       LLVM_DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
528       LLVM_DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
529       LLVM_DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
530       APInt Xq = Xtop; // these need to be initialized, even
531       APInt Xr = Xtop; // though they're just going to be overwritten
532       APInt::sdivrem(Xtop, Xbot, Xq, Xr);
533       APInt Yq = Ytop;
534       APInt Yr = Ytop;
535       APInt::sdivrem(Ytop, Ybot, Yq, Yr);
536       if (Xr != 0 || Yr != 0) {
537         X->setEmpty();
538         ++DeltaSuccesses;
539         return true;
540       }
541       LLVM_DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
542       if (Xq.slt(0) || Yq.slt(0)) {
543         X->setEmpty();
544         ++DeltaSuccesses;
545         return true;
546       }
547       if (const SCEVConstant *CUB =
548           collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
549         const APInt &UpperBound = CUB->getAPInt();
550         LLVM_DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
551         if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
552           X->setEmpty();
553           ++DeltaSuccesses;
554           return true;
555         }
556       }
557       X->setPoint(SE->getConstant(Xq),
558                   SE->getConstant(Yq),
559                   X->getAssociatedLoop());
560       ++DeltaSuccesses;
561       return true;
562     }
563     return false;
564   }
565 
566   // if (X->isLine() && Y->isPoint()) This case can't occur.
567   assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
568 
569   if (X->isPoint() && Y->isLine()) {
570     LLVM_DEBUG(dbgs() << "\t    intersect Point and Line\n");
571     const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
572     const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
573     const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
574     if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
575       return false;
576     if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
577       X->setEmpty();
578       ++DeltaSuccesses;
579       return true;
580     }
581     return false;
582   }
583 
584   llvm_unreachable("shouldn't reach the end of Constraint intersection");
585   return false;
586 }
587 
588 
589 //===----------------------------------------------------------------------===//
590 // DependenceInfo methods
591 
592 // For debugging purposes. Dumps a dependence to OS.
593 void Dependence::dump(raw_ostream &OS) const {
594   bool Splitable = false;
595   if (isConfused())
596     OS << "confused";
597   else {
598     if (isConsistent())
599       OS << "consistent ";
600     if (isFlow())
601       OS << "flow";
602     else if (isOutput())
603       OS << "output";
604     else if (isAnti())
605       OS << "anti";
606     else if (isInput())
607       OS << "input";
608     unsigned Levels = getLevels();
609     OS << " [";
610     for (unsigned II = 1; II <= Levels; ++II) {
611       if (isSplitable(II))
612         Splitable = true;
613       if (isPeelFirst(II))
614         OS << 'p';
615       const SCEV *Distance = getDistance(II);
616       if (Distance)
617         OS << *Distance;
618       else if (isScalar(II))
619         OS << "S";
620       else {
621         unsigned Direction = getDirection(II);
622         if (Direction == DVEntry::ALL)
623           OS << "*";
624         else {
625           if (Direction & DVEntry::LT)
626             OS << "<";
627           if (Direction & DVEntry::EQ)
628             OS << "=";
629           if (Direction & DVEntry::GT)
630             OS << ">";
631         }
632       }
633       if (isPeelLast(II))
634         OS << 'p';
635       if (II < Levels)
636         OS << " ";
637     }
638     if (isLoopIndependent())
639       OS << "|<";
640     OS << "]";
641     if (Splitable)
642       OS << " splitable";
643   }
644   OS << "!\n";
645 }
646 
647 // Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
648 // underlaying objects. If LocA and LocB are known to not alias (for any reason:
649 // tbaa, non-overlapping regions etc), then it is known there is no dependecy.
650 // Otherwise the underlying objects are checked to see if they point to
651 // different identifiable objects.
652 static AliasResult underlyingObjectsAlias(AAResults *AA,
653                                           const DataLayout &DL,
654                                           const MemoryLocation &LocA,
655                                           const MemoryLocation &LocB) {
656   // Check the original locations (minus size) for noalias, which can happen for
657   // tbaa, incompatible underlying object locations, etc.
658   MemoryLocation LocAS =
659       MemoryLocation::getBeforeOrAfter(LocA.Ptr, LocA.AATags);
660   MemoryLocation LocBS =
661       MemoryLocation::getBeforeOrAfter(LocB.Ptr, LocB.AATags);
662   if (AA->isNoAlias(LocAS, LocBS))
663     return AliasResult::NoAlias;
664 
665   // Check the underlying objects are the same
666   const Value *AObj = getUnderlyingObject(LocA.Ptr);
667   const Value *BObj = getUnderlyingObject(LocB.Ptr);
668 
669   // If the underlying objects are the same, they must alias
670   if (AObj == BObj)
671     return AliasResult::MustAlias;
672 
673   // We may have hit the recursion limit for underlying objects, or have
674   // underlying objects where we don't know they will alias.
675   if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
676     return AliasResult::MayAlias;
677 
678   // Otherwise we know the objects are different and both identified objects so
679   // must not alias.
680   return AliasResult::NoAlias;
681 }
682 
683 
684 // Returns true if the load or store can be analyzed. Atomic and volatile
685 // operations have properties which this analysis does not understand.
686 static
687 bool isLoadOrStore(const Instruction *I) {
688   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
689     return LI->isUnordered();
690   else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
691     return SI->isUnordered();
692   return false;
693 }
694 
695 
696 // Examines the loop nesting of the Src and Dst
697 // instructions and establishes their shared loops. Sets the variables
698 // CommonLevels, SrcLevels, and MaxLevels.
699 // The source and destination instructions needn't be contained in the same
700 // loop. The routine establishNestingLevels finds the level of most deeply
701 // nested loop that contains them both, CommonLevels. An instruction that's
702 // not contained in a loop is at level = 0. MaxLevels is equal to the level
703 // of the source plus the level of the destination, minus CommonLevels.
704 // This lets us allocate vectors MaxLevels in length, with room for every
705 // distinct loop referenced in both the source and destination subscripts.
706 // The variable SrcLevels is the nesting depth of the source instruction.
707 // It's used to help calculate distinct loops referenced by the destination.
708 // Here's the map from loops to levels:
709 //            0 - unused
710 //            1 - outermost common loop
711 //          ... - other common loops
712 // CommonLevels - innermost common loop
713 //          ... - loops containing Src but not Dst
714 //    SrcLevels - innermost loop containing Src but not Dst
715 //          ... - loops containing Dst but not Src
716 //    MaxLevels - innermost loops containing Dst but not Src
717 // Consider the follow code fragment:
718 //   for (a = ...) {
719 //     for (b = ...) {
720 //       for (c = ...) {
721 //         for (d = ...) {
722 //           A[] = ...;
723 //         }
724 //       }
725 //       for (e = ...) {
726 //         for (f = ...) {
727 //           for (g = ...) {
728 //             ... = A[];
729 //           }
730 //         }
731 //       }
732 //     }
733 //   }
734 // If we're looking at the possibility of a dependence between the store
735 // to A (the Src) and the load from A (the Dst), we'll note that they
736 // have 2 loops in common, so CommonLevels will equal 2 and the direction
737 // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
738 // A map from loop names to loop numbers would look like
739 //     a - 1
740 //     b - 2 = CommonLevels
741 //     c - 3
742 //     d - 4 = SrcLevels
743 //     e - 5
744 //     f - 6
745 //     g - 7 = MaxLevels
746 void DependenceInfo::establishNestingLevels(const Instruction *Src,
747                                             const Instruction *Dst) {
748   const BasicBlock *SrcBlock = Src->getParent();
749   const BasicBlock *DstBlock = Dst->getParent();
750   unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
751   unsigned DstLevel = LI->getLoopDepth(DstBlock);
752   const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
753   const Loop *DstLoop = LI->getLoopFor(DstBlock);
754   SrcLevels = SrcLevel;
755   MaxLevels = SrcLevel + DstLevel;
756   while (SrcLevel > DstLevel) {
757     SrcLoop = SrcLoop->getParentLoop();
758     SrcLevel--;
759   }
760   while (DstLevel > SrcLevel) {
761     DstLoop = DstLoop->getParentLoop();
762     DstLevel--;
763   }
764   while (SrcLoop != DstLoop) {
765     SrcLoop = SrcLoop->getParentLoop();
766     DstLoop = DstLoop->getParentLoop();
767     SrcLevel--;
768   }
769   CommonLevels = SrcLevel;
770   MaxLevels -= CommonLevels;
771 }
772 
773 
774 // Given one of the loops containing the source, return
775 // its level index in our numbering scheme.
776 unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
777   return SrcLoop->getLoopDepth();
778 }
779 
780 
781 // Given one of the loops containing the destination,
782 // return its level index in our numbering scheme.
783 unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
784   unsigned D = DstLoop->getLoopDepth();
785   if (D > CommonLevels)
786     return D - CommonLevels + SrcLevels;
787   else
788     return D;
789 }
790 
791 
792 // Returns true if Expression is loop invariant in LoopNest.
793 bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
794                                      const Loop *LoopNest) const {
795   if (!LoopNest)
796     return true;
797   return SE->isLoopInvariant(Expression, LoopNest) &&
798     isLoopInvariant(Expression, LoopNest->getParentLoop());
799 }
800 
801 
802 
803 // Finds the set of loops from the LoopNest that
804 // have a level <= CommonLevels and are referred to by the SCEV Expression.
805 void DependenceInfo::collectCommonLoops(const SCEV *Expression,
806                                         const Loop *LoopNest,
807                                         SmallBitVector &Loops) const {
808   while (LoopNest) {
809     unsigned Level = LoopNest->getLoopDepth();
810     if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
811       Loops.set(Level);
812     LoopNest = LoopNest->getParentLoop();
813   }
814 }
815 
816 void DependenceInfo::unifySubscriptType(ArrayRef<Subscript *> Pairs) {
817 
818   unsigned widestWidthSeen = 0;
819   Type *widestType;
820 
821   // Go through each pair and find the widest bit to which we need
822   // to extend all of them.
823   for (Subscript *Pair : Pairs) {
824     const SCEV *Src = Pair->Src;
825     const SCEV *Dst = Pair->Dst;
826     IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
827     IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
828     if (SrcTy == nullptr || DstTy == nullptr) {
829       assert(SrcTy == DstTy && "This function only unify integer types and "
830              "expect Src and Dst share the same type "
831              "otherwise.");
832       continue;
833     }
834     if (SrcTy->getBitWidth() > widestWidthSeen) {
835       widestWidthSeen = SrcTy->getBitWidth();
836       widestType = SrcTy;
837     }
838     if (DstTy->getBitWidth() > widestWidthSeen) {
839       widestWidthSeen = DstTy->getBitWidth();
840       widestType = DstTy;
841     }
842   }
843 
844 
845   assert(widestWidthSeen > 0);
846 
847   // Now extend each pair to the widest seen.
848   for (Subscript *Pair : Pairs) {
849     const SCEV *Src = Pair->Src;
850     const SCEV *Dst = Pair->Dst;
851     IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
852     IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
853     if (SrcTy == nullptr || DstTy == nullptr) {
854       assert(SrcTy == DstTy && "This function only unify integer types and "
855              "expect Src and Dst share the same type "
856              "otherwise.");
857       continue;
858     }
859     if (SrcTy->getBitWidth() < widestWidthSeen)
860       // Sign-extend Src to widestType
861       Pair->Src = SE->getSignExtendExpr(Src, widestType);
862     if (DstTy->getBitWidth() < widestWidthSeen) {
863       // Sign-extend Dst to widestType
864       Pair->Dst = SE->getSignExtendExpr(Dst, widestType);
865     }
866   }
867 }
868 
869 // removeMatchingExtensions - Examines a subscript pair.
870 // If the source and destination are identically sign (or zero)
871 // extended, it strips off the extension in an effect to simplify
872 // the actual analysis.
873 void DependenceInfo::removeMatchingExtensions(Subscript *Pair) {
874   const SCEV *Src = Pair->Src;
875   const SCEV *Dst = Pair->Dst;
876   if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
877       (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
878     const SCEVIntegralCastExpr *SrcCast = cast<SCEVIntegralCastExpr>(Src);
879     const SCEVIntegralCastExpr *DstCast = cast<SCEVIntegralCastExpr>(Dst);
880     const SCEV *SrcCastOp = SrcCast->getOperand();
881     const SCEV *DstCastOp = DstCast->getOperand();
882     if (SrcCastOp->getType() == DstCastOp->getType()) {
883       Pair->Src = SrcCastOp;
884       Pair->Dst = DstCastOp;
885     }
886   }
887 }
888 
889 // Examine the scev and return true iff it's linear.
890 // Collect any loops mentioned in the set of "Loops".
891 bool DependenceInfo::checkSubscript(const SCEV *Expr, const Loop *LoopNest,
892                                     SmallBitVector &Loops, bool IsSrc) {
893   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
894   if (!AddRec)
895     return isLoopInvariant(Expr, LoopNest);
896   const SCEV *Start = AddRec->getStart();
897   const SCEV *Step = AddRec->getStepRecurrence(*SE);
898   const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
899   if (!isa<SCEVCouldNotCompute>(UB)) {
900     if (SE->getTypeSizeInBits(Start->getType()) <
901         SE->getTypeSizeInBits(UB->getType())) {
902       if (!AddRec->getNoWrapFlags())
903         return false;
904     }
905   }
906   if (!isLoopInvariant(Step, LoopNest))
907     return false;
908   if (IsSrc)
909     Loops.set(mapSrcLoop(AddRec->getLoop()));
910   else
911     Loops.set(mapDstLoop(AddRec->getLoop()));
912   return checkSubscript(Start, LoopNest, Loops, IsSrc);
913 }
914 
915 // Examine the scev and return true iff it's linear.
916 // Collect any loops mentioned in the set of "Loops".
917 bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
918                                        SmallBitVector &Loops) {
919   return checkSubscript(Src, LoopNest, Loops, true);
920 }
921 
922 // Examine the scev and return true iff it's linear.
923 // Collect any loops mentioned in the set of "Loops".
924 bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
925                                        SmallBitVector &Loops) {
926   return checkSubscript(Dst, LoopNest, Loops, false);
927 }
928 
929 
930 // Examines the subscript pair (the Src and Dst SCEVs)
931 // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
932 // Collects the associated loops in a set.
933 DependenceInfo::Subscript::ClassificationKind
934 DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
935                              const SCEV *Dst, const Loop *DstLoopNest,
936                              SmallBitVector &Loops) {
937   SmallBitVector SrcLoops(MaxLevels + 1);
938   SmallBitVector DstLoops(MaxLevels + 1);
939   if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
940     return Subscript::NonLinear;
941   if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
942     return Subscript::NonLinear;
943   Loops = SrcLoops;
944   Loops |= DstLoops;
945   unsigned N = Loops.count();
946   if (N == 0)
947     return Subscript::ZIV;
948   if (N == 1)
949     return Subscript::SIV;
950   if (N == 2 && (SrcLoops.count() == 0 ||
951                  DstLoops.count() == 0 ||
952                  (SrcLoops.count() == 1 && DstLoops.count() == 1)))
953     return Subscript::RDIV;
954   return Subscript::MIV;
955 }
956 
957 
958 // A wrapper around SCEV::isKnownPredicate.
959 // Looks for cases where we're interested in comparing for equality.
960 // If both X and Y have been identically sign or zero extended,
961 // it strips off the (confusing) extensions before invoking
962 // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
963 // will be similarly updated.
964 //
965 // If SCEV::isKnownPredicate can't prove the predicate,
966 // we try simple subtraction, which seems to help in some cases
967 // involving symbolics.
968 bool DependenceInfo::isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *X,
969                                       const SCEV *Y) const {
970   if (Pred == CmpInst::ICMP_EQ ||
971       Pred == CmpInst::ICMP_NE) {
972     if ((isa<SCEVSignExtendExpr>(X) &&
973          isa<SCEVSignExtendExpr>(Y)) ||
974         (isa<SCEVZeroExtendExpr>(X) &&
975          isa<SCEVZeroExtendExpr>(Y))) {
976       const SCEVIntegralCastExpr *CX = cast<SCEVIntegralCastExpr>(X);
977       const SCEVIntegralCastExpr *CY = cast<SCEVIntegralCastExpr>(Y);
978       const SCEV *Xop = CX->getOperand();
979       const SCEV *Yop = CY->getOperand();
980       if (Xop->getType() == Yop->getType()) {
981         X = Xop;
982         Y = Yop;
983       }
984     }
985   }
986   if (SE->isKnownPredicate(Pred, X, Y))
987     return true;
988   // If SE->isKnownPredicate can't prove the condition,
989   // we try the brute-force approach of subtracting
990   // and testing the difference.
991   // By testing with SE->isKnownPredicate first, we avoid
992   // the possibility of overflow when the arguments are constants.
993   const SCEV *Delta = SE->getMinusSCEV(X, Y);
994   switch (Pred) {
995   case CmpInst::ICMP_EQ:
996     return Delta->isZero();
997   case CmpInst::ICMP_NE:
998     return SE->isKnownNonZero(Delta);
999   case CmpInst::ICMP_SGE:
1000     return SE->isKnownNonNegative(Delta);
1001   case CmpInst::ICMP_SLE:
1002     return SE->isKnownNonPositive(Delta);
1003   case CmpInst::ICMP_SGT:
1004     return SE->isKnownPositive(Delta);
1005   case CmpInst::ICMP_SLT:
1006     return SE->isKnownNegative(Delta);
1007   default:
1008     llvm_unreachable("unexpected predicate in isKnownPredicate");
1009   }
1010 }
1011 
1012 /// Compare to see if S is less than Size, using isKnownNegative(S - max(Size, 1))
1013 /// with some extra checking if S is an AddRec and we can prove less-than using
1014 /// the loop bounds.
1015 bool DependenceInfo::isKnownLessThan(const SCEV *S, const SCEV *Size) const {
1016   // First unify to the same type
1017   auto *SType = dyn_cast<IntegerType>(S->getType());
1018   auto *SizeType = dyn_cast<IntegerType>(Size->getType());
1019   if (!SType || !SizeType)
1020     return false;
1021   Type *MaxType =
1022       (SType->getBitWidth() >= SizeType->getBitWidth()) ? SType : SizeType;
1023   S = SE->getTruncateOrZeroExtend(S, MaxType);
1024   Size = SE->getTruncateOrZeroExtend(Size, MaxType);
1025 
1026   // Special check for addrecs using BE taken count
1027   const SCEV *Bound = SE->getMinusSCEV(S, Size);
1028   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Bound)) {
1029     if (AddRec->isAffine()) {
1030       const SCEV *BECount = SE->getBackedgeTakenCount(AddRec->getLoop());
1031       if (!isa<SCEVCouldNotCompute>(BECount)) {
1032         const SCEV *Limit = AddRec->evaluateAtIteration(BECount, *SE);
1033         if (SE->isKnownNegative(Limit))
1034           return true;
1035       }
1036     }
1037   }
1038 
1039   // Check using normal isKnownNegative
1040   const SCEV *LimitedBound =
1041       SE->getMinusSCEV(S, SE->getSMaxExpr(Size, SE->getOne(Size->getType())));
1042   return SE->isKnownNegative(LimitedBound);
1043 }
1044 
1045 bool DependenceInfo::isKnownNonNegative(const SCEV *S, const Value *Ptr) const {
1046   bool Inbounds = false;
1047   if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(Ptr))
1048     Inbounds = SrcGEP->isInBounds();
1049   if (Inbounds) {
1050     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
1051       if (AddRec->isAffine()) {
1052         // We know S is for Ptr, the operand on a load/store, so doesn't wrap.
1053         // If both parts are NonNegative, the end result will be NonNegative
1054         if (SE->isKnownNonNegative(AddRec->getStart()) &&
1055             SE->isKnownNonNegative(AddRec->getOperand(1)))
1056           return true;
1057       }
1058     }
1059   }
1060 
1061   return SE->isKnownNonNegative(S);
1062 }
1063 
1064 // All subscripts are all the same type.
1065 // Loop bound may be smaller (e.g., a char).
1066 // Should zero extend loop bound, since it's always >= 0.
1067 // This routine collects upper bound and extends or truncates if needed.
1068 // Truncating is safe when subscripts are known not to wrap. Cases without
1069 // nowrap flags should have been rejected earlier.
1070 // Return null if no bound available.
1071 const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
1072   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
1073     const SCEV *UB = SE->getBackedgeTakenCount(L);
1074     return SE->getTruncateOrZeroExtend(UB, T);
1075   }
1076   return nullptr;
1077 }
1078 
1079 
1080 // Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
1081 // If the cast fails, returns NULL.
1082 const SCEVConstant *DependenceInfo::collectConstantUpperBound(const Loop *L,
1083                                                               Type *T) const {
1084   if (const SCEV *UB = collectUpperBound(L, T))
1085     return dyn_cast<SCEVConstant>(UB);
1086   return nullptr;
1087 }
1088 
1089 
1090 // testZIV -
1091 // When we have a pair of subscripts of the form [c1] and [c2],
1092 // where c1 and c2 are both loop invariant, we attack it using
1093 // the ZIV test. Basically, we test by comparing the two values,
1094 // but there are actually three possible results:
1095 // 1) the values are equal, so there's a dependence
1096 // 2) the values are different, so there's no dependence
1097 // 3) the values might be equal, so we have to assume a dependence.
1098 //
1099 // Return true if dependence disproved.
1100 bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
1101                              FullDependence &Result) const {
1102   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
1103   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
1104   ++ZIVapplications;
1105   if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
1106     LLVM_DEBUG(dbgs() << "    provably dependent\n");
1107     return false; // provably dependent
1108   }
1109   if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
1110     LLVM_DEBUG(dbgs() << "    provably independent\n");
1111     ++ZIVindependence;
1112     return true; // provably independent
1113   }
1114   LLVM_DEBUG(dbgs() << "    possibly dependent\n");
1115   Result.Consistent = false;
1116   return false; // possibly dependent
1117 }
1118 
1119 
1120 // strongSIVtest -
1121 // From the paper, Practical Dependence Testing, Section 4.2.1
1122 //
1123 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
1124 // where i is an induction variable, c1 and c2 are loop invariant,
1125 //  and a is a constant, we can solve it exactly using the Strong SIV test.
1126 //
1127 // Can prove independence. Failing that, can compute distance (and direction).
1128 // In the presence of symbolic terms, we can sometimes make progress.
1129 //
1130 // If there's a dependence,
1131 //
1132 //    c1 + a*i = c2 + a*i'
1133 //
1134 // The dependence distance is
1135 //
1136 //    d = i' - i = (c1 - c2)/a
1137 //
1138 // A dependence only exists if d is an integer and abs(d) <= U, where U is the
1139 // loop's upper bound. If a dependence exists, the dependence direction is
1140 // defined as
1141 //
1142 //                { < if d > 0
1143 //    direction = { = if d = 0
1144 //                { > if d < 0
1145 //
1146 // Return true if dependence disproved.
1147 bool DependenceInfo::strongSIVtest(const SCEV *Coeff, const SCEV *SrcConst,
1148                                    const SCEV *DstConst, const Loop *CurLoop,
1149                                    unsigned Level, FullDependence &Result,
1150                                    Constraint &NewConstraint) const {
1151   LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
1152   LLVM_DEBUG(dbgs() << "\t    Coeff = " << *Coeff);
1153   LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1154   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst);
1155   LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1156   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst);
1157   LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
1158   ++StrongSIVapplications;
1159   assert(0 < Level && Level <= CommonLevels && "level out of range");
1160   Level--;
1161 
1162   const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1163   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta);
1164   LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
1165 
1166   // check that |Delta| < iteration count
1167   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1168     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound);
1169     LLVM_DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
1170     const SCEV *AbsDelta =
1171       SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
1172     const SCEV *AbsCoeff =
1173       SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
1174     const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
1175     if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
1176       // Distance greater than trip count - no dependence
1177       ++StrongSIVindependence;
1178       ++StrongSIVsuccesses;
1179       return true;
1180     }
1181   }
1182 
1183   // Can we compute distance?
1184   if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
1185     APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
1186     APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
1187     APInt Distance  = ConstDelta; // these need to be initialized
1188     APInt Remainder = ConstDelta;
1189     APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
1190     LLVM_DEBUG(dbgs() << "\t    Distance = " << Distance << "\n");
1191     LLVM_DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
1192     // Make sure Coeff divides Delta exactly
1193     if (Remainder != 0) {
1194       // Coeff doesn't divide Distance, no dependence
1195       ++StrongSIVindependence;
1196       ++StrongSIVsuccesses;
1197       return true;
1198     }
1199     Result.DV[Level].Distance = SE->getConstant(Distance);
1200     NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
1201     if (Distance.sgt(0))
1202       Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1203     else if (Distance.slt(0))
1204       Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1205     else
1206       Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1207     ++StrongSIVsuccesses;
1208   }
1209   else if (Delta->isZero()) {
1210     // since 0/X == 0
1211     Result.DV[Level].Distance = Delta;
1212     NewConstraint.setDistance(Delta, CurLoop);
1213     Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1214     ++StrongSIVsuccesses;
1215   }
1216   else {
1217     if (Coeff->isOne()) {
1218       LLVM_DEBUG(dbgs() << "\t    Distance = " << *Delta << "\n");
1219       Result.DV[Level].Distance = Delta; // since X/1 == X
1220       NewConstraint.setDistance(Delta, CurLoop);
1221     }
1222     else {
1223       Result.Consistent = false;
1224       NewConstraint.setLine(Coeff,
1225                             SE->getNegativeSCEV(Coeff),
1226                             SE->getNegativeSCEV(Delta), CurLoop);
1227     }
1228 
1229     // maybe we can get a useful direction
1230     bool DeltaMaybeZero     = !SE->isKnownNonZero(Delta);
1231     bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1232     bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1233     bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1234     bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1235     // The double negatives above are confusing.
1236     // It helps to read !SE->isKnownNonZero(Delta)
1237     // as "Delta might be Zero"
1238     unsigned NewDirection = Dependence::DVEntry::NONE;
1239     if ((DeltaMaybePositive && CoeffMaybePositive) ||
1240         (DeltaMaybeNegative && CoeffMaybeNegative))
1241       NewDirection = Dependence::DVEntry::LT;
1242     if (DeltaMaybeZero)
1243       NewDirection |= Dependence::DVEntry::EQ;
1244     if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1245         (DeltaMaybePositive && CoeffMaybeNegative))
1246       NewDirection |= Dependence::DVEntry::GT;
1247     if (NewDirection < Result.DV[Level].Direction)
1248       ++StrongSIVsuccesses;
1249     Result.DV[Level].Direction &= NewDirection;
1250   }
1251   return false;
1252 }
1253 
1254 
1255 // weakCrossingSIVtest -
1256 // From the paper, Practical Dependence Testing, Section 4.2.2
1257 //
1258 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1259 // where i is an induction variable, c1 and c2 are loop invariant,
1260 // and a is a constant, we can solve it exactly using the
1261 // Weak-Crossing SIV test.
1262 //
1263 // Given c1 + a*i = c2 - a*i', we can look for the intersection of
1264 // the two lines, where i = i', yielding
1265 //
1266 //    c1 + a*i = c2 - a*i
1267 //    2a*i = c2 - c1
1268 //    i = (c2 - c1)/2a
1269 //
1270 // If i < 0, there is no dependence.
1271 // If i > upperbound, there is no dependence.
1272 // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1273 // If i = upperbound, there's a dependence with distance = 0.
1274 // If i is integral, there's a dependence (all directions).
1275 // If the non-integer part = 1/2, there's a dependence (<> directions).
1276 // Otherwise, there's no dependence.
1277 //
1278 // Can prove independence. Failing that,
1279 // can sometimes refine the directions.
1280 // Can determine iteration for splitting.
1281 //
1282 // Return true if dependence disproved.
1283 bool DependenceInfo::weakCrossingSIVtest(
1284     const SCEV *Coeff, const SCEV *SrcConst, const SCEV *DstConst,
1285     const Loop *CurLoop, unsigned Level, FullDependence &Result,
1286     Constraint &NewConstraint, const SCEV *&SplitIter) const {
1287   LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1288   LLVM_DEBUG(dbgs() << "\t    Coeff = " << *Coeff << "\n");
1289   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1290   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1291   ++WeakCrossingSIVapplications;
1292   assert(0 < Level && Level <= CommonLevels && "Level out of range");
1293   Level--;
1294   Result.Consistent = false;
1295   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1296   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1297   NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
1298   if (Delta->isZero()) {
1299     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1300     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1301     ++WeakCrossingSIVsuccesses;
1302     if (!Result.DV[Level].Direction) {
1303       ++WeakCrossingSIVindependence;
1304       return true;
1305     }
1306     Result.DV[Level].Distance = Delta; // = 0
1307     return false;
1308   }
1309   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1310   if (!ConstCoeff)
1311     return false;
1312 
1313   Result.DV[Level].Splitable = true;
1314   if (SE->isKnownNegative(ConstCoeff)) {
1315     ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1316     assert(ConstCoeff &&
1317            "dynamic cast of negative of ConstCoeff should yield constant");
1318     Delta = SE->getNegativeSCEV(Delta);
1319   }
1320   assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1321 
1322   // compute SplitIter for use by DependenceInfo::getSplitIteration()
1323   SplitIter = SE->getUDivExpr(
1324       SE->getSMaxExpr(SE->getZero(Delta->getType()), Delta),
1325       SE->getMulExpr(SE->getConstant(Delta->getType(), 2), ConstCoeff));
1326   LLVM_DEBUG(dbgs() << "\t    Split iter = " << *SplitIter << "\n");
1327 
1328   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1329   if (!ConstDelta)
1330     return false;
1331 
1332   // We're certain that ConstCoeff > 0; therefore,
1333   // if Delta < 0, then no dependence.
1334   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1335   LLVM_DEBUG(dbgs() << "\t    ConstCoeff = " << *ConstCoeff << "\n");
1336   if (SE->isKnownNegative(Delta)) {
1337     // No dependence, Delta < 0
1338     ++WeakCrossingSIVindependence;
1339     ++WeakCrossingSIVsuccesses;
1340     return true;
1341   }
1342 
1343   // We're certain that Delta > 0 and ConstCoeff > 0.
1344   // Check Delta/(2*ConstCoeff) against upper loop bound
1345   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1346     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
1347     const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1348     const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
1349                                     ConstantTwo);
1350     LLVM_DEBUG(dbgs() << "\t    ML = " << *ML << "\n");
1351     if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1352       // Delta too big, no dependence
1353       ++WeakCrossingSIVindependence;
1354       ++WeakCrossingSIVsuccesses;
1355       return true;
1356     }
1357     if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1358       // i = i' = UB
1359       Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1360       Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1361       ++WeakCrossingSIVsuccesses;
1362       if (!Result.DV[Level].Direction) {
1363         ++WeakCrossingSIVindependence;
1364         return true;
1365       }
1366       Result.DV[Level].Splitable = false;
1367       Result.DV[Level].Distance = SE->getZero(Delta->getType());
1368       return false;
1369     }
1370   }
1371 
1372   // check that Coeff divides Delta
1373   APInt APDelta = ConstDelta->getAPInt();
1374   APInt APCoeff = ConstCoeff->getAPInt();
1375   APInt Distance = APDelta; // these need to be initialzed
1376   APInt Remainder = APDelta;
1377   APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1378   LLVM_DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
1379   if (Remainder != 0) {
1380     // Coeff doesn't divide Delta, no dependence
1381     ++WeakCrossingSIVindependence;
1382     ++WeakCrossingSIVsuccesses;
1383     return true;
1384   }
1385   LLVM_DEBUG(dbgs() << "\t    Distance = " << Distance << "\n");
1386 
1387   // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1388   APInt Two = APInt(Distance.getBitWidth(), 2, true);
1389   Remainder = Distance.srem(Two);
1390   LLVM_DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
1391   if (Remainder != 0) {
1392     // Equal direction isn't possible
1393     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
1394     ++WeakCrossingSIVsuccesses;
1395   }
1396   return false;
1397 }
1398 
1399 
1400 // Kirch's algorithm, from
1401 //
1402 //        Optimizing Supercompilers for Supercomputers
1403 //        Michael Wolfe
1404 //        MIT Press, 1989
1405 //
1406 // Program 2.1, page 29.
1407 // Computes the GCD of AM and BM.
1408 // Also finds a solution to the equation ax - by = gcd(a, b).
1409 // Returns true if dependence disproved; i.e., gcd does not divide Delta.
1410 static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM,
1411                     const APInt &Delta, APInt &G, APInt &X, APInt &Y) {
1412   APInt A0(Bits, 1, true), A1(Bits, 0, true);
1413   APInt B0(Bits, 0, true), B1(Bits, 1, true);
1414   APInt G0 = AM.abs();
1415   APInt G1 = BM.abs();
1416   APInt Q = G0; // these need to be initialized
1417   APInt R = G0;
1418   APInt::sdivrem(G0, G1, Q, R);
1419   while (R != 0) {
1420     APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1421     APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1422     G0 = G1; G1 = R;
1423     APInt::sdivrem(G0, G1, Q, R);
1424   }
1425   G = G1;
1426   LLVM_DEBUG(dbgs() << "\t    GCD = " << G << "\n");
1427   X = AM.slt(0) ? -A1 : A1;
1428   Y = BM.slt(0) ? B1 : -B1;
1429 
1430   // make sure gcd divides Delta
1431   R = Delta.srem(G);
1432   if (R != 0)
1433     return true; // gcd doesn't divide Delta, no dependence
1434   Q = Delta.sdiv(G);
1435   return false;
1436 }
1437 
1438 static APInt floorOfQuotient(const APInt &A, const APInt &B) {
1439   APInt Q = A; // these need to be initialized
1440   APInt R = A;
1441   APInt::sdivrem(A, B, Q, R);
1442   if (R == 0)
1443     return Q;
1444   if ((A.sgt(0) && B.sgt(0)) ||
1445       (A.slt(0) && B.slt(0)))
1446     return Q;
1447   else
1448     return Q - 1;
1449 }
1450 
1451 static APInt ceilingOfQuotient(const APInt &A, const APInt &B) {
1452   APInt Q = A; // these need to be initialized
1453   APInt R = A;
1454   APInt::sdivrem(A, B, Q, R);
1455   if (R == 0)
1456     return Q;
1457   if ((A.sgt(0) && B.sgt(0)) ||
1458       (A.slt(0) && B.slt(0)))
1459     return Q + 1;
1460   else
1461     return Q;
1462 }
1463 
1464 // exactSIVtest -
1465 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1466 // where i is an induction variable, c1 and c2 are loop invariant, and a1
1467 // and a2 are constant, we can solve it exactly using an algorithm developed
1468 // by Banerjee and Wolfe. See Algorithm 6.2.1 (case 2.5) in:
1469 //
1470 //        Dependence Analysis for Supercomputing
1471 //        Utpal Banerjee
1472 //        Kluwer Academic Publishers, 1988
1473 //
1474 // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1475 // so use them if possible. They're also a bit better with symbolics and,
1476 // in the case of the strong SIV test, can compute Distances.
1477 //
1478 // Return true if dependence disproved.
1479 //
1480 // This is a modified version of the original Banerjee algorithm. The original
1481 // only tested whether Dst depends on Src. This algorithm extends that and
1482 // returns all the dependencies that exist between Dst and Src.
1483 bool DependenceInfo::exactSIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1484                                   const SCEV *SrcConst, const SCEV *DstConst,
1485                                   const Loop *CurLoop, unsigned Level,
1486                                   FullDependence &Result,
1487                                   Constraint &NewConstraint) const {
1488   LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
1489   LLVM_DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << " = AM\n");
1490   LLVM_DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << " = BM\n");
1491   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1492   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1493   ++ExactSIVapplications;
1494   assert(0 < Level && Level <= CommonLevels && "Level out of range");
1495   Level--;
1496   Result.Consistent = false;
1497   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1498   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1499   NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff), Delta,
1500                         CurLoop);
1501   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1502   const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1503   const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1504   if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1505     return false;
1506 
1507   // find gcd
1508   APInt G, X, Y;
1509   APInt AM = ConstSrcCoeff->getAPInt();
1510   APInt BM = ConstDstCoeff->getAPInt();
1511   APInt CM = ConstDelta->getAPInt();
1512   unsigned Bits = AM.getBitWidth();
1513   if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
1514     // gcd doesn't divide Delta, no dependence
1515     ++ExactSIVindependence;
1516     ++ExactSIVsuccesses;
1517     return true;
1518   }
1519 
1520   LLVM_DEBUG(dbgs() << "\t    X = " << X << ", Y = " << Y << "\n");
1521 
1522   // since SCEV construction normalizes, LM = 0
1523   APInt UM(Bits, 1, true);
1524   bool UMValid = false;
1525   // UM is perhaps unavailable, let's check
1526   if (const SCEVConstant *CUB =
1527           collectConstantUpperBound(CurLoop, Delta->getType())) {
1528     UM = CUB->getAPInt();
1529     LLVM_DEBUG(dbgs() << "\t    UM = " << UM << "\n");
1530     UMValid = true;
1531   }
1532 
1533   APInt TU(APInt::getSignedMaxValue(Bits));
1534   APInt TL(APInt::getSignedMinValue(Bits));
1535   APInt TC = CM.sdiv(G);
1536   APInt TX = X * TC;
1537   APInt TY = Y * TC;
1538   LLVM_DEBUG(dbgs() << "\t    TC = " << TC << "\n");
1539   LLVM_DEBUG(dbgs() << "\t    TX = " << TX << "\n");
1540   LLVM_DEBUG(dbgs() << "\t    TY = " << TY << "\n");
1541 
1542   SmallVector<APInt, 2> TLVec, TUVec;
1543   APInt TB = BM.sdiv(G);
1544   if (TB.sgt(0)) {
1545     TLVec.push_back(ceilingOfQuotient(-TX, TB));
1546     LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1547     // New bound check - modification to Banerjee's e3 check
1548     if (UMValid) {
1549       TUVec.push_back(floorOfQuotient(UM - TX, TB));
1550       LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1551     }
1552   } else {
1553     TUVec.push_back(floorOfQuotient(-TX, TB));
1554     LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1555     // New bound check - modification to Banerjee's e3 check
1556     if (UMValid) {
1557       TLVec.push_back(ceilingOfQuotient(UM - TX, TB));
1558       LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1559     }
1560   }
1561 
1562   APInt TA = AM.sdiv(G);
1563   if (TA.sgt(0)) {
1564     if (UMValid) {
1565       TUVec.push_back(floorOfQuotient(UM - TY, TA));
1566       LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1567     }
1568     // New bound check - modification to Banerjee's e3 check
1569     TLVec.push_back(ceilingOfQuotient(-TY, TA));
1570     LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1571   } else {
1572     if (UMValid) {
1573       TLVec.push_back(ceilingOfQuotient(UM - TY, TA));
1574       LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1575     }
1576     // New bound check - modification to Banerjee's e3 check
1577     TUVec.push_back(floorOfQuotient(-TY, TA));
1578     LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1579   }
1580 
1581   LLVM_DEBUG(dbgs() << "\t    TA = " << TA << "\n");
1582   LLVM_DEBUG(dbgs() << "\t    TB = " << TB << "\n");
1583 
1584   if (TLVec.empty() || TUVec.empty())
1585     return false;
1586   TL = APIntOps::smax(TLVec.front(), TLVec.back());
1587   TU = APIntOps::smin(TUVec.front(), TUVec.back());
1588   LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1589   LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1590 
1591   if (TL.sgt(TU)) {
1592     ++ExactSIVindependence;
1593     ++ExactSIVsuccesses;
1594     return true;
1595   }
1596 
1597   // explore directions
1598   unsigned NewDirection = Dependence::DVEntry::NONE;
1599   APInt LowerDistance, UpperDistance;
1600   if (TA.sgt(TB)) {
1601     LowerDistance = (TY - TX) + (TA - TB) * TL;
1602     UpperDistance = (TY - TX) + (TA - TB) * TU;
1603   } else {
1604     LowerDistance = (TY - TX) + (TA - TB) * TU;
1605     UpperDistance = (TY - TX) + (TA - TB) * TL;
1606   }
1607 
1608   LLVM_DEBUG(dbgs() << "\t    LowerDistance = " << LowerDistance << "\n");
1609   LLVM_DEBUG(dbgs() << "\t    UpperDistance = " << UpperDistance << "\n");
1610 
1611   APInt Zero(Bits, 0, true);
1612   if (LowerDistance.sle(Zero) && UpperDistance.sge(Zero)) {
1613     NewDirection |= Dependence::DVEntry::EQ;
1614     ++ExactSIVsuccesses;
1615   }
1616   if (LowerDistance.slt(0)) {
1617     NewDirection |= Dependence::DVEntry::GT;
1618     ++ExactSIVsuccesses;
1619   }
1620   if (UpperDistance.sgt(0)) {
1621     NewDirection |= Dependence::DVEntry::LT;
1622     ++ExactSIVsuccesses;
1623   }
1624 
1625   // finished
1626   Result.DV[Level].Direction &= NewDirection;
1627   if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1628     ++ExactSIVindependence;
1629   LLVM_DEBUG(dbgs() << "\t    Result = ");
1630   LLVM_DEBUG(Result.dump(dbgs()));
1631   return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1632 }
1633 
1634 
1635 // Return true if the divisor evenly divides the dividend.
1636 static
1637 bool isRemainderZero(const SCEVConstant *Dividend,
1638                      const SCEVConstant *Divisor) {
1639   const APInt &ConstDividend = Dividend->getAPInt();
1640   const APInt &ConstDivisor = Divisor->getAPInt();
1641   return ConstDividend.srem(ConstDivisor) == 0;
1642 }
1643 
1644 
1645 // weakZeroSrcSIVtest -
1646 // From the paper, Practical Dependence Testing, Section 4.2.2
1647 //
1648 // When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1649 // where i is an induction variable, c1 and c2 are loop invariant,
1650 // and a is a constant, we can solve it exactly using the
1651 // Weak-Zero SIV test.
1652 //
1653 // Given
1654 //
1655 //    c1 = c2 + a*i
1656 //
1657 // we get
1658 //
1659 //    (c1 - c2)/a = i
1660 //
1661 // If i is not an integer, there's no dependence.
1662 // If i < 0 or > UB, there's no dependence.
1663 // If i = 0, the direction is >= and peeling the
1664 // 1st iteration will break the dependence.
1665 // If i = UB, the direction is <= and peeling the
1666 // last iteration will break the dependence.
1667 // Otherwise, the direction is *.
1668 //
1669 // Can prove independence. Failing that, we can sometimes refine
1670 // the directions. Can sometimes show that first or last
1671 // iteration carries all the dependences (so worth peeling).
1672 //
1673 // (see also weakZeroDstSIVtest)
1674 //
1675 // Return true if dependence disproved.
1676 bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1677                                         const SCEV *SrcConst,
1678                                         const SCEV *DstConst,
1679                                         const Loop *CurLoop, unsigned Level,
1680                                         FullDependence &Result,
1681                                         Constraint &NewConstraint) const {
1682   // For the WeakSIV test, it's possible the loop isn't common to
1683   // the Src and Dst loops. If it isn't, then there's no need to
1684   // record a direction.
1685   LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1686   LLVM_DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << "\n");
1687   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1688   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1689   ++WeakZeroSIVapplications;
1690   assert(0 < Level && Level <= MaxLevels && "Level out of range");
1691   Level--;
1692   Result.Consistent = false;
1693   const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1694   NewConstraint.setLine(SE->getZero(Delta->getType()), DstCoeff, Delta,
1695                         CurLoop);
1696   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1697   if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
1698     if (Level < CommonLevels) {
1699       Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1700       Result.DV[Level].PeelFirst = true;
1701       ++WeakZeroSIVsuccesses;
1702     }
1703     return false; // dependences caused by first iteration
1704   }
1705   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1706   if (!ConstCoeff)
1707     return false;
1708   const SCEV *AbsCoeff =
1709     SE->isKnownNegative(ConstCoeff) ?
1710     SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1711   const SCEV *NewDelta =
1712     SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1713 
1714   // check that Delta/SrcCoeff < iteration count
1715   // really check NewDelta < count*AbsCoeff
1716   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1717     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
1718     const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1719     if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1720       ++WeakZeroSIVindependence;
1721       ++WeakZeroSIVsuccesses;
1722       return true;
1723     }
1724     if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1725       // dependences caused by last iteration
1726       if (Level < CommonLevels) {
1727         Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1728         Result.DV[Level].PeelLast = true;
1729         ++WeakZeroSIVsuccesses;
1730       }
1731       return false;
1732     }
1733   }
1734 
1735   // check that Delta/SrcCoeff >= 0
1736   // really check that NewDelta >= 0
1737   if (SE->isKnownNegative(NewDelta)) {
1738     // No dependence, newDelta < 0
1739     ++WeakZeroSIVindependence;
1740     ++WeakZeroSIVsuccesses;
1741     return true;
1742   }
1743 
1744   // if SrcCoeff doesn't divide Delta, then no dependence
1745   if (isa<SCEVConstant>(Delta) &&
1746       !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1747     ++WeakZeroSIVindependence;
1748     ++WeakZeroSIVsuccesses;
1749     return true;
1750   }
1751   return false;
1752 }
1753 
1754 
1755 // weakZeroDstSIVtest -
1756 // From the paper, Practical Dependence Testing, Section 4.2.2
1757 //
1758 // When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1759 // where i is an induction variable, c1 and c2 are loop invariant,
1760 // and a is a constant, we can solve it exactly using the
1761 // Weak-Zero SIV test.
1762 //
1763 // Given
1764 //
1765 //    c1 + a*i = c2
1766 //
1767 // we get
1768 //
1769 //    i = (c2 - c1)/a
1770 //
1771 // If i is not an integer, there's no dependence.
1772 // If i < 0 or > UB, there's no dependence.
1773 // If i = 0, the direction is <= and peeling the
1774 // 1st iteration will break the dependence.
1775 // If i = UB, the direction is >= and peeling the
1776 // last iteration will break the dependence.
1777 // Otherwise, the direction is *.
1778 //
1779 // Can prove independence. Failing that, we can sometimes refine
1780 // the directions. Can sometimes show that first or last
1781 // iteration carries all the dependences (so worth peeling).
1782 //
1783 // (see also weakZeroSrcSIVtest)
1784 //
1785 // Return true if dependence disproved.
1786 bool DependenceInfo::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1787                                         const SCEV *SrcConst,
1788                                         const SCEV *DstConst,
1789                                         const Loop *CurLoop, unsigned Level,
1790                                         FullDependence &Result,
1791                                         Constraint &NewConstraint) const {
1792   // For the WeakSIV test, it's possible the loop isn't common to the
1793   // Src and Dst loops. If it isn't, then there's no need to record a direction.
1794   LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1795   LLVM_DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << "\n");
1796   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1797   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1798   ++WeakZeroSIVapplications;
1799   assert(0 < Level && Level <= SrcLevels && "Level out of range");
1800   Level--;
1801   Result.Consistent = false;
1802   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1803   NewConstraint.setLine(SrcCoeff, SE->getZero(Delta->getType()), Delta,
1804                         CurLoop);
1805   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1806   if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
1807     if (Level < CommonLevels) {
1808       Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1809       Result.DV[Level].PeelFirst = true;
1810       ++WeakZeroSIVsuccesses;
1811     }
1812     return false; // dependences caused by first iteration
1813   }
1814   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1815   if (!ConstCoeff)
1816     return false;
1817   const SCEV *AbsCoeff =
1818     SE->isKnownNegative(ConstCoeff) ?
1819     SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1820   const SCEV *NewDelta =
1821     SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1822 
1823   // check that Delta/SrcCoeff < iteration count
1824   // really check NewDelta < count*AbsCoeff
1825   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1826     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
1827     const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1828     if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1829       ++WeakZeroSIVindependence;
1830       ++WeakZeroSIVsuccesses;
1831       return true;
1832     }
1833     if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1834       // dependences caused by last iteration
1835       if (Level < CommonLevels) {
1836         Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1837         Result.DV[Level].PeelLast = true;
1838         ++WeakZeroSIVsuccesses;
1839       }
1840       return false;
1841     }
1842   }
1843 
1844   // check that Delta/SrcCoeff >= 0
1845   // really check that NewDelta >= 0
1846   if (SE->isKnownNegative(NewDelta)) {
1847     // No dependence, newDelta < 0
1848     ++WeakZeroSIVindependence;
1849     ++WeakZeroSIVsuccesses;
1850     return true;
1851   }
1852 
1853   // if SrcCoeff doesn't divide Delta, then no dependence
1854   if (isa<SCEVConstant>(Delta) &&
1855       !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1856     ++WeakZeroSIVindependence;
1857     ++WeakZeroSIVsuccesses;
1858     return true;
1859   }
1860   return false;
1861 }
1862 
1863 
1864 // exactRDIVtest - Tests the RDIV subscript pair for dependence.
1865 // Things of the form [c1 + a*i] and [c2 + b*j],
1866 // where i and j are induction variable, c1 and c2 are loop invariant,
1867 // and a and b are constants.
1868 // Returns true if any possible dependence is disproved.
1869 // Marks the result as inconsistent.
1870 // Works in some cases that symbolicRDIVtest doesn't, and vice versa.
1871 bool DependenceInfo::exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1872                                    const SCEV *SrcConst, const SCEV *DstConst,
1873                                    const Loop *SrcLoop, const Loop *DstLoop,
1874                                    FullDependence &Result) const {
1875   LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
1876   LLVM_DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << " = AM\n");
1877   LLVM_DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << " = BM\n");
1878   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1879   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1880   ++ExactRDIVapplications;
1881   Result.Consistent = false;
1882   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1883   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1884   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1885   const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1886   const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1887   if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1888     return false;
1889 
1890   // find gcd
1891   APInt G, X, Y;
1892   APInt AM = ConstSrcCoeff->getAPInt();
1893   APInt BM = ConstDstCoeff->getAPInt();
1894   APInt CM = ConstDelta->getAPInt();
1895   unsigned Bits = AM.getBitWidth();
1896   if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
1897     // gcd doesn't divide Delta, no dependence
1898     ++ExactRDIVindependence;
1899     return true;
1900   }
1901 
1902   LLVM_DEBUG(dbgs() << "\t    X = " << X << ", Y = " << Y << "\n");
1903 
1904   // since SCEV construction seems to normalize, LM = 0
1905   APInt SrcUM(Bits, 1, true);
1906   bool SrcUMvalid = false;
1907   // SrcUM is perhaps unavailable, let's check
1908   if (const SCEVConstant *UpperBound =
1909           collectConstantUpperBound(SrcLoop, Delta->getType())) {
1910     SrcUM = UpperBound->getAPInt();
1911     LLVM_DEBUG(dbgs() << "\t    SrcUM = " << SrcUM << "\n");
1912     SrcUMvalid = true;
1913   }
1914 
1915   APInt DstUM(Bits, 1, true);
1916   bool DstUMvalid = false;
1917   // UM is perhaps unavailable, let's check
1918   if (const SCEVConstant *UpperBound =
1919           collectConstantUpperBound(DstLoop, Delta->getType())) {
1920     DstUM = UpperBound->getAPInt();
1921     LLVM_DEBUG(dbgs() << "\t    DstUM = " << DstUM << "\n");
1922     DstUMvalid = true;
1923   }
1924 
1925   APInt TU(APInt::getSignedMaxValue(Bits));
1926   APInt TL(APInt::getSignedMinValue(Bits));
1927   APInt TC = CM.sdiv(G);
1928   APInt TX = X * TC;
1929   APInt TY = Y * TC;
1930   LLVM_DEBUG(dbgs() << "\t    TC = " << TC << "\n");
1931   LLVM_DEBUG(dbgs() << "\t    TX = " << TX << "\n");
1932   LLVM_DEBUG(dbgs() << "\t    TY = " << TY << "\n");
1933 
1934   SmallVector<APInt, 2> TLVec, TUVec;
1935   APInt TB = BM.sdiv(G);
1936   if (TB.sgt(0)) {
1937     TLVec.push_back(ceilingOfQuotient(-TX, TB));
1938     LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1939     if (SrcUMvalid) {
1940       TUVec.push_back(floorOfQuotient(SrcUM - TX, TB));
1941       LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1942     }
1943   } else {
1944     TUVec.push_back(floorOfQuotient(-TX, TB));
1945     LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1946     if (SrcUMvalid) {
1947       TLVec.push_back(ceilingOfQuotient(SrcUM - TX, TB));
1948       LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1949     }
1950   }
1951 
1952   APInt TA = AM.sdiv(G);
1953   if (TA.sgt(0)) {
1954     TLVec.push_back(ceilingOfQuotient(-TY, TA));
1955     LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1956     if (DstUMvalid) {
1957       TUVec.push_back(floorOfQuotient(DstUM - TY, TA));
1958       LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1959     }
1960   } else {
1961     TUVec.push_back(floorOfQuotient(-TY, TA));
1962     LLVM_DEBUG(dbgs() << "\t    Possible TU = " << TUVec.back() << "\n");
1963     if (DstUMvalid) {
1964       TLVec.push_back(ceilingOfQuotient(DstUM - TY, TA));
1965       LLVM_DEBUG(dbgs() << "\t    Possible TL = " << TLVec.back() << "\n");
1966     }
1967   }
1968 
1969   if (TLVec.empty() || TUVec.empty())
1970     return false;
1971 
1972   LLVM_DEBUG(dbgs() << "\t    TA = " << TA << "\n");
1973   LLVM_DEBUG(dbgs() << "\t    TB = " << TB << "\n");
1974 
1975   TL = APIntOps::smax(TLVec.front(), TLVec.back());
1976   TU = APIntOps::smin(TUVec.front(), TUVec.back());
1977   LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1978   LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1979 
1980   if (TL.sgt(TU))
1981     ++ExactRDIVindependence;
1982   return TL.sgt(TU);
1983 }
1984 
1985 
1986 // symbolicRDIVtest -
1987 // In Section 4.5 of the Practical Dependence Testing paper,the authors
1988 // introduce a special case of Banerjee's Inequalities (also called the
1989 // Extreme-Value Test) that can handle some of the SIV and RDIV cases,
1990 // particularly cases with symbolics. Since it's only able to disprove
1991 // dependence (not compute distances or directions), we'll use it as a
1992 // fall back for the other tests.
1993 //
1994 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
1995 // where i and j are induction variables and c1 and c2 are loop invariants,
1996 // we can use the symbolic tests to disprove some dependences, serving as a
1997 // backup for the RDIV test. Note that i and j can be the same variable,
1998 // letting this test serve as a backup for the various SIV tests.
1999 //
2000 // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
2001 //  0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
2002 // loop bounds for the i and j loops, respectively. So, ...
2003 //
2004 // c1 + a1*i = c2 + a2*j
2005 // a1*i - a2*j = c2 - c1
2006 //
2007 // To test for a dependence, we compute c2 - c1 and make sure it's in the
2008 // range of the maximum and minimum possible values of a1*i - a2*j.
2009 // Considering the signs of a1 and a2, we have 4 possible cases:
2010 //
2011 // 1) If a1 >= 0 and a2 >= 0, then
2012 //        a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
2013 //              -a2*N2 <= c2 - c1 <= a1*N1
2014 //
2015 // 2) If a1 >= 0 and a2 <= 0, then
2016 //        a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
2017 //                  0 <= c2 - c1 <= a1*N1 - a2*N2
2018 //
2019 // 3) If a1 <= 0 and a2 >= 0, then
2020 //        a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
2021 //        a1*N1 - a2*N2 <= c2 - c1 <= 0
2022 //
2023 // 4) If a1 <= 0 and a2 <= 0, then
2024 //        a1*N1 - a2*0  <= c2 - c1 <= a1*0 - a2*N2
2025 //        a1*N1         <= c2 - c1 <=       -a2*N2
2026 //
2027 // return true if dependence disproved
2028 bool DependenceInfo::symbolicRDIVtest(const SCEV *A1, const SCEV *A2,
2029                                       const SCEV *C1, const SCEV *C2,
2030                                       const Loop *Loop1,
2031                                       const Loop *Loop2) const {
2032   ++SymbolicRDIVapplications;
2033   LLVM_DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
2034   LLVM_DEBUG(dbgs() << "\t    A1 = " << *A1);
2035   LLVM_DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
2036   LLVM_DEBUG(dbgs() << "\t    A2 = " << *A2 << "\n");
2037   LLVM_DEBUG(dbgs() << "\t    C1 = " << *C1 << "\n");
2038   LLVM_DEBUG(dbgs() << "\t    C2 = " << *C2 << "\n");
2039   const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
2040   const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
2041   LLVM_DEBUG(if (N1) dbgs() << "\t    N1 = " << *N1 << "\n");
2042   LLVM_DEBUG(if (N2) dbgs() << "\t    N2 = " << *N2 << "\n");
2043   const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
2044   const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
2045   LLVM_DEBUG(dbgs() << "\t    C2 - C1 = " << *C2_C1 << "\n");
2046   LLVM_DEBUG(dbgs() << "\t    C1 - C2 = " << *C1_C2 << "\n");
2047   if (SE->isKnownNonNegative(A1)) {
2048     if (SE->isKnownNonNegative(A2)) {
2049       // A1 >= 0 && A2 >= 0
2050       if (N1) {
2051         // make sure that c2 - c1 <= a1*N1
2052         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2053         LLVM_DEBUG(dbgs() << "\t    A1*N1 = " << *A1N1 << "\n");
2054         if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
2055           ++SymbolicRDIVindependence;
2056           return true;
2057         }
2058       }
2059       if (N2) {
2060         // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
2061         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2062         LLVM_DEBUG(dbgs() << "\t    A2*N2 = " << *A2N2 << "\n");
2063         if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
2064           ++SymbolicRDIVindependence;
2065           return true;
2066         }
2067       }
2068     }
2069     else if (SE->isKnownNonPositive(A2)) {
2070       // a1 >= 0 && a2 <= 0
2071       if (N1 && N2) {
2072         // make sure that c2 - c1 <= a1*N1 - a2*N2
2073         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2074         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2075         const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2076         LLVM_DEBUG(dbgs() << "\t    A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2077         if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
2078           ++SymbolicRDIVindependence;
2079           return true;
2080         }
2081       }
2082       // make sure that 0 <= c2 - c1
2083       if (SE->isKnownNegative(C2_C1)) {
2084         ++SymbolicRDIVindependence;
2085         return true;
2086       }
2087     }
2088   }
2089   else if (SE->isKnownNonPositive(A1)) {
2090     if (SE->isKnownNonNegative(A2)) {
2091       // a1 <= 0 && a2 >= 0
2092       if (N1 && N2) {
2093         // make sure that a1*N1 - a2*N2 <= c2 - c1
2094         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2095         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2096         const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2097         LLVM_DEBUG(dbgs() << "\t    A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2098         if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
2099           ++SymbolicRDIVindependence;
2100           return true;
2101         }
2102       }
2103       // make sure that c2 - c1 <= 0
2104       if (SE->isKnownPositive(C2_C1)) {
2105         ++SymbolicRDIVindependence;
2106         return true;
2107       }
2108     }
2109     else if (SE->isKnownNonPositive(A2)) {
2110       // a1 <= 0 && a2 <= 0
2111       if (N1) {
2112         // make sure that a1*N1 <= c2 - c1
2113         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2114         LLVM_DEBUG(dbgs() << "\t    A1*N1 = " << *A1N1 << "\n");
2115         if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2116           ++SymbolicRDIVindependence;
2117           return true;
2118         }
2119       }
2120       if (N2) {
2121         // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2122         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2123         LLVM_DEBUG(dbgs() << "\t    A2*N2 = " << *A2N2 << "\n");
2124         if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2125           ++SymbolicRDIVindependence;
2126           return true;
2127         }
2128       }
2129     }
2130   }
2131   return false;
2132 }
2133 
2134 
2135 // testSIV -
2136 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2137 // where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2138 // a2 are constant, we attack it with an SIV test. While they can all be
2139 // solved with the Exact SIV test, it's worthwhile to use simpler tests when
2140 // they apply; they're cheaper and sometimes more precise.
2141 //
2142 // Return true if dependence disproved.
2143 bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
2144                              FullDependence &Result, Constraint &NewConstraint,
2145                              const SCEV *&SplitIter) const {
2146   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
2147   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
2148   const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2149   const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2150   if (SrcAddRec && DstAddRec) {
2151     const SCEV *SrcConst = SrcAddRec->getStart();
2152     const SCEV *DstConst = DstAddRec->getStart();
2153     const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2154     const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2155     const Loop *CurLoop = SrcAddRec->getLoop();
2156     assert(CurLoop == DstAddRec->getLoop() &&
2157            "both loops in SIV should be same");
2158     Level = mapSrcLoop(CurLoop);
2159     bool disproven;
2160     if (SrcCoeff == DstCoeff)
2161       disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2162                                 Level, Result, NewConstraint);
2163     else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2164       disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2165                                       Level, Result, NewConstraint, SplitIter);
2166     else
2167       disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
2168                                Level, Result, NewConstraint);
2169     return disproven ||
2170       gcdMIVtest(Src, Dst, Result) ||
2171       symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
2172   }
2173   if (SrcAddRec) {
2174     const SCEV *SrcConst = SrcAddRec->getStart();
2175     const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2176     const SCEV *DstConst = Dst;
2177     const Loop *CurLoop = SrcAddRec->getLoop();
2178     Level = mapSrcLoop(CurLoop);
2179     return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2180                               Level, Result, NewConstraint) ||
2181       gcdMIVtest(Src, Dst, Result);
2182   }
2183   if (DstAddRec) {
2184     const SCEV *DstConst = DstAddRec->getStart();
2185     const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2186     const SCEV *SrcConst = Src;
2187     const Loop *CurLoop = DstAddRec->getLoop();
2188     Level = mapDstLoop(CurLoop);
2189     return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
2190                               CurLoop, Level, Result, NewConstraint) ||
2191       gcdMIVtest(Src, Dst, Result);
2192   }
2193   llvm_unreachable("SIV test expected at least one AddRec");
2194   return false;
2195 }
2196 
2197 
2198 // testRDIV -
2199 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2200 // where i and j are induction variables, c1 and c2 are loop invariant,
2201 // and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2202 // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2203 // It doesn't make sense to talk about distance or direction in this case,
2204 // so there's no point in making special versions of the Strong SIV test or
2205 // the Weak-crossing SIV test.
2206 //
2207 // With minor algebra, this test can also be used for things like
2208 // [c1 + a1*i + a2*j][c2].
2209 //
2210 // Return true if dependence disproved.
2211 bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
2212                               FullDependence &Result) const {
2213   // we have 3 possible situations here:
2214   //   1) [a*i + b] and [c*j + d]
2215   //   2) [a*i + c*j + b] and [d]
2216   //   3) [b] and [a*i + c*j + d]
2217   // We need to find what we've got and get organized
2218 
2219   const SCEV *SrcConst, *DstConst;
2220   const SCEV *SrcCoeff, *DstCoeff;
2221   const Loop *SrcLoop, *DstLoop;
2222 
2223   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
2224   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
2225   const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2226   const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2227   if (SrcAddRec && DstAddRec) {
2228     SrcConst = SrcAddRec->getStart();
2229     SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2230     SrcLoop = SrcAddRec->getLoop();
2231     DstConst = DstAddRec->getStart();
2232     DstCoeff = DstAddRec->getStepRecurrence(*SE);
2233     DstLoop = DstAddRec->getLoop();
2234   }
2235   else if (SrcAddRec) {
2236     if (const SCEVAddRecExpr *tmpAddRec =
2237         dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
2238       SrcConst = tmpAddRec->getStart();
2239       SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
2240       SrcLoop = tmpAddRec->getLoop();
2241       DstConst = Dst;
2242       DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
2243       DstLoop = SrcAddRec->getLoop();
2244     }
2245     else
2246       llvm_unreachable("RDIV reached by surprising SCEVs");
2247   }
2248   else if (DstAddRec) {
2249     if (const SCEVAddRecExpr *tmpAddRec =
2250         dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
2251       DstConst = tmpAddRec->getStart();
2252       DstCoeff = tmpAddRec->getStepRecurrence(*SE);
2253       DstLoop = tmpAddRec->getLoop();
2254       SrcConst = Src;
2255       SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
2256       SrcLoop = DstAddRec->getLoop();
2257     }
2258     else
2259       llvm_unreachable("RDIV reached by surprising SCEVs");
2260   }
2261   else
2262     llvm_unreachable("RDIV expected at least one AddRec");
2263   return exactRDIVtest(SrcCoeff, DstCoeff,
2264                        SrcConst, DstConst,
2265                        SrcLoop, DstLoop,
2266                        Result) ||
2267     gcdMIVtest(Src, Dst, Result) ||
2268     symbolicRDIVtest(SrcCoeff, DstCoeff,
2269                      SrcConst, DstConst,
2270                      SrcLoop, DstLoop);
2271 }
2272 
2273 
2274 // Tests the single-subscript MIV pair (Src and Dst) for dependence.
2275 // Return true if dependence disproved.
2276 // Can sometimes refine direction vectors.
2277 bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
2278                              const SmallBitVector &Loops,
2279                              FullDependence &Result) const {
2280   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
2281   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
2282   Result.Consistent = false;
2283   return gcdMIVtest(Src, Dst, Result) ||
2284     banerjeeMIVtest(Src, Dst, Loops, Result);
2285 }
2286 
2287 
2288 // Given a product, e.g., 10*X*Y, returns the first constant operand,
2289 // in this case 10. If there is no constant part, returns NULL.
2290 static
2291 const SCEVConstant *getConstantPart(const SCEV *Expr) {
2292   if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
2293     return Constant;
2294   else if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
2295     if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
2296       return Constant;
2297   return nullptr;
2298 }
2299 
2300 
2301 //===----------------------------------------------------------------------===//
2302 // gcdMIVtest -
2303 // Tests an MIV subscript pair for dependence.
2304 // Returns true if any possible dependence is disproved.
2305 // Marks the result as inconsistent.
2306 // Can sometimes disprove the equal direction for 1 or more loops,
2307 // as discussed in Michael Wolfe's book,
2308 // High Performance Compilers for Parallel Computing, page 235.
2309 //
2310 // We spend some effort (code!) to handle cases like
2311 // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2312 // but M and N are just loop-invariant variables.
2313 // This should help us handle linearized subscripts;
2314 // also makes this test a useful backup to the various SIV tests.
2315 //
2316 // It occurs to me that the presence of loop-invariant variables
2317 // changes the nature of the test from "greatest common divisor"
2318 // to "a common divisor".
2319 bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
2320                                 FullDependence &Result) const {
2321   LLVM_DEBUG(dbgs() << "starting gcd\n");
2322   ++GCDapplications;
2323   unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
2324   APInt RunningGCD = APInt::getZero(BitWidth);
2325 
2326   // Examine Src coefficients.
2327   // Compute running GCD and record source constant.
2328   // Because we're looking for the constant at the end of the chain,
2329   // we can't quit the loop just because the GCD == 1.
2330   const SCEV *Coefficients = Src;
2331   while (const SCEVAddRecExpr *AddRec =
2332          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2333     const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2334     // If the coefficient is the product of a constant and other stuff,
2335     // we can use the constant in the GCD computation.
2336     const auto *Constant = getConstantPart(Coeff);
2337     if (!Constant)
2338       return false;
2339     APInt ConstCoeff = Constant->getAPInt();
2340     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2341     Coefficients = AddRec->getStart();
2342   }
2343   const SCEV *SrcConst = Coefficients;
2344 
2345   // Examine Dst coefficients.
2346   // Compute running GCD and record destination constant.
2347   // Because we're looking for the constant at the end of the chain,
2348   // we can't quit the loop just because the GCD == 1.
2349   Coefficients = Dst;
2350   while (const SCEVAddRecExpr *AddRec =
2351          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2352     const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2353     // If the coefficient is the product of a constant and other stuff,
2354     // we can use the constant in the GCD computation.
2355     const auto *Constant = getConstantPart(Coeff);
2356     if (!Constant)
2357       return false;
2358     APInt ConstCoeff = Constant->getAPInt();
2359     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2360     Coefficients = AddRec->getStart();
2361   }
2362   const SCEV *DstConst = Coefficients;
2363 
2364   APInt ExtraGCD = APInt::getZero(BitWidth);
2365   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
2366   LLVM_DEBUG(dbgs() << "    Delta = " << *Delta << "\n");
2367   const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2368   if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
2369     // If Delta is a sum of products, we may be able to make further progress.
2370     for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
2371       const SCEV *Operand = Sum->getOperand(Op);
2372       if (isa<SCEVConstant>(Operand)) {
2373         assert(!Constant && "Surprised to find multiple constants");
2374         Constant = cast<SCEVConstant>(Operand);
2375       }
2376       else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
2377         // Search for constant operand to participate in GCD;
2378         // If none found; return false.
2379         const SCEVConstant *ConstOp = getConstantPart(Product);
2380         if (!ConstOp)
2381           return false;
2382         APInt ConstOpValue = ConstOp->getAPInt();
2383         ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
2384                                                    ConstOpValue.abs());
2385       }
2386       else
2387         return false;
2388     }
2389   }
2390   if (!Constant)
2391     return false;
2392   APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
2393   LLVM_DEBUG(dbgs() << "    ConstDelta = " << ConstDelta << "\n");
2394   if (ConstDelta == 0)
2395     return false;
2396   RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
2397   LLVM_DEBUG(dbgs() << "    RunningGCD = " << RunningGCD << "\n");
2398   APInt Remainder = ConstDelta.srem(RunningGCD);
2399   if (Remainder != 0) {
2400     ++GCDindependence;
2401     return true;
2402   }
2403 
2404   // Try to disprove equal directions.
2405   // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2406   // the code above can't disprove the dependence because the GCD = 1.
2407   // So we consider what happen if i = i' and what happens if j = j'.
2408   // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2409   // which is infeasible, so we can disallow the = direction for the i level.
2410   // Setting j = j' doesn't help matters, so we end up with a direction vector
2411   // of [<>, *]
2412   //
2413   // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2414   // we need to remember that the constant part is 5 and the RunningGCD should
2415   // be initialized to ExtraGCD = 30.
2416   LLVM_DEBUG(dbgs() << "    ExtraGCD = " << ExtraGCD << '\n');
2417 
2418   bool Improved = false;
2419   Coefficients = Src;
2420   while (const SCEVAddRecExpr *AddRec =
2421          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2422     Coefficients = AddRec->getStart();
2423     const Loop *CurLoop = AddRec->getLoop();
2424     RunningGCD = ExtraGCD;
2425     const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2426     const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2427     const SCEV *Inner = Src;
2428     while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2429       AddRec = cast<SCEVAddRecExpr>(Inner);
2430       const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2431       if (CurLoop == AddRec->getLoop())
2432         ; // SrcCoeff == Coeff
2433       else {
2434         // If the coefficient is the product of a constant and other stuff,
2435         // we can use the constant in the GCD computation.
2436         Constant = getConstantPart(Coeff);
2437         if (!Constant)
2438           return false;
2439         APInt ConstCoeff = Constant->getAPInt();
2440         RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2441       }
2442       Inner = AddRec->getStart();
2443     }
2444     Inner = Dst;
2445     while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2446       AddRec = cast<SCEVAddRecExpr>(Inner);
2447       const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2448       if (CurLoop == AddRec->getLoop())
2449         DstCoeff = Coeff;
2450       else {
2451         // If the coefficient is the product of a constant and other stuff,
2452         // we can use the constant in the GCD computation.
2453         Constant = getConstantPart(Coeff);
2454         if (!Constant)
2455           return false;
2456         APInt ConstCoeff = Constant->getAPInt();
2457         RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2458       }
2459       Inner = AddRec->getStart();
2460     }
2461     Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
2462     // If the coefficient is the product of a constant and other stuff,
2463     // we can use the constant in the GCD computation.
2464     Constant = getConstantPart(Delta);
2465     if (!Constant)
2466       // The difference of the two coefficients might not be a product
2467       // or constant, in which case we give up on this direction.
2468       continue;
2469     APInt ConstCoeff = Constant->getAPInt();
2470     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2471     LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
2472     if (RunningGCD != 0) {
2473       Remainder = ConstDelta.srem(RunningGCD);
2474       LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
2475       if (Remainder != 0) {
2476         unsigned Level = mapSrcLoop(CurLoop);
2477         Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
2478         Improved = true;
2479       }
2480     }
2481   }
2482   if (Improved)
2483     ++GCDsuccesses;
2484   LLVM_DEBUG(dbgs() << "all done\n");
2485   return false;
2486 }
2487 
2488 
2489 //===----------------------------------------------------------------------===//
2490 // banerjeeMIVtest -
2491 // Use Banerjee's Inequalities to test an MIV subscript pair.
2492 // (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2493 // Generally follows the discussion in Section 2.5.2 of
2494 //
2495 //    Optimizing Supercompilers for Supercomputers
2496 //    Michael Wolfe
2497 //
2498 // The inequalities given on page 25 are simplified in that loops are
2499 // normalized so that the lower bound is always 0 and the stride is always 1.
2500 // For example, Wolfe gives
2501 //
2502 //     LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2503 //
2504 // where A_k is the coefficient of the kth index in the source subscript,
2505 // B_k is the coefficient of the kth index in the destination subscript,
2506 // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2507 // index, and N_k is the stride of the kth index. Since all loops are normalized
2508 // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2509 // equation to
2510 //
2511 //     LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2512 //            = (A^-_k - B_k)^- (U_k - 1)  - B_k
2513 //
2514 // Similar simplifications are possible for the other equations.
2515 //
2516 // When we can't determine the number of iterations for a loop,
2517 // we use NULL as an indicator for the worst case, infinity.
2518 // When computing the upper bound, NULL denotes +inf;
2519 // for the lower bound, NULL denotes -inf.
2520 //
2521 // Return true if dependence disproved.
2522 bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
2523                                      const SmallBitVector &Loops,
2524                                      FullDependence &Result) const {
2525   LLVM_DEBUG(dbgs() << "starting Banerjee\n");
2526   ++BanerjeeApplications;
2527   LLVM_DEBUG(dbgs() << "    Src = " << *Src << '\n');
2528   const SCEV *A0;
2529   CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
2530   LLVM_DEBUG(dbgs() << "    Dst = " << *Dst << '\n');
2531   const SCEV *B0;
2532   CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2533   BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
2534   const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2535   LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2536 
2537   // Compute bounds for all the * directions.
2538   LLVM_DEBUG(dbgs() << "\tBounds[*]\n");
2539   for (unsigned K = 1; K <= MaxLevels; ++K) {
2540     Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2541     Bound[K].Direction = Dependence::DVEntry::ALL;
2542     Bound[K].DirSet = Dependence::DVEntry::NONE;
2543     findBoundsALL(A, B, Bound, K);
2544 #ifndef NDEBUG
2545     LLVM_DEBUG(dbgs() << "\t    " << K << '\t');
2546     if (Bound[K].Lower[Dependence::DVEntry::ALL])
2547       LLVM_DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
2548     else
2549       LLVM_DEBUG(dbgs() << "-inf\t");
2550     if (Bound[K].Upper[Dependence::DVEntry::ALL])
2551       LLVM_DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
2552     else
2553       LLVM_DEBUG(dbgs() << "+inf\n");
2554 #endif
2555   }
2556 
2557   // Test the *, *, *, ... case.
2558   bool Disproved = false;
2559   if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2560     // Explore the direction vector hierarchy.
2561     unsigned DepthExpanded = 0;
2562     unsigned NewDeps = exploreDirections(1, A, B, Bound,
2563                                          Loops, DepthExpanded, Delta);
2564     if (NewDeps > 0) {
2565       bool Improved = false;
2566       for (unsigned K = 1; K <= CommonLevels; ++K) {
2567         if (Loops[K]) {
2568           unsigned Old = Result.DV[K - 1].Direction;
2569           Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2570           Improved |= Old != Result.DV[K - 1].Direction;
2571           if (!Result.DV[K - 1].Direction) {
2572             Improved = false;
2573             Disproved = true;
2574             break;
2575           }
2576         }
2577       }
2578       if (Improved)
2579         ++BanerjeeSuccesses;
2580     }
2581     else {
2582       ++BanerjeeIndependence;
2583       Disproved = true;
2584     }
2585   }
2586   else {
2587     ++BanerjeeIndependence;
2588     Disproved = true;
2589   }
2590   delete [] Bound;
2591   delete [] A;
2592   delete [] B;
2593   return Disproved;
2594 }
2595 
2596 
2597 // Hierarchically expands the direction vector
2598 // search space, combining the directions of discovered dependences
2599 // in the DirSet field of Bound. Returns the number of distinct
2600 // dependences discovered. If the dependence is disproved,
2601 // it will return 0.
2602 unsigned DependenceInfo::exploreDirections(unsigned Level, CoefficientInfo *A,
2603                                            CoefficientInfo *B, BoundInfo *Bound,
2604                                            const SmallBitVector &Loops,
2605                                            unsigned &DepthExpanded,
2606                                            const SCEV *Delta) const {
2607   // This algorithm has worst case complexity of O(3^n), where 'n' is the number
2608   // of common loop levels. To avoid excessive compile-time, pessimize all the
2609   // results and immediately return when the number of common levels is beyond
2610   // the given threshold.
2611   if (CommonLevels > MIVMaxLevelThreshold) {
2612     LLVM_DEBUG(dbgs() << "Number of common levels exceeded the threshold. MIV "
2613                          "direction exploration is terminated.\n");
2614     for (unsigned K = 1; K <= CommonLevels; ++K)
2615       if (Loops[K])
2616         Bound[K].DirSet = Dependence::DVEntry::ALL;
2617     return 1;
2618   }
2619 
2620   if (Level > CommonLevels) {
2621     // record result
2622     LLVM_DEBUG(dbgs() << "\t[");
2623     for (unsigned K = 1; K <= CommonLevels; ++K) {
2624       if (Loops[K]) {
2625         Bound[K].DirSet |= Bound[K].Direction;
2626 #ifndef NDEBUG
2627         switch (Bound[K].Direction) {
2628         case Dependence::DVEntry::LT:
2629           LLVM_DEBUG(dbgs() << " <");
2630           break;
2631         case Dependence::DVEntry::EQ:
2632           LLVM_DEBUG(dbgs() << " =");
2633           break;
2634         case Dependence::DVEntry::GT:
2635           LLVM_DEBUG(dbgs() << " >");
2636           break;
2637         case Dependence::DVEntry::ALL:
2638           LLVM_DEBUG(dbgs() << " *");
2639           break;
2640         default:
2641           llvm_unreachable("unexpected Bound[K].Direction");
2642         }
2643 #endif
2644       }
2645     }
2646     LLVM_DEBUG(dbgs() << " ]\n");
2647     return 1;
2648   }
2649   if (Loops[Level]) {
2650     if (Level > DepthExpanded) {
2651       DepthExpanded = Level;
2652       // compute bounds for <, =, > at current level
2653       findBoundsLT(A, B, Bound, Level);
2654       findBoundsGT(A, B, Bound, Level);
2655       findBoundsEQ(A, B, Bound, Level);
2656 #ifndef NDEBUG
2657       LLVM_DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2658       LLVM_DEBUG(dbgs() << "\t    <\t");
2659       if (Bound[Level].Lower[Dependence::DVEntry::LT])
2660         LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT]
2661                           << '\t');
2662       else
2663         LLVM_DEBUG(dbgs() << "-inf\t");
2664       if (Bound[Level].Upper[Dependence::DVEntry::LT])
2665         LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT]
2666                           << '\n');
2667       else
2668         LLVM_DEBUG(dbgs() << "+inf\n");
2669       LLVM_DEBUG(dbgs() << "\t    =\t");
2670       if (Bound[Level].Lower[Dependence::DVEntry::EQ])
2671         LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ]
2672                           << '\t');
2673       else
2674         LLVM_DEBUG(dbgs() << "-inf\t");
2675       if (Bound[Level].Upper[Dependence::DVEntry::EQ])
2676         LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ]
2677                           << '\n');
2678       else
2679         LLVM_DEBUG(dbgs() << "+inf\n");
2680       LLVM_DEBUG(dbgs() << "\t    >\t");
2681       if (Bound[Level].Lower[Dependence::DVEntry::GT])
2682         LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT]
2683                           << '\t');
2684       else
2685         LLVM_DEBUG(dbgs() << "-inf\t");
2686       if (Bound[Level].Upper[Dependence::DVEntry::GT])
2687         LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT]
2688                           << '\n');
2689       else
2690         LLVM_DEBUG(dbgs() << "+inf\n");
2691 #endif
2692     }
2693 
2694     unsigned NewDeps = 0;
2695 
2696     // test bounds for <, *, *, ...
2697     if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2698       NewDeps += exploreDirections(Level + 1, A, B, Bound,
2699                                    Loops, DepthExpanded, Delta);
2700 
2701     // Test bounds for =, *, *, ...
2702     if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2703       NewDeps += exploreDirections(Level + 1, A, B, Bound,
2704                                    Loops, DepthExpanded, Delta);
2705 
2706     // test bounds for >, *, *, ...
2707     if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2708       NewDeps += exploreDirections(Level + 1, A, B, Bound,
2709                                    Loops, DepthExpanded, Delta);
2710 
2711     Bound[Level].Direction = Dependence::DVEntry::ALL;
2712     return NewDeps;
2713   }
2714   else
2715     return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
2716 }
2717 
2718 
2719 // Returns true iff the current bounds are plausible.
2720 bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
2721                                 BoundInfo *Bound, const SCEV *Delta) const {
2722   Bound[Level].Direction = DirKind;
2723   if (const SCEV *LowerBound = getLowerBound(Bound))
2724     if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2725       return false;
2726   if (const SCEV *UpperBound = getUpperBound(Bound))
2727     if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2728       return false;
2729   return true;
2730 }
2731 
2732 
2733 // Computes the upper and lower bounds for level K
2734 // using the * direction. Records them in Bound.
2735 // Wolfe gives the equations
2736 //
2737 //    LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2738 //    UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2739 //
2740 // Since we normalize loops, we can simplify these equations to
2741 //
2742 //    LB^*_k = (A^-_k - B^+_k)U_k
2743 //    UB^*_k = (A^+_k - B^-_k)U_k
2744 //
2745 // We must be careful to handle the case where the upper bound is unknown.
2746 // Note that the lower bound is always <= 0
2747 // and the upper bound is always >= 0.
2748 void DependenceInfo::findBoundsALL(CoefficientInfo *A, CoefficientInfo *B,
2749                                    BoundInfo *Bound, unsigned K) const {
2750   Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
2751   Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
2752   if (Bound[K].Iterations) {
2753     Bound[K].Lower[Dependence::DVEntry::ALL] =
2754       SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
2755                      Bound[K].Iterations);
2756     Bound[K].Upper[Dependence::DVEntry::ALL] =
2757       SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
2758                      Bound[K].Iterations);
2759   }
2760   else {
2761     // If the difference is 0, we won't need to know the number of iterations.
2762     if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2763       Bound[K].Lower[Dependence::DVEntry::ALL] =
2764           SE->getZero(A[K].Coeff->getType());
2765     if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2766       Bound[K].Upper[Dependence::DVEntry::ALL] =
2767           SE->getZero(A[K].Coeff->getType());
2768   }
2769 }
2770 
2771 
2772 // Computes the upper and lower bounds for level K
2773 // using the = direction. Records them in Bound.
2774 // Wolfe gives the equations
2775 //
2776 //    LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2777 //    UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2778 //
2779 // Since we normalize loops, we can simplify these equations to
2780 //
2781 //    LB^=_k = (A_k - B_k)^- U_k
2782 //    UB^=_k = (A_k - B_k)^+ U_k
2783 //
2784 // We must be careful to handle the case where the upper bound is unknown.
2785 // Note that the lower bound is always <= 0
2786 // and the upper bound is always >= 0.
2787 void DependenceInfo::findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B,
2788                                   BoundInfo *Bound, unsigned K) const {
2789   Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
2790   Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
2791   if (Bound[K].Iterations) {
2792     const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2793     const SCEV *NegativePart = getNegativePart(Delta);
2794     Bound[K].Lower[Dependence::DVEntry::EQ] =
2795       SE->getMulExpr(NegativePart, Bound[K].Iterations);
2796     const SCEV *PositivePart = getPositivePart(Delta);
2797     Bound[K].Upper[Dependence::DVEntry::EQ] =
2798       SE->getMulExpr(PositivePart, Bound[K].Iterations);
2799   }
2800   else {
2801     // If the positive/negative part of the difference is 0,
2802     // we won't need to know the number of iterations.
2803     const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2804     const SCEV *NegativePart = getNegativePart(Delta);
2805     if (NegativePart->isZero())
2806       Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2807     const SCEV *PositivePart = getPositivePart(Delta);
2808     if (PositivePart->isZero())
2809       Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2810   }
2811 }
2812 
2813 
2814 // Computes the upper and lower bounds for level K
2815 // using the < direction. Records them in Bound.
2816 // Wolfe gives the equations
2817 //
2818 //    LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2819 //    UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2820 //
2821 // Since we normalize loops, we can simplify these equations to
2822 //
2823 //    LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2824 //    UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2825 //
2826 // We must be careful to handle the case where the upper bound is unknown.
2827 void DependenceInfo::findBoundsLT(CoefficientInfo *A, CoefficientInfo *B,
2828                                   BoundInfo *Bound, unsigned K) const {
2829   Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
2830   Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
2831   if (Bound[K].Iterations) {
2832     const SCEV *Iter_1 = SE->getMinusSCEV(
2833         Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2834     const SCEV *NegPart =
2835       getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2836     Bound[K].Lower[Dependence::DVEntry::LT] =
2837       SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2838     const SCEV *PosPart =
2839       getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2840     Bound[K].Upper[Dependence::DVEntry::LT] =
2841       SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2842   }
2843   else {
2844     // If the positive/negative part of the difference is 0,
2845     // we won't need to know the number of iterations.
2846     const SCEV *NegPart =
2847       getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2848     if (NegPart->isZero())
2849       Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2850     const SCEV *PosPart =
2851       getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2852     if (PosPart->isZero())
2853       Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2854   }
2855 }
2856 
2857 
2858 // Computes the upper and lower bounds for level K
2859 // using the > direction. Records them in Bound.
2860 // Wolfe gives the equations
2861 //
2862 //    LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2863 //    UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2864 //
2865 // Since we normalize loops, we can simplify these equations to
2866 //
2867 //    LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2868 //    UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2869 //
2870 // We must be careful to handle the case where the upper bound is unknown.
2871 void DependenceInfo::findBoundsGT(CoefficientInfo *A, CoefficientInfo *B,
2872                                   BoundInfo *Bound, unsigned K) const {
2873   Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
2874   Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
2875   if (Bound[K].Iterations) {
2876     const SCEV *Iter_1 = SE->getMinusSCEV(
2877         Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2878     const SCEV *NegPart =
2879       getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2880     Bound[K].Lower[Dependence::DVEntry::GT] =
2881       SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2882     const SCEV *PosPart =
2883       getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2884     Bound[K].Upper[Dependence::DVEntry::GT] =
2885       SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2886   }
2887   else {
2888     // If the positive/negative part of the difference is 0,
2889     // we won't need to know the number of iterations.
2890     const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2891     if (NegPart->isZero())
2892       Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2893     const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2894     if (PosPart->isZero())
2895       Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2896   }
2897 }
2898 
2899 
2900 // X^+ = max(X, 0)
2901 const SCEV *DependenceInfo::getPositivePart(const SCEV *X) const {
2902   return SE->getSMaxExpr(X, SE->getZero(X->getType()));
2903 }
2904 
2905 
2906 // X^- = min(X, 0)
2907 const SCEV *DependenceInfo::getNegativePart(const SCEV *X) const {
2908   return SE->getSMinExpr(X, SE->getZero(X->getType()));
2909 }
2910 
2911 
2912 // Walks through the subscript,
2913 // collecting each coefficient, the associated loop bounds,
2914 // and recording its positive and negative parts for later use.
2915 DependenceInfo::CoefficientInfo *
2916 DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
2917                                  const SCEV *&Constant) const {
2918   const SCEV *Zero = SE->getZero(Subscript->getType());
2919   CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
2920   for (unsigned K = 1; K <= MaxLevels; ++K) {
2921     CI[K].Coeff = Zero;
2922     CI[K].PosPart = Zero;
2923     CI[K].NegPart = Zero;
2924     CI[K].Iterations = nullptr;
2925   }
2926   while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2927     const Loop *L = AddRec->getLoop();
2928     unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2929     CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2930     CI[K].PosPart = getPositivePart(CI[K].Coeff);
2931     CI[K].NegPart = getNegativePart(CI[K].Coeff);
2932     CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2933     Subscript = AddRec->getStart();
2934   }
2935   Constant = Subscript;
2936 #ifndef NDEBUG
2937   LLVM_DEBUG(dbgs() << "\tCoefficient Info\n");
2938   for (unsigned K = 1; K <= MaxLevels; ++K) {
2939     LLVM_DEBUG(dbgs() << "\t    " << K << "\t" << *CI[K].Coeff);
2940     LLVM_DEBUG(dbgs() << "\tPos Part = ");
2941     LLVM_DEBUG(dbgs() << *CI[K].PosPart);
2942     LLVM_DEBUG(dbgs() << "\tNeg Part = ");
2943     LLVM_DEBUG(dbgs() << *CI[K].NegPart);
2944     LLVM_DEBUG(dbgs() << "\tUpper Bound = ");
2945     if (CI[K].Iterations)
2946       LLVM_DEBUG(dbgs() << *CI[K].Iterations);
2947     else
2948       LLVM_DEBUG(dbgs() << "+inf");
2949     LLVM_DEBUG(dbgs() << '\n');
2950   }
2951   LLVM_DEBUG(dbgs() << "\t    Constant = " << *Subscript << '\n');
2952 #endif
2953   return CI;
2954 }
2955 
2956 
2957 // Looks through all the bounds info and
2958 // computes the lower bound given the current direction settings
2959 // at each level. If the lower bound for any level is -inf,
2960 // the result is -inf.
2961 const SCEV *DependenceInfo::getLowerBound(BoundInfo *Bound) const {
2962   const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2963   for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2964     if (Bound[K].Lower[Bound[K].Direction])
2965       Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2966     else
2967       Sum = nullptr;
2968   }
2969   return Sum;
2970 }
2971 
2972 
2973 // Looks through all the bounds info and
2974 // computes the upper bound given the current direction settings
2975 // at each level. If the upper bound at any level is +inf,
2976 // the result is +inf.
2977 const SCEV *DependenceInfo::getUpperBound(BoundInfo *Bound) const {
2978   const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2979   for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2980     if (Bound[K].Upper[Bound[K].Direction])
2981       Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2982     else
2983       Sum = nullptr;
2984   }
2985   return Sum;
2986 }
2987 
2988 
2989 //===----------------------------------------------------------------------===//
2990 // Constraint manipulation for Delta test.
2991 
2992 // Given a linear SCEV,
2993 // return the coefficient (the step)
2994 // corresponding to the specified loop.
2995 // If there isn't one, return 0.
2996 // For example, given a*i + b*j + c*k, finding the coefficient
2997 // corresponding to the j loop would yield b.
2998 const SCEV *DependenceInfo::findCoefficient(const SCEV *Expr,
2999                                             const Loop *TargetLoop) const {
3000   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
3001   if (!AddRec)
3002     return SE->getZero(Expr->getType());
3003   if (AddRec->getLoop() == TargetLoop)
3004     return AddRec->getStepRecurrence(*SE);
3005   return findCoefficient(AddRec->getStart(), TargetLoop);
3006 }
3007 
3008 
3009 // Given a linear SCEV,
3010 // return the SCEV given by zeroing out the coefficient
3011 // corresponding to the specified loop.
3012 // For example, given a*i + b*j + c*k, zeroing the coefficient
3013 // corresponding to the j loop would yield a*i + c*k.
3014 const SCEV *DependenceInfo::zeroCoefficient(const SCEV *Expr,
3015                                             const Loop *TargetLoop) const {
3016   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
3017   if (!AddRec)
3018     return Expr; // ignore
3019   if (AddRec->getLoop() == TargetLoop)
3020     return AddRec->getStart();
3021   return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
3022                            AddRec->getStepRecurrence(*SE),
3023                            AddRec->getLoop(),
3024                            AddRec->getNoWrapFlags());
3025 }
3026 
3027 
3028 // Given a linear SCEV Expr,
3029 // return the SCEV given by adding some Value to the
3030 // coefficient corresponding to the specified TargetLoop.
3031 // For example, given a*i + b*j + c*k, adding 1 to the coefficient
3032 // corresponding to the j loop would yield a*i + (b+1)*j + c*k.
3033 const SCEV *DependenceInfo::addToCoefficient(const SCEV *Expr,
3034                                              const Loop *TargetLoop,
3035                                              const SCEV *Value) const {
3036   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
3037   if (!AddRec) // create a new addRec
3038     return SE->getAddRecExpr(Expr,
3039                              Value,
3040                              TargetLoop,
3041                              SCEV::FlagAnyWrap); // Worst case, with no info.
3042   if (AddRec->getLoop() == TargetLoop) {
3043     const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
3044     if (Sum->isZero())
3045       return AddRec->getStart();
3046     return SE->getAddRecExpr(AddRec->getStart(),
3047                              Sum,
3048                              AddRec->getLoop(),
3049                              AddRec->getNoWrapFlags());
3050   }
3051   if (SE->isLoopInvariant(AddRec, TargetLoop))
3052     return SE->getAddRecExpr(AddRec, Value, TargetLoop, SCEV::FlagAnyWrap);
3053   return SE->getAddRecExpr(
3054       addToCoefficient(AddRec->getStart(), TargetLoop, Value),
3055       AddRec->getStepRecurrence(*SE), AddRec->getLoop(),
3056       AddRec->getNoWrapFlags());
3057 }
3058 
3059 
3060 // Review the constraints, looking for opportunities
3061 // to simplify a subscript pair (Src and Dst).
3062 // Return true if some simplification occurs.
3063 // If the simplification isn't exact (that is, if it is conservative
3064 // in terms of dependence), set consistent to false.
3065 // Corresponds to Figure 5 from the paper
3066 //
3067 //            Practical Dependence Testing
3068 //            Goff, Kennedy, Tseng
3069 //            PLDI 1991
3070 bool DependenceInfo::propagate(const SCEV *&Src, const SCEV *&Dst,
3071                                SmallBitVector &Loops,
3072                                SmallVectorImpl<Constraint> &Constraints,
3073                                bool &Consistent) {
3074   bool Result = false;
3075   for (unsigned LI : Loops.set_bits()) {
3076     LLVM_DEBUG(dbgs() << "\t    Constraint[" << LI << "] is");
3077     LLVM_DEBUG(Constraints[LI].dump(dbgs()));
3078     if (Constraints[LI].isDistance())
3079       Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
3080     else if (Constraints[LI].isLine())
3081       Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
3082     else if (Constraints[LI].isPoint())
3083       Result |= propagatePoint(Src, Dst, Constraints[LI]);
3084   }
3085   return Result;
3086 }
3087 
3088 
3089 // Attempt to propagate a distance
3090 // constraint into a subscript pair (Src and Dst).
3091 // Return true if some simplification occurs.
3092 // If the simplification isn't exact (that is, if it is conservative
3093 // in terms of dependence), set consistent to false.
3094 bool DependenceInfo::propagateDistance(const SCEV *&Src, const SCEV *&Dst,
3095                                        Constraint &CurConstraint,
3096                                        bool &Consistent) {
3097   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3098   LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3099   const SCEV *A_K = findCoefficient(Src, CurLoop);
3100   if (A_K->isZero())
3101     return false;
3102   const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
3103   Src = SE->getMinusSCEV(Src, DA_K);
3104   Src = zeroCoefficient(Src, CurLoop);
3105   LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3106   LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3107   Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
3108   LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3109   if (!findCoefficient(Dst, CurLoop)->isZero())
3110     Consistent = false;
3111   return true;
3112 }
3113 
3114 
3115 // Attempt to propagate a line
3116 // constraint into a subscript pair (Src and Dst).
3117 // Return true if some simplification occurs.
3118 // If the simplification isn't exact (that is, if it is conservative
3119 // in terms of dependence), set consistent to false.
3120 bool DependenceInfo::propagateLine(const SCEV *&Src, const SCEV *&Dst,
3121                                    Constraint &CurConstraint,
3122                                    bool &Consistent) {
3123   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3124   const SCEV *A = CurConstraint.getA();
3125   const SCEV *B = CurConstraint.getB();
3126   const SCEV *C = CurConstraint.getC();
3127   LLVM_DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C
3128                     << "\n");
3129   LLVM_DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
3130   LLVM_DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
3131   if (A->isZero()) {
3132     const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
3133     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3134     if (!Bconst || !Cconst) return false;
3135     APInt Beta = Bconst->getAPInt();
3136     APInt Charlie = Cconst->getAPInt();
3137     APInt CdivB = Charlie.sdiv(Beta);
3138     assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
3139     const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3140     //    Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3141     Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3142     Dst = zeroCoefficient(Dst, CurLoop);
3143     if (!findCoefficient(Src, CurLoop)->isZero())
3144       Consistent = false;
3145   }
3146   else if (B->isZero()) {
3147     const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3148     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3149     if (!Aconst || !Cconst) return false;
3150     APInt Alpha = Aconst->getAPInt();
3151     APInt Charlie = Cconst->getAPInt();
3152     APInt CdivA = Charlie.sdiv(Alpha);
3153     assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3154     const SCEV *A_K = findCoefficient(Src, CurLoop);
3155     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3156     Src = zeroCoefficient(Src, CurLoop);
3157     if (!findCoefficient(Dst, CurLoop)->isZero())
3158       Consistent = false;
3159   }
3160   else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
3161     const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3162     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3163     if (!Aconst || !Cconst) return false;
3164     APInt Alpha = Aconst->getAPInt();
3165     APInt Charlie = Cconst->getAPInt();
3166     APInt CdivA = Charlie.sdiv(Alpha);
3167     assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3168     const SCEV *A_K = findCoefficient(Src, CurLoop);
3169     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3170     Src = zeroCoefficient(Src, CurLoop);
3171     Dst = addToCoefficient(Dst, CurLoop, A_K);
3172     if (!findCoefficient(Dst, CurLoop)->isZero())
3173       Consistent = false;
3174   }
3175   else {
3176     // paper is incorrect here, or perhaps just misleading
3177     const SCEV *A_K = findCoefficient(Src, CurLoop);
3178     Src = SE->getMulExpr(Src, A);
3179     Dst = SE->getMulExpr(Dst, A);
3180     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
3181     Src = zeroCoefficient(Src, CurLoop);
3182     Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
3183     if (!findCoefficient(Dst, CurLoop)->isZero())
3184       Consistent = false;
3185   }
3186   LLVM_DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
3187   LLVM_DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
3188   return true;
3189 }
3190 
3191 
3192 // Attempt to propagate a point
3193 // constraint into a subscript pair (Src and Dst).
3194 // Return true if some simplification occurs.
3195 bool DependenceInfo::propagatePoint(const SCEV *&Src, const SCEV *&Dst,
3196                                     Constraint &CurConstraint) {
3197   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3198   const SCEV *A_K = findCoefficient(Src, CurLoop);
3199   const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3200   const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
3201   const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
3202   LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3203   Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
3204   Src = zeroCoefficient(Src, CurLoop);
3205   LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3206   LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3207   Dst = zeroCoefficient(Dst, CurLoop);
3208   LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3209   return true;
3210 }
3211 
3212 
3213 // Update direction vector entry based on the current constraint.
3214 void DependenceInfo::updateDirection(Dependence::DVEntry &Level,
3215                                      const Constraint &CurConstraint) const {
3216   LLVM_DEBUG(dbgs() << "\tUpdate direction, constraint =");
3217   LLVM_DEBUG(CurConstraint.dump(dbgs()));
3218   if (CurConstraint.isAny())
3219     ; // use defaults
3220   else if (CurConstraint.isDistance()) {
3221     // this one is consistent, the others aren't
3222     Level.Scalar = false;
3223     Level.Distance = CurConstraint.getD();
3224     unsigned NewDirection = Dependence::DVEntry::NONE;
3225     if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
3226       NewDirection = Dependence::DVEntry::EQ;
3227     if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
3228       NewDirection |= Dependence::DVEntry::LT;
3229     if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
3230       NewDirection |= Dependence::DVEntry::GT;
3231     Level.Direction &= NewDirection;
3232   }
3233   else if (CurConstraint.isLine()) {
3234     Level.Scalar = false;
3235     Level.Distance = nullptr;
3236     // direction should be accurate
3237   }
3238   else if (CurConstraint.isPoint()) {
3239     Level.Scalar = false;
3240     Level.Distance = nullptr;
3241     unsigned NewDirection = Dependence::DVEntry::NONE;
3242     if (!isKnownPredicate(CmpInst::ICMP_NE,
3243                           CurConstraint.getY(),
3244                           CurConstraint.getX()))
3245       // if X may be = Y
3246       NewDirection |= Dependence::DVEntry::EQ;
3247     if (!isKnownPredicate(CmpInst::ICMP_SLE,
3248                           CurConstraint.getY(),
3249                           CurConstraint.getX()))
3250       // if Y may be > X
3251       NewDirection |= Dependence::DVEntry::LT;
3252     if (!isKnownPredicate(CmpInst::ICMP_SGE,
3253                           CurConstraint.getY(),
3254                           CurConstraint.getX()))
3255       // if Y may be < X
3256       NewDirection |= Dependence::DVEntry::GT;
3257     Level.Direction &= NewDirection;
3258   }
3259   else
3260     llvm_unreachable("constraint has unexpected kind");
3261 }
3262 
3263 /// Check if we can delinearize the subscripts. If the SCEVs representing the
3264 /// source and destination array references are recurrences on a nested loop,
3265 /// this function flattens the nested recurrences into separate recurrences
3266 /// for each loop level.
3267 bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
3268                                     SmallVectorImpl<Subscript> &Pair) {
3269   assert(isLoadOrStore(Src) && "instruction is not load or store");
3270   assert(isLoadOrStore(Dst) && "instruction is not load or store");
3271   Value *SrcPtr = getLoadStorePointerOperand(Src);
3272   Value *DstPtr = getLoadStorePointerOperand(Dst);
3273   Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3274   Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3275   const SCEV *SrcAccessFn = SE->getSCEVAtScope(SrcPtr, SrcLoop);
3276   const SCEV *DstAccessFn = SE->getSCEVAtScope(DstPtr, DstLoop);
3277   const SCEVUnknown *SrcBase =
3278       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3279   const SCEVUnknown *DstBase =
3280       dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3281 
3282   if (!SrcBase || !DstBase || SrcBase != DstBase)
3283     return false;
3284 
3285   SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
3286 
3287   if (!tryDelinearizeFixedSize(Src, Dst, SrcAccessFn, DstAccessFn,
3288                                SrcSubscripts, DstSubscripts) &&
3289       !tryDelinearizeParametricSize(Src, Dst, SrcAccessFn, DstAccessFn,
3290                                     SrcSubscripts, DstSubscripts))
3291     return false;
3292 
3293   int Size = SrcSubscripts.size();
3294   LLVM_DEBUG({
3295     dbgs() << "\nSrcSubscripts: ";
3296     for (int I = 0; I < Size; I++)
3297       dbgs() << *SrcSubscripts[I];
3298     dbgs() << "\nDstSubscripts: ";
3299     for (int I = 0; I < Size; I++)
3300       dbgs() << *DstSubscripts[I];
3301   });
3302 
3303   // The delinearization transforms a single-subscript MIV dependence test into
3304   // a multi-subscript SIV dependence test that is easier to compute. So we
3305   // resize Pair to contain as many pairs of subscripts as the delinearization
3306   // has found, and then initialize the pairs following the delinearization.
3307   Pair.resize(Size);
3308   for (int I = 0; I < Size; ++I) {
3309     Pair[I].Src = SrcSubscripts[I];
3310     Pair[I].Dst = DstSubscripts[I];
3311     unifySubscriptType(&Pair[I]);
3312   }
3313 
3314   return true;
3315 }
3316 
3317 bool DependenceInfo::tryDelinearizeFixedSize(
3318     Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3319     const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3320     SmallVectorImpl<const SCEV *> &DstSubscripts) {
3321 
3322   Value *SrcPtr = getLoadStorePointerOperand(Src);
3323   Value *DstPtr = getLoadStorePointerOperand(Dst);
3324   const SCEVUnknown *SrcBase =
3325       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3326   const SCEVUnknown *DstBase =
3327       dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3328   assert(SrcBase && DstBase && SrcBase == DstBase &&
3329          "expected src and dst scev unknowns to be equal");
3330 
3331   // Check the simple case where the array dimensions are fixed size.
3332   auto *SrcGEP = dyn_cast<GetElementPtrInst>(SrcPtr);
3333   auto *DstGEP = dyn_cast<GetElementPtrInst>(DstPtr);
3334   if (!SrcGEP || !DstGEP)
3335     return false;
3336 
3337   SmallVector<int, 4> SrcSizes, DstSizes;
3338   getIndexExpressionsFromGEP(*SE, SrcGEP, SrcSubscripts, SrcSizes);
3339   getIndexExpressionsFromGEP(*SE, DstGEP, DstSubscripts, DstSizes);
3340 
3341   // Check that the two size arrays are non-empty and equal in length and
3342   // value.
3343   if (SrcSizes.empty() || SrcSubscripts.size() <= 1 ||
3344       SrcSizes.size() != DstSizes.size() ||
3345       !std::equal(SrcSizes.begin(), SrcSizes.end(), DstSizes.begin())) {
3346     SrcSubscripts.clear();
3347     DstSubscripts.clear();
3348     return false;
3349   }
3350 
3351   Value *SrcBasePtr = SrcGEP->getOperand(0)->stripPointerCasts();
3352   Value *DstBasePtr = DstGEP->getOperand(0)->stripPointerCasts();
3353 
3354   // Check that for identical base pointers we do not miss index offsets
3355   // that have been added before this GEP is applied.
3356   if (SrcBasePtr != SrcBase->getValue() || DstBasePtr != DstBase->getValue()) {
3357     SrcSubscripts.clear();
3358     DstSubscripts.clear();
3359     return false;
3360   }
3361 
3362   assert(SrcSubscripts.size() == DstSubscripts.size() &&
3363          SrcSubscripts.size() == SrcSizes.size() + 1 &&
3364          "Expected equal number of entries in the list of sizes and "
3365          "subscripts.");
3366 
3367   // In general we cannot safely assume that the subscripts recovered from GEPs
3368   // are in the range of values defined for their corresponding array
3369   // dimensions. For example some C language usage/interpretation make it
3370   // impossible to verify this at compile-time. As such we can only delinearize
3371   // iff the subscripts are positive and are less than the range of the
3372   // dimension.
3373   if (!DisableDelinearizationChecks) {
3374     auto AllIndiciesInRange = [&](SmallVector<int, 4> &DimensionSizes,
3375                                   SmallVectorImpl<const SCEV *> &Subscripts,
3376                                   Value *Ptr) {
3377       size_t SSize = Subscripts.size();
3378       for (size_t I = 1; I < SSize; ++I) {
3379         const SCEV *S = Subscripts[I];
3380         if (!isKnownNonNegative(S, Ptr))
3381           return false;
3382         if (auto *SType = dyn_cast<IntegerType>(S->getType())) {
3383           const SCEV *Range = SE->getConstant(
3384               ConstantInt::get(SType, DimensionSizes[I - 1], false));
3385           if (!isKnownLessThan(S, Range))
3386             return false;
3387         }
3388       }
3389       return true;
3390     };
3391 
3392     if (!AllIndiciesInRange(SrcSizes, SrcSubscripts, SrcPtr) ||
3393         !AllIndiciesInRange(DstSizes, DstSubscripts, DstPtr)) {
3394       SrcSubscripts.clear();
3395       DstSubscripts.clear();
3396       return false;
3397     }
3398   }
3399   LLVM_DEBUG({
3400     dbgs() << "Delinearized subscripts of fixed-size array\n"
3401            << "SrcGEP:" << *SrcGEP << "\n"
3402            << "DstGEP:" << *DstGEP << "\n";
3403   });
3404   return true;
3405 }
3406 
3407 bool DependenceInfo::tryDelinearizeParametricSize(
3408     Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3409     const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3410     SmallVectorImpl<const SCEV *> &DstSubscripts) {
3411 
3412   Value *SrcPtr = getLoadStorePointerOperand(Src);
3413   Value *DstPtr = getLoadStorePointerOperand(Dst);
3414   const SCEVUnknown *SrcBase =
3415       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3416   const SCEVUnknown *DstBase =
3417       dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3418   assert(SrcBase && DstBase && SrcBase == DstBase &&
3419          "expected src and dst scev unknowns to be equal");
3420 
3421   const SCEV *ElementSize = SE->getElementSize(Src);
3422   if (ElementSize != SE->getElementSize(Dst))
3423     return false;
3424 
3425   const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
3426   const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
3427 
3428   const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
3429   const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
3430   if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
3431     return false;
3432 
3433   // First step: collect parametric terms in both array references.
3434   SmallVector<const SCEV *, 4> Terms;
3435   collectParametricTerms(*SE, SrcAR, Terms);
3436   collectParametricTerms(*SE, DstAR, Terms);
3437 
3438   // Second step: find subscript sizes.
3439   SmallVector<const SCEV *, 4> Sizes;
3440   findArrayDimensions(*SE, Terms, Sizes, ElementSize);
3441 
3442   // Third step: compute the access functions for each subscript.
3443   computeAccessFunctions(*SE, SrcAR, SrcSubscripts, Sizes);
3444   computeAccessFunctions(*SE, DstAR, DstSubscripts, Sizes);
3445 
3446   // Fail when there is only a subscript: that's a linearized access function.
3447   if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
3448       SrcSubscripts.size() != DstSubscripts.size())
3449     return false;
3450 
3451   size_t Size = SrcSubscripts.size();
3452 
3453   // Statically check that the array bounds are in-range. The first subscript we
3454   // don't have a size for and it cannot overflow into another subscript, so is
3455   // always safe. The others need to be 0 <= subscript[i] < bound, for both src
3456   // and dst.
3457   // FIXME: It may be better to record these sizes and add them as constraints
3458   // to the dependency checks.
3459   if (!DisableDelinearizationChecks)
3460     for (size_t I = 1; I < Size; ++I) {
3461       if (!isKnownNonNegative(SrcSubscripts[I], SrcPtr))
3462         return false;
3463 
3464       if (!isKnownLessThan(SrcSubscripts[I], Sizes[I - 1]))
3465         return false;
3466 
3467       if (!isKnownNonNegative(DstSubscripts[I], DstPtr))
3468         return false;
3469 
3470       if (!isKnownLessThan(DstSubscripts[I], Sizes[I - 1]))
3471         return false;
3472     }
3473 
3474   return true;
3475 }
3476 
3477 //===----------------------------------------------------------------------===//
3478 
3479 #ifndef NDEBUG
3480 // For debugging purposes, dump a small bit vector to dbgs().
3481 static void dumpSmallBitVector(SmallBitVector &BV) {
3482   dbgs() << "{";
3483   for (unsigned VI : BV.set_bits()) {
3484     dbgs() << VI;
3485     if (BV.find_next(VI) >= 0)
3486       dbgs() << ' ';
3487   }
3488   dbgs() << "}\n";
3489 }
3490 #endif
3491 
3492 bool DependenceInfo::invalidate(Function &F, const PreservedAnalyses &PA,
3493                                 FunctionAnalysisManager::Invalidator &Inv) {
3494   // Check if the analysis itself has been invalidated.
3495   auto PAC = PA.getChecker<DependenceAnalysis>();
3496   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3497     return true;
3498 
3499   // Check transitive dependencies.
3500   return Inv.invalidate<AAManager>(F, PA) ||
3501          Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3502          Inv.invalidate<LoopAnalysis>(F, PA);
3503 }
3504 
3505 // depends -
3506 // Returns NULL if there is no dependence.
3507 // Otherwise, return a Dependence with as many details as possible.
3508 // Corresponds to Section 3.1 in the paper
3509 //
3510 //            Practical Dependence Testing
3511 //            Goff, Kennedy, Tseng
3512 //            PLDI 1991
3513 //
3514 // Care is required to keep the routine below, getSplitIteration(),
3515 // up to date with respect to this routine.
3516 std::unique_ptr<Dependence>
3517 DependenceInfo::depends(Instruction *Src, Instruction *Dst,
3518                         bool PossiblyLoopIndependent) {
3519   if (Src == Dst)
3520     PossiblyLoopIndependent = false;
3521 
3522   if (!(Src->mayReadOrWriteMemory() && Dst->mayReadOrWriteMemory()))
3523     // if both instructions don't reference memory, there's no dependence
3524     return nullptr;
3525 
3526   if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
3527     // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
3528     LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
3529     return std::make_unique<Dependence>(Src, Dst);
3530   }
3531 
3532   assert(isLoadOrStore(Src) && "instruction is not load or store");
3533   assert(isLoadOrStore(Dst) && "instruction is not load or store");
3534   Value *SrcPtr = getLoadStorePointerOperand(Src);
3535   Value *DstPtr = getLoadStorePointerOperand(Dst);
3536 
3537   switch (underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
3538                                  MemoryLocation::get(Dst),
3539                                  MemoryLocation::get(Src))) {
3540   case AliasResult::MayAlias:
3541   case AliasResult::PartialAlias:
3542     // cannot analyse objects if we don't understand their aliasing.
3543     LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
3544     return std::make_unique<Dependence>(Src, Dst);
3545   case AliasResult::NoAlias:
3546     // If the objects noalias, they are distinct, accesses are independent.
3547     LLVM_DEBUG(dbgs() << "no alias\n");
3548     return nullptr;
3549   case AliasResult::MustAlias:
3550     break; // The underlying objects alias; test accesses for dependence.
3551   }
3552 
3553   // establish loop nesting levels
3554   establishNestingLevels(Src, Dst);
3555   LLVM_DEBUG(dbgs() << "    common nesting levels = " << CommonLevels << "\n");
3556   LLVM_DEBUG(dbgs() << "    maximum nesting levels = " << MaxLevels << "\n");
3557 
3558   FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
3559   ++TotalArrayPairs;
3560 
3561   unsigned Pairs = 1;
3562   SmallVector<Subscript, 2> Pair(Pairs);
3563   const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3564   const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3565   LLVM_DEBUG(dbgs() << "    SrcSCEV = " << *SrcSCEV << "\n");
3566   LLVM_DEBUG(dbgs() << "    DstSCEV = " << *DstSCEV << "\n");
3567   if (SE->getPointerBase(SrcSCEV) != SE->getPointerBase(DstSCEV)) {
3568     // If two pointers have different bases, trying to analyze indexes won't
3569     // work; we can't compare them to each other. This can happen, for example,
3570     // if one is produced by an LCSSA PHI node.
3571     //
3572     // We check this upfront so we don't crash in cases where getMinusSCEV()
3573     // returns a SCEVCouldNotCompute.
3574     LLVM_DEBUG(dbgs() << "can't analyze SCEV with different pointer base\n");
3575     return std::make_unique<Dependence>(Src, Dst);
3576   }
3577   Pair[0].Src = SrcSCEV;
3578   Pair[0].Dst = DstSCEV;
3579 
3580   if (Delinearize) {
3581     if (tryDelinearize(Src, Dst, Pair)) {
3582       LLVM_DEBUG(dbgs() << "    delinearized\n");
3583       Pairs = Pair.size();
3584     }
3585   }
3586 
3587   for (unsigned P = 0; P < Pairs; ++P) {
3588     Pair[P].Loops.resize(MaxLevels + 1);
3589     Pair[P].GroupLoops.resize(MaxLevels + 1);
3590     Pair[P].Group.resize(Pairs);
3591     removeMatchingExtensions(&Pair[P]);
3592     Pair[P].Classification =
3593       classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3594                    Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3595                    Pair[P].Loops);
3596     Pair[P].GroupLoops = Pair[P].Loops;
3597     Pair[P].Group.set(P);
3598     LLVM_DEBUG(dbgs() << "    subscript " << P << "\n");
3599     LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
3600     LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
3601     LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
3602     LLVM_DEBUG(dbgs() << "\tloops = ");
3603     LLVM_DEBUG(dumpSmallBitVector(Pair[P].Loops));
3604   }
3605 
3606   SmallBitVector Separable(Pairs);
3607   SmallBitVector Coupled(Pairs);
3608 
3609   // Partition subscripts into separable and minimally-coupled groups
3610   // Algorithm in paper is algorithmically better;
3611   // this may be faster in practice. Check someday.
3612   //
3613   // Here's an example of how it works. Consider this code:
3614   //
3615   //   for (i = ...) {
3616   //     for (j = ...) {
3617   //       for (k = ...) {
3618   //         for (l = ...) {
3619   //           for (m = ...) {
3620   //             A[i][j][k][m] = ...;
3621   //             ... = A[0][j][l][i + j];
3622   //           }
3623   //         }
3624   //       }
3625   //     }
3626   //   }
3627   //
3628   // There are 4 subscripts here:
3629   //    0 [i] and [0]
3630   //    1 [j] and [j]
3631   //    2 [k] and [l]
3632   //    3 [m] and [i + j]
3633   //
3634   // We've already classified each subscript pair as ZIV, SIV, etc.,
3635   // and collected all the loops mentioned by pair P in Pair[P].Loops.
3636   // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
3637   // and set Pair[P].Group = {P}.
3638   //
3639   //      Src Dst    Classification Loops  GroupLoops Group
3640   //    0 [i] [0]         SIV       {1}      {1}        {0}
3641   //    1 [j] [j]         SIV       {2}      {2}        {1}
3642   //    2 [k] [l]         RDIV      {3,4}    {3,4}      {2}
3643   //    3 [m] [i + j]     MIV       {1,2,5}  {1,2,5}    {3}
3644   //
3645   // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
3646   // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
3647   //
3648   // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
3649   // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
3650   // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
3651   // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
3652   // to either Separable or Coupled).
3653   //
3654   // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
3655   // Next, 1 and 3. The intersection of their GroupLoops = {2}, not empty,
3656   // so Pair[3].Group = {0, 1, 3} and Done = false.
3657   //
3658   // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
3659   // Since Done remains true, we add 2 to the set of Separable pairs.
3660   //
3661   // Finally, we consider 3. There's nothing to compare it with,
3662   // so Done remains true and we add it to the Coupled set.
3663   // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
3664   //
3665   // In the end, we've got 1 separable subscript and 1 coupled group.
3666   for (unsigned SI = 0; SI < Pairs; ++SI) {
3667     if (Pair[SI].Classification == Subscript::NonLinear) {
3668       // ignore these, but collect loops for later
3669       ++NonlinearSubscriptPairs;
3670       collectCommonLoops(Pair[SI].Src,
3671                          LI->getLoopFor(Src->getParent()),
3672                          Pair[SI].Loops);
3673       collectCommonLoops(Pair[SI].Dst,
3674                          LI->getLoopFor(Dst->getParent()),
3675                          Pair[SI].Loops);
3676       Result.Consistent = false;
3677     } else if (Pair[SI].Classification == Subscript::ZIV) {
3678       // always separable
3679       Separable.set(SI);
3680     }
3681     else {
3682       // SIV, RDIV, or MIV, so check for coupled group
3683       bool Done = true;
3684       for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3685         SmallBitVector Intersection = Pair[SI].GroupLoops;
3686         Intersection &= Pair[SJ].GroupLoops;
3687         if (Intersection.any()) {
3688           // accumulate set of all the loops in group
3689           Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3690           // accumulate set of all subscripts in group
3691           Pair[SJ].Group |= Pair[SI].Group;
3692           Done = false;
3693         }
3694       }
3695       if (Done) {
3696         if (Pair[SI].Group.count() == 1) {
3697           Separable.set(SI);
3698           ++SeparableSubscriptPairs;
3699         }
3700         else {
3701           Coupled.set(SI);
3702           ++CoupledSubscriptPairs;
3703         }
3704       }
3705     }
3706   }
3707 
3708   LLVM_DEBUG(dbgs() << "    Separable = ");
3709   LLVM_DEBUG(dumpSmallBitVector(Separable));
3710   LLVM_DEBUG(dbgs() << "    Coupled = ");
3711   LLVM_DEBUG(dumpSmallBitVector(Coupled));
3712 
3713   Constraint NewConstraint;
3714   NewConstraint.setAny(SE);
3715 
3716   // test separable subscripts
3717   for (unsigned SI : Separable.set_bits()) {
3718     LLVM_DEBUG(dbgs() << "testing subscript " << SI);
3719     switch (Pair[SI].Classification) {
3720     case Subscript::ZIV:
3721       LLVM_DEBUG(dbgs() << ", ZIV\n");
3722       if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
3723         return nullptr;
3724       break;
3725     case Subscript::SIV: {
3726       LLVM_DEBUG(dbgs() << ", SIV\n");
3727       unsigned Level;
3728       const SCEV *SplitIter = nullptr;
3729       if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result, NewConstraint,
3730                   SplitIter))
3731         return nullptr;
3732       break;
3733     }
3734     case Subscript::RDIV:
3735       LLVM_DEBUG(dbgs() << ", RDIV\n");
3736       if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
3737         return nullptr;
3738       break;
3739     case Subscript::MIV:
3740       LLVM_DEBUG(dbgs() << ", MIV\n");
3741       if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
3742         return nullptr;
3743       break;
3744     default:
3745       llvm_unreachable("subscript has unexpected classification");
3746     }
3747   }
3748 
3749   if (Coupled.count()) {
3750     // test coupled subscript groups
3751     LLVM_DEBUG(dbgs() << "starting on coupled subscripts\n");
3752     LLVM_DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
3753     SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3754     for (unsigned II = 0; II <= MaxLevels; ++II)
3755       Constraints[II].setAny(SE);
3756     for (unsigned SI : Coupled.set_bits()) {
3757       LLVM_DEBUG(dbgs() << "testing subscript group " << SI << " { ");
3758       SmallBitVector Group(Pair[SI].Group);
3759       SmallBitVector Sivs(Pairs);
3760       SmallBitVector Mivs(Pairs);
3761       SmallBitVector ConstrainedLevels(MaxLevels + 1);
3762       SmallVector<Subscript *, 4> PairsInGroup;
3763       for (unsigned SJ : Group.set_bits()) {
3764         LLVM_DEBUG(dbgs() << SJ << " ");
3765         if (Pair[SJ].Classification == Subscript::SIV)
3766           Sivs.set(SJ);
3767         else
3768           Mivs.set(SJ);
3769         PairsInGroup.push_back(&Pair[SJ]);
3770       }
3771       unifySubscriptType(PairsInGroup);
3772       LLVM_DEBUG(dbgs() << "}\n");
3773       while (Sivs.any()) {
3774         bool Changed = false;
3775         for (unsigned SJ : Sivs.set_bits()) {
3776           LLVM_DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
3777           // SJ is an SIV subscript that's part of the current coupled group
3778           unsigned Level;
3779           const SCEV *SplitIter = nullptr;
3780           LLVM_DEBUG(dbgs() << "SIV\n");
3781           if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, Result, NewConstraint,
3782                       SplitIter))
3783             return nullptr;
3784           ConstrainedLevels.set(Level);
3785           if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
3786             if (Constraints[Level].isEmpty()) {
3787               ++DeltaIndependence;
3788               return nullptr;
3789             }
3790             Changed = true;
3791           }
3792           Sivs.reset(SJ);
3793         }
3794         if (Changed) {
3795           // propagate, possibly creating new SIVs and ZIVs
3796           LLVM_DEBUG(dbgs() << "    propagating\n");
3797           LLVM_DEBUG(dbgs() << "\tMivs = ");
3798           LLVM_DEBUG(dumpSmallBitVector(Mivs));
3799           for (unsigned SJ : Mivs.set_bits()) {
3800             // SJ is an MIV subscript that's part of the current coupled group
3801             LLVM_DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
3802             if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
3803                           Constraints, Result.Consistent)) {
3804               LLVM_DEBUG(dbgs() << "\t    Changed\n");
3805               ++DeltaPropagations;
3806               Pair[SJ].Classification =
3807                 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3808                              Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3809                              Pair[SJ].Loops);
3810               switch (Pair[SJ].Classification) {
3811               case Subscript::ZIV:
3812                 LLVM_DEBUG(dbgs() << "ZIV\n");
3813                 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3814                   return nullptr;
3815                 Mivs.reset(SJ);
3816                 break;
3817               case Subscript::SIV:
3818                 Sivs.set(SJ);
3819                 Mivs.reset(SJ);
3820                 break;
3821               case Subscript::RDIV:
3822               case Subscript::MIV:
3823                 break;
3824               default:
3825                 llvm_unreachable("bad subscript classification");
3826               }
3827             }
3828           }
3829         }
3830       }
3831 
3832       // test & propagate remaining RDIVs
3833       for (unsigned SJ : Mivs.set_bits()) {
3834         if (Pair[SJ].Classification == Subscript::RDIV) {
3835           LLVM_DEBUG(dbgs() << "RDIV test\n");
3836           if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3837             return nullptr;
3838           // I don't yet understand how to propagate RDIV results
3839           Mivs.reset(SJ);
3840         }
3841       }
3842 
3843       // test remaining MIVs
3844       // This code is temporary.
3845       // Better to somehow test all remaining subscripts simultaneously.
3846       for (unsigned SJ : Mivs.set_bits()) {
3847         if (Pair[SJ].Classification == Subscript::MIV) {
3848           LLVM_DEBUG(dbgs() << "MIV test\n");
3849           if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
3850             return nullptr;
3851         }
3852         else
3853           llvm_unreachable("expected only MIV subscripts at this point");
3854       }
3855 
3856       // update Result.DV from constraint vector
3857       LLVM_DEBUG(dbgs() << "    updating\n");
3858       for (unsigned SJ : ConstrainedLevels.set_bits()) {
3859         if (SJ > CommonLevels)
3860           break;
3861         updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
3862         if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
3863           return nullptr;
3864       }
3865     }
3866   }
3867 
3868   // Make sure the Scalar flags are set correctly.
3869   SmallBitVector CompleteLoops(MaxLevels + 1);
3870   for (unsigned SI = 0; SI < Pairs; ++SI)
3871     CompleteLoops |= Pair[SI].Loops;
3872   for (unsigned II = 1; II <= CommonLevels; ++II)
3873     if (CompleteLoops[II])
3874       Result.DV[II - 1].Scalar = false;
3875 
3876   if (PossiblyLoopIndependent) {
3877     // Make sure the LoopIndependent flag is set correctly.
3878     // All directions must include equal, otherwise no
3879     // loop-independent dependence is possible.
3880     for (unsigned II = 1; II <= CommonLevels; ++II) {
3881       if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3882         Result.LoopIndependent = false;
3883         break;
3884       }
3885     }
3886   }
3887   else {
3888     // On the other hand, if all directions are equal and there's no
3889     // loop-independent dependence possible, then no dependence exists.
3890     bool AllEqual = true;
3891     for (unsigned II = 1; II <= CommonLevels; ++II) {
3892       if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
3893         AllEqual = false;
3894         break;
3895       }
3896     }
3897     if (AllEqual)
3898       return nullptr;
3899   }
3900 
3901   return std::make_unique<FullDependence>(std::move(Result));
3902 }
3903 
3904 //===----------------------------------------------------------------------===//
3905 // getSplitIteration -
3906 // Rather than spend rarely-used space recording the splitting iteration
3907 // during the Weak-Crossing SIV test, we re-compute it on demand.
3908 // The re-computation is basically a repeat of the entire dependence test,
3909 // though simplified since we know that the dependence exists.
3910 // It's tedious, since we must go through all propagations, etc.
3911 //
3912 // Care is required to keep this code up to date with respect to the routine
3913 // above, depends().
3914 //
3915 // Generally, the dependence analyzer will be used to build
3916 // a dependence graph for a function (basically a map from instructions
3917 // to dependences). Looking for cycles in the graph shows us loops
3918 // that cannot be trivially vectorized/parallelized.
3919 //
3920 // We can try to improve the situation by examining all the dependences
3921 // that make up the cycle, looking for ones we can break.
3922 // Sometimes, peeling the first or last iteration of a loop will break
3923 // dependences, and we've got flags for those possibilities.
3924 // Sometimes, splitting a loop at some other iteration will do the trick,
3925 // and we've got a flag for that case. Rather than waste the space to
3926 // record the exact iteration (since we rarely know), we provide
3927 // a method that calculates the iteration. It's a drag that it must work
3928 // from scratch, but wonderful in that it's possible.
3929 //
3930 // Here's an example:
3931 //
3932 //    for (i = 0; i < 10; i++)
3933 //        A[i] = ...
3934 //        ... = A[11 - i]
3935 //
3936 // There's a loop-carried flow dependence from the store to the load,
3937 // found by the weak-crossing SIV test. The dependence will have a flag,
3938 // indicating that the dependence can be broken by splitting the loop.
3939 // Calling getSplitIteration will return 5.
3940 // Splitting the loop breaks the dependence, like so:
3941 //
3942 //    for (i = 0; i <= 5; i++)
3943 //        A[i] = ...
3944 //        ... = A[11 - i]
3945 //    for (i = 6; i < 10; i++)
3946 //        A[i] = ...
3947 //        ... = A[11 - i]
3948 //
3949 // breaks the dependence and allows us to vectorize/parallelize
3950 // both loops.
3951 const SCEV *DependenceInfo::getSplitIteration(const Dependence &Dep,
3952                                               unsigned SplitLevel) {
3953   assert(Dep.isSplitable(SplitLevel) &&
3954          "Dep should be splitable at SplitLevel");
3955   Instruction *Src = Dep.getSrc();
3956   Instruction *Dst = Dep.getDst();
3957   assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
3958   assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
3959   assert(isLoadOrStore(Src));
3960   assert(isLoadOrStore(Dst));
3961   Value *SrcPtr = getLoadStorePointerOperand(Src);
3962   Value *DstPtr = getLoadStorePointerOperand(Dst);
3963   assert(underlyingObjectsAlias(
3964              AA, F->getParent()->getDataLayout(), MemoryLocation::get(Dst),
3965              MemoryLocation::get(Src)) == AliasResult::MustAlias);
3966 
3967   // establish loop nesting levels
3968   establishNestingLevels(Src, Dst);
3969 
3970   FullDependence Result(Src, Dst, false, CommonLevels);
3971 
3972   unsigned Pairs = 1;
3973   SmallVector<Subscript, 2> Pair(Pairs);
3974   const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3975   const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3976   Pair[0].Src = SrcSCEV;
3977   Pair[0].Dst = DstSCEV;
3978 
3979   if (Delinearize) {
3980     if (tryDelinearize(Src, Dst, Pair)) {
3981       LLVM_DEBUG(dbgs() << "    delinearized\n");
3982       Pairs = Pair.size();
3983     }
3984   }
3985 
3986   for (unsigned P = 0; P < Pairs; ++P) {
3987     Pair[P].Loops.resize(MaxLevels + 1);
3988     Pair[P].GroupLoops.resize(MaxLevels + 1);
3989     Pair[P].Group.resize(Pairs);
3990     removeMatchingExtensions(&Pair[P]);
3991     Pair[P].Classification =
3992       classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3993                    Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3994                    Pair[P].Loops);
3995     Pair[P].GroupLoops = Pair[P].Loops;
3996     Pair[P].Group.set(P);
3997   }
3998 
3999   SmallBitVector Separable(Pairs);
4000   SmallBitVector Coupled(Pairs);
4001 
4002   // partition subscripts into separable and minimally-coupled groups
4003   for (unsigned SI = 0; SI < Pairs; ++SI) {
4004     if (Pair[SI].Classification == Subscript::NonLinear) {
4005       // ignore these, but collect loops for later
4006       collectCommonLoops(Pair[SI].Src,
4007                          LI->getLoopFor(Src->getParent()),
4008                          Pair[SI].Loops);
4009       collectCommonLoops(Pair[SI].Dst,
4010                          LI->getLoopFor(Dst->getParent()),
4011                          Pair[SI].Loops);
4012       Result.Consistent = false;
4013     }
4014     else if (Pair[SI].Classification == Subscript::ZIV)
4015       Separable.set(SI);
4016     else {
4017       // SIV, RDIV, or MIV, so check for coupled group
4018       bool Done = true;
4019       for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
4020         SmallBitVector Intersection = Pair[SI].GroupLoops;
4021         Intersection &= Pair[SJ].GroupLoops;
4022         if (Intersection.any()) {
4023           // accumulate set of all the loops in group
4024           Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
4025           // accumulate set of all subscripts in group
4026           Pair[SJ].Group |= Pair[SI].Group;
4027           Done = false;
4028         }
4029       }
4030       if (Done) {
4031         if (Pair[SI].Group.count() == 1)
4032           Separable.set(SI);
4033         else
4034           Coupled.set(SI);
4035       }
4036     }
4037   }
4038 
4039   Constraint NewConstraint;
4040   NewConstraint.setAny(SE);
4041 
4042   // test separable subscripts
4043   for (unsigned SI : Separable.set_bits()) {
4044     switch (Pair[SI].Classification) {
4045     case Subscript::SIV: {
4046       unsigned Level;
4047       const SCEV *SplitIter = nullptr;
4048       (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
4049                      Result, NewConstraint, SplitIter);
4050       if (Level == SplitLevel) {
4051         assert(SplitIter != nullptr);
4052         return SplitIter;
4053       }
4054       break;
4055     }
4056     case Subscript::ZIV:
4057     case Subscript::RDIV:
4058     case Subscript::MIV:
4059       break;
4060     default:
4061       llvm_unreachable("subscript has unexpected classification");
4062     }
4063   }
4064 
4065   if (Coupled.count()) {
4066     // test coupled subscript groups
4067     SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
4068     for (unsigned II = 0; II <= MaxLevels; ++II)
4069       Constraints[II].setAny(SE);
4070     for (unsigned SI : Coupled.set_bits()) {
4071       SmallBitVector Group(Pair[SI].Group);
4072       SmallBitVector Sivs(Pairs);
4073       SmallBitVector Mivs(Pairs);
4074       SmallBitVector ConstrainedLevels(MaxLevels + 1);
4075       for (unsigned SJ : Group.set_bits()) {
4076         if (Pair[SJ].Classification == Subscript::SIV)
4077           Sivs.set(SJ);
4078         else
4079           Mivs.set(SJ);
4080       }
4081       while (Sivs.any()) {
4082         bool Changed = false;
4083         for (unsigned SJ : Sivs.set_bits()) {
4084           // SJ is an SIV subscript that's part of the current coupled group
4085           unsigned Level;
4086           const SCEV *SplitIter = nullptr;
4087           (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
4088                          Result, NewConstraint, SplitIter);
4089           if (Level == SplitLevel && SplitIter)
4090             return SplitIter;
4091           ConstrainedLevels.set(Level);
4092           if (intersectConstraints(&Constraints[Level], &NewConstraint))
4093             Changed = true;
4094           Sivs.reset(SJ);
4095         }
4096         if (Changed) {
4097           // propagate, possibly creating new SIVs and ZIVs
4098           for (unsigned SJ : Mivs.set_bits()) {
4099             // SJ is an MIV subscript that's part of the current coupled group
4100             if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
4101                           Pair[SJ].Loops, Constraints, Result.Consistent)) {
4102               Pair[SJ].Classification =
4103                 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
4104                              Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
4105                              Pair[SJ].Loops);
4106               switch (Pair[SJ].Classification) {
4107               case Subscript::ZIV:
4108                 Mivs.reset(SJ);
4109                 break;
4110               case Subscript::SIV:
4111                 Sivs.set(SJ);
4112                 Mivs.reset(SJ);
4113                 break;
4114               case Subscript::RDIV:
4115               case Subscript::MIV:
4116                 break;
4117               default:
4118                 llvm_unreachable("bad subscript classification");
4119               }
4120             }
4121           }
4122         }
4123       }
4124     }
4125   }
4126   llvm_unreachable("somehow reached end of routine");
4127   return nullptr;
4128 }
4129