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