1e8d8bef9SDimitry Andric //===- LoopPeel.cpp -------------------------------------------------------===// 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 // Loop Peeling Utilities. 10e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 11e8d8bef9SDimitry Andric 12e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopPeel.h" 13e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h" 14e8d8bef9SDimitry Andric #include "llvm/ADT/Optional.h" 15e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h" 16e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h" 17349cc55cSDimitry Andric #include "llvm/Analysis/Loads.h" 18e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 19e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopIterator.h" 20e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 21e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h" 22e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 23e8d8bef9SDimitry Andric #include "llvm/IR/BasicBlock.h" 24e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 25e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 26e8d8bef9SDimitry Andric #include "llvm/IR/InstrTypes.h" 27e8d8bef9SDimitry Andric #include "llvm/IR/Instruction.h" 28e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h" 29e8d8bef9SDimitry Andric #include "llvm/IR/LLVMContext.h" 30e8d8bef9SDimitry Andric #include "llvm/IR/MDBuilder.h" 31e8d8bef9SDimitry Andric #include "llvm/IR/Metadata.h" 32e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h" 33e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 34e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h" 35e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 36e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 37e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 39e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopSimplify.h" 40e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 41e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/UnrollLoop.h" 42e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h" 43e8d8bef9SDimitry Andric #include <algorithm> 44e8d8bef9SDimitry Andric #include <cassert> 45e8d8bef9SDimitry Andric #include <cstdint> 46e8d8bef9SDimitry Andric #include <limits> 47e8d8bef9SDimitry Andric 48e8d8bef9SDimitry Andric using namespace llvm; 49e8d8bef9SDimitry Andric using namespace llvm::PatternMatch; 50e8d8bef9SDimitry Andric 51e8d8bef9SDimitry Andric #define DEBUG_TYPE "loop-peel" 52e8d8bef9SDimitry Andric 53e8d8bef9SDimitry Andric STATISTIC(NumPeeled, "Number of loops peeled"); 54e8d8bef9SDimitry Andric 55e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelCount( 56e8d8bef9SDimitry Andric "unroll-peel-count", cl::Hidden, 57e8d8bef9SDimitry Andric cl::desc("Set the unroll peeling count, for testing purposes")); 58e8d8bef9SDimitry Andric 59e8d8bef9SDimitry Andric static cl::opt<bool> 60e8d8bef9SDimitry Andric UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 61e8d8bef9SDimitry Andric cl::desc("Allows loops to be peeled when the dynamic " 62e8d8bef9SDimitry Andric "trip count is known to be low.")); 63e8d8bef9SDimitry Andric 64e8d8bef9SDimitry Andric static cl::opt<bool> 65e8d8bef9SDimitry Andric UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", 66e8d8bef9SDimitry Andric cl::init(false), cl::Hidden, 67e8d8bef9SDimitry Andric cl::desc("Allows loop nests to be peeled.")); 68e8d8bef9SDimitry Andric 69e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelMaxCount( 70e8d8bef9SDimitry Andric "unroll-peel-max-count", cl::init(7), cl::Hidden, 71e8d8bef9SDimitry Andric cl::desc("Max average trip count which will cause loop peeling.")); 72e8d8bef9SDimitry Andric 73e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollForcePeelCount( 74e8d8bef9SDimitry Andric "unroll-force-peel-count", cl::init(0), cl::Hidden, 75e8d8bef9SDimitry Andric cl::desc("Force a peel count regardless of profiling information.")); 76e8d8bef9SDimitry Andric 77e8d8bef9SDimitry Andric static const char *PeeledCountMetaData = "llvm.loop.peeled.count"; 78e8d8bef9SDimitry Andric 79e8d8bef9SDimitry Andric // Check whether we are capable of peeling this loop. 80e8d8bef9SDimitry Andric bool llvm::canPeel(Loop *L) { 81e8d8bef9SDimitry Andric // Make sure the loop is in simplified form 82e8d8bef9SDimitry Andric if (!L->isLoopSimplifyForm()) 83e8d8bef9SDimitry Andric return false; 84e8d8bef9SDimitry Andric 85e8d8bef9SDimitry Andric // Don't try to peel loops where the latch is not the exiting block. 86e8d8bef9SDimitry Andric // This can be an indication of two different things: 87e8d8bef9SDimitry Andric // 1) The loop is not rotated. 88e8d8bef9SDimitry Andric // 2) The loop contains irreducible control flow that involves the latch. 89e8d8bef9SDimitry Andric const BasicBlock *Latch = L->getLoopLatch(); 90349cc55cSDimitry Andric if (!L->isLoopExiting(Latch)) 91e8d8bef9SDimitry Andric return false; 92e8d8bef9SDimitry Andric 93e8d8bef9SDimitry Andric // Peeling is only supported if the latch is a branch. 94e8d8bef9SDimitry Andric if (!isa<BranchInst>(Latch->getTerminator())) 95e8d8bef9SDimitry Andric return false; 96e8d8bef9SDimitry Andric 97349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 98349cc55cSDimitry Andric L->getUniqueNonLatchExitBlocks(Exits); 99349cc55cSDimitry Andric // The latch must either be the only exiting block or all non-latch exit 100349cc55cSDimitry Andric // blocks have either a deopt or unreachable terminator or compose a chain of 101349cc55cSDimitry Andric // blocks where the last one is either deopt or unreachable terminated. Both 102349cc55cSDimitry Andric // deopt and unreachable terminators are a strong indication they are not 103349cc55cSDimitry Andric // taken. Note that this is a profitability check, not a legality check. Also 104349cc55cSDimitry Andric // note that LoopPeeling currently can only update the branch weights of latch 105349cc55cSDimitry Andric // blocks and branch weights to blocks with deopt or unreachable do not need 106349cc55cSDimitry Andric // updating. 107*0eae32dcSDimitry Andric return llvm::all_of(Exits, IsBlockFollowedByDeoptOrUnreachable); 108e8d8bef9SDimitry Andric } 109e8d8bef9SDimitry Andric 110e8d8bef9SDimitry Andric // This function calculates the number of iterations after which the given Phi 111e8d8bef9SDimitry Andric // becomes an invariant. The pre-calculated values are memorized in the map. The 112e8d8bef9SDimitry Andric // function (shortcut is I) is calculated according to the following definition: 113e8d8bef9SDimitry Andric // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge]. 114e8d8bef9SDimitry Andric // If %y is a loop invariant, then I(%x) = 1. 115e8d8bef9SDimitry Andric // If %y is a Phi from the loop header, I(%x) = I(%y) + 1. 116e8d8bef9SDimitry Andric // Otherwise, I(%x) is infinite. 117e8d8bef9SDimitry Andric // TODO: Actually if %y is an expression that depends only on Phi %z and some 118e8d8bef9SDimitry Andric // loop invariants, we can estimate I(%x) = I(%z) + 1. The example 119e8d8bef9SDimitry Andric // looks like: 120e8d8bef9SDimitry Andric // %x = phi(0, %a), <-- becomes invariant starting from 3rd iteration. 121e8d8bef9SDimitry Andric // %y = phi(0, 5), 122e8d8bef9SDimitry Andric // %a = %y + 1. 123349cc55cSDimitry Andric static Optional<unsigned> calculateIterationsToInvariance( 124e8d8bef9SDimitry Andric PHINode *Phi, Loop *L, BasicBlock *BackEdge, 125349cc55cSDimitry Andric SmallDenseMap<PHINode *, Optional<unsigned> > &IterationsToInvariance) { 126e8d8bef9SDimitry Andric assert(Phi->getParent() == L->getHeader() && 127e8d8bef9SDimitry Andric "Non-loop Phi should not be checked for turning into invariant."); 128e8d8bef9SDimitry Andric assert(BackEdge == L->getLoopLatch() && "Wrong latch?"); 129e8d8bef9SDimitry Andric // If we already know the answer, take it from the map. 130e8d8bef9SDimitry Andric auto I = IterationsToInvariance.find(Phi); 131e8d8bef9SDimitry Andric if (I != IterationsToInvariance.end()) 132e8d8bef9SDimitry Andric return I->second; 133e8d8bef9SDimitry Andric 134e8d8bef9SDimitry Andric // Otherwise we need to analyze the input from the back edge. 135e8d8bef9SDimitry Andric Value *Input = Phi->getIncomingValueForBlock(BackEdge); 136e8d8bef9SDimitry Andric // Place infinity to map to avoid infinite recursion for cycled Phis. Such 137e8d8bef9SDimitry Andric // cycles can never stop on an invariant. 138349cc55cSDimitry Andric IterationsToInvariance[Phi] = None; 139349cc55cSDimitry Andric Optional<unsigned> ToInvariance = None; 140e8d8bef9SDimitry Andric 141e8d8bef9SDimitry Andric if (L->isLoopInvariant(Input)) 142e8d8bef9SDimitry Andric ToInvariance = 1u; 143e8d8bef9SDimitry Andric else if (PHINode *IncPhi = dyn_cast<PHINode>(Input)) { 144e8d8bef9SDimitry Andric // Only consider Phis in header block. 145e8d8bef9SDimitry Andric if (IncPhi->getParent() != L->getHeader()) 146349cc55cSDimitry Andric return None; 147e8d8bef9SDimitry Andric // If the input becomes an invariant after X iterations, then our Phi 148e8d8bef9SDimitry Andric // becomes an invariant after X + 1 iterations. 149349cc55cSDimitry Andric auto InputToInvariance = calculateIterationsToInvariance( 150e8d8bef9SDimitry Andric IncPhi, L, BackEdge, IterationsToInvariance); 151349cc55cSDimitry Andric if (InputToInvariance) 152349cc55cSDimitry Andric ToInvariance = *InputToInvariance + 1u; 153e8d8bef9SDimitry Andric } 154e8d8bef9SDimitry Andric 155e8d8bef9SDimitry Andric // If we found that this Phi lies in an invariant chain, update the map. 156349cc55cSDimitry Andric if (ToInvariance) 157e8d8bef9SDimitry Andric IterationsToInvariance[Phi] = ToInvariance; 158e8d8bef9SDimitry Andric return ToInvariance; 159e8d8bef9SDimitry Andric } 160e8d8bef9SDimitry Andric 161349cc55cSDimitry Andric // Try to find any invariant memory reads that will become dereferenceable in 162349cc55cSDimitry Andric // the remainder loop after peeling. The load must also be used (transitively) 163349cc55cSDimitry Andric // by an exit condition. Returns the number of iterations to peel off (at the 164349cc55cSDimitry Andric // moment either 0 or 1). 165349cc55cSDimitry Andric static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, 166349cc55cSDimitry Andric DominatorTree &DT) { 167349cc55cSDimitry Andric // Skip loops with a single exiting block, because there should be no benefit 168349cc55cSDimitry Andric // for the heuristic below. 169349cc55cSDimitry Andric if (L.getExitingBlock()) 170349cc55cSDimitry Andric return 0; 171349cc55cSDimitry Andric 172349cc55cSDimitry Andric // All non-latch exit blocks must have an UnreachableInst terminator. 173349cc55cSDimitry Andric // Otherwise the heuristic below may not be profitable. 174349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 175349cc55cSDimitry Andric L.getUniqueNonLatchExitBlocks(Exits); 176349cc55cSDimitry Andric if (any_of(Exits, [](const BasicBlock *BB) { 177349cc55cSDimitry Andric return !isa<UnreachableInst>(BB->getTerminator()); 178349cc55cSDimitry Andric })) 179349cc55cSDimitry Andric return 0; 180349cc55cSDimitry Andric 181349cc55cSDimitry Andric // Now look for invariant loads that dominate the latch and are not known to 182349cc55cSDimitry Andric // be dereferenceable. If there are such loads and no writes, they will become 183349cc55cSDimitry Andric // dereferenceable in the loop if the first iteration is peeled off. Also 184349cc55cSDimitry Andric // collect the set of instructions controlled by such loads. Only peel if an 185349cc55cSDimitry Andric // exit condition uses (transitively) such a load. 186349cc55cSDimitry Andric BasicBlock *Header = L.getHeader(); 187349cc55cSDimitry Andric BasicBlock *Latch = L.getLoopLatch(); 188349cc55cSDimitry Andric SmallPtrSet<Value *, 8> LoadUsers; 189349cc55cSDimitry Andric const DataLayout &DL = L.getHeader()->getModule()->getDataLayout(); 190349cc55cSDimitry Andric for (BasicBlock *BB : L.blocks()) { 191349cc55cSDimitry Andric for (Instruction &I : *BB) { 192349cc55cSDimitry Andric if (I.mayWriteToMemory()) 193349cc55cSDimitry Andric return 0; 194349cc55cSDimitry Andric 195349cc55cSDimitry Andric auto Iter = LoadUsers.find(&I); 196349cc55cSDimitry Andric if (Iter != LoadUsers.end()) { 197349cc55cSDimitry Andric for (Value *U : I.users()) 198349cc55cSDimitry Andric LoadUsers.insert(U); 199349cc55cSDimitry Andric } 200349cc55cSDimitry Andric // Do not look for reads in the header; they can already be hoisted 201349cc55cSDimitry Andric // without peeling. 202349cc55cSDimitry Andric if (BB == Header) 203349cc55cSDimitry Andric continue; 204349cc55cSDimitry Andric if (auto *LI = dyn_cast<LoadInst>(&I)) { 205349cc55cSDimitry Andric Value *Ptr = LI->getPointerOperand(); 206349cc55cSDimitry Andric if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) && 207349cc55cSDimitry Andric !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, &DT)) 208349cc55cSDimitry Andric for (Value *U : I.users()) 209349cc55cSDimitry Andric LoadUsers.insert(U); 210349cc55cSDimitry Andric } 211349cc55cSDimitry Andric } 212349cc55cSDimitry Andric } 213349cc55cSDimitry Andric SmallVector<BasicBlock *> ExitingBlocks; 214349cc55cSDimitry Andric L.getExitingBlocks(ExitingBlocks); 215349cc55cSDimitry Andric if (any_of(ExitingBlocks, [&LoadUsers](BasicBlock *Exiting) { 216349cc55cSDimitry Andric return LoadUsers.contains(Exiting->getTerminator()); 217349cc55cSDimitry Andric })) 218349cc55cSDimitry Andric return 1; 219349cc55cSDimitry Andric return 0; 220349cc55cSDimitry Andric } 221349cc55cSDimitry Andric 222e8d8bef9SDimitry Andric // Return the number of iterations to peel off that make conditions in the 223e8d8bef9SDimitry Andric // body true/false. For example, if we peel 2 iterations off the loop below, 224e8d8bef9SDimitry Andric // the condition i < 2 can be evaluated at compile time. 225e8d8bef9SDimitry Andric // for (i = 0; i < n; i++) 226e8d8bef9SDimitry Andric // if (i < 2) 227e8d8bef9SDimitry Andric // .. 228e8d8bef9SDimitry Andric // else 229e8d8bef9SDimitry Andric // .. 230e8d8bef9SDimitry Andric // } 231e8d8bef9SDimitry Andric static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, 232e8d8bef9SDimitry Andric ScalarEvolution &SE) { 233e8d8bef9SDimitry Andric assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form"); 234e8d8bef9SDimitry Andric unsigned DesiredPeelCount = 0; 235e8d8bef9SDimitry Andric 236e8d8bef9SDimitry Andric for (auto *BB : L.blocks()) { 237e8d8bef9SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 238e8d8bef9SDimitry Andric if (!BI || BI->isUnconditional()) 239e8d8bef9SDimitry Andric continue; 240e8d8bef9SDimitry Andric 241e8d8bef9SDimitry Andric // Ignore loop exit condition. 242e8d8bef9SDimitry Andric if (L.getLoopLatch() == BB) 243e8d8bef9SDimitry Andric continue; 244e8d8bef9SDimitry Andric 245e8d8bef9SDimitry Andric Value *Condition = BI->getCondition(); 246e8d8bef9SDimitry Andric Value *LeftVal, *RightVal; 247e8d8bef9SDimitry Andric CmpInst::Predicate Pred; 248e8d8bef9SDimitry Andric if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal)))) 249e8d8bef9SDimitry Andric continue; 250e8d8bef9SDimitry Andric 251e8d8bef9SDimitry Andric const SCEV *LeftSCEV = SE.getSCEV(LeftVal); 252e8d8bef9SDimitry Andric const SCEV *RightSCEV = SE.getSCEV(RightVal); 253e8d8bef9SDimitry Andric 254e8d8bef9SDimitry Andric // Do not consider predicates that are known to be true or false 255e8d8bef9SDimitry Andric // independently of the loop iteration. 256fe6060f1SDimitry Andric if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV)) 257e8d8bef9SDimitry Andric continue; 258e8d8bef9SDimitry Andric 259e8d8bef9SDimitry Andric // Check if we have a condition with one AddRec and one non AddRec 260e8d8bef9SDimitry Andric // expression. Normalize LeftSCEV to be the AddRec. 261e8d8bef9SDimitry Andric if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 262e8d8bef9SDimitry Andric if (isa<SCEVAddRecExpr>(RightSCEV)) { 263e8d8bef9SDimitry Andric std::swap(LeftSCEV, RightSCEV); 264e8d8bef9SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred); 265e8d8bef9SDimitry Andric } else 266e8d8bef9SDimitry Andric continue; 267e8d8bef9SDimitry Andric } 268e8d8bef9SDimitry Andric 269e8d8bef9SDimitry Andric const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV); 270e8d8bef9SDimitry Andric 271e8d8bef9SDimitry Andric // Avoid huge SCEV computations in the loop below, make sure we only 272e8d8bef9SDimitry Andric // consider AddRecs of the loop we are trying to peel. 273e8d8bef9SDimitry Andric if (!LeftAR->isAffine() || LeftAR->getLoop() != &L) 274e8d8bef9SDimitry Andric continue; 275e8d8bef9SDimitry Andric if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) && 276e8d8bef9SDimitry Andric !SE.getMonotonicPredicateType(LeftAR, Pred)) 277e8d8bef9SDimitry Andric continue; 278e8d8bef9SDimitry Andric 279e8d8bef9SDimitry Andric // Check if extending the current DesiredPeelCount lets us evaluate Pred 280e8d8bef9SDimitry Andric // or !Pred in the loop body statically. 281e8d8bef9SDimitry Andric unsigned NewPeelCount = DesiredPeelCount; 282e8d8bef9SDimitry Andric 283e8d8bef9SDimitry Andric const SCEV *IterVal = LeftAR->evaluateAtIteration( 284e8d8bef9SDimitry Andric SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE); 285e8d8bef9SDimitry Andric 286e8d8bef9SDimitry Andric // If the original condition is not known, get the negated predicate 287e8d8bef9SDimitry Andric // (which holds on the else branch) and check if it is known. This allows 288e8d8bef9SDimitry Andric // us to peel of iterations that make the original condition false. 289e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 290e8d8bef9SDimitry Andric Pred = ICmpInst::getInversePredicate(Pred); 291e8d8bef9SDimitry Andric 292e8d8bef9SDimitry Andric const SCEV *Step = LeftAR->getStepRecurrence(SE); 293e8d8bef9SDimitry Andric const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step); 294e8d8bef9SDimitry Andric auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step, 295e8d8bef9SDimitry Andric &NewPeelCount]() { 296e8d8bef9SDimitry Andric IterVal = NextIterVal; 297e8d8bef9SDimitry Andric NextIterVal = SE.getAddExpr(IterVal, Step); 298e8d8bef9SDimitry Andric NewPeelCount++; 299e8d8bef9SDimitry Andric }; 300e8d8bef9SDimitry Andric 301e8d8bef9SDimitry Andric auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() { 302e8d8bef9SDimitry Andric return NewPeelCount < MaxPeelCount; 303e8d8bef9SDimitry Andric }; 304e8d8bef9SDimitry Andric 305e8d8bef9SDimitry Andric while (CanPeelOneMoreIteration() && 306e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 307e8d8bef9SDimitry Andric PeelOneMoreIteration(); 308e8d8bef9SDimitry Andric 309e8d8bef9SDimitry Andric // With *that* peel count, does the predicate !Pred become known in the 310e8d8bef9SDimitry Andric // first iteration of the loop body after peeling? 311e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal, 312e8d8bef9SDimitry Andric RightSCEV)) 313e8d8bef9SDimitry Andric continue; // If not, give up. 314e8d8bef9SDimitry Andric 315e8d8bef9SDimitry Andric // However, for equality comparisons, that isn't always sufficient to 316e8d8bef9SDimitry Andric // eliminate the comparsion in loop body, we may need to peel one more 317e8d8bef9SDimitry Andric // iteration. See if that makes !Pred become unknown again. 318e8d8bef9SDimitry Andric if (ICmpInst::isEquality(Pred) && 319e8d8bef9SDimitry Andric !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal, 320e8d8bef9SDimitry Andric RightSCEV) && 321e8d8bef9SDimitry Andric !SE.isKnownPredicate(Pred, IterVal, RightSCEV) && 322e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) { 323e8d8bef9SDimitry Andric if (!CanPeelOneMoreIteration()) 324e8d8bef9SDimitry Andric continue; // Need to peel one more iteration, but can't. Give up. 325e8d8bef9SDimitry Andric PeelOneMoreIteration(); // Great! 326e8d8bef9SDimitry Andric } 327e8d8bef9SDimitry Andric 328e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount); 329e8d8bef9SDimitry Andric } 330e8d8bef9SDimitry Andric 331e8d8bef9SDimitry Andric return DesiredPeelCount; 332e8d8bef9SDimitry Andric } 333e8d8bef9SDimitry Andric 334*0eae32dcSDimitry Andric /// This "heuristic" exactly matches implicit behavior which used to exist 335*0eae32dcSDimitry Andric /// inside getLoopEstimatedTripCount. It was added here to keep an 336*0eae32dcSDimitry Andric /// improvement inside that API from causing peeling to become more agressive. 337*0eae32dcSDimitry Andric /// This should probably be removed. 338*0eae32dcSDimitry Andric static bool violatesLegacyMultiExitLoopCheck(Loop *L) { 339*0eae32dcSDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 340*0eae32dcSDimitry Andric if (!Latch) 341*0eae32dcSDimitry Andric return true; 342*0eae32dcSDimitry Andric 343*0eae32dcSDimitry Andric BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 344*0eae32dcSDimitry Andric if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 345*0eae32dcSDimitry Andric return true; 346*0eae32dcSDimitry Andric 347*0eae32dcSDimitry Andric assert((LatchBR->getSuccessor(0) == L->getHeader() || 348*0eae32dcSDimitry Andric LatchBR->getSuccessor(1) == L->getHeader()) && 349*0eae32dcSDimitry Andric "At least one edge out of the latch must go to the header"); 350*0eae32dcSDimitry Andric 351*0eae32dcSDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks; 352*0eae32dcSDimitry Andric L->getUniqueNonLatchExitBlocks(ExitBlocks); 353*0eae32dcSDimitry Andric return any_of(ExitBlocks, [](const BasicBlock *EB) { 354*0eae32dcSDimitry Andric return !EB->getTerminatingDeoptimizeCall(); 355*0eae32dcSDimitry Andric }); 356*0eae32dcSDimitry Andric } 357*0eae32dcSDimitry Andric 358*0eae32dcSDimitry Andric 359e8d8bef9SDimitry Andric // Return the number of iterations we want to peel off. 360e8d8bef9SDimitry Andric void llvm::computePeelCount(Loop *L, unsigned LoopSize, 361e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences &PP, 362349cc55cSDimitry Andric unsigned &TripCount, DominatorTree &DT, 363349cc55cSDimitry Andric ScalarEvolution &SE, unsigned Threshold) { 364e8d8bef9SDimitry Andric assert(LoopSize > 0 && "Zero loop size is not allowed!"); 365e8d8bef9SDimitry Andric // Save the PP.PeelCount value set by the target in 366e8d8bef9SDimitry Andric // TTI.getPeelingPreferences or by the flag -unroll-peel-count. 367e8d8bef9SDimitry Andric unsigned TargetPeelCount = PP.PeelCount; 368e8d8bef9SDimitry Andric PP.PeelCount = 0; 369e8d8bef9SDimitry Andric if (!canPeel(L)) 370e8d8bef9SDimitry Andric return; 371e8d8bef9SDimitry Andric 372e8d8bef9SDimitry Andric // Only try to peel innermost loops by default. 373e8d8bef9SDimitry Andric // The constraint can be relaxed by the target in TTI.getUnrollingPreferences 374e8d8bef9SDimitry Andric // or by the flag -unroll-allow-loop-nests-peeling. 375e8d8bef9SDimitry Andric if (!PP.AllowLoopNestsPeeling && !L->isInnermost()) 376e8d8bef9SDimitry Andric return; 377e8d8bef9SDimitry Andric 378e8d8bef9SDimitry Andric // If the user provided a peel count, use that. 379e8d8bef9SDimitry Andric bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0; 380e8d8bef9SDimitry Andric if (UserPeelCount) { 381e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount 382e8d8bef9SDimitry Andric << " iterations.\n"); 383e8d8bef9SDimitry Andric PP.PeelCount = UnrollForcePeelCount; 384e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 385e8d8bef9SDimitry Andric return; 386e8d8bef9SDimitry Andric } 387e8d8bef9SDimitry Andric 388e8d8bef9SDimitry Andric // Skip peeling if it's disabled. 389e8d8bef9SDimitry Andric if (!PP.AllowPeeling) 390e8d8bef9SDimitry Andric return; 391e8d8bef9SDimitry Andric 392e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 393e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 394e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 395e8d8bef9SDimitry Andric // Stop if we already peeled off the maximum number of iterations. 396e8d8bef9SDimitry Andric if (AlreadyPeeled >= UnrollPeelMaxCount) 397e8d8bef9SDimitry Andric return; 398e8d8bef9SDimitry Andric 399e8d8bef9SDimitry Andric // Here we try to get rid of Phis which become invariants after 1, 2, ..., N 400e8d8bef9SDimitry Andric // iterations of the loop. For this we compute the number for iterations after 401e8d8bef9SDimitry Andric // which every Phi is guaranteed to become an invariant, and try to peel the 402e8d8bef9SDimitry Andric // maximum number of iterations among these values, thus turning all those 403e8d8bef9SDimitry Andric // Phis into invariants. 404e8d8bef9SDimitry Andric // First, check that we can peel at least one iteration. 405e8d8bef9SDimitry Andric if (2 * LoopSize <= Threshold && UnrollPeelMaxCount > 0) { 406e8d8bef9SDimitry Andric // Store the pre-calculated values here. 407349cc55cSDimitry Andric SmallDenseMap<PHINode *, Optional<unsigned> > IterationsToInvariance; 408e8d8bef9SDimitry Andric // Now go through all Phis to calculate their the number of iterations they 409e8d8bef9SDimitry Andric // need to become invariants. 410e8d8bef9SDimitry Andric // Start the max computation with the UP.PeelCount value set by the target 411e8d8bef9SDimitry Andric // in TTI.getUnrollingPreferences or by the flag -unroll-peel-count. 412e8d8bef9SDimitry Andric unsigned DesiredPeelCount = TargetPeelCount; 413e8d8bef9SDimitry Andric BasicBlock *BackEdge = L->getLoopLatch(); 414e8d8bef9SDimitry Andric assert(BackEdge && "Loop is not in simplified form?"); 415e8d8bef9SDimitry Andric for (auto BI = L->getHeader()->begin(); isa<PHINode>(&*BI); ++BI) { 416e8d8bef9SDimitry Andric PHINode *Phi = cast<PHINode>(&*BI); 417349cc55cSDimitry Andric auto ToInvariance = calculateIterationsToInvariance( 418e8d8bef9SDimitry Andric Phi, L, BackEdge, IterationsToInvariance); 419349cc55cSDimitry Andric if (ToInvariance) 420349cc55cSDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, *ToInvariance); 421e8d8bef9SDimitry Andric } 422e8d8bef9SDimitry Andric 423e8d8bef9SDimitry Andric // Pay respect to limitations implied by loop size and the max peel count. 424e8d8bef9SDimitry Andric unsigned MaxPeelCount = UnrollPeelMaxCount; 425e8d8bef9SDimitry Andric MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1); 426e8d8bef9SDimitry Andric 427e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, 428e8d8bef9SDimitry Andric countToEliminateCompares(*L, MaxPeelCount, SE)); 429e8d8bef9SDimitry Andric 430349cc55cSDimitry Andric if (DesiredPeelCount == 0) 431349cc55cSDimitry Andric DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT); 432349cc55cSDimitry Andric 433e8d8bef9SDimitry Andric if (DesiredPeelCount > 0) { 434e8d8bef9SDimitry Andric DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount); 435e8d8bef9SDimitry Andric // Consider max peel count limitation. 436e8d8bef9SDimitry Andric assert(DesiredPeelCount > 0 && "Wrong loop size estimation?"); 437e8d8bef9SDimitry Andric if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) { 438e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount 439e8d8bef9SDimitry Andric << " iteration(s) to turn" 440e8d8bef9SDimitry Andric << " some Phis into invariants.\n"); 441e8d8bef9SDimitry Andric PP.PeelCount = DesiredPeelCount; 442e8d8bef9SDimitry Andric PP.PeelProfiledIterations = false; 443e8d8bef9SDimitry Andric return; 444e8d8bef9SDimitry Andric } 445e8d8bef9SDimitry Andric } 446e8d8bef9SDimitry Andric } 447e8d8bef9SDimitry Andric 448e8d8bef9SDimitry Andric // Bail if we know the statically calculated trip count. 449e8d8bef9SDimitry Andric // In this case we rather prefer partial unrolling. 450e8d8bef9SDimitry Andric if (TripCount) 451e8d8bef9SDimitry Andric return; 452e8d8bef9SDimitry Andric 453e8d8bef9SDimitry Andric // Do not apply profile base peeling if it is disabled. 454e8d8bef9SDimitry Andric if (!PP.PeelProfiledIterations) 455e8d8bef9SDimitry Andric return; 456e8d8bef9SDimitry Andric // If we don't know the trip count, but have reason to believe the average 457e8d8bef9SDimitry Andric // trip count is low, peeling should be beneficial, since we will usually 458e8d8bef9SDimitry Andric // hit the peeled section. 459e8d8bef9SDimitry Andric // We only do this in the presence of profile information, since otherwise 460e8d8bef9SDimitry Andric // our estimates of the trip count are not reliable enough. 461e8d8bef9SDimitry Andric if (L->getHeader()->getParent()->hasProfileData()) { 462*0eae32dcSDimitry Andric if (violatesLegacyMultiExitLoopCheck(L)) 463*0eae32dcSDimitry Andric return; 464e8d8bef9SDimitry Andric Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L); 465e8d8bef9SDimitry Andric if (!PeelCount) 466e8d8bef9SDimitry Andric return; 467e8d8bef9SDimitry Andric 468e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount 469e8d8bef9SDimitry Andric << "\n"); 470e8d8bef9SDimitry Andric 471e8d8bef9SDimitry Andric if (*PeelCount) { 472e8d8bef9SDimitry Andric if ((*PeelCount + AlreadyPeeled <= UnrollPeelMaxCount) && 473e8d8bef9SDimitry Andric (LoopSize * (*PeelCount + 1) <= Threshold)) { 474e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peeling first " << *PeelCount 475e8d8bef9SDimitry Andric << " iterations.\n"); 476e8d8bef9SDimitry Andric PP.PeelCount = *PeelCount; 477e8d8bef9SDimitry Andric return; 478e8d8bef9SDimitry Andric } 479e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n"); 480e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n"); 481e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n"); 482e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1) 483e8d8bef9SDimitry Andric << "\n"); 484e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n"); 485e8d8bef9SDimitry Andric } 486e8d8bef9SDimitry Andric } 487e8d8bef9SDimitry Andric } 488e8d8bef9SDimitry Andric 489e8d8bef9SDimitry Andric /// Update the branch weights of the latch of a peeled-off loop 490e8d8bef9SDimitry Andric /// iteration. 491e8d8bef9SDimitry Andric /// This sets the branch weights for the latch of the recently peeled off loop 492e8d8bef9SDimitry Andric /// iteration correctly. 493e8d8bef9SDimitry Andric /// Let F is a weight of the edge from latch to header. 494e8d8bef9SDimitry Andric /// Let E is a weight of the edge from latch to exit. 495e8d8bef9SDimitry Andric /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to 496e8d8bef9SDimitry Andric /// go to exit. 497e8d8bef9SDimitry Andric /// Then, Estimated TripCount = F / E. 498e8d8bef9SDimitry Andric /// For I-th (counting from 0) peeled off iteration we set the the weights for 499e8d8bef9SDimitry Andric /// the peeled latch as (TC - I, 1). It gives us reasonable distribution, 500e8d8bef9SDimitry Andric /// The probability to go to exit 1/(TC-I) increases. At the same time 501e8d8bef9SDimitry Andric /// the estimated trip count of remaining loop reduces by I. 502e8d8bef9SDimitry Andric /// To avoid dealing with division rounding we can just multiple both part 503e8d8bef9SDimitry Andric /// of weights to E and use weight as (F - I * E, E). 504e8d8bef9SDimitry Andric /// 505e8d8bef9SDimitry Andric /// \param Header The copy of the header block that belongs to next iteration. 506e8d8bef9SDimitry Andric /// \param LatchBR The copy of the latch branch that belongs to this iteration. 507e8d8bef9SDimitry Andric /// \param[in,out] FallThroughWeight The weight of the edge from latch to 508e8d8bef9SDimitry Andric /// header before peeling (in) and after peeled off one iteration (out). 509e8d8bef9SDimitry Andric static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 510e8d8bef9SDimitry Andric uint64_t ExitWeight, 511e8d8bef9SDimitry Andric uint64_t &FallThroughWeight) { 512e8d8bef9SDimitry Andric // FallThroughWeight is 0 means that there is no branch weights on original 513e8d8bef9SDimitry Andric // latch block or estimated trip count is zero. 514e8d8bef9SDimitry Andric if (!FallThroughWeight) 515e8d8bef9SDimitry Andric return; 516e8d8bef9SDimitry Andric 517e8d8bef9SDimitry Andric unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1); 518e8d8bef9SDimitry Andric MDBuilder MDB(LatchBR->getContext()); 519e8d8bef9SDimitry Andric MDNode *WeightNode = 520e8d8bef9SDimitry Andric HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 521e8d8bef9SDimitry Andric : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 522e8d8bef9SDimitry Andric LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 523e8d8bef9SDimitry Andric FallThroughWeight = 524e8d8bef9SDimitry Andric FallThroughWeight > ExitWeight ? FallThroughWeight - ExitWeight : 1; 525e8d8bef9SDimitry Andric } 526e8d8bef9SDimitry Andric 527e8d8bef9SDimitry Andric /// Initialize the weights. 528e8d8bef9SDimitry Andric /// 529e8d8bef9SDimitry Andric /// \param Header The header block. 530e8d8bef9SDimitry Andric /// \param LatchBR The latch branch. 531e8d8bef9SDimitry Andric /// \param[out] ExitWeight The weight of the edge from Latch to Exit. 532e8d8bef9SDimitry Andric /// \param[out] FallThroughWeight The weight of the edge from Latch to Header. 533e8d8bef9SDimitry Andric static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 534e8d8bef9SDimitry Andric uint64_t &ExitWeight, 535e8d8bef9SDimitry Andric uint64_t &FallThroughWeight) { 536e8d8bef9SDimitry Andric uint64_t TrueWeight, FalseWeight; 537e8d8bef9SDimitry Andric if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) 538e8d8bef9SDimitry Andric return; 539e8d8bef9SDimitry Andric unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 540e8d8bef9SDimitry Andric ExitWeight = HeaderIdx ? TrueWeight : FalseWeight; 541e8d8bef9SDimitry Andric FallThroughWeight = HeaderIdx ? FalseWeight : TrueWeight; 542e8d8bef9SDimitry Andric } 543e8d8bef9SDimitry Andric 544e8d8bef9SDimitry Andric /// Update the weights of original Latch block after peeling off all iterations. 545e8d8bef9SDimitry Andric /// 546e8d8bef9SDimitry Andric /// \param Header The header block. 547e8d8bef9SDimitry Andric /// \param LatchBR The latch branch. 548e8d8bef9SDimitry Andric /// \param ExitWeight The weight of the edge from Latch to Exit. 549e8d8bef9SDimitry Andric /// \param FallThroughWeight The weight of the edge from Latch to Header. 550e8d8bef9SDimitry Andric static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 551e8d8bef9SDimitry Andric uint64_t ExitWeight, 552e8d8bef9SDimitry Andric uint64_t FallThroughWeight) { 553e8d8bef9SDimitry Andric // FallThroughWeight is 0 means that there is no branch weights on original 554e8d8bef9SDimitry Andric // latch block or estimated trip count is zero. 555e8d8bef9SDimitry Andric if (!FallThroughWeight) 556e8d8bef9SDimitry Andric return; 557e8d8bef9SDimitry Andric 558e8d8bef9SDimitry Andric // Sets the branch weights on the loop exit. 559e8d8bef9SDimitry Andric MDBuilder MDB(LatchBR->getContext()); 560e8d8bef9SDimitry Andric unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 561e8d8bef9SDimitry Andric MDNode *WeightNode = 562e8d8bef9SDimitry Andric HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 563e8d8bef9SDimitry Andric : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 564e8d8bef9SDimitry Andric LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 565e8d8bef9SDimitry Andric } 566e8d8bef9SDimitry Andric 567e8d8bef9SDimitry Andric /// Clones the body of the loop L, putting it between \p InsertTop and \p 568e8d8bef9SDimitry Andric /// InsertBot. 569e8d8bef9SDimitry Andric /// \param IterNumber The serial number of the iteration currently being 570e8d8bef9SDimitry Andric /// peeled off. 571e8d8bef9SDimitry Andric /// \param ExitEdges The exit edges of the original loop. 572e8d8bef9SDimitry Andric /// \param[out] NewBlocks A list of the blocks in the newly created clone 573e8d8bef9SDimitry Andric /// \param[out] VMap The value map between the loop and the new clone. 574e8d8bef9SDimitry Andric /// \param LoopBlocks A helper for DFS-traversal of the loop. 575e8d8bef9SDimitry Andric /// \param LVMap A value-map that maps instructions from the original loop to 576e8d8bef9SDimitry Andric /// instructions in the last peeled-off iteration. 577e8d8bef9SDimitry Andric static void cloneLoopBlocks( 578e8d8bef9SDimitry Andric Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, 579e8d8bef9SDimitry Andric SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges, 580e8d8bef9SDimitry Andric SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 581e8d8bef9SDimitry Andric ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, 582d409305fSDimitry Andric LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes) { 583e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 584e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 585e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 586e8d8bef9SDimitry Andric 587e8d8bef9SDimitry Andric Function *F = Header->getParent(); 588e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 589e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 590e8d8bef9SDimitry Andric Loop *ParentLoop = L->getParentLoop(); 591e8d8bef9SDimitry Andric 592e8d8bef9SDimitry Andric // For each block in the original loop, create a new copy, 593e8d8bef9SDimitry Andric // and update the value map with the newly created values. 594e8d8bef9SDimitry Andric for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 595e8d8bef9SDimitry Andric BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); 596e8d8bef9SDimitry Andric NewBlocks.push_back(NewBB); 597e8d8bef9SDimitry Andric 598e8d8bef9SDimitry Andric // If an original block is an immediate child of the loop L, its copy 599e8d8bef9SDimitry Andric // is a child of a ParentLoop after peeling. If a block is a child of 600e8d8bef9SDimitry Andric // a nested loop, it is handled in the cloneLoop() call below. 601e8d8bef9SDimitry Andric if (ParentLoop && LI->getLoopFor(*BB) == L) 602e8d8bef9SDimitry Andric ParentLoop->addBasicBlockToLoop(NewBB, *LI); 603e8d8bef9SDimitry Andric 604e8d8bef9SDimitry Andric VMap[*BB] = NewBB; 605e8d8bef9SDimitry Andric 606e8d8bef9SDimitry Andric // If dominator tree is available, insert nodes to represent cloned blocks. 607e8d8bef9SDimitry Andric if (DT) { 608e8d8bef9SDimitry Andric if (Header == *BB) 609e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, InsertTop); 610e8d8bef9SDimitry Andric else { 611e8d8bef9SDimitry Andric DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); 612e8d8bef9SDimitry Andric // VMap must contain entry for IDom, as the iteration order is RPO. 613e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()])); 614e8d8bef9SDimitry Andric } 615e8d8bef9SDimitry Andric } 616e8d8bef9SDimitry Andric } 617e8d8bef9SDimitry Andric 618d409305fSDimitry Andric { 619d409305fSDimitry Andric // Identify what other metadata depends on the cloned version. After 620d409305fSDimitry Andric // cloning, replace the metadata with the corrected version for both 621d409305fSDimitry Andric // memory instructions and noalias intrinsics. 622d409305fSDimitry Andric std::string Ext = (Twine("Peel") + Twine(IterNumber)).str(); 623d409305fSDimitry Andric cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks, 624d409305fSDimitry Andric Header->getContext(), Ext); 625d409305fSDimitry Andric } 626d409305fSDimitry Andric 627e8d8bef9SDimitry Andric // Recursively create the new Loop objects for nested loops, if any, 628e8d8bef9SDimitry Andric // to preserve LoopInfo. 629e8d8bef9SDimitry Andric for (Loop *ChildLoop : *L) { 630e8d8bef9SDimitry Andric cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr); 631e8d8bef9SDimitry Andric } 632e8d8bef9SDimitry Andric 633e8d8bef9SDimitry Andric // Hook-up the control flow for the newly inserted blocks. 634e8d8bef9SDimitry Andric // The new header is hooked up directly to the "top", which is either 635e8d8bef9SDimitry Andric // the original loop preheader (for the first iteration) or the previous 636e8d8bef9SDimitry Andric // iteration's exiting block (for every other iteration) 637e8d8bef9SDimitry Andric InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header])); 638e8d8bef9SDimitry Andric 639e8d8bef9SDimitry Andric // Similarly, for the latch: 640e8d8bef9SDimitry Andric // The original exiting edge is still hooked up to the loop exit. 641e8d8bef9SDimitry Andric // The backedge now goes to the "bottom", which is either the loop's real 642e8d8bef9SDimitry Andric // header (for the last peeled iteration) or the copied header of the next 643e8d8bef9SDimitry Andric // iteration (for every other iteration) 644e8d8bef9SDimitry Andric BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 645e8d8bef9SDimitry Andric BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator()); 646e8d8bef9SDimitry Andric for (unsigned idx = 0, e = LatchBR->getNumSuccessors(); idx < e; ++idx) 647e8d8bef9SDimitry Andric if (LatchBR->getSuccessor(idx) == Header) { 648e8d8bef9SDimitry Andric LatchBR->setSuccessor(idx, InsertBot); 649e8d8bef9SDimitry Andric break; 650e8d8bef9SDimitry Andric } 651e8d8bef9SDimitry Andric if (DT) 652e8d8bef9SDimitry Andric DT->changeImmediateDominator(InsertBot, NewLatch); 653e8d8bef9SDimitry Andric 654e8d8bef9SDimitry Andric // The new copy of the loop body starts with a bunch of PHI nodes 655e8d8bef9SDimitry Andric // that pick an incoming value from either the preheader, or the previous 656e8d8bef9SDimitry Andric // loop iteration. Since this copy is no longer part of the loop, we 657e8d8bef9SDimitry Andric // resolve this statically: 658e8d8bef9SDimitry Andric // For the first iteration, we use the value from the preheader directly. 659e8d8bef9SDimitry Andric // For any other iteration, we replace the phi with the value generated by 660e8d8bef9SDimitry Andric // the immediately preceding clone of the loop body (which represents 661e8d8bef9SDimitry Andric // the previous iteration). 662e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 663e8d8bef9SDimitry Andric PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 664e8d8bef9SDimitry Andric if (IterNumber == 0) { 665e8d8bef9SDimitry Andric VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader); 666e8d8bef9SDimitry Andric } else { 667e8d8bef9SDimitry Andric Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); 668e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 669e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 670e8d8bef9SDimitry Andric VMap[&*I] = LVMap[LatchInst]; 671e8d8bef9SDimitry Andric else 672e8d8bef9SDimitry Andric VMap[&*I] = LatchVal; 673e8d8bef9SDimitry Andric } 674e8d8bef9SDimitry Andric cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 675e8d8bef9SDimitry Andric } 676e8d8bef9SDimitry Andric 677e8d8bef9SDimitry Andric // Fix up the outgoing values - we need to add a value for the iteration 678e8d8bef9SDimitry Andric // we've just created. Note that this must happen *after* the incoming 679e8d8bef9SDimitry Andric // values are adjusted, since the value going out of the latch may also be 680e8d8bef9SDimitry Andric // a value coming into the header. 681e8d8bef9SDimitry Andric for (auto Edge : ExitEdges) 682e8d8bef9SDimitry Andric for (PHINode &PHI : Edge.second->phis()) { 683e8d8bef9SDimitry Andric Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first); 684e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 685e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 686e8d8bef9SDimitry Andric LatchVal = VMap[LatchVal]; 687e8d8bef9SDimitry Andric PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first])); 688e8d8bef9SDimitry Andric } 689e8d8bef9SDimitry Andric 690e8d8bef9SDimitry Andric // LastValueMap is updated with the values for the current loop 691e8d8bef9SDimitry Andric // which are used the next time this function is called. 692e8d8bef9SDimitry Andric for (auto KV : VMap) 693e8d8bef9SDimitry Andric LVMap[KV.first] = KV.second; 694e8d8bef9SDimitry Andric } 695e8d8bef9SDimitry Andric 696e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences llvm::gatherPeelingPreferences( 697e8d8bef9SDimitry Andric Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, 698e8d8bef9SDimitry Andric Optional<bool> UserAllowPeeling, 699e8d8bef9SDimitry Andric Optional<bool> UserAllowProfileBasedPeeling, bool UnrollingSpecficValues) { 700e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences PP; 701e8d8bef9SDimitry Andric 702e8d8bef9SDimitry Andric // Set the default values. 703e8d8bef9SDimitry Andric PP.PeelCount = 0; 704e8d8bef9SDimitry Andric PP.AllowPeeling = true; 705e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = false; 706e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 707e8d8bef9SDimitry Andric 708e8d8bef9SDimitry Andric // Get the target specifc values. 709e8d8bef9SDimitry Andric TTI.getPeelingPreferences(L, SE, PP); 710e8d8bef9SDimitry Andric 711e8d8bef9SDimitry Andric // User specified values using cl::opt. 712e8d8bef9SDimitry Andric if (UnrollingSpecficValues) { 713e8d8bef9SDimitry Andric if (UnrollPeelCount.getNumOccurrences() > 0) 714e8d8bef9SDimitry Andric PP.PeelCount = UnrollPeelCount; 715e8d8bef9SDimitry Andric if (UnrollAllowPeeling.getNumOccurrences() > 0) 716e8d8bef9SDimitry Andric PP.AllowPeeling = UnrollAllowPeeling; 717e8d8bef9SDimitry Andric if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0) 718e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling; 719e8d8bef9SDimitry Andric } 720e8d8bef9SDimitry Andric 721e8d8bef9SDimitry Andric // User specifed values provided by argument. 722e8d8bef9SDimitry Andric if (UserAllowPeeling.hasValue()) 723e8d8bef9SDimitry Andric PP.AllowPeeling = *UserAllowPeeling; 724e8d8bef9SDimitry Andric if (UserAllowProfileBasedPeeling.hasValue()) 725e8d8bef9SDimitry Andric PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; 726e8d8bef9SDimitry Andric 727e8d8bef9SDimitry Andric return PP; 728e8d8bef9SDimitry Andric } 729e8d8bef9SDimitry Andric 730e8d8bef9SDimitry Andric /// Peel off the first \p PeelCount iterations of loop \p L. 731e8d8bef9SDimitry Andric /// 732e8d8bef9SDimitry Andric /// Note that this does not peel them off as a single straight-line block. 733e8d8bef9SDimitry Andric /// Rather, each iteration is peeled off separately, and needs to check the 734e8d8bef9SDimitry Andric /// exit condition. 735e8d8bef9SDimitry Andric /// For loops that dynamically execute \p PeelCount iterations or less 736e8d8bef9SDimitry Andric /// this provides a benefit, since the peeled off iterations, which account 737e8d8bef9SDimitry Andric /// for the bulk of dynamic execution, can be further simplified by scalar 738e8d8bef9SDimitry Andric /// optimizations. 739e8d8bef9SDimitry Andric bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, 740e8d8bef9SDimitry Andric ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, 741e8d8bef9SDimitry Andric bool PreserveLCSSA) { 742e8d8bef9SDimitry Andric assert(PeelCount > 0 && "Attempt to peel out zero iterations?"); 743e8d8bef9SDimitry Andric assert(canPeel(L) && "Attempt to peel a loop which is not peelable?"); 744e8d8bef9SDimitry Andric 745e8d8bef9SDimitry Andric LoopBlocksDFS LoopBlocks(L); 746e8d8bef9SDimitry Andric LoopBlocks.perform(LI); 747e8d8bef9SDimitry Andric 748e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 749e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 750e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 751e8d8bef9SDimitry Andric SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges; 752e8d8bef9SDimitry Andric L->getExitEdges(ExitEdges); 753e8d8bef9SDimitry Andric 754349cc55cSDimitry Andric // Remember dominators of blocks we might reach through exits to change them 755349cc55cSDimitry Andric // later. Immediate dominator of such block might change, because we add more 756349cc55cSDimitry Andric // routes which can lead to the exit: we can reach it from the peeled 757349cc55cSDimitry Andric // iterations too. 758349cc55cSDimitry Andric DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom; 759e8d8bef9SDimitry Andric if (DT) { 760349cc55cSDimitry Andric for (auto *BB : L->blocks()) { 761349cc55cSDimitry Andric auto *BBDomNode = DT->getNode(BB); 762349cc55cSDimitry Andric SmallVector<BasicBlock *, 16> ChildrenToUpdate; 763349cc55cSDimitry Andric for (auto *ChildDomNode : BBDomNode->children()) { 764349cc55cSDimitry Andric auto *ChildBB = ChildDomNode->getBlock(); 765349cc55cSDimitry Andric if (!L->contains(ChildBB)) 766349cc55cSDimitry Andric ChildrenToUpdate.push_back(ChildBB); 767349cc55cSDimitry Andric } 768349cc55cSDimitry Andric // The new idom of the block will be the nearest common dominator 769349cc55cSDimitry Andric // of all copies of the previous idom. This is equivalent to the 770349cc55cSDimitry Andric // nearest common dominator of the previous idom and the first latch, 771349cc55cSDimitry Andric // which dominates all copies of the previous idom. 772349cc55cSDimitry Andric BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, Latch); 773349cc55cSDimitry Andric for (auto *ChildBB : ChildrenToUpdate) 774349cc55cSDimitry Andric NonLoopBlocksIDom[ChildBB] = NewIDom; 775e8d8bef9SDimitry Andric } 776e8d8bef9SDimitry Andric } 777e8d8bef9SDimitry Andric 778e8d8bef9SDimitry Andric Function *F = Header->getParent(); 779e8d8bef9SDimitry Andric 780e8d8bef9SDimitry Andric // Set up all the necessary basic blocks. It is convenient to split the 781e8d8bef9SDimitry Andric // preheader into 3 parts - two blocks to anchor the peeled copy of the loop 782e8d8bef9SDimitry Andric // body, and a new preheader for the "real" loop. 783e8d8bef9SDimitry Andric 784e8d8bef9SDimitry Andric // Peeling the first iteration transforms. 785e8d8bef9SDimitry Andric // 786e8d8bef9SDimitry Andric // PreHeader: 787e8d8bef9SDimitry Andric // ... 788e8d8bef9SDimitry Andric // Header: 789e8d8bef9SDimitry Andric // LoopBody 790e8d8bef9SDimitry Andric // If (cond) goto Header 791e8d8bef9SDimitry Andric // Exit: 792e8d8bef9SDimitry Andric // 793e8d8bef9SDimitry Andric // into 794e8d8bef9SDimitry Andric // 795e8d8bef9SDimitry Andric // InsertTop: 796e8d8bef9SDimitry Andric // LoopBody 797e8d8bef9SDimitry Andric // If (!cond) goto Exit 798e8d8bef9SDimitry Andric // InsertBot: 799e8d8bef9SDimitry Andric // NewPreHeader: 800e8d8bef9SDimitry Andric // ... 801e8d8bef9SDimitry Andric // Header: 802e8d8bef9SDimitry Andric // LoopBody 803e8d8bef9SDimitry Andric // If (cond) goto Header 804e8d8bef9SDimitry Andric // Exit: 805e8d8bef9SDimitry Andric // 806e8d8bef9SDimitry Andric // Each following iteration will split the current bottom anchor in two, 807e8d8bef9SDimitry Andric // and put the new copy of the loop body between these two blocks. That is, 808e8d8bef9SDimitry Andric // after peeling another iteration from the example above, we'll split 809e8d8bef9SDimitry Andric // InsertBot, and get: 810e8d8bef9SDimitry Andric // 811e8d8bef9SDimitry Andric // InsertTop: 812e8d8bef9SDimitry Andric // LoopBody 813e8d8bef9SDimitry Andric // If (!cond) goto Exit 814e8d8bef9SDimitry Andric // InsertBot: 815e8d8bef9SDimitry Andric // LoopBody 816e8d8bef9SDimitry Andric // If (!cond) goto Exit 817e8d8bef9SDimitry Andric // InsertBot.next: 818e8d8bef9SDimitry Andric // NewPreHeader: 819e8d8bef9SDimitry Andric // ... 820e8d8bef9SDimitry Andric // Header: 821e8d8bef9SDimitry Andric // LoopBody 822e8d8bef9SDimitry Andric // If (cond) goto Header 823e8d8bef9SDimitry Andric // Exit: 824e8d8bef9SDimitry Andric 825e8d8bef9SDimitry Andric BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI); 826e8d8bef9SDimitry Andric BasicBlock *InsertBot = 827e8d8bef9SDimitry Andric SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI); 828e8d8bef9SDimitry Andric BasicBlock *NewPreHeader = 829e8d8bef9SDimitry Andric SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); 830e8d8bef9SDimitry Andric 831e8d8bef9SDimitry Andric InsertTop->setName(Header->getName() + ".peel.begin"); 832e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 833e8d8bef9SDimitry Andric NewPreHeader->setName(PreHeader->getName() + ".peel.newph"); 834e8d8bef9SDimitry Andric 835e8d8bef9SDimitry Andric ValueToValueMapTy LVMap; 836e8d8bef9SDimitry Andric 837e8d8bef9SDimitry Andric // If we have branch weight information, we'll want to update it for the 838e8d8bef9SDimitry Andric // newly created branches. 839e8d8bef9SDimitry Andric BranchInst *LatchBR = 840e8d8bef9SDimitry Andric cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator()); 841e8d8bef9SDimitry Andric uint64_t ExitWeight = 0, FallThroughWeight = 0; 842e8d8bef9SDimitry Andric initBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 843e8d8bef9SDimitry Andric 844d409305fSDimitry Andric // Identify what noalias metadata is inside the loop: if it is inside the 845d409305fSDimitry Andric // loop, the associated metadata must be cloned for each iteration. 846d409305fSDimitry Andric SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; 847d409305fSDimitry Andric identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes); 848d409305fSDimitry Andric 849e8d8bef9SDimitry Andric // For each peeled-off iteration, make a copy of the loop. 850e8d8bef9SDimitry Andric for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { 851e8d8bef9SDimitry Andric SmallVector<BasicBlock *, 8> NewBlocks; 852e8d8bef9SDimitry Andric ValueToValueMapTy VMap; 853e8d8bef9SDimitry Andric 854e8d8bef9SDimitry Andric cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks, 855d409305fSDimitry Andric LoopBlocks, VMap, LVMap, DT, LI, 856d409305fSDimitry Andric LoopLocalNoAliasDeclScopes); 857e8d8bef9SDimitry Andric 858e8d8bef9SDimitry Andric // Remap to use values from the current iteration instead of the 859e8d8bef9SDimitry Andric // previous one. 860e8d8bef9SDimitry Andric remapInstructionsInBlocks(NewBlocks, VMap); 861e8d8bef9SDimitry Andric 862e8d8bef9SDimitry Andric if (DT) { 863349cc55cSDimitry Andric // Update IDoms of the blocks reachable through exits. 864e8d8bef9SDimitry Andric if (Iter == 0) 865349cc55cSDimitry Andric for (auto BBIDom : NonLoopBlocksIDom) 866349cc55cSDimitry Andric DT->changeImmediateDominator(BBIDom.first, 867349cc55cSDimitry Andric cast<BasicBlock>(LVMap[BBIDom.second])); 868e8d8bef9SDimitry Andric #ifdef EXPENSIVE_CHECKS 869e8d8bef9SDimitry Andric assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 870e8d8bef9SDimitry Andric #endif 871e8d8bef9SDimitry Andric } 872e8d8bef9SDimitry Andric 873e8d8bef9SDimitry Andric auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]); 874e8d8bef9SDimitry Andric updateBranchWeights(InsertBot, LatchBRCopy, ExitWeight, FallThroughWeight); 875e8d8bef9SDimitry Andric // Remove Loop metadata from the latch branch instruction 876e8d8bef9SDimitry Andric // because it is not the Loop's latch branch anymore. 877e8d8bef9SDimitry Andric LatchBRCopy->setMetadata(LLVMContext::MD_loop, nullptr); 878e8d8bef9SDimitry Andric 879e8d8bef9SDimitry Andric InsertTop = InsertBot; 880e8d8bef9SDimitry Andric InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); 881e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 882e8d8bef9SDimitry Andric 883e8d8bef9SDimitry Andric F->getBasicBlockList().splice(InsertTop->getIterator(), 884e8d8bef9SDimitry Andric F->getBasicBlockList(), 885e8d8bef9SDimitry Andric NewBlocks[0]->getIterator(), F->end()); 886e8d8bef9SDimitry Andric } 887e8d8bef9SDimitry Andric 888e8d8bef9SDimitry Andric // Now adjust the phi nodes in the loop header to get their initial values 889e8d8bef9SDimitry Andric // from the last peeled-off iteration instead of the preheader. 890e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 891e8d8bef9SDimitry Andric PHINode *PHI = cast<PHINode>(I); 892e8d8bef9SDimitry Andric Value *NewVal = PHI->getIncomingValueForBlock(Latch); 893e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(NewVal); 894e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 895e8d8bef9SDimitry Andric NewVal = LVMap[LatchInst]; 896e8d8bef9SDimitry Andric 897e8d8bef9SDimitry Andric PHI->setIncomingValueForBlock(NewPreHeader, NewVal); 898e8d8bef9SDimitry Andric } 899e8d8bef9SDimitry Andric 900e8d8bef9SDimitry Andric fixupBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 901e8d8bef9SDimitry Andric 902e8d8bef9SDimitry Andric // Update Metadata for count of peeled off iterations. 903e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 904e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 905e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 906e8d8bef9SDimitry Andric addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount); 907e8d8bef9SDimitry Andric 908e8d8bef9SDimitry Andric if (Loop *ParentLoop = L->getParentLoop()) 909e8d8bef9SDimitry Andric L = ParentLoop; 910e8d8bef9SDimitry Andric 911e8d8bef9SDimitry Andric // We modified the loop, update SE. 912e8d8bef9SDimitry Andric SE->forgetTopmostLoop(L); 913e8d8bef9SDimitry Andric 914e8d8bef9SDimitry Andric // Finally DomtTree must be correct. 915e8d8bef9SDimitry Andric assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 916e8d8bef9SDimitry Andric 917e8d8bef9SDimitry Andric // FIXME: Incrementally update loop-simplify 918e8d8bef9SDimitry Andric simplifyLoop(L, DT, LI, SE, AC, nullptr, PreserveLCSSA); 919e8d8bef9SDimitry Andric 920e8d8bef9SDimitry Andric NumPeeled++; 921e8d8bef9SDimitry Andric 922e8d8bef9SDimitry Andric return true; 923e8d8bef9SDimitry Andric } 924