blob: 157e8e7c1d78846cc69233fbf815bd9c9851ae40 [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
Max Kazantsev751579c2017-04-17 09:52:02 +000064// Designates that a Phi is estimated to become invariant after an "infinite"
65// number of loop iterations (i.e. only may become an invariant if the loop is
66// fully unrolled).
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000067static const unsigned InfiniteIterationsToInvariance =
68 std::numeric_limits<unsigned>::max();
Max Kazantsev751579c2017-04-17 09:52:02 +000069
Michael Kupersteinb151a642016-11-30 21:13:57 +000070// Check whether we are capable of peeling this loop.
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +000071bool llvm::canPeel(Loop *L) {
Michael Kupersteinb151a642016-11-30 21:13:57 +000072 // Make sure the loop is in simplified form
73 if (!L->isLoopSimplifyForm())
74 return false;
75
76 // Only peel loops that contain a single exit
77 if (!L->getExitingBlock() || !L->getUniqueExitBlock())
78 return false;
79
Michael Kuperstein2da2bfa2017-03-16 21:07:48 +000080 // Don't try to peel loops where the latch is not the exiting block.
81 // This can be an indication of two different things:
82 // 1) The loop is not rotated.
83 // 2) The loop contains irreducible control flow that involves the latch.
84 if (L->getLoopLatch() != L->getExitingBlock())
85 return false;
86
Michael Kupersteinb151a642016-11-30 21:13:57 +000087 return true;
88}
89
Max Kazantsev751579c2017-04-17 09:52:02 +000090// This function calculates the number of iterations after which the given Phi
91// becomes an invariant. The pre-calculated values are memorized in the map. The
92// function (shortcut is I) is calculated according to the following definition:
93// Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge].
94// If %y is a loop invariant, then I(%x) = 1.
95// If %y is a Phi from the loop header, I(%x) = I(%y) + 1.
96// Otherwise, I(%x) is infinite.
97// TODO: Actually if %y is an expression that depends only on Phi %z and some
98// loop invariants, we can estimate I(%x) = I(%z) + 1. The example
99// looks like:
100// %x = phi(0, %a), <-- becomes invariant starting from 3rd iteration.
101// %y = phi(0, 5),
102// %a = %y + 1.
103static unsigned calculateIterationsToInvariance(
104 PHINode *Phi, Loop *L, BasicBlock *BackEdge,
105 SmallDenseMap<PHINode *, unsigned> &IterationsToInvariance) {
106 assert(Phi->getParent() == L->getHeader() &&
107 "Non-loop Phi should not be checked for turning into invariant.");
108 assert(BackEdge == L->getLoopLatch() && "Wrong latch?");
109 // If we already know the answer, take it from the map.
110 auto I = IterationsToInvariance.find(Phi);
111 if (I != IterationsToInvariance.end())
112 return I->second;
113
114 // Otherwise we need to analyze the input from the back edge.
115 Value *Input = Phi->getIncomingValueForBlock(BackEdge);
116 // Place infinity to map to avoid infinite recursion for cycled Phis. Such
117 // cycles can never stop on an invariant.
118 IterationsToInvariance[Phi] = InfiniteIterationsToInvariance;
119 unsigned ToInvariance = InfiniteIterationsToInvariance;
120
121 if (L->isLoopInvariant(Input))
122 ToInvariance = 1u;
123 else if (PHINode *IncPhi = dyn_cast<PHINode>(Input)) {
124 // Only consider Phis in header block.
125 if (IncPhi->getParent() != L->getHeader())
126 return InfiniteIterationsToInvariance;
127 // If the input becomes an invariant after X iterations, then our Phi
128 // becomes an invariant after X + 1 iterations.
129 unsigned InputToInvariance = calculateIterationsToInvariance(
130 IncPhi, L, BackEdge, IterationsToInvariance);
131 if (InputToInvariance != InfiniteIterationsToInvariance)
132 ToInvariance = InputToInvariance + 1u;
133 }
134
135 // If we found that this Phi lies in an invariant chain, update the map.
136 if (ToInvariance != InfiniteIterationsToInvariance)
137 IterationsToInvariance[Phi] = ToInvariance;
138 return ToInvariance;
139}
140
Florian Hahnfc97b612018-03-15 21:34:43 +0000141// Return the number of iterations to peel off that make conditions in the
142// body true/false. For example, if we peel 2 iterations off the loop below,
143// the condition i < 2 can be evaluated at compile time.
144// for (i = 0; i < n; i++)
145// if (i < 2)
146// ..
147// else
148// ..
149// }
150static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount,
151 ScalarEvolution &SE) {
152 assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form");
153 unsigned DesiredPeelCount = 0;
154
155 for (auto *BB : L.blocks()) {
156 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
157 if (!BI || BI->isUnconditional())
158 continue;
159
160 // Ignore loop exit condition.
161 if (L.getLoopLatch() == BB)
162 continue;
163
164 Value *Condition = BI->getCondition();
165 Value *LeftVal, *RightVal;
166 CmpInst::Predicate Pred;
167 if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal))))
168 continue;
169
170 const SCEV *LeftSCEV = SE.getSCEV(LeftVal);
171 const SCEV *RightSCEV = SE.getSCEV(RightVal);
172
173 // Do not consider predicates that are known to be true or false
174 // independently of the loop iteration.
175 if (SE.isKnownPredicate(Pred, LeftSCEV, RightSCEV) ||
176 SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), LeftSCEV,
177 RightSCEV))
178 continue;
179
180 // Check if we have a condition with one AddRec and one non AddRec
181 // expression. Normalize LeftSCEV to be the AddRec.
182 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
183 if (isa<SCEVAddRecExpr>(RightSCEV)) {
184 std::swap(LeftSCEV, RightSCEV);
185 Pred = ICmpInst::getSwappedPredicate(Pred);
186 } else
187 continue;
188 }
189
190 const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV);
191
Florian Hahnac277582018-04-18 12:29:24 +0000192 // Avoid huge SCEV computations in the loop below, make sure we only
193 // consider AddRecs of the loop we are trying to peel and avoid
194 // non-monotonic predicates, as we will not be able to simplify the loop
195 // body.
196 // FIXME: For the non-monotonic predicates ICMP_EQ and ICMP_NE we can
197 // simplify the loop, if we peel 1 additional iteration, if there
198 // is no wrapping.
199 bool Increasing;
200 if (!LeftAR->isAffine() || LeftAR->getLoop() != &L ||
201 !SE.isMonotonicPredicate(LeftAR, Pred, Increasing))
Florian Hahnfc97b612018-03-15 21:34:43 +0000202 continue;
Florian Hahnac277582018-04-18 12:29:24 +0000203 (void)Increasing;
Florian Hahnfc97b612018-03-15 21:34:43 +0000204
Florian Hahnac277582018-04-18 12:29:24 +0000205 // Check if extending the current DesiredPeelCount lets us evaluate Pred
206 // or !Pred in the loop body statically.
207 unsigned NewPeelCount = DesiredPeelCount;
208
Florian Hahnfc97b612018-03-15 21:34:43 +0000209 const SCEV *IterVal = LeftAR->evaluateAtIteration(
Florian Hahnac277582018-04-18 12:29:24 +0000210 SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE);
Florian Hahnfc97b612018-03-15 21:34:43 +0000211
212 // If the original condition is not known, get the negated predicate
213 // (which holds on the else branch) and check if it is known. This allows
214 // us to peel of iterations that make the original condition false.
215 if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV))
216 Pred = ICmpInst::getInversePredicate(Pred);
217
218 const SCEV *Step = LeftAR->getStepRecurrence(SE);
Florian Hahnac277582018-04-18 12:29:24 +0000219 while (NewPeelCount < MaxPeelCount &&
Florian Hahnfc97b612018-03-15 21:34:43 +0000220 SE.isKnownPredicate(Pred, IterVal, RightSCEV)) {
221 IterVal = SE.getAddExpr(IterVal, Step);
Florian Hahnac277582018-04-18 12:29:24 +0000222 NewPeelCount++;
Florian Hahnfc97b612018-03-15 21:34:43 +0000223 }
Florian Hahnac277582018-04-18 12:29:24 +0000224
225 // Only peel the loop if the monotonic predicate !Pred becomes known in the
226 // first iteration of the loop body after peeling.
227 if (NewPeelCount > DesiredPeelCount &&
228 SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal,
229 RightSCEV))
230 DesiredPeelCount = NewPeelCount;
Florian Hahnfc97b612018-03-15 21:34:43 +0000231 }
232
233 return DesiredPeelCount;
234}
235
Michael Kupersteinb151a642016-11-30 21:13:57 +0000236// Return the number of iterations we want to peel off.
237void llvm::computePeelCount(Loop *L, unsigned LoopSize,
Sanjoy Daseed71b92017-03-03 18:19:10 +0000238 TargetTransformInfo::UnrollingPreferences &UP,
Florian Hahnfc97b612018-03-15 21:34:43 +0000239 unsigned &TripCount, ScalarEvolution &SE) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000240 assert(LoopSize > 0 && "Zero loop size is not allowed!");
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +0000241 // Save the UP.PeelCount value set by the target in
242 // TTI.getUnrollingPreferences or by the flag -unroll-peel-count.
243 unsigned TargetPeelCount = UP.PeelCount;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000244 UP.PeelCount = 0;
245 if (!canPeel(L))
246 return;
247
248 // Only try to peel innermost loops.
249 if (!L->empty())
250 return;
251
Chad Rosier45735b82018-04-06 13:57:21 +0000252 // If the user provided a peel count, use that.
253 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
254 if (UserPeelCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000255 LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
256 << " iterations.\n");
Chad Rosier45735b82018-04-06 13:57:21 +0000257 UP.PeelCount = UnrollForcePeelCount;
258 return;
259 }
260
261 // Skip peeling if it's disabled.
262 if (!UP.AllowPeeling)
263 return;
264
Max Kazantsev751579c2017-04-17 09:52:02 +0000265 // Here we try to get rid of Phis which become invariants after 1, 2, ..., N
266 // iterations of the loop. For this we compute the number for iterations after
267 // which every Phi is guaranteed to become an invariant, and try to peel the
268 // maximum number of iterations among these values, thus turning all those
269 // Phis into invariants.
Max Kazantsev8ed6b662017-04-17 05:38:28 +0000270 // First, check that we can peel at least one iteration.
271 if (2 * LoopSize <= UP.Threshold && UnrollPeelMaxCount > 0) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000272 // Store the pre-calculated values here.
273 SmallDenseMap<PHINode *, unsigned> IterationsToInvariance;
274 // Now go through all Phis to calculate their the number of iterations they
275 // need to become invariants.
Ikhlas Ajbarb7322e82018-04-03 03:39:43 +0000276 // Start the max computation with the UP.PeelCount value set by the target
277 // in TTI.getUnrollingPreferences or by the flag -unroll-peel-count.
278 unsigned DesiredPeelCount = TargetPeelCount;
Sanjoy Das30c35382017-03-07 06:03:15 +0000279 BasicBlock *BackEdge = L->getLoopLatch();
280 assert(BackEdge && "Loop is not in simplified form?");
Max Kazantsev751579c2017-04-17 09:52:02 +0000281 for (auto BI = L->getHeader()->begin(); isa<PHINode>(&*BI); ++BI) {
282 PHINode *Phi = cast<PHINode>(&*BI);
283 unsigned ToInvariance = calculateIterationsToInvariance(
284 Phi, L, BackEdge, IterationsToInvariance);
285 if (ToInvariance != InfiniteIterationsToInvariance)
286 DesiredPeelCount = std::max(DesiredPeelCount, ToInvariance);
Sanjoy Das664c9252017-03-03 18:19:15 +0000287 }
Florian Hahnfc97b612018-03-15 21:34:43 +0000288
289 // Pay respect to limitations implied by loop size and the max peel count.
290 unsigned MaxPeelCount = UnrollPeelMaxCount;
291 MaxPeelCount = std::min(MaxPeelCount, UP.Threshold / LoopSize - 1);
292
293 DesiredPeelCount = std::max(DesiredPeelCount,
294 countToEliminateCompares(*L, MaxPeelCount, SE));
295
Max Kazantsev751579c2017-04-17 09:52:02 +0000296 if (DesiredPeelCount > 0) {
Max Kazantsev751579c2017-04-17 09:52:02 +0000297 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount);
298 // Consider max peel count limitation.
299 assert(DesiredPeelCount > 0 && "Wrong loop size estimation?");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000300 LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount
301 << " iteration(s) to turn"
302 << " some Phis into invariants.\n");
Max Kazantsev751579c2017-04-17 09:52:02 +0000303 UP.PeelCount = DesiredPeelCount;
Sanjoy Das664c9252017-03-03 18:19:15 +0000304 return;
305 }
306 }
307
Sanjoy Daseed71b92017-03-03 18:19:10 +0000308 // Bail if we know the statically calculated trip count.
309 // In this case we rather prefer partial unrolling.
310 if (TripCount)
311 return;
312
Michael Kupersteinb151a642016-11-30 21:13:57 +0000313 // If we don't know the trip count, but have reason to believe the average
314 // trip count is low, peeling should be beneficial, since we will usually
315 // hit the peeled section.
316 // We only do this in the presence of profile information, since otherwise
317 // our estimates of the trip count are not reliable enough.
Chad Rosier45735b82018-04-06 13:57:21 +0000318 if (L->getHeader()->getParent()->hasProfileData()) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000319 Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L);
320 if (!PeelCount)
321 return;
322
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000323 LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount
324 << "\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000325
326 if (*PeelCount) {
327 if ((*PeelCount <= UnrollPeelMaxCount) &&
328 (LoopSize * (*PeelCount + 1) <= UP.Threshold)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000329 LLVM_DEBUG(dbgs() << "Peeling first " << *PeelCount
330 << " iterations.\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000331 UP.PeelCount = *PeelCount;
332 return;
333 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000334 LLVM_DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n");
335 LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
336 LLVM_DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1)
337 << "\n");
338 LLVM_DEBUG(dbgs() << "Max peel cost: " << UP.Threshold << "\n");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000339 }
340 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000341}
342
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000343/// Update the branch weights of the latch of a peeled-off loop
Michael Kupersteinb151a642016-11-30 21:13:57 +0000344/// iteration.
345/// This sets the branch weights for the latch of the recently peeled off loop
Fangrui Songf78650a2018-07-30 19:41:25 +0000346/// iteration correctly.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000347/// Our goal is to make sure that:
348/// a) The total weight of all the copies of the loop body is preserved.
349/// b) The total weight of the loop exit is preserved.
350/// c) The body weight is reasonably distributed between the peeled iterations.
351///
352/// \param Header The copy of the header block that belongs to next iteration.
353/// \param LatchBR The copy of the latch branch that belongs to this iteration.
354/// \param IterNumber The serial number of the iteration that was just
355/// peeled off.
356/// \param AvgIters The average number of iterations we expect the loop to have.
357/// \param[in,out] PeeledHeaderWeight The total number of dynamic loop
358/// iterations that are unaccounted for. As an input, it represents the number
359/// of times we expect to enter the header of the iteration currently being
360/// peeled off. The output is the number of times we expect to enter the
361/// header of the next iteration.
362static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
363 unsigned IterNumber, unsigned AvgIters,
364 uint64_t &PeeledHeaderWeight) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000365 // FIXME: Pick a more realistic distribution.
366 // Currently the proportion of weight we assign to the fall-through
367 // side of the branch drops linearly with the iteration number, and we use
368 // a 0.9 fudge factor to make the drop-off less sharp...
369 if (PeeledHeaderWeight) {
370 uint64_t FallThruWeight =
371 PeeledHeaderWeight * ((float)(AvgIters - IterNumber) / AvgIters * 0.9);
372 uint64_t ExitWeight = PeeledHeaderWeight - FallThruWeight;
373 PeeledHeaderWeight -= ExitWeight;
374
375 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
376 MDBuilder MDB(LatchBR->getContext());
377 MDNode *WeightNode =
378 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThruWeight)
379 : MDB.createBranchWeights(FallThruWeight, ExitWeight);
380 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
381 }
382}
383
Serguei Katkovc22e7722019-07-03 05:59:23 +0000384/// Initialize the weights.
385///
386/// \param Header The header block.
387/// \param LatchBR The latch branch.
388/// \param AvgIters The average number of iterations we expect the loop to have.
Serguei Katkov6d8813a2019-07-04 05:10:14 +0000389/// \param[out] ExitWeight The # of times the edge from Latch to Exit is taken.
390/// \param[out] CurHeaderWeight The # of times the header is executed.
Serguei Katkovc22e7722019-07-03 05:59:23 +0000391static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
392 unsigned AvgIters, uint64_t &ExitWeight,
393 uint64_t &CurHeaderWeight) {
394 uint64_t TrueWeight, FalseWeight;
395 if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight))
396 return;
397 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1;
398 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
399 // The # of times the loop body executes is the sum of the exit block
Serguei Katkov6d8813a2019-07-04 05:10:14 +0000400 // is taken and the # of times the backedges are taken.
Serguei Katkovc22e7722019-07-03 05:59:23 +0000401 CurHeaderWeight = TrueWeight + FalseWeight;
402}
403
404/// Update the weights of original Latch block after peeling off all iterations.
405///
406/// \param Header The header block.
407/// \param LatchBR The latch branch.
408/// \param ExitWeight The weight of the edge from Latch to Exit block.
409/// \param CurHeaderWeight The # of time the header is executed.
410static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
411 uint64_t ExitWeight, uint64_t CurHeaderWeight) {
412 // Adjust the branch weights on the loop exit.
413 if (ExitWeight) {
414 // The backedge count is the difference of current header weight and
415 // current loop exit weight. If the current header weight is smaller than
416 // the current loop exit weight, we mark the loop backedge weight as 1.
417 uint64_t BackEdgeWeight = 0;
418 if (ExitWeight < CurHeaderWeight)
419 BackEdgeWeight = CurHeaderWeight - ExitWeight;
420 else
421 BackEdgeWeight = 1;
422 MDBuilder MDB(LatchBR->getContext());
423 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1;
424 MDNode *WeightNode =
425 HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
426 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
427 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
428 }
429}
430
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000431/// Clones the body of the loop L, putting it between \p InsertTop and \p
Michael Kupersteinb151a642016-11-30 21:13:57 +0000432/// InsertBot.
433/// \param IterNumber The serial number of the iteration currently being
434/// peeled off.
435/// \param Exit The exit block of the original loop.
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000436/// \param[out] NewBlocks A list of the blocks in the newly created clone
Michael Kupersteinb151a642016-11-30 21:13:57 +0000437/// \param[out] VMap The value map between the loop and the new clone.
438/// \param LoopBlocks A helper for DFS-traversal of the loop.
439/// \param LVMap A value-map that maps instructions from the original loop to
440/// instructions in the last peeled-off iteration.
441static void cloneLoopBlocks(Loop *L, unsigned IterNumber, BasicBlock *InsertTop,
442 BasicBlock *InsertBot, BasicBlock *Exit,
443 SmallVectorImpl<BasicBlock *> &NewBlocks,
444 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000445 ValueToValueMapTy &LVMap, DominatorTree *DT,
446 LoopInfo *LI) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000447 BasicBlock *Header = L->getHeader();
448 BasicBlock *Latch = L->getLoopLatch();
449 BasicBlock *PreHeader = L->getLoopPreheader();
450
451 Function *F = Header->getParent();
452 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
453 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
454 Loop *ParentLoop = L->getParentLoop();
455
456 // For each block in the original loop, create a new copy,
457 // and update the value map with the newly created values.
458 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
459 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
460 NewBlocks.push_back(NewBB);
461
462 if (ParentLoop)
463 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
464
465 VMap[*BB] = NewBB;
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000466
467 // If dominator tree is available, insert nodes to represent cloned blocks.
468 if (DT) {
469 if (Header == *BB)
470 DT->addNewBlock(NewBB, InsertTop);
471 else {
472 DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
473 // VMap must contain entry for IDom, as the iteration order is RPO.
474 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
475 }
476 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000477 }
478
479 // Hook-up the control flow for the newly inserted blocks.
480 // The new header is hooked up directly to the "top", which is either
481 // the original loop preheader (for the first iteration) or the previous
482 // iteration's exiting block (for every other iteration)
483 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
484
485 // Similarly, for the latch:
486 // The original exiting edge is still hooked up to the loop exit.
487 // The backedge now goes to the "bottom", which is either the loop's real
488 // header (for the last peeled iteration) or the copied header of the next
489 // iteration (for every other iteration)
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000490 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
491 BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000492 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
493 LatchBR->setSuccessor(HeaderIdx, InsertBot);
494 LatchBR->setSuccessor(1 - HeaderIdx, Exit);
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000495 if (DT)
496 DT->changeImmediateDominator(InsertBot, NewLatch);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000497
498 // The new copy of the loop body starts with a bunch of PHI nodes
499 // that pick an incoming value from either the preheader, or the previous
500 // loop iteration. Since this copy is no longer part of the loop, we
501 // resolve this statically:
502 // For the first iteration, we use the value from the preheader directly.
503 // For any other iteration, we replace the phi with the value generated by
504 // the immediately preceding clone of the loop body (which represents
505 // the previous iteration).
506 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
507 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
508 if (IterNumber == 0) {
509 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
510 } else {
511 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
512 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
513 if (LatchInst && L->contains(LatchInst))
514 VMap[&*I] = LVMap[LatchInst];
515 else
516 VMap[&*I] = LatchVal;
517 }
518 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
519 }
520
521 // Fix up the outgoing values - we need to add a value for the iteration
522 // we've just created. Note that this must happen *after* the incoming
523 // values are adjusted, since the value going out of the latch may also be
524 // a value coming into the header.
525 for (BasicBlock::iterator I = Exit->begin(); isa<PHINode>(I); ++I) {
526 PHINode *PHI = cast<PHINode>(I);
527 Value *LatchVal = PHI->getIncomingValueForBlock(Latch);
528 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
529 if (LatchInst && L->contains(LatchInst))
530 LatchVal = VMap[LatchVal];
531 PHI->addIncoming(LatchVal, cast<BasicBlock>(VMap[Latch]));
532 }
533
534 // LastValueMap is updated with the values for the current loop
535 // which are used the next time this function is called.
536 for (const auto &KV : VMap)
537 LVMap[KV.first] = KV.second;
538}
539
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000540/// Peel off the first \p PeelCount iterations of loop \p L.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000541///
542/// Note that this does not peel them off as a single straight-line block.
543/// Rather, each iteration is peeled off separately, and needs to check the
544/// exit condition.
545/// For loops that dynamically execute \p PeelCount iterations or less
546/// this provides a benefit, since the peeled off iterations, which account
547/// for the bulk of dynamic execution, can be further simplified by scalar
548/// optimizations.
549bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
550 ScalarEvolution *SE, DominatorTree *DT,
Eli Friedman0a217452017-01-18 23:26:37 +0000551 AssumptionCache *AC, bool PreserveLCSSA) {
Max Kazantsevb1ad66f2018-03-27 09:40:51 +0000552 assert(PeelCount > 0 && "Attempt to peel out zero iterations?");
553 assert(canPeel(L) && "Attempt to peel a loop which is not peelable?");
Michael Kupersteinb151a642016-11-30 21:13:57 +0000554
555 LoopBlocksDFS LoopBlocks(L);
556 LoopBlocks.perform(LI);
557
558 BasicBlock *Header = L->getHeader();
559 BasicBlock *PreHeader = L->getLoopPreheader();
560 BasicBlock *Latch = L->getLoopLatch();
561 BasicBlock *Exit = L->getUniqueExitBlock();
562
563 Function *F = Header->getParent();
564
565 // Set up all the necessary basic blocks. It is convenient to split the
566 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
567 // body, and a new preheader for the "real" loop.
568
569 // Peeling the first iteration transforms.
570 //
571 // PreHeader:
572 // ...
573 // Header:
574 // LoopBody
575 // If (cond) goto Header
576 // Exit:
577 //
578 // into
579 //
580 // InsertTop:
581 // LoopBody
582 // If (!cond) goto Exit
583 // InsertBot:
584 // NewPreHeader:
585 // ...
586 // Header:
587 // LoopBody
588 // If (cond) goto Header
589 // Exit:
590 //
591 // Each following iteration will split the current bottom anchor in two,
592 // and put the new copy of the loop body between these two blocks. That is,
Fangrui Songf78650a2018-07-30 19:41:25 +0000593 // after peeling another iteration from the example above, we'll split
Michael Kupersteinb151a642016-11-30 21:13:57 +0000594 // InsertBot, and get:
595 //
596 // InsertTop:
597 // LoopBody
598 // If (!cond) goto Exit
599 // InsertBot:
600 // LoopBody
601 // If (!cond) goto Exit
602 // InsertBot.next:
603 // NewPreHeader:
604 // ...
605 // Header:
606 // LoopBody
607 // If (cond) goto Header
608 // Exit:
609
610 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI);
611 BasicBlock *InsertBot =
612 SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI);
613 BasicBlock *NewPreHeader =
614 SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
615
616 InsertTop->setName(Header->getName() + ".peel.begin");
617 InsertBot->setName(Header->getName() + ".peel.next");
618 NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
619
620 ValueToValueMapTy LVMap;
621
622 // If we have branch weight information, we'll want to update it for the
623 // newly created branches.
624 BranchInst *LatchBR =
625 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
Xin Tong29402312017-01-02 20:27:23 +0000626 uint64_t ExitWeight = 0, CurHeaderWeight = 0;
Serguei Katkovc22e7722019-07-03 05:59:23 +0000627 initBranchWeights(Header, LatchBR, PeelCount, ExitWeight, CurHeaderWeight);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000628
629 // For each peeled-off iteration, make a copy of the loop.
630 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
631 SmallVector<BasicBlock *, 8> NewBlocks;
632 ValueToValueMapTy VMap;
633
Xin Tong29402312017-01-02 20:27:23 +0000634 // Subtract the exit weight from the current header weight -- the exit
635 // weight is exactly the weight of the previous iteration's header.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000636 // FIXME: due to the way the distribution is constructed, we need a
637 // guard here to make sure we don't end up with non-positive weights.
Xin Tong29402312017-01-02 20:27:23 +0000638 if (ExitWeight < CurHeaderWeight)
639 CurHeaderWeight -= ExitWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000640 else
Xin Tong29402312017-01-02 20:27:23 +0000641 CurHeaderWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000642
643 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, Exit,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000644 NewBlocks, LoopBlocks, VMap, LVMap, DT, LI);
Serge Pavlovb71bb802017-03-26 16:46:53 +0000645
646 // Remap to use values from the current iteration instead of the
647 // previous one.
648 remapInstructionsInBlocks(NewBlocks, VMap);
649
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000650 if (DT) {
651 // Latches of the cloned loops dominate over the loop exit, so idom of the
652 // latter is the first cloned loop body, as original PreHeader dominates
653 // the original loop body.
654 if (Iter == 0)
655 DT->changeImmediateDominator(Exit, cast<BasicBlock>(LVMap[Latch]));
Eli Friedman3af2f532018-12-21 01:28:49 +0000656#ifdef EXPENSIVE_CHECKS
David Green7c35de12018-02-28 11:00:08 +0000657 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
Eli Friedman3af2f532018-12-21 01:28:49 +0000658#endif
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000659 }
660
Vyacheslav Zakharine06831a2018-09-26 01:03:21 +0000661 auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]);
662 updateBranchWeights(InsertBot, LatchBRCopy, Iter,
Michael Kupersteinb151a642016-11-30 21:13:57 +0000663 PeelCount, ExitWeight);
Vyacheslav Zakharine06831a2018-09-26 01:03:21 +0000664 // Remove Loop metadata from the latch branch instruction
665 // because it is not the Loop's latch branch anymore.
666 LatchBRCopy->setMetadata(LLVMContext::MD_loop, nullptr);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000667
668 InsertTop = InsertBot;
669 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
670 InsertBot->setName(Header->getName() + ".peel.next");
671
672 F->getBasicBlockList().splice(InsertTop->getIterator(),
673 F->getBasicBlockList(),
674 NewBlocks[0]->getIterator(), F->end());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000675 }
676
677 // Now adjust the phi nodes in the loop header to get their initial values
678 // from the last peeled-off iteration instead of the preheader.
679 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
680 PHINode *PHI = cast<PHINode>(I);
681 Value *NewVal = PHI->getIncomingValueForBlock(Latch);
682 Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
683 if (LatchInst && L->contains(LatchInst))
684 NewVal = LVMap[LatchInst];
685
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000686 PHI->setIncomingValueForBlock(NewPreHeader, NewVal);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000687 }
688
Serguei Katkovc22e7722019-07-03 05:59:23 +0000689 fixupBranchWeights(Header, LatchBR, ExitWeight, CurHeaderWeight);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000690
Florian Hahn6ab83b72019-02-14 13:59:39 +0000691 if (Loop *ParentLoop = L->getParentLoop())
692 L = ParentLoop;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000693
Florian Hahn6ab83b72019-02-14 13:59:39 +0000694 // We modified the loop, update SE.
695 SE->forgetTopmostLoop(L);
696
697 // FIXME: Incrementally update loop-simplify
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000698 simplifyLoop(L, DT, LI, SE, AC, nullptr, PreserveLCSSA);
Eli Friedman0a217452017-01-18 23:26:37 +0000699
Michael Kupersteinb151a642016-11-30 21:13:57 +0000700 NumPeeled++;
701
702 return true;
703}