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