1 //===- LoopInterchange.cpp - Loop interchange pass------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This Pass handles loop interchange transform. 11 // This pass interchanges loops to provide a more cache-friendly memory access 12 // patterns. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/BlockFrequencyInfo.h" 20 #include "llvm/Analysis/CodeMetrics.h" 21 #include "llvm/Analysis/DependenceAnalysis.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/LoopIterator.h" 24 #include "llvm/Analysis/LoopPass.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Analysis/ScalarEvolutionExpander.h" 27 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 28 #include "llvm/Analysis/TargetTransformInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/InstIterator.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/Pass.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Transforms/Scalar.h" 40 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 41 #include "llvm/Transforms/Utils/LoopUtils.h" 42 #include "llvm/Transforms/Utils/SSAUpdater.h" 43 using namespace llvm; 44 45 #define DEBUG_TYPE "loop-interchange" 46 47 namespace { 48 49 typedef SmallVector<Loop *, 8> LoopVector; 50 51 // TODO: Check if we can use a sparse matrix here. 52 typedef std::vector<std::vector<char>> CharMatrix; 53 54 // Maximum number of dependencies that can be handled in the dependency matrix. 55 static const unsigned MaxMemInstrCount = 100; 56 57 // Maximum loop depth supported. 58 static const unsigned MaxLoopNestDepth = 10; 59 60 struct LoopInterchange; 61 62 #ifdef DUMP_DEP_MATRICIES 63 void printDepMatrix(CharMatrix &DepMatrix) { 64 for (auto I = DepMatrix.begin(), E = DepMatrix.end(); I != E; ++I) { 65 std::vector<char> Vec = *I; 66 for (auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II) 67 DEBUG(dbgs() << *II << " "); 68 DEBUG(dbgs() << "\n"); 69 } 70 } 71 #endif 72 73 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, 74 Loop *L, DependenceInfo *DI) { 75 typedef SmallVector<Value *, 16> ValueVector; 76 ValueVector MemInstr; 77 78 if (Level > MaxLoopNestDepth) { 79 DEBUG(dbgs() << "Cannot handle loops of depth greater than " 80 << MaxLoopNestDepth << "\n"); 81 return false; 82 } 83 84 // For each block. 85 for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end(); 86 BB != BE; ++BB) { 87 // Scan the BB and collect legal loads and stores. 88 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; 89 ++I) { 90 Instruction *Ins = dyn_cast<Instruction>(I); 91 if (!Ins) 92 return false; 93 LoadInst *Ld = dyn_cast<LoadInst>(I); 94 StoreInst *St = dyn_cast<StoreInst>(I); 95 if (!St && !Ld) 96 continue; 97 if (Ld && !Ld->isSimple()) 98 return false; 99 if (St && !St->isSimple()) 100 return false; 101 MemInstr.push_back(&*I); 102 } 103 } 104 105 DEBUG(dbgs() << "Found " << MemInstr.size() 106 << " Loads and Stores to analyze\n"); 107 108 ValueVector::iterator I, IE, J, JE; 109 110 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { 111 for (J = I, JE = MemInstr.end(); J != JE; ++J) { 112 std::vector<char> Dep; 113 Instruction *Src = dyn_cast<Instruction>(*I); 114 Instruction *Des = dyn_cast<Instruction>(*J); 115 if (Src == Des) 116 continue; 117 if (isa<LoadInst>(Src) && isa<LoadInst>(Des)) 118 continue; 119 if (auto D = DI->depends(Src, Des, true)) { 120 DEBUG(dbgs() << "Found Dependency between Src=" << Src << " Des=" << Des 121 << "\n"); 122 if (D->isFlow()) { 123 // TODO: Handle Flow dependence.Check if it is sufficient to populate 124 // the Dependence Matrix with the direction reversed. 125 DEBUG(dbgs() << "Flow dependence not handled"); 126 return false; 127 } 128 if (D->isAnti()) { 129 DEBUG(dbgs() << "Found Anti dependence \n"); 130 unsigned Levels = D->getLevels(); 131 char Direction; 132 for (unsigned II = 1; II <= Levels; ++II) { 133 const SCEV *Distance = D->getDistance(II); 134 const SCEVConstant *SCEVConst = 135 dyn_cast_or_null<SCEVConstant>(Distance); 136 if (SCEVConst) { 137 const ConstantInt *CI = SCEVConst->getValue(); 138 if (CI->isNegative()) 139 Direction = '<'; 140 else if (CI->isZero()) 141 Direction = '='; 142 else 143 Direction = '>'; 144 Dep.push_back(Direction); 145 } else if (D->isScalar(II)) { 146 Direction = 'S'; 147 Dep.push_back(Direction); 148 } else { 149 unsigned Dir = D->getDirection(II); 150 if (Dir == Dependence::DVEntry::LT || 151 Dir == Dependence::DVEntry::LE) 152 Direction = '<'; 153 else if (Dir == Dependence::DVEntry::GT || 154 Dir == Dependence::DVEntry::GE) 155 Direction = '>'; 156 else if (Dir == Dependence::DVEntry::EQ) 157 Direction = '='; 158 else 159 Direction = '*'; 160 Dep.push_back(Direction); 161 } 162 } 163 while (Dep.size() != Level) { 164 Dep.push_back('I'); 165 } 166 167 DepMatrix.push_back(Dep); 168 if (DepMatrix.size() > MaxMemInstrCount) { 169 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount 170 << " dependencies inside loop\n"); 171 return false; 172 } 173 } 174 } 175 } 176 } 177 178 // We don't have a DepMatrix to check legality return false. 179 if (DepMatrix.size() == 0) 180 return false; 181 return true; 182 } 183 184 // A loop is moved from index 'from' to an index 'to'. Update the Dependence 185 // matrix by exchanging the two columns. 186 static void interChangeDepedencies(CharMatrix &DepMatrix, unsigned FromIndx, 187 unsigned ToIndx) { 188 unsigned numRows = DepMatrix.size(); 189 for (unsigned i = 0; i < numRows; ++i) { 190 char TmpVal = DepMatrix[i][ToIndx]; 191 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; 192 DepMatrix[i][FromIndx] = TmpVal; 193 } 194 } 195 196 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is 197 // '>' 198 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, 199 unsigned Column) { 200 for (unsigned i = 0; i <= Column; ++i) { 201 if (DepMatrix[Row][i] == '<') 202 return false; 203 if (DepMatrix[Row][i] == '>') 204 return true; 205 } 206 // All dependencies were '=','S' or 'I' 207 return false; 208 } 209 210 // Checks if no dependence exist in the dependency matrix in Row before Column. 211 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, 212 unsigned Column) { 213 for (unsigned i = 0; i < Column; ++i) { 214 if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' || 215 DepMatrix[Row][i] != 'I') 216 return false; 217 } 218 return true; 219 } 220 221 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, 222 unsigned OuterLoopId, char InnerDep, 223 char OuterDep) { 224 225 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) 226 return false; 227 228 if (InnerDep == OuterDep) 229 return true; 230 231 // It is legal to interchange if and only if after interchange no row has a 232 // '>' direction as the leftmost non-'='. 233 234 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') 235 return true; 236 237 if (InnerDep == '<') 238 return true; 239 240 if (InnerDep == '>') { 241 // If OuterLoopId represents outermost loop then interchanging will make the 242 // 1st dependency as '>' 243 if (OuterLoopId == 0) 244 return false; 245 246 // If all dependencies before OuterloopId are '=','S'or 'I'. Then 247 // interchanging will result in this row having an outermost non '=' 248 // dependency of '>' 249 if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) 250 return true; 251 } 252 253 return false; 254 } 255 256 // Checks if it is legal to interchange 2 loops. 257 // [Theorem] A permutation of the loops in a perfect nest is legal if and only 258 // if 259 // the direction matrix, after the same permutation is applied to its columns, 260 // has no ">" direction as the leftmost non-"=" direction in any row. 261 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, 262 unsigned InnerLoopId, 263 unsigned OuterLoopId) { 264 265 unsigned NumRows = DepMatrix.size(); 266 // For each row check if it is valid to interchange. 267 for (unsigned Row = 0; Row < NumRows; ++Row) { 268 char InnerDep = DepMatrix[Row][InnerLoopId]; 269 char OuterDep = DepMatrix[Row][OuterLoopId]; 270 if (InnerDep == '*' || OuterDep == '*') 271 return false; 272 else if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, 273 OuterDep)) 274 return false; 275 } 276 return true; 277 } 278 279 static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) { 280 281 DEBUG(dbgs() << "Calling populateWorklist called\n"); 282 LoopVector LoopList; 283 Loop *CurrentLoop = &L; 284 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); 285 while (!Vec->empty()) { 286 // The current loop has multiple subloops in it hence it is not tightly 287 // nested. 288 // Discard all loops above it added into Worklist. 289 if (Vec->size() != 1) { 290 LoopList.clear(); 291 return; 292 } 293 LoopList.push_back(CurrentLoop); 294 CurrentLoop = Vec->front(); 295 Vec = &CurrentLoop->getSubLoops(); 296 } 297 LoopList.push_back(CurrentLoop); 298 V.push_back(std::move(LoopList)); 299 } 300 301 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { 302 PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); 303 if (InnerIndexVar) 304 return InnerIndexVar; 305 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) 306 return nullptr; 307 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 308 PHINode *PhiVar = cast<PHINode>(I); 309 Type *PhiTy = PhiVar->getType(); 310 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 311 !PhiTy->isPointerTy()) 312 return nullptr; 313 const SCEVAddRecExpr *AddRec = 314 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); 315 if (!AddRec || !AddRec->isAffine()) 316 continue; 317 const SCEV *Step = AddRec->getStepRecurrence(*SE); 318 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 319 if (!C) 320 continue; 321 // Found the induction variable. 322 // FIXME: Handle loops with more than one induction variable. Note that, 323 // currently, legality makes sure we have only one induction variable. 324 return PhiVar; 325 } 326 return nullptr; 327 } 328 329 /// LoopInterchangeLegality checks if it is legal to interchange the loop. 330 class LoopInterchangeLegality { 331 public: 332 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 333 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA) 334 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 335 PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {} 336 337 /// Check if the loops can be interchanged. 338 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, 339 CharMatrix &DepMatrix); 340 /// Check if the loop structure is understood. We do not handle triangular 341 /// loops for now. 342 bool isLoopStructureUnderstood(PHINode *InnerInductionVar); 343 344 bool currentLimitations(); 345 346 bool hasInnerLoopReduction() { return InnerLoopHasReduction; } 347 348 private: 349 bool tightlyNested(Loop *Outer, Loop *Inner); 350 bool containsUnsafeInstructionsInHeader(BasicBlock *BB); 351 bool areAllUsesReductions(Instruction *Ins, Loop *L); 352 bool containsUnsafeInstructionsInLatch(BasicBlock *BB); 353 bool findInductionAndReductions(Loop *L, 354 SmallVector<PHINode *, 8> &Inductions, 355 SmallVector<PHINode *, 8> &Reductions); 356 Loop *OuterLoop; 357 Loop *InnerLoop; 358 359 ScalarEvolution *SE; 360 LoopInfo *LI; 361 DominatorTree *DT; 362 bool PreserveLCSSA; 363 364 bool InnerLoopHasReduction; 365 }; 366 367 /// LoopInterchangeProfitability checks if it is profitable to interchange the 368 /// loop. 369 class LoopInterchangeProfitability { 370 public: 371 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE) 372 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {} 373 374 /// Check if the loop interchange is profitable. 375 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, 376 CharMatrix &DepMatrix); 377 378 private: 379 int getInstrOrderCost(); 380 381 Loop *OuterLoop; 382 Loop *InnerLoop; 383 384 /// Scev analysis. 385 ScalarEvolution *SE; 386 }; 387 388 /// LoopInterchangeTransform interchanges the loop. 389 class LoopInterchangeTransform { 390 public: 391 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 392 LoopInfo *LI, DominatorTree *DT, 393 BasicBlock *LoopNestExit, 394 bool InnerLoopContainsReductions) 395 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 396 LoopExit(LoopNestExit), 397 InnerLoopHasReduction(InnerLoopContainsReductions) {} 398 399 /// Interchange OuterLoop and InnerLoop. 400 bool transform(); 401 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop); 402 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); 403 404 private: 405 void splitInnerLoopLatch(Instruction *); 406 void splitOuterLoopLatch(); 407 void splitInnerLoopHeader(); 408 bool adjustLoopLinks(); 409 void adjustLoopPreheaders(); 410 void adjustOuterLoopPreheader(); 411 bool adjustLoopBranches(); 412 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred, 413 BasicBlock *NewPred); 414 415 Loop *OuterLoop; 416 Loop *InnerLoop; 417 418 /// Scev analysis. 419 ScalarEvolution *SE; 420 LoopInfo *LI; 421 DominatorTree *DT; 422 BasicBlock *LoopExit; 423 bool InnerLoopHasReduction; 424 }; 425 426 // Main LoopInterchange Pass. 427 struct LoopInterchange : public FunctionPass { 428 static char ID; 429 ScalarEvolution *SE; 430 LoopInfo *LI; 431 DependenceInfo *DI; 432 DominatorTree *DT; 433 bool PreserveLCSSA; 434 LoopInterchange() 435 : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) { 436 initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); 437 } 438 439 void getAnalysisUsage(AnalysisUsage &AU) const override { 440 AU.addRequired<ScalarEvolutionWrapperPass>(); 441 AU.addRequired<AAResultsWrapperPass>(); 442 AU.addRequired<DominatorTreeWrapperPass>(); 443 AU.addRequired<LoopInfoWrapperPass>(); 444 AU.addRequired<DependenceAnalysisWrapperPass>(); 445 AU.addRequiredID(LoopSimplifyID); 446 AU.addRequiredID(LCSSAID); 447 } 448 449 bool runOnFunction(Function &F) override { 450 if (skipFunction(F)) 451 return false; 452 453 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 454 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 455 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 456 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 457 DT = DTWP ? &DTWP->getDomTree() : nullptr; 458 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 459 460 // Build up a worklist of loop pairs to analyze. 461 SmallVector<LoopVector, 8> Worklist; 462 463 for (Loop *L : *LI) 464 populateWorklist(*L, Worklist); 465 466 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n"); 467 bool Changed = true; 468 while (!Worklist.empty()) { 469 LoopVector LoopList = Worklist.pop_back_val(); 470 Changed = processLoopList(LoopList, F); 471 } 472 return Changed; 473 } 474 475 bool isComputableLoopNest(LoopVector LoopList) { 476 for (auto I = LoopList.begin(), E = LoopList.end(); I != E; ++I) { 477 Loop *L = *I; 478 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); 479 if (ExitCountOuter == SE->getCouldNotCompute()) { 480 DEBUG(dbgs() << "Couldn't compute Backedge count\n"); 481 return false; 482 } 483 if (L->getNumBackEdges() != 1) { 484 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); 485 return false; 486 } 487 if (!L->getExitingBlock()) { 488 DEBUG(dbgs() << "Loop Doesn't have unique exit block\n"); 489 return false; 490 } 491 } 492 return true; 493 } 494 495 unsigned selectLoopForInterchange(const LoopVector &LoopList) { 496 // TODO: Add a better heuristic to select the loop to be interchanged based 497 // on the dependence matrix. Currently we select the innermost loop. 498 return LoopList.size() - 1; 499 } 500 501 bool processLoopList(LoopVector LoopList, Function &F) { 502 503 bool Changed = false; 504 CharMatrix DependencyMatrix; 505 if (LoopList.size() < 2) { 506 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); 507 return false; 508 } 509 if (!isComputableLoopNest(LoopList)) { 510 DEBUG(dbgs() << "Not vaild loop candidate for interchange\n"); 511 return false; 512 } 513 Loop *OuterMostLoop = *(LoopList.begin()); 514 515 DEBUG(dbgs() << "Processing LoopList of size = " << LoopList.size() 516 << "\n"); 517 518 if (!populateDependencyMatrix(DependencyMatrix, LoopList.size(), 519 OuterMostLoop, DI)) { 520 DEBUG(dbgs() << "Populating Dependency matrix failed\n"); 521 return false; 522 } 523 #ifdef DUMP_DEP_MATRICIES 524 DEBUG(dbgs() << "Dependence before inter change \n"); 525 printDepMatrix(DependencyMatrix); 526 #endif 527 528 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch(); 529 BranchInst *OuterMostLoopLatchBI = 530 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator()); 531 if (!OuterMostLoopLatchBI) 532 return false; 533 534 // Since we currently do not handle LCSSA PHI's any failure in loop 535 // condition will now branch to LoopNestExit. 536 // TODO: This should be removed once we handle LCSSA PHI nodes. 537 538 // Get the Outermost loop exit. 539 BasicBlock *LoopNestExit; 540 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader()) 541 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1); 542 else 543 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0); 544 545 if (isa<PHINode>(LoopNestExit->begin())) { 546 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now " 547 "since on failure all loops branch to loop nest exit.\n"); 548 return false; 549 } 550 551 unsigned SelecLoopId = selectLoopForInterchange(LoopList); 552 // Move the selected loop outwards to the best possible position. 553 for (unsigned i = SelecLoopId; i > 0; i--) { 554 bool Interchanged = 555 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); 556 if (!Interchanged) 557 return Changed; 558 // Loops interchanged reflect the same in LoopList 559 std::swap(LoopList[i - 1], LoopList[i]); 560 561 // Update the DependencyMatrix 562 interChangeDepedencies(DependencyMatrix, i, i - 1); 563 DT->recalculate(F); 564 #ifdef DUMP_DEP_MATRICIES 565 DEBUG(dbgs() << "Dependence after inter change \n"); 566 printDepMatrix(DependencyMatrix); 567 #endif 568 Changed |= Interchanged; 569 } 570 return Changed; 571 } 572 573 bool processLoop(LoopVector LoopList, unsigned InnerLoopId, 574 unsigned OuterLoopId, BasicBlock *LoopNestExit, 575 std::vector<std::vector<char>> &DependencyMatrix) { 576 577 DEBUG(dbgs() << "Processing Innder Loop Id = " << InnerLoopId 578 << " and OuterLoopId = " << OuterLoopId << "\n"); 579 Loop *InnerLoop = LoopList[InnerLoopId]; 580 Loop *OuterLoop = LoopList[OuterLoopId]; 581 582 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT, 583 PreserveLCSSA); 584 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { 585 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n"); 586 return false; 587 } 588 DEBUG(dbgs() << "Loops are legal to interchange\n"); 589 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE); 590 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { 591 DEBUG(dbgs() << "Interchanging Loops not profitable\n"); 592 return false; 593 } 594 595 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, 596 LoopNestExit, LIL.hasInnerLoopReduction()); 597 LIT.transform(); 598 DEBUG(dbgs() << "Loops interchanged\n"); 599 return true; 600 } 601 }; 602 603 } // end of namespace 604 bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) { 605 return !std::any_of(Ins->user_begin(), Ins->user_end(), [=](User *U) -> bool { 606 PHINode *UserIns = dyn_cast<PHINode>(U); 607 RecurrenceDescriptor RD; 608 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD); 609 }); 610 } 611 612 bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader( 613 BasicBlock *BB) { 614 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 615 // Load corresponding to reduction PHI's are safe while concluding if 616 // tightly nested. 617 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 618 if (!areAllUsesReductions(L, InnerLoop)) 619 return true; 620 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 621 return true; 622 } 623 return false; 624 } 625 626 bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch( 627 BasicBlock *BB) { 628 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 629 // Stores corresponding to reductions are safe while concluding if tightly 630 // nested. 631 if (StoreInst *L = dyn_cast<StoreInst>(I)) { 632 PHINode *PHI = dyn_cast<PHINode>(L->getOperand(0)); 633 if (!PHI) 634 return true; 635 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 636 return true; 637 } 638 return false; 639 } 640 641 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { 642 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 643 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 644 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 645 646 DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n"); 647 648 // A perfectly nested loop will not have any branch in between the outer and 649 // inner block i.e. outer header will branch to either inner preheader and 650 // outerloop latch. 651 BranchInst *outerLoopHeaderBI = 652 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 653 if (!outerLoopHeaderBI) 654 return false; 655 unsigned num = outerLoopHeaderBI->getNumSuccessors(); 656 for (unsigned i = 0; i < num; i++) { 657 if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader && 658 outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch) 659 return false; 660 } 661 662 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n"); 663 // We do not have any basic block in between now make sure the outer header 664 // and outer loop latch doesn't contain any unsafe instructions. 665 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) || 666 containsUnsafeInstructionsInLatch(OuterLoopLatch)) 667 return false; 668 669 DEBUG(dbgs() << "Loops are perfectly nested \n"); 670 // We have a perfect loop nest. 671 return true; 672 } 673 674 675 bool LoopInterchangeLegality::isLoopStructureUnderstood( 676 PHINode *InnerInduction) { 677 678 unsigned Num = InnerInduction->getNumOperands(); 679 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); 680 for (unsigned i = 0; i < Num; ++i) { 681 Value *Val = InnerInduction->getOperand(i); 682 if (isa<Constant>(Val)) 683 continue; 684 Instruction *I = dyn_cast<Instruction>(Val); 685 if (!I) 686 return false; 687 // TODO: Handle triangular loops. 688 // e.g. for(int i=0;i<N;i++) 689 // for(int j=i;j<N;j++) 690 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); 691 if (InnerInduction->getIncomingBlock(IncomBlockIndx) == 692 InnerLoopPreheader && 693 !OuterLoop->isLoopInvariant(I)) { 694 return false; 695 } 696 } 697 return true; 698 } 699 700 bool LoopInterchangeLegality::findInductionAndReductions( 701 Loop *L, SmallVector<PHINode *, 8> &Inductions, 702 SmallVector<PHINode *, 8> &Reductions) { 703 if (!L->getLoopLatch() || !L->getLoopPredecessor()) 704 return false; 705 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 706 RecurrenceDescriptor RD; 707 InductionDescriptor ID; 708 PHINode *PHI = cast<PHINode>(I); 709 if (InductionDescriptor::isInductionPHI(PHI, SE, ID)) 710 Inductions.push_back(PHI); 711 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) 712 Reductions.push_back(PHI); 713 else { 714 DEBUG( 715 dbgs() << "Failed to recognize PHI as an induction or reduction.\n"); 716 return false; 717 } 718 } 719 return true; 720 } 721 722 static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { 723 for (auto I = Block->begin(); isa<PHINode>(I); ++I) { 724 PHINode *PHI = cast<PHINode>(I); 725 // Reduction lcssa phi will have only 1 incoming block that from loop latch. 726 if (PHI->getNumIncomingValues() > 1) 727 return false; 728 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0)); 729 if (!Ins) 730 return false; 731 // Incoming value for lcssa phi's in outer loop exit can only be inner loop 732 // exits lcssa phi else it would not be tightly nested. 733 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) 734 return false; 735 } 736 return true; 737 } 738 739 static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock, 740 BasicBlock *LoopHeader) { 741 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) { 742 unsigned Num = BI->getNumSuccessors(); 743 assert(Num == 2); 744 for (unsigned i = 0; i < Num; ++i) { 745 if (BI->getSuccessor(i) == LoopHeader) 746 continue; 747 return BI->getSuccessor(i); 748 } 749 } 750 return nullptr; 751 } 752 753 // This function indicates the current limitations in the transform as a result 754 // of which we do not proceed. 755 bool LoopInterchangeLegality::currentLimitations() { 756 757 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 758 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 759 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 760 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 761 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 762 763 PHINode *InnerInductionVar; 764 SmallVector<PHINode *, 8> Inductions; 765 SmallVector<PHINode *, 8> Reductions; 766 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) 767 return true; 768 769 // TODO: Currently we handle only loops with 1 induction variable. 770 if (Inductions.size() != 1) { 771 DEBUG(dbgs() << "We currently only support loops with 1 induction variable." 772 << "Failed to interchange due to current limitation\n"); 773 return true; 774 } 775 if (Reductions.size() > 0) 776 InnerLoopHasReduction = true; 777 778 InnerInductionVar = Inductions.pop_back_val(); 779 Reductions.clear(); 780 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) 781 return true; 782 783 // Outer loop cannot have reduction because then loops will not be tightly 784 // nested. 785 if (!Reductions.empty()) 786 return true; 787 // TODO: Currently we handle only loops with 1 induction variable. 788 if (Inductions.size() != 1) 789 return true; 790 791 // TODO: Triangular loops are not handled for now. 792 if (!isLoopStructureUnderstood(InnerInductionVar)) { 793 DEBUG(dbgs() << "Loop structure not understood by pass\n"); 794 return true; 795 } 796 797 // TODO: We only handle LCSSA PHI's corresponding to reduction for now. 798 BasicBlock *LoopExitBlock = 799 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader); 800 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) 801 return true; 802 803 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader); 804 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) 805 return true; 806 807 // TODO: Current limitation: Since we split the inner loop latch at the point 808 // were induction variable is incremented (induction.next); We cannot have 809 // more than 1 user of induction.next since it would result in broken code 810 // after split. 811 // e.g. 812 // for(i=0;i<N;i++) { 813 // for(j = 0;j<M;j++) { 814 // A[j+1][i+2] = A[j][i]+k; 815 // } 816 // } 817 bool FoundInduction = false; 818 Instruction *InnerIndexVarInc = nullptr; 819 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) 820 InnerIndexVarInc = 821 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); 822 else 823 InnerIndexVarInc = 824 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); 825 826 if (!InnerIndexVarInc) 827 return true; 828 829 // Since we split the inner loop latch on this induction variable. Make sure 830 // we do not have any instruction between the induction variable and branch 831 // instruction. 832 833 for (auto I = InnerLoopLatch->rbegin(), E = InnerLoopLatch->rend(); 834 I != E && !FoundInduction; ++I) { 835 if (isa<BranchInst>(*I) || isa<CmpInst>(*I) || isa<TruncInst>(*I)) 836 continue; 837 const Instruction &Ins = *I; 838 // We found an instruction. If this is not induction variable then it is not 839 // safe to split this loop latch. 840 if (!Ins.isIdenticalTo(InnerIndexVarInc)) 841 return true; 842 else 843 FoundInduction = true; 844 } 845 // The loop latch ended and we didn't find the induction variable return as 846 // current limitation. 847 if (!FoundInduction) 848 return true; 849 850 return false; 851 } 852 853 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, 854 unsigned OuterLoopId, 855 CharMatrix &DepMatrix) { 856 857 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { 858 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId 859 << "and OuterLoopId = " << OuterLoopId 860 << "due to dependence\n"); 861 return false; 862 } 863 864 // Create unique Preheaders if we already do not have one. 865 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 866 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 867 868 // Create a unique outer preheader - 869 // 1) If OuterLoop preheader is not present. 870 // 2) If OuterLoop Preheader is same as OuterLoop Header 871 // 3) If OuterLoop Preheader is same as Header of the previous loop. 872 // 4) If OuterLoop Preheader is Entry node. 873 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() || 874 isa<PHINode>(OuterLoopPreHeader->begin()) || 875 !OuterLoopPreHeader->getUniquePredecessor()) { 876 OuterLoopPreHeader = 877 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA); 878 } 879 880 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() || 881 InnerLoopPreHeader == OuterLoop->getHeader()) { 882 InnerLoopPreHeader = 883 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA); 884 } 885 886 // TODO: The loops could not be interchanged due to current limitations in the 887 // transform module. 888 if (currentLimitations()) { 889 DEBUG(dbgs() << "Not legal because of current transform limitation\n"); 890 return false; 891 } 892 893 // Check if the loops are tightly nested. 894 if (!tightlyNested(OuterLoop, InnerLoop)) { 895 DEBUG(dbgs() << "Loops not tightly nested\n"); 896 return false; 897 } 898 899 return true; 900 } 901 902 int LoopInterchangeProfitability::getInstrOrderCost() { 903 unsigned GoodOrder, BadOrder; 904 BadOrder = GoodOrder = 0; 905 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end(); 906 BI != BE; ++BI) { 907 for (auto I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) { 908 const Instruction &Ins = *I; 909 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { 910 unsigned NumOp = GEP->getNumOperands(); 911 bool FoundInnerInduction = false; 912 bool FoundOuterInduction = false; 913 for (unsigned i = 0; i < NumOp; ++i) { 914 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); 915 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); 916 if (!AR) 917 continue; 918 919 // If we find the inner induction after an outer induction e.g. 920 // for(int i=0;i<N;i++) 921 // for(int j=0;j<N;j++) 922 // A[i][j] = A[i-1][j-1]+k; 923 // then it is a good order. 924 if (AR->getLoop() == InnerLoop) { 925 // We found an InnerLoop induction after OuterLoop induction. It is 926 // a good order. 927 FoundInnerInduction = true; 928 if (FoundOuterInduction) { 929 GoodOrder++; 930 break; 931 } 932 } 933 // If we find the outer induction after an inner induction e.g. 934 // for(int i=0;i<N;i++) 935 // for(int j=0;j<N;j++) 936 // A[j][i] = A[j-1][i-1]+k; 937 // then it is a bad order. 938 if (AR->getLoop() == OuterLoop) { 939 // We found an OuterLoop induction after InnerLoop induction. It is 940 // a bad order. 941 FoundOuterInduction = true; 942 if (FoundInnerInduction) { 943 BadOrder++; 944 break; 945 } 946 } 947 } 948 } 949 } 950 } 951 return GoodOrder - BadOrder; 952 } 953 954 static bool isProfitabileForVectorization(unsigned InnerLoopId, 955 unsigned OuterLoopId, 956 CharMatrix &DepMatrix) { 957 // TODO: Improve this heuristic to catch more cases. 958 // If the inner loop is loop independent or doesn't carry any dependency it is 959 // profitable to move this to outer position. 960 unsigned Row = DepMatrix.size(); 961 for (unsigned i = 0; i < Row; ++i) { 962 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I') 963 return false; 964 // TODO: We need to improve this heuristic. 965 if (DepMatrix[i][OuterLoopId] != '=') 966 return false; 967 } 968 // If outer loop has dependence and inner loop is loop independent then it is 969 // profitable to interchange to enable parallelism. 970 return true; 971 } 972 973 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, 974 unsigned OuterLoopId, 975 CharMatrix &DepMatrix) { 976 977 // TODO: Add better profitability checks. 978 // e.g 979 // 1) Construct dependency matrix and move the one with no loop carried dep 980 // inside to enable vectorization. 981 982 // This is rough cost estimation algorithm. It counts the good and bad order 983 // of induction variables in the instruction and allows reordering if number 984 // of bad orders is more than good. 985 int Cost = 0; 986 Cost += getInstrOrderCost(); 987 DEBUG(dbgs() << "Cost = " << Cost << "\n"); 988 if (Cost < 0) 989 return true; 990 991 // It is not profitable as per current cache profitability model. But check if 992 // we can move this loop outside to improve parallelism. 993 bool ImprovesPar = 994 isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix); 995 return ImprovesPar; 996 } 997 998 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, 999 Loop *InnerLoop) { 1000 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E; 1001 ++I) { 1002 if (*I == InnerLoop) { 1003 OuterLoop->removeChildLoop(I); 1004 return; 1005 } 1006 } 1007 llvm_unreachable("Couldn't find loop"); 1008 } 1009 1010 void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop, 1011 Loop *OuterLoop) { 1012 Loop *OuterLoopParent = OuterLoop->getParentLoop(); 1013 if (OuterLoopParent) { 1014 // Remove the loop from its parent loop. 1015 removeChildLoop(OuterLoopParent, OuterLoop); 1016 removeChildLoop(OuterLoop, InnerLoop); 1017 OuterLoopParent->addChildLoop(InnerLoop); 1018 } else { 1019 removeChildLoop(OuterLoop, InnerLoop); 1020 LI->changeTopLevelLoop(OuterLoop, InnerLoop); 1021 } 1022 1023 while (!InnerLoop->empty()) 1024 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin())); 1025 1026 InnerLoop->addChildLoop(OuterLoop); 1027 } 1028 1029 bool LoopInterchangeTransform::transform() { 1030 1031 DEBUG(dbgs() << "transform\n"); 1032 bool Transformed = false; 1033 Instruction *InnerIndexVar; 1034 1035 if (InnerLoop->getSubLoops().size() == 0) { 1036 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1037 DEBUG(dbgs() << "Calling Split Inner Loop\n"); 1038 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); 1039 if (!InductionPHI) { 1040 DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); 1041 return false; 1042 } 1043 1044 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) 1045 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); 1046 else 1047 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); 1048 1049 // 1050 // Split at the place were the induction variable is 1051 // incremented/decremented. 1052 // TODO: This splitting logic may not work always. Fix this. 1053 splitInnerLoopLatch(InnerIndexVar); 1054 DEBUG(dbgs() << "splitInnerLoopLatch Done\n"); 1055 1056 // Splits the inner loops phi nodes out into a separate basic block. 1057 splitInnerLoopHeader(); 1058 DEBUG(dbgs() << "splitInnerLoopHeader Done\n"); 1059 } 1060 1061 Transformed |= adjustLoopLinks(); 1062 if (!Transformed) { 1063 DEBUG(dbgs() << "adjustLoopLinks Failed\n"); 1064 return false; 1065 } 1066 1067 restructureLoops(InnerLoop, OuterLoop); 1068 return true; 1069 } 1070 1071 void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) { 1072 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1073 BasicBlock *InnerLoopLatchPred = InnerLoopLatch; 1074 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI); 1075 } 1076 1077 void LoopInterchangeTransform::splitOuterLoopLatch() { 1078 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1079 BasicBlock *OuterLatchLcssaPhiBlock = OuterLoopLatch; 1080 OuterLoopLatch = SplitBlock(OuterLatchLcssaPhiBlock, 1081 OuterLoopLatch->getFirstNonPHI(), DT, LI); 1082 } 1083 1084 void LoopInterchangeTransform::splitInnerLoopHeader() { 1085 1086 // Split the inner loop header out. Here make sure that the reduction PHI's 1087 // stay in the innerloop body. 1088 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1089 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1090 if (InnerLoopHasReduction) { 1091 // FIXME: Check if the induction PHI will always be the first PHI. 1092 BasicBlock *New = InnerLoopHeader->splitBasicBlock( 1093 ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split"); 1094 if (LI) 1095 if (Loop *L = LI->getLoopFor(InnerLoopHeader)) 1096 L->addBasicBlockToLoop(New, *LI); 1097 1098 // Adjust Reduction PHI's in the block. 1099 SmallVector<PHINode *, 8> PHIVec; 1100 for (auto I = New->begin(); isa<PHINode>(I); ++I) { 1101 PHINode *PHI = dyn_cast<PHINode>(I); 1102 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader); 1103 PHI->replaceAllUsesWith(V); 1104 PHIVec.push_back((PHI)); 1105 } 1106 for (auto I = PHIVec.begin(), E = PHIVec.end(); I != E; ++I) { 1107 PHINode *P = *I; 1108 P->eraseFromParent(); 1109 } 1110 } else { 1111 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); 1112 } 1113 1114 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & " 1115 "InnerLoopHeader \n"); 1116 } 1117 1118 /// \brief Move all instructions except the terminator from FromBB right before 1119 /// InsertBefore 1120 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { 1121 auto &ToList = InsertBefore->getParent()->getInstList(); 1122 auto &FromList = FromBB->getInstList(); 1123 1124 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), 1125 FromBB->getTerminator()->getIterator()); 1126 } 1127 1128 void LoopInterchangeTransform::adjustOuterLoopPreheader() { 1129 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1130 BasicBlock *InnerPreHeader = InnerLoop->getLoopPreheader(); 1131 1132 moveBBContents(OuterLoopPreHeader, InnerPreHeader->getTerminator()); 1133 } 1134 1135 void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock, 1136 BasicBlock *OldPred, 1137 BasicBlock *NewPred) { 1138 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) { 1139 PHINode *PHI = cast<PHINode>(I); 1140 unsigned Num = PHI->getNumIncomingValues(); 1141 for (unsigned i = 0; i < Num; ++i) { 1142 if (PHI->getIncomingBlock(i) == OldPred) 1143 PHI->setIncomingBlock(i, NewPred); 1144 } 1145 } 1146 } 1147 1148 bool LoopInterchangeTransform::adjustLoopBranches() { 1149 1150 DEBUG(dbgs() << "adjustLoopBranches called\n"); 1151 // Adjust the loop preheader 1152 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1153 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1154 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1155 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1156 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1157 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1158 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); 1159 BasicBlock *InnerLoopLatchPredecessor = 1160 InnerLoopLatch->getUniquePredecessor(); 1161 BasicBlock *InnerLoopLatchSuccessor; 1162 BasicBlock *OuterLoopLatchSuccessor; 1163 1164 BranchInst *OuterLoopLatchBI = 1165 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); 1166 BranchInst *InnerLoopLatchBI = 1167 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 1168 BranchInst *OuterLoopHeaderBI = 1169 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 1170 BranchInst *InnerLoopHeaderBI = 1171 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); 1172 1173 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || 1174 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || 1175 !InnerLoopHeaderBI) 1176 return false; 1177 1178 BranchInst *InnerLoopLatchPredecessorBI = 1179 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); 1180 BranchInst *OuterLoopPredecessorBI = 1181 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); 1182 1183 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) 1184 return false; 1185 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); 1186 if (!InnerLoopHeaderSuccessor) 1187 return false; 1188 1189 // Adjust Loop Preheader and headers 1190 1191 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors(); 1192 for (unsigned i = 0; i < NumSucc; ++i) { 1193 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader) 1194 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader); 1195 } 1196 1197 NumSucc = OuterLoopHeaderBI->getNumSuccessors(); 1198 for (unsigned i = 0; i < NumSucc; ++i) { 1199 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch) 1200 OuterLoopHeaderBI->setSuccessor(i, LoopExit); 1201 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader) 1202 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor); 1203 } 1204 1205 // Adjust reduction PHI's now that the incoming block has changed. 1206 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader, 1207 OuterLoopHeader); 1208 1209 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI); 1210 InnerLoopHeaderBI->eraseFromParent(); 1211 1212 // -------------Adjust loop latches----------- 1213 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) 1214 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); 1215 else 1216 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); 1217 1218 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors(); 1219 for (unsigned i = 0; i < NumSucc; ++i) { 1220 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch) 1221 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor); 1222 } 1223 1224 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with 1225 // the value and remove this PHI node from inner loop. 1226 SmallVector<PHINode *, 8> LcssaVec; 1227 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) { 1228 PHINode *LcssaPhi = cast<PHINode>(I); 1229 LcssaVec.push_back(LcssaPhi); 1230 } 1231 for (auto I = LcssaVec.begin(), E = LcssaVec.end(); I != E; ++I) { 1232 PHINode *P = *I; 1233 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch); 1234 P->replaceAllUsesWith(Incoming); 1235 P->eraseFromParent(); 1236 } 1237 1238 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) 1239 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); 1240 else 1241 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); 1242 1243 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor) 1244 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor); 1245 else 1246 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor); 1247 1248 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch); 1249 1250 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) { 1251 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch); 1252 } else { 1253 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch); 1254 } 1255 1256 return true; 1257 } 1258 void LoopInterchangeTransform::adjustLoopPreheaders() { 1259 1260 // We have interchanged the preheaders so we need to interchange the data in 1261 // the preheader as well. 1262 // This is because the content of inner preheader was previously executed 1263 // inside the outer loop. 1264 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1265 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1266 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1267 BranchInst *InnerTermBI = 1268 cast<BranchInst>(InnerLoopPreHeader->getTerminator()); 1269 1270 // These instructions should now be executed inside the loop. 1271 // Move instruction into a new block after outer header. 1272 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); 1273 // These instructions were not executed previously in the loop so move them to 1274 // the older inner loop preheader. 1275 moveBBContents(OuterLoopPreHeader, InnerTermBI); 1276 } 1277 1278 bool LoopInterchangeTransform::adjustLoopLinks() { 1279 1280 // Adjust all branches in the inner and outer loop. 1281 bool Changed = adjustLoopBranches(); 1282 if (Changed) 1283 adjustLoopPreheaders(); 1284 return Changed; 1285 } 1286 1287 char LoopInterchange::ID = 0; 1288 INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", 1289 "Interchanges loops for cache reuse", false, false) 1290 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1291 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1292 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1293 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 1294 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 1295 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 1296 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 1297 1298 INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", 1299 "Interchanges loops for cache reuse", false, false) 1300 1301 Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } 1302