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