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/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/LoopPass.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/Analysis/ScalarEvolution.h" 25 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 26 #include "llvm/IR/BasicBlock.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DiagnosticInfo.h" 29 #include "llvm/IR/Dominators.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/InstrTypes.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/User.h" 36 #include "llvm/IR/Value.h" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/Transforms/Scalar.h" 44 #include "llvm/Transforms/Utils.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 46 #include "llvm/Transforms/Utils/LoopUtils.h" 47 #include <cassert> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "loop-interchange" 54 55 STATISTIC(LoopsInterchanged, "Number of loops interchanged"); 56 57 static cl::opt<int> LoopInterchangeCostThreshold( 58 "loop-interchange-threshold", cl::init(0), cl::Hidden, 59 cl::desc("Interchange if you gain more than this number")); 60 61 namespace { 62 63 using LoopVector = SmallVector<Loop *, 8>; 64 65 // TODO: Check if we can use a sparse matrix here. 66 using CharMatrix = std::vector<std::vector<char>>; 67 68 } // end anonymous namespace 69 70 // Maximum number of dependencies that can be handled in the dependency matrix. 71 static const unsigned MaxMemInstrCount = 100; 72 73 // Maximum loop depth supported. 74 static const unsigned MaxLoopNestDepth = 10; 75 76 #ifdef DUMP_DEP_MATRICIES 77 static void printDepMatrix(CharMatrix &DepMatrix) { 78 for (auto &Row : DepMatrix) { 79 for (auto D : Row) 80 LLVM_DEBUG(dbgs() << D << " "); 81 LLVM_DEBUG(dbgs() << "\n"); 82 } 83 } 84 #endif 85 86 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, 87 Loop *L, DependenceInfo *DI) { 88 using ValueVector = SmallVector<Value *, 16>; 89 90 ValueVector MemInstr; 91 92 // For each block. 93 for (BasicBlock *BB : L->blocks()) { 94 // Scan the BB and collect legal loads and stores. 95 for (Instruction &I : *BB) { 96 if (!isa<Instruction>(I)) 97 return false; 98 if (auto *Ld = dyn_cast<LoadInst>(&I)) { 99 if (!Ld->isSimple()) 100 return false; 101 MemInstr.push_back(&I); 102 } else if (auto *St = dyn_cast<StoreInst>(&I)) { 103 if (!St->isSimple()) 104 return false; 105 MemInstr.push_back(&I); 106 } 107 } 108 } 109 110 LLVM_DEBUG(dbgs() << "Found " << MemInstr.size() 111 << " Loads and Stores to analyze\n"); 112 113 ValueVector::iterator I, IE, J, JE; 114 115 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { 116 for (J = I, JE = MemInstr.end(); J != JE; ++J) { 117 std::vector<char> Dep; 118 Instruction *Src = cast<Instruction>(*I); 119 Instruction *Dst = cast<Instruction>(*J); 120 if (Src == Dst) 121 continue; 122 // Ignore Input dependencies. 123 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) 124 continue; 125 // Track Output, Flow, and Anti dependencies. 126 if (auto D = DI->depends(Src, Dst, true)) { 127 assert(D->isOrdered() && "Expected an output, flow or anti dep."); 128 LLVM_DEBUG(StringRef DepType = 129 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output"; 130 dbgs() << "Found " << DepType 131 << " dependency between Src and Dst\n" 132 << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); 133 unsigned Levels = D->getLevels(); 134 char Direction; 135 for (unsigned II = 1; II <= Levels; ++II) { 136 const SCEV *Distance = D->getDistance(II); 137 const SCEVConstant *SCEVConst = 138 dyn_cast_or_null<SCEVConstant>(Distance); 139 if (SCEVConst) { 140 const ConstantInt *CI = SCEVConst->getValue(); 141 if (CI->isNegative()) 142 Direction = '<'; 143 else if (CI->isZero()) 144 Direction = '='; 145 else 146 Direction = '>'; 147 Dep.push_back(Direction); 148 } else if (D->isScalar(II)) { 149 Direction = 'S'; 150 Dep.push_back(Direction); 151 } else { 152 unsigned Dir = D->getDirection(II); 153 if (Dir == Dependence::DVEntry::LT || 154 Dir == Dependence::DVEntry::LE) 155 Direction = '<'; 156 else if (Dir == Dependence::DVEntry::GT || 157 Dir == Dependence::DVEntry::GE) 158 Direction = '>'; 159 else if (Dir == Dependence::DVEntry::EQ) 160 Direction = '='; 161 else 162 Direction = '*'; 163 Dep.push_back(Direction); 164 } 165 } 166 while (Dep.size() != Level) { 167 Dep.push_back('I'); 168 } 169 170 DepMatrix.push_back(Dep); 171 if (DepMatrix.size() > MaxMemInstrCount) { 172 LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount 173 << " dependencies inside loop\n"); 174 return false; 175 } 176 } 177 } 178 } 179 180 return true; 181 } 182 183 // A loop is moved from index 'from' to an index 'to'. Update the Dependence 184 // matrix by exchanging the two columns. 185 static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, 186 unsigned ToIndx) { 187 unsigned numRows = DepMatrix.size(); 188 for (unsigned i = 0; i < numRows; ++i) { 189 char TmpVal = DepMatrix[i][ToIndx]; 190 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; 191 DepMatrix[i][FromIndx] = TmpVal; 192 } 193 } 194 195 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is 196 // '>' 197 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, 198 unsigned Column) { 199 for (unsigned i = 0; i <= Column; ++i) { 200 if (DepMatrix[Row][i] == '<') 201 return false; 202 if (DepMatrix[Row][i] == '>') 203 return true; 204 } 205 // All dependencies were '=','S' or 'I' 206 return false; 207 } 208 209 // Checks if no dependence exist in the dependency matrix in Row before Column. 210 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, 211 unsigned Column) { 212 for (unsigned i = 0; i < Column; ++i) { 213 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' && 214 DepMatrix[Row][i] != 'I') 215 return false; 216 } 217 return true; 218 } 219 220 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, 221 unsigned OuterLoopId, char InnerDep, 222 char OuterDep) { 223 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) 224 return false; 225 226 if (InnerDep == OuterDep) 227 return true; 228 229 // It is legal to interchange if and only if after interchange no row has a 230 // '>' direction as the leftmost non-'='. 231 232 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') 233 return true; 234 235 if (InnerDep == '<') 236 return true; 237 238 if (InnerDep == '>') { 239 // If OuterLoopId represents outermost loop then interchanging will make the 240 // 1st dependency as '>' 241 if (OuterLoopId == 0) 242 return false; 243 244 // If all dependencies before OuterloopId are '=','S'or 'I'. Then 245 // interchanging will result in this row having an outermost non '=' 246 // dependency of '>' 247 if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) 248 return true; 249 } 250 251 return false; 252 } 253 254 // Checks if it is legal to interchange 2 loops. 255 // [Theorem] A permutation of the loops in a perfect nest is legal if and only 256 // if the direction matrix, after the same permutation is applied to its 257 // columns, has no ">" direction as the leftmost non-"=" direction in any row. 258 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, 259 unsigned InnerLoopId, 260 unsigned OuterLoopId) { 261 unsigned NumRows = DepMatrix.size(); 262 // For each row check if it is valid to interchange. 263 for (unsigned Row = 0; Row < NumRows; ++Row) { 264 char InnerDep = DepMatrix[Row][InnerLoopId]; 265 char OuterDep = DepMatrix[Row][OuterLoopId]; 266 if (InnerDep == '*' || OuterDep == '*') 267 return false; 268 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) 269 return false; 270 } 271 return true; 272 } 273 274 static LoopVector populateWorklist(Loop &L) { 275 LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: " 276 << L.getHeader()->getParent()->getName() << " Loop: %" 277 << L.getHeader()->getName() << '\n'); 278 LoopVector LoopList; 279 Loop *CurrentLoop = &L; 280 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); 281 while (!Vec->empty()) { 282 // The current loop has multiple subloops in it hence it is not tightly 283 // nested. 284 // Discard all loops above it added into Worklist. 285 if (Vec->size() != 1) 286 return {}; 287 288 LoopList.push_back(CurrentLoop); 289 CurrentLoop = Vec->front(); 290 Vec = &CurrentLoop->getSubLoops(); 291 } 292 LoopList.push_back(CurrentLoop); 293 return LoopList; 294 } 295 296 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { 297 PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); 298 if (InnerIndexVar) 299 return InnerIndexVar; 300 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) 301 return nullptr; 302 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 303 PHINode *PhiVar = cast<PHINode>(I); 304 Type *PhiTy = PhiVar->getType(); 305 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 306 !PhiTy->isPointerTy()) 307 return nullptr; 308 const SCEVAddRecExpr *AddRec = 309 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); 310 if (!AddRec || !AddRec->isAffine()) 311 continue; 312 const SCEV *Step = AddRec->getStepRecurrence(*SE); 313 if (!isa<SCEVConstant>(Step)) 314 continue; 315 // Found the induction variable. 316 // FIXME: Handle loops with more than one induction variable. Note that, 317 // currently, legality makes sure we have only one induction variable. 318 return PhiVar; 319 } 320 return nullptr; 321 } 322 323 namespace { 324 325 /// LoopInterchangeLegality checks if it is legal to interchange the loop. 326 class LoopInterchangeLegality { 327 public: 328 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 329 OptimizationRemarkEmitter *ORE) 330 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} 331 332 /// Check if the loops can be interchanged. 333 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, 334 CharMatrix &DepMatrix); 335 336 /// Check if the loop structure is understood. We do not handle triangular 337 /// loops for now. 338 bool isLoopStructureUnderstood(PHINode *InnerInductionVar); 339 340 bool currentLimitations(); 341 342 private: 343 bool tightlyNested(Loop *Outer, Loop *Inner); 344 bool containsUnsafeInstructions(BasicBlock *BB); 345 bool findInductions(Loop *L, SmallVector<PHINode *, 8> &Inductions); 346 347 Loop *OuterLoop; 348 Loop *InnerLoop; 349 350 ScalarEvolution *SE; 351 352 /// Interface to emit optimization remarks. 353 OptimizationRemarkEmitter *ORE; 354 355 }; 356 357 /// LoopInterchangeProfitability checks if it is profitable to interchange the 358 /// loop. 359 class LoopInterchangeProfitability { 360 public: 361 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 362 OptimizationRemarkEmitter *ORE) 363 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} 364 365 /// Check if the loop interchange is profitable. 366 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, 367 CharMatrix &DepMatrix); 368 369 private: 370 int getInstrOrderCost(); 371 372 Loop *OuterLoop; 373 Loop *InnerLoop; 374 375 /// Scev analysis. 376 ScalarEvolution *SE; 377 378 /// Interface to emit optimization remarks. 379 OptimizationRemarkEmitter *ORE; 380 }; 381 382 /// LoopInterchangeTransform interchanges the loop. 383 class LoopInterchangeTransform { 384 public: 385 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 386 LoopInfo *LI, DominatorTree *DT, 387 BasicBlock *LoopNestExit) 388 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 389 LoopExit(LoopNestExit) {} 390 391 /// Interchange OuterLoop and InnerLoop. 392 bool transform(); 393 void restructureLoops(Loop *NewInner, Loop *NewOuter, 394 BasicBlock *OrigInnerPreHeader, 395 BasicBlock *OrigOuterPreHeader); 396 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); 397 398 private: 399 void splitInnerLoopLatch(Instruction *); 400 void splitInnerLoopHeader(); 401 bool adjustLoopLinks(); 402 void adjustLoopPreheaders(); 403 bool adjustLoopBranches(); 404 405 Loop *OuterLoop; 406 Loop *InnerLoop; 407 408 /// Scev analysis. 409 ScalarEvolution *SE; 410 411 LoopInfo *LI; 412 DominatorTree *DT; 413 BasicBlock *LoopExit; 414 }; 415 416 // Main LoopInterchange Pass. 417 struct LoopInterchange : public LoopPass { 418 static char ID; 419 ScalarEvolution *SE = nullptr; 420 LoopInfo *LI = nullptr; 421 DependenceInfo *DI = nullptr; 422 DominatorTree *DT = nullptr; 423 424 /// Interface to emit optimization remarks. 425 OptimizationRemarkEmitter *ORE; 426 427 LoopInterchange() : LoopPass(ID) { 428 initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); 429 } 430 431 void getAnalysisUsage(AnalysisUsage &AU) const override { 432 AU.addRequired<DependenceAnalysisWrapperPass>(); 433 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 434 435 getLoopAnalysisUsage(AU); 436 } 437 438 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 439 if (skipLoop(L) || L->getParentLoop()) 440 return false; 441 442 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 443 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 444 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 445 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 446 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 447 448 return processLoopList(populateWorklist(*L)); 449 } 450 451 bool isComputableLoopNest(LoopVector LoopList) { 452 for (Loop *L : LoopList) { 453 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); 454 if (ExitCountOuter == SE->getCouldNotCompute()) { 455 LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n"); 456 return false; 457 } 458 if (L->getNumBackEdges() != 1) { 459 LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); 460 return false; 461 } 462 if (!L->getExitingBlock()) { 463 LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n"); 464 return false; 465 } 466 } 467 return true; 468 } 469 470 unsigned selectLoopForInterchange(const LoopVector &LoopList) { 471 // TODO: Add a better heuristic to select the loop to be interchanged based 472 // on the dependence matrix. Currently we select the innermost loop. 473 return LoopList.size() - 1; 474 } 475 476 bool processLoopList(LoopVector LoopList) { 477 bool Changed = false; 478 unsigned LoopNestDepth = LoopList.size(); 479 if (LoopNestDepth < 2) { 480 LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); 481 return false; 482 } 483 if (LoopNestDepth > MaxLoopNestDepth) { 484 LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than " 485 << MaxLoopNestDepth << "\n"); 486 return false; 487 } 488 if (!isComputableLoopNest(LoopList)) { 489 LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); 490 return false; 491 } 492 493 LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth 494 << "\n"); 495 496 CharMatrix DependencyMatrix; 497 Loop *OuterMostLoop = *(LoopList.begin()); 498 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, 499 OuterMostLoop, DI)) { 500 LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n"); 501 return false; 502 } 503 #ifdef DUMP_DEP_MATRICIES 504 LLVM_DEBUG(dbgs() << "Dependence before interchange\n"); 505 printDepMatrix(DependencyMatrix); 506 #endif 507 508 // Get the Outermost loop exit. 509 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock(); 510 if (!LoopNestExit) { 511 LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block"); 512 return false; 513 } 514 515 unsigned SelecLoopId = selectLoopForInterchange(LoopList); 516 // Move the selected loop outwards to the best possible position. 517 for (unsigned i = SelecLoopId; i > 0; i--) { 518 bool Interchanged = 519 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); 520 if (!Interchanged) 521 return Changed; 522 // Loops interchanged reflect the same in LoopList 523 std::swap(LoopList[i - 1], LoopList[i]); 524 525 // Update the DependencyMatrix 526 interChangeDependencies(DependencyMatrix, i, i - 1); 527 #ifdef DUMP_DEP_MATRICIES 528 LLVM_DEBUG(dbgs() << "Dependence after interchange\n"); 529 printDepMatrix(DependencyMatrix); 530 #endif 531 Changed |= Interchanged; 532 } 533 return Changed; 534 } 535 536 bool processLoop(LoopVector LoopList, unsigned InnerLoopId, 537 unsigned OuterLoopId, BasicBlock *LoopNestExit, 538 std::vector<std::vector<char>> &DependencyMatrix) { 539 LLVM_DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId 540 << " and OuterLoopId = " << OuterLoopId << "\n"); 541 Loop *InnerLoop = LoopList[InnerLoopId]; 542 Loop *OuterLoop = LoopList[OuterLoopId]; 543 544 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE); 545 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { 546 LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n"); 547 return false; 548 } 549 LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n"); 550 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE); 551 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { 552 LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n"); 553 return false; 554 } 555 556 ORE->emit([&]() { 557 return OptimizationRemark(DEBUG_TYPE, "Interchanged", 558 InnerLoop->getStartLoc(), 559 InnerLoop->getHeader()) 560 << "Loop interchanged with enclosing loop."; 561 }); 562 563 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, 564 LoopNestExit); 565 LIT.transform(); 566 LLVM_DEBUG(dbgs() << "Loops interchanged.\n"); 567 LoopsInterchanged++; 568 return true; 569 } 570 }; 571 572 } // end anonymous namespace 573 574 bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) { 575 return any_of(*BB, [](const Instruction &I) { 576 return I.mayHaveSideEffects() || I.mayReadFromMemory(); 577 }); 578 } 579 580 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { 581 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 582 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 583 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 584 585 LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n"); 586 587 // A perfectly nested loop will not have any branch in between the outer and 588 // inner block i.e. outer header will branch to either inner preheader and 589 // outerloop latch. 590 BranchInst *OuterLoopHeaderBI = 591 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 592 if (!OuterLoopHeaderBI) 593 return false; 594 595 for (BasicBlock *Succ : successors(OuterLoopHeaderBI)) 596 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() && 597 Succ != OuterLoopLatch) 598 return false; 599 600 LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n"); 601 // We do not have any basic block in between now make sure the outer header 602 // and outer loop latch doesn't contain any unsafe instructions. 603 if (containsUnsafeInstructions(OuterLoopHeader) || 604 containsUnsafeInstructions(OuterLoopLatch)) 605 return false; 606 607 LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n"); 608 // We have a perfect loop nest. 609 return true; 610 } 611 612 bool LoopInterchangeLegality::isLoopStructureUnderstood( 613 PHINode *InnerInduction) { 614 unsigned Num = InnerInduction->getNumOperands(); 615 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); 616 for (unsigned i = 0; i < Num; ++i) { 617 Value *Val = InnerInduction->getOperand(i); 618 if (isa<Constant>(Val)) 619 continue; 620 Instruction *I = dyn_cast<Instruction>(Val); 621 if (!I) 622 return false; 623 // TODO: Handle triangular loops. 624 // e.g. for(int i=0;i<N;i++) 625 // for(int j=i;j<N;j++) 626 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); 627 if (InnerInduction->getIncomingBlock(IncomBlockIndx) == 628 InnerLoopPreheader && 629 !OuterLoop->isLoopInvariant(I)) { 630 return false; 631 } 632 } 633 return true; 634 } 635 636 bool LoopInterchangeLegality::findInductions( 637 Loop *L, SmallVector<PHINode *, 8> &Inductions) { 638 if (!L->getLoopLatch() || !L->getLoopPredecessor()) 639 return false; 640 for (PHINode &PHI : L->getHeader()->phis()) { 641 RecurrenceDescriptor RD; 642 InductionDescriptor ID; 643 if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) 644 Inductions.push_back(&PHI); 645 else { 646 LLVM_DEBUG(dbgs() << "Failed to recognize PHI as an induction.\n"); 647 return false; 648 } 649 } 650 return true; 651 } 652 653 static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { 654 for (PHINode &PHI : Block->phis()) { 655 // Reduction lcssa phi will have only 1 incoming block that from loop latch. 656 if (PHI.getNumIncomingValues() > 1) 657 return false; 658 Instruction *Ins = dyn_cast<Instruction>(PHI.getIncomingValue(0)); 659 if (!Ins) 660 return false; 661 // Incoming value for lcssa phi's in outer loop exit can only be inner loop 662 // exits lcssa phi else it would not be tightly nested. 663 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) 664 return false; 665 } 666 return true; 667 } 668 669 // This function indicates the current limitations in the transform as a result 670 // of which we do not proceed. 671 bool LoopInterchangeLegality::currentLimitations() { 672 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 673 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 674 675 // transform currently expects the loop latches to also be the exiting 676 // blocks. 677 if (InnerLoop->getExitingBlock() != InnerLoopLatch || 678 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() || 679 !isa<BranchInst>(InnerLoopLatch->getTerminator()) || 680 !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) { 681 LLVM_DEBUG( 682 dbgs() << "Loops where the latch is not the exiting block are not" 683 << " supported currently.\n"); 684 ORE->emit([&]() { 685 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch", 686 OuterLoop->getStartLoc(), 687 OuterLoop->getHeader()) 688 << "Loops where the latch is not the exiting block cannot be" 689 " interchange currently."; 690 }); 691 return true; 692 } 693 694 PHINode *InnerInductionVar; 695 SmallVector<PHINode *, 8> Inductions; 696 if (!findInductions(InnerLoop, Inductions)) { 697 LLVM_DEBUG( 698 dbgs() << "Only inner loops with induction or reduction PHI nodes " 699 << "are supported currently.\n"); 700 ORE->emit([&]() { 701 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner", 702 InnerLoop->getStartLoc(), 703 InnerLoop->getHeader()) 704 << "Only inner loops with induction or reduction PHI nodes can be" 705 " interchange currently."; 706 }); 707 return true; 708 } 709 710 // TODO: Currently we handle only loops with 1 induction variable. 711 if (Inductions.size() != 1) { 712 LLVM_DEBUG( 713 dbgs() << "We currently only support loops with 1 induction variable." 714 << "Failed to interchange due to current limitation\n"); 715 ORE->emit([&]() { 716 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner", 717 InnerLoop->getStartLoc(), 718 InnerLoop->getHeader()) 719 << "Only inner loops with 1 induction variable can be " 720 "interchanged currently."; 721 }); 722 return true; 723 } 724 725 InnerInductionVar = Inductions.pop_back_val(); 726 if (!findInductions(OuterLoop, Inductions)) { 727 LLVM_DEBUG( 728 dbgs() << "Only outer loops with induction or reduction PHI nodes " 729 << "are supported currently.\n"); 730 ORE->emit([&]() { 731 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter", 732 OuterLoop->getStartLoc(), 733 OuterLoop->getHeader()) 734 << "Only outer loops with induction or reduction PHI nodes can be" 735 " interchanged currently."; 736 }); 737 return true; 738 } 739 740 // TODO: Currently we handle only loops with 1 induction variable. 741 if (Inductions.size() != 1) { 742 LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not " 743 << "supported currently.\n"); 744 ORE->emit([&]() { 745 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter", 746 OuterLoop->getStartLoc(), 747 OuterLoop->getHeader()) 748 << "Only outer loops with 1 induction variable can be " 749 "interchanged currently."; 750 }); 751 return true; 752 } 753 754 // TODO: Triangular loops are not handled for now. 755 if (!isLoopStructureUnderstood(InnerInductionVar)) { 756 LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n"); 757 ORE->emit([&]() { 758 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner", 759 InnerLoop->getStartLoc(), 760 InnerLoop->getHeader()) 761 << "Inner loop structure not understood currently."; 762 }); 763 return true; 764 } 765 766 // TODO: We only handle LCSSA PHI's corresponding to reduction for now. 767 BasicBlock *InnerExit = InnerLoop->getExitBlock(); 768 if (!containsSafePHI(InnerExit, false)) { 769 LLVM_DEBUG( 770 dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n"); 771 ORE->emit([&]() { 772 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner", 773 InnerLoop->getStartLoc(), 774 InnerLoop->getHeader()) 775 << "Only inner loops with LCSSA PHIs can be interchange " 776 "currently."; 777 }); 778 return true; 779 } 780 781 // TODO: Current limitation: Since we split the inner loop latch at the point 782 // were induction variable is incremented (induction.next); We cannot have 783 // more than 1 user of induction.next since it would result in broken code 784 // after split. 785 // e.g. 786 // for(i=0;i<N;i++) { 787 // for(j = 0;j<M;j++) { 788 // A[j+1][i+2] = A[j][i]+k; 789 // } 790 // } 791 Instruction *InnerIndexVarInc = nullptr; 792 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) 793 InnerIndexVarInc = 794 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); 795 else 796 InnerIndexVarInc = 797 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); 798 799 if (!InnerIndexVarInc) { 800 LLVM_DEBUG( 801 dbgs() << "Did not find an instruction to increment the induction " 802 << "variable.\n"); 803 ORE->emit([&]() { 804 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner", 805 InnerLoop->getStartLoc(), 806 InnerLoop->getHeader()) 807 << "The inner loop does not increment the induction variable."; 808 }); 809 return true; 810 } 811 812 // Since we split the inner loop latch on this induction variable. Make sure 813 // we do not have any instruction between the induction variable and branch 814 // instruction. 815 816 bool FoundInduction = false; 817 for (const Instruction &I : 818 llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) { 819 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) || 820 isa<ZExtInst>(I)) 821 continue; 822 823 // We found an instruction. If this is not induction variable then it is not 824 // safe to split this loop latch. 825 if (!I.isIdenticalTo(InnerIndexVarInc)) { 826 LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction " 827 << "variable increment and branch.\n"); 828 ORE->emit([&]() { 829 return OptimizationRemarkMissed( 830 DEBUG_TYPE, "UnsupportedInsBetweenInduction", 831 InnerLoop->getStartLoc(), InnerLoop->getHeader()) 832 << "Found unsupported instruction between induction variable " 833 "increment and branch."; 834 }); 835 return true; 836 } 837 838 FoundInduction = true; 839 break; 840 } 841 // The loop latch ended and we didn't find the induction variable return as 842 // current limitation. 843 if (!FoundInduction) { 844 LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n"); 845 ORE->emit([&]() { 846 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable", 847 InnerLoop->getStartLoc(), 848 InnerLoop->getHeader()) 849 << "Did not find the induction variable."; 850 }); 851 return true; 852 } 853 return false; 854 } 855 856 // We currently support LCSSA PHI nodes in the outer loop exit, if their 857 // incoming values do not come from the outer loop latch or if the 858 // outer loop latch has a single predecessor. In that case, the value will 859 // be available if both the inner and outer loop conditions are true, which 860 // will still be true after interchanging. If we have multiple predecessor, 861 // that may not be the case, e.g. because the outer loop latch may be executed 862 // if the inner loop is not executed. 863 static bool areLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) { 864 BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock(); 865 for (PHINode &PHI : LoopNestExit->phis()) { 866 // FIXME: We currently are not able to detect floating point reductions 867 // and have to use floating point PHIs as a proxy to prevent 868 // interchanging in the presence of floating point reductions. 869 if (PHI.getType()->isFloatingPointTy()) 870 return false; 871 for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) { 872 Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i)); 873 if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch()) 874 continue; 875 876 // The incoming value is defined in the outer loop latch. Currently we 877 // only support that in case the outer loop latch has a single predecessor. 878 // This guarantees that the outer loop latch is executed if and only if 879 // the inner loop is executed (because tightlyNested() guarantees that the 880 // outer loop header only branches to the inner loop or the outer loop 881 // latch). 882 // FIXME: We could weaken this logic and allow multiple predecessors, 883 // if the values are produced outside the loop latch. We would need 884 // additional logic to update the PHI nodes in the exit block as 885 // well. 886 if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr) 887 return false; 888 } 889 } 890 return true; 891 } 892 893 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, 894 unsigned OuterLoopId, 895 CharMatrix &DepMatrix) { 896 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { 897 LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId 898 << " and OuterLoopId = " << OuterLoopId 899 << " due to dependence\n"); 900 ORE->emit([&]() { 901 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence", 902 InnerLoop->getStartLoc(), 903 InnerLoop->getHeader()) 904 << "Cannot interchange loops due to dependences."; 905 }); 906 return false; 907 } 908 // Check if outer and inner loop contain legal instructions only. 909 for (auto *BB : OuterLoop->blocks()) 910 for (Instruction &I : BB->instructionsWithoutDebug()) 911 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 912 // readnone functions do not prevent interchanging. 913 if (CI->doesNotReadMemory()) 914 continue; 915 LLVM_DEBUG( 916 dbgs() << "Loops with call instructions cannot be interchanged " 917 << "safely."); 918 ORE->emit([&]() { 919 return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst", 920 CI->getDebugLoc(), 921 CI->getParent()) 922 << "Cannot interchange loops due to call instruction."; 923 }); 924 925 return false; 926 } 927 928 // TODO: The loops could not be interchanged due to current limitations in the 929 // transform module. 930 if (currentLimitations()) { 931 LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n"); 932 return false; 933 } 934 935 // Check if the loops are tightly nested. 936 if (!tightlyNested(OuterLoop, InnerLoop)) { 937 LLVM_DEBUG(dbgs() << "Loops not tightly nested\n"); 938 ORE->emit([&]() { 939 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested", 940 InnerLoop->getStartLoc(), 941 InnerLoop->getHeader()) 942 << "Cannot interchange loops because they are not tightly " 943 "nested."; 944 }); 945 return false; 946 } 947 948 if (!areLoopExitPHIsSupported(OuterLoop, InnerLoop)) { 949 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n"); 950 ORE->emit([&]() { 951 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI", 952 OuterLoop->getStartLoc(), 953 OuterLoop->getHeader()) 954 << "Found unsupported PHI node in loop exit."; 955 }); 956 return false; 957 } 958 959 return true; 960 } 961 962 int LoopInterchangeProfitability::getInstrOrderCost() { 963 unsigned GoodOrder, BadOrder; 964 BadOrder = GoodOrder = 0; 965 for (BasicBlock *BB : InnerLoop->blocks()) { 966 for (Instruction &Ins : *BB) { 967 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { 968 unsigned NumOp = GEP->getNumOperands(); 969 bool FoundInnerInduction = false; 970 bool FoundOuterInduction = false; 971 for (unsigned i = 0; i < NumOp; ++i) { 972 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); 973 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); 974 if (!AR) 975 continue; 976 977 // If we find the inner induction after an outer induction e.g. 978 // for(int i=0;i<N;i++) 979 // for(int j=0;j<N;j++) 980 // A[i][j] = A[i-1][j-1]+k; 981 // then it is a good order. 982 if (AR->getLoop() == InnerLoop) { 983 // We found an InnerLoop induction after OuterLoop induction. It is 984 // a good order. 985 FoundInnerInduction = true; 986 if (FoundOuterInduction) { 987 GoodOrder++; 988 break; 989 } 990 } 991 // If we find the outer induction after an inner induction e.g. 992 // for(int i=0;i<N;i++) 993 // for(int j=0;j<N;j++) 994 // A[j][i] = A[j-1][i-1]+k; 995 // then it is a bad order. 996 if (AR->getLoop() == OuterLoop) { 997 // We found an OuterLoop induction after InnerLoop induction. It is 998 // a bad order. 999 FoundOuterInduction = true; 1000 if (FoundInnerInduction) { 1001 BadOrder++; 1002 break; 1003 } 1004 } 1005 } 1006 } 1007 } 1008 } 1009 return GoodOrder - BadOrder; 1010 } 1011 1012 static bool isProfitableForVectorization(unsigned InnerLoopId, 1013 unsigned OuterLoopId, 1014 CharMatrix &DepMatrix) { 1015 // TODO: Improve this heuristic to catch more cases. 1016 // If the inner loop is loop independent or doesn't carry any dependency it is 1017 // profitable to move this to outer position. 1018 for (auto &Row : DepMatrix) { 1019 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I') 1020 return false; 1021 // TODO: We need to improve this heuristic. 1022 if (Row[OuterLoopId] != '=') 1023 return false; 1024 } 1025 // If outer loop has dependence and inner loop is loop independent then it is 1026 // profitable to interchange to enable parallelism. 1027 // If there are no dependences, interchanging will not improve anything. 1028 return !DepMatrix.empty(); 1029 } 1030 1031 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, 1032 unsigned OuterLoopId, 1033 CharMatrix &DepMatrix) { 1034 // TODO: Add better profitability checks. 1035 // e.g 1036 // 1) Construct dependency matrix and move the one with no loop carried dep 1037 // inside to enable vectorization. 1038 1039 // This is rough cost estimation algorithm. It counts the good and bad order 1040 // of induction variables in the instruction and allows reordering if number 1041 // of bad orders is more than good. 1042 int Cost = getInstrOrderCost(); 1043 LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n"); 1044 if (Cost < -LoopInterchangeCostThreshold) 1045 return true; 1046 1047 // It is not profitable as per current cache profitability model. But check if 1048 // we can move this loop outside to improve parallelism. 1049 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix)) 1050 return true; 1051 1052 ORE->emit([&]() { 1053 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable", 1054 InnerLoop->getStartLoc(), 1055 InnerLoop->getHeader()) 1056 << "Interchanging loops is too costly (cost=" 1057 << ore::NV("Cost", Cost) << ", threshold=" 1058 << ore::NV("Threshold", LoopInterchangeCostThreshold) 1059 << ") and it does not improve parallelism."; 1060 }); 1061 return false; 1062 } 1063 1064 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, 1065 Loop *InnerLoop) { 1066 for (Loop *L : *OuterLoop) 1067 if (L == InnerLoop) { 1068 OuterLoop->removeChildLoop(L); 1069 return; 1070 } 1071 llvm_unreachable("Couldn't find loop"); 1072 } 1073 1074 /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the 1075 /// new inner and outer loop after interchanging: NewInner is the original 1076 /// outer loop and NewOuter is the original inner loop. 1077 /// 1078 /// Before interchanging, we have the following structure 1079 /// Outer preheader 1080 // Outer header 1081 // Inner preheader 1082 // Inner header 1083 // Inner body 1084 // Inner latch 1085 // outer bbs 1086 // Outer latch 1087 // 1088 // After interchanging: 1089 // Inner preheader 1090 // Inner header 1091 // Outer preheader 1092 // Outer header 1093 // Inner body 1094 // outer bbs 1095 // Outer latch 1096 // Inner latch 1097 void LoopInterchangeTransform::restructureLoops( 1098 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader, 1099 BasicBlock *OrigOuterPreHeader) { 1100 Loop *OuterLoopParent = OuterLoop->getParentLoop(); 1101 // The original inner loop preheader moves from the new inner loop to 1102 // the parent loop, if there is one. 1103 NewInner->removeBlockFromLoop(OrigInnerPreHeader); 1104 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent); 1105 1106 // Switch the loop levels. 1107 if (OuterLoopParent) { 1108 // Remove the loop from its parent loop. 1109 removeChildLoop(OuterLoopParent, NewInner); 1110 removeChildLoop(NewInner, NewOuter); 1111 OuterLoopParent->addChildLoop(NewOuter); 1112 } else { 1113 removeChildLoop(NewInner, NewOuter); 1114 LI->changeTopLevelLoop(NewInner, NewOuter); 1115 } 1116 while (!NewOuter->empty()) 1117 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin())); 1118 NewOuter->addChildLoop(NewInner); 1119 1120 // BBs from the original inner loop. 1121 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks()); 1122 1123 // Add BBs from the original outer loop to the original inner loop (excluding 1124 // BBs already in inner loop) 1125 for (BasicBlock *BB : NewInner->blocks()) 1126 if (LI->getLoopFor(BB) == NewInner) 1127 NewOuter->addBlockEntry(BB); 1128 1129 // Now remove inner loop header and latch from the new inner loop and move 1130 // other BBs (the loop body) to the new inner loop. 1131 BasicBlock *OuterHeader = NewOuter->getHeader(); 1132 BasicBlock *OuterLatch = NewOuter->getLoopLatch(); 1133 for (BasicBlock *BB : OrigInnerBBs) { 1134 // Nothing will change for BBs in child loops. 1135 if (LI->getLoopFor(BB) != NewOuter) 1136 continue; 1137 // Remove the new outer loop header and latch from the new inner loop. 1138 if (BB == OuterHeader || BB == OuterLatch) 1139 NewInner->removeBlockFromLoop(BB); 1140 else 1141 LI->changeLoopFor(BB, NewInner); 1142 } 1143 1144 // The preheader of the original outer loop becomes part of the new 1145 // outer loop. 1146 NewOuter->addBlockEntry(OrigOuterPreHeader); 1147 LI->changeLoopFor(OrigOuterPreHeader, NewOuter); 1148 1149 // Tell SE that we move the loops around. 1150 SE->forgetLoop(NewOuter); 1151 SE->forgetLoop(NewInner); 1152 } 1153 1154 bool LoopInterchangeTransform::transform() { 1155 bool Transformed = false; 1156 Instruction *InnerIndexVar; 1157 1158 if (InnerLoop->getSubLoops().empty()) { 1159 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1160 LLVM_DEBUG(dbgs() << "Calling Split Inner Loop\n"); 1161 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); 1162 if (!InductionPHI) { 1163 LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); 1164 return false; 1165 } 1166 1167 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) 1168 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); 1169 else 1170 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); 1171 1172 // Ensure that InductionPHI is the first Phi node. 1173 if (&InductionPHI->getParent()->front() != InductionPHI) 1174 InductionPHI->moveBefore(&InductionPHI->getParent()->front()); 1175 1176 // Split at the place were the induction variable is 1177 // incremented/decremented. 1178 // TODO: This splitting logic may not work always. Fix this. 1179 splitInnerLoopLatch(InnerIndexVar); 1180 LLVM_DEBUG(dbgs() << "splitInnerLoopLatch done\n"); 1181 1182 // Splits the inner loops phi nodes out into a separate basic block. 1183 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1184 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); 1185 LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n"); 1186 } 1187 1188 Transformed |= adjustLoopLinks(); 1189 if (!Transformed) { 1190 LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n"); 1191 return false; 1192 } 1193 1194 return true; 1195 } 1196 1197 void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) { 1198 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1199 BasicBlock *InnerLoopLatchPred = InnerLoopLatch; 1200 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI); 1201 } 1202 1203 /// \brief Move all instructions except the terminator from FromBB right before 1204 /// InsertBefore 1205 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { 1206 auto &ToList = InsertBefore->getParent()->getInstList(); 1207 auto &FromList = FromBB->getInstList(); 1208 1209 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), 1210 FromBB->getTerminator()->getIterator()); 1211 } 1212 1213 static void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred, 1214 BasicBlock *NewPred) { 1215 for (PHINode &PHI : CurrBlock->phis()) { 1216 unsigned Num = PHI.getNumIncomingValues(); 1217 for (unsigned i = 0; i < Num; ++i) { 1218 if (PHI.getIncomingBlock(i) == OldPred) 1219 PHI.setIncomingBlock(i, NewPred); 1220 } 1221 } 1222 } 1223 1224 /// Update BI to jump to NewBB instead of OldBB. Records updates to 1225 /// the dominator tree in DTUpdates, if DT should be preserved. 1226 static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, 1227 BasicBlock *NewBB, 1228 std::vector<DominatorTree::UpdateType> &DTUpdates) { 1229 assert(llvm::count_if(successors(BI), 1230 [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 && 1231 "BI must jump to OldBB at most once."); 1232 for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) { 1233 if (BI->getSuccessor(i) == OldBB) { 1234 BI->setSuccessor(i, NewBB); 1235 1236 DTUpdates.push_back( 1237 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB}); 1238 DTUpdates.push_back( 1239 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB}); 1240 break; 1241 } 1242 } 1243 } 1244 1245 // Move Lcssa PHIs to the right place. 1246 static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerLatch, 1247 BasicBlock *OuterLatch) { 1248 SmallVector<PHINode *, 8> LcssaInnerExit; 1249 for (PHINode &P : InnerExit->phis()) 1250 LcssaInnerExit.push_back(&P); 1251 1252 SmallVector<PHINode *, 8> LcssaInnerLatch; 1253 for (PHINode &P : InnerLatch->phis()) 1254 LcssaInnerLatch.push_back(&P); 1255 1256 // Lcssa PHIs for values used outside the inner loop are in InnerExit. 1257 // If a PHI node has users outside of InnerExit, it has a use outside the 1258 // interchanged loop and we have to preserve it. We move these to 1259 // InnerLatch, which will become the new exit block for the innermost 1260 // loop after interchanging. For PHIs only used in InnerExit, we can just 1261 // replace them with the incoming value. 1262 for (PHINode *P : LcssaInnerExit) { 1263 bool hasUsersOutside = false; 1264 for (auto UI = P->use_begin(), E = P->use_end(); UI != E;) { 1265 Use &U = *UI; 1266 ++UI; 1267 auto *Usr = cast<Instruction>(U.getUser()); 1268 if (Usr->getParent() != InnerExit) { 1269 hasUsersOutside = true; 1270 continue; 1271 } 1272 U.set(P->getIncomingValueForBlock(InnerLatch)); 1273 } 1274 if (hasUsersOutside) 1275 P->moveBefore(InnerLatch->getFirstNonPHI()); 1276 else 1277 P->eraseFromParent(); 1278 } 1279 1280 // If the inner loop latch contains LCSSA PHIs, those come from a child loop 1281 // and we have to move them to the new inner latch. 1282 for (PHINode *P : LcssaInnerLatch) 1283 P->moveBefore(InnerExit->getFirstNonPHI()); 1284 1285 // Now adjust the incoming blocks for the LCSSA PHIs. 1286 // For PHIs moved from Inner's exit block, we need to replace Inner's latch 1287 // with the new latch. 1288 updateIncomingBlock(InnerLatch, InnerLatch, OuterLatch); 1289 } 1290 1291 bool LoopInterchangeTransform::adjustLoopBranches() { 1292 LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n"); 1293 std::vector<DominatorTree::UpdateType> DTUpdates; 1294 1295 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1296 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1297 1298 assert(OuterLoopPreHeader != OuterLoop->getHeader() && 1299 InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader && 1300 InnerLoopPreHeader && "Guaranteed by loop-simplify form"); 1301 // Ensure that both preheaders do not contain PHI nodes and have single 1302 // predecessors. This allows us to move them easily. We use 1303 // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing 1304 // preheaders do not satisfy those conditions. 1305 if (isa<PHINode>(OuterLoopPreHeader->begin()) || 1306 !OuterLoopPreHeader->getUniquePredecessor()) 1307 OuterLoopPreHeader = InsertPreheaderForLoop(OuterLoop, DT, LI, true); 1308 if (InnerLoopPreHeader == OuterLoop->getHeader()) 1309 InnerLoopPreHeader = InsertPreheaderForLoop(InnerLoop, DT, LI, true); 1310 1311 // Adjust the loop preheader 1312 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1313 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1314 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1315 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1316 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); 1317 BasicBlock *InnerLoopLatchPredecessor = 1318 InnerLoopLatch->getUniquePredecessor(); 1319 BasicBlock *InnerLoopLatchSuccessor; 1320 BasicBlock *OuterLoopLatchSuccessor; 1321 1322 BranchInst *OuterLoopLatchBI = 1323 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); 1324 BranchInst *InnerLoopLatchBI = 1325 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 1326 BranchInst *OuterLoopHeaderBI = 1327 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 1328 BranchInst *InnerLoopHeaderBI = 1329 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); 1330 1331 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || 1332 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || 1333 !InnerLoopHeaderBI) 1334 return false; 1335 1336 BranchInst *InnerLoopLatchPredecessorBI = 1337 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); 1338 BranchInst *OuterLoopPredecessorBI = 1339 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); 1340 1341 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) 1342 return false; 1343 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); 1344 if (!InnerLoopHeaderSuccessor) 1345 return false; 1346 1347 // Adjust Loop Preheader and headers 1348 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader, 1349 InnerLoopPreHeader, DTUpdates); 1350 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates); 1351 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader, 1352 InnerLoopHeaderSuccessor, DTUpdates); 1353 1354 // Adjust reduction PHI's now that the incoming block has changed. 1355 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader, 1356 OuterLoopHeader); 1357 1358 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor, 1359 OuterLoopPreHeader, DTUpdates); 1360 1361 // -------------Adjust loop latches----------- 1362 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) 1363 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); 1364 else 1365 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); 1366 1367 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch, 1368 InnerLoopLatchSuccessor, DTUpdates); 1369 1370 1371 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) 1372 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); 1373 else 1374 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); 1375 1376 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor, 1377 OuterLoopLatchSuccessor, DTUpdates); 1378 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch, 1379 DTUpdates); 1380 1381 DT->applyUpdates(DTUpdates); 1382 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader, 1383 OuterLoopPreHeader); 1384 1385 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopLatch, OuterLoopLatch); 1386 // For PHIs in the exit block of the outer loop, outer's latch has been 1387 // replaced by Inners'. 1388 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch); 1389 1390 // Make sure we have no other PHIs. 1391 auto InnerPhis = drop_begin(InnerLoopHeader->phis(), 1); 1392 auto OuterPhis = drop_begin(OuterLoopHeader->phis(), 1); 1393 (void) InnerPhis; 1394 (void) OuterPhis; 1395 assert(begin(InnerPhis) == end(InnerPhis) && "Unexpected PHIs in inner loop"); 1396 assert(begin(OuterPhis) == end(OuterPhis) && "Unexpected PHis in outer loop"); 1397 1398 // Update the incoming blocks for moved PHI nodes. 1399 updateIncomingBlock(OuterLoopHeader, InnerLoopPreHeader, OuterLoopPreHeader); 1400 updateIncomingBlock(OuterLoopHeader, InnerLoopLatch, OuterLoopLatch); 1401 updateIncomingBlock(InnerLoopHeader, OuterLoopPreHeader, InnerLoopPreHeader); 1402 updateIncomingBlock(InnerLoopHeader, OuterLoopLatch, InnerLoopLatch); 1403 1404 return true; 1405 } 1406 1407 void LoopInterchangeTransform::adjustLoopPreheaders() { 1408 // We have interchanged the preheaders so we need to interchange the data in 1409 // the preheader as well. 1410 // This is because the content of inner preheader was previously executed 1411 // inside the outer loop. 1412 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1413 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1414 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1415 BranchInst *InnerTermBI = 1416 cast<BranchInst>(InnerLoopPreHeader->getTerminator()); 1417 1418 // These instructions should now be executed inside the loop. 1419 // Move instruction into a new block after outer header. 1420 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); 1421 // These instructions were not executed previously in the loop so move them to 1422 // the older inner loop preheader. 1423 moveBBContents(OuterLoopPreHeader, InnerTermBI); 1424 } 1425 1426 bool LoopInterchangeTransform::adjustLoopLinks() { 1427 // Adjust all branches in the inner and outer loop. 1428 bool Changed = adjustLoopBranches(); 1429 if (Changed) 1430 adjustLoopPreheaders(); 1431 return Changed; 1432 } 1433 1434 char LoopInterchange::ID = 0; 1435 1436 INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", 1437 "Interchanges loops for cache reuse", false, false) 1438 INITIALIZE_PASS_DEPENDENCY(LoopPass) 1439 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1440 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 1441 1442 INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", 1443 "Interchanges loops for cache reuse", false, false) 1444 1445 Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } 1446