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 *Dst = dyn_cast<Instruction>(*J); 115 if (Src == Dst) 116 continue; 117 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) 118 continue; 119 if (auto D = DI->depends(Src, Dst, true)) { 120 DEBUG(dbgs() << "Found Dependency between Src and Dst\n" 121 << " Src:" << *Src << "\n Dst:" << *Dst << '\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\n"); 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 on Func: " 282 << L.getHeader()->getParent()->getName() << " Loop: %" 283 << L.getHeader()->getName() << '\n'); 284 LoopVector LoopList; 285 Loop *CurrentLoop = &L; 286 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); 287 while (!Vec->empty()) { 288 // The current loop has multiple subloops in it hence it is not tightly 289 // nested. 290 // Discard all loops above it added into Worklist. 291 if (Vec->size() != 1) { 292 LoopList.clear(); 293 return; 294 } 295 LoopList.push_back(CurrentLoop); 296 CurrentLoop = Vec->front(); 297 Vec = &CurrentLoop->getSubLoops(); 298 } 299 LoopList.push_back(CurrentLoop); 300 V.push_back(std::move(LoopList)); 301 DEBUG(dbgs() << "Worklist size = " << V.size() << "\n"); 302 } 303 304 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { 305 PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); 306 if (InnerIndexVar) 307 return InnerIndexVar; 308 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) 309 return nullptr; 310 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 311 PHINode *PhiVar = cast<PHINode>(I); 312 Type *PhiTy = PhiVar->getType(); 313 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 314 !PhiTy->isPointerTy()) 315 return nullptr; 316 const SCEVAddRecExpr *AddRec = 317 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); 318 if (!AddRec || !AddRec->isAffine()) 319 continue; 320 const SCEV *Step = AddRec->getStepRecurrence(*SE); 321 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 322 if (!C) 323 continue; 324 // Found the induction variable. 325 // FIXME: Handle loops with more than one induction variable. Note that, 326 // currently, legality makes sure we have only one induction variable. 327 return PhiVar; 328 } 329 return nullptr; 330 } 331 332 /// LoopInterchangeLegality checks if it is legal to interchange the loop. 333 class LoopInterchangeLegality { 334 public: 335 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 336 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA) 337 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 338 PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {} 339 340 /// Check if the loops can be interchanged. 341 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, 342 CharMatrix &DepMatrix); 343 /// Check if the loop structure is understood. We do not handle triangular 344 /// loops for now. 345 bool isLoopStructureUnderstood(PHINode *InnerInductionVar); 346 347 bool currentLimitations(); 348 349 bool hasInnerLoopReduction() { return InnerLoopHasReduction; } 350 351 private: 352 bool tightlyNested(Loop *Outer, Loop *Inner); 353 bool containsUnsafeInstructionsInHeader(BasicBlock *BB); 354 bool areAllUsesReductions(Instruction *Ins, Loop *L); 355 bool containsUnsafeInstructionsInLatch(BasicBlock *BB); 356 bool findInductionAndReductions(Loop *L, 357 SmallVector<PHINode *, 8> &Inductions, 358 SmallVector<PHINode *, 8> &Reductions); 359 Loop *OuterLoop; 360 Loop *InnerLoop; 361 362 ScalarEvolution *SE; 363 LoopInfo *LI; 364 DominatorTree *DT; 365 bool PreserveLCSSA; 366 367 bool InnerLoopHasReduction; 368 }; 369 370 /// LoopInterchangeProfitability checks if it is profitable to interchange the 371 /// loop. 372 class LoopInterchangeProfitability { 373 public: 374 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE) 375 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {} 376 377 /// Check if the loop interchange is profitable. 378 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, 379 CharMatrix &DepMatrix); 380 381 private: 382 int getInstrOrderCost(); 383 384 Loop *OuterLoop; 385 Loop *InnerLoop; 386 387 /// Scev analysis. 388 ScalarEvolution *SE; 389 }; 390 391 /// LoopInterchangeTransform interchanges the loop. 392 class LoopInterchangeTransform { 393 public: 394 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 395 LoopInfo *LI, DominatorTree *DT, 396 BasicBlock *LoopNestExit, 397 bool InnerLoopContainsReductions) 398 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 399 LoopExit(LoopNestExit), 400 InnerLoopHasReduction(InnerLoopContainsReductions) {} 401 402 /// Interchange OuterLoop and InnerLoop. 403 bool transform(); 404 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop); 405 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); 406 407 private: 408 void splitInnerLoopLatch(Instruction *); 409 void splitInnerLoopHeader(); 410 bool adjustLoopLinks(); 411 void adjustLoopPreheaders(); 412 bool adjustLoopBranches(); 413 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred, 414 BasicBlock *NewPred); 415 416 Loop *OuterLoop; 417 Loop *InnerLoop; 418 419 /// Scev analysis. 420 ScalarEvolution *SE; 421 LoopInfo *LI; 422 DominatorTree *DT; 423 BasicBlock *LoopExit; 424 bool InnerLoopHasReduction; 425 }; 426 427 // Main LoopInterchange Pass. 428 struct LoopInterchange : public FunctionPass { 429 static char ID; 430 ScalarEvolution *SE; 431 LoopInfo *LI; 432 DependenceInfo *DI; 433 DominatorTree *DT; 434 bool PreserveLCSSA; 435 LoopInterchange() 436 : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) { 437 initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); 438 } 439 440 void getAnalysisUsage(AnalysisUsage &AU) const override { 441 AU.addRequired<ScalarEvolutionWrapperPass>(); 442 AU.addRequired<AAResultsWrapperPass>(); 443 AU.addRequired<DominatorTreeWrapperPass>(); 444 AU.addRequired<LoopInfoWrapperPass>(); 445 AU.addRequired<DependenceAnalysisWrapperPass>(); 446 AU.addRequiredID(LoopSimplifyID); 447 AU.addRequiredID(LCSSAID); 448 } 449 450 bool runOnFunction(Function &F) override { 451 if (skipFunction(F)) 452 return false; 453 454 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 455 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 456 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 457 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 458 DT = DTWP ? &DTWP->getDomTree() : nullptr; 459 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 460 461 // Build up a worklist of loop pairs to analyze. 462 SmallVector<LoopVector, 8> Worklist; 463 464 for (Loop *L : *LI) 465 populateWorklist(*L, Worklist); 466 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 (Loop *L : LoopList) { 477 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); 478 if (ExitCountOuter == SE->getCouldNotCompute()) { 479 DEBUG(dbgs() << "Couldn't compute Backedge count\n"); 480 return false; 481 } 482 if (L->getNumBackEdges() != 1) { 483 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); 484 return false; 485 } 486 if (!L->getExitingBlock()) { 487 DEBUG(dbgs() << "Loop Doesn't have unique exit block\n"); 488 return false; 489 } 490 } 491 return true; 492 } 493 494 unsigned selectLoopForInterchange(const LoopVector &LoopList) { 495 // TODO: Add a better heuristic to select the loop to be interchanged based 496 // on the dependence matrix. Currently we select the innermost loop. 497 return LoopList.size() - 1; 498 } 499 500 bool processLoopList(LoopVector LoopList, Function &F) { 501 502 bool Changed = false; 503 CharMatrix DependencyMatrix; 504 if (LoopList.size() < 2) { 505 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); 506 return false; 507 } 508 if (!isComputableLoopNest(LoopList)) { 509 DEBUG(dbgs() << "Not vaild loop candidate for interchange\n"); 510 return false; 511 } 512 Loop *OuterMostLoop = *(LoopList.begin()); 513 514 DEBUG(dbgs() << "Processing LoopList of size = " << LoopList.size() 515 << "\n"); 516 517 if (!populateDependencyMatrix(DependencyMatrix, LoopList.size(), 518 OuterMostLoop, DI)) { 519 DEBUG(dbgs() << "Populating Dependency matrix failed\n"); 520 return false; 521 } 522 #ifdef DUMP_DEP_MATRICIES 523 DEBUG(dbgs() << "Dependence before inter change \n"); 524 printDepMatrix(DependencyMatrix); 525 #endif 526 527 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch(); 528 BranchInst *OuterMostLoopLatchBI = 529 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator()); 530 if (!OuterMostLoopLatchBI) 531 return false; 532 533 // Since we currently do not handle LCSSA PHI's any failure in loop 534 // condition will now branch to LoopNestExit. 535 // TODO: This should be removed once we handle LCSSA PHI nodes. 536 537 // Get the Outermost loop exit. 538 BasicBlock *LoopNestExit; 539 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader()) 540 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1); 541 else 542 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0); 543 544 if (isa<PHINode>(LoopNestExit->begin())) { 545 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now " 546 "since on failure all loops branch to loop nest exit.\n"); 547 return false; 548 } 549 550 unsigned SelecLoopId = selectLoopForInterchange(LoopList); 551 // Move the selected loop outwards to the best possible position. 552 for (unsigned i = SelecLoopId; i > 0; i--) { 553 bool Interchanged = 554 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); 555 if (!Interchanged) 556 return Changed; 557 // Loops interchanged reflect the same in LoopList 558 std::swap(LoopList[i - 1], LoopList[i]); 559 560 // Update the DependencyMatrix 561 interChangeDepedencies(DependencyMatrix, i, i - 1); 562 DT->recalculate(F); 563 #ifdef DUMP_DEP_MATRICIES 564 DEBUG(dbgs() << "Dependence after inter change \n"); 565 printDepMatrix(DependencyMatrix); 566 #endif 567 Changed |= Interchanged; 568 } 569 return Changed; 570 } 571 572 bool processLoop(LoopVector LoopList, unsigned InnerLoopId, 573 unsigned OuterLoopId, BasicBlock *LoopNestExit, 574 std::vector<std::vector<char>> &DependencyMatrix) { 575 576 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId 577 << " and OuterLoopId = " << OuterLoopId << "\n"); 578 Loop *InnerLoop = LoopList[InnerLoopId]; 579 Loop *OuterLoop = LoopList[OuterLoopId]; 580 581 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT, 582 PreserveLCSSA); 583 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { 584 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n"); 585 return false; 586 } 587 DEBUG(dbgs() << "Loops are legal to interchange\n"); 588 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE); 589 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { 590 DEBUG(dbgs() << "Interchanging Loops not profitable\n"); 591 return false; 592 } 593 594 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, 595 LoopNestExit, LIL.hasInnerLoopReduction()); 596 LIT.transform(); 597 DEBUG(dbgs() << "Loops interchanged\n"); 598 return true; 599 } 600 }; 601 602 } // end of namespace 603 bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) { 604 return none_of(Ins->users(), [=](User *U) -> bool { 605 auto *UserIns = dyn_cast<PHINode>(U); 606 RecurrenceDescriptor RD; 607 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD); 608 }); 609 } 610 611 bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader( 612 BasicBlock *BB) { 613 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 614 // Load corresponding to reduction PHI's are safe while concluding if 615 // tightly nested. 616 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 617 if (!areAllUsesReductions(L, InnerLoop)) 618 return true; 619 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 620 return true; 621 } 622 return false; 623 } 624 625 bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch( 626 BasicBlock *BB) { 627 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 628 // Stores corresponding to reductions are safe while concluding if tightly 629 // nested. 630 if (StoreInst *L = dyn_cast<StoreInst>(I)) { 631 PHINode *PHI = dyn_cast<PHINode>(L->getOperand(0)); 632 if (!PHI) 633 return true; 634 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 635 return true; 636 } 637 return false; 638 } 639 640 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { 641 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 642 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 643 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 644 645 DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n"); 646 647 // A perfectly nested loop will not have any branch in between the outer and 648 // inner block i.e. outer header will branch to either inner preheader and 649 // outerloop latch. 650 BranchInst *outerLoopHeaderBI = 651 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 652 if (!outerLoopHeaderBI) 653 return false; 654 unsigned num = outerLoopHeaderBI->getNumSuccessors(); 655 for (unsigned i = 0; i < num; i++) { 656 if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader && 657 outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch) 658 return false; 659 } 660 661 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n"); 662 // We do not have any basic block in between now make sure the outer header 663 // and outer loop latch doesn't contain any unsafe instructions. 664 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) || 665 containsUnsafeInstructionsInLatch(OuterLoopLatch)) 666 return false; 667 668 DEBUG(dbgs() << "Loops are perfectly nested \n"); 669 // We have a perfect loop nest. 670 return true; 671 } 672 673 674 bool LoopInterchangeLegality::isLoopStructureUnderstood( 675 PHINode *InnerInduction) { 676 677 unsigned Num = InnerInduction->getNumOperands(); 678 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); 679 for (unsigned i = 0; i < Num; ++i) { 680 Value *Val = InnerInduction->getOperand(i); 681 if (isa<Constant>(Val)) 682 continue; 683 Instruction *I = dyn_cast<Instruction>(Val); 684 if (!I) 685 return false; 686 // TODO: Handle triangular loops. 687 // e.g. for(int i=0;i<N;i++) 688 // for(int j=i;j<N;j++) 689 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); 690 if (InnerInduction->getIncomingBlock(IncomBlockIndx) == 691 InnerLoopPreheader && 692 !OuterLoop->isLoopInvariant(I)) { 693 return false; 694 } 695 } 696 return true; 697 } 698 699 bool LoopInterchangeLegality::findInductionAndReductions( 700 Loop *L, SmallVector<PHINode *, 8> &Inductions, 701 SmallVector<PHINode *, 8> &Reductions) { 702 if (!L->getLoopLatch() || !L->getLoopPredecessor()) 703 return false; 704 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 705 RecurrenceDescriptor RD; 706 InductionDescriptor ID; 707 PHINode *PHI = cast<PHINode>(I); 708 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID)) 709 Inductions.push_back(PHI); 710 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) 711 Reductions.push_back(PHI); 712 else { 713 DEBUG( 714 dbgs() << "Failed to recognize PHI as an induction or reduction.\n"); 715 return false; 716 } 717 } 718 return true; 719 } 720 721 static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { 722 for (auto I = Block->begin(); isa<PHINode>(I); ++I) { 723 PHINode *PHI = cast<PHINode>(I); 724 // Reduction lcssa phi will have only 1 incoming block that from loop latch. 725 if (PHI->getNumIncomingValues() > 1) 726 return false; 727 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0)); 728 if (!Ins) 729 return false; 730 // Incoming value for lcssa phi's in outer loop exit can only be inner loop 731 // exits lcssa phi else it would not be tightly nested. 732 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) 733 return false; 734 } 735 return true; 736 } 737 738 static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock, 739 BasicBlock *LoopHeader) { 740 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) { 741 unsigned Num = BI->getNumSuccessors(); 742 assert(Num == 2); 743 for (unsigned i = 0; i < Num; ++i) { 744 if (BI->getSuccessor(i) == LoopHeader) 745 continue; 746 return BI->getSuccessor(i); 747 } 748 } 749 return nullptr; 750 } 751 752 // This function indicates the current limitations in the transform as a result 753 // of which we do not proceed. 754 bool LoopInterchangeLegality::currentLimitations() { 755 756 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 757 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 758 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 759 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 760 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 761 762 PHINode *InnerInductionVar; 763 SmallVector<PHINode *, 8> Inductions; 764 SmallVector<PHINode *, 8> Reductions; 765 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) 766 return true; 767 768 // TODO: Currently we handle only loops with 1 induction variable. 769 if (Inductions.size() != 1) { 770 DEBUG(dbgs() << "We currently only support loops with 1 induction variable." 771 << "Failed to interchange due to current limitation\n"); 772 return true; 773 } 774 if (Reductions.size() > 0) 775 InnerLoopHasReduction = true; 776 777 InnerInductionVar = Inductions.pop_back_val(); 778 Reductions.clear(); 779 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) 780 return true; 781 782 // Outer loop cannot have reduction because then loops will not be tightly 783 // nested. 784 if (!Reductions.empty()) 785 return true; 786 // TODO: Currently we handle only loops with 1 induction variable. 787 if (Inductions.size() != 1) 788 return true; 789 790 // TODO: Triangular loops are not handled for now. 791 if (!isLoopStructureUnderstood(InnerInductionVar)) { 792 DEBUG(dbgs() << "Loop structure not understood by pass\n"); 793 return true; 794 } 795 796 // TODO: We only handle LCSSA PHI's corresponding to reduction for now. 797 BasicBlock *LoopExitBlock = 798 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader); 799 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) 800 return true; 801 802 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader); 803 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) 804 return true; 805 806 // TODO: Current limitation: Since we split the inner loop latch at the point 807 // were induction variable is incremented (induction.next); We cannot have 808 // more than 1 user of induction.next since it would result in broken code 809 // after split. 810 // e.g. 811 // for(i=0;i<N;i++) { 812 // for(j = 0;j<M;j++) { 813 // A[j+1][i+2] = A[j][i]+k; 814 // } 815 // } 816 Instruction *InnerIndexVarInc = nullptr; 817 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) 818 InnerIndexVarInc = 819 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); 820 else 821 InnerIndexVarInc = 822 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); 823 824 if (!InnerIndexVarInc) 825 return true; 826 827 // Since we split the inner loop latch on this induction variable. Make sure 828 // we do not have any instruction between the induction variable and branch 829 // instruction. 830 831 bool FoundInduction = false; 832 for (const Instruction &I : reverse(*InnerLoopLatch)) { 833 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I)) 834 continue; 835 // We found an instruction. If this is not induction variable then it is not 836 // safe to split this loop latch. 837 if (!I.isIdenticalTo(InnerIndexVarInc)) 838 return true; 839 840 FoundInduction = true; 841 break; 842 } 843 // The loop latch ended and we didn't find the induction variable return as 844 // current limitation. 845 if (!FoundInduction) 846 return true; 847 848 return false; 849 } 850 851 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, 852 unsigned OuterLoopId, 853 CharMatrix &DepMatrix) { 854 855 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { 856 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId 857 << "and OuterLoopId = " << OuterLoopId 858 << "due to dependence\n"); 859 return false; 860 } 861 862 // Create unique Preheaders if we already do not have one. 863 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 864 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 865 866 // Create a unique outer preheader - 867 // 1) If OuterLoop preheader is not present. 868 // 2) If OuterLoop Preheader is same as OuterLoop Header 869 // 3) If OuterLoop Preheader is same as Header of the previous loop. 870 // 4) If OuterLoop Preheader is Entry node. 871 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() || 872 isa<PHINode>(OuterLoopPreHeader->begin()) || 873 !OuterLoopPreHeader->getUniquePredecessor()) { 874 OuterLoopPreHeader = 875 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA); 876 } 877 878 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() || 879 InnerLoopPreHeader == OuterLoop->getHeader()) { 880 InnerLoopPreHeader = 881 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA); 882 } 883 884 // TODO: The loops could not be interchanged due to current limitations in the 885 // transform module. 886 if (currentLimitations()) { 887 DEBUG(dbgs() << "Not legal because of current transform limitation\n"); 888 return false; 889 } 890 891 // Check if the loops are tightly nested. 892 if (!tightlyNested(OuterLoop, InnerLoop)) { 893 DEBUG(dbgs() << "Loops not tightly nested\n"); 894 return false; 895 } 896 897 return true; 898 } 899 900 int LoopInterchangeProfitability::getInstrOrderCost() { 901 unsigned GoodOrder, BadOrder; 902 BadOrder = GoodOrder = 0; 903 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end(); 904 BI != BE; ++BI) { 905 for (Instruction &Ins : **BI) { 906 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { 907 unsigned NumOp = GEP->getNumOperands(); 908 bool FoundInnerInduction = false; 909 bool FoundOuterInduction = false; 910 for (unsigned i = 0; i < NumOp; ++i) { 911 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); 912 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); 913 if (!AR) 914 continue; 915 916 // If we find the inner induction after an outer induction e.g. 917 // for(int i=0;i<N;i++) 918 // for(int j=0;j<N;j++) 919 // A[i][j] = A[i-1][j-1]+k; 920 // then it is a good order. 921 if (AR->getLoop() == InnerLoop) { 922 // We found an InnerLoop induction after OuterLoop induction. It is 923 // a good order. 924 FoundInnerInduction = true; 925 if (FoundOuterInduction) { 926 GoodOrder++; 927 break; 928 } 929 } 930 // If we find the outer induction after an inner induction e.g. 931 // for(int i=0;i<N;i++) 932 // for(int j=0;j<N;j++) 933 // A[j][i] = A[j-1][i-1]+k; 934 // then it is a bad order. 935 if (AR->getLoop() == OuterLoop) { 936 // We found an OuterLoop induction after InnerLoop induction. It is 937 // a bad order. 938 FoundOuterInduction = true; 939 if (FoundInnerInduction) { 940 BadOrder++; 941 break; 942 } 943 } 944 } 945 } 946 } 947 } 948 return GoodOrder - BadOrder; 949 } 950 951 static bool isProfitabileForVectorization(unsigned InnerLoopId, 952 unsigned OuterLoopId, 953 CharMatrix &DepMatrix) { 954 // TODO: Improve this heuristic to catch more cases. 955 // If the inner loop is loop independent or doesn't carry any dependency it is 956 // profitable to move this to outer position. 957 unsigned Row = DepMatrix.size(); 958 for (unsigned i = 0; i < Row; ++i) { 959 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I') 960 return false; 961 // TODO: We need to improve this heuristic. 962 if (DepMatrix[i][OuterLoopId] != '=') 963 return false; 964 } 965 // If outer loop has dependence and inner loop is loop independent then it is 966 // profitable to interchange to enable parallelism. 967 return true; 968 } 969 970 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, 971 unsigned OuterLoopId, 972 CharMatrix &DepMatrix) { 973 974 // TODO: Add better profitability checks. 975 // e.g 976 // 1) Construct dependency matrix and move the one with no loop carried dep 977 // inside to enable vectorization. 978 979 // This is rough cost estimation algorithm. It counts the good and bad order 980 // of induction variables in the instruction and allows reordering if number 981 // of bad orders is more than good. 982 int Cost = 0; 983 Cost += getInstrOrderCost(); 984 DEBUG(dbgs() << "Cost = " << Cost << "\n"); 985 if (Cost < 0) 986 return true; 987 988 // It is not profitable as per current cache profitability model. But check if 989 // we can move this loop outside to improve parallelism. 990 bool ImprovesPar = 991 isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix); 992 return ImprovesPar; 993 } 994 995 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, 996 Loop *InnerLoop) { 997 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E; 998 ++I) { 999 if (*I == InnerLoop) { 1000 OuterLoop->removeChildLoop(I); 1001 return; 1002 } 1003 } 1004 llvm_unreachable("Couldn't find loop"); 1005 } 1006 1007 void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop, 1008 Loop *OuterLoop) { 1009 Loop *OuterLoopParent = OuterLoop->getParentLoop(); 1010 if (OuterLoopParent) { 1011 // Remove the loop from its parent loop. 1012 removeChildLoop(OuterLoopParent, OuterLoop); 1013 removeChildLoop(OuterLoop, InnerLoop); 1014 OuterLoopParent->addChildLoop(InnerLoop); 1015 } else { 1016 removeChildLoop(OuterLoop, InnerLoop); 1017 LI->changeTopLevelLoop(OuterLoop, InnerLoop); 1018 } 1019 1020 while (!InnerLoop->empty()) 1021 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin())); 1022 1023 InnerLoop->addChildLoop(OuterLoop); 1024 } 1025 1026 bool LoopInterchangeTransform::transform() { 1027 1028 DEBUG(dbgs() << "transform\n"); 1029 bool Transformed = false; 1030 Instruction *InnerIndexVar; 1031 1032 if (InnerLoop->getSubLoops().size() == 0) { 1033 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1034 DEBUG(dbgs() << "Calling Split Inner Loop\n"); 1035 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); 1036 if (!InductionPHI) { 1037 DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); 1038 return false; 1039 } 1040 1041 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) 1042 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); 1043 else 1044 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); 1045 1046 // 1047 // Split at the place were the induction variable is 1048 // incremented/decremented. 1049 // TODO: This splitting logic may not work always. Fix this. 1050 splitInnerLoopLatch(InnerIndexVar); 1051 DEBUG(dbgs() << "splitInnerLoopLatch Done\n"); 1052 1053 // Splits the inner loops phi nodes out into a separate basic block. 1054 splitInnerLoopHeader(); 1055 DEBUG(dbgs() << "splitInnerLoopHeader Done\n"); 1056 } 1057 1058 Transformed |= adjustLoopLinks(); 1059 if (!Transformed) { 1060 DEBUG(dbgs() << "adjustLoopLinks Failed\n"); 1061 return false; 1062 } 1063 1064 restructureLoops(InnerLoop, OuterLoop); 1065 return true; 1066 } 1067 1068 void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) { 1069 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1070 BasicBlock *InnerLoopLatchPred = InnerLoopLatch; 1071 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI); 1072 } 1073 1074 void LoopInterchangeTransform::splitInnerLoopHeader() { 1075 1076 // Split the inner loop header out. Here make sure that the reduction PHI's 1077 // stay in the innerloop body. 1078 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1079 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1080 if (InnerLoopHasReduction) { 1081 // FIXME: Check if the induction PHI will always be the first PHI. 1082 BasicBlock *New = InnerLoopHeader->splitBasicBlock( 1083 ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split"); 1084 if (LI) 1085 if (Loop *L = LI->getLoopFor(InnerLoopHeader)) 1086 L->addBasicBlockToLoop(New, *LI); 1087 1088 // Adjust Reduction PHI's in the block. 1089 SmallVector<PHINode *, 8> PHIVec; 1090 for (auto I = New->begin(); isa<PHINode>(I); ++I) { 1091 PHINode *PHI = dyn_cast<PHINode>(I); 1092 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader); 1093 PHI->replaceAllUsesWith(V); 1094 PHIVec.push_back((PHI)); 1095 } 1096 for (PHINode *P : PHIVec) { 1097 P->eraseFromParent(); 1098 } 1099 } else { 1100 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); 1101 } 1102 1103 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & " 1104 "InnerLoopHeader \n"); 1105 } 1106 1107 /// \brief Move all instructions except the terminator from FromBB right before 1108 /// InsertBefore 1109 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { 1110 auto &ToList = InsertBefore->getParent()->getInstList(); 1111 auto &FromList = FromBB->getInstList(); 1112 1113 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), 1114 FromBB->getTerminator()->getIterator()); 1115 } 1116 1117 void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock, 1118 BasicBlock *OldPred, 1119 BasicBlock *NewPred) { 1120 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) { 1121 PHINode *PHI = cast<PHINode>(I); 1122 unsigned Num = PHI->getNumIncomingValues(); 1123 for (unsigned i = 0; i < Num; ++i) { 1124 if (PHI->getIncomingBlock(i) == OldPred) 1125 PHI->setIncomingBlock(i, NewPred); 1126 } 1127 } 1128 } 1129 1130 bool LoopInterchangeTransform::adjustLoopBranches() { 1131 1132 DEBUG(dbgs() << "adjustLoopBranches called\n"); 1133 // Adjust the loop preheader 1134 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1135 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1136 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1137 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1138 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1139 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1140 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); 1141 BasicBlock *InnerLoopLatchPredecessor = 1142 InnerLoopLatch->getUniquePredecessor(); 1143 BasicBlock *InnerLoopLatchSuccessor; 1144 BasicBlock *OuterLoopLatchSuccessor; 1145 1146 BranchInst *OuterLoopLatchBI = 1147 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); 1148 BranchInst *InnerLoopLatchBI = 1149 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 1150 BranchInst *OuterLoopHeaderBI = 1151 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 1152 BranchInst *InnerLoopHeaderBI = 1153 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); 1154 1155 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || 1156 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || 1157 !InnerLoopHeaderBI) 1158 return false; 1159 1160 BranchInst *InnerLoopLatchPredecessorBI = 1161 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); 1162 BranchInst *OuterLoopPredecessorBI = 1163 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); 1164 1165 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) 1166 return false; 1167 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); 1168 if (!InnerLoopHeaderSuccessor) 1169 return false; 1170 1171 // Adjust Loop Preheader and headers 1172 1173 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors(); 1174 for (unsigned i = 0; i < NumSucc; ++i) { 1175 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader) 1176 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader); 1177 } 1178 1179 NumSucc = OuterLoopHeaderBI->getNumSuccessors(); 1180 for (unsigned i = 0; i < NumSucc; ++i) { 1181 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch) 1182 OuterLoopHeaderBI->setSuccessor(i, LoopExit); 1183 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader) 1184 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor); 1185 } 1186 1187 // Adjust reduction PHI's now that the incoming block has changed. 1188 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader, 1189 OuterLoopHeader); 1190 1191 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI); 1192 InnerLoopHeaderBI->eraseFromParent(); 1193 1194 // -------------Adjust loop latches----------- 1195 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) 1196 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); 1197 else 1198 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); 1199 1200 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors(); 1201 for (unsigned i = 0; i < NumSucc; ++i) { 1202 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch) 1203 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor); 1204 } 1205 1206 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with 1207 // the value and remove this PHI node from inner loop. 1208 SmallVector<PHINode *, 8> LcssaVec; 1209 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) { 1210 PHINode *LcssaPhi = cast<PHINode>(I); 1211 LcssaVec.push_back(LcssaPhi); 1212 } 1213 for (PHINode *P : LcssaVec) { 1214 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch); 1215 P->replaceAllUsesWith(Incoming); 1216 P->eraseFromParent(); 1217 } 1218 1219 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) 1220 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); 1221 else 1222 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); 1223 1224 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor) 1225 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor); 1226 else 1227 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor); 1228 1229 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch); 1230 1231 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) { 1232 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch); 1233 } else { 1234 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch); 1235 } 1236 1237 return true; 1238 } 1239 void LoopInterchangeTransform::adjustLoopPreheaders() { 1240 1241 // We have interchanged the preheaders so we need to interchange the data in 1242 // the preheader as well. 1243 // This is because the content of inner preheader was previously executed 1244 // inside the outer loop. 1245 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1246 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1247 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1248 BranchInst *InnerTermBI = 1249 cast<BranchInst>(InnerLoopPreHeader->getTerminator()); 1250 1251 // These instructions should now be executed inside the loop. 1252 // Move instruction into a new block after outer header. 1253 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); 1254 // These instructions were not executed previously in the loop so move them to 1255 // the older inner loop preheader. 1256 moveBBContents(OuterLoopPreHeader, InnerTermBI); 1257 } 1258 1259 bool LoopInterchangeTransform::adjustLoopLinks() { 1260 1261 // Adjust all branches in the inner and outer loop. 1262 bool Changed = adjustLoopBranches(); 1263 if (Changed) 1264 adjustLoopPreheaders(); 1265 return Changed; 1266 } 1267 1268 char LoopInterchange::ID = 0; 1269 INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", 1270 "Interchanges loops for cache reuse", false, false) 1271 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1272 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1273 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1274 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 1275 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 1276 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 1277 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 1278 1279 INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", 1280 "Interchanges loops for cache reuse", false, false) 1281 1282 Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } 1283