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/SmallVector.h" 15e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h" 16349cc55cSDimitry Andric #include "llvm/Analysis/Loads.h" 17e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 18e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopIterator.h" 19e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 20e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h" 21e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 22e8d8bef9SDimitry Andric #include "llvm/IR/BasicBlock.h" 23e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 24e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 25e8d8bef9SDimitry Andric #include "llvm/IR/InstrTypes.h" 26e8d8bef9SDimitry Andric #include "llvm/IR/Instruction.h" 27e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h" 28e8d8bef9SDimitry Andric #include "llvm/IR/LLVMContext.h" 29e8d8bef9SDimitry Andric #include "llvm/IR/MDBuilder.h" 30e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h" 31*bdd1243dSDimitry Andric #include "llvm/IR/ProfDataUtils.h" 32e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 33e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h" 34e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 35e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 36e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 37e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 38e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopSimplify.h" 39e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 40e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h" 41e8d8bef9SDimitry Andric #include <algorithm> 42e8d8bef9SDimitry Andric #include <cassert> 43e8d8bef9SDimitry Andric #include <cstdint> 44*bdd1243dSDimitry Andric #include <optional> 45e8d8bef9SDimitry Andric 46e8d8bef9SDimitry Andric using namespace llvm; 47e8d8bef9SDimitry Andric using namespace llvm::PatternMatch; 48e8d8bef9SDimitry Andric 49e8d8bef9SDimitry Andric #define DEBUG_TYPE "loop-peel" 50e8d8bef9SDimitry Andric 51e8d8bef9SDimitry Andric STATISTIC(NumPeeled, "Number of loops peeled"); 52e8d8bef9SDimitry Andric 53e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelCount( 54e8d8bef9SDimitry Andric "unroll-peel-count", cl::Hidden, 55e8d8bef9SDimitry Andric cl::desc("Set the unroll peeling count, for testing purposes")); 56e8d8bef9SDimitry Andric 57e8d8bef9SDimitry Andric static cl::opt<bool> 58e8d8bef9SDimitry Andric UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 59e8d8bef9SDimitry Andric cl::desc("Allows loops to be peeled when the dynamic " 60e8d8bef9SDimitry Andric "trip count is known to be low.")); 61e8d8bef9SDimitry Andric 62e8d8bef9SDimitry Andric static cl::opt<bool> 63e8d8bef9SDimitry Andric UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", 64e8d8bef9SDimitry Andric cl::init(false), cl::Hidden, 65e8d8bef9SDimitry Andric cl::desc("Allows loop nests to be peeled.")); 66e8d8bef9SDimitry Andric 67e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollPeelMaxCount( 68e8d8bef9SDimitry Andric "unroll-peel-max-count", cl::init(7), cl::Hidden, 69e8d8bef9SDimitry Andric cl::desc("Max average trip count which will cause loop peeling.")); 70e8d8bef9SDimitry Andric 71e8d8bef9SDimitry Andric static cl::opt<unsigned> UnrollForcePeelCount( 72e8d8bef9SDimitry Andric "unroll-force-peel-count", cl::init(0), cl::Hidden, 73e8d8bef9SDimitry Andric cl::desc("Force a peel count regardless of profiling information.")); 74e8d8bef9SDimitry Andric 75*bdd1243dSDimitry Andric static cl::opt<bool> DisableAdvancedPeeling( 76*bdd1243dSDimitry Andric "disable-advanced-peeling", cl::init(false), cl::Hidden, 77*bdd1243dSDimitry Andric cl::desc( 78*bdd1243dSDimitry Andric "Disable advance peeling. Issues for convergent targets (D134803).")); 79*bdd1243dSDimitry Andric 80e8d8bef9SDimitry Andric static const char *PeeledCountMetaData = "llvm.loop.peeled.count"; 81e8d8bef9SDimitry Andric 82e8d8bef9SDimitry Andric // Check whether we are capable of peeling this loop. 83*bdd1243dSDimitry Andric bool llvm::canPeel(const Loop *L) { 84e8d8bef9SDimitry Andric // Make sure the loop is in simplified form 85e8d8bef9SDimitry Andric if (!L->isLoopSimplifyForm()) 86e8d8bef9SDimitry Andric return false; 87*bdd1243dSDimitry Andric if (!DisableAdvancedPeeling) 88*bdd1243dSDimitry Andric return true; 89e8d8bef9SDimitry Andric 90349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 91349cc55cSDimitry Andric L->getUniqueNonLatchExitBlocks(Exits); 92349cc55cSDimitry Andric // The latch must either be the only exiting block or all non-latch exit 93349cc55cSDimitry Andric // blocks have either a deopt or unreachable terminator or compose a chain of 94349cc55cSDimitry Andric // blocks where the last one is either deopt or unreachable terminated. Both 95349cc55cSDimitry Andric // deopt and unreachable terminators are a strong indication they are not 96349cc55cSDimitry Andric // taken. Note that this is a profitability check, not a legality check. Also 97349cc55cSDimitry Andric // note that LoopPeeling currently can only update the branch weights of latch 98349cc55cSDimitry Andric // blocks and branch weights to blocks with deopt or unreachable do not need 99349cc55cSDimitry Andric // updating. 1000eae32dcSDimitry Andric return llvm::all_of(Exits, IsBlockFollowedByDeoptOrUnreachable); 101e8d8bef9SDimitry Andric } 102e8d8bef9SDimitry Andric 103*bdd1243dSDimitry Andric namespace { 104*bdd1243dSDimitry Andric 105*bdd1243dSDimitry Andric // As a loop is peeled, it may be the case that Phi nodes become 106*bdd1243dSDimitry Andric // loop-invariant (ie, known because there is only one choice). 107*bdd1243dSDimitry Andric // For example, consider the following function: 108*bdd1243dSDimitry Andric // void g(int); 109*bdd1243dSDimitry Andric // void binary() { 110*bdd1243dSDimitry Andric // int x = 0; 111*bdd1243dSDimitry Andric // int y = 0; 112*bdd1243dSDimitry Andric // int a = 0; 113*bdd1243dSDimitry Andric // for(int i = 0; i <100000; ++i) { 114*bdd1243dSDimitry Andric // g(x); 115*bdd1243dSDimitry Andric // x = y; 116*bdd1243dSDimitry Andric // g(a); 117*bdd1243dSDimitry Andric // y = a + 1; 118*bdd1243dSDimitry Andric // a = 5; 119*bdd1243dSDimitry Andric // } 120*bdd1243dSDimitry Andric // } 121*bdd1243dSDimitry Andric // Peeling 3 iterations is beneficial because the values for x, y and a 122*bdd1243dSDimitry Andric // become known. The IR for this loop looks something like the following: 123*bdd1243dSDimitry Andric // 124*bdd1243dSDimitry Andric // %i = phi i32 [ 0, %entry ], [ %inc, %if.end ] 125*bdd1243dSDimitry Andric // %a = phi i32 [ 0, %entry ], [ 5, %if.end ] 126*bdd1243dSDimitry Andric // %y = phi i32 [ 0, %entry ], [ %add, %if.end ] 127*bdd1243dSDimitry Andric // %x = phi i32 [ 0, %entry ], [ %y, %if.end ] 128*bdd1243dSDimitry Andric // ... 129*bdd1243dSDimitry Andric // tail call void @_Z1gi(i32 signext %x) 130*bdd1243dSDimitry Andric // tail call void @_Z1gi(i32 signext %a) 131*bdd1243dSDimitry Andric // %add = add nuw nsw i32 %a, 1 132*bdd1243dSDimitry Andric // %inc = add nuw nsw i32 %i, 1 133*bdd1243dSDimitry Andric // %exitcond = icmp eq i32 %inc, 100000 134*bdd1243dSDimitry Andric // br i1 %exitcond, label %for.cond.cleanup, label %for.body 135*bdd1243dSDimitry Andric // 136*bdd1243dSDimitry Andric // The arguments for the calls to g will become known after 3 iterations 137*bdd1243dSDimitry Andric // of the loop, because the phi nodes values become known after 3 iterations 138*bdd1243dSDimitry Andric // of the loop (ie, they are known on the 4th iteration, so peel 3 iterations). 139*bdd1243dSDimitry Andric // The first iteration has g(0), g(0); the second has g(0), g(5); the 140*bdd1243dSDimitry Andric // third has g(1), g(5) and the fourth (and all subsequent) have g(6), g(5). 141*bdd1243dSDimitry Andric // Now consider the phi nodes: 142*bdd1243dSDimitry Andric // %a is a phi with constants so it is determined after iteration 1. 143*bdd1243dSDimitry Andric // %y is a phi based on a constant and %a so it is determined on 144*bdd1243dSDimitry Andric // the iteration after %a is determined, so iteration 2. 145*bdd1243dSDimitry Andric // %x is a phi based on a constant and %y so it is determined on 146*bdd1243dSDimitry Andric // the iteration after %y, so iteration 3. 147*bdd1243dSDimitry Andric // %i is based on itself (and is an induction variable) so it is 148*bdd1243dSDimitry Andric // never determined. 149*bdd1243dSDimitry Andric // This means that peeling off 3 iterations will result in being able to 150*bdd1243dSDimitry Andric // remove the phi nodes for %a, %y, and %x. The arguments for the 151*bdd1243dSDimitry Andric // corresponding calls to g are determined and the code for computing 152*bdd1243dSDimitry Andric // x, y, and a can be removed. 153*bdd1243dSDimitry Andric // 154*bdd1243dSDimitry Andric // The PhiAnalyzer class calculates how many times a loop should be 155*bdd1243dSDimitry Andric // peeled based on the above analysis of the phi nodes in the loop while 156*bdd1243dSDimitry Andric // respecting the maximum specified. 157*bdd1243dSDimitry Andric class PhiAnalyzer { 158*bdd1243dSDimitry Andric public: 159*bdd1243dSDimitry Andric PhiAnalyzer(const Loop &L, unsigned MaxIterations); 160*bdd1243dSDimitry Andric 161*bdd1243dSDimitry Andric // Calculate the sufficient minimum number of iterations of the loop to peel 162*bdd1243dSDimitry Andric // such that phi instructions become determined (subject to allowable limits) 163*bdd1243dSDimitry Andric std::optional<unsigned> calculateIterationsToPeel(); 164*bdd1243dSDimitry Andric 165*bdd1243dSDimitry Andric protected: 166*bdd1243dSDimitry Andric using PeelCounter = std::optional<unsigned>; 167*bdd1243dSDimitry Andric const PeelCounter Unknown = std::nullopt; 168*bdd1243dSDimitry Andric 169*bdd1243dSDimitry Andric // Add 1 respecting Unknown and return Unknown if result over MaxIterations 170*bdd1243dSDimitry Andric PeelCounter addOne(PeelCounter PC) const { 171*bdd1243dSDimitry Andric if (PC == Unknown) 172*bdd1243dSDimitry Andric return Unknown; 173*bdd1243dSDimitry Andric return (*PC + 1 <= MaxIterations) ? PeelCounter{*PC + 1} : Unknown; 174*bdd1243dSDimitry Andric } 175*bdd1243dSDimitry Andric 176*bdd1243dSDimitry Andric // Calculate the number of iterations after which the given value 177*bdd1243dSDimitry Andric // becomes an invariant. 178*bdd1243dSDimitry Andric PeelCounter calculate(const Value &); 179*bdd1243dSDimitry Andric 180*bdd1243dSDimitry Andric const Loop &L; 181*bdd1243dSDimitry Andric const unsigned MaxIterations; 182*bdd1243dSDimitry Andric 183*bdd1243dSDimitry Andric // Map of Values to number of iterations to invariance 184*bdd1243dSDimitry Andric SmallDenseMap<const Value *, PeelCounter> IterationsToInvariance; 185*bdd1243dSDimitry Andric }; 186*bdd1243dSDimitry Andric 187*bdd1243dSDimitry Andric PhiAnalyzer::PhiAnalyzer(const Loop &L, unsigned MaxIterations) 188*bdd1243dSDimitry Andric : L(L), MaxIterations(MaxIterations) { 189*bdd1243dSDimitry Andric assert(canPeel(&L) && "loop is not suitable for peeling"); 190*bdd1243dSDimitry Andric assert(MaxIterations > 0 && "no peeling is allowed?"); 191*bdd1243dSDimitry Andric } 192*bdd1243dSDimitry Andric 193*bdd1243dSDimitry Andric // This function calculates the number of iterations after which the value 194*bdd1243dSDimitry Andric // becomes an invariant. The pre-calculated values are memorized in a map. 195*bdd1243dSDimitry Andric // N.B. This number will be Unknown or <= MaxIterations. 196*bdd1243dSDimitry Andric // The function is calculated according to the following definition: 197e8d8bef9SDimitry Andric // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge]. 198*bdd1243dSDimitry Andric // F(%x) = G(%y) + 1 (N.B. [MaxIterations | Unknown] + 1 => Unknown) 199*bdd1243dSDimitry Andric // G(%y) = 0 if %y is a loop invariant 200*bdd1243dSDimitry Andric // G(%y) = G(%BackEdgeValue) if %y is a phi in the header block 201*bdd1243dSDimitry Andric // G(%y) = TODO: if %y is an expression based on phis and loop invariants 202*bdd1243dSDimitry Andric // The example looks like: 203*bdd1243dSDimitry Andric // %x = phi(0, %a) <-- becomes invariant starting from 3rd iteration. 204*bdd1243dSDimitry Andric // %y = phi(0, 5) 205*bdd1243dSDimitry Andric // %a = %y + 1 206*bdd1243dSDimitry Andric // G(%y) = Unknown otherwise (including phi not in header block) 207*bdd1243dSDimitry Andric PhiAnalyzer::PeelCounter PhiAnalyzer::calculate(const Value &V) { 208e8d8bef9SDimitry Andric // If we already know the answer, take it from the map. 209*bdd1243dSDimitry Andric auto I = IterationsToInvariance.find(&V); 210e8d8bef9SDimitry Andric if (I != IterationsToInvariance.end()) 211e8d8bef9SDimitry Andric return I->second; 212e8d8bef9SDimitry Andric 213*bdd1243dSDimitry Andric // Place Unknown to map to avoid infinite recursion. Such 214e8d8bef9SDimitry Andric // cycles can never stop on an invariant. 215*bdd1243dSDimitry Andric IterationsToInvariance[&V] = Unknown; 216e8d8bef9SDimitry Andric 217*bdd1243dSDimitry Andric if (L.isLoopInvariant(&V)) 218*bdd1243dSDimitry Andric // Loop invariant so known at start. 219*bdd1243dSDimitry Andric return (IterationsToInvariance[&V] = 0); 220*bdd1243dSDimitry Andric if (const PHINode *Phi = dyn_cast<PHINode>(&V)) { 221*bdd1243dSDimitry Andric if (Phi->getParent() != L.getHeader()) { 222*bdd1243dSDimitry Andric // Phi is not in header block so Unknown. 223*bdd1243dSDimitry Andric assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved"); 224*bdd1243dSDimitry Andric return Unknown; 225*bdd1243dSDimitry Andric } 226*bdd1243dSDimitry Andric // We need to analyze the input from the back edge and add 1. 227*bdd1243dSDimitry Andric Value *Input = Phi->getIncomingValueForBlock(L.getLoopLatch()); 228*bdd1243dSDimitry Andric PeelCounter Iterations = calculate(*Input); 229*bdd1243dSDimitry Andric assert(IterationsToInvariance[Input] == Iterations && 230*bdd1243dSDimitry Andric "unexpected value saved"); 231*bdd1243dSDimitry Andric return (IterationsToInvariance[Phi] = addOne(Iterations)); 232*bdd1243dSDimitry Andric } 233*bdd1243dSDimitry Andric if (const Instruction *I = dyn_cast<Instruction>(&V)) { 234*bdd1243dSDimitry Andric if (isa<CmpInst>(I) || I->isBinaryOp()) { 235*bdd1243dSDimitry Andric // Binary instructions get the max of the operands. 236*bdd1243dSDimitry Andric PeelCounter LHS = calculate(*I->getOperand(0)); 237*bdd1243dSDimitry Andric if (LHS == Unknown) 238*bdd1243dSDimitry Andric return Unknown; 239*bdd1243dSDimitry Andric PeelCounter RHS = calculate(*I->getOperand(1)); 240*bdd1243dSDimitry Andric if (RHS == Unknown) 241*bdd1243dSDimitry Andric return Unknown; 242*bdd1243dSDimitry Andric return (IterationsToInvariance[I] = {std::max(*LHS, *RHS)}); 243*bdd1243dSDimitry Andric } 244*bdd1243dSDimitry Andric if (I->isCast()) 245*bdd1243dSDimitry Andric // Cast instructions get the value of the operand. 246*bdd1243dSDimitry Andric return (IterationsToInvariance[I] = calculate(*I->getOperand(0))); 247*bdd1243dSDimitry Andric } 248*bdd1243dSDimitry Andric // TODO: handle more expressions 249*bdd1243dSDimitry Andric 250*bdd1243dSDimitry Andric // Everything else is Unknown. 251*bdd1243dSDimitry Andric assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved"); 252*bdd1243dSDimitry Andric return Unknown; 253e8d8bef9SDimitry Andric } 254e8d8bef9SDimitry Andric 255*bdd1243dSDimitry Andric std::optional<unsigned> PhiAnalyzer::calculateIterationsToPeel() { 256*bdd1243dSDimitry Andric unsigned Iterations = 0; 257*bdd1243dSDimitry Andric for (auto &PHI : L.getHeader()->phis()) { 258*bdd1243dSDimitry Andric PeelCounter ToInvariance = calculate(PHI); 259*bdd1243dSDimitry Andric if (ToInvariance != Unknown) { 260*bdd1243dSDimitry Andric assert(*ToInvariance <= MaxIterations && "bad result in phi analysis"); 261*bdd1243dSDimitry Andric Iterations = std::max(Iterations, *ToInvariance); 262*bdd1243dSDimitry Andric if (Iterations == MaxIterations) 263*bdd1243dSDimitry Andric break; 264e8d8bef9SDimitry Andric } 265*bdd1243dSDimitry Andric } 266*bdd1243dSDimitry Andric assert((Iterations <= MaxIterations) && "bad result in phi analysis"); 267*bdd1243dSDimitry Andric return Iterations ? std::optional<unsigned>(Iterations) : std::nullopt; 268*bdd1243dSDimitry Andric } 269*bdd1243dSDimitry Andric 270*bdd1243dSDimitry Andric } // unnamed namespace 271e8d8bef9SDimitry Andric 272349cc55cSDimitry Andric // Try to find any invariant memory reads that will become dereferenceable in 273349cc55cSDimitry Andric // the remainder loop after peeling. The load must also be used (transitively) 274349cc55cSDimitry Andric // by an exit condition. Returns the number of iterations to peel off (at the 275349cc55cSDimitry Andric // moment either 0 or 1). 276349cc55cSDimitry Andric static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, 277*bdd1243dSDimitry Andric DominatorTree &DT, 278*bdd1243dSDimitry Andric AssumptionCache *AC) { 279349cc55cSDimitry Andric // Skip loops with a single exiting block, because there should be no benefit 280349cc55cSDimitry Andric // for the heuristic below. 281349cc55cSDimitry Andric if (L.getExitingBlock()) 282349cc55cSDimitry Andric return 0; 283349cc55cSDimitry Andric 284349cc55cSDimitry Andric // All non-latch exit blocks must have an UnreachableInst terminator. 285349cc55cSDimitry Andric // Otherwise the heuristic below may not be profitable. 286349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Exits; 287349cc55cSDimitry Andric L.getUniqueNonLatchExitBlocks(Exits); 288349cc55cSDimitry Andric if (any_of(Exits, [](const BasicBlock *BB) { 289349cc55cSDimitry Andric return !isa<UnreachableInst>(BB->getTerminator()); 290349cc55cSDimitry Andric })) 291349cc55cSDimitry Andric return 0; 292349cc55cSDimitry Andric 293349cc55cSDimitry Andric // Now look for invariant loads that dominate the latch and are not known to 294349cc55cSDimitry Andric // be dereferenceable. If there are such loads and no writes, they will become 295349cc55cSDimitry Andric // dereferenceable in the loop if the first iteration is peeled off. Also 296349cc55cSDimitry Andric // collect the set of instructions controlled by such loads. Only peel if an 297349cc55cSDimitry Andric // exit condition uses (transitively) such a load. 298349cc55cSDimitry Andric BasicBlock *Header = L.getHeader(); 299349cc55cSDimitry Andric BasicBlock *Latch = L.getLoopLatch(); 300349cc55cSDimitry Andric SmallPtrSet<Value *, 8> LoadUsers; 301349cc55cSDimitry Andric const DataLayout &DL = L.getHeader()->getModule()->getDataLayout(); 302349cc55cSDimitry Andric for (BasicBlock *BB : L.blocks()) { 303349cc55cSDimitry Andric for (Instruction &I : *BB) { 304349cc55cSDimitry Andric if (I.mayWriteToMemory()) 305349cc55cSDimitry Andric return 0; 306349cc55cSDimitry Andric 307349cc55cSDimitry Andric auto Iter = LoadUsers.find(&I); 308349cc55cSDimitry Andric if (Iter != LoadUsers.end()) { 309349cc55cSDimitry Andric for (Value *U : I.users()) 310349cc55cSDimitry Andric LoadUsers.insert(U); 311349cc55cSDimitry Andric } 312349cc55cSDimitry Andric // Do not look for reads in the header; they can already be hoisted 313349cc55cSDimitry Andric // without peeling. 314349cc55cSDimitry Andric if (BB == Header) 315349cc55cSDimitry Andric continue; 316349cc55cSDimitry Andric if (auto *LI = dyn_cast<LoadInst>(&I)) { 317349cc55cSDimitry Andric Value *Ptr = LI->getPointerOperand(); 318349cc55cSDimitry Andric if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) && 319*bdd1243dSDimitry Andric !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, AC, &DT)) 320349cc55cSDimitry Andric for (Value *U : I.users()) 321349cc55cSDimitry Andric LoadUsers.insert(U); 322349cc55cSDimitry Andric } 323349cc55cSDimitry Andric } 324349cc55cSDimitry Andric } 325349cc55cSDimitry Andric SmallVector<BasicBlock *> ExitingBlocks; 326349cc55cSDimitry Andric L.getExitingBlocks(ExitingBlocks); 327349cc55cSDimitry Andric if (any_of(ExitingBlocks, [&LoadUsers](BasicBlock *Exiting) { 328349cc55cSDimitry Andric return LoadUsers.contains(Exiting->getTerminator()); 329349cc55cSDimitry Andric })) 330349cc55cSDimitry Andric return 1; 331349cc55cSDimitry Andric return 0; 332349cc55cSDimitry Andric } 333349cc55cSDimitry Andric 334e8d8bef9SDimitry Andric // Return the number of iterations to peel off that make conditions in the 335e8d8bef9SDimitry Andric // body true/false. For example, if we peel 2 iterations off the loop below, 336e8d8bef9SDimitry Andric // the condition i < 2 can be evaluated at compile time. 337e8d8bef9SDimitry Andric // for (i = 0; i < n; i++) 338e8d8bef9SDimitry Andric // if (i < 2) 339e8d8bef9SDimitry Andric // .. 340e8d8bef9SDimitry Andric // else 341e8d8bef9SDimitry Andric // .. 342e8d8bef9SDimitry Andric // } 343e8d8bef9SDimitry Andric static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, 344e8d8bef9SDimitry Andric ScalarEvolution &SE) { 345e8d8bef9SDimitry Andric assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form"); 346e8d8bef9SDimitry Andric unsigned DesiredPeelCount = 0; 347e8d8bef9SDimitry Andric 348e8d8bef9SDimitry Andric for (auto *BB : L.blocks()) { 349e8d8bef9SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 350e8d8bef9SDimitry Andric if (!BI || BI->isUnconditional()) 351e8d8bef9SDimitry Andric continue; 352e8d8bef9SDimitry Andric 353e8d8bef9SDimitry Andric // Ignore loop exit condition. 354e8d8bef9SDimitry Andric if (L.getLoopLatch() == BB) 355e8d8bef9SDimitry Andric continue; 356e8d8bef9SDimitry Andric 357e8d8bef9SDimitry Andric Value *Condition = BI->getCondition(); 358e8d8bef9SDimitry Andric Value *LeftVal, *RightVal; 359e8d8bef9SDimitry Andric CmpInst::Predicate Pred; 360e8d8bef9SDimitry Andric if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal)))) 361e8d8bef9SDimitry Andric continue; 362e8d8bef9SDimitry Andric 363e8d8bef9SDimitry Andric const SCEV *LeftSCEV = SE.getSCEV(LeftVal); 364e8d8bef9SDimitry Andric const SCEV *RightSCEV = SE.getSCEV(RightVal); 365e8d8bef9SDimitry Andric 366e8d8bef9SDimitry Andric // Do not consider predicates that are known to be true or false 367e8d8bef9SDimitry Andric // independently of the loop iteration. 368fe6060f1SDimitry Andric if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV)) 369e8d8bef9SDimitry Andric continue; 370e8d8bef9SDimitry Andric 371e8d8bef9SDimitry Andric // Check if we have a condition with one AddRec and one non AddRec 372e8d8bef9SDimitry Andric // expression. Normalize LeftSCEV to be the AddRec. 373e8d8bef9SDimitry Andric if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 374e8d8bef9SDimitry Andric if (isa<SCEVAddRecExpr>(RightSCEV)) { 375e8d8bef9SDimitry Andric std::swap(LeftSCEV, RightSCEV); 376e8d8bef9SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred); 377e8d8bef9SDimitry Andric } else 378e8d8bef9SDimitry Andric continue; 379e8d8bef9SDimitry Andric } 380e8d8bef9SDimitry Andric 381e8d8bef9SDimitry Andric const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV); 382e8d8bef9SDimitry Andric 383e8d8bef9SDimitry Andric // Avoid huge SCEV computations in the loop below, make sure we only 384e8d8bef9SDimitry Andric // consider AddRecs of the loop we are trying to peel. 385e8d8bef9SDimitry Andric if (!LeftAR->isAffine() || LeftAR->getLoop() != &L) 386e8d8bef9SDimitry Andric continue; 387e8d8bef9SDimitry Andric if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) && 388e8d8bef9SDimitry Andric !SE.getMonotonicPredicateType(LeftAR, Pred)) 389e8d8bef9SDimitry Andric continue; 390e8d8bef9SDimitry Andric 391e8d8bef9SDimitry Andric // Check if extending the current DesiredPeelCount lets us evaluate Pred 392e8d8bef9SDimitry Andric // or !Pred in the loop body statically. 393e8d8bef9SDimitry Andric unsigned NewPeelCount = DesiredPeelCount; 394e8d8bef9SDimitry Andric 395e8d8bef9SDimitry Andric const SCEV *IterVal = LeftAR->evaluateAtIteration( 396e8d8bef9SDimitry Andric SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE); 397e8d8bef9SDimitry Andric 398e8d8bef9SDimitry Andric // If the original condition is not known, get the negated predicate 399e8d8bef9SDimitry Andric // (which holds on the else branch) and check if it is known. This allows 400e8d8bef9SDimitry Andric // us to peel of iterations that make the original condition false. 401e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 402e8d8bef9SDimitry Andric Pred = ICmpInst::getInversePredicate(Pred); 403e8d8bef9SDimitry Andric 404e8d8bef9SDimitry Andric const SCEV *Step = LeftAR->getStepRecurrence(SE); 405e8d8bef9SDimitry Andric const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step); 406e8d8bef9SDimitry Andric auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step, 407e8d8bef9SDimitry Andric &NewPeelCount]() { 408e8d8bef9SDimitry Andric IterVal = NextIterVal; 409e8d8bef9SDimitry Andric NextIterVal = SE.getAddExpr(IterVal, Step); 410e8d8bef9SDimitry Andric NewPeelCount++; 411e8d8bef9SDimitry Andric }; 412e8d8bef9SDimitry Andric 413e8d8bef9SDimitry Andric auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() { 414e8d8bef9SDimitry Andric return NewPeelCount < MaxPeelCount; 415e8d8bef9SDimitry Andric }; 416e8d8bef9SDimitry Andric 417e8d8bef9SDimitry Andric while (CanPeelOneMoreIteration() && 418e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 419e8d8bef9SDimitry Andric PeelOneMoreIteration(); 420e8d8bef9SDimitry Andric 421e8d8bef9SDimitry Andric // With *that* peel count, does the predicate !Pred become known in the 422e8d8bef9SDimitry Andric // first iteration of the loop body after peeling? 423e8d8bef9SDimitry Andric if (!SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal, 424e8d8bef9SDimitry Andric RightSCEV)) 425e8d8bef9SDimitry Andric continue; // If not, give up. 426e8d8bef9SDimitry Andric 427e8d8bef9SDimitry Andric // However, for equality comparisons, that isn't always sufficient to 428e8d8bef9SDimitry Andric // eliminate the comparsion in loop body, we may need to peel one more 429e8d8bef9SDimitry Andric // iteration. See if that makes !Pred become unknown again. 430e8d8bef9SDimitry Andric if (ICmpInst::isEquality(Pred) && 431e8d8bef9SDimitry Andric !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal, 432e8d8bef9SDimitry Andric RightSCEV) && 433e8d8bef9SDimitry Andric !SE.isKnownPredicate(Pred, IterVal, RightSCEV) && 434e8d8bef9SDimitry Andric SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) { 435e8d8bef9SDimitry Andric if (!CanPeelOneMoreIteration()) 436e8d8bef9SDimitry Andric continue; // Need to peel one more iteration, but can't. Give up. 437e8d8bef9SDimitry Andric PeelOneMoreIteration(); // Great! 438e8d8bef9SDimitry Andric } 439e8d8bef9SDimitry Andric 440e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount); 441e8d8bef9SDimitry Andric } 442e8d8bef9SDimitry Andric 443e8d8bef9SDimitry Andric return DesiredPeelCount; 444e8d8bef9SDimitry Andric } 445e8d8bef9SDimitry Andric 4460eae32dcSDimitry Andric /// This "heuristic" exactly matches implicit behavior which used to exist 4470eae32dcSDimitry Andric /// inside getLoopEstimatedTripCount. It was added here to keep an 448*bdd1243dSDimitry Andric /// improvement inside that API from causing peeling to become more aggressive. 4490eae32dcSDimitry Andric /// This should probably be removed. 4500eae32dcSDimitry Andric static bool violatesLegacyMultiExitLoopCheck(Loop *L) { 4510eae32dcSDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 4520eae32dcSDimitry Andric if (!Latch) 4530eae32dcSDimitry Andric return true; 4540eae32dcSDimitry Andric 4550eae32dcSDimitry Andric BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 4560eae32dcSDimitry Andric if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 4570eae32dcSDimitry Andric return true; 4580eae32dcSDimitry Andric 4590eae32dcSDimitry Andric assert((LatchBR->getSuccessor(0) == L->getHeader() || 4600eae32dcSDimitry Andric LatchBR->getSuccessor(1) == L->getHeader()) && 4610eae32dcSDimitry Andric "At least one edge out of the latch must go to the header"); 4620eae32dcSDimitry Andric 4630eae32dcSDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks; 4640eae32dcSDimitry Andric L->getUniqueNonLatchExitBlocks(ExitBlocks); 4650eae32dcSDimitry Andric return any_of(ExitBlocks, [](const BasicBlock *EB) { 4660eae32dcSDimitry Andric return !EB->getTerminatingDeoptimizeCall(); 4670eae32dcSDimitry Andric }); 4680eae32dcSDimitry Andric } 4690eae32dcSDimitry Andric 4700eae32dcSDimitry Andric 471e8d8bef9SDimitry Andric // Return the number of iterations we want to peel off. 472e8d8bef9SDimitry Andric void llvm::computePeelCount(Loop *L, unsigned LoopSize, 473e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences &PP, 47404eeddc0SDimitry Andric unsigned TripCount, DominatorTree &DT, 475*bdd1243dSDimitry Andric ScalarEvolution &SE, AssumptionCache *AC, 476*bdd1243dSDimitry Andric unsigned Threshold) { 477e8d8bef9SDimitry Andric assert(LoopSize > 0 && "Zero loop size is not allowed!"); 478e8d8bef9SDimitry Andric // Save the PP.PeelCount value set by the target in 479e8d8bef9SDimitry Andric // TTI.getPeelingPreferences or by the flag -unroll-peel-count. 480e8d8bef9SDimitry Andric unsigned TargetPeelCount = PP.PeelCount; 481e8d8bef9SDimitry Andric PP.PeelCount = 0; 482e8d8bef9SDimitry Andric if (!canPeel(L)) 483e8d8bef9SDimitry Andric return; 484e8d8bef9SDimitry Andric 485e8d8bef9SDimitry Andric // Only try to peel innermost loops by default. 48604eeddc0SDimitry Andric // The constraint can be relaxed by the target in TTI.getPeelingPreferences 487e8d8bef9SDimitry Andric // or by the flag -unroll-allow-loop-nests-peeling. 488e8d8bef9SDimitry Andric if (!PP.AllowLoopNestsPeeling && !L->isInnermost()) 489e8d8bef9SDimitry Andric return; 490e8d8bef9SDimitry Andric 491e8d8bef9SDimitry Andric // If the user provided a peel count, use that. 492e8d8bef9SDimitry Andric bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0; 493e8d8bef9SDimitry Andric if (UserPeelCount) { 494e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount 495e8d8bef9SDimitry Andric << " iterations.\n"); 496e8d8bef9SDimitry Andric PP.PeelCount = UnrollForcePeelCount; 497e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 498e8d8bef9SDimitry Andric return; 499e8d8bef9SDimitry Andric } 500e8d8bef9SDimitry Andric 501e8d8bef9SDimitry Andric // Skip peeling if it's disabled. 502e8d8bef9SDimitry Andric if (!PP.AllowPeeling) 503e8d8bef9SDimitry Andric return; 504e8d8bef9SDimitry Andric 50581ad6265SDimitry Andric // Check that we can peel at least one iteration. 50681ad6265SDimitry Andric if (2 * LoopSize > Threshold) 50781ad6265SDimitry Andric return; 50881ad6265SDimitry Andric 509e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 510e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 511e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 512e8d8bef9SDimitry Andric // Stop if we already peeled off the maximum number of iterations. 513e8d8bef9SDimitry Andric if (AlreadyPeeled >= UnrollPeelMaxCount) 514e8d8bef9SDimitry Andric return; 515e8d8bef9SDimitry Andric 516*bdd1243dSDimitry Andric // Pay respect to limitations implied by loop size and the max peel count. 517*bdd1243dSDimitry Andric unsigned MaxPeelCount = UnrollPeelMaxCount; 518*bdd1243dSDimitry Andric MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1); 519*bdd1243dSDimitry Andric 520*bdd1243dSDimitry Andric // Start the max computation with the PP.PeelCount value set by the target 521*bdd1243dSDimitry Andric // in TTI.getPeelingPreferences or by the flag -unroll-peel-count. 522*bdd1243dSDimitry Andric unsigned DesiredPeelCount = TargetPeelCount; 523*bdd1243dSDimitry Andric 524e8d8bef9SDimitry Andric // Here we try to get rid of Phis which become invariants after 1, 2, ..., N 525e8d8bef9SDimitry Andric // iterations of the loop. For this we compute the number for iterations after 526e8d8bef9SDimitry Andric // which every Phi is guaranteed to become an invariant, and try to peel the 527e8d8bef9SDimitry Andric // maximum number of iterations among these values, thus turning all those 528e8d8bef9SDimitry Andric // Phis into invariants. 529*bdd1243dSDimitry Andric if (MaxPeelCount > DesiredPeelCount) { 530*bdd1243dSDimitry Andric // Check how many iterations are useful for resolving Phis 531*bdd1243dSDimitry Andric auto NumPeels = PhiAnalyzer(*L, MaxPeelCount).calculateIterationsToPeel(); 532*bdd1243dSDimitry Andric if (NumPeels) 533*bdd1243dSDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, *NumPeels); 534e8d8bef9SDimitry Andric } 535e8d8bef9SDimitry Andric 536e8d8bef9SDimitry Andric DesiredPeelCount = std::max(DesiredPeelCount, 537e8d8bef9SDimitry Andric countToEliminateCompares(*L, MaxPeelCount, SE)); 538e8d8bef9SDimitry Andric 539349cc55cSDimitry Andric if (DesiredPeelCount == 0) 540*bdd1243dSDimitry Andric DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT, AC); 541349cc55cSDimitry Andric 542e8d8bef9SDimitry Andric if (DesiredPeelCount > 0) { 543e8d8bef9SDimitry Andric DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount); 544e8d8bef9SDimitry Andric // Consider max peel count limitation. 545e8d8bef9SDimitry Andric assert(DesiredPeelCount > 0 && "Wrong loop size estimation?"); 546e8d8bef9SDimitry Andric if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) { 547e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount 548e8d8bef9SDimitry Andric << " iteration(s) to turn" 549e8d8bef9SDimitry Andric << " some Phis into invariants.\n"); 550e8d8bef9SDimitry Andric PP.PeelCount = DesiredPeelCount; 551e8d8bef9SDimitry Andric PP.PeelProfiledIterations = false; 552e8d8bef9SDimitry Andric return; 553e8d8bef9SDimitry Andric } 554e8d8bef9SDimitry Andric } 555e8d8bef9SDimitry Andric 556e8d8bef9SDimitry Andric // Bail if we know the statically calculated trip count. 557e8d8bef9SDimitry Andric // In this case we rather prefer partial unrolling. 558e8d8bef9SDimitry Andric if (TripCount) 559e8d8bef9SDimitry Andric return; 560e8d8bef9SDimitry Andric 561e8d8bef9SDimitry Andric // Do not apply profile base peeling if it is disabled. 562e8d8bef9SDimitry Andric if (!PP.PeelProfiledIterations) 563e8d8bef9SDimitry Andric return; 564e8d8bef9SDimitry Andric // If we don't know the trip count, but have reason to believe the average 565e8d8bef9SDimitry Andric // trip count is low, peeling should be beneficial, since we will usually 566e8d8bef9SDimitry Andric // hit the peeled section. 567e8d8bef9SDimitry Andric // We only do this in the presence of profile information, since otherwise 568e8d8bef9SDimitry Andric // our estimates of the trip count are not reliable enough. 569e8d8bef9SDimitry Andric if (L->getHeader()->getParent()->hasProfileData()) { 5700eae32dcSDimitry Andric if (violatesLegacyMultiExitLoopCheck(L)) 5710eae32dcSDimitry Andric return; 572*bdd1243dSDimitry Andric std::optional<unsigned> EstimatedTripCount = getLoopEstimatedTripCount(L); 57381ad6265SDimitry Andric if (!EstimatedTripCount) 574e8d8bef9SDimitry Andric return; 575e8d8bef9SDimitry Andric 57681ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " 57781ad6265SDimitry Andric << *EstimatedTripCount << "\n"); 578e8d8bef9SDimitry Andric 57981ad6265SDimitry Andric if (*EstimatedTripCount) { 58081ad6265SDimitry Andric if (*EstimatedTripCount + AlreadyPeeled <= MaxPeelCount) { 58181ad6265SDimitry Andric unsigned PeelCount = *EstimatedTripCount; 58281ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Peeling first " << PeelCount << " iterations.\n"); 58381ad6265SDimitry Andric PP.PeelCount = PeelCount; 584e8d8bef9SDimitry Andric return; 585e8d8bef9SDimitry Andric } 586e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n"); 587e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n"); 58881ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Loop cost: " << LoopSize << "\n"); 589e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n"); 59081ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Max peel count by cost: " 59181ad6265SDimitry Andric << (Threshold / LoopSize - 1) << "\n"); 592e8d8bef9SDimitry Andric } 593e8d8bef9SDimitry Andric } 594e8d8bef9SDimitry Andric } 595e8d8bef9SDimitry Andric 596*bdd1243dSDimitry Andric struct WeightInfo { 597*bdd1243dSDimitry Andric // Weights for current iteration. 598*bdd1243dSDimitry Andric SmallVector<uint32_t> Weights; 599*bdd1243dSDimitry Andric // Weights to subtract after each iteration. 600*bdd1243dSDimitry Andric const SmallVector<uint32_t> SubWeights; 601*bdd1243dSDimitry Andric }; 602*bdd1243dSDimitry Andric 603*bdd1243dSDimitry Andric /// Update the branch weights of an exiting block of a peeled-off loop 604e8d8bef9SDimitry Andric /// iteration. 605*bdd1243dSDimitry Andric /// Let F is a weight of the edge to continue (fallthrough) into the loop. 606*bdd1243dSDimitry Andric /// Let E is a weight of the edge to an exit. 607e8d8bef9SDimitry Andric /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to 608e8d8bef9SDimitry Andric /// go to exit. 609*bdd1243dSDimitry Andric /// Then, Estimated ExitCount = F / E. 610e8d8bef9SDimitry Andric /// For I-th (counting from 0) peeled off iteration we set the the weights for 611*bdd1243dSDimitry Andric /// the peeled exit as (EC - I, 1). It gives us reasonable distribution, 612*bdd1243dSDimitry Andric /// The probability to go to exit 1/(EC-I) increases. At the same time 613*bdd1243dSDimitry Andric /// the estimated exit count in the remainder loop reduces by I. 614e8d8bef9SDimitry Andric /// To avoid dealing with division rounding we can just multiple both part 615e8d8bef9SDimitry Andric /// of weights to E and use weight as (F - I * E, E). 616*bdd1243dSDimitry Andric static void updateBranchWeights(Instruction *Term, WeightInfo &Info) { 617*bdd1243dSDimitry Andric MDBuilder MDB(Term->getContext()); 618*bdd1243dSDimitry Andric Term->setMetadata(LLVMContext::MD_prof, 619*bdd1243dSDimitry Andric MDB.createBranchWeights(Info.Weights)); 620*bdd1243dSDimitry Andric for (auto [Idx, SubWeight] : enumerate(Info.SubWeights)) 621*bdd1243dSDimitry Andric if (SubWeight != 0) 622*bdd1243dSDimitry Andric Info.Weights[Idx] = Info.Weights[Idx] > SubWeight 623*bdd1243dSDimitry Andric ? Info.Weights[Idx] - SubWeight 624*bdd1243dSDimitry Andric : 1; 625e8d8bef9SDimitry Andric } 626e8d8bef9SDimitry Andric 627*bdd1243dSDimitry Andric /// Initialize the weights for all exiting blocks. 628*bdd1243dSDimitry Andric static void initBranchWeights(DenseMap<Instruction *, WeightInfo> &WeightInfos, 629*bdd1243dSDimitry Andric Loop *L) { 630*bdd1243dSDimitry Andric SmallVector<BasicBlock *> ExitingBlocks; 631*bdd1243dSDimitry Andric L->getExitingBlocks(ExitingBlocks); 632*bdd1243dSDimitry Andric for (BasicBlock *ExitingBlock : ExitingBlocks) { 633*bdd1243dSDimitry Andric Instruction *Term = ExitingBlock->getTerminator(); 634*bdd1243dSDimitry Andric SmallVector<uint32_t> Weights; 635*bdd1243dSDimitry Andric if (!extractBranchWeights(*Term, Weights)) 636*bdd1243dSDimitry Andric continue; 637*bdd1243dSDimitry Andric 638*bdd1243dSDimitry Andric // See the comment on updateBranchWeights() for an explanation of what we 639*bdd1243dSDimitry Andric // do here. 640*bdd1243dSDimitry Andric uint32_t FallThroughWeights = 0; 641*bdd1243dSDimitry Andric uint32_t ExitWeights = 0; 642*bdd1243dSDimitry Andric for (auto [Succ, Weight] : zip(successors(Term), Weights)) { 643*bdd1243dSDimitry Andric if (L->contains(Succ)) 644*bdd1243dSDimitry Andric FallThroughWeights += Weight; 645*bdd1243dSDimitry Andric else 646*bdd1243dSDimitry Andric ExitWeights += Weight; 647e8d8bef9SDimitry Andric } 648e8d8bef9SDimitry Andric 649*bdd1243dSDimitry Andric // Don't try to update weights for degenerate case. 650*bdd1243dSDimitry Andric if (FallThroughWeights == 0) 651*bdd1243dSDimitry Andric continue; 652e8d8bef9SDimitry Andric 653*bdd1243dSDimitry Andric SmallVector<uint32_t> SubWeights; 654*bdd1243dSDimitry Andric for (auto [Succ, Weight] : zip(successors(Term), Weights)) { 655*bdd1243dSDimitry Andric if (!L->contains(Succ)) { 656*bdd1243dSDimitry Andric // Exit weights stay the same. 657*bdd1243dSDimitry Andric SubWeights.push_back(0); 658*bdd1243dSDimitry Andric continue; 659*bdd1243dSDimitry Andric } 660*bdd1243dSDimitry Andric 661*bdd1243dSDimitry Andric // Subtract exit weights on each iteration, distributed across all 662*bdd1243dSDimitry Andric // fallthrough edges. 663*bdd1243dSDimitry Andric double W = (double)Weight / (double)FallThroughWeights; 664*bdd1243dSDimitry Andric SubWeights.push_back((uint32_t)(ExitWeights * W)); 665*bdd1243dSDimitry Andric } 666*bdd1243dSDimitry Andric 667*bdd1243dSDimitry Andric WeightInfos.insert({Term, {std::move(Weights), std::move(SubWeights)}}); 668*bdd1243dSDimitry Andric } 669*bdd1243dSDimitry Andric } 670*bdd1243dSDimitry Andric 671*bdd1243dSDimitry Andric /// Update the weights of original exiting block after peeling off all 672*bdd1243dSDimitry Andric /// iterations. 673*bdd1243dSDimitry Andric static void fixupBranchWeights(Instruction *Term, const WeightInfo &Info) { 674*bdd1243dSDimitry Andric MDBuilder MDB(Term->getContext()); 675*bdd1243dSDimitry Andric Term->setMetadata(LLVMContext::MD_prof, 676*bdd1243dSDimitry Andric MDB.createBranchWeights(Info.Weights)); 677e8d8bef9SDimitry Andric } 678e8d8bef9SDimitry Andric 679e8d8bef9SDimitry Andric /// Clones the body of the loop L, putting it between \p InsertTop and \p 680e8d8bef9SDimitry Andric /// InsertBot. 681e8d8bef9SDimitry Andric /// \param IterNumber The serial number of the iteration currently being 682e8d8bef9SDimitry Andric /// peeled off. 683e8d8bef9SDimitry Andric /// \param ExitEdges The exit edges of the original loop. 684e8d8bef9SDimitry Andric /// \param[out] NewBlocks A list of the blocks in the newly created clone 685e8d8bef9SDimitry Andric /// \param[out] VMap The value map between the loop and the new clone. 686e8d8bef9SDimitry Andric /// \param LoopBlocks A helper for DFS-traversal of the loop. 687e8d8bef9SDimitry Andric /// \param LVMap A value-map that maps instructions from the original loop to 688e8d8bef9SDimitry Andric /// instructions in the last peeled-off iteration. 689e8d8bef9SDimitry Andric static void cloneLoopBlocks( 690e8d8bef9SDimitry Andric Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, 691e8d8bef9SDimitry Andric SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges, 692e8d8bef9SDimitry Andric SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 693e8d8bef9SDimitry Andric ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, 69481ad6265SDimitry Andric LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes, 69581ad6265SDimitry Andric ScalarEvolution &SE) { 696e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 697e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 698e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 699e8d8bef9SDimitry Andric 700e8d8bef9SDimitry Andric Function *F = Header->getParent(); 701e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 702e8d8bef9SDimitry Andric LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 703e8d8bef9SDimitry Andric Loop *ParentLoop = L->getParentLoop(); 704e8d8bef9SDimitry Andric 705e8d8bef9SDimitry Andric // For each block in the original loop, create a new copy, 706e8d8bef9SDimitry Andric // and update the value map with the newly created values. 707e8d8bef9SDimitry Andric for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 708e8d8bef9SDimitry Andric BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); 709e8d8bef9SDimitry Andric NewBlocks.push_back(NewBB); 710e8d8bef9SDimitry Andric 711e8d8bef9SDimitry Andric // If an original block is an immediate child of the loop L, its copy 712e8d8bef9SDimitry Andric // is a child of a ParentLoop after peeling. If a block is a child of 713e8d8bef9SDimitry Andric // a nested loop, it is handled in the cloneLoop() call below. 714e8d8bef9SDimitry Andric if (ParentLoop && LI->getLoopFor(*BB) == L) 715e8d8bef9SDimitry Andric ParentLoop->addBasicBlockToLoop(NewBB, *LI); 716e8d8bef9SDimitry Andric 717e8d8bef9SDimitry Andric VMap[*BB] = NewBB; 718e8d8bef9SDimitry Andric 719e8d8bef9SDimitry Andric // If dominator tree is available, insert nodes to represent cloned blocks. 720e8d8bef9SDimitry Andric if (DT) { 721e8d8bef9SDimitry Andric if (Header == *BB) 722e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, InsertTop); 723e8d8bef9SDimitry Andric else { 724e8d8bef9SDimitry Andric DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); 725e8d8bef9SDimitry Andric // VMap must contain entry for IDom, as the iteration order is RPO. 726e8d8bef9SDimitry Andric DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()])); 727e8d8bef9SDimitry Andric } 728e8d8bef9SDimitry Andric } 729e8d8bef9SDimitry Andric } 730e8d8bef9SDimitry Andric 731d409305fSDimitry Andric { 732d409305fSDimitry Andric // Identify what other metadata depends on the cloned version. After 733d409305fSDimitry Andric // cloning, replace the metadata with the corrected version for both 734d409305fSDimitry Andric // memory instructions and noalias intrinsics. 735d409305fSDimitry Andric std::string Ext = (Twine("Peel") + Twine(IterNumber)).str(); 736d409305fSDimitry Andric cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks, 737d409305fSDimitry Andric Header->getContext(), Ext); 738d409305fSDimitry Andric } 739d409305fSDimitry Andric 740e8d8bef9SDimitry Andric // Recursively create the new Loop objects for nested loops, if any, 741e8d8bef9SDimitry Andric // to preserve LoopInfo. 742e8d8bef9SDimitry Andric for (Loop *ChildLoop : *L) { 743e8d8bef9SDimitry Andric cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr); 744e8d8bef9SDimitry Andric } 745e8d8bef9SDimitry Andric 746e8d8bef9SDimitry Andric // Hook-up the control flow for the newly inserted blocks. 747e8d8bef9SDimitry Andric // The new header is hooked up directly to the "top", which is either 748e8d8bef9SDimitry Andric // the original loop preheader (for the first iteration) or the previous 749e8d8bef9SDimitry Andric // iteration's exiting block (for every other iteration) 750e8d8bef9SDimitry Andric InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header])); 751e8d8bef9SDimitry Andric 752e8d8bef9SDimitry Andric // Similarly, for the latch: 753e8d8bef9SDimitry Andric // The original exiting edge is still hooked up to the loop exit. 754e8d8bef9SDimitry Andric // The backedge now goes to the "bottom", which is either the loop's real 755e8d8bef9SDimitry Andric // header (for the last peeled iteration) or the copied header of the next 756e8d8bef9SDimitry Andric // iteration (for every other iteration) 757e8d8bef9SDimitry Andric BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 758*bdd1243dSDimitry Andric auto *LatchTerm = cast<Instruction>(NewLatch->getTerminator()); 759*bdd1243dSDimitry Andric for (unsigned idx = 0, e = LatchTerm->getNumSuccessors(); idx < e; ++idx) 760*bdd1243dSDimitry Andric if (LatchTerm->getSuccessor(idx) == Header) { 761*bdd1243dSDimitry Andric LatchTerm->setSuccessor(idx, InsertBot); 762e8d8bef9SDimitry Andric break; 763e8d8bef9SDimitry Andric } 764e8d8bef9SDimitry Andric if (DT) 765e8d8bef9SDimitry Andric DT->changeImmediateDominator(InsertBot, NewLatch); 766e8d8bef9SDimitry Andric 767e8d8bef9SDimitry Andric // The new copy of the loop body starts with a bunch of PHI nodes 768e8d8bef9SDimitry Andric // that pick an incoming value from either the preheader, or the previous 769e8d8bef9SDimitry Andric // loop iteration. Since this copy is no longer part of the loop, we 770e8d8bef9SDimitry Andric // resolve this statically: 771e8d8bef9SDimitry Andric // For the first iteration, we use the value from the preheader directly. 772e8d8bef9SDimitry Andric // For any other iteration, we replace the phi with the value generated by 773e8d8bef9SDimitry Andric // the immediately preceding clone of the loop body (which represents 774e8d8bef9SDimitry Andric // the previous iteration). 775e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 776e8d8bef9SDimitry Andric PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 777e8d8bef9SDimitry Andric if (IterNumber == 0) { 778e8d8bef9SDimitry Andric VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader); 779e8d8bef9SDimitry Andric } else { 780e8d8bef9SDimitry Andric Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); 781e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 782e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 783e8d8bef9SDimitry Andric VMap[&*I] = LVMap[LatchInst]; 784e8d8bef9SDimitry Andric else 785e8d8bef9SDimitry Andric VMap[&*I] = LatchVal; 786e8d8bef9SDimitry Andric } 787*bdd1243dSDimitry Andric NewPHI->eraseFromParent(); 788e8d8bef9SDimitry Andric } 789e8d8bef9SDimitry Andric 790e8d8bef9SDimitry Andric // Fix up the outgoing values - we need to add a value for the iteration 791e8d8bef9SDimitry Andric // we've just created. Note that this must happen *after* the incoming 792e8d8bef9SDimitry Andric // values are adjusted, since the value going out of the latch may also be 793e8d8bef9SDimitry Andric // a value coming into the header. 794e8d8bef9SDimitry Andric for (auto Edge : ExitEdges) 795e8d8bef9SDimitry Andric for (PHINode &PHI : Edge.second->phis()) { 796e8d8bef9SDimitry Andric Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first); 797e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 798e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 799e8d8bef9SDimitry Andric LatchVal = VMap[LatchVal]; 800e8d8bef9SDimitry Andric PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first])); 80181ad6265SDimitry Andric SE.forgetValue(&PHI); 802e8d8bef9SDimitry Andric } 803e8d8bef9SDimitry Andric 804e8d8bef9SDimitry Andric // LastValueMap is updated with the values for the current loop 805e8d8bef9SDimitry Andric // which are used the next time this function is called. 806e8d8bef9SDimitry Andric for (auto KV : VMap) 807e8d8bef9SDimitry Andric LVMap[KV.first] = KV.second; 808e8d8bef9SDimitry Andric } 809e8d8bef9SDimitry Andric 810*bdd1243dSDimitry Andric TargetTransformInfo::PeelingPreferences 811*bdd1243dSDimitry Andric llvm::gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, 812*bdd1243dSDimitry Andric const TargetTransformInfo &TTI, 813*bdd1243dSDimitry Andric std::optional<bool> UserAllowPeeling, 814*bdd1243dSDimitry Andric std::optional<bool> UserAllowProfileBasedPeeling, 815*bdd1243dSDimitry Andric bool UnrollingSpecficValues) { 816e8d8bef9SDimitry Andric TargetTransformInfo::PeelingPreferences PP; 817e8d8bef9SDimitry Andric 818e8d8bef9SDimitry Andric // Set the default values. 819e8d8bef9SDimitry Andric PP.PeelCount = 0; 820e8d8bef9SDimitry Andric PP.AllowPeeling = true; 821e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = false; 822e8d8bef9SDimitry Andric PP.PeelProfiledIterations = true; 823e8d8bef9SDimitry Andric 824e8d8bef9SDimitry Andric // Get the target specifc values. 825e8d8bef9SDimitry Andric TTI.getPeelingPreferences(L, SE, PP); 826e8d8bef9SDimitry Andric 827e8d8bef9SDimitry Andric // User specified values using cl::opt. 828e8d8bef9SDimitry Andric if (UnrollingSpecficValues) { 829e8d8bef9SDimitry Andric if (UnrollPeelCount.getNumOccurrences() > 0) 830e8d8bef9SDimitry Andric PP.PeelCount = UnrollPeelCount; 831e8d8bef9SDimitry Andric if (UnrollAllowPeeling.getNumOccurrences() > 0) 832e8d8bef9SDimitry Andric PP.AllowPeeling = UnrollAllowPeeling; 833e8d8bef9SDimitry Andric if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0) 834e8d8bef9SDimitry Andric PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling; 835e8d8bef9SDimitry Andric } 836e8d8bef9SDimitry Andric 837e8d8bef9SDimitry Andric // User specifed values provided by argument. 83881ad6265SDimitry Andric if (UserAllowPeeling) 839e8d8bef9SDimitry Andric PP.AllowPeeling = *UserAllowPeeling; 84081ad6265SDimitry Andric if (UserAllowProfileBasedPeeling) 841e8d8bef9SDimitry Andric PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; 842e8d8bef9SDimitry Andric 843e8d8bef9SDimitry Andric return PP; 844e8d8bef9SDimitry Andric } 845e8d8bef9SDimitry Andric 846e8d8bef9SDimitry Andric /// Peel off the first \p PeelCount iterations of loop \p L. 847e8d8bef9SDimitry Andric /// 848e8d8bef9SDimitry Andric /// Note that this does not peel them off as a single straight-line block. 849e8d8bef9SDimitry Andric /// Rather, each iteration is peeled off separately, and needs to check the 850e8d8bef9SDimitry Andric /// exit condition. 851e8d8bef9SDimitry Andric /// For loops that dynamically execute \p PeelCount iterations or less 852e8d8bef9SDimitry Andric /// this provides a benefit, since the peeled off iterations, which account 853e8d8bef9SDimitry Andric /// for the bulk of dynamic execution, can be further simplified by scalar 854e8d8bef9SDimitry Andric /// optimizations. 855e8d8bef9SDimitry Andric bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, 8561fd87a68SDimitry Andric ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, 857*bdd1243dSDimitry Andric bool PreserveLCSSA, ValueToValueMapTy &LVMap) { 858e8d8bef9SDimitry Andric assert(PeelCount > 0 && "Attempt to peel out zero iterations?"); 859e8d8bef9SDimitry Andric assert(canPeel(L) && "Attempt to peel a loop which is not peelable?"); 860e8d8bef9SDimitry Andric 861e8d8bef9SDimitry Andric LoopBlocksDFS LoopBlocks(L); 862e8d8bef9SDimitry Andric LoopBlocks.perform(LI); 863e8d8bef9SDimitry Andric 864e8d8bef9SDimitry Andric BasicBlock *Header = L->getHeader(); 865e8d8bef9SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader(); 866e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 867e8d8bef9SDimitry Andric SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges; 868e8d8bef9SDimitry Andric L->getExitEdges(ExitEdges); 869e8d8bef9SDimitry Andric 870349cc55cSDimitry Andric // Remember dominators of blocks we might reach through exits to change them 871349cc55cSDimitry Andric // later. Immediate dominator of such block might change, because we add more 872349cc55cSDimitry Andric // routes which can lead to the exit: we can reach it from the peeled 873349cc55cSDimitry Andric // iterations too. 874349cc55cSDimitry Andric DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom; 875349cc55cSDimitry Andric for (auto *BB : L->blocks()) { 8761fd87a68SDimitry Andric auto *BBDomNode = DT.getNode(BB); 877349cc55cSDimitry Andric SmallVector<BasicBlock *, 16> ChildrenToUpdate; 878349cc55cSDimitry Andric for (auto *ChildDomNode : BBDomNode->children()) { 879349cc55cSDimitry Andric auto *ChildBB = ChildDomNode->getBlock(); 880349cc55cSDimitry Andric if (!L->contains(ChildBB)) 881349cc55cSDimitry Andric ChildrenToUpdate.push_back(ChildBB); 882349cc55cSDimitry Andric } 883349cc55cSDimitry Andric // The new idom of the block will be the nearest common dominator 884349cc55cSDimitry Andric // of all copies of the previous idom. This is equivalent to the 885349cc55cSDimitry Andric // nearest common dominator of the previous idom and the first latch, 886349cc55cSDimitry Andric // which dominates all copies of the previous idom. 8871fd87a68SDimitry Andric BasicBlock *NewIDom = DT.findNearestCommonDominator(BB, Latch); 888349cc55cSDimitry Andric for (auto *ChildBB : ChildrenToUpdate) 889349cc55cSDimitry Andric NonLoopBlocksIDom[ChildBB] = NewIDom; 890e8d8bef9SDimitry Andric } 891e8d8bef9SDimitry Andric 892e8d8bef9SDimitry Andric Function *F = Header->getParent(); 893e8d8bef9SDimitry Andric 894e8d8bef9SDimitry Andric // Set up all the necessary basic blocks. It is convenient to split the 895e8d8bef9SDimitry Andric // preheader into 3 parts - two blocks to anchor the peeled copy of the loop 896e8d8bef9SDimitry Andric // body, and a new preheader for the "real" loop. 897e8d8bef9SDimitry Andric 898e8d8bef9SDimitry Andric // Peeling the first iteration transforms. 899e8d8bef9SDimitry Andric // 900e8d8bef9SDimitry Andric // PreHeader: 901e8d8bef9SDimitry Andric // ... 902e8d8bef9SDimitry Andric // Header: 903e8d8bef9SDimitry Andric // LoopBody 904e8d8bef9SDimitry Andric // If (cond) goto Header 905e8d8bef9SDimitry Andric // Exit: 906e8d8bef9SDimitry Andric // 907e8d8bef9SDimitry Andric // into 908e8d8bef9SDimitry Andric // 909e8d8bef9SDimitry Andric // InsertTop: 910e8d8bef9SDimitry Andric // LoopBody 911e8d8bef9SDimitry Andric // If (!cond) goto Exit 912e8d8bef9SDimitry Andric // InsertBot: 913e8d8bef9SDimitry Andric // NewPreHeader: 914e8d8bef9SDimitry Andric // ... 915e8d8bef9SDimitry Andric // Header: 916e8d8bef9SDimitry Andric // LoopBody 917e8d8bef9SDimitry Andric // If (cond) goto Header 918e8d8bef9SDimitry Andric // Exit: 919e8d8bef9SDimitry Andric // 920e8d8bef9SDimitry Andric // Each following iteration will split the current bottom anchor in two, 921e8d8bef9SDimitry Andric // and put the new copy of the loop body between these two blocks. That is, 922e8d8bef9SDimitry Andric // after peeling another iteration from the example above, we'll split 923e8d8bef9SDimitry Andric // InsertBot, and get: 924e8d8bef9SDimitry Andric // 925e8d8bef9SDimitry Andric // InsertTop: 926e8d8bef9SDimitry Andric // LoopBody 927e8d8bef9SDimitry Andric // If (!cond) goto Exit 928e8d8bef9SDimitry Andric // InsertBot: 929e8d8bef9SDimitry Andric // LoopBody 930e8d8bef9SDimitry Andric // If (!cond) goto Exit 931e8d8bef9SDimitry Andric // InsertBot.next: 932e8d8bef9SDimitry Andric // NewPreHeader: 933e8d8bef9SDimitry Andric // ... 934e8d8bef9SDimitry Andric // Header: 935e8d8bef9SDimitry Andric // LoopBody 936e8d8bef9SDimitry Andric // If (cond) goto Header 937e8d8bef9SDimitry Andric // Exit: 938e8d8bef9SDimitry Andric 9391fd87a68SDimitry Andric BasicBlock *InsertTop = SplitEdge(PreHeader, Header, &DT, LI); 940e8d8bef9SDimitry Andric BasicBlock *InsertBot = 9411fd87a68SDimitry Andric SplitBlock(InsertTop, InsertTop->getTerminator(), &DT, LI); 942e8d8bef9SDimitry Andric BasicBlock *NewPreHeader = 9431fd87a68SDimitry Andric SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 944e8d8bef9SDimitry Andric 945e8d8bef9SDimitry Andric InsertTop->setName(Header->getName() + ".peel.begin"); 946e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 947e8d8bef9SDimitry Andric NewPreHeader->setName(PreHeader->getName() + ".peel.newph"); 948e8d8bef9SDimitry Andric 949*bdd1243dSDimitry Andric Instruction *LatchTerm = 950*bdd1243dSDimitry Andric cast<Instruction>(cast<BasicBlock>(Latch)->getTerminator()); 951e8d8bef9SDimitry Andric 952e8d8bef9SDimitry Andric // If we have branch weight information, we'll want to update it for the 953e8d8bef9SDimitry Andric // newly created branches. 954*bdd1243dSDimitry Andric DenseMap<Instruction *, WeightInfo> Weights; 955*bdd1243dSDimitry Andric initBranchWeights(Weights, L); 956e8d8bef9SDimitry Andric 957d409305fSDimitry Andric // Identify what noalias metadata is inside the loop: if it is inside the 958d409305fSDimitry Andric // loop, the associated metadata must be cloned for each iteration. 959d409305fSDimitry Andric SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; 960d409305fSDimitry Andric identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes); 961d409305fSDimitry Andric 962e8d8bef9SDimitry Andric // For each peeled-off iteration, make a copy of the loop. 963e8d8bef9SDimitry Andric for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { 964e8d8bef9SDimitry Andric SmallVector<BasicBlock *, 8> NewBlocks; 965e8d8bef9SDimitry Andric ValueToValueMapTy VMap; 966e8d8bef9SDimitry Andric 967e8d8bef9SDimitry Andric cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks, 9681fd87a68SDimitry Andric LoopBlocks, VMap, LVMap, &DT, LI, 96981ad6265SDimitry Andric LoopLocalNoAliasDeclScopes, *SE); 970e8d8bef9SDimitry Andric 971e8d8bef9SDimitry Andric // Remap to use values from the current iteration instead of the 972e8d8bef9SDimitry Andric // previous one. 973e8d8bef9SDimitry Andric remapInstructionsInBlocks(NewBlocks, VMap); 974e8d8bef9SDimitry Andric 975349cc55cSDimitry Andric // Update IDoms of the blocks reachable through exits. 976e8d8bef9SDimitry Andric if (Iter == 0) 977349cc55cSDimitry Andric for (auto BBIDom : NonLoopBlocksIDom) 9781fd87a68SDimitry Andric DT.changeImmediateDominator(BBIDom.first, 979349cc55cSDimitry Andric cast<BasicBlock>(LVMap[BBIDom.second])); 980e8d8bef9SDimitry Andric #ifdef EXPENSIVE_CHECKS 9811fd87a68SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 982e8d8bef9SDimitry Andric #endif 983e8d8bef9SDimitry Andric 984*bdd1243dSDimitry Andric for (auto &[Term, Info] : Weights) { 985*bdd1243dSDimitry Andric auto *TermCopy = cast<Instruction>(VMap[Term]); 986*bdd1243dSDimitry Andric updateBranchWeights(TermCopy, Info); 987*bdd1243dSDimitry Andric } 988*bdd1243dSDimitry Andric 989e8d8bef9SDimitry Andric // Remove Loop metadata from the latch branch instruction 990e8d8bef9SDimitry Andric // because it is not the Loop's latch branch anymore. 991*bdd1243dSDimitry Andric auto *LatchTermCopy = cast<Instruction>(VMap[LatchTerm]); 992*bdd1243dSDimitry Andric LatchTermCopy->setMetadata(LLVMContext::MD_loop, nullptr); 993e8d8bef9SDimitry Andric 994e8d8bef9SDimitry Andric InsertTop = InsertBot; 9951fd87a68SDimitry Andric InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 996e8d8bef9SDimitry Andric InsertBot->setName(Header->getName() + ".peel.next"); 997e8d8bef9SDimitry Andric 998*bdd1243dSDimitry Andric F->splice(InsertTop->getIterator(), F, NewBlocks[0]->getIterator(), 999*bdd1243dSDimitry Andric F->end()); 1000e8d8bef9SDimitry Andric } 1001e8d8bef9SDimitry Andric 1002e8d8bef9SDimitry Andric // Now adjust the phi nodes in the loop header to get their initial values 1003e8d8bef9SDimitry Andric // from the last peeled-off iteration instead of the preheader. 1004e8d8bef9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 1005e8d8bef9SDimitry Andric PHINode *PHI = cast<PHINode>(I); 1006e8d8bef9SDimitry Andric Value *NewVal = PHI->getIncomingValueForBlock(Latch); 1007e8d8bef9SDimitry Andric Instruction *LatchInst = dyn_cast<Instruction>(NewVal); 1008e8d8bef9SDimitry Andric if (LatchInst && L->contains(LatchInst)) 1009e8d8bef9SDimitry Andric NewVal = LVMap[LatchInst]; 1010e8d8bef9SDimitry Andric 1011e8d8bef9SDimitry Andric PHI->setIncomingValueForBlock(NewPreHeader, NewVal); 1012e8d8bef9SDimitry Andric } 1013e8d8bef9SDimitry Andric 1014*bdd1243dSDimitry Andric for (const auto &[Term, Info] : Weights) 1015*bdd1243dSDimitry Andric fixupBranchWeights(Term, Info); 1016e8d8bef9SDimitry Andric 1017e8d8bef9SDimitry Andric // Update Metadata for count of peeled off iterations. 1018e8d8bef9SDimitry Andric unsigned AlreadyPeeled = 0; 1019e8d8bef9SDimitry Andric if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 1020e8d8bef9SDimitry Andric AlreadyPeeled = *Peeled; 1021e8d8bef9SDimitry Andric addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount); 1022e8d8bef9SDimitry Andric 1023e8d8bef9SDimitry Andric if (Loop *ParentLoop = L->getParentLoop()) 1024e8d8bef9SDimitry Andric L = ParentLoop; 1025e8d8bef9SDimitry Andric 1026e8d8bef9SDimitry Andric // We modified the loop, update SE. 1027e8d8bef9SDimitry Andric SE->forgetTopmostLoop(L); 1028e8d8bef9SDimitry Andric 102981ad6265SDimitry Andric #ifdef EXPENSIVE_CHECKS 1030e8d8bef9SDimitry Andric // Finally DomtTree must be correct. 10311fd87a68SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 103281ad6265SDimitry Andric #endif 1033e8d8bef9SDimitry Andric 1034e8d8bef9SDimitry Andric // FIXME: Incrementally update loop-simplify 10351fd87a68SDimitry Andric simplifyLoop(L, &DT, LI, SE, AC, nullptr, PreserveLCSSA); 1036e8d8bef9SDimitry Andric 1037e8d8bef9SDimitry Andric NumPeeled++; 1038e8d8bef9SDimitry Andric 1039e8d8bef9SDimitry Andric return true; 1040e8d8bef9SDimitry Andric } 1041