1 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements some loop unrolling utilities for loops with run-time
11 // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time
14 // The functions in this file are used to generate extra code when the
15 // run-time trip count modulo the unroll factor is not 0. When this is the
16 // case, we need to generate code to execute these 'left over' iterations.
18 // The current strategy generates an if-then-else sequence prior to the
19 // unrolled loop to execute the 'left over' iterations before or after the
22 //===----------------------------------------------------------------------===//
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/LoopIterator.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/ScalarEvolution.h"
30 #include "llvm/Analysis/ScalarEvolutionExpander.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
40 #include "llvm/Transforms/Utils/LoopUtils.h"
41 #include "llvm/Transforms/Utils/UnrollLoop.h"
46 #define DEBUG_TYPE "loop-unroll"
48 STATISTIC(NumRuntimeUnrolled
,
49 "Number of loops unrolled with run-time trip counts");
50 static cl::opt
<bool> UnrollRuntimeMultiExit(
51 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden
,
52 cl::desc("Allow runtime unrolling for loops with multiple exits, when "
53 "epilog is generated"));
55 /// Connect the unrolling prolog code to the original loop.
56 /// The unrolling prolog code contains code to execute the
57 /// 'extra' iterations if the run-time trip count modulo the
58 /// unroll count is non-zero.
60 /// This function performs the following:
61 /// - Create PHI nodes at prolog end block to combine values
62 /// that exit the prolog code and jump around the prolog.
63 /// - Add a PHI operand to a PHI node at the loop exit block
64 /// for values that exit the prolog and go around the loop.
65 /// - Branch around the original loop if the trip count is less
66 /// than the unroll factor.
68 static void ConnectProlog(Loop
*L
, Value
*BECount
, unsigned Count
,
69 BasicBlock
*PrologExit
,
70 BasicBlock
*OriginalLoopLatchExit
,
71 BasicBlock
*PreHeader
, BasicBlock
*NewPreHeader
,
72 ValueToValueMapTy
&VMap
, DominatorTree
*DT
,
73 LoopInfo
*LI
, bool PreserveLCSSA
) {
74 BasicBlock
*Latch
= L
->getLoopLatch();
75 assert(Latch
&& "Loop must have a latch");
76 BasicBlock
*PrologLatch
= cast
<BasicBlock
>(VMap
[Latch
]);
78 // Create a PHI node for each outgoing value from the original loop
79 // (which means it is an outgoing value from the prolog code too).
80 // The new PHI node is inserted in the prolog end basic block.
81 // The new PHI node value is added as an operand of a PHI node in either
82 // the loop header or the loop exit block.
83 for (BasicBlock
*Succ
: successors(Latch
)) {
84 for (Instruction
&BBI
: *Succ
) {
85 PHINode
*PN
= dyn_cast
<PHINode
>(&BBI
);
86 // Exit when we passed all PHI nodes.
89 // Add a new PHI node to the prolog end block and add the
90 // appropriate incoming values.
91 PHINode
*NewPN
= PHINode::Create(PN
->getType(), 2, PN
->getName() + ".unr",
92 PrologExit
->getFirstNonPHI());
93 // Adding a value to the new PHI node from the original loop preheader.
94 // This is the value that skips all the prolog code.
95 if (L
->contains(PN
)) {
96 NewPN
->addIncoming(PN
->getIncomingValueForBlock(NewPreHeader
),
99 NewPN
->addIncoming(UndefValue::get(PN
->getType()), PreHeader
);
102 Value
*V
= PN
->getIncomingValueForBlock(Latch
);
103 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
104 if (L
->contains(I
)) {
108 // Adding a value to the new PHI node from the last prolog block
110 NewPN
->addIncoming(V
, PrologLatch
);
112 // Update the existing PHI node operand with the value from the
113 // new PHI node. How this is done depends on if the existing
114 // PHI node is in the original loop block, or the exit block.
115 if (L
->contains(PN
)) {
116 PN
->setIncomingValue(PN
->getBasicBlockIndex(NewPreHeader
), NewPN
);
118 PN
->addIncoming(NewPN
, PrologExit
);
123 // Make sure that created prolog loop is in simplified form
124 SmallVector
<BasicBlock
*, 4> PrologExitPreds
;
125 Loop
*PrologLoop
= LI
->getLoopFor(PrologLatch
);
127 for (BasicBlock
*PredBB
: predecessors(PrologExit
))
128 if (PrologLoop
->contains(PredBB
))
129 PrologExitPreds
.push_back(PredBB
);
131 SplitBlockPredecessors(PrologExit
, PrologExitPreds
, ".unr-lcssa", DT
, LI
,
135 // Create a branch around the original loop, which is taken if there are no
136 // iterations remaining to be executed after running the prologue.
137 Instruction
*InsertPt
= PrologExit
->getTerminator();
138 IRBuilder
<> B(InsertPt
);
140 assert(Count
!= 0 && "nonsensical Count!");
142 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
143 // This means %xtraiter is (BECount + 1) and all of the iterations of this
144 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
145 // then (BECount + 1) cannot unsigned-overflow.
147 B
.CreateICmpULT(BECount
, ConstantInt::get(BECount
->getType(), Count
- 1));
148 // Split the exit to maintain loop canonicalization guarantees
149 SmallVector
<BasicBlock
*, 4> Preds(predecessors(OriginalLoopLatchExit
));
150 SplitBlockPredecessors(OriginalLoopLatchExit
, Preds
, ".unr-lcssa", DT
, LI
,
152 // Add the branch to the exit block (around the unrolled loop)
153 B
.CreateCondBr(BrLoopExit
, OriginalLoopLatchExit
, NewPreHeader
);
154 InsertPt
->eraseFromParent();
156 DT
->changeImmediateDominator(OriginalLoopLatchExit
, PrologExit
);
159 /// Connect the unrolling epilog code to the original loop.
160 /// The unrolling epilog code contains code to execute the
161 /// 'extra' iterations if the run-time trip count modulo the
162 /// unroll count is non-zero.
164 /// This function performs the following:
165 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
166 /// - Create PHI nodes at the unrolling loop exit to combine
167 /// values that exit the unrolling loop code and jump around it.
168 /// - Update PHI operands in the epilog loop by the new PHI nodes
169 /// - Branch around the epilog loop if extra iters (ModVal) is zero.
171 static void ConnectEpilog(Loop
*L
, Value
*ModVal
, BasicBlock
*NewExit
,
172 BasicBlock
*Exit
, BasicBlock
*PreHeader
,
173 BasicBlock
*EpilogPreHeader
, BasicBlock
*NewPreHeader
,
174 ValueToValueMapTy
&VMap
, DominatorTree
*DT
,
175 LoopInfo
*LI
, bool PreserveLCSSA
) {
176 BasicBlock
*Latch
= L
->getLoopLatch();
177 assert(Latch
&& "Loop must have a latch");
178 BasicBlock
*EpilogLatch
= cast
<BasicBlock
>(VMap
[Latch
]);
180 // Loop structure should be the following:
194 // Update PHI nodes at NewExit and Exit.
195 for (Instruction
&BBI
: *NewExit
) {
196 PHINode
*PN
= dyn_cast
<PHINode
>(&BBI
);
197 // Exit when we passed all PHI nodes.
200 // PN should be used in another PHI located in Exit block as
201 // Exit was split by SplitBlockPredecessors into Exit and NewExit
202 // Basicaly it should look like:
204 // PN = PHI [I, Latch]
207 // EpilogPN = PHI [PN, EpilogPreHeader]
209 // There is EpilogPreHeader incoming block instead of NewExit as
210 // NewExit was spilt 1 more time to get EpilogPreHeader.
211 assert(PN
->hasOneUse() && "The phi should have 1 use");
212 PHINode
*EpilogPN
= cast
<PHINode
> (PN
->use_begin()->getUser());
213 assert(EpilogPN
->getParent() == Exit
&& "EpilogPN should be in Exit block");
215 // Add incoming PreHeader from branch around the Loop
216 PN
->addIncoming(UndefValue::get(PN
->getType()), PreHeader
);
218 Value
*V
= PN
->getIncomingValueForBlock(Latch
);
219 Instruction
*I
= dyn_cast
<Instruction
>(V
);
220 if (I
&& L
->contains(I
))
221 // If value comes from an instruction in the loop add VMap value.
223 // For the instruction out of the loop, constant or undefined value
224 // insert value itself.
225 EpilogPN
->addIncoming(V
, EpilogLatch
);
227 assert(EpilogPN
->getBasicBlockIndex(EpilogPreHeader
) >= 0 &&
228 "EpilogPN should have EpilogPreHeader incoming block");
229 // Change EpilogPreHeader incoming block to NewExit.
230 EpilogPN
->setIncomingBlock(EpilogPN
->getBasicBlockIndex(EpilogPreHeader
),
232 // Now PHIs should look like:
234 // PN = PHI [I, Latch], [undef, PreHeader]
237 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
240 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
241 // Update corresponding PHI nodes in epilog loop.
242 for (BasicBlock
*Succ
: successors(Latch
)) {
243 // Skip this as we already updated phis in exit blocks.
244 if (!L
->contains(Succ
))
246 for (Instruction
&BBI
: *Succ
) {
247 PHINode
*PN
= dyn_cast
<PHINode
>(&BBI
);
248 // Exit when we passed all PHI nodes.
251 // Add new PHI nodes to the loop exit block and update epilog
252 // PHIs with the new PHI values.
253 PHINode
*NewPN
= PHINode::Create(PN
->getType(), 2, PN
->getName() + ".unr",
254 NewExit
->getFirstNonPHI());
255 // Adding a value to the new PHI node from the unrolling loop preheader.
256 NewPN
->addIncoming(PN
->getIncomingValueForBlock(NewPreHeader
), PreHeader
);
257 // Adding a value to the new PHI node from the unrolling loop latch.
258 NewPN
->addIncoming(PN
->getIncomingValueForBlock(Latch
), Latch
);
260 // Update the existing PHI node operand with the value from the new PHI
261 // node. Corresponding instruction in epilog loop should be PHI.
262 PHINode
*VPN
= cast
<PHINode
>(VMap
[&BBI
]);
263 VPN
->setIncomingValue(VPN
->getBasicBlockIndex(EpilogPreHeader
), NewPN
);
267 Instruction
*InsertPt
= NewExit
->getTerminator();
268 IRBuilder
<> B(InsertPt
);
269 Value
*BrLoopExit
= B
.CreateIsNotNull(ModVal
, "lcmp.mod");
270 assert(Exit
&& "Loop must have a single exit block only");
271 // Split the epilogue exit to maintain loop canonicalization guarantees
272 SmallVector
<BasicBlock
*, 4> Preds(predecessors(Exit
));
273 SplitBlockPredecessors(Exit
, Preds
, ".epilog-lcssa", DT
, LI
,
275 // Add the branch to the exit block (around the unrolling loop)
276 B
.CreateCondBr(BrLoopExit
, EpilogPreHeader
, Exit
);
277 InsertPt
->eraseFromParent();
279 DT
->changeImmediateDominator(Exit
, NewExit
);
281 // Split the main loop exit to maintain canonicalization guarantees.
282 SmallVector
<BasicBlock
*, 4> NewExitPreds
{Latch
};
283 SplitBlockPredecessors(NewExit
, NewExitPreds
, ".loopexit", DT
, LI
,
287 /// Create a clone of the blocks in a loop and connect them together.
288 /// If CreateRemainderLoop is false, loop structure will not be cloned,
289 /// otherwise a new loop will be created including all cloned blocks, and the
290 /// iterator of it switches to count NewIter down to 0.
291 /// The cloned blocks should be inserted between InsertTop and InsertBot.
292 /// If loop structure is cloned InsertTop should be new preheader, InsertBot
294 /// Return the new cloned loop that is created when CreateRemainderLoop is true.
296 CloneLoopBlocks(Loop
*L
, Value
*NewIter
, const bool CreateRemainderLoop
,
297 const bool UseEpilogRemainder
, const bool UnrollRemainder
,
298 BasicBlock
*InsertTop
,
299 BasicBlock
*InsertBot
, BasicBlock
*Preheader
,
300 std::vector
<BasicBlock
*> &NewBlocks
, LoopBlocksDFS
&LoopBlocks
,
301 ValueToValueMapTy
&VMap
, DominatorTree
*DT
, LoopInfo
*LI
) {
302 StringRef suffix
= UseEpilogRemainder
? "epil" : "prol";
303 BasicBlock
*Header
= L
->getHeader();
304 BasicBlock
*Latch
= L
->getLoopLatch();
305 Function
*F
= Header
->getParent();
306 LoopBlocksDFS::RPOIterator BlockBegin
= LoopBlocks
.beginRPO();
307 LoopBlocksDFS::RPOIterator BlockEnd
= LoopBlocks
.endRPO();
308 Loop
*ParentLoop
= L
->getParentLoop();
309 NewLoopsMap NewLoops
;
310 NewLoops
[ParentLoop
] = ParentLoop
;
311 if (!CreateRemainderLoop
)
312 NewLoops
[L
] = ParentLoop
;
314 // For each block in the original loop, create a new copy,
315 // and update the value map with the newly created values.
316 for (LoopBlocksDFS::RPOIterator BB
= BlockBegin
; BB
!= BlockEnd
; ++BB
) {
317 BasicBlock
*NewBB
= CloneBasicBlock(*BB
, VMap
, "." + suffix
, F
);
318 NewBlocks
.push_back(NewBB
);
320 // If we're unrolling the outermost loop, there's no remainder loop,
321 // and this block isn't in a nested loop, then the new block is not
322 // in any loop. Otherwise, add it to loopinfo.
323 if (CreateRemainderLoop
|| LI
->getLoopFor(*BB
) != L
|| ParentLoop
)
324 addClonedBlockToLoopInfo(*BB
, NewBB
, LI
, NewLoops
);
328 // For the first block, add a CFG connection to this newly
330 InsertTop
->getTerminator()->setSuccessor(0, NewBB
);
335 // The header is dominated by the preheader.
336 DT
->addNewBlock(NewBB
, InsertTop
);
338 // Copy information from original loop to unrolled loop.
339 BasicBlock
*IDomBB
= DT
->getNode(*BB
)->getIDom()->getBlock();
340 DT
->addNewBlock(NewBB
, cast
<BasicBlock
>(VMap
[IDomBB
]));
345 // For the last block, if CreateRemainderLoop is false, create a direct
346 // jump to InsertBot. If not, create a loop back to cloned head.
347 VMap
.erase((*BB
)->getTerminator());
348 BasicBlock
*FirstLoopBB
= cast
<BasicBlock
>(VMap
[Header
]);
349 BranchInst
*LatchBR
= cast
<BranchInst
>(NewBB
->getTerminator());
350 IRBuilder
<> Builder(LatchBR
);
351 if (!CreateRemainderLoop
) {
352 Builder
.CreateBr(InsertBot
);
354 PHINode
*NewIdx
= PHINode::Create(NewIter
->getType(), 2,
356 FirstLoopBB
->getFirstNonPHI());
358 Builder
.CreateSub(NewIdx
, ConstantInt::get(NewIdx
->getType(), 1),
359 NewIdx
->getName() + ".sub");
361 Builder
.CreateIsNotNull(IdxSub
, NewIdx
->getName() + ".cmp");
362 Builder
.CreateCondBr(IdxCmp
, FirstLoopBB
, InsertBot
);
363 NewIdx
->addIncoming(NewIter
, InsertTop
);
364 NewIdx
->addIncoming(IdxSub
, NewBB
);
366 LatchBR
->eraseFromParent();
370 // Change the incoming values to the ones defined in the preheader or
372 for (BasicBlock::iterator I
= Header
->begin(); isa
<PHINode
>(I
); ++I
) {
373 PHINode
*NewPHI
= cast
<PHINode
>(VMap
[&*I
]);
374 if (!CreateRemainderLoop
) {
375 if (UseEpilogRemainder
) {
376 unsigned idx
= NewPHI
->getBasicBlockIndex(Preheader
);
377 NewPHI
->setIncomingBlock(idx
, InsertTop
);
378 NewPHI
->removeIncomingValue(Latch
, false);
380 VMap
[&*I
] = NewPHI
->getIncomingValueForBlock(Preheader
);
381 cast
<BasicBlock
>(VMap
[Header
])->getInstList().erase(NewPHI
);
384 unsigned idx
= NewPHI
->getBasicBlockIndex(Preheader
);
385 NewPHI
->setIncomingBlock(idx
, InsertTop
);
386 BasicBlock
*NewLatch
= cast
<BasicBlock
>(VMap
[Latch
]);
387 idx
= NewPHI
->getBasicBlockIndex(Latch
);
388 Value
*InVal
= NewPHI
->getIncomingValue(idx
);
389 NewPHI
->setIncomingBlock(idx
, NewLatch
);
390 if (Value
*V
= VMap
.lookup(InVal
))
391 NewPHI
->setIncomingValue(idx
, V
);
394 if (CreateRemainderLoop
) {
395 Loop
*NewLoop
= NewLoops
[L
];
396 assert(NewLoop
&& "L should have been cloned");
398 // Only add loop metadata if the loop is not going to be completely
403 // Add unroll disable metadata to disable future unrolling for this loop.
404 SmallVector
<Metadata
*, 4> MDs
;
405 // Reserve first location for self reference to the LoopID metadata node.
406 MDs
.push_back(nullptr);
407 MDNode
*LoopID
= NewLoop
->getLoopID();
409 // First remove any existing loop unrolling metadata.
410 for (unsigned i
= 1, ie
= LoopID
->getNumOperands(); i
< ie
; ++i
) {
411 bool IsUnrollMetadata
= false;
412 MDNode
*MD
= dyn_cast
<MDNode
>(LoopID
->getOperand(i
));
414 const MDString
*S
= dyn_cast
<MDString
>(MD
->getOperand(0));
415 IsUnrollMetadata
= S
&& S
->getString().startswith("llvm.loop.unroll.");
417 if (!IsUnrollMetadata
)
418 MDs
.push_back(LoopID
->getOperand(i
));
422 LLVMContext
&Context
= NewLoop
->getHeader()->getContext();
423 SmallVector
<Metadata
*, 1> DisableOperands
;
424 DisableOperands
.push_back(MDString::get(Context
,
425 "llvm.loop.unroll.disable"));
426 MDNode
*DisableNode
= MDNode::get(Context
, DisableOperands
);
427 MDs
.push_back(DisableNode
);
429 MDNode
*NewLoopID
= MDNode::get(Context
, MDs
);
430 // Set operand 0 to refer to the loop id itself.
431 NewLoopID
->replaceOperandWith(0, NewLoopID
);
432 NewLoop
->setLoopID(NewLoopID
);
439 /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
440 /// is populated with all the loop exit blocks other than the LatchExit block.
442 canSafelyUnrollMultiExitLoop(Loop
*L
, SmallVectorImpl
<BasicBlock
*> &OtherExits
,
443 BasicBlock
*LatchExit
, bool PreserveLCSSA
,
444 bool UseEpilogRemainder
) {
446 // We currently have some correctness constrains in unrolling a multi-exit
447 // loop. Check for these below.
449 // We rely on LCSSA form being preserved when the exit blocks are transformed.
452 SmallVector
<BasicBlock
*, 4> Exits
;
453 L
->getUniqueExitBlocks(Exits
);
454 for (auto *BB
: Exits
)
456 OtherExits
.push_back(BB
);
458 // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
459 // UnrollRuntimeMultiExit is true. This will need updating the logic in
460 // connectEpilog/connectProlog.
461 if (!LatchExit
->getSinglePredecessor()) {
462 DEBUG(dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
466 // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
467 // and L is an inner loop. This is because in presence of multiple exits, the
468 // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
469 // outer loop. This is automatically handled in the prolog case, so we do not
470 // have that bug in prolog generation.
471 if (UseEpilogRemainder
&& L
->getParentLoop())
474 // All constraints have been satisfied.
478 /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
479 /// we return true only if UnrollRuntimeMultiExit is set to true.
480 static bool canProfitablyUnrollMultiExitLoop(
481 Loop
*L
, SmallVectorImpl
<BasicBlock
*> &OtherExits
, BasicBlock
*LatchExit
,
482 bool PreserveLCSSA
, bool UseEpilogRemainder
) {
485 SmallVector
<BasicBlock
*, 8> OtherExitsDummyCheck
;
486 assert(canSafelyUnrollMultiExitLoop(L
, OtherExitsDummyCheck
, LatchExit
,
487 PreserveLCSSA
, UseEpilogRemainder
) &&
488 "Should be safe to unroll before checking profitability!");
491 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
492 if (UnrollRuntimeMultiExit
.getNumOccurrences())
493 return UnrollRuntimeMultiExit
;
495 // The main pain point with multi-exit loop unrolling is that once unrolled,
496 // we will not be able to merge all blocks into a straight line code.
497 // There are branches within the unrolled loop that go to the OtherExits.
498 // The second point is the increase in code size, but this is true
499 // irrespective of multiple exits.
501 // Note: Both the heuristics below are coarse grained. We are essentially
502 // enabling unrolling of loops that have a single side exit other than the
503 // normal LatchExit (i.e. exiting into a deoptimize block).
504 // The heuristics considered are:
505 // 1. low number of branches in the unrolled version.
506 // 2. high predictability of these extra branches.
507 // We avoid unrolling loops that have more than two exiting blocks. This
508 // limits the total number of branches in the unrolled loop to be atmost
509 // the unroll factor (since one of the exiting blocks is the latch block).
510 SmallVector
<BasicBlock
*, 4> ExitingBlocks
;
511 L
->getExitingBlocks(ExitingBlocks
);
512 if (ExitingBlocks
.size() > 2)
515 // The second heuristic is that L has one exit other than the latchexit and
516 // that exit is a deoptimize block. We know that deoptimize blocks are rarely
517 // taken, which also implies the branch leading to the deoptimize block is
518 // highly predictable.
519 return (OtherExits
.size() == 1 &&
520 OtherExits
[0]->getTerminatingDeoptimizeCall());
521 // TODO: These can be fine-tuned further to consider code size or deopt states
522 // that are captured by the deoptimize exit block.
523 // Also, we can extend this to support more cases, if we actually
524 // know of kinds of multiexit loops that would benefit from unrolling.
527 /// Insert code in the prolog/epilog code when unrolling a loop with a
528 /// run-time trip-count.
530 /// This method assumes that the loop unroll factor is total number
531 /// of loop bodies in the loop after unrolling. (Some folks refer
532 /// to the unroll factor as the number of *extra* copies added).
533 /// We assume also that the loop unroll factor is a power-of-two. So, after
534 /// unrolling the loop, the number of loop bodies executed is 2,
535 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
536 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
537 /// the switch instruction is generated.
539 /// ***Prolog case***
540 /// extraiters = tripcount % loopfactor
541 /// if (extraiters == 0) jump Loop:
544 /// extraiters -= 1 // Omitted if unroll factor is 2.
545 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
546 /// if (tripcount < loopfactor) jump End:
551 /// ***Epilog case***
552 /// extraiters = tripcount % loopfactor
553 /// if (tripcount < loopfactor) jump LoopExit:
554 /// unroll_iters = tripcount - extraiters
555 /// Loop: LoopBody; (executes unroll_iter times);
557 /// if (unroll_iter != 0) jump Loop:
559 /// if (extraiters == 0) jump EpilExit:
560 /// Epil: LoopBody; (executes extraiters times)
561 /// extraiters -= 1 // Omitted if unroll factor is 2.
562 /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
565 bool llvm::UnrollRuntimeLoopRemainder(Loop
*L
, unsigned Count
,
566 bool AllowExpensiveTripCount
,
567 bool UseEpilogRemainder
,
568 bool UnrollRemainder
,
569 LoopInfo
*LI
, ScalarEvolution
*SE
,
570 DominatorTree
*DT
, AssumptionCache
*AC
,
571 OptimizationRemarkEmitter
*ORE
,
572 bool PreserveLCSSA
) {
573 DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
575 DEBUG(UseEpilogRemainder
? dbgs() << "Using epilog remainder.\n" :
576 dbgs() << "Using prolog remainder.\n");
578 // Make sure the loop is in canonical form.
579 if (!L
->isLoopSimplifyForm()) {
580 DEBUG(dbgs() << "Not in simplify form!\n");
584 // Guaranteed by LoopSimplifyForm.
585 BasicBlock
*Latch
= L
->getLoopLatch();
586 BasicBlock
*Header
= L
->getHeader();
588 BranchInst
*LatchBR
= cast
<BranchInst
>(Latch
->getTerminator());
589 unsigned ExitIndex
= LatchBR
->getSuccessor(0) == Header
? 1 : 0;
590 BasicBlock
*LatchExit
= LatchBR
->getSuccessor(ExitIndex
);
591 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
592 // targets of the Latch be an exit block out of the loop. This needs
593 // to be guaranteed by the callers of UnrollRuntimeLoopRemainder.
594 assert(!L
->contains(LatchExit
) &&
595 "one of the loop latch successors should be the exit block!");
596 // These are exit blocks other than the target of the latch exiting block.
597 SmallVector
<BasicBlock
*, 4> OtherExits
;
598 bool isMultiExitUnrollingEnabled
=
599 canSafelyUnrollMultiExitLoop(L
, OtherExits
, LatchExit
, PreserveLCSSA
,
600 UseEpilogRemainder
) &&
601 canProfitablyUnrollMultiExitLoop(L
, OtherExits
, LatchExit
, PreserveLCSSA
,
603 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
604 if (!isMultiExitUnrollingEnabled
&&
605 (!L
->getExitingBlock() || OtherExits
.size())) {
608 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
612 // Use Scalar Evolution to compute the trip count. This allows more loops to
613 // be unrolled than relying on induction var simplification.
617 // Only unroll loops with a computable trip count, and the trip count needs
618 // to be an int value (allowing a pointer type is a TODO item).
619 // We calculate the backedge count by using getExitCount on the Latch block,
620 // which is proven to be the only exiting block in this loop. This is same as
621 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
623 const SCEV
*BECountSC
= SE
->getExitCount(L
, Latch
);
624 if (isa
<SCEVCouldNotCompute
>(BECountSC
) ||
625 !BECountSC
->getType()->isIntegerTy()) {
626 DEBUG(dbgs() << "Could not compute exit block SCEV\n");
630 unsigned BEWidth
= cast
<IntegerType
>(BECountSC
->getType())->getBitWidth();
632 // Add 1 since the backedge count doesn't include the first loop iteration.
633 const SCEV
*TripCountSC
=
634 SE
->getAddExpr(BECountSC
, SE
->getConstant(BECountSC
->getType(), 1));
635 if (isa
<SCEVCouldNotCompute
>(TripCountSC
)) {
636 DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
640 BasicBlock
*PreHeader
= L
->getLoopPreheader();
641 BranchInst
*PreHeaderBR
= cast
<BranchInst
>(PreHeader
->getTerminator());
642 const DataLayout
&DL
= Header
->getModule()->getDataLayout();
643 SCEVExpander
Expander(*SE
, DL
, "loop-unroll");
644 if (!AllowExpensiveTripCount
&&
645 Expander
.isHighCostExpansion(TripCountSC
, L
, PreHeaderBR
)) {
646 DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
650 // This constraint lets us deal with an overflowing trip count easily; see the
651 // comment on ModVal below.
652 if (Log2_32(Count
) > BEWidth
) {
654 << "Count failed constraint on overflow trip count calculation.\n");
658 // Loop structure is the following:
666 BasicBlock
*NewPreHeader
;
667 BasicBlock
*NewExit
= nullptr;
668 BasicBlock
*PrologExit
= nullptr;
669 BasicBlock
*EpilogPreHeader
= nullptr;
670 BasicBlock
*PrologPreHeader
= nullptr;
672 if (UseEpilogRemainder
) {
673 // If epilog remainder
674 // Split PreHeader to insert a branch around loop for unrolling.
675 NewPreHeader
= SplitBlock(PreHeader
, PreHeader
->getTerminator(), DT
, LI
);
676 NewPreHeader
->setName(PreHeader
->getName() + ".new");
677 // Split LatchExit to create phi nodes from branch above.
678 SmallVector
<BasicBlock
*, 4> Preds(predecessors(LatchExit
));
679 NewExit
= SplitBlockPredecessors(LatchExit
, Preds
, ".unr-lcssa",
680 DT
, LI
, PreserveLCSSA
);
681 // Split NewExit to insert epilog remainder loop.
682 EpilogPreHeader
= SplitBlock(NewExit
, NewExit
->getTerminator(), DT
, LI
);
683 EpilogPreHeader
->setName(Header
->getName() + ".epil.preheader");
685 // If prolog remainder
686 // Split the original preheader twice to insert prolog remainder loop
687 PrologPreHeader
= SplitEdge(PreHeader
, Header
, DT
, LI
);
688 PrologPreHeader
->setName(Header
->getName() + ".prol.preheader");
689 PrologExit
= SplitBlock(PrologPreHeader
, PrologPreHeader
->getTerminator(),
691 PrologExit
->setName(Header
->getName() + ".prol.loopexit");
692 // Split PrologExit to get NewPreHeader.
693 NewPreHeader
= SplitBlock(PrologExit
, PrologExit
->getTerminator(), DT
, LI
);
694 NewPreHeader
->setName(PreHeader
->getName() + ".new");
696 // Loop structure should be the following:
699 // PreHeader PreHeader
700 // *NewPreHeader *PrologPreHeader
701 // Header *PrologExit
705 // *EpilogPreHeader Latch
706 // LatchExit LatchExit
708 // Calculate conditions for branch around loop for unrolling
709 // in epilog case and around prolog remainder loop in prolog case.
710 // Compute the number of extra iterations required, which is:
711 // extra iterations = run-time trip count % loop unroll factor
712 PreHeaderBR
= cast
<BranchInst
>(PreHeader
->getTerminator());
713 Value
*TripCount
= Expander
.expandCodeFor(TripCountSC
, TripCountSC
->getType(),
715 Value
*BECount
= Expander
.expandCodeFor(BECountSC
, BECountSC
->getType(),
717 IRBuilder
<> B(PreHeaderBR
);
719 // Calculate ModVal = (BECount + 1) % Count.
720 // Note that TripCount is BECount + 1.
721 if (isPowerOf2_32(Count
)) {
722 // When Count is power of 2 we don't BECount for epilog case, however we'll
723 // need it for a branch around unrolling loop for prolog case.
724 ModVal
= B
.CreateAnd(TripCount
, Count
- 1, "xtraiter");
725 // 1. There are no iterations to be run in the prolog/epilog loop.
727 // 2. The addition computing TripCount overflowed.
729 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
730 // the number of iterations that remain to be run in the original loop is a
731 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
732 // explicitly check this above).
734 // As (BECount + 1) can potentially unsigned overflow we count
735 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
736 Value
*ModValTmp
= B
.CreateURem(BECount
,
737 ConstantInt::get(BECount
->getType(),
739 Value
*ModValAdd
= B
.CreateAdd(ModValTmp
,
740 ConstantInt::get(ModValTmp
->getType(), 1));
741 // At that point (BECount % Count) + 1 could be equal to Count.
742 // To handle this case we need to take mod by Count one more time.
743 ModVal
= B
.CreateURem(ModValAdd
,
744 ConstantInt::get(BECount
->getType(), Count
),
748 UseEpilogRemainder
? B
.CreateICmpULT(BECount
,
749 ConstantInt::get(BECount
->getType(),
751 B
.CreateIsNotNull(ModVal
, "lcmp.mod");
752 BasicBlock
*RemainderLoop
= UseEpilogRemainder
? NewExit
: PrologPreHeader
;
753 BasicBlock
*UnrollingLoop
= UseEpilogRemainder
? NewPreHeader
: PrologExit
;
754 // Branch to either remainder (extra iterations) loop or unrolling loop.
755 B
.CreateCondBr(BranchVal
, RemainderLoop
, UnrollingLoop
);
756 PreHeaderBR
->eraseFromParent();
758 if (UseEpilogRemainder
)
759 DT
->changeImmediateDominator(NewExit
, PreHeader
);
761 DT
->changeImmediateDominator(PrologExit
, PreHeader
);
763 Function
*F
= Header
->getParent();
764 // Get an ordered list of blocks in the loop to help with the ordering of the
765 // cloned blocks in the prolog/epilog code
766 LoopBlocksDFS
LoopBlocks(L
);
767 LoopBlocks
.perform(LI
);
770 // For each extra loop iteration, create a copy of the loop's basic blocks
771 // and generate a condition that branches to the copy depending on the
772 // number of 'left over' iterations.
774 std::vector
<BasicBlock
*> NewBlocks
;
775 ValueToValueMapTy VMap
;
777 // For unroll factor 2 remainder loop will have 1 iterations.
778 // Do not create 1 iteration loop.
779 bool CreateRemainderLoop
= (Count
!= 2);
781 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
782 // the loop, otherwise we create a cloned loop to execute the extra
783 // iterations. This function adds the appropriate CFG connections.
784 BasicBlock
*InsertBot
= UseEpilogRemainder
? LatchExit
: PrologExit
;
785 BasicBlock
*InsertTop
= UseEpilogRemainder
? EpilogPreHeader
: PrologPreHeader
;
786 Loop
*remainderLoop
= CloneLoopBlocks(
787 L
, ModVal
, CreateRemainderLoop
, UseEpilogRemainder
, UnrollRemainder
,
788 InsertTop
, InsertBot
,
789 NewPreHeader
, NewBlocks
, LoopBlocks
, VMap
, DT
, LI
);
791 // Insert the cloned blocks into the function.
792 F
->getBasicBlockList().splice(InsertBot
->getIterator(),
793 F
->getBasicBlockList(),
794 NewBlocks
[0]->getIterator(),
797 // Now the loop blocks are cloned and the other exiting blocks from the
798 // remainder are connected to the original Loop's exit blocks. The remaining
799 // work is to update the phi nodes in the original loop, and take in the
800 // values from the cloned region. Also update the dominator info for
801 // OtherExits and their immediate successors, since we have new edges into
803 SmallSet
<BasicBlock
*, 8> ImmediateSuccessorsOfExitBlocks
;
804 for (auto *BB
: OtherExits
) {
805 for (auto &II
: *BB
) {
807 // Given we preserve LCSSA form, we know that the values used outside the
808 // loop will be used through these phi nodes at the exit blocks that are
809 // transformed below.
810 if (!isa
<PHINode
>(II
))
812 PHINode
*Phi
= cast
<PHINode
>(&II
);
813 unsigned oldNumOperands
= Phi
->getNumIncomingValues();
814 // Add the incoming values from the remainder code to the end of the phi
816 for (unsigned i
=0; i
< oldNumOperands
; i
++){
817 Value
*newVal
= VMap
.lookup(Phi
->getIncomingValue(i
));
818 // newVal can be a constant or derived from values outside the loop, and
819 // hence need not have a VMap value. Also, since lookup already generated
820 // a default "null" VMap entry for this value, we need to populate that
821 // VMap entry correctly, with the mapped entry being itself.
823 newVal
= Phi
->getIncomingValue(i
);
824 VMap
[Phi
->getIncomingValue(i
)] = Phi
->getIncomingValue(i
);
826 Phi
->addIncoming(newVal
,
827 cast
<BasicBlock
>(VMap
[Phi
->getIncomingBlock(i
)]));
830 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
831 for (BasicBlock
*SuccBB
: successors(BB
)) {
832 assert(!(any_of(OtherExits
,
833 [SuccBB
](BasicBlock
*EB
) { return EB
== SuccBB
; }) ||
834 SuccBB
== LatchExit
) &&
835 "Breaks the definition of dedicated exits!");
838 // Update the dominator info because the immediate dominator is no longer the
839 // header of the original Loop. BB has edges both from L and remainder code.
840 // Since the preheader determines which loop is run (L or directly jump to
841 // the remainder code), we set the immediate dominator as the preheader.
843 DT
->changeImmediateDominator(BB
, PreHeader
);
844 // Also update the IDom for immediate successors of BB. If the current
845 // IDom is the header, update the IDom to be the preheader because that is
846 // the nearest common dominator of all predecessors of SuccBB. We need to
847 // check for IDom being the header because successors of exit blocks can
848 // have edges from outside the loop, and we should not incorrectly update
849 // the IDom in that case.
850 for (BasicBlock
*SuccBB
: successors(BB
))
851 if (ImmediateSuccessorsOfExitBlocks
.insert(SuccBB
).second
) {
852 if (DT
->getNode(SuccBB
)->getIDom()->getBlock() == Header
) {
853 assert(!SuccBB
->getSinglePredecessor() &&
854 "BB should be the IDom then!");
855 DT
->changeImmediateDominator(SuccBB
, PreHeader
);
861 // Loop structure should be the following:
864 // PreHeader PreHeader
865 // NewPreHeader PrologPreHeader
866 // Header PrologHeader
869 // NewExit PrologExit
870 // EpilogPreHeader NewPreHeader
871 // EpilogHeader Header
874 // LatchExit LatchExit
876 // Rewrite the cloned instruction operands to use the values created when the
878 for (BasicBlock
*BB
: NewBlocks
) {
879 for (Instruction
&I
: *BB
) {
880 RemapInstruction(&I
, VMap
,
881 RF_NoModuleLevelChanges
| RF_IgnoreMissingLocals
);
885 if (UseEpilogRemainder
) {
886 // Connect the epilog code to the original loop and update the
888 ConnectEpilog(L
, ModVal
, NewExit
, LatchExit
, PreHeader
,
889 EpilogPreHeader
, NewPreHeader
, VMap
, DT
, LI
,
892 // Update counter in loop for unrolling.
893 // I should be multiply of Count.
894 IRBuilder
<> B2(NewPreHeader
->getTerminator());
895 Value
*TestVal
= B2
.CreateSub(TripCount
, ModVal
, "unroll_iter");
896 BranchInst
*LatchBR
= cast
<BranchInst
>(Latch
->getTerminator());
897 B2
.SetInsertPoint(LatchBR
);
898 PHINode
*NewIdx
= PHINode::Create(TestVal
->getType(), 2, "niter",
899 Header
->getFirstNonPHI());
901 B2
.CreateSub(NewIdx
, ConstantInt::get(NewIdx
->getType(), 1),
902 NewIdx
->getName() + ".nsub");
904 if (LatchBR
->getSuccessor(0) == Header
)
905 IdxCmp
= B2
.CreateIsNotNull(IdxSub
, NewIdx
->getName() + ".ncmp");
907 IdxCmp
= B2
.CreateIsNull(IdxSub
, NewIdx
->getName() + ".ncmp");
908 NewIdx
->addIncoming(TestVal
, NewPreHeader
);
909 NewIdx
->addIncoming(IdxSub
, Latch
);
910 LatchBR
->setCondition(IdxCmp
);
912 // Connect the prolog code to the original loop and update the
914 ConnectProlog(L
, BECount
, Count
, PrologExit
, LatchExit
, PreHeader
,
915 NewPreHeader
, VMap
, DT
, LI
, PreserveLCSSA
);
918 // If this loop is nested, then the loop unroller changes the code in the
919 // parent loop, so the Scalar Evolution pass needs to be run again.
920 if (Loop
*ParentLoop
= L
->getParentLoop())
921 SE
->forgetLoop(ParentLoop
);
923 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
924 // cannot rely on the LoopUnrollPass to do this because it only does
925 // canonicalization for parent/subloops and not the sibling loops.
926 if (OtherExits
.size() > 0) {
927 // Generate dedicated exit blocks for the original loop, to preserve
929 formDedicatedExitBlocks(L
, DT
, LI
, PreserveLCSSA
);
930 // Generate dedicated exit blocks for the remainder loop if one exists, to
931 // preserve LoopSimplifyForm.
933 formDedicatedExitBlocks(remainderLoop
, DT
, LI
, PreserveLCSSA
);
936 if (remainderLoop
&& UnrollRemainder
) {
937 DEBUG(dbgs() << "Unrolling remainder loop\n");
938 UnrollLoop(remainderLoop
, /*Count*/Count
- 1, /*TripCount*/Count
- 1,
939 /*Force*/false, /*AllowRuntime*/false,
940 /*AllowExpensiveTripCount*/false, /*PreserveCondBr*/true,
941 /*PreserveOnlyFirst*/false, /*TripMultiple*/1,
942 /*PeelCount*/0, /*UnrollRemainder*/false, LI
, SE
, DT
, AC
, ORE
,
946 NumRuntimeUnrolled
++;