LLVM 22.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"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/CFG.h"
38#include "llvm/IR/Constants.h"
40#include "llvm/IR/DebugLoc.h"
42#include "llvm/IR/Dominators.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/IRBuilder.h"
45#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Metadata.h"
50#include "llvm/IR/Use.h"
51#include "llvm/IR/User.h"
52#include "llvm/IR/ValueHandle.h"
53#include "llvm/IR/ValueMap.h"
56#include "llvm/Support/Debug.h"
67#include <assert.h>
68#include <numeric>
69#include <type_traits>
70#include <vector>
71
72namespace llvm {
73class DataLayout;
74class Value;
75} // namespace llvm
76
77using namespace llvm;
78
79#define DEBUG_TYPE "loop-unroll"
80
81// TODO: Should these be here or in LoopUnroll?
82STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
83STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
84STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
85 "latch (completely or otherwise)");
86
87static cl::opt<bool>
88UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
89 cl::desc("Allow runtime unrolled loops to be unrolled "
90 "with epilog instead of prolog."));
91
92static cl::opt<bool>
93UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
94 cl::desc("Verify domtree after unrolling"),
95#ifdef EXPENSIVE_CHECKS
96 cl::init(true)
97#else
98 cl::init(false)
99#endif
100 );
101
102static cl::opt<bool>
103UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
104 cl::desc("Verify loopinfo after unrolling"),
105#ifdef EXPENSIVE_CHECKS
106 cl::init(true)
107#else
108 cl::init(false)
109#endif
110 );
111
113 "unroll-add-parallel-reductions", cl::init(false), cl::Hidden,
114 cl::desc("Allow unrolling to add parallel reduction phis."));
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();
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()->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// Loops containing convergent instructions that are uncontrolled or controlled
423// from outside the loop must have a count that divides their TripMultiple.
425static bool canHaveUnrollRemainder(const Loop *L) {
427 return false;
428
429 // Check for uncontrolled convergent operations.
430 for (auto &BB : L->blocks()) {
431 for (auto &I : *BB) {
433 return true;
434 if (auto *CB = dyn_cast<CallBase>(&I))
435 if (CB->isConvergent())
436 return CB->getConvergenceControlToken();
437 }
438 }
439 return true;
440}
441
442/// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
443/// can only fail when the loop's latch block is not terminated by a conditional
444/// branch instruction. However, if the trip count (and multiple) are not known,
445/// loop unrolling will mostly produce more code that is no faster.
446///
447/// If Runtime is true then UnrollLoop will try to insert a prologue or
448/// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
449/// will not runtime-unroll the loop if computing the run-time trip count will
450/// be expensive and AllowExpensiveTripCount is false.
451///
452/// The LoopInfo Analysis that is passed will be kept consistent.
453///
454/// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
455/// DominatorTree if they are non-null.
456///
457/// If RemainderLoop is non-null, it will receive the remainder loop (if
458/// required and not fully unrolled).
463 bool PreserveLCSSA, Loop **RemainderLoop, AAResults *AA) {
464 assert(DT && "DomTree is required");
465
466 if (!L->getLoopPreheader()) {
467 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
469 }
470
471 if (!L->getLoopLatch()) {
472 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
474 }
475
476 // Loops with indirectbr cannot be cloned.
477 if (!L->isSafeToClone()) {
478 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
480 }
481
482 if (L->getHeader()->hasAddressTaken()) {
483 // The loop-rotate pass can be helpful to avoid this in many cases.
485 dbgs() << " Won't unroll loop: address of header block is taken.\n");
487 }
488
489 assert(ULO.Count > 0);
490
491 // All these values should be taken only after peeling because they might have
492 // changed.
493 BasicBlock *Preheader = L->getLoopPreheader();
494 BasicBlock *Header = L->getHeader();
495 BasicBlock *LatchBlock = L->getLoopLatch();
497 L->getExitBlocks(ExitBlocks);
498 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
499
500 const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
501 const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
502 unsigned EstimatedLoopInvocationWeight = 0;
503 std::optional<unsigned> OriginalTripCount =
504 llvm::getLoopEstimatedTripCount(L, &EstimatedLoopInvocationWeight);
505
506 // Effectively "DCE" unrolled iterations that are beyond the max tripcount
507 // and will never be executed.
508 if (MaxTripCount && ULO.Count > MaxTripCount)
509 ULO.Count = MaxTripCount;
510
511 struct ExitInfo {
512 unsigned TripCount;
513 unsigned TripMultiple;
514 unsigned BreakoutTrip;
515 bool ExitOnTrue;
516 BasicBlock *FirstExitingBlock = nullptr;
517 SmallVector<BasicBlock *> ExitingBlocks;
518 };
520 SmallVector<BasicBlock *, 4> ExitingBlocks;
521 L->getExitingBlocks(ExitingBlocks);
522 for (auto *ExitingBlock : ExitingBlocks) {
523 // The folding code is not prepared to deal with non-branch instructions
524 // right now.
525 auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
526 if (!BI)
527 continue;
528
529 ExitInfo &Info = ExitInfos[ExitingBlock];
530 Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
531 Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
532 if (Info.TripCount != 0) {
533 Info.BreakoutTrip = Info.TripCount % ULO.Count;
534 Info.TripMultiple = 0;
535 } else {
536 Info.BreakoutTrip = Info.TripMultiple =
537 (unsigned)std::gcd(ULO.Count, Info.TripMultiple);
538 }
539 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
540 Info.ExitingBlocks.push_back(ExitingBlock);
541 LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
542 << ": TripCount=" << Info.TripCount
543 << ", TripMultiple=" << Info.TripMultiple
544 << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
545 }
546
547 // Are we eliminating the loop control altogether? Note that we can know
548 // we're eliminating the backedge without knowing exactly which iteration
549 // of the unrolled body exits.
550 const bool CompletelyUnroll = ULO.Count == MaxTripCount;
551
552 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
553
554 // There's no point in performing runtime unrolling if this unroll count
555 // results in a full unroll.
556 if (CompletelyUnroll)
557 ULO.Runtime = false;
558
559 // Go through all exits of L and see if there are any phi-nodes there. We just
560 // conservatively assume that they're inserted to preserve LCSSA form, which
561 // means that complete unrolling might break this form. We need to either fix
562 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
563 // now we just recompute LCSSA for the outer loop, but it should be possible
564 // to fix it in-place.
565 bool NeedToFixLCSSA =
566 PreserveLCSSA && CompletelyUnroll &&
567 any_of(ExitBlocks,
568 [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
569
570 // The current loop unroll pass can unroll loops that have
571 // (1) single latch; and
572 // (2a) latch is unconditional; or
573 // (2b) latch is conditional and is an exiting block
574 // FIXME: The implementation can be extended to work with more complicated
575 // cases, e.g. loops with multiple latches.
576 BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
577
578 // A conditional branch which exits the loop, which can be optimized to an
579 // unconditional branch in the unrolled loop in some cases.
580 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
581 if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
583 dbgs() << "Can't unroll; a conditional latch must exit the loop");
585 }
586
588 "Can't runtime unroll if loop contains a convergent operation.");
589
590 bool EpilogProfitability =
591 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
593
594 if (ULO.Runtime &&
596 EpilogProfitability, ULO.UnrollRemainder,
597 ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
598 PreserveLCSSA, ULO.SCEVExpansionBudget,
599 ULO.RuntimeUnrollMultiExit, RemainderLoop)) {
600 if (ULO.Force)
601 ULO.Runtime = false;
602 else {
603 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
604 "generated when assuming runtime trip count\n");
606 }
607 }
608
609 using namespace ore;
610 // Report the unrolling decision.
611 if (CompletelyUnroll) {
612 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
613 << " with trip count " << ULO.Count << "!\n");
614 if (ORE)
615 ORE->emit([&]() {
616 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
617 L->getHeader())
618 << "completely unrolled loop with "
619 << NV("UnrollCount", ULO.Count) << " iterations";
620 });
621 } else {
622 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
623 << ULO.Count);
624 if (ULO.Runtime)
625 LLVM_DEBUG(dbgs() << " with run-time trip count");
626 LLVM_DEBUG(dbgs() << "!\n");
627
628 if (ORE)
629 ORE->emit([&]() {
630 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
631 L->getHeader());
632 Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
633 if (ULO.Runtime)
634 Diag << " with run-time trip count";
635 return Diag;
636 });
637 }
638
639 // We are going to make changes to this loop. SCEV may be keeping cached info
640 // about it, in particular about backedge taken count. The changes we make
641 // are guaranteed to invalidate this information for our loop. It is tempting
642 // to only invalidate the loop being unrolled, but it is incorrect as long as
643 // all exiting branches from all inner loops have impact on the outer loops,
644 // and if something changes inside them then any of outer loops may also
645 // change. When we forget outermost loop, we also forget all contained loops
646 // and this is what we need here.
647 if (SE) {
648 if (ULO.ForgetAllSCEV)
649 SE->forgetAllLoops();
650 else {
651 SE->forgetTopmostLoop(L);
653 }
654 }
655
656 if (!LatchIsExiting)
657 ++NumUnrolledNotLatch;
658
659 // For the first iteration of the loop, we should use the precloned values for
660 // PHI nodes. Insert associations now.
661 ValueToValueMapTy LastValueMap;
662 std::vector<PHINode*> OrigPHINode;
663 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
664 OrigPHINode.push_back(cast<PHINode>(I));
665 }
666
667 // Collect phi nodes for reductions for which we can introduce multiple
668 // parallel reduction phis and compute the final reduction result after the
669 // loop. This requires a single exit block after unrolling. This is ensured by
670 // restricting to single-block loops where the unrolled iterations are known
671 // to not exit.
673 bool CanAddAdditionalAccumulators =
674 (UnrollAddParallelReductions.getNumOccurrences() > 0
677 !CompletelyUnroll && L->getNumBlocks() == 1 &&
678 (ULO.Runtime ||
679 (ExitInfos.contains(Header) && ((ExitInfos[Header].TripCount != 0 &&
680 ExitInfos[Header].BreakoutTrip == 0))));
681
682 // Limit parallelizing reductions to unroll counts of 4 or less for now.
683 // TODO: The number of parallel reductions should depend on the number of
684 // execution units. We also don't have to add a parallel reduction phi per
685 // unrolled iteration, but could for example add a parallel phi for every 2
686 // unrolled iterations.
687 if (CanAddAdditionalAccumulators && ULO.Count <= 4) {
688 for (PHINode &Phi : Header->phis()) {
689 auto RdxDesc = canParallelizeReductionWhenUnrolling(Phi, L, SE);
690 if (!RdxDesc)
691 continue;
692
693 // Only handle duplicate phis for a single reduction for now.
694 // TODO: Handle any number of reductions
695 if (!Reductions.empty())
696 continue;
697
698 Reductions[&Phi] = *RdxDesc;
699 }
700 }
701
702 std::vector<BasicBlock *> Headers;
703 std::vector<BasicBlock *> Latches;
704 Headers.push_back(Header);
705 Latches.push_back(LatchBlock);
706
707 // The current on-the-fly SSA update requires blocks to be processed in
708 // reverse postorder so that LastValueMap contains the correct value at each
709 // exit.
710 LoopBlocksDFS DFS(L);
711 DFS.perform(LI);
712
713 // Stash the DFS iterators before adding blocks to the loop.
714 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
715 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
716
717 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
718
719 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
720 // might break loop-simplified form for these loops (as they, e.g., would
721 // share the same exit blocks). We'll keep track of loops for which we can
722 // break this so that later we can re-simplify them.
723 SmallSetVector<Loop *, 4> LoopsToSimplify;
724 LoopsToSimplify.insert_range(*L);
725
726 // When a FSDiscriminator is enabled, we don't need to add the multiply
727 // factors to the discriminators.
728 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
730 for (BasicBlock *BB : L->getBlocks())
731 for (Instruction &I : *BB)
732 if (!I.isDebugOrPseudoInst())
733 if (const DILocation *DIL = I.getDebugLoc()) {
734 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
735 if (NewDIL)
736 I.setDebugLoc(*NewDIL);
737 else
739 << "Failed to create new discriminator: "
740 << DIL->getFilename() << " Line: " << DIL->getLine());
741 }
742
743 // Identify what noalias metadata is inside the loop: if it is inside the
744 // loop, the associated metadata must be cloned for each iteration.
745 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
746 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
747
748 // We place the unrolled iterations immediately after the original loop
749 // latch. This is a reasonable default placement if we don't have block
750 // frequencies, and if we do, well the layout will be adjusted later.
751 auto BlockInsertPt = std::next(LatchBlock->getIterator());
752 SmallVector<Instruction *> PartialReductions;
753 for (unsigned It = 1; It != ULO.Count; ++It) {
756 NewLoops[L] = L;
757
758 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
760 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
761 Header->getParent()->insert(BlockInsertPt, New);
762
763 assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
764 "Header should not be in a sub-loop");
765 // Tell LI about New.
766 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
767 if (OldLoop)
768 LoopsToSimplify.insert(NewLoops[OldLoop]);
769
770 if (*BB == Header) {
771 // Loop over all of the PHI nodes in the block, changing them to use
772 // the incoming values from the previous block.
773 for (PHINode *OrigPHI : OrigPHINode) {
774 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
775 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
776
777 // Use cloned phis as parallel phis for partial reductions, which will
778 // get combined to the final reduction result after the loop.
779 if (Reductions.contains(OrigPHI)) {
780 // Collect partial reduction results.
781 if (PartialReductions.empty())
782 PartialReductions.push_back(cast<Instruction>(InVal));
783 PartialReductions.push_back(cast<Instruction>(VMap[InVal]));
784
785 // Update the start value for the cloned phis to use the identity
786 // value for the reduction.
787 const RecurrenceDescriptor &RdxDesc = Reductions[OrigPHI];
789 L->getLoopPreheader(),
791 OrigPHI->getType(),
792 RdxDesc.getFastMathFlags()));
793
794 // Update NewPHI to use the cloned value for the iteration and move
795 // to header.
796 NewPHI->replaceUsesOfWith(InVal, VMap[InVal]);
797 NewPHI->moveBefore(OrigPHI->getIterator());
798 continue;
799 }
800
801 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
802 if (It > 1 && L->contains(InValI))
803 InVal = LastValueMap[InValI];
804 VMap[OrigPHI] = InVal;
805 NewPHI->eraseFromParent();
806 }
807
808 // Eliminate copies of the loop heart intrinsic, if any.
809 if (ULO.Heart) {
810 auto it = VMap.find(ULO.Heart);
811 assert(it != VMap.end());
812 Instruction *heartCopy = cast<Instruction>(it->second);
813 heartCopy->eraseFromParent();
814 VMap.erase(it);
815 }
816 }
817
818 // Remap source location atom instance. Do this now, rather than
819 // when we remap instructions, because remap is called once we've
820 // cloned all blocks (all the clones would get the same atom
821 // number).
822 if (!VMap.AtomMap.empty())
823 for (Instruction &I : *New)
824 RemapSourceAtom(&I, VMap);
825
826 // Update our running map of newest clones
827 LastValueMap[*BB] = New;
828 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
829 VI != VE; ++VI)
830 LastValueMap[VI->first] = VI->second;
831
832 // Add phi entries for newly created values to all exit blocks.
833 for (BasicBlock *Succ : successors(*BB)) {
834 if (L->contains(Succ))
835 continue;
836 for (PHINode &PHI : Succ->phis()) {
837 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
838 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
839 if (It != LastValueMap.end())
840 Incoming = It->second;
841 PHI.addIncoming(Incoming, New);
843 }
844 }
845 // Keep track of new headers and latches as we create them, so that
846 // we can insert the proper branches later.
847 if (*BB == Header)
848 Headers.push_back(New);
849 if (*BB == LatchBlock)
850 Latches.push_back(New);
851
852 // Keep track of the exiting block and its successor block contained in
853 // the loop for the current iteration.
854 auto ExitInfoIt = ExitInfos.find(*BB);
855 if (ExitInfoIt != ExitInfos.end())
856 ExitInfoIt->second.ExitingBlocks.push_back(New);
857
858 NewBlocks.push_back(New);
859 UnrolledLoopBlocks.push_back(New);
860
861 // Update DomTree: since we just copy the loop body, and each copy has a
862 // dedicated entry block (copy of the header block), this header's copy
863 // dominates all copied blocks. That means, dominance relations in the
864 // copied body are the same as in the original body.
865 if (*BB == Header)
866 DT->addNewBlock(New, Latches[It - 1]);
867 else {
868 auto BBDomNode = DT->getNode(*BB);
869 auto BBIDom = BBDomNode->getIDom();
870 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
871 DT->addNewBlock(
872 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
873 }
874 }
875
876 // Remap all instructions in the most recent iteration.
877 // Key Instructions: Nothing to do - we've already remapped the atoms.
878 remapInstructionsInBlocks(NewBlocks, LastValueMap);
879 for (BasicBlock *NewBlock : NewBlocks)
880 for (Instruction &I : *NewBlock)
881 if (auto *II = dyn_cast<AssumeInst>(&I))
883
884 {
885 // Identify what other metadata depends on the cloned version. After
886 // cloning, replace the metadata with the corrected version for both
887 // memory instructions and noalias intrinsics.
888 std::string ext = (Twine("It") + Twine(It)).str();
889 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
890 Header->getContext(), ext);
891 }
892 }
893
894 // Loop over the PHI nodes in the original block, setting incoming values.
895 for (PHINode *PN : OrigPHINode) {
896 if (CompletelyUnroll) {
897 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
898 PN->eraseFromParent();
899 } else if (ULO.Count > 1) {
900 if (Reductions.contains(PN))
901 continue;
902
903 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
904 // If this value was defined in the loop, take the value defined by the
905 // last iteration of the loop.
906 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
907 if (L->contains(InValI))
908 InVal = LastValueMap[InVal];
909 }
910 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
911 PN->addIncoming(InVal, Latches.back());
912 }
913 }
914
915 // Connect latches of the unrolled iterations to the headers of the next
916 // iteration. Currently they point to the header of the same iteration.
917 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
918 unsigned j = (i + 1) % e;
919 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
920 }
921
922 // Update dominators of blocks we might reach through exits.
923 // Immediate dominator of such block might change, because we add more
924 // routes which can lead to the exit: we can now reach it from the copied
925 // iterations too.
926 if (ULO.Count > 1) {
927 for (auto *BB : OriginalLoopBlocks) {
928 auto *BBDomNode = DT->getNode(BB);
929 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
930 for (auto *ChildDomNode : BBDomNode->children()) {
931 auto *ChildBB = ChildDomNode->getBlock();
932 if (!L->contains(ChildBB))
933 ChildrenToUpdate.push_back(ChildBB);
934 }
935 // The new idom of the block will be the nearest common dominator
936 // of all copies of the previous idom. This is equivalent to the
937 // nearest common dominator of the previous idom and the first latch,
938 // which dominates all copies of the previous idom.
939 BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
940 for (auto *ChildBB : ChildrenToUpdate)
941 DT->changeImmediateDominator(ChildBB, NewIDom);
942 }
943 }
944
946 DT->verify(DominatorTree::VerificationLevel::Fast));
947
949 auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
950 auto *Term = cast<BranchInst>(Src->getTerminator());
951 const unsigned Idx = ExitOnTrue ^ WillExit;
952 BasicBlock *Dest = Term->getSuccessor(Idx);
953 BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
954
955 // Remove predecessors from all non-Dest successors.
956 DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
957
958 // Replace the conditional branch with an unconditional one.
959 auto *BI = BranchInst::Create(Dest, Term->getIterator());
960 BI->setDebugLoc(Term->getDebugLoc());
961 Term->eraseFromParent();
962
963 DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
964 };
965
966 auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
967 bool IsLatch) -> std::optional<bool> {
968 if (CompletelyUnroll) {
969 if (PreserveOnlyFirst) {
970 if (i == 0)
971 return std::nullopt;
972 return j == 0;
973 }
974 // Complete (but possibly inexact) unrolling
975 if (j == 0)
976 return true;
977 if (Info.TripCount && j != Info.TripCount)
978 return false;
979 return std::nullopt;
980 }
981
982 if (ULO.Runtime) {
983 // If runtime unrolling inserts a prologue, information about non-latch
984 // exits may be stale.
985 if (IsLatch && j != 0)
986 return false;
987 return std::nullopt;
988 }
989
990 if (j != Info.BreakoutTrip &&
991 (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
992 // If we know the trip count or a multiple of it, we can safely use an
993 // unconditional branch for some iterations.
994 return false;
995 }
996 return std::nullopt;
997 };
998
999 // Fold branches for iterations where we know that they will exit or not
1000 // exit.
1001 for (auto &Pair : ExitInfos) {
1002 ExitInfo &Info = Pair.second;
1003 for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
1004 // The branch destination.
1005 unsigned j = (i + 1) % e;
1006 bool IsLatch = Pair.first == LatchBlock;
1007 std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
1008 if (!KnownWillExit) {
1009 if (!Info.FirstExitingBlock)
1010 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1011 continue;
1012 }
1013
1014 // We don't fold known-exiting branches for non-latch exits here,
1015 // because this ensures that both all loop blocks and all exit blocks
1016 // remain reachable in the CFG.
1017 // TODO: We could fold these branches, but it would require much more
1018 // sophisticated updates to LoopInfo.
1019 if (*KnownWillExit && !IsLatch) {
1020 if (!Info.FirstExitingBlock)
1021 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1022 continue;
1023 }
1024
1025 SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
1026 }
1027 }
1028
1029 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1030 DomTreeUpdater *DTUToUse = &DTU;
1031 if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
1032 // Manually update the DT if there's a single exiting node. In that case
1033 // there's a single exit node and it is sufficient to update the nodes
1034 // immediately dominated by the original exiting block. They will become
1035 // dominated by the first exiting block that leaves the loop after
1036 // unrolling. Note that the CFG inside the loop does not change, so there's
1037 // no need to update the DT inside the unrolled loop.
1038 DTUToUse = nullptr;
1039 auto &[OriginalExit, Info] = *ExitInfos.begin();
1040 if (!Info.FirstExitingBlock)
1041 Info.FirstExitingBlock = Info.ExitingBlocks.back();
1042 for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
1043 if (L->contains(C->getBlock()))
1044 continue;
1045 C->setIDom(DT->getNode(Info.FirstExitingBlock));
1046 }
1047 } else {
1048 DTU.applyUpdates(DTUpdates);
1049 }
1050
1051 // When completely unrolling, the last latch becomes unreachable.
1052 if (!LatchIsExiting && CompletelyUnroll) {
1053 // There is no need to update the DT here, because there must be a unique
1054 // latch. Hence if the latch is not exiting it must directly branch back to
1055 // the original loop header and does not dominate any nodes.
1056 assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
1057 changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
1058 }
1059
1060 // Merge adjacent basic blocks, if possible.
1061 for (BasicBlock *Latch : Latches) {
1062 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
1063 assert((Term ||
1064 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
1065 "Need a branch as terminator, except when fully unrolling with "
1066 "unconditional latch");
1067 if (Term && Term->isUnconditional()) {
1068 BasicBlock *Dest = Term->getSuccessor(0);
1069 BasicBlock *Fold = Dest->getUniquePredecessor();
1070 if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
1071 /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
1072 /*PredecessorWithTwoSuccessors=*/false,
1073 DTUToUse ? nullptr : DT)) {
1074 // Dest has been folded into Fold. Update our worklists accordingly.
1075 llvm::replace(Latches, Dest, Fold);
1076 llvm::erase(UnrolledLoopBlocks, Dest);
1077 }
1078 }
1079 }
1080
1081 // If there are partial reductions, create code in the exit block to compute
1082 // the final result and update users of the final result.
1083 if (!PartialReductions.empty()) {
1084 BasicBlock *ExitBlock = L->getExitBlock();
1085 assert(ExitBlock &&
1086 "Can only introduce parallel reduction phis with single exit block");
1087 assert(Reductions.size() == 1 &&
1088 "currently only a single reduction is supported");
1089 Value *FinalRdxValue = PartialReductions.back();
1090 Value *RdxResult = nullptr;
1091 for (PHINode &Phi : ExitBlock->phis()) {
1092 if (Phi.getIncomingValueForBlock(L->getLoopLatch()) != FinalRdxValue)
1093 continue;
1094 if (!RdxResult) {
1095 RdxResult = PartialReductions.front();
1096 IRBuilder Builder(ExitBlock, ExitBlock->getFirstNonPHIIt());
1097 RecurKind RK = Reductions.begin()->second.getRecurrenceKind();
1098 for (Instruction *RdxPart : drop_begin(PartialReductions)) {
1099 RdxResult = Builder.CreateBinOp(
1101 RdxPart, RdxResult, "bin.rdx");
1102 }
1103 NeedToFixLCSSA = true;
1104 for (Instruction *RdxPart : PartialReductions)
1105 RdxPart->dropPoisonGeneratingFlags();
1106 }
1107
1108 Phi.replaceAllUsesWith(RdxResult);
1109 continue;
1110 }
1111 }
1112
1113 if (DTUToUse) {
1114 // Apply updates to the DomTree.
1115 DT = &DTU.getDomTree();
1116 }
1118 DT->verify(DominatorTree::VerificationLevel::Fast));
1119
1120 // At this point, the code is well formed. We now simplify the unrolled loop,
1121 // doing constant propagation and dead code elimination as we go.
1122 simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
1123 TTI, AA);
1124
1125 NumCompletelyUnrolled += CompletelyUnroll;
1126 ++NumUnrolled;
1127
1128 Loop *OuterL = L->getParentLoop();
1129 // Update LoopInfo if the loop is completely removed.
1130 if (CompletelyUnroll) {
1131 LI->erase(L);
1132 // We shouldn't try to use `L` anymore.
1133 L = nullptr;
1134 } else if (OriginalTripCount) {
1135 // Update the trip count. Note that the remainder has already logic
1136 // computing it in `UnrollRuntimeLoopRemainder`.
1137 setLoopEstimatedTripCount(L, *OriginalTripCount / ULO.Count,
1138 EstimatedLoopInvocationWeight);
1139 }
1140
1141 // LoopInfo should not be valid, confirm that.
1143 LI->verify(*DT);
1144
1145 // After complete unrolling most of the blocks should be contained in OuterL.
1146 // However, some of them might happen to be out of OuterL (e.g. if they
1147 // precede a loop exit). In this case we might need to insert PHI nodes in
1148 // order to preserve LCSSA form.
1149 // We don't need to check this if we already know that we need to fix LCSSA
1150 // form.
1151 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
1152 // it should be possible to fix it in-place.
1153 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1154 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
1155
1156 // Make sure that loop-simplify form is preserved. We want to simplify
1157 // at least one layer outside of the loop that was unrolled so that any
1158 // changes to the parent loop exposed by the unrolling are considered.
1159 if (OuterL) {
1160 // OuterL includes all loops for which we can break loop-simplify, so
1161 // it's sufficient to simplify only it (it'll recursively simplify inner
1162 // loops too).
1163 if (NeedToFixLCSSA) {
1164 // LCSSA must be performed on the outermost affected loop. The unrolled
1165 // loop's last loop latch is guaranteed to be in the outermost loop
1166 // after LoopInfo's been updated by LoopInfo::erase.
1167 Loop *LatchLoop = LI->getLoopFor(Latches.back());
1168 Loop *FixLCSSALoop = OuterL;
1169 if (!FixLCSSALoop->contains(LatchLoop))
1170 while (FixLCSSALoop->getParentLoop() != LatchLoop)
1171 FixLCSSALoop = FixLCSSALoop->getParentLoop();
1172
1173 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
1174 } else if (PreserveLCSSA) {
1175 assert(OuterL->isLCSSAForm(*DT) &&
1176 "Loops should be in LCSSA form after loop-unroll.");
1177 }
1178
1179 // TODO: That potentially might be compile-time expensive. We should try
1180 // to fix the loop-simplified form incrementally.
1181 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1182 } else {
1183 // Simplify loops for which we might've broken loop-simplify form.
1184 for (Loop *SubLoop : LoopsToSimplify)
1185 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1186 }
1187
1188 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
1190}
1191
1192/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
1193/// node with the given name (for example, "llvm.loop.unroll.count"). If no
1194/// such metadata node exists, then nullptr is returned.
1196 // First operand should refer to the loop id itself.
1197 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1198 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1199
1200 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1201 MDNode *MD = dyn_cast<MDNode>(MDO);
1202 if (!MD)
1203 continue;
1204
1206 if (!S)
1207 continue;
1208
1209 if (Name == S->getString())
1210 return MD;
1211 }
1212 return nullptr;
1213}
1214
1215std::optional<RecurrenceDescriptor>
1217 ScalarEvolution *SE) {
1218 RecurrenceDescriptor RdxDesc;
1219 if (!RecurrenceDescriptor::isReductionPHI(&Phi, L, RdxDesc,
1220 /*DemandedBits=*/nullptr,
1221 /*AC=*/nullptr, /*DT=*/nullptr, SE))
1222 return std::nullopt;
1223 RecurKind RK = RdxDesc.getRecurrenceKind();
1224 // Skip unsupported reductions.
1225 // TODO: Handle additional reductions, including FP and min-max
1226 // reductions.
1231 return std::nullopt;
1232
1233 if (RdxDesc.IntermediateStore)
1234 return std::nullopt;
1235
1236 // Don't unroll reductions with constant ops; those can be folded to a
1237 // single induction update.
1238 if (any_of(cast<Instruction>(Phi.getIncomingValueForBlock(L->getLoopLatch()))
1239 ->operands(),
1241 return std::nullopt;
1242
1243 BasicBlock *Latch = L->getLoopLatch();
1244 if (!Latch ||
1245 !is_contained(
1246 cast<Instruction>(Phi.getIncomingValueForBlock(Latch))->operands(),
1247 &Phi))
1248 return std::nullopt;
1249
1250 return RdxDesc;
1251}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Optimize for code generation
#define LLVM_ATTRIBUTE_USED
Definition Compiler.h:236
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
#define DEBUG_TYPE
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...
This defines the Use class.
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.
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale.
void loadCSE(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
Value * getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
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."))
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))
static LLVM_ATTRIBUTE_USED bool canHaveUnrollRemainder(const Loop *L)
static cl::opt< bool > UnrollAddParallelReductions("unroll-add-parallel-reductions", cl::init(false), cl::Hidden, cl::desc("Allow unrolling to add parallel reduction phis."))
#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.
uint64_t IntrinsicInst * II
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
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
void childGeneration(unsigned generation)
bool isProcessed() const
unsigned currentGeneration() const
unsigned childGeneration() const
StackNode(ScopedHashTable< const SCEV *, LoadValue > &AvailableLoads, unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child, DomTreeNode::const_iterator End)
DomTreeNode::const_iterator end() const
void process()
DomTreeNode * nextChild()
DomTreeNode::const_iterator childIter() const
DomTreeNode * node()
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1928
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 begin()
Instruction iterator methods.
Definition BasicBlock.h:459
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 * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
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
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
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, InsertPosition InsertBefore=nullptr)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
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:187
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:165
unsigned size() const
Definition DenseMap.h:108
iterator begin()
Definition DenseMap.h:78
iterator end()
Definition DenseMap.h:81
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:156
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
typename SmallVector< DomTreeNodeBase *, 4 >::const_iterator const_iterator
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...
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2780
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
An instruction for reading from memory.
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.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
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:442
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:899
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
Definition LoopInfo.cpp:475
Metadata node.
Definition Metadata.h:1077
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1445
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1443
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1451
Tracking metadata reference owned by Metadata.
Definition Metadata.h:899
A single uniqued string.
Definition Metadata.h:720
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:617
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:1053
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
FastMathFlags getFastMathFlags() const
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isIntegerRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
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 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.
LLVM_ABI void forgetAllLoops()
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
ScopedHashTableScope< K, V, KInfo, AllocatorTy > ScopeTy
ScopeTy - This is a helpful typedef that allows clients to get easy access to the name of the scope f...
void insert_range(Range &&R)
Definition SetVector.h:193
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:168
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:356
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.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:21
ValueMapIterator< MapT, const Value * > iterator
Definition ValueMap.h:135
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator begin()
Definition ValueMap.h:138
iterator end()
Definition ValueMap.h:139
bool erase(const KeyT &Val)
Definition ValueMap.h:195
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
Definition ValueMap.h:123
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:134
Abstract Attribute helper functions.
Definition Attributor.h:165
@ 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)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:330
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
LLVM_ABI 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.
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...
LLVM_ABI std::optional< RecurrenceDescriptor > canParallelizeReductionWhenUnrolling(PHINode &Phi, Loop *L, ScalarEvolution *SE)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
auto successors(const MachineBasicBlock *BB)
SmallDenseMap< const Loop *, Loop *, 4 > NewLoopsMap
Definition UnrollLoop.h:41
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:449
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:646
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:95
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:759
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2130
LLVM_ABI 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:1734
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
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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...
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
Definition UnrollLoop.h:58
@ PartiallyUnrolled
The loop was partially unrolled – we still have a loop, but with a smaller trip count.
Definition UnrollLoop.h:65
@ Unmodified
The loop was not modified.
Definition UnrollLoop.h:60
@ FullyUnrolled
The loop was fully unrolled into straight-line code.
Definition UnrollLoop.h:69
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:548
LLVM_ABI 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:2513
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.
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1862
RecurKind
These are the kinds of recurrences that we support.
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, unsigned EstimatedLoopInvocationWeight)
Set a loop's branch weight metadata to reflect that loop has EstimatedTripCount iterations and Estima...
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
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:565
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1899
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)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI 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...
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:836
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
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
Instruction * DefI
LoadValue()=default
unsigned Generation
LoadValue(Instruction *Inst, unsigned Generation)
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
const Instruction * Heart
Definition UnrollLoop.h:79