blob: 13f33277ff10e2be20d129be66ee6c8e39c76bc3 [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- UnrollLoopPeel.cpp - Loop peeling utilities ------------------------===//
Michael Kupersteinb151a642016-11-30 21:13:57 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Michael Kupersteinb151a642016-11-30 21:13:57 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements some loop unrolling utilities for peeling loops
10// with dynamically inferred (from PGO) trip counts. See LoopUnroll.cpp for
11// unrolling loops with compile-time constant trip counts.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/SmallVector.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000018#include "llvm/ADT/Statistic.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000019#include "llvm/Analysis/LoopInfo.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000020#include "llvm/Analysis/LoopIterator.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000021#include "llvm/Analysis/ScalarEvolution.h"
Florian Hahnfc97b612018-03-15 21:34:43 +000022#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000023#include "llvm/Analysis/TargetTransformInfo.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Dominators.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000026#include "llvm/IR/Function.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/LLVMContext.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000031#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Metadata.h"
Florian Hahnfc97b612018-03-15 21:34:43 +000033#include "llvm/IR/PatternMatch.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000034#include "llvm/Support/Casting.h"
35#include "llvm/Support/CommandLine.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000036#include "llvm/Support/Debug.h"
37#include "llvm/Support/raw_ostream.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/Cloning.h"
Eli Friedman0a217452017-01-18 23:26:37 +000040#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000041#include "llvm/Transforms/Utils/LoopUtils.h"
42#include "llvm/Transforms/Utils/UnrollLoop.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000043#include "llvm/Transforms/Utils/ValueMapper.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000044#include <algorithm>
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000045#include <cassert>
46#include <cstdint>
47#include <limits>
Michael Kupersteinb151a642016-11-30 21:13:57 +000048
49using namespace llvm;
Florian Hahnfc97b612018-03-15 21:34:43 +000050using namespace llvm::PatternMatch;
Michael Kupersteinb151a642016-11-30 21:13:57 +000051
52#define DEBUG_TYPE "loop-unroll"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000053
Michael Kupersteinb151a642016-11-30 21:13:57 +000054STATISTIC(NumPeeled, "Number of loops peeled");
55
56static cl::opt<unsigned> UnrollPeelMaxCount(
57 "unroll-peel-max-count", cl::init(7), cl::Hidden,
58 cl::desc("Max average trip count which will cause loop peeling."));
59
60static cl::opt<unsigned> UnrollForcePeelCount(
61 "unroll-force-peel-count", cl::init(0), cl::Hidden,
62 cl::desc("Force a peel count regardless of profiling information."));
63
Serguei Katkov3ed93b42019-07-15 08:26:45 +000064static cl::opt<bool> UnrollPeelMultiDeoptExit(
Serguei Katkovbde33af2019-07-19 08:35:45 +000065 "unroll-peel-multi-deopt-exit", cl::init(true), cl::Hidden,
Serguei Katkov3ed93b42019-07-15 08:26:45 +000066 cl::desc("Allow peeling of loops with multiple deopt exits."));
67
Serguei Katkovbbdcc822019-08-02 04:29:23 +000068static const char *PeeledCountMetaData = "llvm.loop.peeled.count";
69
Max Kazantsev751579c2017-04-17 09:52:02 +000070// Designates that a Phi is estimated to become invariant after an "infinite"
71// number of loop iterations (i.e. only may become an invariant if the loop is
72// fully unrolled).
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000073static const unsigned InfiniteIterationsToInvariance =
74 std::numeric_limits<unsigned>::max();
Max Kazantsev751579c2017-04-17 09:52:02 +000075
Michael Kupersteinb151a642016-11-30 21:13:57 +000076// Check whether we are capable of peeling this loop.
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +000077bool llvm::canPeel(Loop *L) {
Michael Kupersteinb151a642016-11-30 21:13:57 +000078 // Make sure the loop is in simplified form
79 if (!L->isLoopSimplifyForm())
80 return false;
81
Serguei Katkov3ed93b42019-07-15 08:26:45 +000082 if (UnrollPeelMultiDeoptExit) {
83 SmallVector<BasicBlock *, 4> Exits;
84 L->getUniqueNonLatchExitBlocks(Exits);
85
86 if (!Exits.empty()) {
87 // Latch's terminator is a conditional branch, Latch is exiting and
88 // all non Latch exits ends up with deoptimize.
89 const BasicBlock *Latch = L->getLoopLatch();
90 const BranchInst *T = dyn_cast<BranchInst>(Latch->getTerminator());
91 return T && T->isConditional() && L->isLoopExiting(Latch) &&
92 all_of(Exits, [](const BasicBlock *BB) {
93 return BB->getTerminatingDeoptimizeCall();
94 });
95 }
96 }
97
Michael Kupersteinb151a642016-11-30 21:13:57 +000098 // Only peel loops that contain a single exit
99 if (!L->getExitingBlock() || !L->getUniqueExitBlock())
100 return false;
101
Michael Kuperstein2da2bfa2017-03-16 21:07:48 +0000102 // Don't try to peel loops where the latch is not the exiting block.
103 // This can be an indication of two different things:
104 // 1) The loop is not rotated.
105 // 2) The loop contains irreducible control flow that involves the latch.
106 if (L->getLoopLatch() != L->getExitingBlock())
107 return false;
108
Michael Kupersteinb151a642016-11-30 21:13:57 +0000109 return true;
110}
111
Max Kazantsev751579c2017-04-17 09:52:02 +0000112// 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.
125static unsigned calculateIterationsToInvariance(
126 PHINode *Phi, Loop *L, BasicBlock *BackEdge,
127 SmallDenseMap<PHINode *, 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] = InfiniteIterationsToInvariance;
141 unsigned ToInvariance = InfiniteIterationsToInvariance;
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 InfiniteIterationsToInvariance;
149 // If the input becomes an invariant after X iterations, then our Phi
150 // becomes an invariant after X + 1 iterations.
151 unsigned InputToInvariance = calculateIterationsToInvariance(
152 IncPhi, L, BackEdge, IterationsToInvariance);
153 if (InputToInvariance != InfiniteIterationsToInvariance)
154 ToInvariance = InputToInvariance + 1u;
155 }
156
157 // If we found that this Phi lies in an invariant chain, update the map.
158 if (ToInvariance != InfiniteIterationsToInvariance)
159 IterationsToInvariance[Phi] = ToInvariance;
160 return ToInvariance;
161}
162
Florian Hahnfc97b612018-03-15 21:34:43 +0000163// Return the number of iterations to peel off that make conditions in the
164// body true/false. For example, if we peel 2 iterations off the loop below,
165// the condition i < 2 can be evaluated at compile time.
166// for (i = 0; i < n; i++)
167// if (i < 2)
168// ..
169// else
170// ..
171// }
172static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount,
173 ScalarEvolution &SE) {
174 assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form");
175 unsigned DesiredPeelCount = 0;
176
177 for (auto *BB : L.blocks()) {
178 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
179 if (!BI || BI->isUnconditional())
180 continue;
181
182 // Ignore loop exit condition.
183 if (L.getLoopLatch() == BB)
184 continue;
185
186 Value *Condition = BI->getCondition();
187 Value *LeftVal, *RightVal;
188 CmpInst::Predicate Pred;
189 if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal))))
190 continue;
191
192 const SCEV *LeftSCEV = SE.getSCEV(LeftVal);
193 const SCEV *RightSCEV = SE.getSCEV(RightVal);
194
195 // Do not consider predicates that are known to be true or false
196 // independently of the loop iteration.
197 if (SE.isKnownPredicate(Pred, LeftSCEV, RightSCEV) ||
198 SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), LeftSCEV,
199 RightSCEV))
200 continue;
201
202 // Check if we have a condition with one AddRec and one non AddRec
203 // expression. Normalize LeftSCEV to be the AddRec.
204 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
205 if (isa<SCEVAddRecExpr>(RightSCEV)) {
206 std::swap(LeftSCEV, RightSCEV);
207 Pred = ICmpInst::getSwappedPredicate(Pred);
208 } else
209 continue;
210 }
211
212 const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV);
213
Florian Hahnac277582018-04-18 12:29:24 +0000214 // Avoid huge SCEV computations in the loop below, make sure we only
Roman Lebedev4fe94d02019-11-06 14:57:49 +0300215 // consider AddRecs of the loop we are trying to peel.
216 if (!LeftAR->isAffine() || LeftAR->getLoop() != &L)
217 continue;
Florian Hahnac277582018-04-18 12:29:24 +0000218 bool Increasing;
Roman Lebedev4fe94d02019-11-06 14:57:49 +0300219 if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) &&
Florian Hahnac277582018-04-18 12:29:24 +0000220 !SE.isMonotonicPredicate(LeftAR, Pred, Increasing))
Florian Hahnfc97b612018-03-15 21:34:43 +0000221 continue;
Florian Hahnac277582018-04-18 12:29:24 +0000222 (void)Increasing;
Florian Hahnfc97b612018-03-15 21:34:43 +0000223
Florian Hahnac277582018-04-18 12:29:24 +0000224 // Check if extending the current DesiredPeelCount lets us evaluate Pred
225 // or !Pred in the loop body statically.
226 unsigned NewPeelCount = DesiredPeelCount;
227
Florian Hahnfc97b612018-03-15 21:34:43 +0000228 const SCEV *IterVal = LeftAR->evaluateAtIteration(
Florian Hahnac277582018-04-18 12:29:24 +0000229 SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE);
Florian Hahnfc97b612018-03-15 21:34:43 +0000230
231 // If the original condition is not known, get the negated predicate
232 // (which holds on the else branch) and check if it is known. This allows
233 // us to peel of iterations that make the original condition false.
234 if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV))
235 Pred = ICmpInst::getInversePredicate(Pred);
236
237 const SCEV *Step = LeftAR->getStepRecurrence(SE);
Roman Lebedev4fe94d02019-11-06 14:57:49 +0300238 const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step);
239 auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step,
240 &NewPeelCount]() {
241 IterVal = NextIterVal;
242 NextIterVal = SE.getAddExpr(IterVal, Step);
Florian Hahnac277582018-04-18 12:29:24 +0000243 NewPeelCount++;
Roman Lebedev4fe94d02019-11-06 14:57:49 +0300244 };
245
246 auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() {
247 return NewPeelCount < MaxPeelCount;
248 };
249
250 while (CanPeelOneMoreIteration() &&
251 SE.isKnownPredicate(Pred, IterVal, RightSCEV))
252 PeelOneMoreIteration();
253
254 // With *that* peel count, does the predicate !Pred become known in the
255 // first iteration of the loop body after peeling?
256 if (!SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal,
257 RightSCEV))
258 continue; // If not, give up.
259
260 // However, for equality comparisons, that isn't always sufficient to
261 // eliminate the comparsion in loop body, we may need to peel one more
262 // iteration. See if that makes !Pred become unknown again.
263 if (ICmpInst::isEquality(Pred) &&
264 !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal,
265 RightSCEV)) {
266 assert(!SE.isKnownPredicate(Pred, IterVal, RightSCEV) &&
267 SE.isKnownPredicate(Pred, NextIterVal, RightSCEV) &&
268 "Expected Pred to go from known to unknown.");
269 if (!CanPeelOneMoreIteration())
270 continue; // Need to peel one more iteration, but can't. Give up.
271 PeelOneMoreIteration(); // Great!
Florian Hahnfc97b612018-03-15 21:34:43 +0000272 }
Florian Hahnac277582018-04-18 12:29:24 +0000273
Roman Lebedev4fe94d02019-11-06 14:57:49 +0300274 DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount);
Florian Hahnfc97b612018-03-15 21:34:43 +0000275 }
276
277 return DesiredPeelCount;
278}
279
Michael Kupersteinb151a642016-11-30 21:13:57 +0000280// Return the number of iterations we want to peel off.
281void llvm::computePeelCount(Loop *L, unsigned LoopSize,
Sanjoy Daseed71b92017-03-03 18:19:10 +0000282 TargetTransformInfo::UnrollingPreferences &UP,
Florian Hahnfc97b612018-03-15 21:34:43 +0000283 unsigned &TripCount, ScalarEvolution &SE) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000284 assert(LoopSize > 0 && "Zero loop size is not allowed!");
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +0000285 // Save the UP.PeelCount value set by the target in
286 // TTI.getUnrollingPreferences or by the flag -unroll-peel-count.
287 unsigned TargetPeelCount = UP.PeelCount;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000288 UP.PeelCount = 0;
289 if (!canPeel(L))
290 return;
291
292 // Only try to peel innermost loops.
293 if (!L->empty())
294 return;
295
Chad Rosier45735b82018-04-06 13:57:21 +0000296 // If the user provided a peel count, use that.
297 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
298 if (UserPeelCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000299 LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
300 << " iterations.\n");
Chad Rosier45735b82018-04-06 13:57:21 +0000301 UP.PeelCount = UnrollForcePeelCount;
Serguei Katkovbbdcc822019-08-02 04:29:23 +0000302 UP.PeelProfiledIterations = true;
Chad Rosier45735b82018-04-06 13:57:21 +0000303 return;
304 }
305
306 // Skip peeling if it's disabled.
307 if (!UP.AllowPeeling)
308 return;
309
Serguei Katkovbbdcc822019-08-02 04:29:23 +0000310 unsigned AlreadyPeeled = 0;
311 if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData))
312 AlreadyPeeled = *Peeled;
313 // Stop if we already peeled off the maximum number of iterations.
314 if (AlreadyPeeled >= UnrollPeelMaxCount)
315 return;
316
Max Kazantsev751579c2017-04-17 09:52:02 +0000317 // Here we try to get rid of Phis which become invariants after 1, 2, ..., N
318 // iterations of the loop. For this we compute the number for iterations after
319 // which every Phi is guaranteed to become an invariant, and try to peel the
320 // maximum number of iterations among these values, thus turning all those
321 // Phis into invariants.
Max Kazantsev8ed6b662017-04-17 05:38:28 +0000322 // First, check that we can peel at least one iteration.
323 if (2 * LoopSize <= UP.Threshold && UnrollPeelMaxCount > 0) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000324 // Store the pre-calculated values here.
325 SmallDenseMap<PHINode *, unsigned> IterationsToInvariance;
326 // Now go through all Phis to calculate their the number of iterations they
327 // need to become invariants.
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +0000328 // Start the max computation with the UP.PeelCount value set by the target
329 // in TTI.getUnrollingPreferences or by the flag -unroll-peel-count.
330 unsigned DesiredPeelCount = TargetPeelCount;
Sanjoy Das30c35382017-03-07 06:03:15 +0000331 BasicBlock *BackEdge = L->getLoopLatch();
332 assert(BackEdge && "Loop is not in simplified form?");
Max Kazantsev751579c2017-04-17 09:52:02 +0000333 for (auto BI = L->getHeader()->begin(); isa<PHINode>(&*BI); ++BI) {
334 PHINode *Phi = cast<PHINode>(&*BI);
335 unsigned ToInvariance = calculateIterationsToInvariance(
336 Phi, L, BackEdge, IterationsToInvariance);
337 if (ToInvariance != InfiniteIterationsToInvariance)
338 DesiredPeelCount = std::max(DesiredPeelCount, ToInvariance);
Sanjoy Das664c9252017-03-03 18:19:15 +0000339 }
Florian Hahnfc97b612018-03-15 21:34:43 +0000340
341 // Pay respect to limitations implied by loop size and the max peel count.
342 unsigned MaxPeelCount = UnrollPeelMaxCount;
343 MaxPeelCount = std::min(MaxPeelCount, UP.Threshold / LoopSize - 1);
344
345 DesiredPeelCount = std::max(DesiredPeelCount,
346 countToEliminateCompares(*L, MaxPeelCount, SE));
347
Max Kazantsev751579c2017-04-17 09:52:02 +0000348 if (DesiredPeelCount > 0) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000349 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount);
350 // Consider max peel count limitation.
351 assert(DesiredPeelCount > 0 && "Wrong loop size estimation?");
Serguei Katkovbbdcc822019-08-02 04:29:23 +0000352 if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) {
353 LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount
354 << " iteration(s) to turn"
355 << " some Phis into invariants.\n");
356 UP.PeelCount = DesiredPeelCount;
357 UP.PeelProfiledIterations = false;
358 return;
359 }
Sanjoy Das664c9252017-03-03 18:19:15 +0000360 }
361 }
362
Sanjoy Daseed71b92017-03-03 18:19:10 +0000363 // Bail if we know the statically calculated trip count.
364 // In this case we rather prefer partial unrolling.
365 if (TripCount)
366 return;
367
Serguei Katkovbbdcc822019-08-02 04:29:23 +0000368 // Do not apply profile base peeling if it is disabled.
369 if (!UP.PeelProfiledIterations)
370 return;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000371 // If we don't know the trip count, but have reason to believe the average
372 // trip count is low, peeling should be beneficial, since we will usually
373 // hit the peeled section.
374 // We only do this in the presence of profile information, since otherwise
375 // our estimates of the trip count are not reliable enough.
Chad Rosier45735b82018-04-06 13:57:21 +0000376 if (L->getHeader()->getParent()->hasProfileData()) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000377 Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L);
378 if (!PeelCount)
379 return;
380
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000381 LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount
382 << "\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000383
384 if (*PeelCount) {
Serguei Katkovbbdcc822019-08-02 04:29:23 +0000385 if ((*PeelCount + AlreadyPeeled <= UnrollPeelMaxCount) &&
Michael Kupersteinb151a642016-11-30 21:13:57 +0000386 (LoopSize * (*PeelCount + 1) <= UP.Threshold)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000387 LLVM_DEBUG(dbgs() << "Peeling first " << *PeelCount
388 << " iterations.\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000389 UP.PeelCount = *PeelCount;
390 return;
391 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000392 LLVM_DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n");
Serguei Katkovbbdcc822019-08-02 04:29:23 +0000393 LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000394 LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
395 LLVM_DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1)
396 << "\n");
397 LLVM_DEBUG(dbgs() << "Max peel cost: " << UP.Threshold << "\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000398 }
399 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000400}
401
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000402/// Update the branch weights of the latch of a peeled-off loop
Michael Kupersteinb151a642016-11-30 21:13:57 +0000403/// iteration.
404/// This sets the branch weights for the latch of the recently peeled off loop
Fangrui Songf78650a2018-07-30 19:41:25 +0000405/// iteration correctly.
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000406/// Let F is a weight of the edge from latch to header.
407/// Let E is a weight of the edge from latch to exit.
408/// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to
409/// go to exit.
410/// Then, Estimated TripCount = F / E.
411/// For I-th (counting from 0) peeled off iteration we set the the weights for
412/// the peeled latch as (TC - I, 1). It gives us reasonable distribution,
413/// The probability to go to exit 1/(TC-I) increases. At the same time
414/// the estimated trip count of remaining loop reduces by I.
415/// To avoid dealing with division rounding we can just multiple both part
416/// of weights to E and use weight as (F - I * E, E).
Michael Kupersteinb151a642016-11-30 21:13:57 +0000417///
418/// \param Header The copy of the header block that belongs to next iteration.
419/// \param LatchBR The copy of the latch branch that belongs to this iteration.
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000420/// \param[in,out] FallThroughWeight The weight of the edge from latch to
421/// header before peeling (in) and after peeled off one iteration (out).
Michael Kupersteinb151a642016-11-30 21:13:57 +0000422static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000423 uint64_t ExitWeight,
424 uint64_t &FallThroughWeight) {
425 // FallThroughWeight is 0 means that there is no branch weights on original
426 // latch block or estimated trip count is zero.
427 if (!FallThroughWeight)
Serguei Katkov0ffa8332019-07-18 07:36:20 +0000428 return;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000429
Serguei Katkov0ffa8332019-07-18 07:36:20 +0000430 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
431 MDBuilder MDB(LatchBR->getContext());
432 MDNode *WeightNode =
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000433 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight)
434 : MDB.createBranchWeights(FallThroughWeight, ExitWeight);
Serguei Katkov0ffa8332019-07-18 07:36:20 +0000435 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000436 FallThroughWeight =
437 FallThroughWeight > ExitWeight ? FallThroughWeight - ExitWeight : 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000438}
439
Serguei Katkovc22e7722019-07-03 05:59:23 +0000440/// Initialize the weights.
441///
442/// \param Header The header block.
443/// \param LatchBR The latch branch.
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000444/// \param[out] ExitWeight The weight of the edge from Latch to Exit.
445/// \param[out] FallThroughWeight The weight of the edge from Latch to Header.
Serguei Katkovc22e7722019-07-03 05:59:23 +0000446static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000447 uint64_t &ExitWeight,
448 uint64_t &FallThroughWeight) {
Serguei Katkovc22e7722019-07-03 05:59:23 +0000449 uint64_t TrueWeight, FalseWeight;
450 if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight))
451 return;
452 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1;
453 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000454 FallThroughWeight = HeaderIdx ? FalseWeight : TrueWeight;
Serguei Katkovc22e7722019-07-03 05:59:23 +0000455}
456
457/// Update the weights of original Latch block after peeling off all iterations.
458///
459/// \param Header The header block.
460/// \param LatchBR The latch branch.
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000461/// \param ExitWeight The weight of the edge from Latch to Exit.
462/// \param FallThroughWeight The weight of the edge from Latch to Header.
Serguei Katkovc22e7722019-07-03 05:59:23 +0000463static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000464 uint64_t ExitWeight,
465 uint64_t FallThroughWeight) {
466 // FallThroughWeight is 0 means that there is no branch weights on original
467 // latch block or estimated trip count is zero.
468 if (!FallThroughWeight)
Serguei Katkov0ffa8332019-07-18 07:36:20 +0000469 return;
470
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000471 // Sets the branch weights on the loop exit.
Serguei Katkov0ffa8332019-07-18 07:36:20 +0000472 MDBuilder MDB(LatchBR->getContext());
473 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1;
474 MDNode *WeightNode =
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000475 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight)
476 : MDB.createBranchWeights(FallThroughWeight, ExitWeight);
Serguei Katkov0ffa8332019-07-18 07:36:20 +0000477 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
Serguei Katkovc22e7722019-07-03 05:59:23 +0000478}
479
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000480/// Clones the body of the loop L, putting it between \p InsertTop and \p
Michael Kupersteinb151a642016-11-30 21:13:57 +0000481/// InsertBot.
482/// \param IterNumber The serial number of the iteration currently being
483/// peeled off.
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000484/// \param ExitEdges The exit edges of the original loop.
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000485/// \param[out] NewBlocks A list of the blocks in the newly created clone
Michael Kupersteinb151a642016-11-30 21:13:57 +0000486/// \param[out] VMap The value map between the loop and the new clone.
487/// \param LoopBlocks A helper for DFS-traversal of the loop.
488/// \param LVMap A value-map that maps instructions from the original loop to
489/// instructions in the last peeled-off iteration.
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000490static void cloneLoopBlocks(
491 Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot,
492 SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *> > &ExitEdges,
493 SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
494 ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT,
495 LoopInfo *LI) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000496 BasicBlock *Header = L->getHeader();
497 BasicBlock *Latch = L->getLoopLatch();
498 BasicBlock *PreHeader = L->getLoopPreheader();
499
500 Function *F = Header->getParent();
501 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
502 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
503 Loop *ParentLoop = L->getParentLoop();
504
505 // For each block in the original loop, create a new copy,
506 // and update the value map with the newly created values.
507 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
508 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
509 NewBlocks.push_back(NewBB);
510
511 if (ParentLoop)
512 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
513
514 VMap[*BB] = NewBB;
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000515
516 // If dominator tree is available, insert nodes to represent cloned blocks.
517 if (DT) {
518 if (Header == *BB)
519 DT->addNewBlock(NewBB, InsertTop);
520 else {
521 DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
522 // VMap must contain entry for IDom, as the iteration order is RPO.
523 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
524 }
525 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000526 }
527
528 // Hook-up the control flow for the newly inserted blocks.
529 // The new header is hooked up directly to the "top", which is either
530 // the original loop preheader (for the first iteration) or the previous
531 // iteration's exiting block (for every other iteration)
532 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
533
534 // Similarly, for the latch:
535 // The original exiting edge is still hooked up to the loop exit.
536 // The backedge now goes to the "bottom", which is either the loop's real
537 // header (for the last peeled iteration) or the copied header of the next
538 // iteration (for every other iteration)
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000539 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
540 BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator());
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000541 for (unsigned idx = 0, e = LatchBR->getNumSuccessors(); idx < e; ++idx)
542 if (LatchBR->getSuccessor(idx) == Header) {
543 LatchBR->setSuccessor(idx, InsertBot);
544 break;
545 }
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000546 if (DT)
547 DT->changeImmediateDominator(InsertBot, NewLatch);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000548
549 // The new copy of the loop body starts with a bunch of PHI nodes
550 // that pick an incoming value from either the preheader, or the previous
551 // loop iteration. Since this copy is no longer part of the loop, we
552 // resolve this statically:
553 // For the first iteration, we use the value from the preheader directly.
554 // For any other iteration, we replace the phi with the value generated by
555 // the immediately preceding clone of the loop body (which represents
556 // the previous iteration).
557 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
558 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
559 if (IterNumber == 0) {
560 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
561 } else {
562 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
563 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
564 if (LatchInst && L->contains(LatchInst))
565 VMap[&*I] = LVMap[LatchInst];
566 else
567 VMap[&*I] = LatchVal;
568 }
569 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
570 }
571
572 // Fix up the outgoing values - we need to add a value for the iteration
573 // we've just created. Note that this must happen *after* the incoming
574 // values are adjusted, since the value going out of the latch may also be
575 // a value coming into the header.
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000576 for (auto Edge : ExitEdges)
577 for (PHINode &PHI : Edge.second->phis()) {
578 Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first);
579 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
580 if (LatchInst && L->contains(LatchInst))
581 LatchVal = VMap[LatchVal];
582 PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first]));
583 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000584
585 // LastValueMap is updated with the values for the current loop
586 // which are used the next time this function is called.
587 for (const auto &KV : VMap)
588 LVMap[KV.first] = KV.second;
589}
590
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000591/// Peel off the first \p PeelCount iterations of loop \p L.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000592///
593/// Note that this does not peel them off as a single straight-line block.
594/// Rather, each iteration is peeled off separately, and needs to check the
595/// exit condition.
596/// For loops that dynamically execute \p PeelCount iterations or less
597/// this provides a benefit, since the peeled off iterations, which account
598/// for the bulk of dynamic execution, can be further simplified by scalar
599/// optimizations.
600bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
601 ScalarEvolution *SE, DominatorTree *DT,
Eli Friedman0a217452017-01-18 23:26:37 +0000602 AssumptionCache *AC, bool PreserveLCSSA) {
Max Kazantsevb1ad66f2018-03-27 09:40:51 +0000603 assert(PeelCount > 0 && "Attempt to peel out zero iterations?");
604 assert(canPeel(L) && "Attempt to peel a loop which is not peelable?");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000605
606 LoopBlocksDFS LoopBlocks(L);
607 LoopBlocks.perform(LI);
608
609 BasicBlock *Header = L->getHeader();
610 BasicBlock *PreHeader = L->getLoopPreheader();
611 BasicBlock *Latch = L->getLoopLatch();
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000612 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges;
613 L->getExitEdges(ExitEdges);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000614
Serguei Katkovd021ad92019-07-15 09:13:11 +0000615 DenseMap<BasicBlock *, BasicBlock *> ExitIDom;
616 if (DT) {
Serguei Katkovcde00c02019-07-25 19:31:50 +0000617 // We'd like to determine the idom of exit block after peeling one
618 // iteration.
619 // Let Exit is exit block.
620 // Let ExitingSet - is a set of predecessors of Exit block. They are exiting
621 // blocks.
622 // Let Latch' and ExitingSet' are copies after a peeling.
623 // We'd like to find an idom'(Exit) - idom of Exit after peeling.
624 // It is an evident that idom'(Exit) will be the nearest common dominator
625 // of ExitingSet and ExitingSet'.
626 // idom(Exit) is a nearest common dominator of ExitingSet.
627 // idom(Exit)' is a nearest common dominator of ExitingSet'.
628 // Taking into account that we have a single Latch, Latch' will dominate
629 // Header and idom(Exit).
630 // So the idom'(Exit) is nearest common dominator of idom(Exit)' and Latch'.
631 // All these basic blocks are in the same loop, so what we find is
632 // (nearest common dominator of idom(Exit) and Latch)'.
633 // In the loop below we remember nearest common dominator of idom(Exit) and
634 // Latch to update idom of Exit later.
Serguei Katkovd021ad92019-07-15 09:13:11 +0000635 assert(L->hasDedicatedExits() && "No dedicated exits?");
636 for (auto Edge : ExitEdges) {
637 if (ExitIDom.count(Edge.second))
638 continue;
Serguei Katkovcde00c02019-07-25 19:31:50 +0000639 BasicBlock *BB = DT->findNearestCommonDominator(
640 DT->getNode(Edge.second)->getIDom()->getBlock(), Latch);
Serguei Katkovd021ad92019-07-15 09:13:11 +0000641 assert(L->contains(BB) && "IDom is not in a loop");
642 ExitIDom[Edge.second] = BB;
643 }
644 }
645
Michael Kupersteinb151a642016-11-30 21:13:57 +0000646 Function *F = Header->getParent();
647
648 // Set up all the necessary basic blocks. It is convenient to split the
649 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
650 // body, and a new preheader for the "real" loop.
651
652 // Peeling the first iteration transforms.
653 //
654 // PreHeader:
655 // ...
656 // Header:
657 // LoopBody
658 // If (cond) goto Header
659 // Exit:
660 //
661 // into
662 //
663 // InsertTop:
664 // LoopBody
665 // If (!cond) goto Exit
666 // InsertBot:
667 // NewPreHeader:
668 // ...
669 // Header:
670 // LoopBody
671 // If (cond) goto Header
672 // Exit:
673 //
674 // Each following iteration will split the current bottom anchor in two,
675 // and put the new copy of the loop body between these two blocks. That is,
Fangrui Songf78650a2018-07-30 19:41:25 +0000676 // after peeling another iteration from the example above, we'll split
Michael Kupersteinb151a642016-11-30 21:13:57 +0000677 // InsertBot, and get:
678 //
679 // InsertTop:
680 // LoopBody
681 // If (!cond) goto Exit
682 // InsertBot:
683 // LoopBody
684 // If (!cond) goto Exit
685 // InsertBot.next:
686 // NewPreHeader:
687 // ...
688 // Header:
689 // LoopBody
690 // If (cond) goto Header
691 // Exit:
692
693 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI);
694 BasicBlock *InsertBot =
695 SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI);
696 BasicBlock *NewPreHeader =
697 SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
698
699 InsertTop->setName(Header->getName() + ".peel.begin");
700 InsertBot->setName(Header->getName() + ".peel.next");
701 NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
702
703 ValueToValueMapTy LVMap;
704
705 // If we have branch weight information, we'll want to update it for the
706 // newly created branches.
707 BranchInst *LatchBR =
708 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000709 uint64_t ExitWeight = 0, FallThroughWeight = 0;
710 initBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000711
712 // For each peeled-off iteration, make a copy of the loop.
713 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
714 SmallVector<BasicBlock *, 8> NewBlocks;
715 ValueToValueMapTy VMap;
716
Serguei Katkov77bb3a42019-07-09 06:07:25 +0000717 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks,
718 LoopBlocks, VMap, LVMap, DT, LI);
Serge Pavlovb71bb802017-03-26 16:46:53 +0000719
720 // Remap to use values from the current iteration instead of the
721 // previous one.
722 remapInstructionsInBlocks(NewBlocks, VMap);
723
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000724 if (DT) {
725 // Latches of the cloned loops dominate over the loop exit, so idom of the
726 // latter is the first cloned loop body, as original PreHeader dominates
727 // the original loop body.
728 if (Iter == 0)
Serguei Katkovd021ad92019-07-15 09:13:11 +0000729 for (auto Exit : ExitIDom)
730 DT->changeImmediateDominator(Exit.first,
731 cast<BasicBlock>(LVMap[Exit.second]));
Eli Friedman3af2f532018-12-21 01:28:49 +0000732#ifdef EXPENSIVE_CHECKS
David Green7c35de12018-02-28 11:00:08 +0000733 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
Eli Friedman3af2f532018-12-21 01:28:49 +0000734#endif
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000735 }
736
Vyacheslav Zakharine06831a2018-09-26 01:03:21 +0000737 auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]);
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000738 updateBranchWeights(InsertBot, LatchBRCopy, ExitWeight, FallThroughWeight);
Vyacheslav Zakharine06831a2018-09-26 01:03:21 +0000739 // Remove Loop metadata from the latch branch instruction
740 // because it is not the Loop's latch branch anymore.
741 LatchBRCopy->setMetadata(LLVMContext::MD_loop, nullptr);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000742
743 InsertTop = InsertBot;
744 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
745 InsertBot->setName(Header->getName() + ".peel.next");
746
747 F->getBasicBlockList().splice(InsertTop->getIterator(),
748 F->getBasicBlockList(),
749 NewBlocks[0]->getIterator(), F->end());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000750 }
751
752 // Now adjust the phi nodes in the loop header to get their initial values
753 // from the last peeled-off iteration instead of the preheader.
754 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
755 PHINode *PHI = cast<PHINode>(I);
756 Value *NewVal = PHI->getIncomingValueForBlock(Latch);
757 Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
758 if (LatchInst && L->contains(LatchInst))
759 NewVal = LVMap[LatchInst];
760
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000761 PHI->setIncomingValueForBlock(NewPreHeader, NewVal);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000762 }
763
Serguei Katkovc6c31da2019-07-22 05:15:34 +0000764 fixupBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000765
Serguei Katkov036e6362019-08-22 10:06:46 +0000766 // Update Metadata for count of peeled off iterations.
767 unsigned AlreadyPeeled = 0;
768 if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData))
769 AlreadyPeeled = *Peeled;
770 addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount);
771
Florian Hahn6ab83b72019-02-14 13:59:39 +0000772 if (Loop *ParentLoop = L->getParentLoop())
773 L = ParentLoop;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000774
Florian Hahn6ab83b72019-02-14 13:59:39 +0000775 // We modified the loop, update SE.
776 SE->forgetTopmostLoop(L);
777
Serguei Katkovd021ad92019-07-15 09:13:11 +0000778 // Finally DomtTree must be correct.
779 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
780
Florian Hahn6ab83b72019-02-14 13:59:39 +0000781 // FIXME: Incrementally update loop-simplify
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000782 simplifyLoop(L, DT, LI, SE, AC, nullptr, PreserveLCSSA);
Eli Friedman0a217452017-01-18 23:26:37 +0000783
Michael Kupersteinb151a642016-11-30 21:13:57 +0000784 NumPeeled++;
785
Michael Kupersteinb151a642016-11-30 21:13:57 +0000786 return true;
787}