LLVM 24.0.0git
LoopUnrollPass.cpp
Go to the documentation of this file.
1//===- LoopUnroll.cpp - Loop unroller pass --------------------------------===//
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 pass implements a simple loop unroller. It works best when loops have
10// been canonicalized by the -indvars pass, allowing it to determine the trip
11// counts of loops easily.
12//===----------------------------------------------------------------------===//
13
15#include "ScalarOptions.h"
16#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/StringRef.h"
38#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/CFG.h"
40#include "llvm/IR/Constant.h"
41#include "llvm/IR/Constants.h"
43#include "llvm/IR/Dominators.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/Instruction.h"
47#include "llvm/IR/Metadata.h"
48#include "llvm/IR/PassManager.h"
50#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
65#include <algorithm>
66#include <cassert>
67#include <cstdint>
68#include <limits>
69#include <optional>
70#include <string>
71#include <tuple>
72#include <utility>
73
74using namespace llvm;
75
76#define DEBUG_TYPE "loop-unroll"
77
79 const cl::LibraryOptionsContext &LibraryOptions) {
80 return LibraryOptions.get<ScalarOptions>().forget_scev_loop_unroll;
81}
82
83/// A magic value for use with the Threshold parameter to indicate
84/// that the loop unroll should be performed regardless of how much
85/// code expansion would result.
86static const unsigned NoThreshold = std::numeric_limits<unsigned>::max();
87
88/// Gather the various unrolling parameters based on the defaults, compiler
89/// flags, TTI overrides and user specified parameters.
93 OptimizationRemarkEmitter &ORE, int OptLevel,
94 std::optional<unsigned> UserThreshold, std::optional<bool> UserAllowPartial,
95 std::optional<bool> UserRuntime, std::optional<bool> UserUpperBound,
96 std::optional<unsigned> UserFullUnrollMaxCount) {
97 const ScalarOptions &Opts = getScalarOptions(*L);
99
100 // Set up the defaults that depend on options. All other fields use the
101 // default member initializers of UnrollingPreferences.
102 UP.Threshold = OptLevel > 2 ? Opts.unroll_threshold_aggressive
103 : Opts.unroll_threshold_default;
104 UP.OptSizeThreshold = Opts.unroll_optsize_threshold;
105 UP.PartialOptSizeThreshold = Opts.unroll_optsize_threshold;
107
108 // Override with any target specific settings
109 TTI.getUnrollingPreferences(L, SE, UP, &ORE);
110
111 // Apply size attributes
112 bool OptForSize = L->getHeader()->getParent()->hasOptSize() ||
113 // Let unroll hints / pragmas take precedence over PGSO.
115 llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
117 if (OptForSize) {
121 }
122
123 // Apply any user values specified by cl::opt
124 if (Opts.unroll_threshold)
125 UP.Threshold = *Opts.unroll_threshold;
126 if (Opts.unroll_partial_threshold)
127 UP.PartialThreshold = *Opts.unroll_partial_threshold;
128 if (Opts.unroll_max_percent_threshold_boost)
129 UP.MaxPercentThresholdBoost = *Opts.unroll_max_percent_threshold_boost;
130 if (Opts.unroll_max_count)
131 UP.MaxCount = *Opts.unroll_max_count;
132 if (Opts.unroll_max_upperbound)
133 UP.MaxUpperBound = *Opts.unroll_max_upperbound;
134 if (Opts.unroll_full_max_count)
135 UP.FullUnrollMaxCount = *Opts.unroll_full_max_count;
136 UP.Partial = valueOr(Opts.unroll_allow_partial, UP.Partial);
137 UP.AllowRemainder = valueOr(Opts.unroll_allow_remainder, UP.AllowRemainder);
138 UP.Runtime = valueOr(Opts.unroll_runtime, UP.Runtime);
139 if (Opts.unroll_max_upperbound == 0)
140 UP.UpperBound = false;
141 UP.UnrollRemainder = valueOr(Opts.unroll_remainder, UP.UnrollRemainder);
142 if (Opts.unroll_max_iteration_count_to_analyze)
144 *Opts.unroll_max_iteration_count_to_analyze;
145
146 // Apply user values provided by argument
147 if (UserThreshold) {
148 UP.Threshold = *UserThreshold;
149 UP.PartialThreshold = *UserThreshold;
150 }
151 if (UserAllowPartial)
152 UP.Partial = *UserAllowPartial;
153 if (UserRuntime)
154 UP.Runtime = *UserRuntime;
155 if (UserUpperBound)
156 UP.UpperBound = *UserUpperBound;
157 if (UserFullUnrollMaxCount)
158 UP.FullUnrollMaxCount = *UserFullUnrollMaxCount;
159
160 return UP;
161}
162
163namespace {
164
165/// A struct to densely store the state of an instruction after unrolling at
166/// each iteration.
167///
168/// This is designed to work like a tuple of <Instruction *, int> for the
169/// purposes of hashing and lookup, but to be able to associate two boolean
170/// states with each key.
171struct UnrolledInstState {
172 Instruction *I;
173 int Iteration : 30;
174 unsigned IsFree : 1;
175 unsigned IsCounted : 1;
176};
177
178/// Hashing and equality testing for a set of the instruction states.
179struct UnrolledInstStateKeyInfo {
180 using PairInfo = DenseMapInfo<std::pair<Instruction *, int>>;
181
182 static inline unsigned getHashValue(const UnrolledInstState &S) {
183 return PairInfo::getHashValue({S.I, S.Iteration});
184 }
185
186 static inline bool isEqual(const UnrolledInstState &LHS,
187 const UnrolledInstState &RHS) {
188 return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
189 }
190};
191
192struct EstimatedUnrollCost {
193 /// The estimated cost after unrolling.
194 unsigned UnrolledCost;
195
196 /// The estimated dynamic cost of executing the instructions in the
197 /// rolled form.
198 unsigned RolledDynamicCost;
199};
200
201} // end anonymous namespace
202
203/// Figure out if the loop is worth full unrolling.
204///
205/// Complete loop unrolling can make some loads constant, and we need to know
206/// if that would expose any further optimization opportunities. This routine
207/// estimates this optimization. It computes cost of unrolled loop
208/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
209/// dynamic cost we mean that we won't count costs of blocks that are known not
210/// to be executed (i.e. if we have a branch in the loop and we know that at the
211/// given iteration its condition would be resolved to true, we won't add up the
212/// cost of the 'false'-block).
213/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
214/// the analysis failed (no benefits expected from the unrolling, or the loop is
215/// too big to analyze), the returned value is std::nullopt.
216static std::optional<EstimatedUnrollCost> analyzeLoopUnrollCost(
217 const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE,
218 const SmallPtrSetImpl<const Value *> &EphValues,
219 const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize,
220 unsigned MaxIterationsCountToAnalyze) {
221 // We want to be able to scale offsets by the trip count and add more offsets
222 // to them without checking for overflows, and we already don't want to
223 // analyze *massive* trip counts, so we force the max to be reasonably small.
224 assert(MaxIterationsCountToAnalyze <
225 (unsigned)(std::numeric_limits<int>::max() / 2) &&
226 "The unroll iterations max is too large!");
227
228 // Only analyze inner loops. We can't properly estimate cost of nested loops
229 // and we won't visit inner loops again anyway.
230 if (!L->isInnermost()) {
232 << "Not analyzing loop cost: not an innermost loop.\n");
233 return std::nullopt;
234 }
235
236 // Don't simulate loops with a big or unknown tripcount
237 if (!TripCount || TripCount > MaxIterationsCountToAnalyze) {
239 << "Not analyzing loop cost: trip count "
240 << (TripCount ? "too large" : "unknown") << ".\n");
241 return std::nullopt;
242 }
243
246 DenseMap<Value *, Value *> SimplifiedValues;
247 SmallVector<std::pair<Value *, Value *>, 4> SimplifiedInputValues;
248
249 // The estimated cost of the unrolled form of the loop. We try to estimate
250 // this by simplifying as much as we can while computing the estimate.
251 InstructionCost UnrolledCost = 0;
252
253 // We also track the estimated dynamic (that is, actually executed) cost in
254 // the rolled form. This helps identify cases when the savings from unrolling
255 // aren't just exposing dead control flows, but actual reduced dynamic
256 // instructions due to the simplifications which we expect to occur after
257 // unrolling.
258 InstructionCost RolledDynamicCost = 0;
259
260 // We track the simplification of each instruction in each iteration. We use
261 // this to recursively merge costs into the unrolled cost on-demand so that
262 // we don't count the cost of any dead code. This is essentially a map from
263 // <instruction, int> to <bool, bool>, but stored as a densely packed struct.
265
266 // A small worklist used to accumulate cost of instructions from each
267 // observable and reached root in the loop.
269
270 // PHI-used worklist used between iterations while accumulating cost.
272
273 // Helper function to accumulate cost for instructions in the loop.
274 auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
275 assert(Iteration >= 0 && "Cannot have a negative iteration!");
276 assert(CostWorklist.empty() && "Must start with an empty cost list");
277 assert(PHIUsedList.empty() && "Must start with an empty phi used list");
278 CostWorklist.push_back(&RootI);
280 RootI.getFunction()->hasMinSize() ?
283 for (;; --Iteration) {
284 do {
285 Instruction *I = CostWorklist.pop_back_val();
286
287 // InstCostMap only uses I and Iteration as a key, the other two values
288 // don't matter here.
289 auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
290 if (CostIter == InstCostMap.end())
291 // If an input to a PHI node comes from a dead path through the loop
292 // we may have no cost data for it here. What that actually means is
293 // that it is free.
294 continue;
295 auto &Cost = *CostIter;
296 if (Cost.IsCounted)
297 // Already counted this instruction.
298 continue;
299
300 // Mark that we are counting the cost of this instruction now.
301 Cost.IsCounted = true;
302
303 // If this is a PHI node in the loop header, just add it to the PHI set.
304 if (auto *PhiI = dyn_cast<PHINode>(I))
305 if (PhiI->getParent() == L->getHeader()) {
306 assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
307 "inherently simplify during unrolling.");
308 if (Iteration == 0)
309 continue;
310
311 // Push the incoming value from the backedge into the PHI used list
312 // if it is an in-loop instruction. We'll use this to populate the
313 // cost worklist for the next iteration (as we count backwards).
314 if (auto *OpI = dyn_cast<Instruction>(
315 PhiI->getIncomingValueForBlock(L->getLoopLatch())))
316 if (L->contains(OpI))
317 PHIUsedList.push_back(OpI);
318 continue;
319 }
320
321 // First accumulate the cost of this instruction.
322 if (!Cost.IsFree) {
323 // Consider simplified operands in instruction cost.
325 transform(I->operands(), std::back_inserter(Operands),
326 [&](Value *Op) {
327 if (auto Res = SimplifiedValues.lookup(Op))
328 return Res;
329 return Op;
330 });
331 UnrolledCost += TTI.getInstructionCost(I, Operands, CostKind);
333 << "Adding cost of instruction (iteration " << Iteration
334 << "): ");
335 LLVM_DEBUG(I->dump());
336 }
337
338 // We must count the cost of every operand which is not free,
339 // recursively. If we reach a loop PHI node, simply add it to the set
340 // to be considered on the next iteration (backwards!).
341 for (Value *Op : I->operands()) {
342 // Check whether this operand is free due to being a constant or
343 // outside the loop.
344 auto *OpI = dyn_cast<Instruction>(Op);
345 if (!OpI || !L->contains(OpI))
346 continue;
347
348 // Otherwise accumulate its cost.
349 CostWorklist.push_back(OpI);
350 }
351 } while (!CostWorklist.empty());
352
353 if (PHIUsedList.empty())
354 // We've exhausted the search.
355 break;
356
357 assert(Iteration > 0 &&
358 "Cannot track PHI-used values past the first iteration!");
359 CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
360 PHIUsedList.clear();
361 }
362 };
363
364 // Ensure that we don't violate the loop structure invariants relied on by
365 // this analysis.
366 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
367 assert(L->isLCSSAForm(DT) &&
368 "Must have loops in LCSSA form to track live-out values.");
369
371 << "Starting LoopUnroll profitability analysis...\n");
372
374 L->getHeader()->getParent()->hasMinSize() ?
376 // Simulate execution of each iteration of the loop counting instructions,
377 // which would be simplified.
378 // Since the same load will take different values on different iterations,
379 // we literally have to go through all loop's iterations.
380 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
381 LLVM_DEBUG(dbgs().indent(3) << "Analyzing iteration " << Iteration << "\n");
382
383 // Prepare for the iteration by collecting any simplified entry or backedge
384 // inputs.
385 for (Instruction &I : *L->getHeader()) {
386 auto *PHI = dyn_cast<PHINode>(&I);
387 if (!PHI)
388 break;
389
390 // The loop header PHI nodes must have exactly two input: one from the
391 // loop preheader and one from the loop latch.
392 assert(
393 PHI->getNumIncomingValues() == 2 &&
394 "Must have an incoming value only for the preheader and the latch.");
395
396 Value *V = PHI->getIncomingValueForBlock(
397 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
398 if (Iteration != 0 && SimplifiedValues.contains(V))
399 V = SimplifiedValues.lookup(V);
400 SimplifiedInputValues.push_back({PHI, V});
401 }
402
403 // Now clear and re-populate the map for the next iteration.
404 SimplifiedValues.clear();
405 while (!SimplifiedInputValues.empty())
406 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
407
408 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
409
410 BBWorklist.clear();
411 BBWorklist.insert(L->getHeader());
412 // Note that we *must not* cache the size, this loop grows the worklist.
413 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
414 BasicBlock *BB = BBWorklist[Idx];
415
416 // Visit all instructions in the given basic block and try to simplify
417 // it. We don't change the actual IR, just count optimization
418 // opportunities.
419 for (Instruction &I : *BB) {
420 // These won't get into the final code - don't even try calculating the
421 // cost for them.
422 if (EphValues.contains(&I))
423 continue;
424
425 // Track this instruction's expected baseline cost when executing the
426 // rolled loop form.
427 RolledDynamicCost += TTI.getInstructionCost(&I, CostKind);
428
429 // Visit the instruction to analyze its loop cost after unrolling,
430 // and if the visitor returns true, mark the instruction as free after
431 // unrolling and continue.
432 bool IsFree = Analyzer.visit(I);
433 bool Inserted = InstCostMap.insert({&I, (int)Iteration,
434 (unsigned)IsFree,
435 /*IsCounted*/ false}).second;
436 (void)Inserted;
437 assert(Inserted && "Cannot have a state for an unvisited instruction!");
438
439 if (IsFree)
440 continue;
441
442 // Can't properly model a cost of a call.
443 // FIXME: With a proper cost model we should be able to do it.
444 if (auto *CI = dyn_cast<CallInst>(&I)) {
445 const Function *Callee = CI->getCalledFunction();
446 if (!Callee || TTI.isLoweredToCall(Callee)) {
448 << "Can't analyze cost of loop with call\n");
449 return std::nullopt;
450 }
451 }
452
453 // If the instruction might have a side-effect recursively account for
454 // the cost of it and all the instructions leading up to it.
455 if (I.mayHaveSideEffects())
456 AddCostRecursively(I, Iteration);
457
458 // If unrolled body turns out to be too big, bail out.
459 if (UnrolledCost > MaxUnrolledLoopSize) {
460 LLVM_DEBUG({
461 dbgs().indent(3) << "Exceeded threshold.. exiting.\n";
462 dbgs().indent(3)
463 << "UnrolledCost: " << UnrolledCost
464 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize << "\n";
465 });
466 return std::nullopt;
467 }
468 }
469
470 Instruction *TI = BB->getTerminator();
471
472 auto getSimplifiedConstant = [&](Value *V) -> Constant * {
473 if (SimplifiedValues.contains(V))
474 V = SimplifiedValues.lookup(V);
475 return dyn_cast<Constant>(V);
476 };
477
478 // Add in the live successors by first checking whether we have terminator
479 // that may be simplified based on the values simplified by this call.
480 BasicBlock *KnownSucc = nullptr;
481 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
482 if (auto *SimpleCond = getSimplifiedConstant(BI->getCondition())) {
483 // Just take the first successor if condition is undef
484 if (isa<UndefValue>(SimpleCond))
485 KnownSucc = BI->getSuccessor(0);
486 else if (ConstantInt *SimpleCondVal =
487 dyn_cast<ConstantInt>(SimpleCond))
488 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
489 }
490 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
491 if (auto *SimpleCond = getSimplifiedConstant(SI->getCondition())) {
492 // Just take the first successor if condition is undef
493 if (isa<UndefValue>(SimpleCond))
494 KnownSucc = SI->getSuccessor(0);
495 else if (ConstantInt *SimpleCondVal =
496 dyn_cast<ConstantInt>(SimpleCond))
497 KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
498 }
499 }
500 if (KnownSucc) {
501 if (L->contains(KnownSucc))
502 BBWorklist.insert(KnownSucc);
503 else
504 ExitWorklist.insert({BB, KnownSucc});
505 continue;
506 }
507
508 // Add BB's successors to the worklist.
509 for (BasicBlock *Succ : successors(BB))
510 if (L->contains(Succ))
511 BBWorklist.insert(Succ);
512 else
513 ExitWorklist.insert({BB, Succ});
514 AddCostRecursively(*TI, Iteration);
515 }
516
517 // If we found no optimization opportunities on the first iteration, we
518 // won't find them on later ones too.
519 if (UnrolledCost == RolledDynamicCost) {
520 LLVM_DEBUG({
521 dbgs().indent(3) << "No opportunities found.. exiting.\n";
522 dbgs().indent(3) << "UnrolledCost: " << UnrolledCost << "\n";
523 });
524 return std::nullopt;
525 }
526 }
527
528 while (!ExitWorklist.empty()) {
529 BasicBlock *ExitingBB, *ExitBB;
530 std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
531
532 for (Instruction &I : *ExitBB) {
533 auto *PN = dyn_cast<PHINode>(&I);
534 if (!PN)
535 break;
536
537 Value *Op = PN->getIncomingValueForBlock(ExitingBB);
538 if (auto *OpI = dyn_cast<Instruction>(Op))
539 if (L->contains(OpI))
540 AddCostRecursively(*OpI, TripCount - 1);
541 }
542 }
543
544 assert(UnrolledCost.isValid() && RolledDynamicCost.isValid() &&
545 "All instructions must have a valid cost, whether the "
546 "loop is rolled or unrolled.");
547
548 LLVM_DEBUG({
549 dbgs().indent(3) << "Analysis finished:\n";
550 dbgs().indent(3) << "UnrolledCost: " << UnrolledCost
551 << ", RolledDynamicCost: " << RolledDynamicCost << "\n";
552 });
553 return {{unsigned(UnrolledCost.getValue()),
554 unsigned(RolledDynamicCost.getValue())}};
555}
556
558 const Loop *L, const TargetTransformInfo &TTI,
559 const SmallPtrSetImpl<const Value *> &EphValues, unsigned BEInsns,
560 bool PrepareForLTO, bool TripCountIsUniform) {
562 for (BasicBlock *BB : L->blocks())
563 Metrics.analyzeBasicBlock(BB, TTI, EphValues, PrepareForLTO, L);
564 NumInlineCandidates = Metrics.NumInlineCandidates;
565 NotDuplicatable = Metrics.notDuplicatable;
566 Convergence = Metrics.Convergence;
567 LoopSize = Metrics.NumInsts;
568 // Convergent operations make the remainder prelude unsafe by adding a
569 // control-flow dependency, unless the trip count is uniform per
570 // UniformityInfo, in which case all paths agree and the remainder is safe.
572 (Metrics.Convergence != ConvergenceKind::Uncontrolled &&
574 TripCountIsUniform;
575
576 // Don't allow an estimate of size zero. This would allows unrolling of loops
577 // with huge iteration counts, which is a compile time problem even if it's
578 // not a problem for code quality. Also, the code using this size may assume
579 // that each loop has at least three instructions (likely a conditional
580 // branch, a comparison feeding that branch, and some kind of loop increment
581 // feeding that comparison instruction).
582 if (LoopSize.isValid() && LoopSize < BEInsns + 1)
583 // This is an open coded max() on InstructionCost
584 LoopSize = BEInsns + 1;
585}
586
588 const Loop *L) const {
589 auto ReportCannotUnroll = [&](StringRef Reason) {
590 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: " << Reason << ".\n");
591 if (ORE && L)
592 ORE->emit([&]() {
593 return OptimizationRemarkMissed(DEBUG_TYPE, "CannotUnrollLoop",
594 L->getStartLoc(), L->getHeader())
595 << "unable to unroll loop: " << Reason;
596 });
597 };
598
600 ReportCannotUnroll("contains convergent operations");
601 return false;
602 }
603 if (!LoopSize.isValid()) {
604 ReportCannotUnroll("loop size could not be computed");
605 return false;
606 }
607 if (NotDuplicatable) {
608 ReportCannotUnroll("contains non-duplicatable instructions");
609 return false;
610 }
611 return true;
612}
613
615 const TargetTransformInfo::UnrollingPreferences &UP, unsigned Count) const {
616 unsigned LS = LoopSize.getValue();
617 assert(LS >= UP.BEInsns && "LoopSize should not be less than BEInsns!");
618 return static_cast<uint64_t>(LS - UP.BEInsns) * Count + UP.BEInsns;
619}
620
621// Returns true if the loop has an unroll(full) pragma.
622static bool hasUnrollFullPragma(const Loop *L) {
623 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
624}
625
626// Returns true if the loop has an unroll(enable) pragma. This metadata is used
627// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
628static bool hasUnrollEnablePragma(const Loop *L) {
629 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
630}
631
632// Returns true if the loop has a runtime unroll(disable) pragma.
633static bool hasRuntimeUnrollDisablePragma(const Loop *L) {
634 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
635}
636
637/// Returns true if the SCEV expression is uniform, i.e., all threads in a
638/// convergent execution agree on its value.
639/// Returns false if the SCEV could not be computed.
640static bool isSCEVUniform(const SCEV *S, UniformityInfo &UI) {
642 return false;
643 return !SCEVExprContains(S, [&](const SCEV *Node) {
644 const auto *U = dyn_cast<SCEVUnknown>(Node);
645 return U && !UI.isUniformAtDef(U->getValue());
646 });
647}
648
649// If loop has an unroll_count pragma return the (necessarily
650// positive) value from the pragma. Otherwise return 0.
651static unsigned unrollCountPragmaValue(const Loop *L) {
652 MDNode *MD = getUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
653 if (MD) {
654 assert(MD->getNumOperands() == 2 &&
655 "Unroll count hint metadata should have two operands.");
656 unsigned Count =
657 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
658 assert(Count >= 1 && "Unroll count must be positive.");
659 return Count;
660 }
661 return 0;
662}
663
672
673// Computes the boosting factor for complete unrolling.
674// If fully unrolling the loop would save a lot of RolledDynamicCost, it would
675// be beneficial to fully unroll the loop even if unrolledcost is large. We
676// use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust
677// the unroll threshold.
678static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost,
679 unsigned MaxPercentThresholdBoost) {
680 if (Cost.RolledDynamicCost >= std::numeric_limits<unsigned>::max() / 100)
681 return 100;
682 else if (Cost.UnrolledCost != 0)
683 // The boosting factor is RolledDynamicCost / UnrolledCost
684 return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
685 MaxPercentThresholdBoost);
686 else
687 return MaxPercentThresholdBoost;
688}
689
690static std::optional<unsigned>
691shouldPragmaUnroll(const ScalarOptions &Opts, Loop *L,
692 const UnrollPragmaInfo &PInfo, const unsigned TripMultiple,
693 const unsigned TripCount, unsigned MaxTripCount,
694 const UnrollCostEstimator UCE,
697
698 // Using unroll pragma
699 // 1st priority is unroll count set by "unroll-count" option.
700
701 if (PInfo.UserUnrollCount) {
702 if (UP.AllowRemainder &&
703 UCE.getUnrolledLoopSize(UP, *Opts.unroll_count) < UP.Threshold) {
704 LLVM_DEBUG(dbgs().indent(2) << "Unrolling with user-specified count: "
705 << *Opts.unroll_count << ".\n");
706 return *Opts.unroll_count;
707 }
709 << "Not unrolling with user count " << *Opts.unroll_count << ": "
710 << (UP.AllowRemainder ? "exceeds threshold"
711 : "remainder not allowed")
712 << ".\n");
713 }
714
715 // 2nd priority is unroll count set by pragma.
716 if (PInfo.PragmaCount > 0) {
717 if ((UP.AllowRemainder || (TripMultiple % PInfo.PragmaCount == 0))) {
718 LLVM_DEBUG(dbgs().indent(2) << "Unrolling with pragma count: "
719 << PInfo.PragmaCount << ".\n");
720 return PInfo.PragmaCount;
721 }
723 << "Not unrolling with pragma count " << PInfo.PragmaCount
724 << ": remainder not allowed, count does not divide trip "
725 << "multiple " << TripMultiple << ".\n");
726 ORE->emit([&]() {
727 return OptimizationRemarkAnalysis(DEBUG_TYPE, "PragmaUnrollCountRejected",
728 L->getStartLoc(), L->getHeader())
729 << "may be unable to unroll loop with count "
730 << ore::NV("PragmaCount", PInfo.PragmaCount)
731 << ": remainder loop is not allowed and count does not divide "
732 "trip multiple "
733 << ore::NV("TripMultiple", TripMultiple);
734 });
735 }
736
737 if (PInfo.PragmaFullUnroll) {
738 if (TripCount != 0) {
739 // Certain cases with UBSAN can cause trip count to be calculated as
740 // INT_MAX, Block full unrolling at a reasonable limit so that the
741 // compiler doesn't hang trying to unroll the loop. See PR77842
742 if (TripCount > Opts.pragma_unroll_full_max_iterations) {
744 << "Won't unroll; trip count is too large.\n");
745 ORE->emit([&]() {
747 "PragmaFullUnrollTripCountTooLarge",
748 L->getStartLoc(), L->getHeader())
749 << "may be unable to fully unroll loop: trip count "
750 << ore::NV("TripCount", TripCount) << " exceeds limit "
751 << ore::NV("Limit", Opts.pragma_unroll_full_max_iterations);
752 });
753 return std::nullopt;
754 }
755
757 << "Fully unrolling with trip count: " << TripCount << ".\n");
758 return TripCount;
759 }
761 << "Not fully unrolling: unknown trip count.\n");
762 ORE->emit([&]() {
764 "PragmaFullUnrollUnknownTripCount",
765 L->getStartLoc(), L->getHeader())
766 << "may be unable to fully unroll loop: trip count is unknown";
767 });
768 }
769
770 if (PInfo.PragmaEnableUnroll && !TripCount && MaxTripCount &&
771 MaxTripCount <= UP.MaxUpperBound) {
773 << "Unrolling with max trip count: " << MaxTripCount << ".\n");
774 return MaxTripCount;
775 }
776
777 return std::nullopt;
778}
779
780static std::optional<unsigned> shouldFullUnroll(
783 const unsigned FullUnrollTripCount, const UnrollCostEstimator UCE,
785 assert(FullUnrollTripCount && "should be non-zero!");
786
787 if (FullUnrollTripCount > UP.FullUnrollMaxCount) {
789 << "Not unrolling: trip count " << FullUnrollTripCount
790 << " exceeds max count " << UP.FullUnrollMaxCount << ".\n");
791 return std::nullopt;
792 }
793
794 // When computing the unrolled size, note that BEInsns are not replicated
795 // like the rest of the loop body.
796 uint64_t UnrolledSize = UCE.getUnrolledLoopSize(UP, FullUnrollTripCount);
797 if (UnrolledSize < UP.Threshold) {
798 LLVM_DEBUG(dbgs().indent(2) << "Unrolling: size " << UnrolledSize
799 << " < threshold " << UP.Threshold << ".\n");
800 return FullUnrollTripCount;
801 }
802
804 << "Unrolled size " << UnrolledSize << " exceeds threshold "
805 << UP.Threshold << "; checking for cost benefit.\n");
806
807 // The loop isn't that small, but we still can fully unroll it if that
808 // helps to remove a significant number of instructions.
809 // To check that, run additional analysis on the loop.
810 if (std::optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
811 L, FullUnrollTripCount, DT, SE, EphValues, TTI,
814 unsigned Boost =
816 unsigned BoostedThreshold = UP.Threshold * Boost / 100;
817 if (Cost->UnrolledCost < BoostedThreshold) {
818 LLVM_DEBUG(dbgs().indent(2) << "Profitable after cost analysis.\n");
819 return FullUnrollTripCount;
820 }
822 << "Not unrolling: cost " << Cost->UnrolledCost
823 << " >= boosted threshold " << BoostedThreshold << ".\n");
824 }
825
826 return std::nullopt;
827}
828
829static std::optional<unsigned>
830shouldPartialUnroll(const unsigned LoopSize, const unsigned TripCount,
831 const UnrollCostEstimator UCE,
833
834 if (!TripCount)
835 return std::nullopt;
836
837 if (!UP.Partial) {
838 LLVM_DEBUG(dbgs().indent(2) << "Will not try to unroll partially because "
839 << "-unroll-allow-partial not given\n");
840 return 0;
841 }
842 unsigned Count = TripCount;
843 if (UP.PartialThreshold != NoThreshold) {
844 // Reduce unroll count to be modulo of TripCount for partial unrolling.
845 if (UCE.getUnrolledLoopSize(UP, Count) > UP.PartialThreshold) {
846 unsigned NewCount =
847 (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) /
848 (LoopSize - UP.BEInsns);
850 << "Unrolled size exceeds threshold; reducing count "
851 << "from " << Count << " to " << NewCount << ".\n");
852 Count = NewCount;
853 }
854 if (Count > UP.MaxCount)
855 Count = UP.MaxCount;
856 while (Count != 0 && TripCount % Count != 0)
857 Count--;
858 if (UP.AllowRemainder && Count <= 1) {
859 // If there is no Count that is modulo of TripCount, set Count to
860 // largest power-of-two factor that satisfies the threshold limit.
861 // As we'll create fixup loop, do the type of unrolling only if
862 // remainder loop is allowed.
863 // Note: DefaultUnrollRuntimeCount is used as a reasonable starting point
864 // even though this is partial unrolling (not runtime unrolling).
866 while (Count != 0 &&
868 Count >>= 1;
869 }
870 if (Count < 2) {
872 << "Will not partially unroll: no profitable count.\n");
873 Count = 0;
874 }
875 } else {
876 Count = TripCount;
877 }
878 if (Count > UP.MaxCount)
879 Count = UP.MaxCount;
880
882 << "Partially unrolling with count: " << Count << "\n");
883
884 return Count;
885}
886
887static unsigned
888shouldRuntimeUnroll(Loop *L, unsigned MaxTripCount, unsigned TripMultiple,
889 const UnrollCostEstimator &UCE,
890 const UnrollPragmaInfo &PInfo, const ScalarOptions &Opts,
892 // Don't unroll a runtime trip count loop when it is disabled.
893 if (PInfo.PragmaRuntimeUnrollDisable) {
895 << "Not runtime unrolling: disabled by pragma.\n");
896 return 0;
897 }
898
899 // Don't unroll a small upper bound loop unless user or TTI asked to do so.
900 if (MaxTripCount && !UP.Force && MaxTripCount <= UP.MaxUpperBound) {
901 LLVM_DEBUG(dbgs().indent(2) << "Not runtime unrolling: max trip count "
902 << MaxTripCount << " is small (<= "
903 << UP.MaxUpperBound << ") and not forced.\n");
904 return 0;
905 }
906
907 // Check if the runtime trip count is too small when profile is available.
908 if (L->getHeader()->getParent()->hasProfileData()) {
909 if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) {
910 if (*ProfileTripCount < Opts.flat_loop_tripcount_threshold)
911 return 0;
912 else
913 UP.AllowExpensiveTripCount = true;
914 }
915 }
916 if (!UP.Runtime) {
918 << "Will not try to unroll loop with runtime trip count "
919 << "because -unroll-runtime not given\n");
920 return 0;
921 }
922
923 unsigned Count = UP.DefaultUnrollRuntimeCount;
924
925 // Reduce unroll count to be the largest power-of-two factor of
926 // the original count which satisfies the threshold limit.
927 while (Count != 0 && UCE.getUnrolledLoopSize(UP, Count) > UP.PartialThreshold)
928 Count >>= 1;
929
930#ifndef NDEBUG
931 unsigned OrigCount = Count;
932#endif
933
934 if (!UP.AllowRemainder && Count != 0 && (TripMultiple % Count) != 0) {
935 while (Count != 0 && TripMultiple % Count != 0)
936 Count >>= 1;
938 << "Remainder loop is restricted (that could be architecture "
939 "specific or because the loop contains a convergent "
940 "instruction), so unroll count must divide the trip "
941 "multiple, "
942 << TripMultiple << ". Reducing unroll count from " << OrigCount
943 << " to " << Count << ".\n");
944 }
945
946 if (Count > UP.MaxCount)
947 Count = UP.MaxCount;
948
949 if (MaxTripCount && Count > MaxTripCount)
950 Count = MaxTripCount;
951
952 if (Count < 2)
953 Count = 0;
954 else
956 << "Runtime unrolling with count: " << Count << "\n");
957 return Count;
958}
959
960// Calculates and returns the unroll count, using metadata and command-line
961// options that are specific to the LoopUnroll pass (which, for instance, are
962// irrelevant for the LoopUnrollAndJam pass).
963// FIXME: This function is used by LoopUnroll and LoopUnrollAndJam, but consumes
964// many LoopUnroll-specific options. The shared functionality should be
965// refactored into it own function.
969 const SmallPtrSetImpl<const Value *> &EphValues,
970 OptimizationRemarkEmitter *ORE, const unsigned TripCount,
971 const unsigned MaxTripCount, const bool MaxOrZero,
972 const unsigned TripMultiple, const UnrollCostEstimator &UCE,
975 const ScalarOptions &Opts = getScalarOptions(*L);
976
977 unsigned LoopSize = UCE.getRolledLoopSize();
978
979 LLVM_DEBUG(dbgs().indent(1) << "Computing unroll count: TripCount="
980 << TripCount << ", MaxTripCount=" << MaxTripCount
981 << (MaxOrZero ? " (MaxOrZero)" : "")
982 << ", TripMultiple=" << TripMultiple << "\n");
983
984 UnrollPragmaInfo PInfo(L);
985 LLVM_DEBUG({
986 if (PInfo.ExplicitUnroll) {
987 dbgs().indent(1) << "Explicit unroll requested:";
988 if (PInfo.UserUnrollCount)
989 dbgs() << " user-count";
990 if (PInfo.PragmaFullUnroll)
991 dbgs() << " pragma-full";
992 if (PInfo.PragmaCount > 0)
993 dbgs() << " pragma-count(" << PInfo.PragmaCount << ")";
994 if (PInfo.PragmaEnableUnroll)
995 dbgs() << " pragma-enable";
996 dbgs() << "\n";
997 }
998 });
999
1000 // Use an explicit peel count that has been specified for testing. In this
1001 // case it's not permitted to also specify an explicit unroll count.
1002 if (PP.PeelCount) {
1003 if (Opts.unroll_count) {
1004 reportFatalUsageError("Cannot specify both explicit peel count and "
1005 "explicit unroll count");
1006 }
1008 << "Using explicit peel count: " << PP.PeelCount << ".\n");
1009 UP.Runtime = false;
1010 return 1;
1011 }
1012
1013 // If a user provided an explicit unroll pragma (with or without count),
1014 // enable runtime unrolling and override expensive trip count checks.
1015 if (PInfo.PragmaEnableUnroll || PInfo.PragmaCount > 0) {
1016 UP.AllowExpensiveTripCount = true;
1017 UP.Runtime = true;
1018 }
1019
1020 // Check for an explicit unroll count.
1021 // 1st priority is unroll count set by "unroll-count" option.
1022 // 2nd priority is unroll count set by pragma.
1023 LLVM_DEBUG(dbgs().indent(1) << "Trying pragma unroll...\n");
1024 if (auto UnrollFactor =
1025 shouldPragmaUnroll(Opts, L, PInfo, TripMultiple, TripCount,
1026 MaxTripCount, UCE, UP, ORE)) {
1027 if (PInfo.UserUnrollCount || (PInfo.PragmaCount > 0)) {
1028 UP.AllowExpensiveTripCount = true;
1029 UP.Force = true;
1030 }
1031 return *UnrollFactor;
1032 } else {
1033 if (PInfo.ExplicitUnroll && TripCount != 0) {
1034 // If the loop has an unrolling pragma, we want to be more aggressive with
1035 // unrolling limits. Set thresholds to at least the PragmaUnrollThreshold
1036 // value which is larger than the default limits.
1037 UP.Threshold = std::max(UP.Threshold, Opts.pragma_unroll_threshold);
1038 UP.PartialThreshold =
1039 std::max(UP.PartialThreshold, Opts.pragma_unroll_threshold);
1040 }
1041 }
1042
1043 // 3rd priority is exact full unrolling. This will eliminate all copies
1044 // of some exit test.
1045 LLVM_DEBUG(dbgs().indent(1) << "Trying full unroll...\n");
1046 if (TripCount) {
1047 if (auto UnrollFactor =
1048 shouldFullUnroll(L, TTI, DT, SE, EphValues, TripCount, UCE, UP))
1049 return *UnrollFactor;
1050 }
1051
1052 // 4th priority is bounded unrolling.
1053 // We can unroll by the upper bound amount if it's generally allowed or if
1054 // we know that the loop is executed either the upper bound or zero times.
1055 // (MaxOrZero unrolling keeps only the first loop test, so the number of
1056 // loop tests remains the same compared to the non-unrolled version, whereas
1057 // the generic upper bound unrolling keeps all but the last loop test so the
1058 // number of loop tests goes up which may end up being worse on targets with
1059 // constrained branch predictor resources so is controlled by an option.)
1060 // In addition we only unroll small upper bounds.
1061 // Note that the cost of bounded unrolling is always strictly greater than
1062 // cost of exact full unrolling. As such, if we have an exact count and
1063 // found it unprofitable, we'll never chose to bounded unroll.
1064 LLVM_DEBUG(dbgs().indent(1) << "Trying upper-bound unroll...\n");
1065 if (!TripCount && MaxTripCount && (UP.UpperBound || MaxOrZero) &&
1066 MaxTripCount <= UP.MaxUpperBound) {
1067 if (auto UnrollFactor =
1068 shouldFullUnroll(L, TTI, DT, SE, EphValues, MaxTripCount, UCE, UP))
1069 return *UnrollFactor;
1070 }
1071
1072 // 5th priority is loop peeling.
1073 LLVM_DEBUG(dbgs().indent(1) << "Trying loop peeling...\n");
1074 computePeelCount(L, LoopSize, PP, TripCount, DT, SE, TTI, AC, UP.Threshold);
1075 if (PP.PeelCount) {
1077 << "Peeling with count: " << PP.PeelCount << ".\n");
1078 UP.Runtime = false;
1079 return 1;
1080 }
1081
1082 // Before starting partial unrolling, set UP.Partial to true,
1083 // if user explicitly asked for unrolling.
1084 if (TripCount)
1085 UP.Partial |= PInfo.ExplicitUnroll;
1086
1087 // 6th priority is partial unrolling.
1088 // Try partial unroll only when TripCount could be statically calculated.
1089 LLVM_DEBUG(dbgs().indent(1) << "Trying partial unroll...\n");
1090 if (auto UnrollFactor = shouldPartialUnroll(LoopSize, TripCount, UCE, UP))
1091 return *UnrollFactor;
1092 assert(TripCount == 0 &&
1093 "All cases when TripCount is constant should be covered here.");
1094
1095 // 7th priority is runtime unrolling.
1096 LLVM_DEBUG(dbgs().indent(1) << "Trying runtime unroll...\n");
1097 return shouldRuntimeUnroll(L, MaxTripCount, TripMultiple, UCE, PInfo, Opts,
1098 UP);
1099}
1100
1101static LoopUnrollResult
1105 ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel,
1106 bool OnlyFullUnroll, bool OnlyWhenForced, bool ForgetAllSCEV,
1107 bool PrepareForLTO, std::optional<unsigned> ProvidedThreshold,
1108 std::optional<bool> ProvidedAllowPartial,
1109 std::optional<bool> ProvidedRuntime,
1110 std::optional<bool> ProvidedUpperBound,
1111 std::optional<bool> ProvidedAllowPeeling,
1112 std::optional<bool> ProvidedAllowProfileBasedPeeling,
1113 std::optional<unsigned> ProvidedFullUnrollMaxCount,
1114 UniformityInfo *UI = nullptr, AAResults *AA = nullptr) {
1115
1116 LLVM_DEBUG(dbgs() << "Loop Unroll: F["
1117 << L->getHeader()->getParent()->getName() << "] Loop %"
1118 << L->getHeader()->getName()
1119 << " (depth=" << L->getLoopDepth() << ")\n");
1121 if (TM & TM_Disable) {
1122 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: transformation disabled by "
1123 << "metadata.\n");
1125 }
1126
1127 // If this loop isn't forced to be unrolled, avoid unrolling it when the
1128 // parent loop has an explicit unroll-and-jam pragma. This is to prevent
1129 // automatic unrolling from interfering with the user requested
1130 // transformation.
1131 Loop *ParentL = L->getParentLoop();
1132 if (ParentL != nullptr &&
1135 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling loop since parent loop has"
1136 << " llvm.loop.unroll_and_jam.\n");
1138 }
1139
1140 // If this loop isn't forced to be unrolled, avoid unrolling it when the
1141 // loop has an explicit unroll-and-jam pragma. This is to prevent automatic
1142 // unrolling from interfering with the user requested transformation.
1145 LLVM_DEBUG(
1146 dbgs().indent(1)
1147 << "Not unrolling loop since it has llvm.loop.unroll_and_jam.\n");
1149 }
1150
1151 if (!L->isLoopSimplifyForm()) {
1153 << "Not unrolling loop which is not in loop-simplify form.\n");
1154 if (TM & TM_ForcedByUser) {
1155 ORE.emit([&]() {
1156 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInLoopSimplifyForm",
1157 L->getStartLoc(), L->getHeader())
1158 << "unable to unroll loop: not in loop-simplify form";
1159 });
1160 }
1162 }
1163
1164 // When automatic unrolling is disabled, do not unroll unless overridden for
1165 // this loop.
1166 if (OnlyWhenForced && !(TM & TM_Enable)) {
1167 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: automatic unrolling "
1168 << "disabled and loop not explicitly "
1169 << "enabled.\n");
1171 }
1172
1173 bool OptForSize = L->getHeader()->getParent()->hasOptSize();
1175 L, SE, TTI, BFI, PSI, ORE, OptLevel, ProvidedThreshold,
1176 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1177 ProvidedFullUnrollMaxCount);
1179 L, SE, TTI, ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling, true);
1180
1181 // Exit early if unrolling is disabled. For OptForSize, we pick the loop size
1182 // as threshold later on.
1183 if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0) &&
1184 !OptForSize) {
1185 LLVM_DEBUG(dbgs().indent(1) << "Not unrolling: all thresholds are zero.\n");
1186 if (TM & TM_ForcedByUser) {
1187 ORE.emit([&]() {
1188 return OptimizationRemarkMissed(DEBUG_TYPE, "UnrollThresholdsZero",
1189 L->getStartLoc(), L->getHeader())
1190 << "unable to unroll loop: unroll threshold is zero";
1191 });
1192 }
1194 }
1195
1197 CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
1198
1199 // Check if the backedge-taken count is uniform before constructing UCE.
1200 // This is used to allow runtime unrolling with a remainder for convergent
1201 // loops when all threads agree on the trip count.
1202 const SCEV *BTC = SE.getBackedgeTakenCount(L);
1203 bool TripCountIsUniform = UI && isSCEVUniform(BTC, *UI);
1204 UnrollCostEstimator UCE(L, TTI, EphValues, UP.BEInsns, PrepareForLTO,
1205 TripCountIsUniform);
1206 if (!UCE.canUnroll((TM & TM_ForcedByUser) ? &ORE : nullptr, L))
1208
1209 unsigned LoopSize = UCE.getRolledLoopSize();
1210 LLVM_DEBUG(dbgs() << "Loop Size = " << LoopSize << "\n");
1211
1212 // When optimizing for size, use LoopSize + 1 as threshold (we use < Threshold
1213 // later), to (fully) unroll loops, if it does not increase code size.
1214 if (OptForSize)
1215 UP.Threshold = std::max(UP.Threshold, LoopSize + 1);
1216
1217 if (UCE.NumInlineCandidates != 0) {
1219 << "Not unrolling loop with inlinable calls.\n");
1220 if (TM & TM_ForcedByUser) {
1221 ORE.emit([&]() {
1223 "InlineCandidatesPreventUnroll",
1224 L->getStartLoc(), L->getHeader())
1225 << "unable to unroll loop: contains inlinable calls";
1226 });
1227 }
1229 }
1230
1231 // Find the smallest exact trip count for any exit. This is an upper bound
1232 // on the loop trip count, but an exit at an earlier iteration is still
1233 // possible. An unroll by the smallest exact trip count guarantees that all
1234 // branches relating to at least one exit can be eliminated. This is unlike
1235 // the max trip count, which only guarantees that the backedge can be broken.
1236 unsigned TripCount = 0;
1237 unsigned TripMultiple = 1;
1238 SmallVector<BasicBlock *, 8> ExitingBlocks;
1239 L->getExitingBlocks(ExitingBlocks);
1240 for (BasicBlock *ExitingBlock : ExitingBlocks)
1241 if (unsigned TC = SE.getSmallConstantTripCount(L, ExitingBlock))
1242 if (!TripCount || TC < TripCount)
1243 TripCount = TripMultiple = TC;
1244
1245 if (!TripCount) {
1246 // If no exact trip count is known, determine the trip multiple of either
1247 // the loop latch or the single exiting block.
1248 // TODO: Relax for multiple exits.
1249 BasicBlock *ExitingBlock = L->getLoopLatch();
1250 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
1251 ExitingBlock = L->getExitingBlock();
1252 if (ExitingBlock)
1253 TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock);
1254 }
1255
1256 // If the loop contains a convergent operation, the prelude we'd add
1257 // to do the first few instructions before we hit the unrolled loop
1258 // is unsafe -- it adds a control-flow dependency to the convergent
1259 // operation. Therefore restrict remainder loop (try unrolling without).
1261
1262 // Try to find the trip count upper bound if we cannot find the exact trip
1263 // count.
1264 unsigned MaxTripCount = 0;
1265 bool MaxOrZero = false;
1266 if (!TripCount) {
1267 MaxTripCount = SE.getSmallConstantMaxTripCount(L);
1268 MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L);
1269 }
1270
1271 // computeUnrollCount() decides whether it is beneficial to use upper bound to
1272 // fully unroll the loop.
1273 unsigned Count =
1274 computeUnrollCount(L, TTI, DT, LI, &AC, SE, EphValues, &ORE, TripCount,
1275 MaxTripCount, MaxOrZero, TripMultiple, UCE, UP, PP);
1276 if (!Count) {
1278 << "Not unrolling: no viable strategy found.\n");
1279 if (TM & TM_ForcedByUser) {
1280 ORE.emit([&]() {
1281 return OptimizationRemarkMissed(DEBUG_TYPE, "NoUnrollStrategy",
1282 L->getStartLoc(), L->getHeader())
1283 << "unable to unroll loop: no viable unroll count found";
1284 });
1285 }
1287 }
1288
1290
1291 if (PP.PeelCount) {
1292 assert(Count == 1 && "Cannot perform peel and unroll in the same step");
1293 LLVM_DEBUG(dbgs() << "PEELING loop %" << L->getHeader()->getName()
1294 << " with iteration count " << PP.PeelCount << "!\n");
1295 ORE.emit([&]() {
1296 return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
1297 L->getHeader())
1298 << "peeled loop by " << ore::NV("PeelCount", PP.PeelCount)
1299 << " iterations";
1300 });
1301
1302 ValueToValueMapTy VMap;
1303 peelLoop(L, PP.PeelCount, PP.PeelLast, LI, &SE, DT, &AC, PreserveLCSSA,
1304 VMap);
1305 simplifyLoopAfterUnroll(L, true, LI, &SE, &DT, &AC, &TTI, L->getBlocks(),
1306 nullptr);
1307 // If the loop was peeled, we already "used up" the profile information
1308 // we had, so we don't want to unroll or peel again.
1310 L->setLoopAlreadyUnrolled();
1312 }
1313
1314 // Do not attempt partial/runtime unrolling in FullLoopUnrolling
1315 if (OnlyFullUnroll && ((!TripCount && !MaxTripCount) || Count < TripCount ||
1316 Count < MaxTripCount)) {
1318 << "Not attempting partial/runtime unroll in FullLoopUnroll.\n");
1320 }
1321
1322 // At this point, UP.Runtime indicates that run-time unrolling is allowed.
1323 // However, we only want to actually perform it if we don't know the trip
1324 // count and the unroll count doesn't divide the known trip multiple.
1325 // TODO: This decision should probably be pushed up into
1326 // computeUnrollCount().
1327 UP.Runtime &= TripCount == 0 && TripMultiple % Count != 0;
1328
1329 // Save loop properties before it is transformed.
1330 MDNode *OrigLoopID = L->getLoopID();
1331 UnrollPragmaInfo PInfo(L);
1332 DebugLoc LoopStartLoc = L->getStartLoc();
1333 BasicBlock *LoopHeader = L->getHeader();
1334
1335 // Unroll the loop.
1336 Loop *RemainderLoop = nullptr;
1338 ULO.Count = Count;
1339 ULO.Force = UP.Force;
1342 ULO.Runtime = UP.Runtime;
1343 ULO.ForgetAllSCEV = ForgetAllSCEV;
1348 LoopUnrollResult UnrollResult = UnrollLoop(
1349 L, ULO, LI, &SE, &DT, &AC, &TTI, &ORE, PreserveLCSSA, &RemainderLoop, AA);
1350 if (UnrollResult == LoopUnrollResult::Unmodified) {
1351 if (PInfo.ExplicitUnroll) {
1353 << "Failed to unroll loop as explicitly requested.\n");
1354 ORE.emit([&]() {
1355 return OptimizationRemarkMissed(DEBUG_TYPE, "FailedToUnrollAsRequested",
1356 LoopStartLoc, LoopHeader)
1357 << "failed to unroll loop as explicitly requested";
1358 });
1359 }
1361 }
1362
1363 if (PInfo.PragmaFullUnroll && ULO.Count != TripCount) {
1364 ORE.emit([&]() {
1365 return OptimizationRemarkMissed(DEBUG_TYPE, "FullUnrollAsDirectedFailed",
1366 LoopStartLoc, LoopHeader)
1367 << "unable to fully unroll loop as directed; "
1368 << "unrolled by factor " << ore::NV("UnrollCount", ULO.Count);
1369 });
1370 }
1371 if (PInfo.PragmaCount > 0 && ULO.Count != PInfo.PragmaCount) {
1372 ORE.emit([&]() {
1373 return OptimizationRemarkMissed(DEBUG_TYPE, "UnrollCountDiffers",
1374 LoopStartLoc, LoopHeader)
1375 << "unable to unroll loop with requested count "
1376 << ore::NV("RequestedCount", PInfo.PragmaCount)
1377 << "; unrolled by factor " << ore::NV("UnrollCount", ULO.Count);
1378 });
1379 }
1380
1381 if (RemainderLoop) {
1382 std::optional<MDNode *> RemainderLoopID =
1385 if (RemainderLoopID)
1386 RemainderLoop->setLoopID(*RemainderLoopID);
1387 }
1388
1389 if (UnrollResult != LoopUnrollResult::FullyUnrolled) {
1390 std::optional<MDNode *> NewLoopID =
1393 if (NewLoopID) {
1394 L->setLoopID(*NewLoopID);
1395
1396 // Do not setLoopAlreadyUnrolled if loop attributes have been specified
1397 // explicitly.
1398 return UnrollResult;
1399 }
1400 }
1401
1402 // If loop has an unroll count pragma or unrolled by explicitly set count
1403 // mark loop as unrolled to prevent unrolling beyond that requested.
1404 if (UnrollResult != LoopUnrollResult::FullyUnrolled && PInfo.ExplicitUnroll)
1405 L->setLoopAlreadyUnrolled();
1406
1407 return UnrollResult;
1408}
1409
1410namespace {
1411
1412class LoopUnroll : public LoopPass {
1413public:
1414 static char ID; // Pass ID, replacement for typeid
1415
1416 int OptLevel;
1417
1418 /// If false, use a cost model to determine whether unrolling of a loop is
1419 /// profitable. If true, only loops that explicitly request unrolling via
1420 /// metadata are considered. All other loops are skipped.
1421 bool OnlyWhenForced;
1422
1423 /// If false, when SCEV is invalidated, only forget everything in the
1424 /// top-most loop (call forgetTopMostLoop), of the loop being processed.
1425 /// Otherwise, forgetAllLoops and rebuild when needed next.
1426 bool ForgetAllSCEV;
1427
1428 std::optional<unsigned> ProvidedThreshold;
1429 std::optional<bool> ProvidedAllowPartial;
1430 std::optional<bool> ProvidedRuntime;
1431 std::optional<bool> ProvidedUpperBound;
1432 std::optional<bool> ProvidedAllowPeeling;
1433 std::optional<bool> ProvidedAllowProfileBasedPeeling;
1434 std::optional<unsigned> ProvidedFullUnrollMaxCount;
1435
1436 LoopUnroll(int OptLevel = 2, bool OnlyWhenForced = false,
1437 bool ForgetAllSCEV = false,
1438 std::optional<unsigned> Threshold = std::nullopt,
1439 std::optional<bool> AllowPartial = std::nullopt,
1440 std::optional<bool> Runtime = std::nullopt,
1441 std::optional<bool> UpperBound = std::nullopt,
1442 std::optional<bool> AllowPeeling = std::nullopt,
1443 std::optional<bool> AllowProfileBasedPeeling = std::nullopt,
1444 std::optional<unsigned> ProvidedFullUnrollMaxCount = std::nullopt)
1445 : LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced),
1446 ForgetAllSCEV(ForgetAllSCEV), ProvidedThreshold(Threshold),
1447 ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime),
1448 ProvidedUpperBound(UpperBound), ProvidedAllowPeeling(AllowPeeling),
1449 ProvidedAllowProfileBasedPeeling(AllowProfileBasedPeeling),
1450 ProvidedFullUnrollMaxCount(ProvidedFullUnrollMaxCount) {
1452 }
1453
1454 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1455 if (skipLoop(L))
1456 return false;
1457
1458 Function &F = *L->getHeader()->getParent();
1459
1460 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1461 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1462 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1463 const TargetTransformInfo &TTI =
1464 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1465 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1466 UniformityInfo *UI =
1468 ? &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo()
1469 : nullptr;
1470 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
1471 // pass. Function analyses need to be preserved across loop transformations
1472 // but ORE cannot be preserved (see comment before the pass definition).
1473 OptimizationRemarkEmitter ORE(&F);
1474 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1475
1477 L, DT, LI, SE, TTI, AC, ORE, nullptr, nullptr, PreserveLCSSA, OptLevel,
1478 /*OnlyFullUnroll*/ false, OnlyWhenForced, ForgetAllSCEV,
1479 /*PrepareForLTO*/ false, ProvidedThreshold, ProvidedAllowPartial,
1480 ProvidedRuntime, ProvidedUpperBound, ProvidedAllowPeeling,
1481 ProvidedAllowProfileBasedPeeling, ProvidedFullUnrollMaxCount, UI);
1482
1483 if (Result == LoopUnrollResult::FullyUnrolled)
1484 LPM.markLoopAsDeleted(*L);
1485
1486 return Result != LoopUnrollResult::Unmodified;
1487 }
1488
1489 /// This transformation requires natural loop information & requires that
1490 /// loop preheaders be inserted into the CFG...
1491 void getAnalysisUsage(AnalysisUsage &AU) const override {
1492 AU.addRequired<AssumptionCacheTracker>();
1493 AU.addRequired<TargetTransformInfoWrapperPass>();
1494 AU.addRequired<UniformityInfoWrapperPass>();
1495 // FIXME: Loop passes are required to preserve domtree, and for now we just
1496 // recreate dom info if anything gets unrolled.
1498 }
1499};
1500
1501} // end anonymous namespace
1502
1503char LoopUnroll::ID = 0;
1504
1505INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1510INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
1511
1512Pass *llvm::createLoopUnrollPass(int OptLevel, bool OnlyWhenForced,
1513 bool ForgetAllSCEV, int Threshold,
1514 int AllowPartial, int Runtime, int UpperBound,
1515 int AllowPeeling) {
1516 // TODO: It would make more sense for this function to take the optionals
1517 // directly, but that's dangerous since it would silently break out of tree
1518 // callers.
1519 return new LoopUnroll(
1520 OptLevel, OnlyWhenForced, ForgetAllSCEV,
1521 Threshold == -1 ? std::nullopt : std::optional<unsigned>(Threshold),
1522 AllowPartial == -1 ? std::nullopt : std::optional<bool>(AllowPartial),
1523 Runtime == -1 ? std::nullopt : std::optional<bool>(Runtime),
1524 UpperBound == -1 ? std::nullopt : std::optional<bool>(UpperBound),
1525 AllowPeeling == -1 ? std::nullopt : std::optional<bool>(AllowPeeling));
1526}
1527
1530 LPMUpdater &Updater) {
1531 // For the new PM, we can't use OptimizationRemarkEmitter as an analysis
1532 // pass. Function analyses need to be preserved across loop transformations
1533 // but ORE cannot be preserved (see comment before the pass definition).
1534 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
1535 const ScalarOptions &Opts = getScalarOptions(L);
1536
1537 // Keep track of the previous loop structure so we can identify new loops
1538 // created by unrolling.
1539 Loop *ParentL = L.getParentLoop();
1540 SmallPtrSet<Loop *, 4> OldLoops;
1541 if (ParentL)
1542 OldLoops.insert_range(*ParentL);
1543 else
1544 OldLoops.insert_range(AR.LI);
1545
1546 std::string LoopName = std::string(L.getName());
1547
1548 bool Changed =
1549 tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, ORE,
1550 /*BFI*/ nullptr, /*PSI*/ nullptr,
1551 /*PreserveLCSSA*/ true, OptLevel, /*OnlyFullUnroll*/ true,
1552 OnlyWhenForced, ForgetSCEV, PrepareForLTO,
1553 /*Threshold*/ std::nullopt, /*AllowPartial*/ false,
1554 /*Runtime*/ false, /*UpperBound*/ false,
1555 /*AllowPeeling*/ true,
1556 /*AllowProfileBasedPeeling*/ false,
1557 /*FullUnrollMaxCount*/ std::nullopt) !=
1559 if (!Changed)
1560 return PreservedAnalyses::all();
1561
1562 // The parent must not be damaged by unrolling!
1563#ifndef NDEBUG
1564 if (ParentL)
1565 ParentL->verifyLoop();
1566#endif
1567
1568 // Unrolling can do several things to introduce new loops into a loop nest:
1569 // - Full unrolling clones child loops within the current loop but then
1570 // removes the current loop making all of the children appear to be new
1571 // sibling loops.
1572 //
1573 // When a new loop appears as a sibling loop after fully unrolling,
1574 // its nesting structure has fundamentally changed and we want to revisit
1575 // it to reflect that.
1576 //
1577 // When unrolling has removed the current loop, we need to tell the
1578 // infrastructure that it is gone.
1579 //
1580 // Finally, we support a debugging/testing mode where we revisit child loops
1581 // as well. These are not expected to require further optimizations as either
1582 // they or the loop they were cloned from have been directly visited already.
1583 // But the debugging mode allows us to check this assumption.
1584 bool IsCurrentLoopValid = false;
1585 SmallVector<Loop *, 4> SibLoops;
1586 if (ParentL)
1587 SibLoops.append(ParentL->begin(), ParentL->end());
1588 else
1589 SibLoops.append(AR.LI.begin(), AR.LI.end());
1590 erase_if(SibLoops, [&](Loop *SibLoop) {
1591 if (SibLoop == &L) {
1592 IsCurrentLoopValid = true;
1593 return true;
1594 }
1595
1596 // Otherwise erase the loop from the list if it was in the old loops.
1597 return OldLoops.contains(SibLoop);
1598 });
1599 Updater.addSiblingLoops(SibLoops);
1600
1601 if (!IsCurrentLoopValid) {
1602 Updater.markLoopAsDeleted(L, LoopName);
1603 } else {
1604 // We can only walk child loops if the current loop remained valid.
1605 if (Opts.unroll_revisit_child_loops) {
1606 // Walk *all* of the child loops.
1607 SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end());
1608 Updater.addChildLoops(ChildLoops);
1609 }
1610 }
1611
1613}
1614
1617 auto &LI = AM.getResult<LoopAnalysis>(F);
1618 // There are no loops in the function. Return before computing other expensive
1619 // analyses.
1620 if (LI.empty())
1621 return PreservedAnalyses::all();
1622 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1623 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1624 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1625 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1628
1629 UniformityInfo *UI = TTI.hasBranchDivergence(&F)
1631 : nullptr;
1632
1633 LoopAnalysisManager *LAM = nullptr;
1634 if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F))
1635 LAM = &LAMProxy->getManager();
1636
1637 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1638 ProfileSummaryInfo *PSI =
1639 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1640 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
1641 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
1642
1643 bool Changed = false;
1644
1645 // The unroller requires loops to be in simplified form, and also needs LCSSA.
1646 // Since simplification may add new inner loops, it has to run before the
1647 // legality and profitability checks. This means running the loop unroller
1648 // will simplify all loops, regardless of whether anything end up being
1649 // unrolled.
1650 for (const auto &L : LI) {
1651 Changed |= simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr,
1652 false /* PreserveLCSSA */, &TTI);
1653 Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
1654 }
1655
1656 // Add the loop nests in the reverse order of LoopInfo. See method
1657 // declaration.
1659 appendLoopsToWorklist(LI, Worklist);
1660
1661 // Cache the number of loops in each top-level nest. The gated transforms
1662 // never add loops to the worklist, so the counts stay a safe upper bound.
1663 const unsigned MaxNestLoops = getScalarOptions(F).unroll_max_nest_loops;
1664 DenseMap<const Loop *, unsigned> TopLevelNestSize;
1665 if (MaxNestLoops)
1666 for (const Loop *TopL : LI)
1667 TopLevelNestSize[TopL] = TopL->getLoopsInPreorder().size();
1668
1669 while (!Worklist.empty()) {
1670 // Because the LoopInfo stores the loops in RPO, we walk the worklist
1671 // from back to front so that we work forward across the CFG, which
1672 // for unrolling is only needed to get optimization remarks emitted in
1673 // a forward order.
1674 Loop &L = *Worklist.pop_back_val();
1675#ifndef NDEBUG
1676 Loop *ParentL = L.getParentLoop();
1677#endif
1678
1679 // Check if the profile summary indicates that the profiled application
1680 // has a huge working set size, in which case we disable peeling to avoid
1681 // bloating it further.
1682 std::optional<bool> LocalAllowPeeling = UnrollOpts.AllowPeeling;
1683 if (PSI && PSI->hasHugeWorkingSetSize())
1684 LocalAllowPeeling = false;
1685
1686 // Suppress heuristic runtime/partial unrolling and peeling for loops in a
1687 // pathologically large nest, where each such transform forces a whole-nest
1688 // SCEV invalidation (quadratic compile time). Explicit unroll pragmas still
1689 // win: gatherUnrollingPreferences applies these overrides before
1690 // computeUnrollCount re-enables unrolling for pragma-marked loops.
1691 std::optional<bool> LocalAllowRuntime = UnrollOpts.AllowRuntime;
1692 std::optional<bool> LocalAllowPartial = UnrollOpts.AllowPartial;
1693 if (MaxNestLoops) {
1694 unsigned NestSize = TopLevelNestSize.lookup(L.getOutermostLoop());
1695 if (NestSize > MaxNestLoops) {
1696 LocalAllowRuntime = false;
1697 LocalAllowPartial = false;
1698 LocalAllowPeeling = false;
1700 << "Disabling runtime/partial unroll and peeling: "
1701 "outermost nest has "
1702 << NestSize << " loops (> " << MaxNestLoops << ").\n");
1703 }
1704 }
1705
1706 std::string LoopName = std::string(L.getName());
1707 // The API here is quite complex to call and we allow to select some
1708 // flavors of unrolling during construction time (by setting UnrollOpts).
1709 LoopUnrollResult Result =
1710 tryToUnrollLoop(&L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI,
1711 /*PreserveLCSSA*/ true, UnrollOpts.OptLevel,
1712 /*OnlyFullUnroll*/ false, UnrollOpts.OnlyWhenForced,
1713 UnrollOpts.ForgetSCEV, UnrollOpts.PrepareForLTO,
1714 /*Threshold*/ std::nullopt, LocalAllowPartial,
1715 LocalAllowRuntime, UnrollOpts.AllowUpperBound,
1716 LocalAllowPeeling, UnrollOpts.AllowProfileBasedPeeling,
1717 UnrollOpts.FullUnrollMaxCount, UI, &AA);
1719
1720 // The parent must not be damaged by unrolling!
1721#ifndef NDEBUG
1722 if (Result != LoopUnrollResult::Unmodified && ParentL)
1723 ParentL->verifyLoop();
1724#endif
1725
1726 // Clear any cached analysis results for L if we removed it completely.
1727 if (LAM && Result == LoopUnrollResult::FullyUnrolled)
1728 LAM->clear(L, LoopName);
1729 }
1730
1731 if (!Changed)
1732 return PreservedAnalyses::all();
1733
1735}
1736
1738 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1739 static_cast<PassInfoMixin<LoopUnrollPass> *>(this)->printPipeline(
1740 OS, MapClassName2PassName);
1741 OS << '<';
1742 if (UnrollOpts.AllowPartial != std::nullopt)
1743 OS << (*UnrollOpts.AllowPartial ? "" : "no-") << "partial;";
1744 if (UnrollOpts.AllowPeeling != std::nullopt)
1745 OS << (*UnrollOpts.AllowPeeling ? "" : "no-") << "peeling;";
1746 if (UnrollOpts.AllowRuntime != std::nullopt)
1747 OS << (*UnrollOpts.AllowRuntime ? "" : "no-") << "runtime;";
1748 if (UnrollOpts.AllowUpperBound != std::nullopt)
1749 OS << (*UnrollOpts.AllowUpperBound ? "" : "no-") << "upperbound;";
1750 if (UnrollOpts.AllowProfileBasedPeeling != std::nullopt)
1751 OS << (*UnrollOpts.AllowProfileBasedPeeling ? "" : "no-")
1752 << "profile-peeling;";
1753 if (UnrollOpts.FullUnrollMaxCount != std::nullopt)
1754 OS << "full-unroll-max=" << UnrollOpts.FullUnrollMaxCount << ';';
1755 if (UnrollOpts.PrepareForLTO)
1756 OS << "prepare-for-lto;";
1757 OS << 'O' << UnrollOpts.OptLevel;
1758 OS << '>';
1759}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
#define DEBUG_TYPE
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
This header provides classes for managing per-loop analyses.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
static LoopUnrollResult tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, const TargetTransformInfo &TTI, AssumptionCache &AC, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel, bool OnlyFullUnroll, bool OnlyWhenForced, bool ForgetAllSCEV, bool PrepareForLTO, std::optional< unsigned > ProvidedThreshold, std::optional< bool > ProvidedAllowPartial, std::optional< bool > ProvidedRuntime, std::optional< bool > ProvidedUpperBound, std::optional< bool > ProvidedAllowPeeling, std::optional< bool > ProvidedAllowProfileBasedPeeling, std::optional< unsigned > ProvidedFullUnrollMaxCount, UniformityInfo *UI=nullptr, AAResults *AA=nullptr)
static bool hasUnrollFullPragma(const Loop *L)
static bool isSCEVUniform(const SCEV *S, UniformityInfo &UI)
Returns true if the SCEV expression is uniform, i.e., all threads in a convergent execution agree on ...
static unsigned unrollCountPragmaValue(const Loop *L)
static bool hasUnrollEnablePragma(const Loop *L)
static std::optional< unsigned > shouldFullUnroll(Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, ScalarEvolution &SE, const SmallPtrSetImpl< const Value * > &EphValues, const unsigned FullUnrollTripCount, const UnrollCostEstimator UCE, const TargetTransformInfo::UnrollingPreferences &UP)
static std::optional< EstimatedUnrollCost > analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const SmallPtrSetImpl< const Value * > &EphValues, const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize, unsigned MaxIterationsCountToAnalyze)
Figure out if the loop is worth full unrolling.
static std::optional< unsigned > shouldPragmaUnroll(const ScalarOptions &Opts, Loop *L, const UnrollPragmaInfo &PInfo, const unsigned TripMultiple, const unsigned TripCount, unsigned MaxTripCount, const UnrollCostEstimator UCE, const TargetTransformInfo::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE)
static std::optional< unsigned > shouldPartialUnroll(const unsigned LoopSize, const unsigned TripCount, const UnrollCostEstimator UCE, const TargetTransformInfo::UnrollingPreferences &UP)
static const unsigned NoThreshold
A magic value for use with the Threshold parameter to indicate that the loop unroll should be perform...
static unsigned shouldRuntimeUnroll(Loop *L, unsigned MaxTripCount, unsigned TripMultiple, const UnrollCostEstimator &UCE, const UnrollPragmaInfo &PInfo, const ScalarOptions &Opts, TargetTransformInfo::UnrollingPreferences &UP)
static bool hasRuntimeUnrollDisablePragma(const Loop *L)
static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost, unsigned MaxPercentThresholdBoost)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Trace Metrics
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.
LoopAnalysisManager LAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SI Fold Operands
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 SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
Value * RHS
Value * LHS
A manager for alias analyses.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional Branch instruction.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
A debug info location.
Definition DebugLoc.h:127
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
bool isUniformAtDef(ConstValueRefT V) const
Whether V is uniform/non-divergent at its definition.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
void addChildLoops(ArrayRef< Loop * > NewChildLoops)
Loop passes should use this method to indicate they have added new child loops of the current loop.
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
void addSiblingLoops(ArrayRef< Loop * > NewSibLoops)
Loop passes should use this method to indicate they have added new sibling loops to the current loop.
void markLoopAsDeleted(Loop &L)
Definition LoopPass.cpp:124
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
void verifyLoop() const
Verify loop structure.
iterator end() const
iterator begin() const
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
iterator end() const
iterator begin() const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:577
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
Diagnostic information for optimization analysis remarks.
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 missed-optimization remarks.
Diagnostic information for applied optimization remarks.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
bool empty() const
Determine if the PriorityWorklist is empty or not.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
This class represents an analyzed expression in the program.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
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 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 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.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
void insert_range(Range &&R)
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
TargetCostKind
The kind of cost model.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
Produce an estimate of the unrolled cost of the specified loop.
Definition UnrollLoop.h:150
ConvergenceKind Convergence
Definition UnrollLoop.h:156
LLVM_ABI bool canUnroll(OptimizationRemarkEmitter *ORE=nullptr, const Loop *L=nullptr) const
Whether it is legal to unroll this loop.
LLVM_ABI uint64_t getUnrolledLoopSize(const TargetTransformInfo::UnrollingPreferences &UP, unsigned Count) const
Returns loop size estimation for an unrolled loop with the given unroll count and the unrolling confi...
LLVM_ABI UnrollCostEstimator(const Loop *L, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &EphValues, unsigned BEInsns, bool PrepareForLTO=false, bool TripCountIsUniform=false)
uint64_t getRolledLoopSize() const
Definition UnrollLoop.h:174
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
iterator find(const_arg_type_t< ValueT > V)
Definition DenseSet.h:175
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Abstract Attribute helper functions.
Definition Attributor.h:166
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
LLVM_ABI Pass * createLoopUnrollPass(int OptLevel=2, bool OnlyWhenForced=false, bool ForgetAllSCEV=false, int Threshold=-1, int AllowPartial=-1, int Runtime=-1, int UpperBound=-1, int AllowPeeling=-1)
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
LLVM_ABI unsigned computeUnrollCount(Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI, AssumptionCache *AC, ScalarEvolution &SE, const SmallPtrSetImpl< const Value * > &EphValues, OptimizationRemarkEmitter *ORE, unsigned TripCount, unsigned MaxTripCount, bool MaxOrZero, unsigned TripMultiple, const UnrollCostEstimator &UCE, TargetTransformInfo::UnrollingPreferences &UP, TargetTransformInfo::PeelingPreferences &PP)
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Runtime
Detect stack use after return if not disabled runtime with (ASAN_OPTIONS=detect_stack_use_after_retur...
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
LLVM_ABI std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
LLVM_ABI TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, llvm::OptimizationRemarkEmitter &ORE, int OptLevel, std::optional< unsigned > UserThreshold, std::optional< bool > UserAllowPartial, std::optional< bool > UserRuntime, std::optional< bool > UserUpperBound, std::optional< unsigned > UserFullUnrollMaxCount)
Gather the various unrolling parameters based on the defaults, compiler flags, TTI overrides and user...
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:545
LLVM_ABI void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, ArrayRef< BasicBlock * > Blocks, AAResults *AA=nullptr)
Perform some cleanup and simplifications on loops after unrolling.
const ScalarOptions & getScalarOptions(const LLVMContext &C)
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, const TargetTransformInfo *TTI=nullptr)
Simplify each loop in a loop nest recursively.
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
LLVM_ABI void initializeLoopUnrollPass(PassRegistry &)
LLVM_ABI TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI bool getForgetSCEVInLoopUnroll(const cl::LibraryOptionsContext &LibraryOptions)
Return -forget-scev-loop-unroll.
LLVM_ABI TransformationMode hasUnrollAndJamTransformation(const Loop *L)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::PeelingPreferences &PP, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const TargetTransformInfo &TTI, AssumptionCache *AC=nullptr, unsigned Threshold=UINT_MAX)
Definition LoopPeel.cpp:749
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
LLVM_ABI TransformationMode hasUnrollTransformation(const Loop *L)
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:547
LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_ABI void peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
const char *const LLVMLoopUnrollFollowupAll
Definition UnrollLoop.h:45
TargetTransformInfo TTI
TransformationMode
The mode sets how eager a transformation should be applied.
Definition LoopUtils.h:292
@ TM_ForcedByUser
The transformation was directed by the user, e.g.
Definition LoopUtils.h:309
@ TM_Disable
The transformation should not be applied.
Definition LoopUtils.h:301
@ TM_Enable
The transformation should be applied without considering a cost model.
Definition LoopUtils.h:298
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI MDNode * getUnrollMetadataForLoop(const Loop *L, StringRef Name)
DWARFExpression::Operation Op
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
const char *const LLVMLoopUnrollFollowupRemainder
Definition UnrollLoop.h:48
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
const char *const LLVMLoopUnrollFollowupUnrolled
Definition UnrollLoop.h:46
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
constexpr bool valueOr(BoolOrDefault X, bool Default)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition CodeMetrics.h:34
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
bool PeelLast
Peel off the last PeelCount loop iterations.
bool PeelProfiledIterations
Allow peeling basing on profile.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...
Parameters that control the generic loop unrolling transformation.
bool UpperBound
Allow using trip count upper bound to unroll loops.
unsigned Threshold
The cost threshold for the unrolled loop.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
unsigned DefaultUnrollRuntimeCount
Default unroll count for loops with run-time trip count.
unsigned MaxPercentThresholdBoost
If complete unrolling will reduce the cost of the loop, we will boost the Threshold by a certain perc...
bool RuntimeUnrollMultiExit
Allow runtime unrolling multi-exit loops.
unsigned SCEVExpansionBudget
Don't allow runtime unrolling if expanding the trip count takes more than SCEVExpansionBudget.
bool AddAdditionalAccumulators
Allow unrolling to add parallel reduction phis.
unsigned MaxIterationsCountToAnalyze
Don't allow loop unrolling to simulate more than this number of iterations when checking full unroll ...
bool AllowRemainder
Allow generation of a loop remainder (extra iterations after unroll).
bool UnrollRemainder
Allow unrolling of all the iterations of the runtime loop remainder.
unsigned FullUnrollMaxCount
Set the maximum unrolling factor for full unrolling.
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable).
bool AllowExpensiveTripCount
Allow emitting expensive instructions (such as divisions) when computing the trip count of a loop for...
unsigned MaxUpperBound
Set the maximum upper bound of trip count.
const Instruction * Heart
Definition UnrollLoop.h:79
const bool PragmaFullUnroll
Definition UnrollLoop.h:131
LLVM_ABI UnrollPragmaInfo(const Loop *L)
const unsigned PragmaCount
Definition UnrollLoop.h:132
const bool ExplicitUnroll
Definition UnrollLoop.h:135
const bool PragmaRuntimeUnrollDisable
Definition UnrollLoop.h:134
const bool UserUnrollCount
Definition UnrollLoop.h:130
const bool PragmaEnableUnroll
Definition UnrollLoop.h:133