LLVM 19.0.0git
LoopUnroll.cpp
Go to the documentation of this file.
1//===-- UnrollLoop.cpp - 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. It does not define any
10// actual pass or policy, but provides a single function to perform loop
11// unrolling.
12//
13// The process of unrolling can produce extraneous basic blocks linked with
14// unconditional branches. This will be corrected in the future.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/Twine.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constants.h"
41#include "llvm/IR/DebugLoc.h"
43#include "llvm/IR/Dominators.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Metadata.h"
49#include "llvm/IR/Module.h"
51#include "llvm/IR/Use.h"
52#include "llvm/IR/User.h"
53#include "llvm/IR/ValueHandle.h"
54#include "llvm/IR/ValueMap.h"
57#include "llvm/Support/Debug.h"
69#include <algorithm>
70#include <assert.h>
71#include <numeric>
72#include <type_traits>
73#include <vector>
74
75namespace llvm {
76class DataLayout;
77class Value;
78} // namespace llvm
79
80using namespace llvm;
81
82#define DEBUG_TYPE "loop-unroll"
83
84// TODO: Should these be here or in LoopUnroll?
85STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
86STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
87STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
88 "latch (completely or otherwise)");
89
90static cl::opt<bool>
91UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
92 cl::desc("Allow runtime unrolled loops to be unrolled "
93 "with epilog instead of prolog."));
94
95static cl::opt<bool>
96UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
97 cl::desc("Verify domtree after unrolling"),
98#ifdef EXPENSIVE_CHECKS
99 cl::init(true)
100#else
101 cl::init(false)
102#endif
103 );
104
105static cl::opt<bool>
106UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
107 cl::desc("Verify loopinfo after unrolling"),
108#ifdef EXPENSIVE_CHECKS
109 cl::init(true)
110#else
111 cl::init(false)
112#endif
113 );
114
115
116/// Check if unrolling created a situation where we need to insert phi nodes to
117/// preserve LCSSA form.
118/// \param Blocks is a vector of basic blocks representing unrolled loop.
119/// \param L is the outer loop.
120/// It's possible that some of the blocks are in L, and some are not. In this
121/// case, if there is a use is outside L, and definition is inside L, we need to
122/// insert a phi-node, otherwise LCSSA will be broken.
123/// The function is just a helper function for llvm::UnrollLoop that returns
124/// true if this situation occurs, indicating that LCSSA needs to be fixed.
126 const std::vector<BasicBlock *> &Blocks,
127 LoopInfo *LI) {
128 for (BasicBlock *BB : Blocks) {
129 if (LI->getLoopFor(BB) == L)
130 continue;
131 for (Instruction &I : *BB) {
132 for (Use &U : I.operands()) {
133 if (const auto *Def = dyn_cast<Instruction>(U)) {
134 Loop *DefLoop = LI->getLoopFor(Def->getParent());
135 if (!DefLoop)
136 continue;
137 if (DefLoop->contains(L))
138 return true;
139 }
140 }
141 }
142 }
143 return false;
144}
145
146/// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
147/// and adds a mapping from the original loop to the new loop to NewLoops.
148/// Returns nullptr if no new loop was created and a pointer to the
149/// original loop OriginalBB was part of otherwise.
151 BasicBlock *ClonedBB, LoopInfo *LI,
152 NewLoopsMap &NewLoops) {
153 // Figure out which loop New is in.
154 const Loop *OldLoop = LI->getLoopFor(OriginalBB);
155 assert(OldLoop && "Should (at least) be in the loop being unrolled!");
156
157 Loop *&NewLoop = NewLoops[OldLoop];
158 if (!NewLoop) {
159 // Found a new sub-loop.
160 assert(OriginalBB == OldLoop->getHeader() &&
161 "Header should be first in RPO");
162
163 NewLoop = LI->AllocateLoop();
164 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
165
166 if (NewLoopParent)
167 NewLoopParent->addChildLoop(NewLoop);
168 else
169 LI->addTopLevelLoop(NewLoop);
170
171 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
172 return OldLoop;
173 } else {
174 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
175 return nullptr;
176 }
177}
178
179/// The function chooses which type of unroll (epilog or prolog) is more
180/// profitabale.
181/// Epilog unroll is more profitable when there is PHI that starts from
182/// constant. In this case epilog will leave PHI start from constant,
183/// but prolog will convert it to non-constant.
184///
185/// loop:
186/// PN = PHI [I, Latch], [CI, PreHeader]
187/// I = foo(PN)
188/// ...
189///
190/// Epilog unroll case.
191/// loop:
192/// PN = PHI [I2, Latch], [CI, PreHeader]
193/// I1 = foo(PN)
194/// I2 = foo(I1)
195/// ...
196/// Prolog unroll case.
197/// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
198/// loop:
199/// PN = PHI [I2, Latch], [NewPN, PreHeader]
200/// I1 = foo(PN)
201/// I2 = foo(I1)
202/// ...
203///
204static bool isEpilogProfitable(Loop *L) {
205 BasicBlock *PreHeader = L->getLoopPreheader();
206 BasicBlock *Header = L->getHeader();
207 assert(PreHeader && Header);
208 for (const PHINode &PN : Header->phis()) {
209 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
210 return true;
211 }
212 return false;
213}
214
215struct LoadValue {
216 Instruction *DefI = nullptr;
217 unsigned Generation = 0;
218 LoadValue() = default;
220 : DefI(Inst), Generation(Generation) {}
221};
222
225 unsigned CurrentGeneration;
226 unsigned ChildGeneration;
227 DomTreeNode *Node;
230 bool Processed = false;
231
232public:
234 unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child,
236 : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg),
237 Node(N), ChildIter(Child), EndIter(End) {}
238 // Accessors.
239 unsigned currentGeneration() const { return CurrentGeneration; }
240 unsigned childGeneration() const { return ChildGeneration; }
241 void childGeneration(unsigned generation) { ChildGeneration = generation; }
242 DomTreeNode *node() { return Node; }
243 DomTreeNode::const_iterator childIter() const { return ChildIter; }
244
246 DomTreeNode *Child = *ChildIter;
247 ++ChildIter;
248 return Child;
249 }
250
251 DomTreeNode::const_iterator end() const { return EndIter; }
252 bool isProcessed() const { return Processed; }
253 void process() { Processed = true; }
254};
255
256Value *getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration,
257 BatchAAResults &BAA,
258 function_ref<MemorySSA *()> GetMSSA) {
259 if (!LV.DefI)
260 return nullptr;
261 if (LV.DefI->getType() != LI->getType())
262 return nullptr;
263 if (LV.Generation != CurrentGeneration) {
264 MemorySSA *MSSA = GetMSSA();
265 if (!MSSA)
266 return nullptr;
267 auto *EarlierMA = MSSA->getMemoryAccess(LV.DefI);
268 MemoryAccess *LaterDef =
269 MSSA->getWalker()->getClobberingMemoryAccess(LI, BAA);
270 if (!MSSA->dominates(LaterDef, EarlierMA))
271 return nullptr;
272 }
273 return LV.DefI;
274}
275
277 BatchAAResults &BAA, function_ref<MemorySSA *()> GetMSSA) {
280 DomTreeNode *HeaderD = DT.getNode(L->getHeader());
281 NodesToProcess.emplace_back(new StackNode(AvailableLoads, 0, HeaderD,
282 HeaderD->begin(), HeaderD->end()));
283
284 unsigned CurrentGeneration = 0;
285 while (!NodesToProcess.empty()) {
286 StackNode *NodeToProcess = &*NodesToProcess.back();
287
288 CurrentGeneration = NodeToProcess->currentGeneration();
289
290 if (!NodeToProcess->isProcessed()) {
291 // Process the node.
292
293 // If this block has a single predecessor, then the predecessor is the
294 // parent
295 // of the domtree node and all of the live out memory values are still
296 // current in this block. If this block has multiple predecessors, then
297 // they could have invalidated the live-out memory values of our parent
298 // value. For now, just be conservative and invalidate memory if this
299 // block has multiple predecessors.
300 if (!NodeToProcess->node()->getBlock()->getSinglePredecessor())
301 ++CurrentGeneration;
302 for (auto &I : make_early_inc_range(*NodeToProcess->node()->getBlock())) {
303
304 auto *Load = dyn_cast<LoadInst>(&I);
305 if (!Load || !Load->isSimple()) {
306 if (I.mayWriteToMemory())
307 CurrentGeneration++;
308 continue;
309 }
310
311 const SCEV *PtrSCEV = SE.getSCEV(Load->getPointerOperand());
312 LoadValue LV = AvailableLoads.lookup(PtrSCEV);
313 if (Value *M =
314 getMatchingValue(LV, Load, CurrentGeneration, BAA, GetMSSA)) {
315 if (LI.replacementPreservesLCSSAForm(Load, M)) {
316 Load->replaceAllUsesWith(M);
317 Load->eraseFromParent();
318 }
319 } else {
320 AvailableLoads.insert(PtrSCEV, LoadValue(Load, CurrentGeneration));
321 }
322 }
323 NodeToProcess->childGeneration(CurrentGeneration);
324 NodeToProcess->process();
325 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
326 // Push the next child onto the stack.
327 DomTreeNode *Child = NodeToProcess->nextChild();
328 if (!L->contains(Child->getBlock()))
329 continue;
330 NodesToProcess.emplace_back(
331 new StackNode(AvailableLoads, NodeToProcess->childGeneration(), Child,
332 Child->begin(), Child->end()));
333 } else {
334 // It has been processed, and there are no more children to process,
335 // so delete it and pop it off the stack.
336 NodesToProcess.pop_back();
337 }
338 }
339}
340
341/// Perform some cleanup and simplifications on loops after unrolling. It is
342/// useful to simplify the IV's in the new loop, as well as do a quick
343/// simplify/dce pass of the instructions.
344void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
346 AssumptionCache *AC,
348 AAResults *AA) {
349 using namespace llvm::PatternMatch;
350
351 // Simplify any new induction variables in the partially unrolled loop.
352 if (SE && SimplifyIVs) {
354 simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
355
356 // Aggressively clean up dead instructions that simplifyLoopIVs already
357 // identified. Any remaining should be cleaned up below.
358 while (!DeadInsts.empty()) {
359 Value *V = DeadInsts.pop_back_val();
360 if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
362 }
363
364 if (AA) {
365 std::unique_ptr<MemorySSA> MSSA = nullptr;
366 BatchAAResults BAA(*AA);
367 loadCSE(L, *DT, *SE, *LI, BAA, [L, AA, DT, &MSSA]() -> MemorySSA * {
368 if (!MSSA)
369 MSSA.reset(new MemorySSA(*L, AA, DT));
370 return &*MSSA;
371 });
372 }
373 }
374
375 // At this point, the code is well formed. Perform constprop, instsimplify,
376 // and dce.
377 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
379 for (BasicBlock *BB : L->getBlocks()) {
380 // Remove repeated debug instructions after loop unrolling.
381 if (BB->getParent()->getSubprogram())
383
384 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
385 if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
386 if (LI->replacementPreservesLCSSAForm(&Inst, V))
387 Inst.replaceAllUsesWith(V);
389 DeadInsts.emplace_back(&Inst);
390
391 // Fold ((add X, C1), C2) to (add X, C1+C2). This is very common in
392 // unrolled loops, and handling this early allows following code to
393 // identify the IV as a "simple recurrence" without first folding away
394 // a long chain of adds.
395 {
396 Value *X;
397 const APInt *C1, *C2;
398 if (match(&Inst, m_Add(m_Add(m_Value(X), m_APInt(C1)), m_APInt(C2)))) {
399 auto *InnerI = dyn_cast<Instruction>(Inst.getOperand(0));
400 auto *InnerOBO = cast<OverflowingBinaryOperator>(Inst.getOperand(0));
401 bool SignedOverflow;
402 APInt NewC = C1->sadd_ov(*C2, SignedOverflow);
403 Inst.setOperand(0, X);
404 Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
405 Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
406 InnerOBO->hasNoUnsignedWrap());
407 Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
408 InnerOBO->hasNoSignedWrap() &&
409 !SignedOverflow);
410 if (InnerI && isInstructionTriviallyDead(InnerI))
411 DeadInsts.emplace_back(InnerI);
412 }
413 }
414 }
415 // We can't do recursive deletion until we're done iterating, as we might
416 // have a phi which (potentially indirectly) uses instructions later in
417 // the block we're iterating through.
419 }
420}
421
422/// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
423/// can only fail when the loop's latch block is not terminated by a conditional
424/// branch instruction. However, if the trip count (and multiple) are not known,
425/// loop unrolling will mostly produce more code that is no faster.
426///
427/// If Runtime is true then UnrollLoop will try to insert a prologue or
428/// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
429/// will not runtime-unroll the loop if computing the run-time trip count will
430/// be expensive and AllowExpensiveTripCount is false.
431///
432/// The LoopInfo Analysis that is passed will be kept consistent.
433///
434/// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
435/// DominatorTree if they are non-null.
436///
437/// If RemainderLoop is non-null, it will receive the remainder loop (if
438/// required and not fully unrolled).
443 bool PreserveLCSSA, Loop **RemainderLoop, AAResults *AA) {
444 assert(DT && "DomTree is required");
445
446 if (!L->getLoopPreheader()) {
447 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
448 return LoopUnrollResult::Unmodified;
449 }
450
451 if (!L->getLoopLatch()) {
452 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
453 return LoopUnrollResult::Unmodified;
454 }
455
456 // Loops with indirectbr cannot be cloned.
457 if (!L->isSafeToClone()) {
458 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
459 return LoopUnrollResult::Unmodified;
460 }
461
462 if (L->getHeader()->hasAddressTaken()) {
463 // The loop-rotate pass can be helpful to avoid this in many cases.
465 dbgs() << " Won't unroll loop: address of header block is taken.\n");
466 return LoopUnrollResult::Unmodified;
467 }
468
469 assert(ULO.Count > 0);
470
471 // All these values should be taken only after peeling because they might have
472 // changed.
473 BasicBlock *Preheader = L->getLoopPreheader();
474 BasicBlock *Header = L->getHeader();
475 BasicBlock *LatchBlock = L->getLoopLatch();
477 L->getExitBlocks(ExitBlocks);
478 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
479
480 const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
481 const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
482 unsigned EstimatedLoopInvocationWeight = 0;
483 std::optional<unsigned> OriginalTripCount =
484 llvm::getLoopEstimatedTripCount(L, &EstimatedLoopInvocationWeight);
485
486 // Effectively "DCE" unrolled iterations that are beyond the max tripcount
487 // and will never be executed.
488 if (MaxTripCount && ULO.Count > MaxTripCount)
489 ULO.Count = MaxTripCount;
490
491 struct ExitInfo {
492 unsigned TripCount;
493 unsigned TripMultiple;
494 unsigned BreakoutTrip;
495 bool ExitOnTrue;
496 BasicBlock *FirstExitingBlock = nullptr;
497 SmallVector<BasicBlock *> ExitingBlocks;
498 };
500 SmallVector<BasicBlock *, 4> ExitingBlocks;
501 L->getExitingBlocks(ExitingBlocks);
502 for (auto *ExitingBlock : ExitingBlocks) {
503 // The folding code is not prepared to deal with non-branch instructions
504 // right now.
505 auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
506 if (!BI)
507 continue;
508
509 ExitInfo &Info = ExitInfos.try_emplace(ExitingBlock).first->second;
510 Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
511 Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
512 if (Info.TripCount != 0) {
513 Info.BreakoutTrip = Info.TripCount % ULO.Count;
514 Info.TripMultiple = 0;
515 } else {
516 Info.BreakoutTrip = Info.TripMultiple =
517 (unsigned)std::gcd(ULO.Count, Info.TripMultiple);
518 }
519 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
520 Info.ExitingBlocks.push_back(ExitingBlock);
521 LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
522 << ": TripCount=" << Info.TripCount
523 << ", TripMultiple=" << Info.TripMultiple
524 << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
525 }
526
527 // Are we eliminating the loop control altogether? Note that we can know
528 // we're eliminating the backedge without knowing exactly which iteration
529 // of the unrolled body exits.
530 const bool CompletelyUnroll = ULO.Count == MaxTripCount;
531
532 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
533
534 // There's no point in performing runtime unrolling if this unroll count
535 // results in a full unroll.
536 if (CompletelyUnroll)
537 ULO.Runtime = false;
538
539 // Go through all exits of L and see if there are any phi-nodes there. We just
540 // conservatively assume that they're inserted to preserve LCSSA form, which
541 // means that complete unrolling might break this form. We need to either fix
542 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
543 // now we just recompute LCSSA for the outer loop, but it should be possible
544 // to fix it in-place.
545 bool NeedToFixLCSSA =
546 PreserveLCSSA && CompletelyUnroll &&
547 any_of(ExitBlocks,
548 [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
549
550 // The current loop unroll pass can unroll loops that have
551 // (1) single latch; and
552 // (2a) latch is unconditional; or
553 // (2b) latch is conditional and is an exiting block
554 // FIXME: The implementation can be extended to work with more complicated
555 // cases, e.g. loops with multiple latches.
556 BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
557
558 // A conditional branch which exits the loop, which can be optimized to an
559 // unconditional branch in the unrolled loop in some cases.
560 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
561 if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
563 dbgs() << "Can't unroll; a conditional latch must exit the loop");
564 return LoopUnrollResult::Unmodified;
565 }
566
567 // Loops containing convergent instructions cannot use runtime unrolling,
568 // as the prologue/epilogue may add additional control-dependencies to
569 // convergent operations.
571 {
572 bool HasConvergent = false;
573 for (auto &BB : L->blocks())
574 for (auto &I : *BB)
575 if (auto *CB = dyn_cast<CallBase>(&I))
576 HasConvergent |= CB->isConvergent();
577 assert((!HasConvergent || !ULO.Runtime) &&
578 "Can't runtime unroll if loop contains a convergent operation.");
579 });
580
581 bool EpilogProfitability =
582 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
584
585 if (ULO.Runtime &&
587 EpilogProfitability, ULO.UnrollRemainder,
588 ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
589 PreserveLCSSA, RemainderLoop)) {
590 if (ULO.Force)
591 ULO.Runtime = false;
592 else {
593 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
594 "generated when assuming runtime trip count\n");
595 return LoopUnrollResult::Unmodified;
596 }
597 }
598
599 using namespace ore;
600 // Report the unrolling decision.
601 if (CompletelyUnroll) {
602 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
603 << " with trip count " << ULO.Count << "!\n");
604 if (ORE)
605 ORE->emit([&]() {
606 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
607 L->getHeader())
608 << "completely unrolled loop with "
609 << NV("UnrollCount", ULO.Count) << " iterations";
610 });
611 } else {
612 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
613 << ULO.Count);
614 if (ULO.Runtime)
615 LLVM_DEBUG(dbgs() << " with run-time trip count");
616 LLVM_DEBUG(dbgs() << "!\n");
617
618 if (ORE)
619 ORE->emit([&]() {
620 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
621 L->getHeader());
622 Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
623 if (ULO.Runtime)
624 Diag << " with run-time trip count";
625 return Diag;
626 });
627 }
628
629 // We are going to make changes to this loop. SCEV may be keeping cached info
630 // about it, in particular about backedge taken count. The changes we make
631 // are guaranteed to invalidate this information for our loop. It is tempting
632 // to only invalidate the loop being unrolled, but it is incorrect as long as
633 // all exiting branches from all inner loops have impact on the outer loops,
634 // and if something changes inside them then any of outer loops may also
635 // change. When we forget outermost loop, we also forget all contained loops
636 // and this is what we need here.
637 if (SE) {
638 if (ULO.ForgetAllSCEV)
639 SE->forgetAllLoops();
640 else {
641 SE->forgetTopmostLoop(L);
643 }
644 }
645
646 if (!LatchIsExiting)
647 ++NumUnrolledNotLatch;
648
649 // For the first iteration of the loop, we should use the precloned values for
650 // PHI nodes. Insert associations now.
651 ValueToValueMapTy LastValueMap;
652 std::vector<PHINode*> OrigPHINode;
653 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
654 OrigPHINode.push_back(cast<PHINode>(I));
655 }
656
657 std::vector<BasicBlock *> Headers;
658 std::vector<BasicBlock *> Latches;
659 Headers.push_back(Header);
660 Latches.push_back(LatchBlock);
661
662 // The current on-the-fly SSA update requires blocks to be processed in
663 // reverse postorder so that LastValueMap contains the correct value at each
664 // exit.
665 LoopBlocksDFS DFS(L);
666 DFS.perform(LI);
667
668 // Stash the DFS iterators before adding blocks to the loop.
669 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
670 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
671
672 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
673
674 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
675 // might break loop-simplified form for these loops (as they, e.g., would
676 // share the same exit blocks). We'll keep track of loops for which we can
677 // break this so that later we can re-simplify them.
678 SmallSetVector<Loop *, 4> LoopsToSimplify;
679 for (Loop *SubLoop : *L)
680 LoopsToSimplify.insert(SubLoop);
681
682 // When a FSDiscriminator is enabled, we don't need to add the multiply
683 // factors to the discriminators.
684 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
686 for (BasicBlock *BB : L->getBlocks())
687 for (Instruction &I : *BB)
688 if (!I.isDebugOrPseudoInst())
689 if (const DILocation *DIL = I.getDebugLoc()) {
690 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
691 if (NewDIL)
692 I.setDebugLoc(*NewDIL);
693 else
695 << "Failed to create new discriminator: "
696 << DIL->getFilename() << " Line: " << DIL->getLine());
697 }
698
699 // Identify what noalias metadata is inside the loop: if it is inside the
700 // loop, the associated metadata must be cloned for each iteration.
701 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
702 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
703
704 // We place the unrolled iterations immediately after the original loop
705 // latch. This is a reasonable default placement if we don't have block
706 // frequencies, and if we do, well the layout will be adjusted later.
707 auto BlockInsertPt = std::next(LatchBlock->getIterator());
708 for (unsigned It = 1; It != ULO.Count; ++It) {
711 NewLoops[L] = L;
712
713 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
715 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
716 Header->getParent()->insert(BlockInsertPt, New);
717
718 assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
719 "Header should not be in a sub-loop");
720 // Tell LI about New.
721 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
722 if (OldLoop)
723 LoopsToSimplify.insert(NewLoops[OldLoop]);
724
725 if (*BB == Header)
726 // Loop over all of the PHI nodes in the block, changing them to use
727 // the incoming values from the previous block.
728 for (PHINode *OrigPHI : OrigPHINode) {
729 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
730 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
731 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
732 if (It > 1 && L->contains(InValI))
733 InVal = LastValueMap[InValI];
734 VMap[OrigPHI] = InVal;
735 NewPHI->eraseFromParent();
736 }
737
738 // Update our running map of newest clones
739 LastValueMap[*BB] = New;
740 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
741 VI != VE; ++VI)
742 LastValueMap[VI->first] = VI->second;
743
744 // Add phi entries for newly created values to all exit blocks.
745 for (BasicBlock *Succ : successors(*BB)) {
746 if (L->contains(Succ))
747 continue;
748 for (PHINode &PHI : Succ->phis()) {
749 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
750 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
751 if (It != LastValueMap.end())
752 Incoming = It->second;
753 PHI.addIncoming(Incoming, New);
754 SE->forgetValue(&PHI);
755 }
756 }
757 // Keep track of new headers and latches as we create them, so that
758 // we can insert the proper branches later.
759 if (*BB == Header)
760 Headers.push_back(New);
761 if (*BB == LatchBlock)
762 Latches.push_back(New);
763
764 // Keep track of the exiting block and its successor block contained in
765 // the loop for the current iteration.
766 auto ExitInfoIt = ExitInfos.find(*BB);
767 if (ExitInfoIt != ExitInfos.end())
768 ExitInfoIt->second.ExitingBlocks.push_back(New);
769
770 NewBlocks.push_back(New);
771 UnrolledLoopBlocks.push_back(New);
772
773 // Update DomTree: since we just copy the loop body, and each copy has a
774 // dedicated entry block (copy of the header block), this header's copy
775 // dominates all copied blocks. That means, dominance relations in the
776 // copied body are the same as in the original body.
777 if (*BB == Header)
778 DT->addNewBlock(New, Latches[It - 1]);
779 else {
780 auto BBDomNode = DT->getNode(*BB);
781 auto BBIDom = BBDomNode->getIDom();
782 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
783 DT->addNewBlock(
784 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
785 }
786 }
787
788 // Remap all instructions in the most recent iteration
789 remapInstructionsInBlocks(NewBlocks, LastValueMap);
790 for (BasicBlock *NewBlock : NewBlocks)
791 for (Instruction &I : *NewBlock)
792 if (auto *II = dyn_cast<AssumeInst>(&I))
793 AC->registerAssumption(II);
794
795 {
796 // Identify what other metadata depends on the cloned version. After
797 // cloning, replace the metadata with the corrected version for both
798 // memory instructions and noalias intrinsics.
799 std::string ext = (Twine("It") + Twine(It)).str();
800 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
801 Header->getContext(), ext);
802 }
803 }
804
805 // Loop over the PHI nodes in the original block, setting incoming values.
806 for (PHINode *PN : OrigPHINode) {
807 if (CompletelyUnroll) {
808 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
809 PN->eraseFromParent();
810 } else if (ULO.Count > 1) {
811 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
812 // If this value was defined in the loop, take the value defined by the
813 // last iteration of the loop.
814 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
815 if (L->contains(InValI))
816 InVal = LastValueMap[InVal];
817 }
818 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
819 PN->addIncoming(InVal, Latches.back());
820 }
821 }
822
823 // Connect latches of the unrolled iterations to the headers of the next
824 // iteration. Currently they point to the header of the same iteration.
825 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
826 unsigned j = (i + 1) % e;
827 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
828 }
829
830 // Update dominators of blocks we might reach through exits.
831 // Immediate dominator of such block might change, because we add more
832 // routes which can lead to the exit: we can now reach it from the copied
833 // iterations too.
834 if (ULO.Count > 1) {
835 for (auto *BB : OriginalLoopBlocks) {
836 auto *BBDomNode = DT->getNode(BB);
837 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
838 for (auto *ChildDomNode : BBDomNode->children()) {
839 auto *ChildBB = ChildDomNode->getBlock();
840 if (!L->contains(ChildBB))
841 ChildrenToUpdate.push_back(ChildBB);
842 }
843 // The new idom of the block will be the nearest common dominator
844 // of all copies of the previous idom. This is equivalent to the
845 // nearest common dominator of the previous idom and the first latch,
846 // which dominates all copies of the previous idom.
847 BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
848 for (auto *ChildBB : ChildrenToUpdate)
849 DT->changeImmediateDominator(ChildBB, NewIDom);
850 }
851 }
852
854 DT->verify(DominatorTree::VerificationLevel::Fast));
855
857 auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
858 auto *Term = cast<BranchInst>(Src->getTerminator());
859 const unsigned Idx = ExitOnTrue ^ WillExit;
860 BasicBlock *Dest = Term->getSuccessor(Idx);
861 BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
862
863 // Remove predecessors from all non-Dest successors.
864 DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
865
866 // Replace the conditional branch with an unconditional one.
867 BranchInst::Create(Dest, Term->getIterator());
868 Term->eraseFromParent();
869
870 DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
871 };
872
873 auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
874 bool IsLatch) -> std::optional<bool> {
875 if (CompletelyUnroll) {
876 if (PreserveOnlyFirst) {
877 if (i == 0)
878 return std::nullopt;
879 return j == 0;
880 }
881 // Complete (but possibly inexact) unrolling
882 if (j == 0)
883 return true;
884 if (Info.TripCount && j != Info.TripCount)
885 return false;
886 return std::nullopt;
887 }
888
889 if (ULO.Runtime) {
890 // If runtime unrolling inserts a prologue, information about non-latch
891 // exits may be stale.
892 if (IsLatch && j != 0)
893 return false;
894 return std::nullopt;
895 }
896
897 if (j != Info.BreakoutTrip &&
898 (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
899 // If we know the trip count or a multiple of it, we can safely use an
900 // unconditional branch for some iterations.
901 return false;
902 }
903 return std::nullopt;
904 };
905
906 // Fold branches for iterations where we know that they will exit or not
907 // exit.
908 for (auto &Pair : ExitInfos) {
909 ExitInfo &Info = Pair.second;
910 for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
911 // The branch destination.
912 unsigned j = (i + 1) % e;
913 bool IsLatch = Pair.first == LatchBlock;
914 std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
915 if (!KnownWillExit) {
916 if (!Info.FirstExitingBlock)
917 Info.FirstExitingBlock = Info.ExitingBlocks[i];
918 continue;
919 }
920
921 // We don't fold known-exiting branches for non-latch exits here,
922 // because this ensures that both all loop blocks and all exit blocks
923 // remain reachable in the CFG.
924 // TODO: We could fold these branches, but it would require much more
925 // sophisticated updates to LoopInfo.
926 if (*KnownWillExit && !IsLatch) {
927 if (!Info.FirstExitingBlock)
928 Info.FirstExitingBlock = Info.ExitingBlocks[i];
929 continue;
930 }
931
932 SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
933 }
934 }
935
936 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
937 DomTreeUpdater *DTUToUse = &DTU;
938 if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
939 // Manually update the DT if there's a single exiting node. In that case
940 // there's a single exit node and it is sufficient to update the nodes
941 // immediately dominated by the original exiting block. They will become
942 // dominated by the first exiting block that leaves the loop after
943 // unrolling. Note that the CFG inside the loop does not change, so there's
944 // no need to update the DT inside the unrolled loop.
945 DTUToUse = nullptr;
946 auto &[OriginalExit, Info] = *ExitInfos.begin();
947 if (!Info.FirstExitingBlock)
948 Info.FirstExitingBlock = Info.ExitingBlocks.back();
949 for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
950 if (L->contains(C->getBlock()))
951 continue;
952 C->setIDom(DT->getNode(Info.FirstExitingBlock));
953 }
954 } else {
955 DTU.applyUpdates(DTUpdates);
956 }
957
958 // When completely unrolling, the last latch becomes unreachable.
959 if (!LatchIsExiting && CompletelyUnroll) {
960 // There is no need to update the DT here, because there must be a unique
961 // latch. Hence if the latch is not exiting it must directly branch back to
962 // the original loop header and does not dominate any nodes.
963 assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
964 changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
965 }
966
967 // Merge adjacent basic blocks, if possible.
968 for (BasicBlock *Latch : Latches) {
969 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
970 assert((Term ||
971 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
972 "Need a branch as terminator, except when fully unrolling with "
973 "unconditional latch");
974 if (Term && Term->isUnconditional()) {
975 BasicBlock *Dest = Term->getSuccessor(0);
976 BasicBlock *Fold = Dest->getUniquePredecessor();
977 if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
978 /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
979 /*PredecessorWithTwoSuccessors=*/false,
980 DTUToUse ? nullptr : DT)) {
981 // Dest has been folded into Fold. Update our worklists accordingly.
982 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
983 llvm::erase(UnrolledLoopBlocks, Dest);
984 }
985 }
986 }
987
988 if (DTUToUse) {
989 // Apply updates to the DomTree.
990 DT = &DTU.getDomTree();
991 }
993 DT->verify(DominatorTree::VerificationLevel::Fast));
994
995 // At this point, the code is well formed. We now simplify the unrolled loop,
996 // doing constant propagation and dead code elimination as we go.
997 simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
998 TTI, AA);
999
1000 NumCompletelyUnrolled += CompletelyUnroll;
1001 ++NumUnrolled;
1002
1003 Loop *OuterL = L->getParentLoop();
1004 // Update LoopInfo if the loop is completely removed.
1005 if (CompletelyUnroll) {
1006 LI->erase(L);
1007 // We shouldn't try to use `L` anymore.
1008 L = nullptr;
1009 } else if (OriginalTripCount) {
1010 // Update the trip count. Note that the remainder has already logic
1011 // computing it in `UnrollRuntimeLoopRemainder`.
1012 setLoopEstimatedTripCount(L, *OriginalTripCount / ULO.Count,
1013 EstimatedLoopInvocationWeight);
1014 }
1015
1016 // LoopInfo should not be valid, confirm that.
1018 LI->verify(*DT);
1019
1020 // After complete unrolling most of the blocks should be contained in OuterL.
1021 // However, some of them might happen to be out of OuterL (e.g. if they
1022 // precede a loop exit). In this case we might need to insert PHI nodes in
1023 // order to preserve LCSSA form.
1024 // We don't need to check this if we already know that we need to fix LCSSA
1025 // form.
1026 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
1027 // it should be possible to fix it in-place.
1028 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1029 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
1030
1031 // Make sure that loop-simplify form is preserved. We want to simplify
1032 // at least one layer outside of the loop that was unrolled so that any
1033 // changes to the parent loop exposed by the unrolling are considered.
1034 if (OuterL) {
1035 // OuterL includes all loops for which we can break loop-simplify, so
1036 // it's sufficient to simplify only it (it'll recursively simplify inner
1037 // loops too).
1038 if (NeedToFixLCSSA) {
1039 // LCSSA must be performed on the outermost affected loop. The unrolled
1040 // loop's last loop latch is guaranteed to be in the outermost loop
1041 // after LoopInfo's been updated by LoopInfo::erase.
1042 Loop *LatchLoop = LI->getLoopFor(Latches.back());
1043 Loop *FixLCSSALoop = OuterL;
1044 if (!FixLCSSALoop->contains(LatchLoop))
1045 while (FixLCSSALoop->getParentLoop() != LatchLoop)
1046 FixLCSSALoop = FixLCSSALoop->getParentLoop();
1047
1048 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
1049 } else if (PreserveLCSSA) {
1050 assert(OuterL->isLCSSAForm(*DT) &&
1051 "Loops should be in LCSSA form after loop-unroll.");
1052 }
1053
1054 // TODO: That potentially might be compile-time expensive. We should try
1055 // to fix the loop-simplified form incrementally.
1056 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1057 } else {
1058 // Simplify loops for which we might've broken loop-simplify form.
1059 for (Loop *SubLoop : LoopsToSimplify)
1060 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1061 }
1062
1063 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
1064 : LoopUnrollResult::PartiallyUnrolled;
1065}
1066
1067/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
1068/// node with the given name (for example, "llvm.loop.unroll.count"). If no
1069/// such metadata node exists, then nullptr is returned.
1071 // First operand should refer to the loop id itself.
1072 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1073 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1074
1075 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1076 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1077 if (!MD)
1078 continue;
1079
1080 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1081 if (!S)
1082 continue;
1083
1084 if (Name == S->getString())
1085 return MD;
1086 }
1087 return nullptr;
1088}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
Optimize for code generation
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
std::string Name
bool End
Definition: ELF_riscv.cpp:480
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:507
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool needToInsertPhisForLCSSA(Loop *L, const std::vector< BasicBlock * > &Blocks, LoopInfo *LI)
Check if unrolling created a situation where we need to insert phi nodes to preserve LCSSA form.
Definition: LoopUnroll.cpp:125
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale.
Definition: LoopUnroll.cpp:204
void loadCSE(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
Definition: LoopUnroll.cpp:276
Value * getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
Definition: LoopUnroll.cpp:256
static cl::opt< bool > UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolled loops to be unrolled " "with epilog instead of prolog."))
#define DEBUG_TYPE
Definition: LoopUnroll.cpp:82
static cl::opt< bool > UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden, cl::desc("Verify loopinfo after unrolling"), cl::init(false))
static cl::opt< bool > UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, cl::desc("Verify domtree after unrolling"), cl::init(false))
#define I(x, y, z)
Definition: MD5.cpp:58
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
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:167
This defines the Use class.
void childGeneration(unsigned generation)
Definition: LoopUnroll.cpp:241
bool isProcessed() const
Definition: LoopUnroll.cpp:252
unsigned currentGeneration() const
Definition: LoopUnroll.cpp:239
unsigned childGeneration() const
Definition: LoopUnroll.cpp:240
StackNode(ScopedHashTable< const SCEV *, LoadValue > &AvailableLoads, unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child, DomTreeNode::const_iterator End)
Definition: LoopUnroll.cpp:233
DomTreeNode::const_iterator end() const
Definition: LoopUnroll.cpp:251
void process()
Definition: LoopUnroll.cpp:253
DomTreeNode * nextChild()
Definition: LoopUnroll.cpp:245
DomTreeNode::const_iterator childIter() const
Definition: LoopUnroll.cpp:243
DomTreeNode * node()
Definition: LoopUnroll.cpp:242
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1898
A cache of @llvm.assume calls within a function.
void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:430
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:452
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:460
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:482
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
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:221
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:509
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
Debug location.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:235
unsigned size() const
Definition: DenseMap.h:99
iterator begin()
Definition: DenseMap.h:75
iterator end()
Definition: DenseMap.h:84
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
typename SmallVector< DomTreeNodeBase *, 4 >::const_iterator const_iterator
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
DominatorTree & getDomTree()
Flush DomTree updates and return DomTree.
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:162
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...
Definition: Dominators.cpp:344
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
An instruction for reading from memory.
Definition: Instructions.h:184
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Store the result of a depth first search within basic blocks contained by a single loop.
Definition: LoopIterator.h:97
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
Definition: LoopIterator.h:136
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
Definition: LoopIterator.h:101
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopInfo.cpp:1222
RPOIterator endRPO() const
Definition: LoopIterator.h:140
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
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:439
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition: LoopInfo.cpp:875
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition: LoopInfo.cpp:462
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1434
A single uniqued string.
Definition: Metadata.h:720
StringRef getString() const
Definition: Metadata.cpp:610
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition: MemorySSA.h:1045
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:701
bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
Definition: MemorySSA.cpp:2173
MemorySSAWalker * getWalker()
Definition: MemorySSA.cpp:1590
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition: MemorySSA.h:719
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This class represents an analyzed expression in the program.
The main scalar evolution driver.
unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getSmallConstantMaxTripCount(const Loop *L)
Returns the upper bound of the loop trip count as a normal unsigned value.
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
void forgetTopmostLoop(const Loop *L)
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
iterator find(const KeyT &Val)
Definition: ValueMap.h:155
iterator begin()
Definition: ValueMap.h:134
iterator end()
Definition: ValueMap.h:135
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition: ilist_node.h:109
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
Definition: LoopUtils.cpp:849
void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, AAResults *AA=nullptr)
Perform some cleanup and simplifications on loops after unrolling.
Definition: LoopUnroll.cpp:344
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:540
auto successors(const MachineBasicBlock *BB)
bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:425
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:656
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition: STLExtras.h:2059
cl::opt< bool > EnableFSDiscriminator
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
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:400
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Definition: SmallVector.h:1312
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
Definition: UnrollLoop.h:55
unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition: Local.cpp:2833
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.
bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, unsigned EstimatedLoopInvocationWeight)
Set a loop's branch weight metadata to reflect that loop has EstimatedTripCount iterations and Estima...
Definition: LoopUtils.cpp:867
void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
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...
Definition: LoopUnroll.cpp:150
void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
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, Loop **ResultLoop=nullptr)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
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.
Definition: LoopUnroll.cpp:440
#define N
Instruction * DefI
Definition: LoopUnroll.cpp:216
LoadValue()=default
unsigned Generation
Definition: LoopUnroll.cpp:217
LoadValue(Instruction *Inst, unsigned Generation)
Definition: LoopUnroll.cpp:219
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...