xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/LoopPeel.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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"
31bdd1243dSDimitry 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>
44bdd1243dSDimitry 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 
75bdd1243dSDimitry Andric static cl::opt<bool> DisableAdvancedPeeling(
76bdd1243dSDimitry Andric     "disable-advanced-peeling", cl::init(false), cl::Hidden,
77bdd1243dSDimitry Andric     cl::desc(
78bdd1243dSDimitry Andric         "Disable advance peeling. Issues for convergent targets (D134803)."));
79bdd1243dSDimitry Andric 
80e8d8bef9SDimitry Andric static const char *PeeledCountMetaData = "llvm.loop.peeled.count";
81e8d8bef9SDimitry Andric 
82e8d8bef9SDimitry Andric // Check whether we are capable of peeling this loop.
83bdd1243dSDimitry 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;
87bdd1243dSDimitry Andric   if (!DisableAdvancedPeeling)
88bdd1243dSDimitry 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 
103bdd1243dSDimitry Andric namespace {
104bdd1243dSDimitry Andric 
105bdd1243dSDimitry Andric // As a loop is peeled, it may be the case that Phi nodes become
106bdd1243dSDimitry Andric // loop-invariant (ie, known because there is only one choice).
107bdd1243dSDimitry Andric // For example, consider the following function:
108bdd1243dSDimitry Andric //   void g(int);
109bdd1243dSDimitry Andric //   void binary() {
110bdd1243dSDimitry Andric //     int x = 0;
111bdd1243dSDimitry Andric //     int y = 0;
112bdd1243dSDimitry Andric //     int a = 0;
113bdd1243dSDimitry Andric //     for(int i = 0; i <100000; ++i) {
114bdd1243dSDimitry Andric //       g(x);
115bdd1243dSDimitry Andric //       x = y;
116bdd1243dSDimitry Andric //       g(a);
117bdd1243dSDimitry Andric //       y = a + 1;
118bdd1243dSDimitry Andric //       a = 5;
119bdd1243dSDimitry Andric //     }
120bdd1243dSDimitry Andric //   }
121bdd1243dSDimitry Andric // Peeling 3 iterations is beneficial because the values for x, y and a
122bdd1243dSDimitry Andric // become known.  The IR for this loop looks something like the following:
123bdd1243dSDimitry Andric //
124bdd1243dSDimitry Andric //   %i = phi i32 [ 0, %entry ], [ %inc, %if.end ]
125bdd1243dSDimitry Andric //   %a = phi i32 [ 0, %entry ], [ 5, %if.end ]
126bdd1243dSDimitry Andric //   %y = phi i32 [ 0, %entry ], [ %add, %if.end ]
127bdd1243dSDimitry Andric //   %x = phi i32 [ 0, %entry ], [ %y, %if.end ]
128bdd1243dSDimitry Andric //   ...
129bdd1243dSDimitry Andric //   tail call void @_Z1gi(i32 signext %x)
130bdd1243dSDimitry Andric //   tail call void @_Z1gi(i32 signext %a)
131bdd1243dSDimitry Andric //   %add = add nuw nsw i32 %a, 1
132bdd1243dSDimitry Andric //   %inc = add nuw nsw i32 %i, 1
133bdd1243dSDimitry Andric //   %exitcond = icmp eq i32 %inc, 100000
134bdd1243dSDimitry Andric //   br i1 %exitcond, label %for.cond.cleanup, label %for.body
135bdd1243dSDimitry Andric //
136bdd1243dSDimitry Andric // The arguments for the calls to g will become known after 3 iterations
137bdd1243dSDimitry Andric // of the loop, because the phi nodes values become known after 3 iterations
138bdd1243dSDimitry Andric // of the loop (ie, they are known on the 4th iteration, so peel 3 iterations).
139bdd1243dSDimitry Andric // The first iteration has g(0), g(0); the second has g(0), g(5); the
140bdd1243dSDimitry Andric // third has g(1), g(5) and the fourth (and all subsequent) have g(6), g(5).
141bdd1243dSDimitry Andric // Now consider the phi nodes:
142bdd1243dSDimitry Andric //   %a is a phi with constants so it is determined after iteration 1.
143bdd1243dSDimitry Andric //   %y is a phi based on a constant and %a so it is determined on
144bdd1243dSDimitry Andric //     the iteration after %a is determined, so iteration 2.
145bdd1243dSDimitry Andric //   %x is a phi based on a constant and %y so it is determined on
146bdd1243dSDimitry Andric //     the iteration after %y, so iteration 3.
147bdd1243dSDimitry Andric //   %i is based on itself (and is an induction variable) so it is
148bdd1243dSDimitry Andric //     never determined.
149bdd1243dSDimitry Andric // This means that peeling off 3 iterations will result in being able to
150bdd1243dSDimitry Andric // remove the phi nodes for %a, %y, and %x.  The arguments for the
151bdd1243dSDimitry Andric // corresponding calls to g are determined and the code for computing
152bdd1243dSDimitry Andric // x, y, and a can be removed.
153bdd1243dSDimitry Andric //
154bdd1243dSDimitry Andric // The PhiAnalyzer class calculates how many times a loop should be
155bdd1243dSDimitry Andric // peeled based on the above analysis of the phi nodes in the loop while
156bdd1243dSDimitry Andric // respecting the maximum specified.
157bdd1243dSDimitry Andric class PhiAnalyzer {
158bdd1243dSDimitry Andric public:
159bdd1243dSDimitry Andric   PhiAnalyzer(const Loop &L, unsigned MaxIterations);
160bdd1243dSDimitry Andric 
161bdd1243dSDimitry Andric   // Calculate the sufficient minimum number of iterations of the loop to peel
162bdd1243dSDimitry Andric   // such that phi instructions become determined (subject to allowable limits)
163bdd1243dSDimitry Andric   std::optional<unsigned> calculateIterationsToPeel();
164bdd1243dSDimitry Andric 
165bdd1243dSDimitry Andric protected:
166bdd1243dSDimitry Andric   using PeelCounter = std::optional<unsigned>;
167bdd1243dSDimitry Andric   const PeelCounter Unknown = std::nullopt;
168bdd1243dSDimitry Andric 
169bdd1243dSDimitry Andric   // Add 1 respecting Unknown and return Unknown if result over MaxIterations
170bdd1243dSDimitry Andric   PeelCounter addOne(PeelCounter PC) const {
171bdd1243dSDimitry Andric     if (PC == Unknown)
172bdd1243dSDimitry Andric       return Unknown;
173bdd1243dSDimitry Andric     return (*PC + 1 <= MaxIterations) ? PeelCounter{*PC + 1} : Unknown;
174bdd1243dSDimitry Andric   }
175bdd1243dSDimitry Andric 
176bdd1243dSDimitry Andric   // Calculate the number of iterations after which the given value
177bdd1243dSDimitry Andric   // becomes an invariant.
178bdd1243dSDimitry Andric   PeelCounter calculate(const Value &);
179bdd1243dSDimitry Andric 
180bdd1243dSDimitry Andric   const Loop &L;
181bdd1243dSDimitry Andric   const unsigned MaxIterations;
182bdd1243dSDimitry Andric 
183bdd1243dSDimitry Andric   // Map of Values to number of iterations to invariance
184bdd1243dSDimitry Andric   SmallDenseMap<const Value *, PeelCounter> IterationsToInvariance;
185bdd1243dSDimitry Andric };
186bdd1243dSDimitry Andric 
187bdd1243dSDimitry Andric PhiAnalyzer::PhiAnalyzer(const Loop &L, unsigned MaxIterations)
188bdd1243dSDimitry Andric     : L(L), MaxIterations(MaxIterations) {
189bdd1243dSDimitry Andric   assert(canPeel(&L) && "loop is not suitable for peeling");
190bdd1243dSDimitry Andric   assert(MaxIterations > 0 && "no peeling is allowed?");
191bdd1243dSDimitry Andric }
192bdd1243dSDimitry Andric 
193bdd1243dSDimitry Andric // This function calculates the number of iterations after which the value
194bdd1243dSDimitry Andric // becomes an invariant. The pre-calculated values are memorized in a map.
195bdd1243dSDimitry Andric // N.B. This number will be Unknown or <= MaxIterations.
196bdd1243dSDimitry Andric // The function is calculated according to the following definition:
197e8d8bef9SDimitry Andric // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge].
198bdd1243dSDimitry Andric //   F(%x) = G(%y) + 1 (N.B. [MaxIterations | Unknown] + 1 => Unknown)
199bdd1243dSDimitry Andric //   G(%y) = 0 if %y is a loop invariant
200bdd1243dSDimitry Andric //   G(%y) = G(%BackEdgeValue) if %y is a phi in the header block
201bdd1243dSDimitry Andric //   G(%y) = TODO: if %y is an expression based on phis and loop invariants
202bdd1243dSDimitry Andric //           The example looks like:
203bdd1243dSDimitry Andric //           %x = phi(0, %a) <-- becomes invariant starting from 3rd iteration.
204bdd1243dSDimitry Andric //           %y = phi(0, 5)
205bdd1243dSDimitry Andric //           %a = %y + 1
206bdd1243dSDimitry Andric //   G(%y) = Unknown otherwise (including phi not in header block)
207bdd1243dSDimitry Andric PhiAnalyzer::PeelCounter PhiAnalyzer::calculate(const Value &V) {
208e8d8bef9SDimitry Andric   // If we already know the answer, take it from the map.
209bdd1243dSDimitry Andric   auto I = IterationsToInvariance.find(&V);
210e8d8bef9SDimitry Andric   if (I != IterationsToInvariance.end())
211e8d8bef9SDimitry Andric     return I->second;
212e8d8bef9SDimitry Andric 
213bdd1243dSDimitry Andric   // Place Unknown to map to avoid infinite recursion. Such
214e8d8bef9SDimitry Andric   // cycles can never stop on an invariant.
215bdd1243dSDimitry Andric   IterationsToInvariance[&V] = Unknown;
216e8d8bef9SDimitry Andric 
217bdd1243dSDimitry Andric   if (L.isLoopInvariant(&V))
218bdd1243dSDimitry Andric     // Loop invariant so known at start.
219bdd1243dSDimitry Andric     return (IterationsToInvariance[&V] = 0);
220bdd1243dSDimitry Andric   if (const PHINode *Phi = dyn_cast<PHINode>(&V)) {
221bdd1243dSDimitry Andric     if (Phi->getParent() != L.getHeader()) {
222bdd1243dSDimitry Andric       // Phi is not in header block so Unknown.
223bdd1243dSDimitry Andric       assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved");
224bdd1243dSDimitry Andric       return Unknown;
225bdd1243dSDimitry Andric     }
226bdd1243dSDimitry Andric     // We need to analyze the input from the back edge and add 1.
227bdd1243dSDimitry Andric     Value *Input = Phi->getIncomingValueForBlock(L.getLoopLatch());
228bdd1243dSDimitry Andric     PeelCounter Iterations = calculate(*Input);
229bdd1243dSDimitry Andric     assert(IterationsToInvariance[Input] == Iterations &&
230bdd1243dSDimitry Andric            "unexpected value saved");
231bdd1243dSDimitry Andric     return (IterationsToInvariance[Phi] = addOne(Iterations));
232bdd1243dSDimitry Andric   }
233bdd1243dSDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(&V)) {
234bdd1243dSDimitry Andric     if (isa<CmpInst>(I) || I->isBinaryOp()) {
235bdd1243dSDimitry Andric       // Binary instructions get the max of the operands.
236bdd1243dSDimitry Andric       PeelCounter LHS = calculate(*I->getOperand(0));
237bdd1243dSDimitry Andric       if (LHS == Unknown)
238bdd1243dSDimitry Andric         return Unknown;
239bdd1243dSDimitry Andric       PeelCounter RHS = calculate(*I->getOperand(1));
240bdd1243dSDimitry Andric       if (RHS == Unknown)
241bdd1243dSDimitry Andric         return Unknown;
242bdd1243dSDimitry Andric       return (IterationsToInvariance[I] = {std::max(*LHS, *RHS)});
243bdd1243dSDimitry Andric     }
244bdd1243dSDimitry Andric     if (I->isCast())
245bdd1243dSDimitry Andric       // Cast instructions get the value of the operand.
246bdd1243dSDimitry Andric       return (IterationsToInvariance[I] = calculate(*I->getOperand(0)));
247bdd1243dSDimitry Andric   }
248bdd1243dSDimitry Andric   // TODO: handle more expressions
249bdd1243dSDimitry Andric 
250bdd1243dSDimitry Andric   // Everything else is Unknown.
251bdd1243dSDimitry Andric   assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved");
252bdd1243dSDimitry Andric   return Unknown;
253e8d8bef9SDimitry Andric }
254e8d8bef9SDimitry Andric 
255bdd1243dSDimitry Andric std::optional<unsigned> PhiAnalyzer::calculateIterationsToPeel() {
256bdd1243dSDimitry Andric   unsigned Iterations = 0;
257bdd1243dSDimitry Andric   for (auto &PHI : L.getHeader()->phis()) {
258bdd1243dSDimitry Andric     PeelCounter ToInvariance = calculate(PHI);
259bdd1243dSDimitry Andric     if (ToInvariance != Unknown) {
260bdd1243dSDimitry Andric       assert(*ToInvariance <= MaxIterations && "bad result in phi analysis");
261bdd1243dSDimitry Andric       Iterations = std::max(Iterations, *ToInvariance);
262bdd1243dSDimitry Andric       if (Iterations == MaxIterations)
263bdd1243dSDimitry Andric         break;
264e8d8bef9SDimitry Andric     }
265bdd1243dSDimitry Andric   }
266bdd1243dSDimitry Andric   assert((Iterations <= MaxIterations) && "bad result in phi analysis");
267bdd1243dSDimitry Andric   return Iterations ? std::optional<unsigned>(Iterations) : std::nullopt;
268bdd1243dSDimitry Andric }
269bdd1243dSDimitry Andric 
270bdd1243dSDimitry 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,
277bdd1243dSDimitry Andric                                                       DominatorTree &DT,
278bdd1243dSDimitry 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) &&
319bdd1243dSDimitry 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 
348*06c3fb27SDimitry Andric   // Do not peel the entire loop.
349*06c3fb27SDimitry Andric   const SCEV *BE = SE.getConstantMaxBackedgeTakenCount(&L);
350*06c3fb27SDimitry Andric   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(BE))
351*06c3fb27SDimitry Andric     MaxPeelCount =
352*06c3fb27SDimitry Andric         std::min((unsigned)SC->getAPInt().getLimitedValue() - 1, MaxPeelCount);
353e8d8bef9SDimitry Andric 
354*06c3fb27SDimitry Andric   auto ComputePeelCount = [&](Value *Condition) -> void {
355*06c3fb27SDimitry Andric     if (!Condition->getType()->isIntegerTy())
356*06c3fb27SDimitry Andric       return;
357e8d8bef9SDimitry Andric 
358e8d8bef9SDimitry Andric     Value *LeftVal, *RightVal;
359e8d8bef9SDimitry Andric     CmpInst::Predicate Pred;
360e8d8bef9SDimitry Andric     if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal))))
361*06c3fb27SDimitry Andric       return;
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))
369*06c3fb27SDimitry Andric       return;
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
378*06c3fb27SDimitry Andric         return;
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)
386*06c3fb27SDimitry Andric       return;
387e8d8bef9SDimitry Andric     if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) &&
388e8d8bef9SDimitry Andric         !SE.getMonotonicPredicateType(LeftAR, Pred))
389*06c3fb27SDimitry Andric       return;
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))
425*06c3fb27SDimitry Andric       return; // 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())
436*06c3fb27SDimitry Andric         return; // 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);
441*06c3fb27SDimitry Andric   };
442*06c3fb27SDimitry Andric 
443*06c3fb27SDimitry Andric   for (BasicBlock *BB : L.blocks()) {
444*06c3fb27SDimitry Andric     for (Instruction &I : *BB) {
445*06c3fb27SDimitry Andric       if (SelectInst *SI = dyn_cast<SelectInst>(&I))
446*06c3fb27SDimitry Andric         ComputePeelCount(SI->getCondition());
447*06c3fb27SDimitry Andric     }
448*06c3fb27SDimitry Andric 
449*06c3fb27SDimitry Andric     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
450*06c3fb27SDimitry Andric     if (!BI || BI->isUnconditional())
451*06c3fb27SDimitry Andric       continue;
452*06c3fb27SDimitry Andric 
453*06c3fb27SDimitry Andric     // Ignore loop exit condition.
454*06c3fb27SDimitry Andric     if (L.getLoopLatch() == BB)
455*06c3fb27SDimitry Andric       continue;
456*06c3fb27SDimitry Andric 
457*06c3fb27SDimitry Andric     ComputePeelCount(BI->getCondition());
458e8d8bef9SDimitry Andric   }
459e8d8bef9SDimitry Andric 
460e8d8bef9SDimitry Andric   return DesiredPeelCount;
461e8d8bef9SDimitry Andric }
462e8d8bef9SDimitry Andric 
4630eae32dcSDimitry Andric /// This "heuristic" exactly matches implicit behavior which used to exist
4640eae32dcSDimitry Andric /// inside getLoopEstimatedTripCount.  It was added here to keep an
465bdd1243dSDimitry Andric /// improvement inside that API from causing peeling to become more aggressive.
4660eae32dcSDimitry Andric /// This should probably be removed.
4670eae32dcSDimitry Andric static bool violatesLegacyMultiExitLoopCheck(Loop *L) {
4680eae32dcSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
4690eae32dcSDimitry Andric   if (!Latch)
4700eae32dcSDimitry Andric     return true;
4710eae32dcSDimitry Andric 
4720eae32dcSDimitry Andric   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
4730eae32dcSDimitry Andric   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
4740eae32dcSDimitry Andric     return true;
4750eae32dcSDimitry Andric 
4760eae32dcSDimitry Andric   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
4770eae32dcSDimitry Andric           LatchBR->getSuccessor(1) == L->getHeader()) &&
4780eae32dcSDimitry Andric          "At least one edge out of the latch must go to the header");
4790eae32dcSDimitry Andric 
4800eae32dcSDimitry Andric   SmallVector<BasicBlock *, 4> ExitBlocks;
4810eae32dcSDimitry Andric   L->getUniqueNonLatchExitBlocks(ExitBlocks);
4820eae32dcSDimitry Andric   return any_of(ExitBlocks, [](const BasicBlock *EB) {
4830eae32dcSDimitry Andric       return !EB->getTerminatingDeoptimizeCall();
4840eae32dcSDimitry Andric     });
4850eae32dcSDimitry Andric }
4860eae32dcSDimitry Andric 
4870eae32dcSDimitry Andric 
488e8d8bef9SDimitry Andric // Return the number of iterations we want to peel off.
489e8d8bef9SDimitry Andric void llvm::computePeelCount(Loop *L, unsigned LoopSize,
490e8d8bef9SDimitry Andric                             TargetTransformInfo::PeelingPreferences &PP,
49104eeddc0SDimitry Andric                             unsigned TripCount, DominatorTree &DT,
492bdd1243dSDimitry Andric                             ScalarEvolution &SE, AssumptionCache *AC,
493bdd1243dSDimitry Andric                             unsigned Threshold) {
494e8d8bef9SDimitry Andric   assert(LoopSize > 0 && "Zero loop size is not allowed!");
495e8d8bef9SDimitry Andric   // Save the PP.PeelCount value set by the target in
496e8d8bef9SDimitry Andric   // TTI.getPeelingPreferences or by the flag -unroll-peel-count.
497e8d8bef9SDimitry Andric   unsigned TargetPeelCount = PP.PeelCount;
498e8d8bef9SDimitry Andric   PP.PeelCount = 0;
499e8d8bef9SDimitry Andric   if (!canPeel(L))
500e8d8bef9SDimitry Andric     return;
501e8d8bef9SDimitry Andric 
502e8d8bef9SDimitry Andric   // Only try to peel innermost loops by default.
50304eeddc0SDimitry Andric   // The constraint can be relaxed by the target in TTI.getPeelingPreferences
504e8d8bef9SDimitry Andric   // or by the flag -unroll-allow-loop-nests-peeling.
505e8d8bef9SDimitry Andric   if (!PP.AllowLoopNestsPeeling && !L->isInnermost())
506e8d8bef9SDimitry Andric     return;
507e8d8bef9SDimitry Andric 
508e8d8bef9SDimitry Andric   // If the user provided a peel count, use that.
509e8d8bef9SDimitry Andric   bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
510e8d8bef9SDimitry Andric   if (UserPeelCount) {
511e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
512e8d8bef9SDimitry Andric                       << " iterations.\n");
513e8d8bef9SDimitry Andric     PP.PeelCount = UnrollForcePeelCount;
514e8d8bef9SDimitry Andric     PP.PeelProfiledIterations = true;
515e8d8bef9SDimitry Andric     return;
516e8d8bef9SDimitry Andric   }
517e8d8bef9SDimitry Andric 
518e8d8bef9SDimitry Andric   // Skip peeling if it's disabled.
519e8d8bef9SDimitry Andric   if (!PP.AllowPeeling)
520e8d8bef9SDimitry Andric     return;
521e8d8bef9SDimitry Andric 
52281ad6265SDimitry Andric   // Check that we can peel at least one iteration.
52381ad6265SDimitry Andric   if (2 * LoopSize > Threshold)
52481ad6265SDimitry Andric     return;
52581ad6265SDimitry Andric 
526e8d8bef9SDimitry Andric   unsigned AlreadyPeeled = 0;
527e8d8bef9SDimitry Andric   if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData))
528e8d8bef9SDimitry Andric     AlreadyPeeled = *Peeled;
529e8d8bef9SDimitry Andric   // Stop if we already peeled off the maximum number of iterations.
530e8d8bef9SDimitry Andric   if (AlreadyPeeled >= UnrollPeelMaxCount)
531e8d8bef9SDimitry Andric     return;
532e8d8bef9SDimitry Andric 
533bdd1243dSDimitry Andric   // Pay respect to limitations implied by loop size and the max peel count.
534bdd1243dSDimitry Andric   unsigned MaxPeelCount = UnrollPeelMaxCount;
535bdd1243dSDimitry Andric   MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1);
536bdd1243dSDimitry Andric 
537bdd1243dSDimitry Andric   // Start the max computation with the PP.PeelCount value set by the target
538bdd1243dSDimitry Andric   // in TTI.getPeelingPreferences or by the flag -unroll-peel-count.
539bdd1243dSDimitry Andric   unsigned DesiredPeelCount = TargetPeelCount;
540bdd1243dSDimitry Andric 
541e8d8bef9SDimitry Andric   // Here we try to get rid of Phis which become invariants after 1, 2, ..., N
542e8d8bef9SDimitry Andric   // iterations of the loop. For this we compute the number for iterations after
543e8d8bef9SDimitry Andric   // which every Phi is guaranteed to become an invariant, and try to peel the
544e8d8bef9SDimitry Andric   // maximum number of iterations among these values, thus turning all those
545e8d8bef9SDimitry Andric   // Phis into invariants.
546bdd1243dSDimitry Andric   if (MaxPeelCount > DesiredPeelCount) {
547bdd1243dSDimitry Andric     // Check how many iterations are useful for resolving Phis
548bdd1243dSDimitry Andric     auto NumPeels = PhiAnalyzer(*L, MaxPeelCount).calculateIterationsToPeel();
549bdd1243dSDimitry Andric     if (NumPeels)
550bdd1243dSDimitry Andric       DesiredPeelCount = std::max(DesiredPeelCount, *NumPeels);
551e8d8bef9SDimitry Andric   }
552e8d8bef9SDimitry Andric 
553e8d8bef9SDimitry Andric   DesiredPeelCount = std::max(DesiredPeelCount,
554e8d8bef9SDimitry Andric                               countToEliminateCompares(*L, MaxPeelCount, SE));
555e8d8bef9SDimitry Andric 
556349cc55cSDimitry Andric   if (DesiredPeelCount == 0)
557bdd1243dSDimitry Andric     DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT, AC);
558349cc55cSDimitry Andric 
559e8d8bef9SDimitry Andric   if (DesiredPeelCount > 0) {
560e8d8bef9SDimitry Andric     DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount);
561e8d8bef9SDimitry Andric     // Consider max peel count limitation.
562e8d8bef9SDimitry Andric     assert(DesiredPeelCount > 0 && "Wrong loop size estimation?");
563e8d8bef9SDimitry Andric     if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) {
564e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount
565e8d8bef9SDimitry Andric                         << " iteration(s) to turn"
566e8d8bef9SDimitry Andric                         << " some Phis into invariants.\n");
567e8d8bef9SDimitry Andric       PP.PeelCount = DesiredPeelCount;
568e8d8bef9SDimitry Andric       PP.PeelProfiledIterations = false;
569e8d8bef9SDimitry Andric       return;
570e8d8bef9SDimitry Andric     }
571e8d8bef9SDimitry Andric   }
572e8d8bef9SDimitry Andric 
573e8d8bef9SDimitry Andric   // Bail if we know the statically calculated trip count.
574e8d8bef9SDimitry Andric   // In this case we rather prefer partial unrolling.
575e8d8bef9SDimitry Andric   if (TripCount)
576e8d8bef9SDimitry Andric     return;
577e8d8bef9SDimitry Andric 
578e8d8bef9SDimitry Andric   // Do not apply profile base peeling if it is disabled.
579e8d8bef9SDimitry Andric   if (!PP.PeelProfiledIterations)
580e8d8bef9SDimitry Andric     return;
581e8d8bef9SDimitry Andric   // If we don't know the trip count, but have reason to believe the average
582e8d8bef9SDimitry Andric   // trip count is low, peeling should be beneficial, since we will usually
583e8d8bef9SDimitry Andric   // hit the peeled section.
584e8d8bef9SDimitry Andric   // We only do this in the presence of profile information, since otherwise
585e8d8bef9SDimitry Andric   // our estimates of the trip count are not reliable enough.
586e8d8bef9SDimitry Andric   if (L->getHeader()->getParent()->hasProfileData()) {
5870eae32dcSDimitry Andric     if (violatesLegacyMultiExitLoopCheck(L))
5880eae32dcSDimitry Andric       return;
589bdd1243dSDimitry Andric     std::optional<unsigned> EstimatedTripCount = getLoopEstimatedTripCount(L);
59081ad6265SDimitry Andric     if (!EstimatedTripCount)
591e8d8bef9SDimitry Andric       return;
592e8d8bef9SDimitry Andric 
59381ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is "
59481ad6265SDimitry Andric                       << *EstimatedTripCount << "\n");
595e8d8bef9SDimitry Andric 
59681ad6265SDimitry Andric     if (*EstimatedTripCount) {
59781ad6265SDimitry Andric       if (*EstimatedTripCount + AlreadyPeeled <= MaxPeelCount) {
59881ad6265SDimitry Andric         unsigned PeelCount = *EstimatedTripCount;
59981ad6265SDimitry Andric         LLVM_DEBUG(dbgs() << "Peeling first " << PeelCount << " iterations.\n");
60081ad6265SDimitry Andric         PP.PeelCount = PeelCount;
601e8d8bef9SDimitry Andric         return;
602e8d8bef9SDimitry Andric       }
603e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n");
604e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
60581ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "Loop cost: " << LoopSize << "\n");
606e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n");
60781ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "Max peel count by cost: "
60881ad6265SDimitry Andric                         << (Threshold / LoopSize - 1) << "\n");
609e8d8bef9SDimitry Andric     }
610e8d8bef9SDimitry Andric   }
611e8d8bef9SDimitry Andric }
612e8d8bef9SDimitry Andric 
613bdd1243dSDimitry Andric struct WeightInfo {
614bdd1243dSDimitry Andric   // Weights for current iteration.
615bdd1243dSDimitry Andric   SmallVector<uint32_t> Weights;
616bdd1243dSDimitry Andric   // Weights to subtract after each iteration.
617bdd1243dSDimitry Andric   const SmallVector<uint32_t> SubWeights;
618bdd1243dSDimitry Andric };
619bdd1243dSDimitry Andric 
620bdd1243dSDimitry Andric /// Update the branch weights of an exiting block of a peeled-off loop
621e8d8bef9SDimitry Andric /// iteration.
622bdd1243dSDimitry Andric /// Let F is a weight of the edge to continue (fallthrough) into the loop.
623bdd1243dSDimitry Andric /// Let E is a weight of the edge to an exit.
624e8d8bef9SDimitry Andric /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to
625e8d8bef9SDimitry Andric /// go to exit.
626bdd1243dSDimitry Andric /// Then, Estimated ExitCount = F / E.
627e8d8bef9SDimitry Andric /// For I-th (counting from 0) peeled off iteration we set the the weights for
628bdd1243dSDimitry Andric /// the peeled exit as (EC - I, 1). It gives us reasonable distribution,
629bdd1243dSDimitry Andric /// The probability to go to exit 1/(EC-I) increases. At the same time
630bdd1243dSDimitry Andric /// the estimated exit count in the remainder loop reduces by I.
631e8d8bef9SDimitry Andric /// To avoid dealing with division rounding we can just multiple both part
632e8d8bef9SDimitry Andric /// of weights to E and use weight as (F - I * E, E).
633bdd1243dSDimitry Andric static void updateBranchWeights(Instruction *Term, WeightInfo &Info) {
634bdd1243dSDimitry Andric   MDBuilder MDB(Term->getContext());
635bdd1243dSDimitry Andric   Term->setMetadata(LLVMContext::MD_prof,
636bdd1243dSDimitry Andric                     MDB.createBranchWeights(Info.Weights));
637bdd1243dSDimitry Andric   for (auto [Idx, SubWeight] : enumerate(Info.SubWeights))
638bdd1243dSDimitry Andric     if (SubWeight != 0)
639bdd1243dSDimitry Andric       Info.Weights[Idx] = Info.Weights[Idx] > SubWeight
640bdd1243dSDimitry Andric                               ? Info.Weights[Idx] - SubWeight
641bdd1243dSDimitry Andric                               : 1;
642e8d8bef9SDimitry Andric }
643e8d8bef9SDimitry Andric 
644bdd1243dSDimitry Andric /// Initialize the weights for all exiting blocks.
645bdd1243dSDimitry Andric static void initBranchWeights(DenseMap<Instruction *, WeightInfo> &WeightInfos,
646bdd1243dSDimitry Andric                               Loop *L) {
647bdd1243dSDimitry Andric   SmallVector<BasicBlock *> ExitingBlocks;
648bdd1243dSDimitry Andric   L->getExitingBlocks(ExitingBlocks);
649bdd1243dSDimitry Andric   for (BasicBlock *ExitingBlock : ExitingBlocks) {
650bdd1243dSDimitry Andric     Instruction *Term = ExitingBlock->getTerminator();
651bdd1243dSDimitry Andric     SmallVector<uint32_t> Weights;
652bdd1243dSDimitry Andric     if (!extractBranchWeights(*Term, Weights))
653bdd1243dSDimitry Andric       continue;
654bdd1243dSDimitry Andric 
655bdd1243dSDimitry Andric     // See the comment on updateBranchWeights() for an explanation of what we
656bdd1243dSDimitry Andric     // do here.
657bdd1243dSDimitry Andric     uint32_t FallThroughWeights = 0;
658bdd1243dSDimitry Andric     uint32_t ExitWeights = 0;
659bdd1243dSDimitry Andric     for (auto [Succ, Weight] : zip(successors(Term), Weights)) {
660bdd1243dSDimitry Andric       if (L->contains(Succ))
661bdd1243dSDimitry Andric         FallThroughWeights += Weight;
662bdd1243dSDimitry Andric       else
663bdd1243dSDimitry Andric         ExitWeights += Weight;
664e8d8bef9SDimitry Andric     }
665e8d8bef9SDimitry Andric 
666bdd1243dSDimitry Andric     // Don't try to update weights for degenerate case.
667bdd1243dSDimitry Andric     if (FallThroughWeights == 0)
668bdd1243dSDimitry Andric       continue;
669e8d8bef9SDimitry Andric 
670bdd1243dSDimitry Andric     SmallVector<uint32_t> SubWeights;
671bdd1243dSDimitry Andric     for (auto [Succ, Weight] : zip(successors(Term), Weights)) {
672bdd1243dSDimitry Andric       if (!L->contains(Succ)) {
673bdd1243dSDimitry Andric         // Exit weights stay the same.
674bdd1243dSDimitry Andric         SubWeights.push_back(0);
675bdd1243dSDimitry Andric         continue;
676bdd1243dSDimitry Andric       }
677bdd1243dSDimitry Andric 
678bdd1243dSDimitry Andric       // Subtract exit weights on each iteration, distributed across all
679bdd1243dSDimitry Andric       // fallthrough edges.
680bdd1243dSDimitry Andric       double W = (double)Weight / (double)FallThroughWeights;
681bdd1243dSDimitry Andric       SubWeights.push_back((uint32_t)(ExitWeights * W));
682bdd1243dSDimitry Andric     }
683bdd1243dSDimitry Andric 
684bdd1243dSDimitry Andric     WeightInfos.insert({Term, {std::move(Weights), std::move(SubWeights)}});
685bdd1243dSDimitry Andric   }
686bdd1243dSDimitry Andric }
687bdd1243dSDimitry Andric 
688bdd1243dSDimitry Andric /// Update the weights of original exiting block after peeling off all
689bdd1243dSDimitry Andric /// iterations.
690bdd1243dSDimitry Andric static void fixupBranchWeights(Instruction *Term, const WeightInfo &Info) {
691bdd1243dSDimitry Andric   MDBuilder MDB(Term->getContext());
692bdd1243dSDimitry Andric   Term->setMetadata(LLVMContext::MD_prof,
693bdd1243dSDimitry Andric                     MDB.createBranchWeights(Info.Weights));
694e8d8bef9SDimitry Andric }
695e8d8bef9SDimitry Andric 
696e8d8bef9SDimitry Andric /// Clones the body of the loop L, putting it between \p InsertTop and \p
697e8d8bef9SDimitry Andric /// InsertBot.
698e8d8bef9SDimitry Andric /// \param IterNumber The serial number of the iteration currently being
699e8d8bef9SDimitry Andric /// peeled off.
700e8d8bef9SDimitry Andric /// \param ExitEdges The exit edges of the original loop.
701e8d8bef9SDimitry Andric /// \param[out] NewBlocks A list of the blocks in the newly created clone
702e8d8bef9SDimitry Andric /// \param[out] VMap The value map between the loop and the new clone.
703e8d8bef9SDimitry Andric /// \param LoopBlocks A helper for DFS-traversal of the loop.
704e8d8bef9SDimitry Andric /// \param LVMap A value-map that maps instructions from the original loop to
705e8d8bef9SDimitry Andric /// instructions in the last peeled-off iteration.
706e8d8bef9SDimitry Andric static void cloneLoopBlocks(
707e8d8bef9SDimitry Andric     Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot,
708e8d8bef9SDimitry Andric     SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges,
709e8d8bef9SDimitry Andric     SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
710e8d8bef9SDimitry Andric     ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT,
71181ad6265SDimitry Andric     LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes,
71281ad6265SDimitry Andric     ScalarEvolution &SE) {
713e8d8bef9SDimitry Andric   BasicBlock *Header = L->getHeader();
714e8d8bef9SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
715e8d8bef9SDimitry Andric   BasicBlock *PreHeader = L->getLoopPreheader();
716e8d8bef9SDimitry Andric 
717e8d8bef9SDimitry Andric   Function *F = Header->getParent();
718e8d8bef9SDimitry Andric   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
719e8d8bef9SDimitry Andric   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
720e8d8bef9SDimitry Andric   Loop *ParentLoop = L->getParentLoop();
721e8d8bef9SDimitry Andric 
722e8d8bef9SDimitry Andric   // For each block in the original loop, create a new copy,
723e8d8bef9SDimitry Andric   // and update the value map with the newly created values.
724e8d8bef9SDimitry Andric   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
725e8d8bef9SDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
726e8d8bef9SDimitry Andric     NewBlocks.push_back(NewBB);
727e8d8bef9SDimitry Andric 
728e8d8bef9SDimitry Andric     // If an original block is an immediate child of the loop L, its copy
729e8d8bef9SDimitry Andric     // is a child of a ParentLoop after peeling. If a block is a child of
730e8d8bef9SDimitry Andric     // a nested loop, it is handled in the cloneLoop() call below.
731e8d8bef9SDimitry Andric     if (ParentLoop && LI->getLoopFor(*BB) == L)
732e8d8bef9SDimitry Andric       ParentLoop->addBasicBlockToLoop(NewBB, *LI);
733e8d8bef9SDimitry Andric 
734e8d8bef9SDimitry Andric     VMap[*BB] = NewBB;
735e8d8bef9SDimitry Andric 
736e8d8bef9SDimitry Andric     // If dominator tree is available, insert nodes to represent cloned blocks.
737e8d8bef9SDimitry Andric     if (DT) {
738e8d8bef9SDimitry Andric       if (Header == *BB)
739e8d8bef9SDimitry Andric         DT->addNewBlock(NewBB, InsertTop);
740e8d8bef9SDimitry Andric       else {
741e8d8bef9SDimitry Andric         DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
742e8d8bef9SDimitry Andric         // VMap must contain entry for IDom, as the iteration order is RPO.
743e8d8bef9SDimitry Andric         DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
744e8d8bef9SDimitry Andric       }
745e8d8bef9SDimitry Andric     }
746e8d8bef9SDimitry Andric   }
747e8d8bef9SDimitry Andric 
748d409305fSDimitry Andric   {
749d409305fSDimitry Andric     // Identify what other metadata depends on the cloned version. After
750d409305fSDimitry Andric     // cloning, replace the metadata with the corrected version for both
751d409305fSDimitry Andric     // memory instructions and noalias intrinsics.
752d409305fSDimitry Andric     std::string Ext = (Twine("Peel") + Twine(IterNumber)).str();
753d409305fSDimitry Andric     cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
754d409305fSDimitry Andric                                Header->getContext(), Ext);
755d409305fSDimitry Andric   }
756d409305fSDimitry Andric 
757e8d8bef9SDimitry Andric   // Recursively create the new Loop objects for nested loops, if any,
758e8d8bef9SDimitry Andric   // to preserve LoopInfo.
759e8d8bef9SDimitry Andric   for (Loop *ChildLoop : *L) {
760e8d8bef9SDimitry Andric     cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr);
761e8d8bef9SDimitry Andric   }
762e8d8bef9SDimitry Andric 
763e8d8bef9SDimitry Andric   // Hook-up the control flow for the newly inserted blocks.
764e8d8bef9SDimitry Andric   // The new header is hooked up directly to the "top", which is either
765e8d8bef9SDimitry Andric   // the original loop preheader (for the first iteration) or the previous
766e8d8bef9SDimitry Andric   // iteration's exiting block (for every other iteration)
767e8d8bef9SDimitry Andric   InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
768e8d8bef9SDimitry Andric 
769e8d8bef9SDimitry Andric   // Similarly, for the latch:
770e8d8bef9SDimitry Andric   // The original exiting edge is still hooked up to the loop exit.
771e8d8bef9SDimitry Andric   // The backedge now goes to the "bottom", which is either the loop's real
772e8d8bef9SDimitry Andric   // header (for the last peeled iteration) or the copied header of the next
773e8d8bef9SDimitry Andric   // iteration (for every other iteration)
774e8d8bef9SDimitry Andric   BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
775bdd1243dSDimitry Andric   auto *LatchTerm = cast<Instruction>(NewLatch->getTerminator());
776bdd1243dSDimitry Andric   for (unsigned idx = 0, e = LatchTerm->getNumSuccessors(); idx < e; ++idx)
777bdd1243dSDimitry Andric     if (LatchTerm->getSuccessor(idx) == Header) {
778bdd1243dSDimitry Andric       LatchTerm->setSuccessor(idx, InsertBot);
779e8d8bef9SDimitry Andric       break;
780e8d8bef9SDimitry Andric     }
781e8d8bef9SDimitry Andric   if (DT)
782e8d8bef9SDimitry Andric     DT->changeImmediateDominator(InsertBot, NewLatch);
783e8d8bef9SDimitry Andric 
784e8d8bef9SDimitry Andric   // The new copy of the loop body starts with a bunch of PHI nodes
785e8d8bef9SDimitry Andric   // that pick an incoming value from either the preheader, or the previous
786e8d8bef9SDimitry Andric   // loop iteration. Since this copy is no longer part of the loop, we
787e8d8bef9SDimitry Andric   // resolve this statically:
788e8d8bef9SDimitry Andric   // For the first iteration, we use the value from the preheader directly.
789e8d8bef9SDimitry Andric   // For any other iteration, we replace the phi with the value generated by
790e8d8bef9SDimitry Andric   // the immediately preceding clone of the loop body (which represents
791e8d8bef9SDimitry Andric   // the previous iteration).
792e8d8bef9SDimitry Andric   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
793e8d8bef9SDimitry Andric     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
794e8d8bef9SDimitry Andric     if (IterNumber == 0) {
795e8d8bef9SDimitry Andric       VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
796e8d8bef9SDimitry Andric     } else {
797e8d8bef9SDimitry Andric       Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
798e8d8bef9SDimitry Andric       Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
799e8d8bef9SDimitry Andric       if (LatchInst && L->contains(LatchInst))
800e8d8bef9SDimitry Andric         VMap[&*I] = LVMap[LatchInst];
801e8d8bef9SDimitry Andric       else
802e8d8bef9SDimitry Andric         VMap[&*I] = LatchVal;
803e8d8bef9SDimitry Andric     }
804bdd1243dSDimitry Andric     NewPHI->eraseFromParent();
805e8d8bef9SDimitry Andric   }
806e8d8bef9SDimitry Andric 
807e8d8bef9SDimitry Andric   // Fix up the outgoing values - we need to add a value for the iteration
808e8d8bef9SDimitry Andric   // we've just created. Note that this must happen *after* the incoming
809e8d8bef9SDimitry Andric   // values are adjusted, since the value going out of the latch may also be
810e8d8bef9SDimitry Andric   // a value coming into the header.
811e8d8bef9SDimitry Andric   for (auto Edge : ExitEdges)
812e8d8bef9SDimitry Andric     for (PHINode &PHI : Edge.second->phis()) {
813e8d8bef9SDimitry Andric       Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first);
814e8d8bef9SDimitry Andric       Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
815e8d8bef9SDimitry Andric       if (LatchInst && L->contains(LatchInst))
816e8d8bef9SDimitry Andric         LatchVal = VMap[LatchVal];
817e8d8bef9SDimitry Andric       PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first]));
81881ad6265SDimitry Andric       SE.forgetValue(&PHI);
819e8d8bef9SDimitry Andric     }
820e8d8bef9SDimitry Andric 
821e8d8bef9SDimitry Andric   // LastValueMap is updated with the values for the current loop
822e8d8bef9SDimitry Andric   // which are used the next time this function is called.
823e8d8bef9SDimitry Andric   for (auto KV : VMap)
824e8d8bef9SDimitry Andric     LVMap[KV.first] = KV.second;
825e8d8bef9SDimitry Andric }
826e8d8bef9SDimitry Andric 
827bdd1243dSDimitry Andric TargetTransformInfo::PeelingPreferences
828bdd1243dSDimitry Andric llvm::gatherPeelingPreferences(Loop *L, ScalarEvolution &SE,
829bdd1243dSDimitry Andric                                const TargetTransformInfo &TTI,
830bdd1243dSDimitry Andric                                std::optional<bool> UserAllowPeeling,
831bdd1243dSDimitry Andric                                std::optional<bool> UserAllowProfileBasedPeeling,
832bdd1243dSDimitry Andric                                bool UnrollingSpecficValues) {
833e8d8bef9SDimitry Andric   TargetTransformInfo::PeelingPreferences PP;
834e8d8bef9SDimitry Andric 
835e8d8bef9SDimitry Andric   // Set the default values.
836e8d8bef9SDimitry Andric   PP.PeelCount = 0;
837e8d8bef9SDimitry Andric   PP.AllowPeeling = true;
838e8d8bef9SDimitry Andric   PP.AllowLoopNestsPeeling = false;
839e8d8bef9SDimitry Andric   PP.PeelProfiledIterations = true;
840e8d8bef9SDimitry Andric 
841e8d8bef9SDimitry Andric   // Get the target specifc values.
842e8d8bef9SDimitry Andric   TTI.getPeelingPreferences(L, SE, PP);
843e8d8bef9SDimitry Andric 
844e8d8bef9SDimitry Andric   // User specified values using cl::opt.
845e8d8bef9SDimitry Andric   if (UnrollingSpecficValues) {
846e8d8bef9SDimitry Andric     if (UnrollPeelCount.getNumOccurrences() > 0)
847e8d8bef9SDimitry Andric       PP.PeelCount = UnrollPeelCount;
848e8d8bef9SDimitry Andric     if (UnrollAllowPeeling.getNumOccurrences() > 0)
849e8d8bef9SDimitry Andric       PP.AllowPeeling = UnrollAllowPeeling;
850e8d8bef9SDimitry Andric     if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0)
851e8d8bef9SDimitry Andric       PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling;
852e8d8bef9SDimitry Andric   }
853e8d8bef9SDimitry Andric 
854e8d8bef9SDimitry Andric   // User specifed values provided by argument.
85581ad6265SDimitry Andric   if (UserAllowPeeling)
856e8d8bef9SDimitry Andric     PP.AllowPeeling = *UserAllowPeeling;
85781ad6265SDimitry Andric   if (UserAllowProfileBasedPeeling)
858e8d8bef9SDimitry Andric     PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling;
859e8d8bef9SDimitry Andric 
860e8d8bef9SDimitry Andric   return PP;
861e8d8bef9SDimitry Andric }
862e8d8bef9SDimitry Andric 
863e8d8bef9SDimitry Andric /// Peel off the first \p PeelCount iterations of loop \p L.
864e8d8bef9SDimitry Andric ///
865e8d8bef9SDimitry Andric /// Note that this does not peel them off as a single straight-line block.
866e8d8bef9SDimitry Andric /// Rather, each iteration is peeled off separately, and needs to check the
867e8d8bef9SDimitry Andric /// exit condition.
868e8d8bef9SDimitry Andric /// For loops that dynamically execute \p PeelCount iterations or less
869e8d8bef9SDimitry Andric /// this provides a benefit, since the peeled off iterations, which account
870e8d8bef9SDimitry Andric /// for the bulk of dynamic execution, can be further simplified by scalar
871e8d8bef9SDimitry Andric /// optimizations.
872e8d8bef9SDimitry Andric bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
8731fd87a68SDimitry Andric                     ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC,
874bdd1243dSDimitry Andric                     bool PreserveLCSSA, ValueToValueMapTy &LVMap) {
875e8d8bef9SDimitry Andric   assert(PeelCount > 0 && "Attempt to peel out zero iterations?");
876e8d8bef9SDimitry Andric   assert(canPeel(L) && "Attempt to peel a loop which is not peelable?");
877e8d8bef9SDimitry Andric 
878e8d8bef9SDimitry Andric   LoopBlocksDFS LoopBlocks(L);
879e8d8bef9SDimitry Andric   LoopBlocks.perform(LI);
880e8d8bef9SDimitry Andric 
881e8d8bef9SDimitry Andric   BasicBlock *Header = L->getHeader();
882e8d8bef9SDimitry Andric   BasicBlock *PreHeader = L->getLoopPreheader();
883e8d8bef9SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
884e8d8bef9SDimitry Andric   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges;
885e8d8bef9SDimitry Andric   L->getExitEdges(ExitEdges);
886e8d8bef9SDimitry Andric 
887349cc55cSDimitry Andric   // Remember dominators of blocks we might reach through exits to change them
888349cc55cSDimitry Andric   // later. Immediate dominator of such block might change, because we add more
889349cc55cSDimitry Andric   // routes which can lead to the exit: we can reach it from the peeled
890349cc55cSDimitry Andric   // iterations too.
891349cc55cSDimitry Andric   DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom;
892349cc55cSDimitry Andric   for (auto *BB : L->blocks()) {
8931fd87a68SDimitry Andric     auto *BBDomNode = DT.getNode(BB);
894349cc55cSDimitry Andric     SmallVector<BasicBlock *, 16> ChildrenToUpdate;
895349cc55cSDimitry Andric     for (auto *ChildDomNode : BBDomNode->children()) {
896349cc55cSDimitry Andric       auto *ChildBB = ChildDomNode->getBlock();
897349cc55cSDimitry Andric       if (!L->contains(ChildBB))
898349cc55cSDimitry Andric         ChildrenToUpdate.push_back(ChildBB);
899349cc55cSDimitry Andric     }
900349cc55cSDimitry Andric     // The new idom of the block will be the nearest common dominator
901349cc55cSDimitry Andric     // of all copies of the previous idom. This is equivalent to the
902349cc55cSDimitry Andric     // nearest common dominator of the previous idom and the first latch,
903349cc55cSDimitry Andric     // which dominates all copies of the previous idom.
9041fd87a68SDimitry Andric     BasicBlock *NewIDom = DT.findNearestCommonDominator(BB, Latch);
905349cc55cSDimitry Andric     for (auto *ChildBB : ChildrenToUpdate)
906349cc55cSDimitry Andric       NonLoopBlocksIDom[ChildBB] = NewIDom;
907e8d8bef9SDimitry Andric   }
908e8d8bef9SDimitry Andric 
909e8d8bef9SDimitry Andric   Function *F = Header->getParent();
910e8d8bef9SDimitry Andric 
911e8d8bef9SDimitry Andric   // Set up all the necessary basic blocks. It is convenient to split the
912e8d8bef9SDimitry Andric   // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
913e8d8bef9SDimitry Andric   // body, and a new preheader for the "real" loop.
914e8d8bef9SDimitry Andric 
915e8d8bef9SDimitry Andric   // Peeling the first iteration transforms.
916e8d8bef9SDimitry Andric   //
917e8d8bef9SDimitry Andric   // PreHeader:
918e8d8bef9SDimitry Andric   // ...
919e8d8bef9SDimitry Andric   // Header:
920e8d8bef9SDimitry Andric   //   LoopBody
921e8d8bef9SDimitry Andric   //   If (cond) goto Header
922e8d8bef9SDimitry Andric   // Exit:
923e8d8bef9SDimitry Andric   //
924e8d8bef9SDimitry Andric   // into
925e8d8bef9SDimitry Andric   //
926e8d8bef9SDimitry Andric   // InsertTop:
927e8d8bef9SDimitry Andric   //   LoopBody
928e8d8bef9SDimitry Andric   //   If (!cond) goto Exit
929e8d8bef9SDimitry Andric   // InsertBot:
930e8d8bef9SDimitry Andric   // NewPreHeader:
931e8d8bef9SDimitry Andric   // ...
932e8d8bef9SDimitry Andric   // Header:
933e8d8bef9SDimitry Andric   //  LoopBody
934e8d8bef9SDimitry Andric   //  If (cond) goto Header
935e8d8bef9SDimitry Andric   // Exit:
936e8d8bef9SDimitry Andric   //
937e8d8bef9SDimitry Andric   // Each following iteration will split the current bottom anchor in two,
938e8d8bef9SDimitry Andric   // and put the new copy of the loop body between these two blocks. That is,
939e8d8bef9SDimitry Andric   // after peeling another iteration from the example above, we'll split
940e8d8bef9SDimitry Andric   // InsertBot, and get:
941e8d8bef9SDimitry Andric   //
942e8d8bef9SDimitry Andric   // InsertTop:
943e8d8bef9SDimitry Andric   //   LoopBody
944e8d8bef9SDimitry Andric   //   If (!cond) goto Exit
945e8d8bef9SDimitry Andric   // InsertBot:
946e8d8bef9SDimitry Andric   //   LoopBody
947e8d8bef9SDimitry Andric   //   If (!cond) goto Exit
948e8d8bef9SDimitry Andric   // InsertBot.next:
949e8d8bef9SDimitry Andric   // NewPreHeader:
950e8d8bef9SDimitry Andric   // ...
951e8d8bef9SDimitry Andric   // Header:
952e8d8bef9SDimitry Andric   //  LoopBody
953e8d8bef9SDimitry Andric   //  If (cond) goto Header
954e8d8bef9SDimitry Andric   // Exit:
955e8d8bef9SDimitry Andric 
9561fd87a68SDimitry Andric   BasicBlock *InsertTop = SplitEdge(PreHeader, Header, &DT, LI);
957e8d8bef9SDimitry Andric   BasicBlock *InsertBot =
9581fd87a68SDimitry Andric       SplitBlock(InsertTop, InsertTop->getTerminator(), &DT, LI);
959e8d8bef9SDimitry Andric   BasicBlock *NewPreHeader =
9601fd87a68SDimitry Andric       SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI);
961e8d8bef9SDimitry Andric 
962e8d8bef9SDimitry Andric   InsertTop->setName(Header->getName() + ".peel.begin");
963e8d8bef9SDimitry Andric   InsertBot->setName(Header->getName() + ".peel.next");
964e8d8bef9SDimitry Andric   NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
965e8d8bef9SDimitry Andric 
966bdd1243dSDimitry Andric   Instruction *LatchTerm =
967bdd1243dSDimitry Andric       cast<Instruction>(cast<BasicBlock>(Latch)->getTerminator());
968e8d8bef9SDimitry Andric 
969e8d8bef9SDimitry Andric   // If we have branch weight information, we'll want to update it for the
970e8d8bef9SDimitry Andric   // newly created branches.
971bdd1243dSDimitry Andric   DenseMap<Instruction *, WeightInfo> Weights;
972bdd1243dSDimitry Andric   initBranchWeights(Weights, L);
973e8d8bef9SDimitry Andric 
974d409305fSDimitry Andric   // Identify what noalias metadata is inside the loop: if it is inside the
975d409305fSDimitry Andric   // loop, the associated metadata must be cloned for each iteration.
976d409305fSDimitry Andric   SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
977d409305fSDimitry Andric   identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
978d409305fSDimitry Andric 
979e8d8bef9SDimitry Andric   // For each peeled-off iteration, make a copy of the loop.
980e8d8bef9SDimitry Andric   for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
981e8d8bef9SDimitry Andric     SmallVector<BasicBlock *, 8> NewBlocks;
982e8d8bef9SDimitry Andric     ValueToValueMapTy VMap;
983e8d8bef9SDimitry Andric 
984e8d8bef9SDimitry Andric     cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks,
9851fd87a68SDimitry Andric                     LoopBlocks, VMap, LVMap, &DT, LI,
98681ad6265SDimitry Andric                     LoopLocalNoAliasDeclScopes, *SE);
987e8d8bef9SDimitry Andric 
988e8d8bef9SDimitry Andric     // Remap to use values from the current iteration instead of the
989e8d8bef9SDimitry Andric     // previous one.
990e8d8bef9SDimitry Andric     remapInstructionsInBlocks(NewBlocks, VMap);
991e8d8bef9SDimitry Andric 
992349cc55cSDimitry Andric     // Update IDoms of the blocks reachable through exits.
993e8d8bef9SDimitry Andric     if (Iter == 0)
994349cc55cSDimitry Andric       for (auto BBIDom : NonLoopBlocksIDom)
9951fd87a68SDimitry Andric         DT.changeImmediateDominator(BBIDom.first,
996349cc55cSDimitry Andric                                      cast<BasicBlock>(LVMap[BBIDom.second]));
997e8d8bef9SDimitry Andric #ifdef EXPENSIVE_CHECKS
9981fd87a68SDimitry Andric     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
999e8d8bef9SDimitry Andric #endif
1000e8d8bef9SDimitry Andric 
1001bdd1243dSDimitry Andric     for (auto &[Term, Info] : Weights) {
1002bdd1243dSDimitry Andric       auto *TermCopy = cast<Instruction>(VMap[Term]);
1003bdd1243dSDimitry Andric       updateBranchWeights(TermCopy, Info);
1004bdd1243dSDimitry Andric     }
1005bdd1243dSDimitry Andric 
1006e8d8bef9SDimitry Andric     // Remove Loop metadata from the latch branch instruction
1007e8d8bef9SDimitry Andric     // because it is not the Loop's latch branch anymore.
1008bdd1243dSDimitry Andric     auto *LatchTermCopy = cast<Instruction>(VMap[LatchTerm]);
1009bdd1243dSDimitry Andric     LatchTermCopy->setMetadata(LLVMContext::MD_loop, nullptr);
1010e8d8bef9SDimitry Andric 
1011e8d8bef9SDimitry Andric     InsertTop = InsertBot;
10121fd87a68SDimitry Andric     InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI);
1013e8d8bef9SDimitry Andric     InsertBot->setName(Header->getName() + ".peel.next");
1014e8d8bef9SDimitry Andric 
1015bdd1243dSDimitry Andric     F->splice(InsertTop->getIterator(), F, NewBlocks[0]->getIterator(),
1016bdd1243dSDimitry Andric               F->end());
1017e8d8bef9SDimitry Andric   }
1018e8d8bef9SDimitry Andric 
1019e8d8bef9SDimitry Andric   // Now adjust the phi nodes in the loop header to get their initial values
1020e8d8bef9SDimitry Andric   // from the last peeled-off iteration instead of the preheader.
1021e8d8bef9SDimitry Andric   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
1022e8d8bef9SDimitry Andric     PHINode *PHI = cast<PHINode>(I);
1023e8d8bef9SDimitry Andric     Value *NewVal = PHI->getIncomingValueForBlock(Latch);
1024e8d8bef9SDimitry Andric     Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
1025e8d8bef9SDimitry Andric     if (LatchInst && L->contains(LatchInst))
1026e8d8bef9SDimitry Andric       NewVal = LVMap[LatchInst];
1027e8d8bef9SDimitry Andric 
1028e8d8bef9SDimitry Andric     PHI->setIncomingValueForBlock(NewPreHeader, NewVal);
1029e8d8bef9SDimitry Andric   }
1030e8d8bef9SDimitry Andric 
1031bdd1243dSDimitry Andric   for (const auto &[Term, Info] : Weights)
1032bdd1243dSDimitry Andric     fixupBranchWeights(Term, Info);
1033e8d8bef9SDimitry Andric 
1034e8d8bef9SDimitry Andric   // Update Metadata for count of peeled off iterations.
1035e8d8bef9SDimitry Andric   unsigned AlreadyPeeled = 0;
1036e8d8bef9SDimitry Andric   if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData))
1037e8d8bef9SDimitry Andric     AlreadyPeeled = *Peeled;
1038e8d8bef9SDimitry Andric   addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount);
1039e8d8bef9SDimitry Andric 
1040e8d8bef9SDimitry Andric   if (Loop *ParentLoop = L->getParentLoop())
1041e8d8bef9SDimitry Andric     L = ParentLoop;
1042e8d8bef9SDimitry Andric 
1043e8d8bef9SDimitry Andric   // We modified the loop, update SE.
1044e8d8bef9SDimitry Andric   SE->forgetTopmostLoop(L);
1045*06c3fb27SDimitry Andric   SE->forgetBlockAndLoopDispositions();
1046e8d8bef9SDimitry Andric 
104781ad6265SDimitry Andric #ifdef EXPENSIVE_CHECKS
1048e8d8bef9SDimitry Andric   // Finally DomtTree must be correct.
10491fd87a68SDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
105081ad6265SDimitry Andric #endif
1051e8d8bef9SDimitry Andric 
1052e8d8bef9SDimitry Andric   // FIXME: Incrementally update loop-simplify
10531fd87a68SDimitry Andric   simplifyLoop(L, &DT, LI, SE, AC, nullptr, PreserveLCSSA);
1054e8d8bef9SDimitry Andric 
1055e8d8bef9SDimitry Andric   NumPeeled++;
1056e8d8bef9SDimitry Andric 
1057e8d8bef9SDimitry Andric   return true;
1058e8d8bef9SDimitry Andric }
1059