LLVM 22.0.0git
LoopUnrollRuntime.cpp
Go to the documentation of this file.
1//===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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
11// trip counts.
12//
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.
16//
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
19// unrolled loop.
20//
21//===----------------------------------------------------------------------===//
22
23#include "llvm/ADT/Statistic.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
35#include "llvm/Support/Debug.h"
43#include <cmath>
44
45using namespace llvm;
46
47#define DEBUG_TYPE "loop-unroll"
48
49STATISTIC(NumRuntimeUnrolled,
50 "Number of loops unrolled with run-time trip counts");
52 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
53 cl::desc("Allow runtime unrolling for loops with multiple exits, when "
54 "epilog is generated"));
56 "unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden,
57 cl::desc("Assume the non latch exit block to be predictable"));
58
59// Probability that the loop trip count is so small that after the prolog
60// we do not enter the unrolled loop at all.
61// It is unlikely that the loop trip count is smaller than the unroll factor;
62// other than that, the choice of constant is not tuned yet.
63static const uint32_t UnrolledLoopHeaderWeights[] = {1, 127};
64// Probability that the loop trip count is so small that we skip the unrolled
65// loop completely and immediately enter the epilogue loop.
66// It is unlikely that the loop trip count is smaller than the unroll factor;
67// other than that, the choice of constant is not tuned yet.
68static const uint32_t EpilogHeaderWeights[] = {1, 127};
69
70/// Connect the unrolling prolog code to the original loop.
71/// The unrolling prolog code contains code to execute the
72/// 'extra' iterations if the run-time trip count modulo the
73/// unroll count is non-zero.
74///
75/// This function performs the following:
76/// - Create PHI nodes at prolog end block to combine values
77/// that exit the prolog code and jump around the prolog.
78/// - Add a PHI operand to a PHI node at the loop exit block
79/// for values that exit the prolog and go around the loop.
80/// - Branch around the original loop if the trip count is less
81/// than the unroll factor.
82///
83static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
84 BasicBlock *PrologExit,
85 BasicBlock *OriginalLoopLatchExit,
86 BasicBlock *PreHeader, BasicBlock *NewPreHeader,
88 LoopInfo *LI, bool PreserveLCSSA,
89 ScalarEvolution &SE) {
90 // Loop structure should be the following:
91 // Preheader
92 // PrologHeader
93 // ...
94 // PrologLatch
95 // PrologExit
96 // NewPreheader
97 // Header
98 // ...
99 // Latch
100 // LatchExit
101 BasicBlock *Latch = L->getLoopLatch();
102 assert(Latch && "Loop must have a latch");
103 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
104
105 // Create a PHI node for each outgoing value from the original loop
106 // (which means it is an outgoing value from the prolog code too).
107 // The new PHI node is inserted in the prolog end basic block.
108 // The new PHI node value is added as an operand of a PHI node in either
109 // the loop header or the loop exit block.
110 for (BasicBlock *Succ : successors(Latch)) {
111 for (PHINode &PN : Succ->phis()) {
112 // Add a new PHI node to the prolog end block and add the
113 // appropriate incoming values.
114 // TODO: This code assumes that the PrologExit (or the LatchExit block for
115 // prolog loop) contains only one predecessor from the loop, i.e. the
116 // PrologLatch. When supporting multiple-exiting block loops, we can have
117 // two or more blocks that have the LatchExit as the target in the
118 // original loop.
119 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr");
120 NewPN->insertBefore(PrologExit->getFirstNonPHIIt());
121 // Adding a value to the new PHI node from the original loop preheader.
122 // This is the value that skips all the prolog code.
123 if (L->contains(&PN)) {
124 // Succ is loop header.
125 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
126 PreHeader);
127 } else {
128 // Succ is LatchExit.
129 NewPN->addIncoming(PoisonValue::get(PN.getType()), PreHeader);
130 }
131
132 Value *V = PN.getIncomingValueForBlock(Latch);
134 if (L->contains(I)) {
135 V = VMap.lookup(I);
136 }
137 }
138 // Adding a value to the new PHI node from the last prolog block
139 // that was created.
140 NewPN->addIncoming(V, PrologLatch);
141
142 // Update the existing PHI node operand with the value from the
143 // new PHI node. How this is done depends on if the existing
144 // PHI node is in the original loop block, or the exit block.
145 if (L->contains(&PN))
146 PN.setIncomingValueForBlock(NewPreHeader, NewPN);
147 else
148 PN.addIncoming(NewPN, PrologExit);
150 }
151 }
152
153 // Make sure that created prolog loop is in simplified form
154 SmallVector<BasicBlock *, 4> PrologExitPreds;
155 Loop *PrologLoop = LI->getLoopFor(PrologLatch);
156 if (PrologLoop) {
157 for (BasicBlock *PredBB : predecessors(PrologExit))
158 if (PrologLoop->contains(PredBB))
159 PrologExitPreds.push_back(PredBB);
160
161 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
162 nullptr, PreserveLCSSA);
163 }
164
165 // Create a branch around the original loop, which is taken if there are no
166 // iterations remaining to be executed after running the prologue.
167 Instruction *InsertPt = PrologExit->getTerminator();
168 IRBuilder<> B(InsertPt);
169
170 assert(Count != 0 && "nonsensical Count!");
171
172 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
173 // This means %xtraiter is (BECount + 1) and all of the iterations of this
174 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
175 // then (BECount + 1) cannot unsigned-overflow.
176 Value *BrLoopExit =
177 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
178 // Split the exit to maintain loop canonicalization guarantees
179 SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
180 SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
181 nullptr, PreserveLCSSA);
182 // Add the branch to the exit block (around the unrolled loop)
183 MDNode *BranchWeights = nullptr;
184 if (hasBranchWeightMD(*Latch->getTerminator())) {
185 // Assume loop is nearly always entered.
186 MDBuilder MDB(B.getContext());
188 }
189 B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader,
190 BranchWeights);
191 InsertPt->eraseFromParent();
192 if (DT) {
193 auto *NewDom = DT->findNearestCommonDominator(OriginalLoopLatchExit,
194 PrologExit);
195 DT->changeImmediateDominator(OriginalLoopLatchExit, NewDom);
196 }
197}
198
199/// Assume, due to our position in the remainder loop or its guard, anywhere
200/// from 0 to \p N more iterations can possibly execute. Among such cases in
201/// the original loop (with loop probability \p OriginalLoopProb), what is the
202/// probability of executing at least one more iteration?
204probOfNextInRemainder(BranchProbability OriginalLoopProb, unsigned N) {
205 // OriginalLoopProb == 1 would produce a division by zero in the calculation
206 // below. The problem is that case indicates an always infinite loop, but a
207 // remainder loop cannot be calculated at run time if the original loop is
208 // infinite as infinity % UnrollCount is undefined. We then choose
209 // probabilities indicating that all remainder loop iterations will always
210 // execute.
211 //
212 // Currently, the remainder loop here is an epilogue, which cannot be reached
213 // if the original loop is infinite, so the aforementioned choice is
214 // arbitrary.
215 //
216 // FIXME: Branch weights still need to be fixed in the case of prologues
217 // (issue #135812). In that case, the aforementioned choice seems reasonable
218 // for the goal of maintaining the original loop's block frequencies. That
219 // is, an infinite loop's initial iterations are not skipped, and the prologue
220 // loop body might have unique blocks that execute a finite number of times
221 // if, for example, the original loop body contains conditionals like i <
222 // UnrollCount.
223 if (OriginalLoopProb == BranchProbability::getOne())
225
226 // Each of these variables holds the original loop's probability that the
227 // number of iterations it will execute is some m in the specified range.
228 BranchProbability ProbOne = OriginalLoopProb; // 1 <= m
229 BranchProbability ProbTooMany = ProbOne.pow(N + 1); // N + 1 <= m
230 BranchProbability ProbNotTooMany = ProbTooMany.getCompl(); // 0 <= m <= N
231 BranchProbability ProbOneNotTooMany = ProbOne - ProbTooMany; // 1 <= m <= N
232 return ProbOneNotTooMany / ProbNotTooMany;
233}
234
235/// Connect the unrolling epilog code to the original loop.
236/// The unrolling epilog code contains code to execute the
237/// 'extra' iterations if the run-time trip count modulo the
238/// unroll count is non-zero.
239///
240/// This function performs the following:
241/// - Update PHI nodes at the epilog loop exit
242/// - Create PHI nodes at the unrolling loop exit and epilog preheader to
243/// combine values that exit the unrolling loop code and jump around it.
244/// - Update PHI operands in the epilog loop by the new PHI nodes
245/// - At the unrolling loop exit, branch around the epilog loop if extra iters
246// (ModVal) is zero.
247/// - At the epilog preheader, add an llvm.assume call that extra iters is
248/// non-zero. If the unrolling loop exit is the predecessor, the above new
249/// branch guarantees that assumption. If the unrolling loop preheader is the
250/// predecessor, then the required first iteration from the original loop has
251/// yet to be executed, so it must be executed in the epilog loop. If we
252/// later unroll the epilog loop, that llvm.assume call somehow enables
253/// ScalarEvolution to compute a epilog loop maximum trip count, which enables
254/// eliminating the branch at the end of the final unrolled epilog iteration.
255///
256static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
257 BasicBlock *Exit, BasicBlock *PreHeader,
258 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
260 LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE,
261 unsigned Count, AssumptionCache &AC,
262 BranchProbability OriginalLoopProb) {
263 BasicBlock *Latch = L->getLoopLatch();
264 assert(Latch && "Loop must have a latch");
265 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
266
267 // Loop structure should be the following:
268 //
269 // PreHeader
270 // NewPreHeader
271 // Header
272 // ...
273 // Latch
274 // NewExit (PN)
275 // EpilogPreHeader
276 // EpilogHeader
277 // ...
278 // EpilogLatch
279 // Exit (EpilogPN)
280
281 // Update PHI nodes at Exit.
282 for (PHINode &PN : NewExit->phis()) {
283 // PN should be used in another PHI located in Exit block as
284 // Exit was split by SplitBlockPredecessors into Exit and NewExit
285 // Basically it should look like:
286 // NewExit:
287 // PN = PHI [I, Latch]
288 // ...
289 // Exit:
290 // EpilogPN = PHI [PN, EpilogPreHeader], [X, Exit2], [Y, Exit2.epil]
291 //
292 // Exits from non-latch blocks point to the original exit block and the
293 // epilogue edges have already been added.
294 //
295 // There is EpilogPreHeader incoming block instead of NewExit as
296 // NewExit was split 1 more time to get EpilogPreHeader.
297 assert(PN.hasOneUse() && "The phi should have 1 use");
298 PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
299 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
300
301 Value *V = PN.getIncomingValueForBlock(Latch);
303 if (I && L->contains(I))
304 // If value comes from an instruction in the loop add VMap value.
305 V = VMap.lookup(I);
306 // For the instruction out of the loop, constant or undefined value
307 // insert value itself.
308 EpilogPN->addIncoming(V, EpilogLatch);
309
310 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
311 "EpilogPN should have EpilogPreHeader incoming block");
312 // Change EpilogPreHeader incoming block to NewExit.
313 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
314 NewExit);
315 // Now PHIs should look like:
316 // NewExit:
317 // PN = PHI [I, Latch]
318 // ...
319 // Exit:
320 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
321 }
322
323 // Create PHI nodes at NewExit (from the unrolling loop Latch) and at
324 // EpilogPreHeader (from PreHeader and NewExit). Update corresponding PHI
325 // nodes in epilog loop.
326 for (BasicBlock *Succ : successors(Latch)) {
327 // Skip this as we already updated phis in exit blocks.
328 if (!L->contains(Succ))
329 continue;
330
331 // Succ here appears to always be just L->getHeader(). Otherwise, how do we
332 // know its corresponding epilog block (from VMap) is EpilogHeader and thus
333 // EpilogPreHeader is the right incoming block for VPN, as set below?
334 // TODO: Can we thus avoid the enclosing loop over successors?
335 assert(Succ == L->getHeader() &&
336 "Expect the only in-loop successor of latch to be the loop header");
337
338 for (PHINode &PN : Succ->phis()) {
339 // Add new PHI nodes to the loop exit block.
340 PHINode *NewPN0 = PHINode::Create(PN.getType(), /*NumReservedValues=*/1,
341 PN.getName() + ".unr");
342 NewPN0->insertBefore(NewExit->getFirstNonPHIIt());
343 // Add value to the new PHI node from the unrolling loop latch.
344 NewPN0->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
345
346 // Add new PHI nodes to EpilogPreHeader.
347 PHINode *NewPN1 = PHINode::Create(PN.getType(), /*NumReservedValues=*/2,
348 PN.getName() + ".epil.init");
349 NewPN1->insertBefore(EpilogPreHeader->getFirstNonPHIIt());
350 // Add value to the new PHI node from the unrolling loop preheader.
351 NewPN1->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
352 // Add value to the new PHI node from the epilog loop guard.
353 NewPN1->addIncoming(NewPN0, NewExit);
354
355 // Update the existing PHI node operand with the value from the new PHI
356 // node. Corresponding instruction in epilog loop should be PHI.
357 PHINode *VPN = cast<PHINode>(VMap[&PN]);
358 VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN1);
359 }
360 }
361
362 // In NewExit, branch around the epilog loop if no extra iters.
363 Instruction *InsertPt = NewExit->getTerminator();
364 IRBuilder<> B(InsertPt);
365 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
366 assert(Exit && "Loop must have a single exit block only");
367 // Split the epilogue exit to maintain loop canonicalization guarantees
369 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
370 PreserveLCSSA);
371 // Add the branch to the exit block (around the epilog loop)
372 MDNode *BranchWeights = nullptr;
373 if (OriginalLoopProb.isUnknown() &&
374 hasBranchWeightMD(*Latch->getTerminator())) {
375 // Assume equal distribution in interval [0, Count).
376 MDBuilder MDB(B.getContext());
377 BranchWeights = MDB.createBranchWeights(1, Count - 1);
378 }
379 BranchInst *RemainderLoopGuard =
380 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit, BranchWeights);
381 if (!OriginalLoopProb.isUnknown()) {
382 setBranchProbability(RemainderLoopGuard,
383 probOfNextInRemainder(OriginalLoopProb, Count - 1),
384 /*ForFirstTarget=*/true);
385 }
386 InsertPt->eraseFromParent();
387 if (DT) {
388 auto *NewDom = DT->findNearestCommonDominator(Exit, NewExit);
389 DT->changeImmediateDominator(Exit, NewDom);
390 }
391
392 // In EpilogPreHeader, assume extra iters is non-zero.
393 IRBuilder<> B2(EpilogPreHeader, EpilogPreHeader->getFirstNonPHIIt());
394 Value *ModIsNotNull = B2.CreateIsNotNull(ModVal, "lcmp.mod");
395 AssumeInst *AI = cast<AssumeInst>(B2.CreateAssumption(ModIsNotNull));
396 AC.registerAssumption(AI);
397}
398
399/// Create a clone of the blocks in a loop and connect them together. A new
400/// loop will be created including all cloned blocks, and the iterator of the
401/// new loop switched to count NewIter down to 0.
402/// The cloned blocks should be inserted between InsertTop and InsertBot.
403/// InsertTop should be new preheader, InsertBot new loop exit.
404/// Returns the new cloned loop that is created.
405static Loop *CloneLoopBlocks(Loop *L, Value *NewIter,
406 const bool UseEpilogRemainder,
407 const bool UnrollRemainder, BasicBlock *InsertTop,
408 BasicBlock *InsertBot, BasicBlock *Preheader,
409 std::vector<BasicBlock *> &NewBlocks,
410 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
411 DominatorTree *DT, LoopInfo *LI, unsigned Count,
412 std::optional<unsigned> OriginalTripCount,
413 BranchProbability OriginalLoopProb) {
414 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
415 BasicBlock *Header = L->getHeader();
416 BasicBlock *Latch = L->getLoopLatch();
417 Function *F = Header->getParent();
418 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
419 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
420 Loop *ParentLoop = L->getParentLoop();
421 NewLoopsMap NewLoops;
422 NewLoops[ParentLoop] = ParentLoop;
423
424 // For each block in the original loop, create a new copy,
425 // and update the value map with the newly created values.
426 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
427 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
428 NewBlocks.push_back(NewBB);
429
430 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
431
432 VMap[*BB] = NewBB;
433 if (Header == *BB) {
434 // For the first block, add a CFG connection to this newly
435 // created block.
436 InsertTop->getTerminator()->setSuccessor(0, NewBB);
437 }
438
439 if (DT) {
440 if (Header == *BB) {
441 // The header is dominated by the preheader.
442 DT->addNewBlock(NewBB, InsertTop);
443 } else {
444 // Copy information from original loop to unrolled loop.
445 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
446 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
447 }
448 }
449
450 if (Latch == *BB) {
451 // For the last block, create a loop back to cloned head.
452 VMap.erase((*BB)->getTerminator());
453 // Use an incrementing IV. Pre-incr/post-incr is backedge/trip count.
454 // Subtle: NewIter can be 0 if we wrapped when computing the trip count,
455 // thus we must compare the post-increment (wrapping) value.
456 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
457 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
458 IRBuilder<> Builder(LatchBR);
459 PHINode *NewIdx =
460 PHINode::Create(NewIter->getType(), 2, suffix + ".iter");
461 NewIdx->insertBefore(FirstLoopBB->getFirstNonPHIIt());
462 auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
463 auto *One = ConstantInt::get(NewIdx->getType(), 1);
464 Value *IdxNext =
465 Builder.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
466 Value *IdxCmp = Builder.CreateICmpNE(IdxNext, NewIter, NewIdx->getName() + ".cmp");
467 MDNode *BranchWeights = nullptr;
468 if ((OriginalLoopProb.isUnknown() || !UseEpilogRemainder) &&
469 hasBranchWeightMD(*LatchBR)) {
470 uint32_t ExitWeight;
471 uint32_t BackEdgeWeight;
472 if (Count >= 3) {
473 // Note: We do not enter this loop for zero-remainders. The check
474 // is at the end of the loop. We assume equal distribution between
475 // possible remainders in [1, Count).
476 ExitWeight = 1;
477 BackEdgeWeight = (Count - 2) / 2;
478 } else {
479 // Unnecessary backedge, should never be taken. The conditional
480 // jump should be optimized away later.
481 ExitWeight = 1;
482 BackEdgeWeight = 0;
483 }
484 MDBuilder MDB(Builder.getContext());
485 BranchWeights = MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
486 }
487 BranchInst *RemainderLoopLatch =
488 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot, BranchWeights);
489 if (!OriginalLoopProb.isUnknown() && UseEpilogRemainder) {
490 // Compute the total frequency of the original loop body from the
491 // remainder iterations. Once we've reached them, the first of them
492 // always executes, so its frequency and probability are 1.
493 double FreqRemIters = 1;
494 if (Count > 2) {
496 for (unsigned N = Count - 2; N >= 1; --N) {
497 ProbReaching *= probOfNextInRemainder(OriginalLoopProb, N);
498 FreqRemIters += double(ProbReaching.getNumerator()) /
499 ProbReaching.getDenominator();
500 }
501 }
502 // Solve for the loop probability that would produce that frequency.
503 // Sum(i=0..inf)(Prob^i) = 1/(1-Prob) = FreqRemIters.
504 double ProbDouble = 1 - 1 / FreqRemIters;
506 std::round(ProbDouble * BranchProbability::getDenominator()),
508 setBranchProbability(RemainderLoopLatch, Prob, /*ForFirstTarget=*/true);
509 }
510 NewIdx->addIncoming(Zero, InsertTop);
511 NewIdx->addIncoming(IdxNext, NewBB);
512 LatchBR->eraseFromParent();
513 }
514 }
515
516 // Change the incoming values to the ones defined in the preheader or
517 // cloned loop.
518 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
519 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
520 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
521 NewPHI->setIncomingBlock(idx, InsertTop);
522 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
523 idx = NewPHI->getBasicBlockIndex(Latch);
524 Value *InVal = NewPHI->getIncomingValue(idx);
525 NewPHI->setIncomingBlock(idx, NewLatch);
526 if (Value *V = VMap.lookup(InVal))
527 NewPHI->setIncomingValue(idx, V);
528 }
529
530 Loop *NewLoop = NewLoops[L];
531 assert(NewLoop && "L should have been cloned");
532
533 if (OriginalTripCount && UseEpilogRemainder)
534 setLoopEstimatedTripCount(NewLoop, *OriginalTripCount % Count);
535
536 // Add unroll disable metadata to disable future unrolling for this loop.
537 if (!UnrollRemainder)
538 NewLoop->setLoopAlreadyUnrolled();
539 return NewLoop;
540}
541
542/// Returns true if we can profitably unroll the multi-exit loop L. Currently,
543/// we return true only if UnrollRuntimeMultiExit is set to true.
545 Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
546 bool UseEpilogRemainder) {
547
548 // The main pain point with multi-exit loop unrolling is that once unrolled,
549 // we will not be able to merge all blocks into a straight line code.
550 // There are branches within the unrolled loop that go to the OtherExits.
551 // The second point is the increase in code size, but this is true
552 // irrespective of multiple exits.
553
554 // Note: Both the heuristics below are coarse grained. We are essentially
555 // enabling unrolling of loops that have a single side exit other than the
556 // normal LatchExit (i.e. exiting into a deoptimize block).
557 // The heuristics considered are:
558 // 1. low number of branches in the unrolled version.
559 // 2. high predictability of these extra branches.
560 // We avoid unrolling loops that have more than two exiting blocks. This
561 // limits the total number of branches in the unrolled loop to be atmost
562 // the unroll factor (since one of the exiting blocks is the latch block).
563 SmallVector<BasicBlock*, 4> ExitingBlocks;
564 L->getExitingBlocks(ExitingBlocks);
565 if (ExitingBlocks.size() > 2)
566 return false;
567
568 // Allow unrolling of loops with no non latch exit blocks.
569 if (OtherExits.size() == 0)
570 return true;
571
572 // The second heuristic is that L has one exit other than the latchexit and
573 // that exit is a deoptimize block. We know that deoptimize blocks are rarely
574 // taken, which also implies the branch leading to the deoptimize block is
575 // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we
576 // assume the other exit branch is predictable even if it has no deoptimize
577 // call.
578 return (OtherExits.size() == 1 &&
580 OtherExits[0]->getPostdominatingDeoptimizeCall()));
581 // TODO: These can be fine-tuned further to consider code size or deopt states
582 // that are captured by the deoptimize exit block.
583 // Also, we can extend this to support more cases, if we actually
584 // know of kinds of multiexit loops that would benefit from unrolling.
585}
586
587/// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
588/// accounting for the possibility of unsigned overflow in the 2s complement
589/// domain. Preconditions:
590/// 1) TripCount = BECount + 1 (allowing overflow)
591/// 2) Log2(Count) <= BitWidth(BECount)
593 Value *TripCount, unsigned Count) {
594 // Note that TripCount is BECount + 1.
595 if (isPowerOf2_32(Count))
596 // If the expression is zero, then either:
597 // 1. There are no iterations to be run in the prolog/epilog loop.
598 // OR
599 // 2. The addition computing TripCount overflowed.
600 //
601 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
602 // the number of iterations that remain to be run in the original loop is a
603 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
604 // precondition of this method).
605 return B.CreateAnd(TripCount, Count - 1, "xtraiter");
606
607 // As (BECount + 1) can potentially unsigned overflow we count
608 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
609 Constant *CountC = ConstantInt::get(BECount->getType(), Count);
610 Value *ModValTmp = B.CreateURem(BECount, CountC);
611 Value *ModValAdd = B.CreateAdd(ModValTmp,
612 ConstantInt::get(ModValTmp->getType(), 1));
613 // At that point (BECount % Count) + 1 could be equal to Count.
614 // To handle this case we need to take mod by Count one more time.
615 return B.CreateURem(ModValAdd, CountC, "xtraiter");
616}
617
618
619/// Insert code in the prolog/epilog code when unrolling a loop with a
620/// run-time trip-count.
621///
622/// This method assumes that the loop unroll factor is total number
623/// of loop bodies in the loop after unrolling. (Some folks refer
624/// to the unroll factor as the number of *extra* copies added).
625/// We assume also that the loop unroll factor is a power-of-two. So, after
626/// unrolling the loop, the number of loop bodies executed is 2,
627/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
628/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
629/// the switch instruction is generated.
630///
631/// ***Prolog case***
632/// extraiters = tripcount % loopfactor
633/// if (extraiters == 0) jump Loop:
634/// else jump Prol:
635/// Prol: LoopBody;
636/// extraiters -= 1 // Omitted if unroll factor is 2.
637/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
638/// if (tripcount < loopfactor) jump End:
639/// Loop:
640/// ...
641/// End:
642///
643/// ***Epilog case***
644/// extraiters = tripcount % loopfactor
645/// if (tripcount < loopfactor) jump LoopExit:
646/// unroll_iters = tripcount - extraiters
647/// Loop: LoopBody; (executes unroll_iter times);
648/// unroll_iter -= 1
649/// if (unroll_iter != 0) jump Loop:
650/// LoopExit:
651/// if (extraiters == 0) jump EpilExit:
652/// Epil: LoopBody; (executes extraiters times)
653/// extraiters -= 1 // Omitted if unroll factor is 2.
654/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
655/// EpilExit:
656
658 Loop *L, unsigned Count, bool AllowExpensiveTripCount,
659 bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV,
661 const TargetTransformInfo *TTI, bool PreserveLCSSA,
662 unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit,
663 Loop **ResultLoop, std::optional<unsigned> OriginalTripCount,
664 BranchProbability OriginalLoopProb) {
665 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
666 LLVM_DEBUG(L->dump());
667 LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
668 : dbgs() << "Using prolog remainder.\n");
669
670 // Make sure the loop is in canonical form.
671 if (!L->isLoopSimplifyForm()) {
672 LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
673 return false;
674 }
675
676 // Guaranteed by LoopSimplifyForm.
677 BasicBlock *Latch = L->getLoopLatch();
678 BasicBlock *Header = L->getHeader();
679
680 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
681
682 if (!LatchBR || LatchBR->isUnconditional()) {
683 // The loop-rotate pass can be helpful to avoid this in many cases.
685 dbgs()
686 << "Loop latch not terminated by a conditional branch.\n");
687 return false;
688 }
689
690 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
691 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
692
693 if (L->contains(LatchExit)) {
694 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
695 // targets of the Latch be an exit block out of the loop.
697 dbgs()
698 << "One of the loop latch successors must be the exit block.\n");
699 return false;
700 }
701
702 // These are exit blocks other than the target of the latch exiting block.
704 L->getUniqueNonLatchExitBlocks(OtherExits);
705 // Support only single exit and exiting block unless multi-exit loop
706 // unrolling is enabled.
707 if (!L->getExitingBlock() || OtherExits.size()) {
708 // We rely on LCSSA form being preserved when the exit blocks are transformed.
709 // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
710 if (!PreserveLCSSA)
711 return false;
712
713 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
714 if (UnrollRuntimeMultiExit.getNumOccurrences()) {
716 return false;
717 } else {
718 // Otherwise perform multi-exit unrolling, if either the target indicates
719 // it is profitable or the general profitability heuristics apply.
720 if (!RuntimeUnrollMultiExit &&
721 !canProfitablyRuntimeUnrollMultiExitLoop(L, OtherExits, LatchExit,
722 UseEpilogRemainder)) {
723 LLVM_DEBUG(dbgs() << "Multiple exit/exiting blocks in loop and "
724 "multi-exit unrolling not enabled!\n");
725 return false;
726 }
727 }
728 }
729 // Use Scalar Evolution to compute the trip count. This allows more loops to
730 // be unrolled than relying on induction var simplification.
731 if (!SE)
732 return false;
733
734 // Only unroll loops with a computable trip count.
735 // We calculate the backedge count by using getExitCount on the Latch block,
736 // which is proven to be the only exiting block in this loop. This is same as
737 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
738 // exiting blocks).
739 const SCEV *BECountSC = SE->getExitCount(L, Latch);
740 if (isa<SCEVCouldNotCompute>(BECountSC)) {
741 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
742 return false;
743 }
744
745 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
746
747 // Add 1 since the backedge count doesn't include the first loop iteration.
748 // (Note that overflow can occur, this is handled explicitly below)
749 const SCEV *TripCountSC =
750 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
751 if (isa<SCEVCouldNotCompute>(TripCountSC)) {
752 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
753 return false;
754 }
755
756 BasicBlock *PreHeader = L->getLoopPreheader();
757 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
758 const DataLayout &DL = Header->getDataLayout();
759 SCEVExpander Expander(*SE, DL, "loop-unroll");
760 if (!AllowExpensiveTripCount &&
761 Expander.isHighCostExpansion(TripCountSC, L, SCEVExpansionBudget, TTI,
762 PreHeaderBR)) {
763 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
764 return false;
765 }
766
767 // This constraint lets us deal with an overflowing trip count easily; see the
768 // comment on ModVal below.
769 if (Log2_32(Count) > BEWidth) {
771 dbgs()
772 << "Count failed constraint on overflow trip count calculation.\n");
773 return false;
774 }
775
776 // Loop structure is the following:
777 //
778 // PreHeader
779 // Header
780 // ...
781 // Latch
782 // LatchExit
783
784 BasicBlock *NewPreHeader;
785 BasicBlock *NewExit = nullptr;
786 BasicBlock *PrologExit = nullptr;
787 BasicBlock *EpilogPreHeader = nullptr;
788 BasicBlock *PrologPreHeader = nullptr;
789
790 if (UseEpilogRemainder) {
791 // If epilog remainder
792 // Split PreHeader to insert a branch around loop for unrolling.
793 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
794 NewPreHeader->setName(PreHeader->getName() + ".new");
795 // Split LatchExit to create phi nodes from branch above.
796 NewExit = SplitBlockPredecessors(LatchExit, {Latch}, ".unr-lcssa", DT, LI,
797 nullptr, PreserveLCSSA);
798 // NewExit gets its DebugLoc from LatchExit, which is not part of the
799 // original Loop.
800 // Fix this by setting Loop's DebugLoc to NewExit.
801 auto *NewExitTerminator = NewExit->getTerminator();
802 NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
803 // Split NewExit to insert epilog remainder loop.
804 EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
805 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
806
807 // If the latch exits from multiple level of nested loops, then
808 // by assumption there must be another loop exit which branches to the
809 // outer loop and we must adjust the loop for the newly inserted blocks
810 // to account for the fact that our epilogue is still in the same outer
811 // loop. Note that this leaves loopinfo temporarily out of sync with the
812 // CFG until the actual epilogue loop is inserted.
813 if (auto *ParentL = L->getParentLoop())
814 if (LI->getLoopFor(LatchExit) != ParentL) {
815 LI->removeBlock(NewExit);
816 ParentL->addBasicBlockToLoop(NewExit, *LI);
817 LI->removeBlock(EpilogPreHeader);
818 ParentL->addBasicBlockToLoop(EpilogPreHeader, *LI);
819 }
820
821 } else {
822 // If prolog remainder
823 // Split the original preheader twice to insert prolog remainder loop
824 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
825 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
826 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
827 DT, LI);
828 PrologExit->setName(Header->getName() + ".prol.loopexit");
829 // Split PrologExit to get NewPreHeader.
830 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
831 NewPreHeader->setName(PreHeader->getName() + ".new");
832 }
833 // Loop structure should be the following:
834 // Epilog Prolog
835 //
836 // PreHeader PreHeader
837 // *NewPreHeader *PrologPreHeader
838 // Header *PrologExit
839 // ... *NewPreHeader
840 // Latch Header
841 // *NewExit ...
842 // *EpilogPreHeader Latch
843 // LatchExit LatchExit
844
845 // Calculate conditions for branch around loop for unrolling
846 // in epilog case and around prolog remainder loop in prolog case.
847 // Compute the number of extra iterations required, which is:
848 // extra iterations = run-time trip count % loop unroll factor
849 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
850 IRBuilder<> B(PreHeaderBR);
851 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
852 PreHeaderBR);
853 Value *BECount;
854 // If there are other exits before the latch, that may cause the latch exit
855 // branch to never be executed, and the latch exit count may be poison.
856 // In this case, freeze the TripCount and base BECount on the frozen
857 // TripCount. We will introduce two branches using these values, and it's
858 // important that they see a consistent value (which would not be guaranteed
859 // if were frozen independently.)
860 if ((!OtherExits.empty() || !SE->loopHasNoAbnormalExits(L)) &&
861 !isGuaranteedNotToBeUndefOrPoison(TripCount, AC, PreHeaderBR, DT)) {
862 TripCount = B.CreateFreeze(TripCount);
863 BECount =
864 B.CreateAdd(TripCount, Constant::getAllOnesValue(TripCount->getType()));
865 } else {
866 // If we don't need to freeze, use SCEVExpander for BECount as well, to
867 // allow slightly better value reuse.
868 BECount =
869 Expander.expandCodeFor(BECountSC, BECountSC->getType(), PreHeaderBR);
870 }
871
872 Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count);
873
874 Value *BranchVal =
875 UseEpilogRemainder ? B.CreateICmpULT(BECount,
876 ConstantInt::get(BECount->getType(),
877 Count - 1)) :
878 B.CreateIsNotNull(ModVal, "lcmp.mod");
879 BasicBlock *RemainderLoop =
880 UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
881 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
882 // Branch to either remainder (extra iterations) loop or unrolling loop.
883 MDNode *BranchWeights = nullptr;
884 if ((OriginalLoopProb.isUnknown() || !UseEpilogRemainder) &&
885 hasBranchWeightMD(*Latch->getTerminator())) {
886 // Assume loop is nearly always entered.
887 MDBuilder MDB(B.getContext());
888 BranchWeights = MDB.createBranchWeights(EpilogHeaderWeights);
889 }
890 BranchInst *UnrollingLoopGuard =
891 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop, BranchWeights);
892 if (!OriginalLoopProb.isUnknown() && UseEpilogRemainder) {
893 // The original loop's first iteration always happens. Compute the
894 // probability of the original loop executing Count-1 iterations after that
895 // to complete the first iteration of the unrolled loop.
896 BranchProbability ProbOne = OriginalLoopProb;
897 BranchProbability ProbRest = ProbOne.pow(Count - 1);
898 setBranchProbability(UnrollingLoopGuard, ProbRest,
899 /*ForFirstTarget=*/false);
900 }
901 PreHeaderBR->eraseFromParent();
902 if (DT) {
903 if (UseEpilogRemainder)
904 DT->changeImmediateDominator(EpilogPreHeader, PreHeader);
905 else
906 DT->changeImmediateDominator(PrologExit, PreHeader);
907 }
908 Function *F = Header->getParent();
909 // Get an ordered list of blocks in the loop to help with the ordering of the
910 // cloned blocks in the prolog/epilog code
911 LoopBlocksDFS LoopBlocks(L);
912 LoopBlocks.perform(LI);
913
914 //
915 // For each extra loop iteration, create a copy of the loop's basic blocks
916 // and generate a condition that branches to the copy depending on the
917 // number of 'left over' iterations.
918 //
919 std::vector<BasicBlock *> NewBlocks;
921
922 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
923 // the loop, otherwise we create a cloned loop to execute the extra
924 // iterations. This function adds the appropriate CFG connections.
925 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
926 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
927 Loop *remainderLoop =
928 CloneLoopBlocks(L, ModVal, UseEpilogRemainder, UnrollRemainder, InsertTop,
929 InsertBot, NewPreHeader, NewBlocks, LoopBlocks, VMap, DT,
930 LI, Count, OriginalTripCount, OriginalLoopProb);
931
932 // Insert the cloned blocks into the function.
933 F->splice(InsertBot->getIterator(), F, NewBlocks[0]->getIterator(), F->end());
934
935 // Now the loop blocks are cloned and the other exiting blocks from the
936 // remainder are connected to the original Loop's exit blocks. The remaining
937 // work is to update the phi nodes in the original loop, and take in the
938 // values from the cloned region.
939 for (auto *BB : OtherExits) {
940 // Given we preserve LCSSA form, we know that the values used outside the
941 // loop will be used through these phi nodes at the exit blocks that are
942 // transformed below.
943 for (PHINode &PN : BB->phis()) {
944 unsigned oldNumOperands = PN.getNumIncomingValues();
945 // Add the incoming values from the remainder code to the end of the phi
946 // node.
947 for (unsigned i = 0; i < oldNumOperands; i++){
948 auto *PredBB =PN.getIncomingBlock(i);
949 if (PredBB == Latch)
950 // The latch exit is handled separately, see connectX
951 continue;
952 if (!L->contains(PredBB))
953 // Even if we had dedicated exits, the code above inserted an
954 // extra branch which can reach the latch exit.
955 continue;
956
957 auto *V = PN.getIncomingValue(i);
959 if (L->contains(I))
960 V = VMap.lookup(I);
961 PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB]));
962 }
963 }
964#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
965 for (BasicBlock *SuccBB : successors(BB)) {
966 assert(!(llvm::is_contained(OtherExits, SuccBB) || SuccBB == LatchExit) &&
967 "Breaks the definition of dedicated exits!");
968 }
969#endif
970 }
971
972 // Update the immediate dominator of the exit blocks and blocks that are
973 // reachable from the exit blocks. This is needed because we now have paths
974 // from both the original loop and the remainder code reaching the exit
975 // blocks. While the IDom of these exit blocks were from the original loop,
976 // now the IDom is the preheader (which decides whether the original loop or
977 // remainder code should run) unless the block still has just the original
978 // predecessor (such as NewExit in the case of an epilog remainder).
979 if (DT && !L->getExitingBlock()) {
980 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
981 // NB! We have to examine the dom children of all loop blocks, not just
982 // those which are the IDom of the exit blocks. This is because blocks
983 // reachable from the exit blocks can have their IDom as the nearest common
984 // dominator of the exit blocks.
985 for (auto *BB : L->blocks()) {
986 auto *DomNodeBB = DT->getNode(BB);
987 for (auto *DomChild : DomNodeBB->children()) {
988 auto *DomChildBB = DomChild->getBlock();
989 if (!L->contains(LI->getLoopFor(DomChildBB)) &&
990 DomChildBB->getUniquePredecessor() != BB)
991 ChildrenToUpdate.push_back(DomChildBB);
992 }
993 }
994 for (auto *BB : ChildrenToUpdate)
995 DT->changeImmediateDominator(BB, PreHeader);
996 }
997
998 // Loop structure should be the following:
999 // Epilog Prolog
1000 //
1001 // PreHeader PreHeader
1002 // NewPreHeader PrologPreHeader
1003 // Header PrologHeader
1004 // ... ...
1005 // Latch PrologLatch
1006 // NewExit PrologExit
1007 // EpilogPreHeader NewPreHeader
1008 // EpilogHeader Header
1009 // ... ...
1010 // EpilogLatch Latch
1011 // LatchExit LatchExit
1012
1013 // Rewrite the cloned instruction operands to use the values created when the
1014 // clone is created.
1015 for (BasicBlock *BB : NewBlocks) {
1016 Module *M = BB->getModule();
1017 for (Instruction &I : *BB) {
1018 RemapInstruction(&I, VMap,
1020 RemapDbgRecordRange(M, I.getDbgRecordRange(), VMap,
1022 }
1023 }
1024
1025 if (UseEpilogRemainder) {
1026 // Connect the epilog code to the original loop and update the
1027 // PHI functions.
1028 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, EpilogPreHeader,
1029 NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE, Count, *AC,
1030 OriginalLoopProb);
1031
1032 // Update counter in loop for unrolling.
1033 // Use an incrementing IV. Pre-incr/post-incr is backedge/trip count.
1034 // Subtle: TestVal can be 0 if we wrapped when computing the trip count,
1035 // thus we must compare the post-increment (wrapping) value.
1036 IRBuilder<> B2(NewPreHeader->getTerminator());
1037 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
1038 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
1039 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter");
1040 NewIdx->insertBefore(Header->getFirstNonPHIIt());
1041 B2.SetInsertPoint(LatchBR);
1042 auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
1043 auto *One = ConstantInt::get(NewIdx->getType(), 1);
1044 Value *IdxNext = B2.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
1045 auto Pred = LatchBR->getSuccessor(0) == Header ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
1046 Value *IdxCmp = B2.CreateICmp(Pred, IdxNext, TestVal, NewIdx->getName() + ".ncmp");
1047 NewIdx->addIncoming(Zero, NewPreHeader);
1048 NewIdx->addIncoming(IdxNext, Latch);
1049 LatchBR->setCondition(IdxCmp);
1050 } else {
1051 // Connect the prolog code to the original loop and update the
1052 // PHI functions.
1053 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
1054 NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE);
1055 }
1056
1057 // If this loop is nested, then the loop unroller changes the code in the any
1058 // of its parent loops, so the Scalar Evolution pass needs to be run again.
1059 SE->forgetTopmostLoop(L);
1060
1061 // Verify that the Dom Tree and Loop Info are correct.
1062#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
1063 if (DT) {
1064 assert(DT->verify(DominatorTree::VerificationLevel::Full));
1065 LI->verify(*DT);
1066 }
1067#endif
1068
1069 // For unroll factor 2 remainder loop will have 1 iteration.
1070 if (Count == 2 && DT && LI && SE) {
1071 // TODO: This code could probably be pulled out into a helper function
1072 // (e.g. breakLoopBackedgeAndSimplify) and reused in loop-deletion.
1073 BasicBlock *RemainderLatch = remainderLoop->getLoopLatch();
1074 assert(RemainderLatch);
1075 SmallVector<BasicBlock *> RemainderBlocks(remainderLoop->getBlocks());
1076 breakLoopBackedge(remainderLoop, *DT, *SE, *LI, nullptr);
1077 remainderLoop = nullptr;
1078
1079 // Simplify loop values after breaking the backedge
1080 const DataLayout &DL = L->getHeader()->getDataLayout();
1082 for (BasicBlock *BB : RemainderBlocks) {
1083 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
1084 if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
1085 if (LI->replacementPreservesLCSSAForm(&Inst, V))
1086 Inst.replaceAllUsesWith(V);
1087 if (isInstructionTriviallyDead(&Inst))
1088 DeadInsts.emplace_back(&Inst);
1089 }
1090 // We can't do recursive deletion until we're done iterating, as we might
1091 // have a phi which (potentially indirectly) uses instructions later in
1092 // the block we're iterating through.
1094 }
1095
1096 // Merge latch into exit block.
1097 auto *ExitBB = RemainderLatch->getSingleSuccessor();
1098 assert(ExitBB && "required after breaking cond br backedge");
1099 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1100 MergeBlockIntoPredecessor(ExitBB, &DTU, LI);
1101 }
1102
1103 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
1104 // cannot rely on the LoopUnrollPass to do this because it only does
1105 // canonicalization for parent/subloops and not the sibling loops.
1106 if (OtherExits.size() > 0) {
1107 // Generate dedicated exit blocks for the original loop, to preserve
1108 // LoopSimplifyForm.
1109 formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
1110 // Generate dedicated exit blocks for the remainder loop if one exists, to
1111 // preserve LoopSimplifyForm.
1112 if (remainderLoop)
1113 formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
1114 }
1115
1116 auto UnrollResult = LoopUnrollResult::Unmodified;
1117 if (remainderLoop && UnrollRemainder) {
1118 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
1120 ULO.Count = Count - 1;
1121 ULO.Force = false;
1122 ULO.Runtime = false;
1123 ULO.AllowExpensiveTripCount = false;
1124 ULO.UnrollRemainder = false;
1125 ULO.ForgetAllSCEV = ForgetAllSCEV;
1127 "A loop with a convergence heart does not allow runtime unrolling.");
1128 UnrollResult = UnrollLoop(remainderLoop, ULO, LI, SE, DT, AC, TTI,
1129 /*ORE*/ nullptr, PreserveLCSSA);
1130 }
1131
1132 if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
1133 *ResultLoop = remainderLoop;
1134 NumRuntimeUnrolled++;
1135 return true;
1136}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Module.h This file contains the declarations for the Module class.
static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, BasicBlock *Exit, BasicBlock *PreHeader, BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE, unsigned Count, AssumptionCache &AC, BranchProbability OriginalLoopProb)
Connect the unrolling epilog code to the original loop.
static const uint32_t UnrolledLoopHeaderWeights[]
static Value * CreateTripRemainder(IRBuilder<> &B, Value *BECount, Value *TripCount, unsigned Count)
Calculate ModVal = (BECount + 1) % Count on the abstract integer domain accounting for the possibilit...
static Loop * CloneLoopBlocks(Loop *L, Value *NewIter, const bool UseEpilogRemainder, const bool UnrollRemainder, BasicBlock *InsertTop, BasicBlock *InsertBot, BasicBlock *Preheader, std::vector< BasicBlock * > &NewBlocks, LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI, unsigned Count, std::optional< unsigned > OriginalTripCount, BranchProbability OriginalLoopProb)
Create a clone of the blocks in a loop and connect them together.
static cl::opt< bool > UnrollRuntimeOtherExitPredictable("unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden, cl::desc("Assume the non latch exit block to be predictable"))
static bool canProfitablyRuntimeUnrollMultiExitLoop(Loop *L, SmallVectorImpl< BasicBlock * > &OtherExits, BasicBlock *LatchExit, bool UseEpilogRemainder)
Returns true if we can profitably unroll the multi-exit loop L.
static const uint32_t EpilogHeaderWeights[]
static cl::opt< bool > UnrollRuntimeMultiExit("unroll-runtime-multi-exit", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolling for loops with multiple exits, when " "epilog is generated"))
static BranchProbability probOfNextInRemainder(BranchProbability OriginalLoopProb, unsigned N)
Assume, due to our position in the remainder loop or its guard, anywhere from 0 to N more iterations ...
static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, BasicBlock *PrologExit, BasicBlock *OriginalLoopLatchExit, BasicBlock *PreHeader, BasicBlock *NewPreHeader, ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE)
Connect the unrolling prolog code to the original loop.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
This file contains the declarations for profiling metadata utility functions.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:528
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
BranchProbability pow(unsigned N) const
Compute pow(Probability, N).
static BranchProbability getOne()
uint32_t getNumerator() const
BranchProbability getCompl() const
@ ICMP_NE
not equal
Definition InstrTypes.h:698
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI CallInst * CreateAssumption(Value *Cond, ArrayRef< OperandBundleDef > OpBundles={})
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1420
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1403
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2659
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2442
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Store the result of a depth first search within basic blocks contained by a single loop.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:441
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
Definition LoopInfo.cpp:538
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1078
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
void setIncomingBlock(unsigned i, BasicBlock *BB)
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class uses information about analyze scalars to rewrite expressions in canonical form.
bool isHighCostExpansion(ArrayRef< const SCEV * > Exprs, Loop *L, unsigned Budget, const TargetTransformInfo *TTI, const Instruction *At)
Return true for expressions that can't be evaluated at runtime within given Budget.
LLVM_ABI Value * expandCodeFor(const SCEV *SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
bool erase(const KeyT &Val)
Definition ValueMap.h:192
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:533
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
SmallDenseMap< const Loop *, Loop *, 4 > NewLoopsMap
Definition UnrollLoop.h:41
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool setBranchProbability(BranchInst *B, BranchProbability P, bool ForFirstTarget)
Set branch weight metadata for B to indicate that P and 1 - P are the probabilities of control flowin...
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:402
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:331
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
@ Unmodified
The loop was not modified.
Definition UnrollLoop.h:60
@ FullyUnrolled
The loop was fully unrolled into straight-line code.
Definition UnrollLoop.h:69
LLVM_ABI void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA)
Remove the backedge of the specified loop.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
TargetTransformInfo TTI
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
Definition LoopUtils.cpp:58
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, std::optional< unsigned > EstimatedLoopInvocationWeight=std::nullopt)
Set llvm.loop.estimated_trip_count with the value EstimatedTripCount in the loop metadata of L.
LLVM_ABI const Loop * addClonedBlockToLoopInfo(BasicBlock *OriginalBB, BasicBlock *ClonedBB, LoopInfo *LI, NewLoopsMap &NewLoops)
Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary and adds a mapping from the o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1897
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, bool PreserveLCSSA, unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit, Loop **ResultLoop=nullptr, std::optional< unsigned > OriginalTripCount=std::nullopt, BranchProbability OriginalLoopProb=BranchProbability::getUnknown())
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
LLVM_ABI LoopUnrollResult UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const llvm::TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop=nullptr, AAResults *AA=nullptr)
Unroll the given loop by Count.
#define N