1 //===- LoopInterchange.cpp - Loop interchange pass-------------------------===// 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 // This Pass handles loop interchange transform. 10 // This pass interchanges loops to provide a more cache-friendly memory access 11 // patterns. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Scalar/LoopInterchange.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/Analysis/DependenceAnalysis.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/Analysis/LoopNestAnalysis.h" 23 #include "llvm/Analysis/LoopPass.h" 24 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DiagnosticInfo.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/InstrTypes.h" 34 #include "llvm/IR/Instruction.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/User.h" 37 #include "llvm/IR/Value.h" 38 #include "llvm/InitializePasses.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/Casting.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/raw_ostream.h" 45 #include "llvm/Transforms/Scalar.h" 46 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 47 #include "llvm/Transforms/Utils/LoopUtils.h" 48 #include <cassert> 49 #include <utility> 50 #include <vector> 51 52 using namespace llvm; 53 54 #define DEBUG_TYPE "loop-interchange" 55 56 STATISTIC(LoopsInterchanged, "Number of loops interchanged"); 57 58 static cl::opt<int> LoopInterchangeCostThreshold( 59 "loop-interchange-threshold", cl::init(0), cl::Hidden, 60 cl::desc("Interchange if you gain more than this number")); 61 62 namespace { 63 64 using LoopVector = SmallVector<Loop *, 8>; 65 66 // TODO: Check if we can use a sparse matrix here. 67 using CharMatrix = std::vector<std::vector<char>>; 68 69 } // end anonymous namespace 70 71 // Maximum number of dependencies that can be handled in the dependency matrix. 72 static const unsigned MaxMemInstrCount = 100; 73 74 // Maximum loop depth supported. 75 static const unsigned MaxLoopNestDepth = 10; 76 77 #ifdef DUMP_DEP_MATRICIES 78 static void printDepMatrix(CharMatrix &DepMatrix) { 79 for (auto &Row : DepMatrix) { 80 for (auto D : Row) 81 LLVM_DEBUG(dbgs() << D << " "); 82 LLVM_DEBUG(dbgs() << "\n"); 83 } 84 } 85 #endif 86 87 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, 88 Loop *L, DependenceInfo *DI) { 89 using ValueVector = SmallVector<Value *, 16>; 90 91 ValueVector MemInstr; 92 93 // For each block. 94 for (BasicBlock *BB : L->blocks()) { 95 // Scan the BB and collect legal loads and stores. 96 for (Instruction &I : *BB) { 97 if (!isa<Instruction>(I)) 98 return false; 99 if (auto *Ld = dyn_cast<LoadInst>(&I)) { 100 if (!Ld->isSimple()) 101 return false; 102 MemInstr.push_back(&I); 103 } else if (auto *St = dyn_cast<StoreInst>(&I)) { 104 if (!St->isSimple()) 105 return false; 106 MemInstr.push_back(&I); 107 } 108 } 109 } 110 111 LLVM_DEBUG(dbgs() << "Found " << MemInstr.size() 112 << " Loads and Stores to analyze\n"); 113 114 ValueVector::iterator I, IE, J, JE; 115 116 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { 117 for (J = I, JE = MemInstr.end(); J != JE; ++J) { 118 std::vector<char> Dep; 119 Instruction *Src = cast<Instruction>(*I); 120 Instruction *Dst = cast<Instruction>(*J); 121 if (Src == Dst) 122 continue; 123 // Ignore Input dependencies. 124 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) 125 continue; 126 // Track Output, Flow, and Anti dependencies. 127 if (auto D = DI->depends(Src, Dst, true)) { 128 assert(D->isOrdered() && "Expected an output, flow or anti dep."); 129 LLVM_DEBUG(StringRef DepType = 130 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output"; 131 dbgs() << "Found " << DepType 132 << " dependency between Src and Dst\n" 133 << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); 134 unsigned Levels = D->getLevels(); 135 char Direction; 136 for (unsigned II = 1; II <= Levels; ++II) { 137 const SCEV *Distance = D->getDistance(II); 138 const SCEVConstant *SCEVConst = 139 dyn_cast_or_null<SCEVConstant>(Distance); 140 if (SCEVConst) { 141 const ConstantInt *CI = SCEVConst->getValue(); 142 if (CI->isNegative()) 143 Direction = '<'; 144 else if (CI->isZero()) 145 Direction = '='; 146 else 147 Direction = '>'; 148 Dep.push_back(Direction); 149 } else if (D->isScalar(II)) { 150 Direction = 'S'; 151 Dep.push_back(Direction); 152 } else { 153 unsigned Dir = D->getDirection(II); 154 if (Dir == Dependence::DVEntry::LT || 155 Dir == Dependence::DVEntry::LE) 156 Direction = '<'; 157 else if (Dir == Dependence::DVEntry::GT || 158 Dir == Dependence::DVEntry::GE) 159 Direction = '>'; 160 else if (Dir == Dependence::DVEntry::EQ) 161 Direction = '='; 162 else 163 Direction = '*'; 164 Dep.push_back(Direction); 165 } 166 } 167 while (Dep.size() != Level) { 168 Dep.push_back('I'); 169 } 170 171 DepMatrix.push_back(Dep); 172 if (DepMatrix.size() > MaxMemInstrCount) { 173 LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount 174 << " dependencies inside loop\n"); 175 return false; 176 } 177 } 178 } 179 } 180 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 interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, 187 unsigned ToIndx) { 188 for (unsigned I = 0, E = DepMatrix.size(); I < E; ++I) 189 std::swap(DepMatrix[I][ToIndx], DepMatrix[I][FromIndx]); 190 } 191 192 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is 193 // '>' 194 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, 195 unsigned Column) { 196 for (unsigned i = 0; i <= Column; ++i) { 197 if (DepMatrix[Row][i] == '<') 198 return false; 199 if (DepMatrix[Row][i] == '>') 200 return true; 201 } 202 // All dependencies were '=','S' or 'I' 203 return false; 204 } 205 206 // Checks if no dependence exist in the dependency matrix in Row before Column. 207 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, 208 unsigned Column) { 209 for (unsigned i = 0; i < Column; ++i) { 210 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' && 211 DepMatrix[Row][i] != 'I') 212 return false; 213 } 214 return true; 215 } 216 217 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, 218 unsigned OuterLoopId, char InnerDep, 219 char OuterDep) { 220 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) 221 return false; 222 223 if (InnerDep == OuterDep) 224 return true; 225 226 // It is legal to interchange if and only if after interchange no row has a 227 // '>' direction as the leftmost non-'='. 228 229 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') 230 return true; 231 232 if (InnerDep == '<') 233 return true; 234 235 if (InnerDep == '>') { 236 // If OuterLoopId represents outermost loop then interchanging will make the 237 // 1st dependency as '>' 238 if (OuterLoopId == 0) 239 return false; 240 241 // If all dependencies before OuterloopId are '=','S'or 'I'. Then 242 // interchanging will result in this row having an outermost non '=' 243 // dependency of '>' 244 if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) 245 return true; 246 } 247 248 return false; 249 } 250 251 // Checks if it is legal to interchange 2 loops. 252 // [Theorem] A permutation of the loops in a perfect nest is legal if and only 253 // if the direction matrix, after the same permutation is applied to its 254 // columns, has no ">" direction as the leftmost non-"=" direction in any row. 255 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, 256 unsigned InnerLoopId, 257 unsigned OuterLoopId) { 258 unsigned NumRows = DepMatrix.size(); 259 // For each row check if it is valid to interchange. 260 for (unsigned Row = 0; Row < NumRows; ++Row) { 261 char InnerDep = DepMatrix[Row][InnerLoopId]; 262 char OuterDep = DepMatrix[Row][OuterLoopId]; 263 if (InnerDep == '*' || OuterDep == '*') 264 return false; 265 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) 266 return false; 267 } 268 return true; 269 } 270 271 static LoopVector populateWorklist(Loop &L) { 272 LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: " 273 << L.getHeader()->getParent()->getName() << " Loop: %" 274 << L.getHeader()->getName() << '\n'); 275 LoopVector LoopList; 276 Loop *CurrentLoop = &L; 277 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); 278 while (!Vec->empty()) { 279 // The current loop has multiple subloops in it hence it is not tightly 280 // nested. 281 // Discard all loops above it added into Worklist. 282 if (Vec->size() != 1) 283 return {}; 284 285 LoopList.push_back(CurrentLoop); 286 CurrentLoop = Vec->front(); 287 Vec = &CurrentLoop->getSubLoops(); 288 } 289 LoopList.push_back(CurrentLoop); 290 return LoopList; 291 } 292 293 namespace { 294 295 /// LoopInterchangeLegality checks if it is legal to interchange the loop. 296 class LoopInterchangeLegality { 297 public: 298 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 299 OptimizationRemarkEmitter *ORE) 300 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} 301 302 /// Check if the loops can be interchanged. 303 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, 304 CharMatrix &DepMatrix); 305 306 /// Discover induction PHIs in the header of \p L. Induction 307 /// PHIs are added to \p Inductions. 308 bool findInductions(Loop *L, SmallVectorImpl<PHINode *> &Inductions); 309 310 /// Check if the loop structure is understood. We do not handle triangular 311 /// loops for now. 312 bool isLoopStructureUnderstood(); 313 314 bool currentLimitations(); 315 316 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const { 317 return OuterInnerReductions; 318 } 319 320 const SmallVectorImpl<PHINode *> &getInnerLoopInductions() const { 321 return InnerLoopInductions; 322 } 323 324 private: 325 bool tightlyNested(Loop *Outer, Loop *Inner); 326 bool containsUnsafeInstructions(BasicBlock *BB); 327 328 /// Discover induction and reduction PHIs in the header of \p L. Induction 329 /// PHIs are added to \p Inductions, reductions are added to 330 /// OuterInnerReductions. When the outer loop is passed, the inner loop needs 331 /// to be passed as \p InnerLoop. 332 bool findInductionAndReductions(Loop *L, 333 SmallVector<PHINode *, 8> &Inductions, 334 Loop *InnerLoop); 335 336 Loop *OuterLoop; 337 Loop *InnerLoop; 338 339 ScalarEvolution *SE; 340 341 /// Interface to emit optimization remarks. 342 OptimizationRemarkEmitter *ORE; 343 344 /// Set of reduction PHIs taking part of a reduction across the inner and 345 /// outer loop. 346 SmallPtrSet<PHINode *, 4> OuterInnerReductions; 347 348 /// Set of inner loop induction PHIs 349 SmallVector<PHINode *, 8> InnerLoopInductions; 350 }; 351 352 /// LoopInterchangeProfitability checks if it is profitable to interchange the 353 /// loop. 354 class LoopInterchangeProfitability { 355 public: 356 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 357 OptimizationRemarkEmitter *ORE) 358 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} 359 360 /// Check if the loop interchange is profitable. 361 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, 362 CharMatrix &DepMatrix); 363 364 private: 365 int getInstrOrderCost(); 366 367 Loop *OuterLoop; 368 Loop *InnerLoop; 369 370 /// Scev analysis. 371 ScalarEvolution *SE; 372 373 /// Interface to emit optimization remarks. 374 OptimizationRemarkEmitter *ORE; 375 }; 376 377 /// LoopInterchangeTransform interchanges the loop. 378 class LoopInterchangeTransform { 379 public: 380 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 381 LoopInfo *LI, DominatorTree *DT, 382 const LoopInterchangeLegality &LIL) 383 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), LIL(LIL) {} 384 385 /// Interchange OuterLoop and InnerLoop. 386 bool transform(); 387 void restructureLoops(Loop *NewInner, Loop *NewOuter, 388 BasicBlock *OrigInnerPreHeader, 389 BasicBlock *OrigOuterPreHeader); 390 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); 391 392 private: 393 bool adjustLoopLinks(); 394 bool adjustLoopBranches(); 395 396 Loop *OuterLoop; 397 Loop *InnerLoop; 398 399 /// Scev analysis. 400 ScalarEvolution *SE; 401 402 LoopInfo *LI; 403 DominatorTree *DT; 404 405 const LoopInterchangeLegality &LIL; 406 }; 407 408 struct LoopInterchange { 409 ScalarEvolution *SE = nullptr; 410 LoopInfo *LI = nullptr; 411 DependenceInfo *DI = nullptr; 412 DominatorTree *DT = nullptr; 413 414 /// Interface to emit optimization remarks. 415 OptimizationRemarkEmitter *ORE; 416 417 LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI, 418 DominatorTree *DT, OptimizationRemarkEmitter *ORE) 419 : SE(SE), LI(LI), DI(DI), DT(DT), ORE(ORE) {} 420 421 bool run(Loop *L) { 422 if (L->getParentLoop()) 423 return false; 424 425 return processLoopList(populateWorklist(*L)); 426 } 427 428 bool run(LoopNest &LN) { 429 const auto &LoopList = LN.getLoops(); 430 for (unsigned I = 1; I < LoopList.size(); ++I) 431 if (LoopList[I]->getParentLoop() != LoopList[I - 1]) 432 return false; 433 return processLoopList(LoopList); 434 } 435 436 bool isComputableLoopNest(ArrayRef<Loop *> LoopList) { 437 for (Loop *L : LoopList) { 438 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); 439 if (isa<SCEVCouldNotCompute>(ExitCountOuter)) { 440 LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n"); 441 return false; 442 } 443 if (L->getNumBackEdges() != 1) { 444 LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); 445 return false; 446 } 447 if (!L->getExitingBlock()) { 448 LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n"); 449 return false; 450 } 451 } 452 return true; 453 } 454 455 unsigned selectLoopForInterchange(ArrayRef<Loop *> LoopList) { 456 // TODO: Add a better heuristic to select the loop to be interchanged based 457 // on the dependence matrix. Currently we select the innermost loop. 458 return LoopList.size() - 1; 459 } 460 461 bool processLoopList(ArrayRef<Loop *> LoopList) { 462 bool Changed = false; 463 unsigned LoopNestDepth = LoopList.size(); 464 if (LoopNestDepth < 2) { 465 LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); 466 return false; 467 } 468 if (LoopNestDepth > MaxLoopNestDepth) { 469 LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than " 470 << MaxLoopNestDepth << "\n"); 471 return false; 472 } 473 if (!isComputableLoopNest(LoopList)) { 474 LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); 475 return false; 476 } 477 478 LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth 479 << "\n"); 480 481 CharMatrix DependencyMatrix; 482 Loop *OuterMostLoop = *(LoopList.begin()); 483 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, 484 OuterMostLoop, DI)) { 485 LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n"); 486 return false; 487 } 488 #ifdef DUMP_DEP_MATRICIES 489 LLVM_DEBUG(dbgs() << "Dependence before interchange\n"); 490 printDepMatrix(DependencyMatrix); 491 #endif 492 493 // Get the Outermost loop exit. 494 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock(); 495 if (!LoopNestExit) { 496 LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block"); 497 return false; 498 } 499 500 unsigned SelecLoopId = selectLoopForInterchange(LoopList); 501 // Move the selected loop outwards to the best possible position. 502 Loop *LoopToBeInterchanged = LoopList[SelecLoopId]; 503 for (unsigned i = SelecLoopId; i > 0; i--) { 504 bool Interchanged = processLoop(LoopToBeInterchanged, LoopList[i - 1], i, 505 i - 1, DependencyMatrix); 506 if (!Interchanged) 507 return Changed; 508 // Update the DependencyMatrix 509 interChangeDependencies(DependencyMatrix, i, i - 1); 510 #ifdef DUMP_DEP_MATRICIES 511 LLVM_DEBUG(dbgs() << "Dependence after interchange\n"); 512 printDepMatrix(DependencyMatrix); 513 #endif 514 Changed |= Interchanged; 515 } 516 return Changed; 517 } 518 519 bool processLoop(Loop *InnerLoop, Loop *OuterLoop, unsigned InnerLoopId, 520 unsigned OuterLoopId, 521 std::vector<std::vector<char>> &DependencyMatrix) { 522 LLVM_DEBUG(dbgs() << "Processing InnerLoopId = " << InnerLoopId 523 << " and OuterLoopId = " << OuterLoopId << "\n"); 524 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE); 525 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { 526 LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n"); 527 return false; 528 } 529 LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n"); 530 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE); 531 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { 532 LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n"); 533 return false; 534 } 535 536 ORE->emit([&]() { 537 return OptimizationRemark(DEBUG_TYPE, "Interchanged", 538 InnerLoop->getStartLoc(), 539 InnerLoop->getHeader()) 540 << "Loop interchanged with enclosing loop."; 541 }); 542 543 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LIL); 544 LIT.transform(); 545 LLVM_DEBUG(dbgs() << "Loops interchanged.\n"); 546 LoopsInterchanged++; 547 548 assert(InnerLoop->isLCSSAForm(*DT) && 549 "Inner loop not left in LCSSA form after loop interchange!"); 550 assert(OuterLoop->isLCSSAForm(*DT) && 551 "Outer loop not left in LCSSA form after loop interchange!"); 552 553 return true; 554 } 555 }; 556 557 } // end anonymous namespace 558 559 bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) { 560 return any_of(*BB, [](const Instruction &I) { 561 return I.mayHaveSideEffects() || I.mayReadFromMemory(); 562 }); 563 } 564 565 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { 566 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 567 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 568 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 569 570 LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n"); 571 572 // A perfectly nested loop will not have any branch in between the outer and 573 // inner block i.e. outer header will branch to either inner preheader and 574 // outerloop latch. 575 BranchInst *OuterLoopHeaderBI = 576 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 577 if (!OuterLoopHeaderBI) 578 return false; 579 580 for (BasicBlock *Succ : successors(OuterLoopHeaderBI)) 581 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() && 582 Succ != OuterLoopLatch) 583 return false; 584 585 LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n"); 586 // We do not have any basic block in between now make sure the outer header 587 // and outer loop latch doesn't contain any unsafe instructions. 588 if (containsUnsafeInstructions(OuterLoopHeader) || 589 containsUnsafeInstructions(OuterLoopLatch)) 590 return false; 591 592 // Also make sure the inner loop preheader does not contain any unsafe 593 // instructions. Note that all instructions in the preheader will be moved to 594 // the outer loop header when interchanging. 595 if (InnerLoopPreHeader != OuterLoopHeader && 596 containsUnsafeInstructions(InnerLoopPreHeader)) 597 return false; 598 599 BasicBlock *InnerLoopExit = InnerLoop->getExitBlock(); 600 // Ensure the inner loop exit block flows to the outer loop latch possibly 601 // through empty blocks. 602 const BasicBlock &SuccInner = 603 LoopNest::skipEmptyBlockUntil(InnerLoopExit, OuterLoopLatch); 604 if (&SuccInner != OuterLoopLatch) { 605 LLVM_DEBUG(dbgs() << "Inner loop exit block " << *InnerLoopExit 606 << " does not lead to the outer loop latch.\n";); 607 return false; 608 } 609 // The inner loop exit block does flow to the outer loop latch and not some 610 // other BBs, now make sure it contains safe instructions, since it will be 611 // moved into the (new) inner loop after interchange. 612 if (containsUnsafeInstructions(InnerLoopExit)) 613 return false; 614 615 LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n"); 616 // We have a perfect loop nest. 617 return true; 618 } 619 620 bool LoopInterchangeLegality::isLoopStructureUnderstood() { 621 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); 622 for (PHINode *InnerInduction : InnerLoopInductions) { 623 unsigned Num = InnerInduction->getNumOperands(); 624 for (unsigned i = 0; i < Num; ++i) { 625 Value *Val = InnerInduction->getOperand(i); 626 if (isa<Constant>(Val)) 627 continue; 628 Instruction *I = dyn_cast<Instruction>(Val); 629 if (!I) 630 return false; 631 // TODO: Handle triangular loops. 632 // e.g. for(int i=0;i<N;i++) 633 // for(int j=i;j<N;j++) 634 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); 635 if (InnerInduction->getIncomingBlock(IncomBlockIndx) == 636 InnerLoopPreheader && 637 !OuterLoop->isLoopInvariant(I)) { 638 return false; 639 } 640 } 641 } 642 643 // TODO: Handle triangular loops of another form. 644 // e.g. for(int i=0;i<N;i++) 645 // for(int j=0;j<i;j++) 646 // or, 647 // for(int i=0;i<N;i++) 648 // for(int j=0;j*i<N;j++) 649 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 650 BranchInst *InnerLoopLatchBI = 651 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 652 if (!InnerLoopLatchBI->isConditional()) 653 return false; 654 if (CmpInst *InnerLoopCmp = 655 dyn_cast<CmpInst>(InnerLoopLatchBI->getCondition())) { 656 Value *Op0 = InnerLoopCmp->getOperand(0); 657 Value *Op1 = InnerLoopCmp->getOperand(1); 658 659 // LHS and RHS of the inner loop exit condition, e.g., 660 // in "for(int j=0;j<i;j++)", LHS is j and RHS is i. 661 Value *Left = nullptr; 662 Value *Right = nullptr; 663 664 // Check if V only involves inner loop induction variable. 665 // Return true if V is InnerInduction, or a cast from 666 // InnerInduction, or a binary operator that involves 667 // InnerInduction and a constant. 668 std::function<bool(Value *)> IsPathToInnerIndVar; 669 IsPathToInnerIndVar = [this, &IsPathToInnerIndVar](const Value *V) -> bool { 670 if (llvm::is_contained(InnerLoopInductions, V)) 671 return true; 672 if (isa<Constant>(V)) 673 return true; 674 const Instruction *I = dyn_cast<Instruction>(V); 675 if (!I) 676 return false; 677 if (isa<CastInst>(I)) 678 return IsPathToInnerIndVar(I->getOperand(0)); 679 if (isa<BinaryOperator>(I)) 680 return IsPathToInnerIndVar(I->getOperand(0)) && 681 IsPathToInnerIndVar(I->getOperand(1)); 682 return false; 683 }; 684 685 // In case of multiple inner loop indvars, it is okay if LHS and RHS 686 // are both inner indvar related variables. 687 if (IsPathToInnerIndVar(Op0) && IsPathToInnerIndVar(Op1)) 688 return true; 689 690 // Otherwise we check if the cmp instruction compares an inner indvar 691 // related variable (Left) with a outer loop invariant (Right). 692 if (IsPathToInnerIndVar(Op0) && !isa<Constant>(Op0)) { 693 Left = Op0; 694 Right = Op1; 695 } else if (IsPathToInnerIndVar(Op1) && !isa<Constant>(Op1)) { 696 Left = Op1; 697 Right = Op0; 698 } 699 700 if (Left == nullptr) 701 return false; 702 703 const SCEV *S = SE->getSCEV(Right); 704 if (!SE->isLoopInvariant(S, OuterLoop)) 705 return false; 706 } 707 708 return true; 709 } 710 711 // If SV is a LCSSA PHI node with a single incoming value, return the incoming 712 // value. 713 static Value *followLCSSA(Value *SV) { 714 PHINode *PHI = dyn_cast<PHINode>(SV); 715 if (!PHI) 716 return SV; 717 718 if (PHI->getNumIncomingValues() != 1) 719 return SV; 720 return followLCSSA(PHI->getIncomingValue(0)); 721 } 722 723 // Check V's users to see if it is involved in a reduction in L. 724 static PHINode *findInnerReductionPhi(Loop *L, Value *V) { 725 // Reduction variables cannot be constants. 726 if (isa<Constant>(V)) 727 return nullptr; 728 729 for (Value *User : V->users()) { 730 if (PHINode *PHI = dyn_cast<PHINode>(User)) { 731 if (PHI->getNumIncomingValues() == 1) 732 continue; 733 RecurrenceDescriptor RD; 734 if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) { 735 // Detect floating point reduction only when it can be reordered. 736 if (RD.getExactFPMathInst() != nullptr) 737 return nullptr; 738 return PHI; 739 } 740 return nullptr; 741 } 742 } 743 744 return nullptr; 745 } 746 747 bool LoopInterchangeLegality::findInductionAndReductions( 748 Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) { 749 if (!L->getLoopLatch() || !L->getLoopPredecessor()) 750 return false; 751 for (PHINode &PHI : L->getHeader()->phis()) { 752 RecurrenceDescriptor RD; 753 InductionDescriptor ID; 754 if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) 755 Inductions.push_back(&PHI); 756 else { 757 // PHIs in inner loops need to be part of a reduction in the outer loop, 758 // discovered when checking the PHIs of the outer loop earlier. 759 if (!InnerLoop) { 760 if (!OuterInnerReductions.count(&PHI)) { 761 LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions " 762 "across the outer loop.\n"); 763 return false; 764 } 765 } else { 766 assert(PHI.getNumIncomingValues() == 2 && 767 "Phis in loop header should have exactly 2 incoming values"); 768 // Check if we have a PHI node in the outer loop that has a reduction 769 // result from the inner loop as an incoming value. 770 Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch())); 771 PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V); 772 if (!InnerRedPhi || 773 !llvm::is_contained(InnerRedPhi->incoming_values(), &PHI)) { 774 LLVM_DEBUG( 775 dbgs() 776 << "Failed to recognize PHI as an induction or reduction.\n"); 777 return false; 778 } 779 OuterInnerReductions.insert(&PHI); 780 OuterInnerReductions.insert(InnerRedPhi); 781 } 782 } 783 } 784 return true; 785 } 786 787 // This function indicates the current limitations in the transform as a result 788 // of which we do not proceed. 789 bool LoopInterchangeLegality::currentLimitations() { 790 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 791 792 // transform currently expects the loop latches to also be the exiting 793 // blocks. 794 if (InnerLoop->getExitingBlock() != InnerLoopLatch || 795 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() || 796 !isa<BranchInst>(InnerLoopLatch->getTerminator()) || 797 !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) { 798 LLVM_DEBUG( 799 dbgs() << "Loops where the latch is not the exiting block are not" 800 << " supported currently.\n"); 801 ORE->emit([&]() { 802 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch", 803 OuterLoop->getStartLoc(), 804 OuterLoop->getHeader()) 805 << "Loops where the latch is not the exiting block cannot be" 806 " interchange currently."; 807 }); 808 return true; 809 } 810 811 SmallVector<PHINode *, 8> Inductions; 812 if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) { 813 LLVM_DEBUG( 814 dbgs() << "Only outer loops with induction or reduction PHI nodes " 815 << "are supported currently.\n"); 816 ORE->emit([&]() { 817 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter", 818 OuterLoop->getStartLoc(), 819 OuterLoop->getHeader()) 820 << "Only outer loops with induction or reduction PHI nodes can be" 821 " interchanged currently."; 822 }); 823 return true; 824 } 825 826 Inductions.clear(); 827 if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) { 828 LLVM_DEBUG( 829 dbgs() << "Only inner loops with induction or reduction PHI nodes " 830 << "are supported currently.\n"); 831 ORE->emit([&]() { 832 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner", 833 InnerLoop->getStartLoc(), 834 InnerLoop->getHeader()) 835 << "Only inner loops with induction or reduction PHI nodes can be" 836 " interchange currently."; 837 }); 838 return true; 839 } 840 841 // TODO: Triangular loops are not handled for now. 842 if (!isLoopStructureUnderstood()) { 843 LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n"); 844 ORE->emit([&]() { 845 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner", 846 InnerLoop->getStartLoc(), 847 InnerLoop->getHeader()) 848 << "Inner loop structure not understood currently."; 849 }); 850 return true; 851 } 852 853 return false; 854 } 855 856 bool LoopInterchangeLegality::findInductions( 857 Loop *L, SmallVectorImpl<PHINode *> &Inductions) { 858 for (PHINode &PHI : L->getHeader()->phis()) { 859 InductionDescriptor ID; 860 if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) 861 Inductions.push_back(&PHI); 862 } 863 return !Inductions.empty(); 864 } 865 866 // We currently only support LCSSA PHI nodes in the inner loop exit, if their 867 // users are either reduction PHIs or PHIs outside the outer loop (which means 868 // the we are only interested in the final value after the loop). 869 static bool 870 areInnerLoopExitPHIsSupported(Loop *InnerL, Loop *OuterL, 871 SmallPtrSetImpl<PHINode *> &Reductions) { 872 BasicBlock *InnerExit = OuterL->getUniqueExitBlock(); 873 for (PHINode &PHI : InnerExit->phis()) { 874 // Reduction lcssa phi will have only 1 incoming block that from loop latch. 875 if (PHI.getNumIncomingValues() > 1) 876 return false; 877 if (any_of(PHI.users(), [&Reductions, OuterL](User *U) { 878 PHINode *PN = dyn_cast<PHINode>(U); 879 return !PN || 880 (!Reductions.count(PN) && OuterL->contains(PN->getParent())); 881 })) { 882 return false; 883 } 884 } 885 return true; 886 } 887 888 // We currently support LCSSA PHI nodes in the outer loop exit, if their 889 // incoming values do not come from the outer loop latch or if the 890 // outer loop latch has a single predecessor. In that case, the value will 891 // be available if both the inner and outer loop conditions are true, which 892 // will still be true after interchanging. If we have multiple predecessor, 893 // that may not be the case, e.g. because the outer loop latch may be executed 894 // if the inner loop is not executed. 895 static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) { 896 BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock(); 897 for (PHINode &PHI : LoopNestExit->phis()) { 898 for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) { 899 Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i)); 900 if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch()) 901 continue; 902 903 // The incoming value is defined in the outer loop latch. Currently we 904 // only support that in case the outer loop latch has a single predecessor. 905 // This guarantees that the outer loop latch is executed if and only if 906 // the inner loop is executed (because tightlyNested() guarantees that the 907 // outer loop header only branches to the inner loop or the outer loop 908 // latch). 909 // FIXME: We could weaken this logic and allow multiple predecessors, 910 // if the values are produced outside the loop latch. We would need 911 // additional logic to update the PHI nodes in the exit block as 912 // well. 913 if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr) 914 return false; 915 } 916 } 917 return true; 918 } 919 920 // In case of multi-level nested loops, it may occur that lcssa phis exist in 921 // the latch of InnerLoop, i.e., when defs of the incoming values are further 922 // inside the loopnest. Sometimes those incoming values are not available 923 // after interchange, since the original inner latch will become the new outer 924 // latch which may have predecessor paths that do not include those incoming 925 // values. 926 // TODO: Handle transformation of lcssa phis in the InnerLoop latch in case of 927 // multi-level loop nests. 928 static bool areInnerLoopLatchPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) { 929 if (InnerLoop->getSubLoops().empty()) 930 return true; 931 // If the original outer latch has only one predecessor, then values defined 932 // further inside the looploop, e.g., in the innermost loop, will be available 933 // at the new outer latch after interchange. 934 if (OuterLoop->getLoopLatch()->getUniquePredecessor() != nullptr) 935 return true; 936 937 // The outer latch has more than one predecessors, i.e., the inner 938 // exit and the inner header. 939 // PHI nodes in the inner latch are lcssa phis where the incoming values 940 // are defined further inside the loopnest. Check if those phis are used 941 // in the original inner latch. If that is the case then bail out since 942 // those incoming values may not be available at the new outer latch. 943 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 944 for (PHINode &PHI : InnerLoopLatch->phis()) { 945 for (auto *U : PHI.users()) { 946 Instruction *UI = cast<Instruction>(U); 947 if (InnerLoopLatch == UI->getParent()) 948 return false; 949 } 950 } 951 return true; 952 } 953 954 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, 955 unsigned OuterLoopId, 956 CharMatrix &DepMatrix) { 957 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { 958 LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId 959 << " and OuterLoopId = " << OuterLoopId 960 << " due to dependence\n"); 961 ORE->emit([&]() { 962 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence", 963 InnerLoop->getStartLoc(), 964 InnerLoop->getHeader()) 965 << "Cannot interchange loops due to dependences."; 966 }); 967 return false; 968 } 969 // Check if outer and inner loop contain legal instructions only. 970 for (auto *BB : OuterLoop->blocks()) 971 for (Instruction &I : BB->instructionsWithoutDebug()) 972 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 973 // readnone functions do not prevent interchanging. 974 if (CI->onlyWritesMemory()) 975 continue; 976 LLVM_DEBUG( 977 dbgs() << "Loops with call instructions cannot be interchanged " 978 << "safely."); 979 ORE->emit([&]() { 980 return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst", 981 CI->getDebugLoc(), 982 CI->getParent()) 983 << "Cannot interchange loops due to call instruction."; 984 }); 985 986 return false; 987 } 988 989 if (!findInductions(InnerLoop, InnerLoopInductions)) { 990 LLVM_DEBUG(dbgs() << "Cound not find inner loop induction variables.\n"); 991 return false; 992 } 993 994 if (!areInnerLoopLatchPHIsSupported(OuterLoop, InnerLoop)) { 995 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop latch.\n"); 996 ORE->emit([&]() { 997 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerLatchPHI", 998 InnerLoop->getStartLoc(), 999 InnerLoop->getHeader()) 1000 << "Cannot interchange loops because unsupported PHI nodes found " 1001 "in inner loop latch."; 1002 }); 1003 return false; 1004 } 1005 1006 // TODO: The loops could not be interchanged due to current limitations in the 1007 // transform module. 1008 if (currentLimitations()) { 1009 LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n"); 1010 return false; 1011 } 1012 1013 // Check if the loops are tightly nested. 1014 if (!tightlyNested(OuterLoop, InnerLoop)) { 1015 LLVM_DEBUG(dbgs() << "Loops not tightly nested\n"); 1016 ORE->emit([&]() { 1017 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested", 1018 InnerLoop->getStartLoc(), 1019 InnerLoop->getHeader()) 1020 << "Cannot interchange loops because they are not tightly " 1021 "nested."; 1022 }); 1023 return false; 1024 } 1025 1026 if (!areInnerLoopExitPHIsSupported(OuterLoop, InnerLoop, 1027 OuterInnerReductions)) { 1028 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop exit.\n"); 1029 ORE->emit([&]() { 1030 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI", 1031 InnerLoop->getStartLoc(), 1032 InnerLoop->getHeader()) 1033 << "Found unsupported PHI node in loop exit."; 1034 }); 1035 return false; 1036 } 1037 1038 if (!areOuterLoopExitPHIsSupported(OuterLoop, InnerLoop)) { 1039 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n"); 1040 ORE->emit([&]() { 1041 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI", 1042 OuterLoop->getStartLoc(), 1043 OuterLoop->getHeader()) 1044 << "Found unsupported PHI node in loop exit."; 1045 }); 1046 return false; 1047 } 1048 1049 return true; 1050 } 1051 1052 int LoopInterchangeProfitability::getInstrOrderCost() { 1053 unsigned GoodOrder, BadOrder; 1054 BadOrder = GoodOrder = 0; 1055 for (BasicBlock *BB : InnerLoop->blocks()) { 1056 for (Instruction &Ins : *BB) { 1057 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { 1058 unsigned NumOp = GEP->getNumOperands(); 1059 bool FoundInnerInduction = false; 1060 bool FoundOuterInduction = false; 1061 for (unsigned i = 0; i < NumOp; ++i) { 1062 // Skip operands that are not SCEV-able. 1063 if (!SE->isSCEVable(GEP->getOperand(i)->getType())) 1064 continue; 1065 1066 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); 1067 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); 1068 if (!AR) 1069 continue; 1070 1071 // If we find the inner induction after an outer induction e.g. 1072 // for(int i=0;i<N;i++) 1073 // for(int j=0;j<N;j++) 1074 // A[i][j] = A[i-1][j-1]+k; 1075 // then it is a good order. 1076 if (AR->getLoop() == InnerLoop) { 1077 // We found an InnerLoop induction after OuterLoop induction. It is 1078 // a good order. 1079 FoundInnerInduction = true; 1080 if (FoundOuterInduction) { 1081 GoodOrder++; 1082 break; 1083 } 1084 } 1085 // If we find the outer induction after an inner induction e.g. 1086 // for(int i=0;i<N;i++) 1087 // for(int j=0;j<N;j++) 1088 // A[j][i] = A[j-1][i-1]+k; 1089 // then it is a bad order. 1090 if (AR->getLoop() == OuterLoop) { 1091 // We found an OuterLoop induction after InnerLoop induction. It is 1092 // a bad order. 1093 FoundOuterInduction = true; 1094 if (FoundInnerInduction) { 1095 BadOrder++; 1096 break; 1097 } 1098 } 1099 } 1100 } 1101 } 1102 } 1103 return GoodOrder - BadOrder; 1104 } 1105 1106 static bool isProfitableForVectorization(unsigned InnerLoopId, 1107 unsigned OuterLoopId, 1108 CharMatrix &DepMatrix) { 1109 // TODO: Improve this heuristic to catch more cases. 1110 // If the inner loop is loop independent or doesn't carry any dependency it is 1111 // profitable to move this to outer position. 1112 for (auto &Row : DepMatrix) { 1113 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I') 1114 return false; 1115 // TODO: We need to improve this heuristic. 1116 if (Row[OuterLoopId] != '=') 1117 return false; 1118 } 1119 // If outer loop has dependence and inner loop is loop independent then it is 1120 // profitable to interchange to enable parallelism. 1121 // If there are no dependences, interchanging will not improve anything. 1122 return !DepMatrix.empty(); 1123 } 1124 1125 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, 1126 unsigned OuterLoopId, 1127 CharMatrix &DepMatrix) { 1128 // TODO: Add better profitability checks. 1129 // e.g 1130 // 1) Construct dependency matrix and move the one with no loop carried dep 1131 // inside to enable vectorization. 1132 1133 // This is rough cost estimation algorithm. It counts the good and bad order 1134 // of induction variables in the instruction and allows reordering if number 1135 // of bad orders is more than good. 1136 int Cost = getInstrOrderCost(); 1137 LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n"); 1138 if (Cost < -LoopInterchangeCostThreshold) 1139 return true; 1140 1141 // It is not profitable as per current cache profitability model. But check if 1142 // we can move this loop outside to improve parallelism. 1143 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix)) 1144 return true; 1145 1146 ORE->emit([&]() { 1147 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable", 1148 InnerLoop->getStartLoc(), 1149 InnerLoop->getHeader()) 1150 << "Interchanging loops is too costly (cost=" 1151 << ore::NV("Cost", Cost) << ", threshold=" 1152 << ore::NV("Threshold", LoopInterchangeCostThreshold) 1153 << ") and it does not improve parallelism."; 1154 }); 1155 return false; 1156 } 1157 1158 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, 1159 Loop *InnerLoop) { 1160 for (Loop *L : *OuterLoop) 1161 if (L == InnerLoop) { 1162 OuterLoop->removeChildLoop(L); 1163 return; 1164 } 1165 llvm_unreachable("Couldn't find loop"); 1166 } 1167 1168 /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the 1169 /// new inner and outer loop after interchanging: NewInner is the original 1170 /// outer loop and NewOuter is the original inner loop. 1171 /// 1172 /// Before interchanging, we have the following structure 1173 /// Outer preheader 1174 // Outer header 1175 // Inner preheader 1176 // Inner header 1177 // Inner body 1178 // Inner latch 1179 // outer bbs 1180 // Outer latch 1181 // 1182 // After interchanging: 1183 // Inner preheader 1184 // Inner header 1185 // Outer preheader 1186 // Outer header 1187 // Inner body 1188 // outer bbs 1189 // Outer latch 1190 // Inner latch 1191 void LoopInterchangeTransform::restructureLoops( 1192 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader, 1193 BasicBlock *OrigOuterPreHeader) { 1194 Loop *OuterLoopParent = OuterLoop->getParentLoop(); 1195 // The original inner loop preheader moves from the new inner loop to 1196 // the parent loop, if there is one. 1197 NewInner->removeBlockFromLoop(OrigInnerPreHeader); 1198 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent); 1199 1200 // Switch the loop levels. 1201 if (OuterLoopParent) { 1202 // Remove the loop from its parent loop. 1203 removeChildLoop(OuterLoopParent, NewInner); 1204 removeChildLoop(NewInner, NewOuter); 1205 OuterLoopParent->addChildLoop(NewOuter); 1206 } else { 1207 removeChildLoop(NewInner, NewOuter); 1208 LI->changeTopLevelLoop(NewInner, NewOuter); 1209 } 1210 while (!NewOuter->isInnermost()) 1211 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin())); 1212 NewOuter->addChildLoop(NewInner); 1213 1214 // BBs from the original inner loop. 1215 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks()); 1216 1217 // Add BBs from the original outer loop to the original inner loop (excluding 1218 // BBs already in inner loop) 1219 for (BasicBlock *BB : NewInner->blocks()) 1220 if (LI->getLoopFor(BB) == NewInner) 1221 NewOuter->addBlockEntry(BB); 1222 1223 // Now remove inner loop header and latch from the new inner loop and move 1224 // other BBs (the loop body) to the new inner loop. 1225 BasicBlock *OuterHeader = NewOuter->getHeader(); 1226 BasicBlock *OuterLatch = NewOuter->getLoopLatch(); 1227 for (BasicBlock *BB : OrigInnerBBs) { 1228 // Nothing will change for BBs in child loops. 1229 if (LI->getLoopFor(BB) != NewOuter) 1230 continue; 1231 // Remove the new outer loop header and latch from the new inner loop. 1232 if (BB == OuterHeader || BB == OuterLatch) 1233 NewInner->removeBlockFromLoop(BB); 1234 else 1235 LI->changeLoopFor(BB, NewInner); 1236 } 1237 1238 // The preheader of the original outer loop becomes part of the new 1239 // outer loop. 1240 NewOuter->addBlockEntry(OrigOuterPreHeader); 1241 LI->changeLoopFor(OrigOuterPreHeader, NewOuter); 1242 1243 // Tell SE that we move the loops around. 1244 SE->forgetLoop(NewOuter); 1245 SE->forgetLoop(NewInner); 1246 } 1247 1248 bool LoopInterchangeTransform::transform() { 1249 bool Transformed = false; 1250 1251 if (InnerLoop->getSubLoops().empty()) { 1252 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1253 LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n"); 1254 auto &InductionPHIs = LIL.getInnerLoopInductions(); 1255 if (InductionPHIs.empty()) { 1256 LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); 1257 return false; 1258 } 1259 1260 SmallVector<Instruction *, 8> InnerIndexVarList; 1261 for (PHINode *CurInductionPHI : InductionPHIs) { 1262 if (CurInductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) 1263 InnerIndexVarList.push_back( 1264 dyn_cast<Instruction>(CurInductionPHI->getIncomingValue(1))); 1265 else 1266 InnerIndexVarList.push_back( 1267 dyn_cast<Instruction>(CurInductionPHI->getIncomingValue(0))); 1268 } 1269 1270 // Create a new latch block for the inner loop. We split at the 1271 // current latch's terminator and then move the condition and all 1272 // operands that are not either loop-invariant or the induction PHI into the 1273 // new latch block. 1274 BasicBlock *NewLatch = 1275 SplitBlock(InnerLoop->getLoopLatch(), 1276 InnerLoop->getLoopLatch()->getTerminator(), DT, LI); 1277 1278 SmallSetVector<Instruction *, 4> WorkList; 1279 unsigned i = 0; 1280 auto MoveInstructions = [&i, &WorkList, this, &InductionPHIs, NewLatch]() { 1281 for (; i < WorkList.size(); i++) { 1282 // Duplicate instruction and move it the new latch. Update uses that 1283 // have been moved. 1284 Instruction *NewI = WorkList[i]->clone(); 1285 NewI->insertBefore(NewLatch->getFirstNonPHI()); 1286 assert(!NewI->mayHaveSideEffects() && 1287 "Moving instructions with side-effects may change behavior of " 1288 "the loop nest!"); 1289 for (Use &U : llvm::make_early_inc_range(WorkList[i]->uses())) { 1290 Instruction *UserI = cast<Instruction>(U.getUser()); 1291 if (!InnerLoop->contains(UserI->getParent()) || 1292 UserI->getParent() == NewLatch || 1293 llvm::is_contained(InductionPHIs, UserI)) 1294 U.set(NewI); 1295 } 1296 // Add operands of moved instruction to the worklist, except if they are 1297 // outside the inner loop or are the induction PHI. 1298 for (Value *Op : WorkList[i]->operands()) { 1299 Instruction *OpI = dyn_cast<Instruction>(Op); 1300 if (!OpI || 1301 this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop || 1302 llvm::is_contained(InductionPHIs, OpI)) 1303 continue; 1304 WorkList.insert(OpI); 1305 } 1306 } 1307 }; 1308 1309 // FIXME: Should we interchange when we have a constant condition? 1310 Instruction *CondI = dyn_cast<Instruction>( 1311 cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator()) 1312 ->getCondition()); 1313 if (CondI) 1314 WorkList.insert(CondI); 1315 MoveInstructions(); 1316 for (Instruction *InnerIndexVar : InnerIndexVarList) 1317 WorkList.insert(cast<Instruction>(InnerIndexVar)); 1318 MoveInstructions(); 1319 1320 // Splits the inner loops phi nodes out into a separate basic block. 1321 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1322 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); 1323 LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n"); 1324 } 1325 1326 // Instructions in the original inner loop preheader may depend on values 1327 // defined in the outer loop header. Move them there, because the original 1328 // inner loop preheader will become the entry into the interchanged loop nest. 1329 // Currently we move all instructions and rely on LICM to move invariant 1330 // instructions outside the loop nest. 1331 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1332 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1333 if (InnerLoopPreHeader != OuterLoopHeader) { 1334 SmallPtrSet<Instruction *, 4> NeedsMoving; 1335 for (Instruction &I : 1336 make_early_inc_range(make_range(InnerLoopPreHeader->begin(), 1337 std::prev(InnerLoopPreHeader->end())))) 1338 I.moveBefore(OuterLoopHeader->getTerminator()); 1339 } 1340 1341 Transformed |= adjustLoopLinks(); 1342 if (!Transformed) { 1343 LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n"); 1344 return false; 1345 } 1346 1347 return true; 1348 } 1349 1350 /// \brief Move all instructions except the terminator from FromBB right before 1351 /// InsertBefore 1352 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { 1353 auto &ToList = InsertBefore->getParent()->getInstList(); 1354 auto &FromList = FromBB->getInstList(); 1355 1356 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), 1357 FromBB->getTerminator()->getIterator()); 1358 } 1359 1360 /// Swap instructions between \p BB1 and \p BB2 but keep terminators intact. 1361 static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2) { 1362 // Save all non-terminator instructions of BB1 into TempInstrs and unlink them 1363 // from BB1 afterwards. 1364 auto Iter = map_range(*BB1, [](Instruction &I) { return &I; }); 1365 SmallVector<Instruction *, 4> TempInstrs(Iter.begin(), std::prev(Iter.end())); 1366 for (Instruction *I : TempInstrs) 1367 I->removeFromParent(); 1368 1369 // Move instructions from BB2 to BB1. 1370 moveBBContents(BB2, BB1->getTerminator()); 1371 1372 // Move instructions from TempInstrs to BB2. 1373 for (Instruction *I : TempInstrs) 1374 I->insertBefore(BB2->getTerminator()); 1375 } 1376 1377 // Update BI to jump to NewBB instead of OldBB. Records updates to the 1378 // dominator tree in DTUpdates. If \p MustUpdateOnce is true, assert that 1379 // \p OldBB is exactly once in BI's successor list. 1380 static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, 1381 BasicBlock *NewBB, 1382 std::vector<DominatorTree::UpdateType> &DTUpdates, 1383 bool MustUpdateOnce = true) { 1384 assert((!MustUpdateOnce || 1385 llvm::count_if(successors(BI), 1386 [OldBB](BasicBlock *BB) { 1387 return BB == OldBB; 1388 }) == 1) && "BI must jump to OldBB exactly once."); 1389 bool Changed = false; 1390 for (Use &Op : BI->operands()) 1391 if (Op == OldBB) { 1392 Op.set(NewBB); 1393 Changed = true; 1394 } 1395 1396 if (Changed) { 1397 DTUpdates.push_back( 1398 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB}); 1399 DTUpdates.push_back( 1400 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB}); 1401 } 1402 assert(Changed && "Expected a successor to be updated"); 1403 } 1404 1405 // Move Lcssa PHIs to the right place. 1406 static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, 1407 BasicBlock *InnerLatch, BasicBlock *OuterHeader, 1408 BasicBlock *OuterLatch, BasicBlock *OuterExit, 1409 Loop *InnerLoop, LoopInfo *LI) { 1410 1411 // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are 1412 // defined either in the header or latch. Those blocks will become header and 1413 // latch of the new outer loop, and the only possible users can PHI nodes 1414 // in the exit block of the loop nest or the outer loop header (reduction 1415 // PHIs, in that case, the incoming value must be defined in the inner loop 1416 // header). We can just substitute the user with the incoming value and remove 1417 // the PHI. 1418 for (PHINode &P : make_early_inc_range(InnerExit->phis())) { 1419 assert(P.getNumIncomingValues() == 1 && 1420 "Only loops with a single exit are supported!"); 1421 1422 // Incoming values are guaranteed be instructions currently. 1423 auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch)); 1424 // Skip phis with incoming values from the inner loop body, excluding the 1425 // header and latch. 1426 if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader) 1427 continue; 1428 1429 assert(all_of(P.users(), 1430 [OuterHeader, OuterExit, IncI, InnerHeader](User *U) { 1431 return (cast<PHINode>(U)->getParent() == OuterHeader && 1432 IncI->getParent() == InnerHeader) || 1433 cast<PHINode>(U)->getParent() == OuterExit; 1434 }) && 1435 "Can only replace phis iff the uses are in the loop nest exit or " 1436 "the incoming value is defined in the inner header (it will " 1437 "dominate all loop blocks after interchanging)"); 1438 P.replaceAllUsesWith(IncI); 1439 P.eraseFromParent(); 1440 } 1441 1442 SmallVector<PHINode *, 8> LcssaInnerExit; 1443 for (PHINode &P : InnerExit->phis()) 1444 LcssaInnerExit.push_back(&P); 1445 1446 SmallVector<PHINode *, 8> LcssaInnerLatch; 1447 for (PHINode &P : InnerLatch->phis()) 1448 LcssaInnerLatch.push_back(&P); 1449 1450 // Lcssa PHIs for values used outside the inner loop are in InnerExit. 1451 // If a PHI node has users outside of InnerExit, it has a use outside the 1452 // interchanged loop and we have to preserve it. We move these to 1453 // InnerLatch, which will become the new exit block for the innermost 1454 // loop after interchanging. 1455 for (PHINode *P : LcssaInnerExit) 1456 P->moveBefore(InnerLatch->getFirstNonPHI()); 1457 1458 // If the inner loop latch contains LCSSA PHIs, those come from a child loop 1459 // and we have to move them to the new inner latch. 1460 for (PHINode *P : LcssaInnerLatch) 1461 P->moveBefore(InnerExit->getFirstNonPHI()); 1462 1463 // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have 1464 // incoming values defined in the outer loop, we have to add a new PHI 1465 // in the inner loop latch, which became the exit block of the outer loop, 1466 // after interchanging. 1467 if (OuterExit) { 1468 for (PHINode &P : OuterExit->phis()) { 1469 if (P.getNumIncomingValues() != 1) 1470 continue; 1471 // Skip Phis with incoming values defined in the inner loop. Those should 1472 // already have been updated. 1473 auto I = dyn_cast<Instruction>(P.getIncomingValue(0)); 1474 if (!I || LI->getLoopFor(I->getParent()) == InnerLoop) 1475 continue; 1476 1477 PHINode *NewPhi = dyn_cast<PHINode>(P.clone()); 1478 NewPhi->setIncomingValue(0, P.getIncomingValue(0)); 1479 NewPhi->setIncomingBlock(0, OuterLatch); 1480 // We might have incoming edges from other BBs, i.e., the original outer 1481 // header. 1482 for (auto *Pred : predecessors(InnerLatch)) { 1483 if (Pred == OuterLatch) 1484 continue; 1485 NewPhi->addIncoming(P.getIncomingValue(0), Pred); 1486 } 1487 NewPhi->insertBefore(InnerLatch->getFirstNonPHI()); 1488 P.setIncomingValue(0, NewPhi); 1489 } 1490 } 1491 1492 // Now adjust the incoming blocks for the LCSSA PHIs. 1493 // For PHIs moved from Inner's exit block, we need to replace Inner's latch 1494 // with the new latch. 1495 InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch); 1496 } 1497 1498 bool LoopInterchangeTransform::adjustLoopBranches() { 1499 LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n"); 1500 std::vector<DominatorTree::UpdateType> DTUpdates; 1501 1502 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1503 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1504 1505 assert(OuterLoopPreHeader != OuterLoop->getHeader() && 1506 InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader && 1507 InnerLoopPreHeader && "Guaranteed by loop-simplify form"); 1508 // Ensure that both preheaders do not contain PHI nodes and have single 1509 // predecessors. This allows us to move them easily. We use 1510 // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing 1511 // preheaders do not satisfy those conditions. 1512 if (isa<PHINode>(OuterLoopPreHeader->begin()) || 1513 !OuterLoopPreHeader->getUniquePredecessor()) 1514 OuterLoopPreHeader = 1515 InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true); 1516 if (InnerLoopPreHeader == OuterLoop->getHeader()) 1517 InnerLoopPreHeader = 1518 InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true); 1519 1520 // Adjust the loop preheader 1521 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1522 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1523 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1524 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1525 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); 1526 BasicBlock *InnerLoopLatchPredecessor = 1527 InnerLoopLatch->getUniquePredecessor(); 1528 BasicBlock *InnerLoopLatchSuccessor; 1529 BasicBlock *OuterLoopLatchSuccessor; 1530 1531 BranchInst *OuterLoopLatchBI = 1532 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); 1533 BranchInst *InnerLoopLatchBI = 1534 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 1535 BranchInst *OuterLoopHeaderBI = 1536 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 1537 BranchInst *InnerLoopHeaderBI = 1538 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); 1539 1540 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || 1541 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || 1542 !InnerLoopHeaderBI) 1543 return false; 1544 1545 BranchInst *InnerLoopLatchPredecessorBI = 1546 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); 1547 BranchInst *OuterLoopPredecessorBI = 1548 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); 1549 1550 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) 1551 return false; 1552 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); 1553 if (!InnerLoopHeaderSuccessor) 1554 return false; 1555 1556 // Adjust Loop Preheader and headers. 1557 // The branches in the outer loop predecessor and the outer loop header can 1558 // be unconditional branches or conditional branches with duplicates. Consider 1559 // this when updating the successors. 1560 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader, 1561 InnerLoopPreHeader, DTUpdates, /*MustUpdateOnce=*/false); 1562 // The outer loop header might or might not branch to the outer latch. 1563 // We are guaranteed to branch to the inner loop preheader. 1564 if (llvm::is_contained(OuterLoopHeaderBI->successors(), OuterLoopLatch)) { 1565 // In this case the outerLoopHeader should branch to the InnerLoopLatch. 1566 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, InnerLoopLatch, 1567 DTUpdates, 1568 /*MustUpdateOnce=*/false); 1569 } 1570 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader, 1571 InnerLoopHeaderSuccessor, DTUpdates, 1572 /*MustUpdateOnce=*/false); 1573 1574 // Adjust reduction PHI's now that the incoming block has changed. 1575 InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader, 1576 OuterLoopHeader); 1577 1578 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor, 1579 OuterLoopPreHeader, DTUpdates); 1580 1581 // -------------Adjust loop latches----------- 1582 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) 1583 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); 1584 else 1585 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); 1586 1587 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch, 1588 InnerLoopLatchSuccessor, DTUpdates); 1589 1590 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) 1591 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); 1592 else 1593 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); 1594 1595 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor, 1596 OuterLoopLatchSuccessor, DTUpdates); 1597 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch, 1598 DTUpdates); 1599 1600 DT->applyUpdates(DTUpdates); 1601 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader, 1602 OuterLoopPreHeader); 1603 1604 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch, 1605 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock(), 1606 InnerLoop, LI); 1607 // For PHIs in the exit block of the outer loop, outer's latch has been 1608 // replaced by Inners'. 1609 OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); 1610 1611 auto &OuterInnerReductions = LIL.getOuterInnerReductions(); 1612 // Now update the reduction PHIs in the inner and outer loop headers. 1613 SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs; 1614 for (PHINode &PHI : InnerLoopHeader->phis()) 1615 if (OuterInnerReductions.contains(&PHI)) 1616 InnerLoopPHIs.push_back(&PHI); 1617 1618 for (PHINode &PHI : OuterLoopHeader->phis()) 1619 if (OuterInnerReductions.contains(&PHI)) 1620 OuterLoopPHIs.push_back(&PHI); 1621 1622 // Now move the remaining reduction PHIs from outer to inner loop header and 1623 // vice versa. The PHI nodes must be part of a reduction across the inner and 1624 // outer loop and all the remains to do is and updating the incoming blocks. 1625 for (PHINode *PHI : OuterLoopPHIs) { 1626 LLVM_DEBUG(dbgs() << "Outer loop reduction PHIs:\n"; PHI->dump();); 1627 PHI->moveBefore(InnerLoopHeader->getFirstNonPHI()); 1628 assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node"); 1629 } 1630 for (PHINode *PHI : InnerLoopPHIs) { 1631 LLVM_DEBUG(dbgs() << "Inner loop reduction PHIs:\n"; PHI->dump();); 1632 PHI->moveBefore(OuterLoopHeader->getFirstNonPHI()); 1633 assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node"); 1634 } 1635 1636 // Update the incoming blocks for moved PHI nodes. 1637 OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader); 1638 OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch); 1639 InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader); 1640 InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); 1641 1642 // Values defined in the outer loop header could be used in the inner loop 1643 // latch. In that case, we need to create LCSSA phis for them, because after 1644 // interchanging they will be defined in the new inner loop and used in the 1645 // new outer loop. 1646 IRBuilder<> Builder(OuterLoopHeader->getContext()); 1647 SmallVector<Instruction *, 4> MayNeedLCSSAPhis; 1648 for (Instruction &I : 1649 make_range(OuterLoopHeader->begin(), std::prev(OuterLoopHeader->end()))) 1650 MayNeedLCSSAPhis.push_back(&I); 1651 formLCSSAForInstructions(MayNeedLCSSAPhis, *DT, *LI, SE, Builder); 1652 1653 return true; 1654 } 1655 1656 bool LoopInterchangeTransform::adjustLoopLinks() { 1657 // Adjust all branches in the inner and outer loop. 1658 bool Changed = adjustLoopBranches(); 1659 if (Changed) { 1660 // We have interchanged the preheaders so we need to interchange the data in 1661 // the preheaders as well. This is because the content of the inner 1662 // preheader was previously executed inside the outer loop. 1663 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1664 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1665 swapBBContents(OuterLoopPreHeader, InnerLoopPreHeader); 1666 } 1667 return Changed; 1668 } 1669 1670 namespace { 1671 /// Main LoopInterchange Pass. 1672 struct LoopInterchangeLegacyPass : public LoopPass { 1673 static char ID; 1674 1675 LoopInterchangeLegacyPass() : LoopPass(ID) { 1676 initializeLoopInterchangeLegacyPassPass(*PassRegistry::getPassRegistry()); 1677 } 1678 1679 void getAnalysisUsage(AnalysisUsage &AU) const override { 1680 AU.addRequired<DependenceAnalysisWrapperPass>(); 1681 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 1682 1683 getLoopAnalysisUsage(AU); 1684 } 1685 1686 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 1687 if (skipLoop(L)) 1688 return false; 1689 1690 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1691 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1692 auto *DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 1693 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1694 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 1695 1696 return LoopInterchange(SE, LI, DI, DT, ORE).run(L); 1697 } 1698 }; 1699 } // namespace 1700 1701 char LoopInterchangeLegacyPass::ID = 0; 1702 1703 INITIALIZE_PASS_BEGIN(LoopInterchangeLegacyPass, "loop-interchange", 1704 "Interchanges loops for cache reuse", false, false) 1705 INITIALIZE_PASS_DEPENDENCY(LoopPass) 1706 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1707 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 1708 1709 INITIALIZE_PASS_END(LoopInterchangeLegacyPass, "loop-interchange", 1710 "Interchanges loops for cache reuse", false, false) 1711 1712 Pass *llvm::createLoopInterchangePass() { 1713 return new LoopInterchangeLegacyPass(); 1714 } 1715 1716 PreservedAnalyses LoopInterchangePass::run(LoopNest &LN, 1717 LoopAnalysisManager &AM, 1718 LoopStandardAnalysisResults &AR, 1719 LPMUpdater &U) { 1720 Function &F = *LN.getParent(); 1721 1722 DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI); 1723 OptimizationRemarkEmitter ORE(&F); 1724 if (!LoopInterchange(&AR.SE, &AR.LI, &DI, &AR.DT, &ORE).run(LN)) 1725 return PreservedAnalyses::all(); 1726 return getLoopPassPreservedAnalyses(); 1727 } 1728