1 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements some loop unrolling utilities for loops with run-time
10 // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time
13 // The functions in this file are used to generate extra code when the
14 // run-time trip count modulo the unroll factor is not 0. When this is the
15 // case, we need to generate code to execute these 'left over' iterations.
17 // The current strategy generates an if-then-else sequence prior to the
18 // unrolled loop to execute the 'left over' iterations before or after the
21 //===----------------------------------------------------------------------===//
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/LoopIterator.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/Utils.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/LoopUtils.h"
39 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
40 #include "llvm/Transforms/Utils/UnrollLoop.h"
45 #define DEBUG_TYPE "loop-unroll"
47 STATISTIC(NumRuntimeUnrolled
,
48 "Number of loops unrolled with run-time trip counts");
49 static cl::opt
<bool> UnrollRuntimeMultiExit(
50 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden
,
51 cl::desc("Allow runtime unrolling for loops with multiple exits, when "
52 "epilog is generated"));
53 static cl::opt
<bool> UnrollRuntimeOtherExitPredictable(
54 "unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden
,
55 cl::desc("Assume the non latch exit block to be predictable"));
57 /// Connect the unrolling prolog code to the original loop.
58 /// The unrolling prolog code contains code to execute the
59 /// 'extra' iterations if the run-time trip count modulo the
60 /// unroll count is non-zero.
62 /// This function performs the following:
63 /// - Create PHI nodes at prolog end block to combine values
64 /// that exit the prolog code and jump around the prolog.
65 /// - Add a PHI operand to a PHI node at the loop exit block
66 /// for values that exit the prolog and go around the loop.
67 /// - Branch around the original loop if the trip count is less
68 /// than the unroll factor.
70 static void ConnectProlog(Loop
*L
, Value
*BECount
, unsigned Count
,
71 BasicBlock
*PrologExit
,
72 BasicBlock
*OriginalLoopLatchExit
,
73 BasicBlock
*PreHeader
, BasicBlock
*NewPreHeader
,
74 ValueToValueMapTy
&VMap
, DominatorTree
*DT
,
75 LoopInfo
*LI
, bool PreserveLCSSA
) {
76 // Loop structure should be the following:
87 BasicBlock
*Latch
= L
->getLoopLatch();
88 assert(Latch
&& "Loop must have a latch");
89 BasicBlock
*PrologLatch
= cast
<BasicBlock
>(VMap
[Latch
]);
91 // Create a PHI node for each outgoing value from the original loop
92 // (which means it is an outgoing value from the prolog code too).
93 // The new PHI node is inserted in the prolog end basic block.
94 // The new PHI node value is added as an operand of a PHI node in either
95 // the loop header or the loop exit block.
96 for (BasicBlock
*Succ
: successors(Latch
)) {
97 for (PHINode
&PN
: Succ
->phis()) {
98 // Add a new PHI node to the prolog end block and add the
99 // appropriate incoming values.
100 // TODO: This code assumes that the PrologExit (or the LatchExit block for
101 // prolog loop) contains only one predecessor from the loop, i.e. the
102 // PrologLatch. When supporting multiple-exiting block loops, we can have
103 // two or more blocks that have the LatchExit as the target in the
105 PHINode
*NewPN
= PHINode::Create(PN
.getType(), 2, PN
.getName() + ".unr",
106 PrologExit
->getFirstNonPHI());
107 // Adding a value to the new PHI node from the original loop preheader.
108 // This is the value that skips all the prolog code.
109 if (L
->contains(&PN
)) {
110 // Succ is loop header.
111 NewPN
->addIncoming(PN
.getIncomingValueForBlock(NewPreHeader
),
114 // Succ is LatchExit.
115 NewPN
->addIncoming(UndefValue::get(PN
.getType()), PreHeader
);
118 Value
*V
= PN
.getIncomingValueForBlock(Latch
);
119 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
120 if (L
->contains(I
)) {
124 // Adding a value to the new PHI node from the last prolog block
126 NewPN
->addIncoming(V
, PrologLatch
);
128 // Update the existing PHI node operand with the value from the
129 // new PHI node. How this is done depends on if the existing
130 // PHI node is in the original loop block, or the exit block.
131 if (L
->contains(&PN
))
132 PN
.setIncomingValueForBlock(NewPreHeader
, NewPN
);
134 PN
.addIncoming(NewPN
, PrologExit
);
138 // Make sure that created prolog loop is in simplified form
139 SmallVector
<BasicBlock
*, 4> PrologExitPreds
;
140 Loop
*PrologLoop
= LI
->getLoopFor(PrologLatch
);
142 for (BasicBlock
*PredBB
: predecessors(PrologExit
))
143 if (PrologLoop
->contains(PredBB
))
144 PrologExitPreds
.push_back(PredBB
);
146 SplitBlockPredecessors(PrologExit
, PrologExitPreds
, ".unr-lcssa", DT
, LI
,
147 nullptr, PreserveLCSSA
);
150 // Create a branch around the original loop, which is taken if there are no
151 // iterations remaining to be executed after running the prologue.
152 Instruction
*InsertPt
= PrologExit
->getTerminator();
153 IRBuilder
<> B(InsertPt
);
155 assert(Count
!= 0 && "nonsensical Count!");
157 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
158 // This means %xtraiter is (BECount + 1) and all of the iterations of this
159 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
160 // then (BECount + 1) cannot unsigned-overflow.
162 B
.CreateICmpULT(BECount
, ConstantInt::get(BECount
->getType(), Count
- 1));
163 // Split the exit to maintain loop canonicalization guarantees
164 SmallVector
<BasicBlock
*, 4> Preds(predecessors(OriginalLoopLatchExit
));
165 SplitBlockPredecessors(OriginalLoopLatchExit
, Preds
, ".unr-lcssa", DT
, LI
,
166 nullptr, PreserveLCSSA
);
167 // Add the branch to the exit block (around the unrolled loop)
168 B
.CreateCondBr(BrLoopExit
, OriginalLoopLatchExit
, NewPreHeader
);
169 InsertPt
->eraseFromParent();
171 auto *NewDom
= DT
->findNearestCommonDominator(OriginalLoopLatchExit
,
173 DT
->changeImmediateDominator(OriginalLoopLatchExit
, NewDom
);
177 /// Connect the unrolling epilog code to the original loop.
178 /// The unrolling epilog code contains code to execute the
179 /// 'extra' iterations if the run-time trip count modulo the
180 /// unroll count is non-zero.
182 /// This function performs the following:
183 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
184 /// - Create PHI nodes at the unrolling loop exit to combine
185 /// values that exit the unrolling loop code and jump around it.
186 /// - Update PHI operands in the epilog loop by the new PHI nodes
187 /// - Branch around the epilog loop if extra iters (ModVal) is zero.
189 static void ConnectEpilog(Loop
*L
, Value
*ModVal
, BasicBlock
*NewExit
,
190 BasicBlock
*Exit
, BasicBlock
*PreHeader
,
191 BasicBlock
*EpilogPreHeader
, BasicBlock
*NewPreHeader
,
192 ValueToValueMapTy
&VMap
, DominatorTree
*DT
,
193 LoopInfo
*LI
, bool PreserveLCSSA
) {
194 BasicBlock
*Latch
= L
->getLoopLatch();
195 assert(Latch
&& "Loop must have a latch");
196 BasicBlock
*EpilogLatch
= cast
<BasicBlock
>(VMap
[Latch
]);
198 // Loop structure should be the following:
212 // Update PHI nodes at NewExit and Exit.
213 for (PHINode
&PN
: NewExit
->phis()) {
214 // PN should be used in another PHI located in Exit block as
215 // Exit was split by SplitBlockPredecessors into Exit and NewExit
216 // Basicaly it should look like:
218 // PN = PHI [I, Latch]
221 // EpilogPN = PHI [PN, EpilogPreHeader], [X, Exit2], [Y, Exit2.epil]
223 // Exits from non-latch blocks point to the original exit block and the
224 // epilogue edges have already been added.
226 // There is EpilogPreHeader incoming block instead of NewExit as
227 // NewExit was spilt 1 more time to get EpilogPreHeader.
228 assert(PN
.hasOneUse() && "The phi should have 1 use");
229 PHINode
*EpilogPN
= cast
<PHINode
>(PN
.use_begin()->getUser());
230 assert(EpilogPN
->getParent() == Exit
&& "EpilogPN should be in Exit block");
232 // Add incoming PreHeader from branch around the Loop
233 PN
.addIncoming(UndefValue::get(PN
.getType()), PreHeader
);
235 Value
*V
= PN
.getIncomingValueForBlock(Latch
);
236 Instruction
*I
= dyn_cast
<Instruction
>(V
);
237 if (I
&& L
->contains(I
))
238 // If value comes from an instruction in the loop add VMap value.
240 // For the instruction out of the loop, constant or undefined value
241 // insert value itself.
242 EpilogPN
->addIncoming(V
, EpilogLatch
);
244 assert(EpilogPN
->getBasicBlockIndex(EpilogPreHeader
) >= 0 &&
245 "EpilogPN should have EpilogPreHeader incoming block");
246 // Change EpilogPreHeader incoming block to NewExit.
247 EpilogPN
->setIncomingBlock(EpilogPN
->getBasicBlockIndex(EpilogPreHeader
),
249 // Now PHIs should look like:
251 // PN = PHI [I, Latch], [undef, PreHeader]
254 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
257 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
258 // Update corresponding PHI nodes in epilog loop.
259 for (BasicBlock
*Succ
: successors(Latch
)) {
260 // Skip this as we already updated phis in exit blocks.
261 if (!L
->contains(Succ
))
263 for (PHINode
&PN
: Succ
->phis()) {
264 // Add new PHI nodes to the loop exit block and update epilog
265 // PHIs with the new PHI values.
266 PHINode
*NewPN
= PHINode::Create(PN
.getType(), 2, PN
.getName() + ".unr",
267 NewExit
->getFirstNonPHI());
268 // Adding a value to the new PHI node from the unrolling loop preheader.
269 NewPN
->addIncoming(PN
.getIncomingValueForBlock(NewPreHeader
), PreHeader
);
270 // Adding a value to the new PHI node from the unrolling loop latch.
271 NewPN
->addIncoming(PN
.getIncomingValueForBlock(Latch
), Latch
);
273 // Update the existing PHI node operand with the value from the new PHI
274 // node. Corresponding instruction in epilog loop should be PHI.
275 PHINode
*VPN
= cast
<PHINode
>(VMap
[&PN
]);
276 VPN
->setIncomingValueForBlock(EpilogPreHeader
, NewPN
);
280 Instruction
*InsertPt
= NewExit
->getTerminator();
281 IRBuilder
<> B(InsertPt
);
282 Value
*BrLoopExit
= B
.CreateIsNotNull(ModVal
, "lcmp.mod");
283 assert(Exit
&& "Loop must have a single exit block only");
284 // Split the epilogue exit to maintain loop canonicalization guarantees
285 SmallVector
<BasicBlock
*, 4> Preds(predecessors(Exit
));
286 SplitBlockPredecessors(Exit
, Preds
, ".epilog-lcssa", DT
, LI
, nullptr,
288 // Add the branch to the exit block (around the unrolling loop)
289 B
.CreateCondBr(BrLoopExit
, EpilogPreHeader
, Exit
);
290 InsertPt
->eraseFromParent();
292 auto *NewDom
= DT
->findNearestCommonDominator(Exit
, NewExit
);
293 DT
->changeImmediateDominator(Exit
, NewDom
);
296 // Split the main loop exit to maintain canonicalization guarantees.
297 SmallVector
<BasicBlock
*, 4> NewExitPreds
{Latch
};
298 SplitBlockPredecessors(NewExit
, NewExitPreds
, ".loopexit", DT
, LI
, nullptr,
302 /// Create a clone of the blocks in a loop and connect them together.
303 /// If CreateRemainderLoop is false, loop structure will not be cloned,
304 /// otherwise a new loop will be created including all cloned blocks, and the
305 /// iterator of it switches to count NewIter down to 0.
306 /// The cloned blocks should be inserted between InsertTop and InsertBot.
307 /// If loop structure is cloned InsertTop should be new preheader, InsertBot
309 /// Return the new cloned loop that is created when CreateRemainderLoop is true.
311 CloneLoopBlocks(Loop
*L
, Value
*NewIter
, const bool CreateRemainderLoop
,
312 const bool UseEpilogRemainder
, const bool UnrollRemainder
,
313 BasicBlock
*InsertTop
,
314 BasicBlock
*InsertBot
, BasicBlock
*Preheader
,
315 std::vector
<BasicBlock
*> &NewBlocks
, LoopBlocksDFS
&LoopBlocks
,
316 ValueToValueMapTy
&VMap
, DominatorTree
*DT
, LoopInfo
*LI
) {
317 StringRef suffix
= UseEpilogRemainder
? "epil" : "prol";
318 BasicBlock
*Header
= L
->getHeader();
319 BasicBlock
*Latch
= L
->getLoopLatch();
320 Function
*F
= Header
->getParent();
321 LoopBlocksDFS::RPOIterator BlockBegin
= LoopBlocks
.beginRPO();
322 LoopBlocksDFS::RPOIterator BlockEnd
= LoopBlocks
.endRPO();
323 Loop
*ParentLoop
= L
->getParentLoop();
324 NewLoopsMap NewLoops
;
325 NewLoops
[ParentLoop
] = ParentLoop
;
326 if (!CreateRemainderLoop
)
327 NewLoops
[L
] = ParentLoop
;
329 // For each block in the original loop, create a new copy,
330 // and update the value map with the newly created values.
331 for (LoopBlocksDFS::RPOIterator BB
= BlockBegin
; BB
!= BlockEnd
; ++BB
) {
332 BasicBlock
*NewBB
= CloneBasicBlock(*BB
, VMap
, "." + suffix
, F
);
333 NewBlocks
.push_back(NewBB
);
335 // If we're unrolling the outermost loop, there's no remainder loop,
336 // and this block isn't in a nested loop, then the new block is not
337 // in any loop. Otherwise, add it to loopinfo.
338 if (CreateRemainderLoop
|| LI
->getLoopFor(*BB
) != L
|| ParentLoop
)
339 addClonedBlockToLoopInfo(*BB
, NewBB
, LI
, NewLoops
);
343 // For the first block, add a CFG connection to this newly
345 InsertTop
->getTerminator()->setSuccessor(0, NewBB
);
350 // The header is dominated by the preheader.
351 DT
->addNewBlock(NewBB
, InsertTop
);
353 // Copy information from original loop to unrolled loop.
354 BasicBlock
*IDomBB
= DT
->getNode(*BB
)->getIDom()->getBlock();
355 DT
->addNewBlock(NewBB
, cast
<BasicBlock
>(VMap
[IDomBB
]));
360 // For the last block, if CreateRemainderLoop is false, create a direct
361 // jump to InsertBot. If not, create a loop back to cloned head.
362 VMap
.erase((*BB
)->getTerminator());
363 BasicBlock
*FirstLoopBB
= cast
<BasicBlock
>(VMap
[Header
]);
364 BranchInst
*LatchBR
= cast
<BranchInst
>(NewBB
->getTerminator());
365 IRBuilder
<> Builder(LatchBR
);
366 if (!CreateRemainderLoop
) {
367 Builder
.CreateBr(InsertBot
);
369 PHINode
*NewIdx
= PHINode::Create(NewIter
->getType(), 2,
371 FirstLoopBB
->getFirstNonPHI());
373 Builder
.CreateSub(NewIdx
, ConstantInt::get(NewIdx
->getType(), 1),
374 NewIdx
->getName() + ".sub");
376 Builder
.CreateIsNotNull(IdxSub
, NewIdx
->getName() + ".cmp");
377 Builder
.CreateCondBr(IdxCmp
, FirstLoopBB
, InsertBot
);
378 NewIdx
->addIncoming(NewIter
, InsertTop
);
379 NewIdx
->addIncoming(IdxSub
, NewBB
);
381 LatchBR
->eraseFromParent();
385 // Change the incoming values to the ones defined in the preheader or
387 for (BasicBlock::iterator I
= Header
->begin(); isa
<PHINode
>(I
); ++I
) {
388 PHINode
*NewPHI
= cast
<PHINode
>(VMap
[&*I
]);
389 if (!CreateRemainderLoop
) {
390 if (UseEpilogRemainder
) {
391 unsigned idx
= NewPHI
->getBasicBlockIndex(Preheader
);
392 NewPHI
->setIncomingBlock(idx
, InsertTop
);
393 NewPHI
->removeIncomingValue(Latch
, false);
395 VMap
[&*I
] = NewPHI
->getIncomingValueForBlock(Preheader
);
396 cast
<BasicBlock
>(VMap
[Header
])->getInstList().erase(NewPHI
);
399 unsigned idx
= NewPHI
->getBasicBlockIndex(Preheader
);
400 NewPHI
->setIncomingBlock(idx
, InsertTop
);
401 BasicBlock
*NewLatch
= cast
<BasicBlock
>(VMap
[Latch
]);
402 idx
= NewPHI
->getBasicBlockIndex(Latch
);
403 Value
*InVal
= NewPHI
->getIncomingValue(idx
);
404 NewPHI
->setIncomingBlock(idx
, NewLatch
);
405 if (Value
*V
= VMap
.lookup(InVal
))
406 NewPHI
->setIncomingValue(idx
, V
);
409 if (CreateRemainderLoop
) {
410 Loop
*NewLoop
= NewLoops
[L
];
411 assert(NewLoop
&& "L should have been cloned");
412 MDNode
*LoopID
= NewLoop
->getLoopID();
414 // Only add loop metadata if the loop is not going to be completely
419 Optional
<MDNode
*> NewLoopID
= makeFollowupLoopID(
420 LoopID
, {LLVMLoopUnrollFollowupAll
, LLVMLoopUnrollFollowupRemainder
});
421 if (NewLoopID
.hasValue()) {
422 NewLoop
->setLoopID(NewLoopID
.getValue());
424 // Do not setLoopAlreadyUnrolled if loop attributes have been defined
429 // Add unroll disable metadata to disable future unrolling for this loop.
430 NewLoop
->setLoopAlreadyUnrolled();
437 /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
438 /// is populated with all the loop exit blocks other than the LatchExit block.
439 static bool canSafelyUnrollMultiExitLoop(Loop
*L
, BasicBlock
*LatchExit
,
441 bool UseEpilogRemainder
) {
443 // We currently have some correctness constrains in unrolling a multi-exit
444 // loop. Check for these below.
446 // We rely on LCSSA form being preserved when the exit blocks are transformed.
447 // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
451 // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
452 // and L is an inner loop. This is because in presence of multiple exits, the
453 // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
454 // outer loop. This is automatically handled in the prolog case, so we do not
455 // have that bug in prolog generation.
456 if (UseEpilogRemainder
&& L
->getParentLoop())
459 // All constraints have been satisfied.
463 /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
464 /// we return true only if UnrollRuntimeMultiExit is set to true.
465 static bool canProfitablyUnrollMultiExitLoop(
466 Loop
*L
, SmallVectorImpl
<BasicBlock
*> &OtherExits
, BasicBlock
*LatchExit
,
467 bool PreserveLCSSA
, bool UseEpilogRemainder
) {
470 assert(canSafelyUnrollMultiExitLoop(L
, LatchExit
, PreserveLCSSA
,
471 UseEpilogRemainder
) &&
472 "Should be safe to unroll before checking profitability!");
475 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
476 if (UnrollRuntimeMultiExit
.getNumOccurrences())
477 return UnrollRuntimeMultiExit
;
479 // TODO: We used to bail out for correctness (now fixed). Under what
480 // circumstances is this case profitable to allow?
481 if (!LatchExit
->getSinglePredecessor())
484 // The main pain point with multi-exit loop unrolling is that once unrolled,
485 // we will not be able to merge all blocks into a straight line code.
486 // There are branches within the unrolled loop that go to the OtherExits.
487 // The second point is the increase in code size, but this is true
488 // irrespective of multiple exits.
490 // Note: Both the heuristics below are coarse grained. We are essentially
491 // enabling unrolling of loops that have a single side exit other than the
492 // normal LatchExit (i.e. exiting into a deoptimize block).
493 // The heuristics considered are:
494 // 1. low number of branches in the unrolled version.
495 // 2. high predictability of these extra branches.
496 // We avoid unrolling loops that have more than two exiting blocks. This
497 // limits the total number of branches in the unrolled loop to be atmost
498 // the unroll factor (since one of the exiting blocks is the latch block).
499 SmallVector
<BasicBlock
*, 4> ExitingBlocks
;
500 L
->getExitingBlocks(ExitingBlocks
);
501 if (ExitingBlocks
.size() > 2)
504 // Allow unrolling of loops with no non latch exit blocks.
505 if (OtherExits
.size() == 0)
508 // The second heuristic is that L has one exit other than the latchexit and
509 // that exit is a deoptimize block. We know that deoptimize blocks are rarely
510 // taken, which also implies the branch leading to the deoptimize block is
511 // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we
512 // assume the other exit branch is predictable even if it has no deoptimize
514 return (OtherExits
.size() == 1 &&
515 (UnrollRuntimeOtherExitPredictable
||
516 OtherExits
[0]->getTerminatingDeoptimizeCall()));
517 // TODO: These can be fine-tuned further to consider code size or deopt states
518 // that are captured by the deoptimize exit block.
519 // Also, we can extend this to support more cases, if we actually
520 // know of kinds of multiexit loops that would benefit from unrolling.
523 // Assign the maximum possible trip count as the back edge weight for the
524 // remainder loop if the original loop comes with a branch weight.
525 static void updateLatchBranchWeightsForRemainderLoop(Loop
*OrigLoop
,
527 uint64_t UnrollFactor
) {
528 uint64_t TrueWeight
, FalseWeight
;
529 BranchInst
*LatchBR
=
530 cast
<BranchInst
>(OrigLoop
->getLoopLatch()->getTerminator());
531 if (LatchBR
->extractProfMetadata(TrueWeight
, FalseWeight
)) {
532 uint64_t ExitWeight
= LatchBR
->getSuccessor(0) == OrigLoop
->getHeader()
535 assert(UnrollFactor
> 1);
536 uint64_t BackEdgeWeight
= (UnrollFactor
- 1) * ExitWeight
;
537 BasicBlock
*Header
= RemainderLoop
->getHeader();
538 BasicBlock
*Latch
= RemainderLoop
->getLoopLatch();
539 auto *RemainderLatchBR
= cast
<BranchInst
>(Latch
->getTerminator());
540 unsigned HeaderIdx
= (RemainderLatchBR
->getSuccessor(0) == Header
? 0 : 1);
541 MDBuilder
MDB(RemainderLatchBR
->getContext());
543 HeaderIdx
? MDB
.createBranchWeights(ExitWeight
, BackEdgeWeight
)
544 : MDB
.createBranchWeights(BackEdgeWeight
, ExitWeight
);
545 RemainderLatchBR
->setMetadata(LLVMContext::MD_prof
, WeightNode
);
549 /// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
550 /// accounting for the possibility of unsigned overflow in the 2s complement
551 /// domain. Preconditions:
552 /// 1) TripCount = BECount + 1 (allowing overflow)
553 /// 2) Log2(Count) <= BitWidth(BECount)
554 static Value
*CreateTripRemainder(IRBuilder
<> &B
, Value
*BECount
,
555 Value
*TripCount
, unsigned Count
) {
556 // Note that TripCount is BECount + 1.
557 if (isPowerOf2_32(Count
))
558 // If the expression is zero, then either:
559 // 1. There are no iterations to be run in the prolog/epilog loop.
561 // 2. The addition computing TripCount overflowed.
563 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
564 // the number of iterations that remain to be run in the original loop is a
565 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
566 // precondition of this method).
567 return B
.CreateAnd(TripCount
, Count
- 1, "xtraiter");
569 // As (BECount + 1) can potentially unsigned overflow we count
570 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
571 Constant
*CountC
= ConstantInt::get(BECount
->getType(), Count
);
572 Value
*ModValTmp
= B
.CreateURem(BECount
, CountC
);
573 Value
*ModValAdd
= B
.CreateAdd(ModValTmp
,
574 ConstantInt::get(ModValTmp
->getType(), 1));
575 // At that point (BECount % Count) + 1 could be equal to Count.
576 // To handle this case we need to take mod by Count one more time.
577 return B
.CreateURem(ModValAdd
, CountC
, "xtraiter");
581 /// Insert code in the prolog/epilog code when unrolling a loop with a
582 /// run-time trip-count.
584 /// This method assumes that the loop unroll factor is total number
585 /// of loop bodies in the loop after unrolling. (Some folks refer
586 /// to the unroll factor as the number of *extra* copies added).
587 /// We assume also that the loop unroll factor is a power-of-two. So, after
588 /// unrolling the loop, the number of loop bodies executed is 2,
589 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
590 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
591 /// the switch instruction is generated.
593 /// ***Prolog case***
594 /// extraiters = tripcount % loopfactor
595 /// if (extraiters == 0) jump Loop:
598 /// extraiters -= 1 // Omitted if unroll factor is 2.
599 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
600 /// if (tripcount < loopfactor) jump End:
605 /// ***Epilog case***
606 /// extraiters = tripcount % loopfactor
607 /// if (tripcount < loopfactor) jump LoopExit:
608 /// unroll_iters = tripcount - extraiters
609 /// Loop: LoopBody; (executes unroll_iter times);
611 /// if (unroll_iter != 0) jump Loop:
613 /// if (extraiters == 0) jump EpilExit:
614 /// Epil: LoopBody; (executes extraiters times)
615 /// extraiters -= 1 // Omitted if unroll factor is 2.
616 /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
619 bool llvm::UnrollRuntimeLoopRemainder(
620 Loop
*L
, unsigned Count
, bool AllowExpensiveTripCount
,
621 bool UseEpilogRemainder
, bool UnrollRemainder
, bool ForgetAllSCEV
,
622 LoopInfo
*LI
, ScalarEvolution
*SE
, DominatorTree
*DT
, AssumptionCache
*AC
,
623 const TargetTransformInfo
*TTI
, bool PreserveLCSSA
, Loop
**ResultLoop
) {
624 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
625 LLVM_DEBUG(L
->dump());
626 LLVM_DEBUG(UseEpilogRemainder
? dbgs() << "Using epilog remainder.\n"
627 : dbgs() << "Using prolog remainder.\n");
629 // Make sure the loop is in canonical form.
630 if (!L
->isLoopSimplifyForm()) {
631 LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
635 // Guaranteed by LoopSimplifyForm.
636 BasicBlock
*Latch
= L
->getLoopLatch();
637 BasicBlock
*Header
= L
->getHeader();
639 BranchInst
*LatchBR
= cast
<BranchInst
>(Latch
->getTerminator());
641 if (!LatchBR
|| LatchBR
->isUnconditional()) {
642 // The loop-rotate pass can be helpful to avoid this in many cases.
645 << "Loop latch not terminated by a conditional branch.\n");
649 unsigned ExitIndex
= LatchBR
->getSuccessor(0) == Header
? 1 : 0;
650 BasicBlock
*LatchExit
= LatchBR
->getSuccessor(ExitIndex
);
652 if (L
->contains(LatchExit
)) {
653 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
654 // targets of the Latch be an exit block out of the loop.
657 << "One of the loop latch successors must be the exit block.\n");
661 // These are exit blocks other than the target of the latch exiting block.
662 SmallVector
<BasicBlock
*, 4> OtherExits
;
663 L
->getUniqueNonLatchExitBlocks(OtherExits
);
664 bool isMultiExitUnrollingEnabled
=
665 canSafelyUnrollMultiExitLoop(L
, LatchExit
, PreserveLCSSA
,
666 UseEpilogRemainder
) &&
667 canProfitablyUnrollMultiExitLoop(L
, OtherExits
, LatchExit
, PreserveLCSSA
,
669 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
670 if (!isMultiExitUnrollingEnabled
&&
671 (!L
->getExitingBlock() || OtherExits
.size())) {
674 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
678 // Use Scalar Evolution to compute the trip count. This allows more loops to
679 // be unrolled than relying on induction var simplification.
683 // Only unroll loops with a computable trip count, and the trip count needs
684 // to be an int value (allowing a pointer type is a TODO item).
685 // We calculate the backedge count by using getExitCount on the Latch block,
686 // which is proven to be the only exiting block in this loop. This is same as
687 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
689 const SCEV
*BECountSC
= SE
->getExitCount(L
, Latch
);
690 if (isa
<SCEVCouldNotCompute
>(BECountSC
) ||
691 !BECountSC
->getType()->isIntegerTy()) {
692 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
696 unsigned BEWidth
= cast
<IntegerType
>(BECountSC
->getType())->getBitWidth();
698 // Add 1 since the backedge count doesn't include the first loop iteration.
699 // (Note that overflow can occur, this is handled explicitly below)
700 const SCEV
*TripCountSC
=
701 SE
->getAddExpr(BECountSC
, SE
->getConstant(BECountSC
->getType(), 1));
702 if (isa
<SCEVCouldNotCompute
>(TripCountSC
)) {
703 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
707 BasicBlock
*PreHeader
= L
->getLoopPreheader();
708 BranchInst
*PreHeaderBR
= cast
<BranchInst
>(PreHeader
->getTerminator());
709 const DataLayout
&DL
= Header
->getModule()->getDataLayout();
710 SCEVExpander
Expander(*SE
, DL
, "loop-unroll");
711 if (!AllowExpensiveTripCount
&&
712 Expander
.isHighCostExpansion(TripCountSC
, L
, SCEVCheapExpansionBudget
,
714 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
718 // This constraint lets us deal with an overflowing trip count easily; see the
719 // comment on ModVal below.
720 if (Log2_32(Count
) > BEWidth
) {
723 << "Count failed constraint on overflow trip count calculation.\n");
727 // Loop structure is the following:
735 BasicBlock
*NewPreHeader
;
736 BasicBlock
*NewExit
= nullptr;
737 BasicBlock
*PrologExit
= nullptr;
738 BasicBlock
*EpilogPreHeader
= nullptr;
739 BasicBlock
*PrologPreHeader
= nullptr;
741 if (UseEpilogRemainder
) {
742 // If epilog remainder
743 // Split PreHeader to insert a branch around loop for unrolling.
744 NewPreHeader
= SplitBlock(PreHeader
, PreHeader
->getTerminator(), DT
, LI
);
745 NewPreHeader
->setName(PreHeader
->getName() + ".new");
746 // Split LatchExit to create phi nodes from branch above.
747 NewExit
= SplitBlockPredecessors(LatchExit
, {Latch
}, ".unr-lcssa", DT
, LI
,
748 nullptr, PreserveLCSSA
);
749 // NewExit gets its DebugLoc from LatchExit, which is not part of the
751 // Fix this by setting Loop's DebugLoc to NewExit.
752 auto *NewExitTerminator
= NewExit
->getTerminator();
753 NewExitTerminator
->setDebugLoc(Header
->getTerminator()->getDebugLoc());
754 // Split NewExit to insert epilog remainder loop.
755 EpilogPreHeader
= SplitBlock(NewExit
, NewExitTerminator
, DT
, LI
);
756 EpilogPreHeader
->setName(Header
->getName() + ".epil.preheader");
758 // If prolog remainder
759 // Split the original preheader twice to insert prolog remainder loop
760 PrologPreHeader
= SplitEdge(PreHeader
, Header
, DT
, LI
);
761 PrologPreHeader
->setName(Header
->getName() + ".prol.preheader");
762 PrologExit
= SplitBlock(PrologPreHeader
, PrologPreHeader
->getTerminator(),
764 PrologExit
->setName(Header
->getName() + ".prol.loopexit");
765 // Split PrologExit to get NewPreHeader.
766 NewPreHeader
= SplitBlock(PrologExit
, PrologExit
->getTerminator(), DT
, LI
);
767 NewPreHeader
->setName(PreHeader
->getName() + ".new");
769 // Loop structure should be the following:
772 // PreHeader PreHeader
773 // *NewPreHeader *PrologPreHeader
774 // Header *PrologExit
778 // *EpilogPreHeader Latch
779 // LatchExit LatchExit
781 // Calculate conditions for branch around loop for unrolling
782 // in epilog case and around prolog remainder loop in prolog case.
783 // Compute the number of extra iterations required, which is:
784 // extra iterations = run-time trip count % loop unroll factor
785 PreHeaderBR
= cast
<BranchInst
>(PreHeader
->getTerminator());
786 Value
*TripCount
= Expander
.expandCodeFor(TripCountSC
, TripCountSC
->getType(),
788 Value
*BECount
= Expander
.expandCodeFor(BECountSC
, BECountSC
->getType(),
790 IRBuilder
<> B(PreHeaderBR
);
791 Value
* const ModVal
= CreateTripRemainder(B
, BECount
, TripCount
, Count
);
794 UseEpilogRemainder
? B
.CreateICmpULT(BECount
,
795 ConstantInt::get(BECount
->getType(),
797 B
.CreateIsNotNull(ModVal
, "lcmp.mod");
798 BasicBlock
*RemainderLoop
= UseEpilogRemainder
? NewExit
: PrologPreHeader
;
799 BasicBlock
*UnrollingLoop
= UseEpilogRemainder
? NewPreHeader
: PrologExit
;
800 // Branch to either remainder (extra iterations) loop or unrolling loop.
801 B
.CreateCondBr(BranchVal
, RemainderLoop
, UnrollingLoop
);
802 PreHeaderBR
->eraseFromParent();
804 if (UseEpilogRemainder
)
805 DT
->changeImmediateDominator(NewExit
, PreHeader
);
807 DT
->changeImmediateDominator(PrologExit
, PreHeader
);
809 Function
*F
= Header
->getParent();
810 // Get an ordered list of blocks in the loop to help with the ordering of the
811 // cloned blocks in the prolog/epilog code
812 LoopBlocksDFS
LoopBlocks(L
);
813 LoopBlocks
.perform(LI
);
816 // For each extra loop iteration, create a copy of the loop's basic blocks
817 // and generate a condition that branches to the copy depending on the
818 // number of 'left over' iterations.
820 std::vector
<BasicBlock
*> NewBlocks
;
821 ValueToValueMapTy VMap
;
823 // For unroll factor 2 remainder loop will have 1 iterations.
824 // Do not create 1 iteration loop.
825 bool CreateRemainderLoop
= (Count
!= 2);
827 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
828 // the loop, otherwise we create a cloned loop to execute the extra
829 // iterations. This function adds the appropriate CFG connections.
830 BasicBlock
*InsertBot
= UseEpilogRemainder
? LatchExit
: PrologExit
;
831 BasicBlock
*InsertTop
= UseEpilogRemainder
? EpilogPreHeader
: PrologPreHeader
;
832 Loop
*remainderLoop
= CloneLoopBlocks(
833 L
, ModVal
, CreateRemainderLoop
, UseEpilogRemainder
, UnrollRemainder
,
834 InsertTop
, InsertBot
,
835 NewPreHeader
, NewBlocks
, LoopBlocks
, VMap
, DT
, LI
);
837 // Assign the maximum possible trip count as the back edge weight for the
838 // remainder loop if the original loop comes with a branch weight.
839 if (remainderLoop
&& !UnrollRemainder
)
840 updateLatchBranchWeightsForRemainderLoop(L
, remainderLoop
, Count
);
842 // Insert the cloned blocks into the function.
843 F
->getBasicBlockList().splice(InsertBot
->getIterator(),
844 F
->getBasicBlockList(),
845 NewBlocks
[0]->getIterator(),
848 // Now the loop blocks are cloned and the other exiting blocks from the
849 // remainder are connected to the original Loop's exit blocks. The remaining
850 // work is to update the phi nodes in the original loop, and take in the
851 // values from the cloned region.
852 for (auto *BB
: OtherExits
) {
853 // Given we preserve LCSSA form, we know that the values used outside the
854 // loop will be used through these phi nodes at the exit blocks that are
855 // transformed below.
856 for (PHINode
&PN
: BB
->phis()) {
857 unsigned oldNumOperands
= PN
.getNumIncomingValues();
858 // Add the incoming values from the remainder code to the end of the phi
860 for (unsigned i
= 0; i
< oldNumOperands
; i
++){
861 auto *PredBB
=PN
.getIncomingBlock(i
);
863 // The latch exit is handled seperately, see connectX
865 if (!L
->contains(PredBB
))
866 // Even if we had dedicated exits, the code above inserted an
867 // extra branch which can reach the latch exit.
870 auto *V
= PN
.getIncomingValue(i
);
871 if (Instruction
*I
= dyn_cast
<Instruction
>(V
))
874 PN
.addIncoming(V
, cast
<BasicBlock
>(VMap
[PredBB
]));
877 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
878 for (BasicBlock
*SuccBB
: successors(BB
)) {
879 assert(!(any_of(OtherExits
,
880 [SuccBB
](BasicBlock
*EB
) { return EB
== SuccBB
; }) ||
881 SuccBB
== LatchExit
) &&
882 "Breaks the definition of dedicated exits!");
887 // Update the immediate dominator of the exit blocks and blocks that are
888 // reachable from the exit blocks. This is needed because we now have paths
889 // from both the original loop and the remainder code reaching the exit
890 // blocks. While the IDom of these exit blocks were from the original loop,
891 // now the IDom is the preheader (which decides whether the original loop or
892 // remainder code should run).
893 if (DT
&& !L
->getExitingBlock()) {
894 SmallVector
<BasicBlock
*, 16> ChildrenToUpdate
;
895 // NB! We have to examine the dom children of all loop blocks, not just
896 // those which are the IDom of the exit blocks. This is because blocks
897 // reachable from the exit blocks can have their IDom as the nearest common
898 // dominator of the exit blocks.
899 for (auto *BB
: L
->blocks()) {
900 auto *DomNodeBB
= DT
->getNode(BB
);
901 for (auto *DomChild
: DomNodeBB
->children()) {
902 auto *DomChildBB
= DomChild
->getBlock();
903 if (!L
->contains(LI
->getLoopFor(DomChildBB
)))
904 ChildrenToUpdate
.push_back(DomChildBB
);
907 for (auto *BB
: ChildrenToUpdate
)
908 DT
->changeImmediateDominator(BB
, PreHeader
);
911 // Loop structure should be the following:
914 // PreHeader PreHeader
915 // NewPreHeader PrologPreHeader
916 // Header PrologHeader
919 // NewExit PrologExit
920 // EpilogPreHeader NewPreHeader
921 // EpilogHeader Header
924 // LatchExit LatchExit
926 // Rewrite the cloned instruction operands to use the values created when the
928 for (BasicBlock
*BB
: NewBlocks
) {
929 for (Instruction
&I
: *BB
) {
930 RemapInstruction(&I
, VMap
,
931 RF_NoModuleLevelChanges
| RF_IgnoreMissingLocals
);
935 if (UseEpilogRemainder
) {
936 // Connect the epilog code to the original loop and update the
938 ConnectEpilog(L
, ModVal
, NewExit
, LatchExit
, PreHeader
,
939 EpilogPreHeader
, NewPreHeader
, VMap
, DT
, LI
,
942 // Update counter in loop for unrolling.
943 // I should be multiply of Count.
944 IRBuilder
<> B2(NewPreHeader
->getTerminator());
945 Value
*TestVal
= B2
.CreateSub(TripCount
, ModVal
, "unroll_iter");
946 BranchInst
*LatchBR
= cast
<BranchInst
>(Latch
->getTerminator());
947 B2
.SetInsertPoint(LatchBR
);
948 PHINode
*NewIdx
= PHINode::Create(TestVal
->getType(), 2, "niter",
949 Header
->getFirstNonPHI());
951 B2
.CreateSub(NewIdx
, ConstantInt::get(NewIdx
->getType(), 1),
952 NewIdx
->getName() + ".nsub");
954 if (LatchBR
->getSuccessor(0) == Header
)
955 IdxCmp
= B2
.CreateIsNotNull(IdxSub
, NewIdx
->getName() + ".ncmp");
957 IdxCmp
= B2
.CreateIsNull(IdxSub
, NewIdx
->getName() + ".ncmp");
958 NewIdx
->addIncoming(TestVal
, NewPreHeader
);
959 NewIdx
->addIncoming(IdxSub
, Latch
);
960 LatchBR
->setCondition(IdxCmp
);
962 // Connect the prolog code to the original loop and update the
964 ConnectProlog(L
, BECount
, Count
, PrologExit
, LatchExit
, PreHeader
,
965 NewPreHeader
, VMap
, DT
, LI
, PreserveLCSSA
);
968 // If this loop is nested, then the loop unroller changes the code in the any
969 // of its parent loops, so the Scalar Evolution pass needs to be run again.
970 SE
->forgetTopmostLoop(L
);
972 // Verify that the Dom Tree is correct.
973 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
975 assert(DT
->verify(DominatorTree::VerificationLevel::Full
));
978 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
979 // cannot rely on the LoopUnrollPass to do this because it only does
980 // canonicalization for parent/subloops and not the sibling loops.
981 if (OtherExits
.size() > 0) {
982 // Generate dedicated exit blocks for the original loop, to preserve
984 formDedicatedExitBlocks(L
, DT
, LI
, nullptr, PreserveLCSSA
);
985 // Generate dedicated exit blocks for the remainder loop if one exists, to
986 // preserve LoopSimplifyForm.
988 formDedicatedExitBlocks(remainderLoop
, DT
, LI
, nullptr, PreserveLCSSA
);
991 auto UnrollResult
= LoopUnrollResult::Unmodified
;
992 if (remainderLoop
&& UnrollRemainder
) {
993 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
995 UnrollLoop(remainderLoop
,
996 {/*Count*/ Count
- 1, /*Force*/ false, /*Runtime*/ false,
997 /*AllowExpensiveTripCount*/ false,
998 /*UnrollRemainder*/ false, ForgetAllSCEV
},
999 LI
, SE
, DT
, AC
, TTI
, /*ORE*/ nullptr, PreserveLCSSA
);
1002 if (ResultLoop
&& UnrollResult
!= LoopUnrollResult::FullyUnrolled
)
1003 *ResultLoop
= remainderLoop
;
1004 NumRuntimeUnrolled
++;