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