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