1 //===- LoopFlatten.cpp - Loop flattening 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 flattens pairs nested loops into a single loop. 10 // 11 // The intention is to optimise loop nests like this, which together access an 12 // array linearly: 13 // for (int i = 0; i < N; ++i) 14 // for (int j = 0; j < M; ++j) 15 // f(A[i*M+j]); 16 // into one loop: 17 // for (int i = 0; i < (N*M); ++i) 18 // f(A[i]); 19 // 20 // It can also flatten loops where the induction variables are not used in the 21 // loop. This is only worth doing if the induction variables are only used in an 22 // expression like i*M+j. If they had any other uses, we would have to insert a 23 // div/mod to reconstruct the original values, so this wouldn't be profitable. 24 // 25 // We also need to prove that N*M will not overflow. 26 // 27 //===----------------------------------------------------------------------===// 28 29 #include "llvm/Transforms/Scalar/LoopFlatten.h" 30 #include "llvm/Analysis/AssumptionCache.h" 31 #include "llvm/Analysis/LoopInfo.h" 32 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 33 #include "llvm/Analysis/ScalarEvolution.h" 34 #include "llvm/Analysis/TargetTransformInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/IR/Dominators.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/IRBuilder.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/IR/PatternMatch.h" 41 #include "llvm/IR/Verifier.h" 42 #include "llvm/InitializePasses.h" 43 #include "llvm/Pass.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Transforms/Scalar.h" 47 #include "llvm/Transforms/Utils/Local.h" 48 #include "llvm/Transforms/Utils/LoopUtils.h" 49 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 50 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 51 52 #define DEBUG_TYPE "loop-flatten" 53 54 using namespace llvm; 55 using namespace llvm::PatternMatch; 56 57 static cl::opt<unsigned> RepeatedInstructionThreshold( 58 "loop-flatten-cost-threshold", cl::Hidden, cl::init(2), 59 cl::desc("Limit on the cost of instructions that can be repeated due to " 60 "loop flattening")); 61 62 static cl::opt<bool> 63 AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, 64 cl::init(false), 65 cl::desc("Assume that the product of the two iteration " 66 "limits will never overflow")); 67 68 static cl::opt<bool> 69 WidenIV("loop-flatten-widen-iv", cl::Hidden, 70 cl::init(true), 71 cl::desc("Widen the loop induction variables, if possible, so " 72 "overflow checks won't reject flattening")); 73 74 struct FlattenInfo { 75 Loop *OuterLoop = nullptr; 76 Loop *InnerLoop = nullptr; 77 PHINode *InnerInductionPHI = nullptr; 78 PHINode *OuterInductionPHI = nullptr; 79 Value *InnerLimit = nullptr; 80 Value *OuterLimit = nullptr; 81 BinaryOperator *InnerIncrement = nullptr; 82 BinaryOperator *OuterIncrement = nullptr; 83 BranchInst *InnerBranch = nullptr; 84 BranchInst *OuterBranch = nullptr; 85 SmallPtrSet<Value *, 4> LinearIVUses; 86 SmallPtrSet<PHINode *, 4> InnerPHIsToTransform; 87 88 // Whether this holds the flatten info before or after widening. 89 bool Widened = false; 90 91 FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL) {}; 92 }; 93 94 // Finds the induction variable, increment and limit for a simple loop that we 95 // can flatten. 96 static bool findLoopComponents( 97 Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions, 98 PHINode *&InductionPHI, Value *&Limit, BinaryOperator *&Increment, 99 BranchInst *&BackBranch, ScalarEvolution *SE) { 100 LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n"); 101 102 if (!L->isLoopSimplifyForm()) { 103 LLVM_DEBUG(dbgs() << "Loop is not in normal form\n"); 104 return false; 105 } 106 107 // There must be exactly one exiting block, and it must be the same at the 108 // latch. 109 BasicBlock *Latch = L->getLoopLatch(); 110 if (L->getExitingBlock() != Latch) { 111 LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n"); 112 return false; 113 } 114 // Latch block must end in a conditional branch. 115 BackBranch = dyn_cast<BranchInst>(Latch->getTerminator()); 116 if (!BackBranch || !BackBranch->isConditional()) { 117 LLVM_DEBUG(dbgs() << "Could not find back-branch\n"); 118 return false; 119 } 120 IterationInstructions.insert(BackBranch); 121 LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump()); 122 bool ContinueOnTrue = L->contains(BackBranch->getSuccessor(0)); 123 124 // Find the induction PHI. If there is no induction PHI, we can't do the 125 // transformation. TODO: could other variables trigger this? Do we have to 126 // search for the best one? 127 InductionPHI = L->getInductionVariable(*SE); 128 if (!InductionPHI) { 129 LLVM_DEBUG(dbgs() << "Could not find induction PHI\n"); 130 return false; 131 } 132 LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump()); 133 134 auto IsValidPredicate = [&](ICmpInst::Predicate Pred) { 135 if (ContinueOnTrue) 136 return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT; 137 else 138 return Pred == CmpInst::ICMP_EQ; 139 }; 140 141 // Find Compare and make sure it is valid 142 ICmpInst *Compare = dyn_cast<ICmpInst>(BackBranch->getCondition()); 143 if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) || 144 Compare->hasNUsesOrMore(2)) { 145 LLVM_DEBUG(dbgs() << "Could not find valid comparison\n"); 146 return false; 147 } 148 IterationInstructions.insert(Compare); 149 LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump()); 150 151 // Find increment and limit from the compare 152 Increment = nullptr; 153 if (match(Compare->getOperand(0), 154 m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { 155 Increment = dyn_cast<BinaryOperator>(Compare->getOperand(0)); 156 Limit = Compare->getOperand(1); 157 } else if (Compare->getUnsignedPredicate() == CmpInst::ICMP_NE && 158 match(Compare->getOperand(1), 159 m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { 160 Increment = dyn_cast<BinaryOperator>(Compare->getOperand(1)); 161 Limit = Compare->getOperand(0); 162 } 163 if (!Increment || Increment->hasNUsesOrMore(3)) { 164 LLVM_DEBUG(dbgs() << "Cound not find valid increment\n"); 165 return false; 166 } 167 IterationInstructions.insert(Increment); 168 LLVM_DEBUG(dbgs() << "Found increment: "; Increment->dump()); 169 LLVM_DEBUG(dbgs() << "Found limit: "; Limit->dump()); 170 171 assert(InductionPHI->getNumIncomingValues() == 2); 172 173 if (InductionPHI->getIncomingValueForBlock(Latch) != Increment) { 174 LLVM_DEBUG( 175 dbgs() << "Incoming value from latch is not the increment inst\n"); 176 return false; 177 } 178 179 auto *CI = dyn_cast<ConstantInt>( 180 InductionPHI->getIncomingValueForBlock(L->getLoopPreheader())); 181 if (!CI || !CI->isZero()) { 182 LLVM_DEBUG(dbgs() << "PHI value is not zero: "; CI->dump()); 183 return false; 184 } 185 186 LLVM_DEBUG(dbgs() << "Successfully found all loop components\n"); 187 return true; 188 } 189 190 static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) { 191 // All PHIs in the inner and outer headers must either be: 192 // - The induction PHI, which we are going to rewrite as one induction in 193 // the new loop. This is already checked by findLoopComponents. 194 // - An outer header PHI with all incoming values from outside the loop. 195 // LoopSimplify guarantees we have a pre-header, so we don't need to 196 // worry about that here. 197 // - Pairs of PHIs in the inner and outer headers, which implement a 198 // loop-carried dependency that will still be valid in the new loop. To 199 // be valid, this variable must be modified only in the inner loop. 200 201 // The set of PHI nodes in the outer loop header that we know will still be 202 // valid after the transformation. These will not need to be modified (with 203 // the exception of the induction variable), but we do need to check that 204 // there are no unsafe PHI nodes. 205 SmallPtrSet<PHINode *, 4> SafeOuterPHIs; 206 SafeOuterPHIs.insert(FI.OuterInductionPHI); 207 208 // Check that all PHI nodes in the inner loop header match one of the valid 209 // patterns. 210 for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) { 211 // The induction PHIs break these rules, and that's OK because we treat 212 // them specially when doing the transformation. 213 if (&InnerPHI == FI.InnerInductionPHI) 214 continue; 215 216 // Each inner loop PHI node must have two incoming values/blocks - one 217 // from the pre-header, and one from the latch. 218 assert(InnerPHI.getNumIncomingValues() == 2); 219 Value *PreHeaderValue = 220 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader()); 221 Value *LatchValue = 222 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch()); 223 224 // The incoming value from the outer loop must be the PHI node in the 225 // outer loop header, with no modifications made in the top of the outer 226 // loop. 227 PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue); 228 if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) { 229 LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n"); 230 return false; 231 } 232 233 // The other incoming value must come from the inner loop, without any 234 // modifications in the tail end of the outer loop. We are in LCSSA form, 235 // so this will actually be a PHI in the inner loop's exit block, which 236 // only uses values from inside the inner loop. 237 PHINode *LCSSAPHI = dyn_cast<PHINode>( 238 OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch())); 239 if (!LCSSAPHI) { 240 LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n"); 241 return false; 242 } 243 244 // The value used by the LCSSA PHI must be the same one that the inner 245 // loop's PHI uses. 246 if (LCSSAPHI->hasConstantValue() != LatchValue) { 247 LLVM_DEBUG( 248 dbgs() << "LCSSA PHI incoming value does not match latch value\n"); 249 return false; 250 } 251 252 LLVM_DEBUG(dbgs() << "PHI pair is safe:\n"); 253 LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump()); 254 LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump()); 255 SafeOuterPHIs.insert(OuterPHI); 256 FI.InnerPHIsToTransform.insert(&InnerPHI); 257 } 258 259 for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) { 260 if (!SafeOuterPHIs.count(&OuterPHI)) { 261 LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump()); 262 return false; 263 } 264 } 265 266 LLVM_DEBUG(dbgs() << "checkPHIs: OK\n"); 267 return true; 268 } 269 270 static bool 271 checkOuterLoopInsts(FlattenInfo &FI, 272 SmallPtrSetImpl<Instruction *> &IterationInstructions, 273 const TargetTransformInfo *TTI) { 274 // Check for instructions in the outer but not inner loop. If any of these 275 // have side-effects then this transformation is not legal, and if there is 276 // a significant amount of code here which can't be optimised out that it's 277 // not profitable (as these instructions would get executed for each 278 // iteration of the inner loop). 279 InstructionCost RepeatedInstrCost = 0; 280 for (auto *B : FI.OuterLoop->getBlocks()) { 281 if (FI.InnerLoop->contains(B)) 282 continue; 283 284 for (auto &I : *B) { 285 if (!isa<PHINode>(&I) && !I.isTerminator() && 286 !isSafeToSpeculativelyExecute(&I)) { 287 LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have " 288 "side effects: "; 289 I.dump()); 290 return false; 291 } 292 // The execution count of the outer loop's iteration instructions 293 // (increment, compare and branch) will be increased, but the 294 // equivalent instructions will be removed from the inner loop, so 295 // they make a net difference of zero. 296 if (IterationInstructions.count(&I)) 297 continue; 298 // The uncoditional branch to the inner loop's header will turn into 299 // a fall-through, so adds no cost. 300 BranchInst *Br = dyn_cast<BranchInst>(&I); 301 if (Br && Br->isUnconditional() && 302 Br->getSuccessor(0) == FI.InnerLoop->getHeader()) 303 continue; 304 // Multiplies of the outer iteration variable and inner iteration 305 // count will be optimised out. 306 if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI), 307 m_Specific(FI.InnerLimit)))) 308 continue; 309 InstructionCost Cost = 310 TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 311 LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump()); 312 RepeatedInstrCost += Cost; 313 } 314 } 315 316 LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: " 317 << RepeatedInstrCost << "\n"); 318 // Bail out if flattening the loops would cause instructions in the outer 319 // loop but not in the inner loop to be executed extra times. 320 if (RepeatedInstrCost > RepeatedInstructionThreshold) { 321 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n"); 322 return false; 323 } 324 325 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n"); 326 return true; 327 } 328 329 static bool checkIVUsers(FlattenInfo &FI) { 330 // We require all uses of both induction variables to match this pattern: 331 // 332 // (OuterPHI * InnerLimit) + InnerPHI 333 // 334 // Any uses of the induction variables not matching that pattern would 335 // require a div/mod to reconstruct in the flattened loop, so the 336 // transformation wouldn't be profitable. 337 338 Value *InnerLimit = FI.InnerLimit; 339 if (FI.Widened && 340 (isa<SExtInst>(InnerLimit) || isa<ZExtInst>(InnerLimit))) 341 InnerLimit = cast<Instruction>(InnerLimit)->getOperand(0); 342 343 // Check that all uses of the inner loop's induction variable match the 344 // expected pattern, recording the uses of the outer IV. 345 SmallPtrSet<Value *, 4> ValidOuterPHIUses; 346 for (User *U : FI.InnerInductionPHI->users()) { 347 if (U == FI.InnerIncrement) 348 continue; 349 350 // After widening the IVs, a trunc instruction might have been introduced, so 351 // look through truncs. 352 if (isa<TruncInst>(U)) { 353 if (!U->hasOneUse()) 354 return false; 355 U = *U->user_begin(); 356 } 357 358 LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump()); 359 360 Value *MatchedMul; 361 Value *MatchedItCount; 362 bool IsAdd = match(U, m_c_Add(m_Specific(FI.InnerInductionPHI), 363 m_Value(MatchedMul))) && 364 match(MatchedMul, m_c_Mul(m_Specific(FI.OuterInductionPHI), 365 m_Value(MatchedItCount))); 366 367 // Matches the same pattern as above, except it also looks for truncs 368 // on the phi, which can be the result of widening the induction variables. 369 bool IsAddTrunc = match(U, m_c_Add(m_Trunc(m_Specific(FI.InnerInductionPHI)), 370 m_Value(MatchedMul))) && 371 match(MatchedMul, 372 m_c_Mul(m_Trunc(m_Specific(FI.OuterInductionPHI)), 373 m_Value(MatchedItCount))); 374 375 if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerLimit) { 376 LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 377 ValidOuterPHIUses.insert(MatchedMul); 378 FI.LinearIVUses.insert(U); 379 } else { 380 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 381 return false; 382 } 383 } 384 385 // Check that there are no uses of the outer IV other than the ones found 386 // as part of the pattern above. 387 for (User *U : FI.OuterInductionPHI->users()) { 388 if (U == FI.OuterIncrement) 389 continue; 390 391 auto IsValidOuterPHIUses = [&] (User *U) -> bool { 392 LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump()); 393 if (!ValidOuterPHIUses.count(U)) { 394 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 395 return false; 396 } 397 LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 398 return true; 399 }; 400 401 if (auto *V = dyn_cast<TruncInst>(U)) { 402 for (auto *K : V->users()) { 403 if (!IsValidOuterPHIUses(K)) 404 return false; 405 } 406 continue; 407 } 408 409 if (!IsValidOuterPHIUses(U)) 410 return false; 411 } 412 413 LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n"; 414 dbgs() << "Found " << FI.LinearIVUses.size() 415 << " value(s) that can be replaced:\n"; 416 for (Value *V : FI.LinearIVUses) { 417 dbgs() << " "; 418 V->dump(); 419 }); 420 return true; 421 } 422 423 // Return an OverflowResult dependant on if overflow of the multiplication of 424 // InnerLimit and OuterLimit can be assumed not to happen. 425 static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT, 426 AssumptionCache *AC) { 427 Function *F = FI.OuterLoop->getHeader()->getParent(); 428 const DataLayout &DL = F->getParent()->getDataLayout(); 429 430 // For debugging/testing. 431 if (AssumeNoOverflow) 432 return OverflowResult::NeverOverflows; 433 434 // Check if the multiply could not overflow due to known ranges of the 435 // input values. 436 OverflowResult OR = computeOverflowForUnsignedMul( 437 FI.InnerLimit, FI.OuterLimit, DL, AC, 438 FI.OuterLoop->getLoopPreheader()->getTerminator(), DT); 439 if (OR != OverflowResult::MayOverflow) 440 return OR; 441 442 for (Value *V : FI.LinearIVUses) { 443 for (Value *U : V->users()) { 444 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 445 // The IV is used as the operand of a GEP, and the IV is at least as 446 // wide as the address space of the GEP. In this case, the GEP would 447 // wrap around the address space before the IV increment wraps, which 448 // would be UB. 449 if (GEP->isInBounds() && 450 V->getType()->getIntegerBitWidth() >= 451 DL.getPointerTypeSizeInBits(GEP->getType())) { 452 LLVM_DEBUG( 453 dbgs() << "use of linear IV would be UB if overflow occurred: "; 454 GEP->dump()); 455 return OverflowResult::NeverOverflows; 456 } 457 } 458 } 459 } 460 461 return OverflowResult::MayOverflow; 462 } 463 464 static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 465 ScalarEvolution *SE, AssumptionCache *AC, 466 const TargetTransformInfo *TTI) { 467 SmallPtrSet<Instruction *, 8> IterationInstructions; 468 if (!findLoopComponents(FI.InnerLoop, IterationInstructions, FI.InnerInductionPHI, 469 FI.InnerLimit, FI.InnerIncrement, FI.InnerBranch, SE)) 470 return false; 471 if (!findLoopComponents(FI.OuterLoop, IterationInstructions, FI.OuterInductionPHI, 472 FI.OuterLimit, FI.OuterIncrement, FI.OuterBranch, SE)) 473 return false; 474 475 // Both of the loop limit values must be invariant in the outer loop 476 // (non-instructions are all inherently invariant). 477 if (!FI.OuterLoop->isLoopInvariant(FI.InnerLimit)) { 478 LLVM_DEBUG(dbgs() << "inner loop limit not invariant\n"); 479 return false; 480 } 481 if (!FI.OuterLoop->isLoopInvariant(FI.OuterLimit)) { 482 LLVM_DEBUG(dbgs() << "outer loop limit not invariant\n"); 483 return false; 484 } 485 486 if (!checkPHIs(FI, TTI)) 487 return false; 488 489 // FIXME: it should be possible to handle different types correctly. 490 if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType()) 491 return false; 492 493 if (!checkOuterLoopInsts(FI, IterationInstructions, TTI)) 494 return false; 495 496 // Find the values in the loop that can be replaced with the linearized 497 // induction variable, and check that there are no other uses of the inner 498 // or outer induction variable. If there were, we could still do this 499 // transformation, but we'd have to insert a div/mod to calculate the 500 // original IVs, so it wouldn't be profitable. 501 if (!checkIVUsers(FI)) 502 return false; 503 504 LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n"); 505 return true; 506 } 507 508 static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 509 ScalarEvolution *SE, AssumptionCache *AC, 510 const TargetTransformInfo *TTI) { 511 Function *F = FI.OuterLoop->getHeader()->getParent(); 512 LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n"); 513 { 514 using namespace ore; 515 OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(), 516 FI.InnerLoop->getHeader()); 517 OptimizationRemarkEmitter ORE(F); 518 Remark << "Flattened into outer loop"; 519 ORE.emit(Remark); 520 } 521 522 Value *NewTripCount = 523 BinaryOperator::CreateMul(FI.InnerLimit, FI.OuterLimit, "flatten.tripcount", 524 FI.OuterLoop->getLoopPreheader()->getTerminator()); 525 LLVM_DEBUG(dbgs() << "Created new trip count in preheader: "; 526 NewTripCount->dump()); 527 528 // Fix up PHI nodes that take values from the inner loop back-edge, which 529 // we are about to remove. 530 FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 531 532 // The old Phi will be optimised away later, but for now we can't leave 533 // leave it in an invalid state, so are updating them too. 534 for (PHINode *PHI : FI.InnerPHIsToTransform) 535 PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 536 537 // Modify the trip count of the outer loop to be the product of the two 538 // trip counts. 539 cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount); 540 541 // Replace the inner loop backedge with an unconditional branch to the exit. 542 BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock(); 543 BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock(); 544 InnerExitingBlock->getTerminator()->eraseFromParent(); 545 BranchInst::Create(InnerExitBlock, InnerExitingBlock); 546 DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader()); 547 548 // Replace all uses of the polynomial calculated from the two induction 549 // variables with the one new one. 550 IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator()); 551 for (Value *V : FI.LinearIVUses) { 552 Value *OuterValue = FI.OuterInductionPHI; 553 if (FI.Widened) 554 OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(), 555 "flatten.trunciv"); 556 557 LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); 558 dbgs() << "with: "; OuterValue->dump()); 559 V->replaceAllUsesWith(OuterValue); 560 } 561 562 // Tell LoopInfo, SCEV and the pass manager that the inner loop has been 563 // deleted, and any information that have about the outer loop invalidated. 564 SE->forgetLoop(FI.OuterLoop); 565 SE->forgetLoop(FI.InnerLoop); 566 LI->erase(FI.InnerLoop); 567 return true; 568 } 569 570 static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 571 ScalarEvolution *SE, AssumptionCache *AC, 572 const TargetTransformInfo *TTI) { 573 if (!WidenIV) { 574 LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n"); 575 return false; 576 } 577 578 LLVM_DEBUG(dbgs() << "Try widening the IVs\n"); 579 Module *M = FI.InnerLoop->getHeader()->getParent()->getParent(); 580 auto &DL = M->getDataLayout(); 581 auto *InnerType = FI.InnerInductionPHI->getType(); 582 auto *OuterType = FI.OuterInductionPHI->getType(); 583 unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits(); 584 auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext()); 585 586 // If both induction types are less than the maximum legal integer width, 587 // promote both to the widest type available so we know calculating 588 // (OuterLimit * InnerLimit) as the new trip count is safe. 589 if (InnerType != OuterType || 590 InnerType->getScalarSizeInBits() >= MaxLegalSize || 591 MaxLegalType->getScalarSizeInBits() < InnerType->getScalarSizeInBits() * 2) { 592 LLVM_DEBUG(dbgs() << "Can't widen the IV\n"); 593 return false; 594 } 595 596 SCEVExpander Rewriter(*SE, DL, "loopflatten"); 597 SmallVector<WideIVInfo, 2> WideIVs; 598 SmallVector<WeakTrackingVH, 4> DeadInsts; 599 WideIVs.push_back( {FI.InnerInductionPHI, MaxLegalType, false }); 600 WideIVs.push_back( {FI.OuterInductionPHI, MaxLegalType, false }); 601 unsigned ElimExt = 0; 602 unsigned Widened = 0; 603 604 for (const auto &WideIV : WideIVs) { 605 PHINode *WidePhi = createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, 606 ElimExt, Widened, true /* HasGuards */, 607 true /* UsePostIncrementRanges */); 608 if (!WidePhi) 609 return false; 610 LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump()); 611 LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump()); 612 RecursivelyDeleteDeadPHINode(WideIV.NarrowIV); 613 } 614 // After widening, rediscover all the loop components. 615 assert(Widened && "Widened IV expected"); 616 FI.Widened = true; 617 return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 618 } 619 620 static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 621 ScalarEvolution *SE, AssumptionCache *AC, 622 const TargetTransformInfo *TTI) { 623 LLVM_DEBUG( 624 dbgs() << "Loop flattening running on outer loop " 625 << FI.OuterLoop->getHeader()->getName() << " and inner loop " 626 << FI.InnerLoop->getHeader()->getName() << " in " 627 << FI.OuterLoop->getHeader()->getParent()->getName() << "\n"); 628 629 if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI)) 630 return false; 631 632 // Check if we can widen the induction variables to avoid overflow checks. 633 if (CanWidenIV(FI, DT, LI, SE, AC, TTI)) 634 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 635 636 // Check if the new iteration variable might overflow. In this case, we 637 // need to version the loop, and select the original version at runtime if 638 // the iteration space is too large. 639 // TODO: We currently don't version the loop. 640 OverflowResult OR = checkOverflow(FI, DT, AC); 641 if (OR == OverflowResult::AlwaysOverflowsHigh || 642 OR == OverflowResult::AlwaysOverflowsLow) { 643 LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n"); 644 return false; 645 } else if (OR == OverflowResult::MayOverflow) { 646 LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n"); 647 return false; 648 } 649 650 LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n"); 651 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 652 } 653 654 bool Flatten(LoopNest &LN, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, 655 AssumptionCache *AC, TargetTransformInfo *TTI) { 656 bool Changed = false; 657 for (Loop *InnerLoop : LN.getLoops()) { 658 auto *OuterLoop = InnerLoop->getParentLoop(); 659 if (!OuterLoop) 660 continue; 661 FlattenInfo FI(OuterLoop, InnerLoop); 662 Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI); 663 } 664 return Changed; 665 } 666 667 PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM, 668 LoopStandardAnalysisResults &AR, 669 LPMUpdater &U) { 670 671 bool Changed = false; 672 673 // The loop flattening pass requires loops to be 674 // in simplified form, and also needs LCSSA. Running 675 // this pass will simplify all loops that contain inner loops, 676 // regardless of whether anything ends up being flattened. 677 Changed |= Flatten(LN, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI); 678 679 if (!Changed) 680 return PreservedAnalyses::all(); 681 682 return PreservedAnalyses::none(); 683 } 684 685 namespace { 686 class LoopFlattenLegacyPass : public FunctionPass { 687 public: 688 static char ID; // Pass ID, replacement for typeid 689 LoopFlattenLegacyPass() : FunctionPass(ID) { 690 initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry()); 691 } 692 693 // Possibly flatten loop L into its child. 694 bool runOnFunction(Function &F) override; 695 696 void getAnalysisUsage(AnalysisUsage &AU) const override { 697 getLoopAnalysisUsage(AU); 698 AU.addRequired<TargetTransformInfoWrapperPass>(); 699 AU.addPreserved<TargetTransformInfoWrapperPass>(); 700 AU.addRequired<AssumptionCacheTracker>(); 701 AU.addPreserved<AssumptionCacheTracker>(); 702 } 703 }; 704 } // namespace 705 706 char LoopFlattenLegacyPass::ID = 0; 707 INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 708 false, false) 709 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 710 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 711 INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 712 false, false) 713 714 FunctionPass *llvm::createLoopFlattenPass() { return new LoopFlattenLegacyPass(); } 715 716 bool LoopFlattenLegacyPass::runOnFunction(Function &F) { 717 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 718 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 719 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 720 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 721 auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>(); 722 auto *TTI = &TTIP.getTTI(F); 723 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 724 bool Changed = false; 725 for (Loop *L : *LI) { 726 auto LN = LoopNest::getLoopNest(*L, *SE); 727 Changed |= Flatten(*LN, DT, LI, SE, AC, TTI); 728 } 729 return Changed; 730 } 731