blob: b8147fcb697fbb51f47ddaa41c03d6ddb593b7e3 [file] [log] [blame]
Michael Kupersteinb151a642016-11-30 21:13:57 +00001//===-- UnrollLoopPeel.cpp - Loop peeling utilities -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements some loop unrolling utilities for peeling loops
11// with dynamically inferred (from PGO) trip counts. See LoopUnroll.cpp for
12// unrolling loops with compile-time constant trip counts.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/LoopIterator.h"
18#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/ScalarEvolution.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Dominators.h"
23#include "llvm/IR/MDBuilder.h"
24#include "llvm/IR/Metadata.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Scalar.h"
29#include "llvm/Transforms/Utils/BasicBlockUtils.h"
30#include "llvm/Transforms/Utils/Cloning.h"
Eli Friedman0a217452017-01-18 23:26:37 +000031#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000032#include "llvm/Transforms/Utils/LoopUtils.h"
33#include "llvm/Transforms/Utils/UnrollLoop.h"
34#include <algorithm>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "loop-unroll"
39STATISTIC(NumPeeled, "Number of loops peeled");
40
41static cl::opt<unsigned> UnrollPeelMaxCount(
42 "unroll-peel-max-count", cl::init(7), cl::Hidden,
43 cl::desc("Max average trip count which will cause loop peeling."));
44
45static cl::opt<unsigned> UnrollForcePeelCount(
46 "unroll-force-peel-count", cl::init(0), cl::Hidden,
47 cl::desc("Force a peel count regardless of profiling information."));
48
49// Check whether we are capable of peeling this loop.
50static bool canPeel(Loop *L) {
51 // Make sure the loop is in simplified form
52 if (!L->isLoopSimplifyForm())
53 return false;
54
55 // Only peel loops that contain a single exit
56 if (!L->getExitingBlock() || !L->getUniqueExitBlock())
57 return false;
58
59 return true;
60}
61
62// Return the number of iterations we want to peel off.
63void llvm::computePeelCount(Loop *L, unsigned LoopSize,
Sanjoy Daseed71b92017-03-03 18:19:10 +000064 TargetTransformInfo::UnrollingPreferences &UP,
65 unsigned &TripCount) {
Michael Kupersteinb151a642016-11-30 21:13:57 +000066 UP.PeelCount = 0;
67 if (!canPeel(L))
68 return;
69
70 // Only try to peel innermost loops.
71 if (!L->empty())
72 return;
73
Sanjoy Das664c9252017-03-03 18:19:15 +000074 // Try to find a Phi node that has the same loop invariant as an input from
75 // its only back edge. If there is such Phi, peeling 1 iteration from the
76 // loop is profitable, because starting from 2nd iteration we will have an
77 // invariant instead of this Phi.
Sanjoy Das30c35382017-03-07 06:03:15 +000078 if (LoopSize <= UP.Threshold) {
79 BasicBlock *BackEdge = L->getLoopLatch();
80 assert(BackEdge && "Loop is not in simplified form?");
Sanjoy Das664c9252017-03-03 18:19:15 +000081 BasicBlock *Header = L->getHeader();
82 // Iterate over Phis to find one with invariant input on back edge.
83 bool FoundCandidate = false;
84 PHINode *Phi;
Sanjoy Das0a4ec552017-03-03 18:53:09 +000085 for (auto BI = Header->begin(); isa<PHINode>(&*BI); ++BI) {
86 Phi = cast<PHINode>(&*BI);
Sanjoy Das664c9252017-03-03 18:19:15 +000087 Value *Input = Phi->getIncomingValueForBlock(BackEdge);
88 if (L->isLoopInvariant(Input)) {
89 FoundCandidate = true;
90 break;
91 }
92 }
93 if (FoundCandidate) {
94 DEBUG(dbgs() << "Peel one iteration to get rid of " << *Phi
95 << " because starting from 2nd iteration it is always"
96 << " an invariant\n");
97 UP.PeelCount = 1;
98 return;
99 }
100 }
101
Sanjoy Daseed71b92017-03-03 18:19:10 +0000102 // Bail if we know the statically calculated trip count.
103 // In this case we rather prefer partial unrolling.
104 if (TripCount)
105 return;
106
Michael Kupersteinb151a642016-11-30 21:13:57 +0000107 // If the user provided a peel count, use that.
108 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
109 if (UserPeelCount) {
110 DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
111 << " iterations.\n");
112 UP.PeelCount = UnrollForcePeelCount;
113 return;
114 }
115
116 // If we don't know the trip count, but have reason to believe the average
117 // trip count is low, peeling should be beneficial, since we will usually
118 // hit the peeled section.
119 // We only do this in the presence of profile information, since otherwise
120 // our estimates of the trip count are not reliable enough.
121 if (UP.AllowPeeling && L->getHeader()->getParent()->getEntryCount()) {
122 Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L);
123 if (!PeelCount)
124 return;
125
126 DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount
127 << "\n");
128
129 if (*PeelCount) {
130 if ((*PeelCount <= UnrollPeelMaxCount) &&
131 (LoopSize * (*PeelCount + 1) <= UP.Threshold)) {
132 DEBUG(dbgs() << "Peeling first " << *PeelCount << " iterations.\n");
133 UP.PeelCount = *PeelCount;
134 return;
135 }
136 DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n");
137 DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
138 DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1) << "\n");
139 DEBUG(dbgs() << "Max peel cost: " << UP.Threshold << "\n");
140 }
141 }
142
143 return;
144}
145
146/// \brief Update the branch weights of the latch of a peeled-off loop
147/// iteration.
148/// This sets the branch weights for the latch of the recently peeled off loop
149/// iteration correctly.
150/// Our goal is to make sure that:
151/// a) The total weight of all the copies of the loop body is preserved.
152/// b) The total weight of the loop exit is preserved.
153/// c) The body weight is reasonably distributed between the peeled iterations.
154///
155/// \param Header The copy of the header block that belongs to next iteration.
156/// \param LatchBR The copy of the latch branch that belongs to this iteration.
157/// \param IterNumber The serial number of the iteration that was just
158/// peeled off.
159/// \param AvgIters The average number of iterations we expect the loop to have.
160/// \param[in,out] PeeledHeaderWeight The total number of dynamic loop
161/// iterations that are unaccounted for. As an input, it represents the number
162/// of times we expect to enter the header of the iteration currently being
163/// peeled off. The output is the number of times we expect to enter the
164/// header of the next iteration.
165static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
166 unsigned IterNumber, unsigned AvgIters,
167 uint64_t &PeeledHeaderWeight) {
168
169 // FIXME: Pick a more realistic distribution.
170 // Currently the proportion of weight we assign to the fall-through
171 // side of the branch drops linearly with the iteration number, and we use
172 // a 0.9 fudge factor to make the drop-off less sharp...
173 if (PeeledHeaderWeight) {
174 uint64_t FallThruWeight =
175 PeeledHeaderWeight * ((float)(AvgIters - IterNumber) / AvgIters * 0.9);
176 uint64_t ExitWeight = PeeledHeaderWeight - FallThruWeight;
177 PeeledHeaderWeight -= ExitWeight;
178
179 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
180 MDBuilder MDB(LatchBR->getContext());
181 MDNode *WeightNode =
182 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThruWeight)
183 : MDB.createBranchWeights(FallThruWeight, ExitWeight);
184 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
185 }
186}
187
188/// \brief Clones the body of the loop L, putting it between \p InsertTop and \p
189/// InsertBot.
190/// \param IterNumber The serial number of the iteration currently being
191/// peeled off.
192/// \param Exit The exit block of the original loop.
193/// \param[out] NewBlocks A list of the the blocks in the newly created clone
194/// \param[out] VMap The value map between the loop and the new clone.
195/// \param LoopBlocks A helper for DFS-traversal of the loop.
196/// \param LVMap A value-map that maps instructions from the original loop to
197/// instructions in the last peeled-off iteration.
198static void cloneLoopBlocks(Loop *L, unsigned IterNumber, BasicBlock *InsertTop,
199 BasicBlock *InsertBot, BasicBlock *Exit,
200 SmallVectorImpl<BasicBlock *> &NewBlocks,
201 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000202 ValueToValueMapTy &LVMap, DominatorTree *DT,
203 LoopInfo *LI) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000204
205 BasicBlock *Header = L->getHeader();
206 BasicBlock *Latch = L->getLoopLatch();
207 BasicBlock *PreHeader = L->getLoopPreheader();
208
209 Function *F = Header->getParent();
210 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
211 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
212 Loop *ParentLoop = L->getParentLoop();
213
214 // For each block in the original loop, create a new copy,
215 // and update the value map with the newly created values.
216 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
217 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
218 NewBlocks.push_back(NewBB);
219
220 if (ParentLoop)
221 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
222
223 VMap[*BB] = NewBB;
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000224
225 // If dominator tree is available, insert nodes to represent cloned blocks.
226 if (DT) {
227 if (Header == *BB)
228 DT->addNewBlock(NewBB, InsertTop);
229 else {
230 DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
231 // VMap must contain entry for IDom, as the iteration order is RPO.
232 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
233 }
234 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000235 }
236
237 // Hook-up the control flow for the newly inserted blocks.
238 // The new header is hooked up directly to the "top", which is either
239 // the original loop preheader (for the first iteration) or the previous
240 // iteration's exiting block (for every other iteration)
241 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
242
243 // Similarly, for the latch:
244 // The original exiting edge is still hooked up to the loop exit.
245 // The backedge now goes to the "bottom", which is either the loop's real
246 // header (for the last peeled iteration) or the copied header of the next
247 // iteration (for every other iteration)
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000248 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
249 BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000250 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
251 LatchBR->setSuccessor(HeaderIdx, InsertBot);
252 LatchBR->setSuccessor(1 - HeaderIdx, Exit);
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000253 if (DT)
254 DT->changeImmediateDominator(InsertBot, NewLatch);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000255
256 // The new copy of the loop body starts with a bunch of PHI nodes
257 // that pick an incoming value from either the preheader, or the previous
258 // loop iteration. Since this copy is no longer part of the loop, we
259 // resolve this statically:
260 // For the first iteration, we use the value from the preheader directly.
261 // For any other iteration, we replace the phi with the value generated by
262 // the immediately preceding clone of the loop body (which represents
263 // the previous iteration).
264 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
265 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
266 if (IterNumber == 0) {
267 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
268 } else {
269 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
270 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
271 if (LatchInst && L->contains(LatchInst))
272 VMap[&*I] = LVMap[LatchInst];
273 else
274 VMap[&*I] = LatchVal;
275 }
276 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
277 }
278
279 // Fix up the outgoing values - we need to add a value for the iteration
280 // we've just created. Note that this must happen *after* the incoming
281 // values are adjusted, since the value going out of the latch may also be
282 // a value coming into the header.
283 for (BasicBlock::iterator I = Exit->begin(); isa<PHINode>(I); ++I) {
284 PHINode *PHI = cast<PHINode>(I);
285 Value *LatchVal = PHI->getIncomingValueForBlock(Latch);
286 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
287 if (LatchInst && L->contains(LatchInst))
288 LatchVal = VMap[LatchVal];
289 PHI->addIncoming(LatchVal, cast<BasicBlock>(VMap[Latch]));
290 }
291
292 // LastValueMap is updated with the values for the current loop
293 // which are used the next time this function is called.
294 for (const auto &KV : VMap)
295 LVMap[KV.first] = KV.second;
296}
297
298/// \brief Peel off the first \p PeelCount iterations of loop \p L.
299///
300/// Note that this does not peel them off as a single straight-line block.
301/// Rather, each iteration is peeled off separately, and needs to check the
302/// exit condition.
303/// For loops that dynamically execute \p PeelCount iterations or less
304/// this provides a benefit, since the peeled off iterations, which account
305/// for the bulk of dynamic execution, can be further simplified by scalar
306/// optimizations.
307bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
308 ScalarEvolution *SE, DominatorTree *DT,
Eli Friedman0a217452017-01-18 23:26:37 +0000309 AssumptionCache *AC, bool PreserveLCSSA) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000310 if (!canPeel(L))
311 return false;
312
313 LoopBlocksDFS LoopBlocks(L);
314 LoopBlocks.perform(LI);
315
316 BasicBlock *Header = L->getHeader();
317 BasicBlock *PreHeader = L->getLoopPreheader();
318 BasicBlock *Latch = L->getLoopLatch();
319 BasicBlock *Exit = L->getUniqueExitBlock();
320
321 Function *F = Header->getParent();
322
323 // Set up all the necessary basic blocks. It is convenient to split the
324 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
325 // body, and a new preheader for the "real" loop.
326
327 // Peeling the first iteration transforms.
328 //
329 // PreHeader:
330 // ...
331 // Header:
332 // LoopBody
333 // If (cond) goto Header
334 // Exit:
335 //
336 // into
337 //
338 // InsertTop:
339 // LoopBody
340 // If (!cond) goto Exit
341 // InsertBot:
342 // NewPreHeader:
343 // ...
344 // Header:
345 // LoopBody
346 // If (cond) goto Header
347 // Exit:
348 //
349 // Each following iteration will split the current bottom anchor in two,
350 // and put the new copy of the loop body between these two blocks. That is,
351 // after peeling another iteration from the example above, we'll split
352 // InsertBot, and get:
353 //
354 // InsertTop:
355 // LoopBody
356 // If (!cond) goto Exit
357 // InsertBot:
358 // LoopBody
359 // If (!cond) goto Exit
360 // InsertBot.next:
361 // NewPreHeader:
362 // ...
363 // Header:
364 // LoopBody
365 // If (cond) goto Header
366 // Exit:
367
368 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI);
369 BasicBlock *InsertBot =
370 SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI);
371 BasicBlock *NewPreHeader =
372 SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
373
374 InsertTop->setName(Header->getName() + ".peel.begin");
375 InsertBot->setName(Header->getName() + ".peel.next");
376 NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
377
378 ValueToValueMapTy LVMap;
379
380 // If we have branch weight information, we'll want to update it for the
381 // newly created branches.
382 BranchInst *LatchBR =
383 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
384 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
385
386 uint64_t TrueWeight, FalseWeight;
Xin Tong29402312017-01-02 20:27:23 +0000387 uint64_t ExitWeight = 0, CurHeaderWeight = 0;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000388 if (LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) {
389 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
Xin Tong29402312017-01-02 20:27:23 +0000390 // The # of times the loop body executes is the sum of the exit block
391 // weight and the # of times the backedges are taken.
392 CurHeaderWeight = TrueWeight + FalseWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000393 }
394
395 // For each peeled-off iteration, make a copy of the loop.
396 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
397 SmallVector<BasicBlock *, 8> NewBlocks;
398 ValueToValueMapTy VMap;
399
Xin Tong29402312017-01-02 20:27:23 +0000400 // Subtract the exit weight from the current header weight -- the exit
401 // weight is exactly the weight of the previous iteration's header.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000402 // FIXME: due to the way the distribution is constructed, we need a
403 // guard here to make sure we don't end up with non-positive weights.
Xin Tong29402312017-01-02 20:27:23 +0000404 if (ExitWeight < CurHeaderWeight)
405 CurHeaderWeight -= ExitWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000406 else
Xin Tong29402312017-01-02 20:27:23 +0000407 CurHeaderWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000408
409 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, Exit,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000410 NewBlocks, LoopBlocks, VMap, LVMap, DT, LI);
411 if (DT) {
412 // Latches of the cloned loops dominate over the loop exit, so idom of the
413 // latter is the first cloned loop body, as original PreHeader dominates
414 // the original loop body.
415 if (Iter == 0)
416 DT->changeImmediateDominator(Exit, cast<BasicBlock>(LVMap[Latch]));
417#ifndef NDEBUG
418 if (VerifyDomInfo)
419 DT->verifyDomTree();
420#endif
421 }
422
Michael Kupersteinb151a642016-11-30 21:13:57 +0000423 updateBranchWeights(InsertBot, cast<BranchInst>(VMap[LatchBR]), Iter,
424 PeelCount, ExitWeight);
425
426 InsertTop = InsertBot;
427 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
428 InsertBot->setName(Header->getName() + ".peel.next");
429
430 F->getBasicBlockList().splice(InsertTop->getIterator(),
431 F->getBasicBlockList(),
432 NewBlocks[0]->getIterator(), F->end());
433
434 // Remap to use values from the current iteration instead of the
435 // previous one.
436 remapInstructionsInBlocks(NewBlocks, VMap);
437 }
438
439 // Now adjust the phi nodes in the loop header to get their initial values
440 // from the last peeled-off iteration instead of the preheader.
441 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
442 PHINode *PHI = cast<PHINode>(I);
443 Value *NewVal = PHI->getIncomingValueForBlock(Latch);
444 Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
445 if (LatchInst && L->contains(LatchInst))
446 NewVal = LVMap[LatchInst];
447
448 PHI->setIncomingValue(PHI->getBasicBlockIndex(NewPreHeader), NewVal);
449 }
450
451 // Adjust the branch weights on the loop exit.
452 if (ExitWeight) {
Xin Tong29402312017-01-02 20:27:23 +0000453 // The backedge count is the difference of current header weight and
454 // current loop exit weight. If the current header weight is smaller than
455 // the current loop exit weight, we mark the loop backedge weight as 1.
456 uint64_t BackEdgeWeight = 0;
457 if (ExitWeight < CurHeaderWeight)
458 BackEdgeWeight = CurHeaderWeight - ExitWeight;
459 else
460 BackEdgeWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000461 MDBuilder MDB(LatchBR->getContext());
462 MDNode *WeightNode =
463 HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
464 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
465 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
466 }
467
468 // If the loop is nested, we changed the parent loop, update SE.
Eli Friedman0a217452017-01-18 23:26:37 +0000469 if (Loop *ParentLoop = L->getParentLoop()) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000470 SE->forgetLoop(ParentLoop);
471
Eli Friedman0a217452017-01-18 23:26:37 +0000472 // FIXME: Incrementally update loop-simplify
473 simplifyLoop(ParentLoop, DT, LI, SE, AC, PreserveLCSSA);
474 } else {
475 // FIXME: Incrementally update loop-simplify
476 simplifyLoop(L, DT, LI, SE, AC, PreserveLCSSA);
477 }
478
Michael Kupersteinb151a642016-11-30 21:13:57 +0000479 NumPeeled++;
480
481 return true;
482}