LLVM 24.0.0git
LoopVectorize.cpp
Go to the documentation of this file.
1//===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
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 is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
10// and generates target-independent LLVM-IR.
11// The vectorizer uses the TargetTransformInfo analysis to estimate the costs
12// of instructions in order to estimate the profitability of vectorization.
13//
14// The loop vectorizer combines consecutive loop iterations into a single
15// 'wide' iteration. After this transformation the index is incremented
16// by the SIMD vector width, and not by one.
17//
18// This pass has three parts:
19// 1. The main loop pass that drives the different parts.
20// 2. LoopVectorizationLegality - A unit that checks for the legality
21// of the vectorization.
22// 3. InnerLoopVectorizer - A unit that performs the actual
23// widening of instructions.
24// 4. LoopVectorizationCostModel - A unit that checks for the profitability
25// of vectorization. It decides on the optimal vector width, which
26// can be one, if vectorization is not profitable.
27//
28// There is a development effort going on to migrate loop vectorizer to the
29// VPlan infrastructure and to introduce outer loop vectorization support (see
30// docs/VectorizationPlan.rst and
31// http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
32// purpose, we temporarily introduced the VPlan-native vectorization path: an
33// alternative vectorization path that is natively implemented on top of the
34// VPlan infrastructure. See EnableVPlanNativePath for enabling.
35//
36//===----------------------------------------------------------------------===//
37//
38// The reduction-variable vectorization is based on the paper:
39// D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
40//
41// Variable uniformity checks are inspired by:
42// Karrenberg, R. and Hack, S. Whole Function Vectorization.
43//
44// The interleaved access vectorization is based on the paper:
45// Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
46// Data for SIMD
47//
48// Other ideas/concepts are from:
49// A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
50//
51// S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
52// Vectorizing Compilers.
53//
54//===----------------------------------------------------------------------===//
55
58#include "VPRecipeBuilder.h"
59#include "VPlan.h"
60#include "VPlanAnalysis.h"
61#include "VPlanCFG.h"
62#include "VPlanHelpers.h"
63#include "VPlanPatternMatch.h"
64#include "VPlanTransforms.h"
65#include "VPlanUtils.h"
66#include "VPlanVerifier.h"
67#include "llvm/ADT/APInt.h"
68#include "llvm/ADT/ArrayRef.h"
69#include "llvm/ADT/DenseMap.h"
70#include "llvm/ADT/Hashing.h"
71#include "llvm/ADT/MapVector.h"
72#include "llvm/ADT/STLExtras.h"
75#include "llvm/ADT/Statistic.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/Twine.h"
78#include "llvm/ADT/TypeSwitch.h"
84#include "llvm/Analysis/CFG.h"
102#include "llvm/IR/Attributes.h"
103#include "llvm/IR/BasicBlock.h"
104#include "llvm/IR/CFG.h"
105#include "llvm/IR/Constant.h"
106#include "llvm/IR/Constants.h"
107#include "llvm/IR/DataLayout.h"
108#include "llvm/IR/DebugInfo.h"
109#include "llvm/IR/DebugLoc.h"
110#include "llvm/IR/DerivedTypes.h"
112#include "llvm/IR/Dominators.h"
113#include "llvm/IR/Function.h"
114#include "llvm/IR/IRBuilder.h"
115#include "llvm/IR/InstrTypes.h"
116#include "llvm/IR/Instruction.h"
117#include "llvm/IR/Instructions.h"
119#include "llvm/IR/Intrinsics.h"
120#include "llvm/IR/MDBuilder.h"
121#include "llvm/IR/Metadata.h"
122#include "llvm/IR/Module.h"
123#include "llvm/IR/Operator.h"
124#include "llvm/IR/PatternMatch.h"
126#include "llvm/IR/Type.h"
127#include "llvm/IR/Use.h"
128#include "llvm/IR/User.h"
129#include "llvm/IR/Value.h"
130#include "llvm/IR/Verifier.h"
131#include "llvm/Support/Casting.h"
133#include "llvm/Support/Debug.h"
148#include <algorithm>
149#include <cassert>
150#include <cmath>
151#include <cstdint>
152#include <functional>
153#include <iterator>
154#include <memory>
155#include <string>
156#include <tuple>
157#include <utility>
158
159using namespace llvm;
160using namespace SCEVPatternMatch;
161using namespace LoopVectorizationUtils;
162
163#define LV_NAME "loop-vectorize"
164#define DEBUG_TYPE LV_NAME
165
166#ifndef NDEBUG
167const char VerboseDebug[] = DEBUG_TYPE "-verbose";
168#endif
169
170STATISTIC(LoopsVectorized, "Number of loops vectorized");
171STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
172STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
173STATISTIC(LoopsEarlyExitVectorized, "Number of early exit loops vectorized");
174STATISTIC(LoopsPartialAliasVectorized,
175 "Number of partial aliasing loops vectorized");
176
178 "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
179 cl::desc("Enable vectorization of epilogue loops."));
180
182 "epilogue-vectorization-force-VF", cl::init(ElementCount::getFixed(1)),
184 cl::desc("When epilogue vectorization is enabled, and a value greater than "
185 "1 is specified, forces the given VF for all applicable epilogue "
186 "loops. Note: This allows all scalable VFs >= vscale x 1."));
187
189 "epilogue-vectorization-minimum-VF", cl::Hidden,
190 cl::desc("Only loops with vectorization factor equal to or larger than "
191 "the specified value are considered for epilogue vectorization."));
192
193/// Loops with a known constant trip count below this number are vectorized only
194/// if no scalar iteration overheads are incurred.
196 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
197 cl::desc("Loops with a constant trip count that is smaller than this "
198 "value are vectorized only if no scalar iteration overheads "
199 "are incurred."));
200
202 "force-partial-aliasing-vectorization", cl::init(false), cl::Hidden,
203 cl::desc("Replace pointer diff checks with alias masks."));
204
205/// Option tail-folding-policy controls the tail-folding strategy and lists all
206/// available options. The vectorizer will attempt to fold the tail-loop into
207/// the vector loop (main/epilogue loops) and predicate the instructions
208/// accordingly. If tail-folding fails, there are different fallback strategies
209/// depending on these values:
211
213 "tail-folding-policy", cl::init(TailFoldingPolicyTy::None), cl::Hidden,
214 cl::desc("Tail-folding preferences over creating an epilogue loop."),
216 clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail",
217 "Don't tail-fold loops."),
219 "prefer tail-folding, otherwise create an epilogue when "
220 "appropriate."),
222 "always tail-fold, don't attempt vectorization if "
223 "tail-folding fails.")));
224
226 "epilogue-tail-folding-policy", cl::Hidden,
227 cl::desc(
228 "Epilogue-tail-folding preferences over creating an epilogue loop."),
230 clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail",
231 "Don't tail-fold loops."),
233 "prefer tail-folding, otherwise create an epilogue when "
234 "appropriate.")));
235
237 "force-tail-folding-style", cl::desc("Force the tail folding style"),
240 clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"),
243 "Create lane mask for data only, using active.lane.mask intrinsic"),
245 "data-without-lane-mask",
246 "Create lane mask with compare/stepvector"),
248 "Create lane mask using active.lane.mask intrinsic, and use "
249 "it for both data and control flow"),
251 "Use predicated EVL instructions for tail folding. If EVL "
252 "is unsupported, fallback to data-without-lane-mask.")));
253
255 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
256 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
257
258/// An interleave-group may need masking if it resides in a block that needs
259/// predication, or in order to mask away gaps.
261 "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
262 cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
263
265 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
266 cl::desc("A flag that overrides the target's number of scalar registers."));
267
269 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
270 cl::desc("A flag that overrides the target's number of vector registers."));
271
273 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
274 cl::desc("A flag that overrides the target's max interleave factor for "
275 "scalar loops."));
276
278 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
279 cl::desc("A flag that overrides the target's max interleave factor for "
280 "vectorized loops."));
281
283 "small-loop-cost", cl::init(20), cl::Hidden,
284 cl::desc(
285 "The cost of a loop that is considered 'small' by the interleaver."));
286
288 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
289 cl::desc("Enable the use of the block frequency analysis to access PGO "
290 "heuristics minimizing code growth in cold regions and being more "
291 "aggressive in hot regions."));
292
293// Runtime interleave loops for load/store throughput.
295 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
296 cl::desc(
297 "Enable runtime interleaving until load/store ports are saturated"));
298
299// TODO: Move size-based thresholds out of legality checking, make cost based
300// decisions instead of hard thresholds.
302 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
303 cl::desc("The maximum number of SCEV checks allowed."));
304
306 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
307 cl::desc("The maximum number of SCEV checks allowed with a "
308 "vectorize(enable) pragma"));
309
311 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
312 cl::desc("Count the induction variable only once when interleaving"));
313
315 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
316 cl::desc("The maximum interleave count to use when interleaving a scalar "
317 "reduction in a nested loop."));
318
320 "force-ordered-reductions", cl::init(false), cl::Hidden,
321 cl::desc("Enable the vectorisation of loops with in-order (strict) "
322 "FP reductions"));
323
325 "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
326 cl::desc(
327 "Prefer predicating a reduction operation over an after loop select."));
328
330 "enable-vplan-native-path", cl::Hidden,
331 cl::desc("Enable VPlan-native vectorization path with "
332 "support for outer loop vectorization."));
333
335 llvm::VerifyEachVPlan("vplan-verify-each",
336#ifdef EXPENSIVE_CHECKS
337 cl::init(true),
338#else
339 cl::init(false),
340#endif
342 cl::desc("Verify VPlans after VPlan transforms."));
343
344#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
346 "vplan-print-before-all", cl::init(false), cl::Hidden,
347 cl::desc("Print VPlans before all VPlan transformations."));
348
350 "vplan-print-after-all", cl::init(false), cl::Hidden,
351 cl::desc("Print VPlans after all VPlan transformations."));
352
354 "vplan-print-before", cl::Hidden,
355 cl::desc("Print VPlans before specified VPlan transformations (regexp)."));
356
358 "vplan-print-after", cl::Hidden,
359 cl::desc("Print VPlans after specified VPlan transformations (regexp)."));
360
362 "vplan-print-vector-region-scope", cl::init(false), cl::Hidden,
363 cl::desc("Limit VPlan printing to vector loop region in "
364 "`-vplan-print-after*` if the plan has one."));
365#endif
366
368 "interleave-loops", cl::init(true), cl::Hidden,
369 cl::desc("Enable loop interleaving in Loop vectorization passes"));
371 "vectorize-loops", cl::init(true), cl::Hidden,
372 cl::desc("Run the Loop vectorization passes"));
373
374namespace llvm {
376 "force-target-instruction-cost", cl::init(0), cl::Hidden,
377 cl::desc("A flag that overrides the target's expected cost for "
378 "an instruction to a single constant value. Mostly "
379 "useful for getting consistent testing."));
380
381/// The number of stores in a loop that are allowed to need predication.
383 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
384 cl::desc("Max number of stores to be predicated behind an if."));
385
386// This flag enables the stress testing of the VPlan H-CFG construction in the
387// VPlan-native vectorization path. It must be used in conjuction with
388// -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
389// verification of the H-CFGs built.
391 "vplan-build-outerloop-stress-test", cl::init(false), cl::Hidden,
392 cl::desc(
393 "Build VPlan for every supported loop nest in the function and bail "
394 "out right after the build (stress test the VPlan H-CFG construction "
395 "in the VPlan-native vectorization path)."));
396} // namespace llvm
397
399 ForceMaskedDivRem("force-widen-divrem-via-masked-intrinsic", cl::Hidden,
400 cl::desc("Override cost based masked intrinsic widening "
401 "for div/rem instructions"));
402
404 "enable-early-exit-vectorization", cl::init(true), cl::Hidden,
405 cl::desc(
406 "Enable vectorization of early exit loops with uncountable exits."));
407
409 "enable-early-exit-vectorization-with-side-effects", cl::init(false),
411 cl::desc("Enable vectorization of early exit loops with uncountable exits "
412 "and side effects"));
413
415 "low-trip-count-loop-body-size-limit", cl::init(20), cl::Hidden,
416 cl::desc("Minimum number of instructions to vectorize loops with trip "
417 "counts below tail folding threshold"));
418
419// Returns true if the epilogue VF has been set to a non-zero value other than
420// VF=1 (scalar).
425
426// Likelyhood of bypassing the vectorized loop because there are zero trips left
427// after prolog. See `emitIterationCountCheck`.
428static constexpr uint32_t MinItersBypassWeights[] = {1, 127};
429
430/// A version of ScalarEvolution::getSmallConstantTripCount that returns an
431/// ElementCount to include loops whose trip count is a function of vscale.
433 const Loop *L) {
434 if (unsigned ExpectedTC = SE->getSmallConstantTripCount(L))
435 return ElementCount::getFixed(ExpectedTC);
436
437 const SCEV *BTC = SE->getBackedgeTakenCount(L);
439 return ElementCount::getFixed(0);
440
441 const SCEV *ExitCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
442 if (isa<SCEVVScale>(ExitCount))
444
445 const APInt *Scale;
446 if (match(ExitCount, m_scev_Mul(m_scev_APInt(Scale), m_SCEVVScale())))
447 if (cast<SCEVMulExpr>(ExitCount)->hasNoUnsignedWrap())
448 if (Scale->getActiveBits() <= 32)
450
451 return ElementCount::getFixed(0);
452}
453
454/// Get the maximum trip count for \p L from the SCEV unsigned range, excluding
455/// zero from the range. Only valid when not folding the tail, as the minimum
456/// iteration count check guards against a zero trip count. Returns 0 if
457/// unknown.
459 Loop *L) {
460 const SCEV *BTC = PSE.getBackedgeTakenCount();
462 return 0;
463 ScalarEvolution *SE = PSE.getSE();
464 const SCEV *TripCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
465 ConstantRange TCRange = SE->getUnsignedRange(TripCount);
466 APInt MaxTCFromRange = TCRange.getUnsignedMax();
467 if (!MaxTCFromRange.isZero() && MaxTCFromRange.getActiveBits() <= 32)
468 return MaxTCFromRange.getZExtValue();
469 return 0;
470}
471
472/// Returns "best known" trip count, which is either a valid positive trip count
473/// or std::nullopt when an estimate cannot be made (including when the trip
474/// count would overflow), for the specified loop \p L as defined by the
475/// following procedure:
476/// 1) Returns exact trip count if it is known.
477/// 2) Returns expected trip count according to profile data if any.
478/// 3) Returns upper bound estimate if known, if \p CanUseConstantMax, and
479/// if \p ComputeUpperBoundOnly is false.
480/// 4) Returns the maximum trip count from the SCEV range excluding zero,
481/// if \p CanUseConstantMax and \p CanExcludeZeroTrips.
482/// 5) Returns std::nullopt if all of the above failed.
483static std::optional<ElementCount> getSmallBestKnownTC(
484 PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax = true,
485 bool CanExcludeZeroTrips = false, bool ComputeUpperBoundOnly = false) {
486 // Check if exact trip count is known.
487 if (auto ExpectedTC = getSmallConstantTripCount(PSE.getSE(), L))
488 return ExpectedTC;
489
490 // Check if there is an expected trip count available from profile data.
491 // An estimate of zero means the loop is estimated not to be entered; it is
492 // not a usable trip count for the profitability decisions below (and would
493 // e.g. divide by zero when scaling runtime check cost), so treat it as
494 // unknown.
495 if (LoopVectorizeWithBlockFrequency && !ComputeUpperBoundOnly)
496 if (unsigned EstimatedTC = getLoopEstimatedTripCount(L).value_or(0))
497 return ElementCount::getFixed(EstimatedTC);
498
499 if (!CanUseConstantMax)
500 return std::nullopt;
501
502 // Check if upper bound estimate is known.
503 if (unsigned ExpectedTC = PSE.getSmallConstantMaxTripCount())
504 return ElementCount::getFixed(ExpectedTC);
505
506 // Get the maximum trip count from the SCEV range excluding zero. This is
507 // only safe when not folding the tail, as the minimum iteration count check
508 // prevents entering the vector loop with a zero trip count.
509 if (CanUseConstantMax && CanExcludeZeroTrips)
510 if (unsigned RefinedTC = getMaxTCFromNonZeroRange(PSE, L))
511 return ElementCount::getFixed(RefinedTC);
512
513 return std::nullopt;
514}
515
516namespace {
517// Forward declare GeneratedRTChecks.
518class GeneratedRTChecks;
519
520using SCEV2ValueTy = DenseMap<const SCEV *, Value *>;
521} // namespace
522
523namespace llvm {
524
526
527/// InnerLoopVectorizer vectorizes loops which contain only one basic
528/// block to a specified vectorization factor (VF).
529/// This class performs the widening of scalars into vectors, or multiple
530/// scalars. This class also implements the following features:
531/// * It inserts an epilogue loop for handling loops that don't have iteration
532/// counts that are known to be a multiple of the vectorization factor.
533/// * It handles the code generation for reduction variables.
534/// * Scalarization (implementation using scalars) of un-vectorizable
535/// instructions.
536/// InnerLoopVectorizer does not perform any vectorization-legality
537/// checks, and relies on the caller to check for the different legality
538/// aspects. The InnerLoopVectorizer relies on the
539/// LoopVectorizationLegality class to provide information about the induction
540/// and reduction variables that were found to a given vectorization factor.
542public:
546 ElementCount VecWidth, unsigned UnrollFactor,
547 GeneratedRTChecks &RTChecks, VPlan &Plan)
548 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TTI(TTI), AC(AC),
549 VF(VecWidth), UF(UnrollFactor), Builder(PSE.getSE()->getModule()),
552 Plan.getVectorLoopRegion()->getSinglePredecessor())) {}
553
554 virtual ~InnerLoopVectorizer() = default;
555
556 /// Creates a basic block for the scalar preheader.
557 /// EpilogueVectorizerEpilogueLoop overrides the method to create additional
558 /// blocks and checks needed for epilogue vectorization.
560
561 /// Fix the vectorized code, taking care of header phi's, and more.
563
564protected:
566
567 /// Create and return a new IR basic block for the scalar preheader whose name
568 /// is prefixed with \p Prefix.
570
571 /// The original loop.
573
574 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
575 /// dynamic knowledge to simplify SCEV expressions and converts them to a
576 /// more usable form.
578
579 /// Loop Info.
581
582 /// Dominator Tree.
584
585 /// Target Transform Info.
587
588 /// Assumption Cache.
590
591 /// The vectorization SIMD factor to use. Each vector will have this many
592 /// vector elements.
594
595 /// The vectorization unroll factor to use. Each scalar is vectorized to this
596 /// many different vector instructions.
597 unsigned UF;
598
599 /// The builder that we use
601
602 // --- Vectorization state ---
603
604 /// Structure to hold information about generated runtime checks, responsible
605 /// for cleaning the checks, if vectorization turns out unprofitable.
606 GeneratedRTChecks &RTChecks;
607
609
610 /// The vector preheader block of \p Plan, used as target for check blocks
611 /// introduced during skeleton creation.
613};
614
615/// A specialized derived class of inner loop vectorizer that performs
616/// vectorization of *epilogue* loops in the process of vectorizing loops and
617/// their epilogues. The idea is to run the vplan on a given loop twice, firstly
618/// to vectorize the main loop, and secondly to complete the skeleton from the
619/// first step and vectorize the epilogue. This helps us avoid regenerating and
620/// recomputing runtime safety checks, and shortens the iteration-count-check
621/// path length for loops whose iteration count is so small that the main vector
622/// loop is completely skipped.
624 VPlan &MainPlan;
625
626public:
628
633 unsigned UnrollFactor,
634 GeneratedRTChecks &Checks, VPlan &Plan,
635 VPlan &MainPlan)
636 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TTI, AC, VecWidth,
637 UnrollFactor, Checks, Plan),
638 MainPlan(MainPlan) {}
639 /// Implements the interface for creating a vectorized skeleton using the
640 /// *epilogue loop* strategy (i.e., the second pass of VPlan execution).
642};
643} // end namespace llvm
644
645/// Look for a meaningful debug location on the instruction or its operands.
647 if (!I)
648 return DebugLoc::getUnknown();
649
651 if (I->getDebugLoc() != Empty)
652 return I->getDebugLoc();
653
654 for (Use &Op : I->operands()) {
655 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
656 if (OpInst->getDebugLoc() != Empty)
657 return OpInst->getDebugLoc();
658 }
659
660 return I->getDebugLoc();
661}
662
663namespace llvm {
664
665/// Return the runtime value for VF.
667 return B.CreateElementCount(Ty, VF);
668}
669
670} // end namespace llvm
671
672namespace llvm {
673
674// Loop vectorization cost-model hints how the epilogue/tail loop should be
675// lowered.
677
678 // The default: allowing epilogues.
680
681 // Vectorization with OptForSize: don't allow epilogues.
683
684 // A special case of vectorisation with OptForSize: loops with a very small
685 // trip count are considered for vectorization under OptForSize, thereby
686 // making sure the cost of their loop body is dominant, free of runtime
687 // guards and scalar iteration overheads.
689
690 // Loop hint indicating an epilogue is undesired, apply tail folding.
692
693 // Directive indicating we must either fold the epilogue/tail or not vectorize
695};
696
698
699/// LoopVectorizationCostModel - estimates the expected speedups due to
700/// vectorization.
701/// In many cases vectorization is not profitable. This can happen because of
702/// a number of reasons. In this class we mainly attempt to predict the
703/// expected speedup/slowdowns due to the supported instruction set. We use the
704/// TargetTransformInfo to query the different backends for the cost of
705/// different operations.
708
709public:
716 std::function<BlockFrequencyInfo &()> GetBFI,
717 const Function *F, InterleavedAccessInfo &IAI,
718 VFSelectionContext &Config)
719 : Config(Config), EpilogueLoweringStatus(SEL), TheLoop(L), PSE(PSE),
720 LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), AC(AC), ORE(ORE),
722
723 /// \return An upper bound for the vectorization factors (both fixed and
724 /// scalable). If the factors are 0, vectorization and interleaving should be
725 /// avoided up front.
726 FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
727
728 /// Memory access instruction may be vectorized in more than one way.
729 /// Form of instruction after vectorization depends on cost.
730 /// This function takes cost-based decisions for Load/Store instructions
731 /// and collects them in a map. This decisions map is used for building
732 /// the lists of loop-uniform and loop-scalar instructions.
733 /// The calculated cost is saved with widening decision in order to
734 /// avoid redundant calculations.
735 void setCostBasedWideningDecision(ElementCount VF);
736
737 /// Collect values we want to ignore in the cost model.
738 void collectValuesToIgnore();
739
740 /// \returns True if it is more profitable to scalarize instruction \p I for
741 /// vectorization factor \p VF.
743 assert(VF.isVector() &&
744 "Profitable to scalarize relevant only for VF > 1.");
745 assert(
746 TheLoop->isInnermost() &&
747 "cost-model should not be used for outer loops (in VPlan-native path)");
748
749 auto Scalars = InstsToScalarize.find(VF);
750 assert(Scalars != InstsToScalarize.end() &&
751 "VF not yet analyzed for scalarization profitability");
752 return Scalars->second.contains(I);
753 }
754
755 /// Returns true if \p I is known to be uniform after vectorization.
757 assert(
758 TheLoop->isInnermost() &&
759 "cost-model should not be used for outer loops (in VPlan-native path)");
760
761 // If VF is scalar, then all instructions are trivially uniform.
762 if (VF.isScalar())
763 return true;
764
765 // Pseudo probes must be duplicated per vector lane so that the
766 // profiled loop trip count is not undercounted.
768 return false;
769
770 auto UniformsPerVF = Uniforms.find(VF);
771 assert(UniformsPerVF != Uniforms.end() &&
772 "VF not yet analyzed for uniformity");
773 return UniformsPerVF->second.count(I);
774 }
775
776 /// Returns true if \p I is known to be scalar after vectorization.
778 assert(
779 TheLoop->isInnermost() &&
780 "cost-model should not be used for outer loops (in VPlan-native path)");
781 if (VF.isScalar())
782 return true;
783
784 auto ScalarsPerVF = Scalars.find(VF);
785 assert(ScalarsPerVF != Scalars.end() &&
786 "Scalar values are not calculated for VF");
787 return ScalarsPerVF->second.count(I);
788 }
789
790 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
791 /// for vectorization factor \p VF.
793 const auto &MinBWs = Config.getMinimalBitwidths();
794 // Truncs must truncate at most to their destination type.
795 if (isa_and_nonnull<TruncInst>(I) && MinBWs.contains(I) &&
796 I->getType()->getScalarSizeInBits() < MinBWs.lookup(I))
797 return false;
798 return VF.isVector() && MinBWs.contains(I) &&
801 }
802
803 /// Decision that was taken during cost calculation for memory instruction.
806 CM_Widen, // For consecutive accesses with stride +1.
807 CM_Widen_Reverse, // For consecutive accesses with stride -1.
811 /// A widening decision that has been invalidated after replacing the
812 /// corresponding recipe during VPlan transforms.
813 /// TODO: Remove once the legacy exit cost computation is retired.
815 };
816
817#ifndef NDEBUG
819 constexpr StringLiteral WideningStr[] = {
820 "Unknown", "Widen", "Widen_Reverse", "Interleave",
821 "GatherScatter", "Scalarize", "InvalidatedDecision"};
822 return WideningStr[W];
823 }
824#endif
825
826 /// Save vectorization decision \p W and \p Cost taken by the cost model for
827 /// instruction \p I and vector width \p VF.
830 assert(VF.isVector() && "Expected VF >=2");
831 LLVM_DEBUG(dbgs() << "LV: Setting widening decision to "
832 << getInstWideningStr(W) << " for VF " << VF
833 << " and instruction: " << *I << '\n');
834 WideningDecisions[{I, VF}] = {W, Cost};
835 }
836
837 /// Save vectorization decision \p W and \p Cost taken by the cost model for
838 /// interleaving group \p Grp and vector width \p VF.
842 assert(VF.isVector() && "Expected VF >=2");
843 /// Broadcast this decicion to all instructions inside the group.
844 /// When interleaving, the cost will only be assigned one instruction, the
845 /// insert position. For other cases, add the appropriate fraction of the
846 /// total cost to each instruction. This ensures accurate costs are used,
847 /// even if the insert position instruction is not used.
848 InstructionCost InsertPosCost = Cost;
849 InstructionCost OtherMemberCost = 0;
850 if (W != CM_Interleave)
851 OtherMemberCost = InsertPosCost = Cost / Grp->getNumMembers();
852 ;
853 for (auto *I : Grp->members()) {
854 LLVM_DEBUG(dbgs() << "LV: Setting widening decision to "
855 << getInstWideningStr(W) << " for VF " << VF
856 << " and instruction: " << *I << '\n');
857 if (Grp->getInsertPos() == I)
858 WideningDecisions[{I, VF}] = {W, InsertPosCost};
859 else
860 WideningDecisions[{I, VF}] = {W, OtherMemberCost};
861 }
862 }
863
864 /// Return the cost model decision for the given instruction \p I and vector
865 /// width \p VF. Return CM_Unknown if this instruction did not pass
866 /// through the cost modeling.
868 assert(VF.isVector() && "Expected VF to be a vector VF");
869 assert(
870 TheLoop->isInnermost() &&
871 "cost-model should not be used for outer loops (in VPlan-native path)");
872
873 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
874 auto Itr = WideningDecisions.find(InstOnVF);
875 if (Itr == WideningDecisions.end())
876 return CM_Unknown;
877 return Itr->second.first;
878 }
879
880 /// Return the vectorization cost for the given instruction \p I and vector
881 /// width \p VF.
883 assert(VF.isVector() && "Expected VF >=2");
884 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
885 assert(WideningDecisions.contains(InstOnVF) &&
886 "The cost is not calculated");
887 return WideningDecisions[InstOnVF].second;
888 }
889
890 /// Return True if instruction \p I is an optimizable truncate whose operand
891 /// is an induction variable. Such a truncate will be removed by adding a new
892 /// induction variable with the destination type.
894 // If the instruction is not a truncate, return false.
895 auto *Trunc = dyn_cast<TruncInst>(I);
896 if (!Trunc)
897 return false;
898
899 // Get the source and destination types of the truncate.
900 Type *SrcTy = toVectorTy(Trunc->getSrcTy(), VF);
901 Type *DestTy = toVectorTy(Trunc->getDestTy(), VF);
902
903 // If the truncate is free for the given types, return false. Replacing a
904 // free truncate with an induction variable would add an induction variable
905 // update instruction to each iteration of the loop. We exclude from this
906 // check the primary induction variable since it will need an update
907 // instruction regardless.
908 Value *Op = Trunc->getOperand(0);
909 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
910 return false;
911
912 // If the truncated value is not an induction variable, return false.
913 return Legal->isInductionPhi(Op);
914 }
915
916 /// Collects the instructions to scalarize for each predicated instruction in
917 /// the loop.
918 void collectInstsToScalarize(ElementCount VF);
919
920 /// Collect values that will not be widened, including Uniforms, Scalars, and
921 /// Instructions to Scalarize for the given \p VF.
922 /// The sets depend on CM decision for Load/Store instructions
923 /// that may be vectorized as interleave, gather-scatter or scalarized.
924 /// Also make a decision on what to do about call instructions in the loop
925 /// at that VF -- scalarize, call a known vector routine, or call a
926 /// vector intrinsic.
928 // Do the analysis once.
929 if (VF.isScalar() || Uniforms.contains(VF))
930 return;
932 collectLoopUniforms(VF);
933 collectLoopScalars(VF);
935 }
936
937 /// Given costs for both strategies, return true if the scalar predication
938 /// lowering should be used for div/rem. This incorporates an override
939 /// option so it is not simply a cost comparison.
941 InstructionCost MaskedCost) const {
942 switch (ForceMaskedDivRem) {
944 return ScalarCost < MaskedCost;
946 return false;
948 return true;
949 }
950 llvm_unreachable("impossible case value");
951 }
952
953 /// Returns true if \p I is an instruction which requires predication and
954 /// for which our chosen predication strategy is scalarization (i.e. we
955 /// don't have an alternate strategy such as masking available).
956 /// \p VF is the vectorization factor that will be used to vectorize \p I.
957 bool isScalarWithPredication(Instruction *I, ElementCount VF);
958
959 /// Wrapper function for LoopVectorizationLegality::isMaskRequired,
960 /// that passes the Instruction \p I and if we fold tail.
961 bool isMaskRequired(Instruction *I) const;
962
963 /// Returns true if \p I is an instruction that needs to be predicated
964 /// at runtime. The result is independent of the predication mechanism.
965 /// Superset of instructions that return true for isScalarWithPredication.
966 bool isPredicatedInst(Instruction *I) const;
967
968 /// A helper function that returns how much we should divide the cost of a
969 /// predicated block by. Typically this is the reciprocal of the block
970 /// probability, i.e. if we return X we are assuming the predicated block will
971 /// execute once for every X iterations of the loop header so the block should
972 /// only contribute 1/X of its cost to the total cost calculation, but when
973 /// optimizing for code size it will just be 1 as code size costs don't depend
974 /// on execution probabilities.
975 ///
976 /// Note that if a block wasn't originally predicated but was predicated due
977 /// to tail folding, the divisor will still be 1 because it will execute for
978 /// every iteration of the loop header.
979 inline uint64_t
980 getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind,
981 const BasicBlock *BB);
982
983 /// Returns true if an artificially high cost for emulated masked memrefs
984 /// should be used.
985 bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF) const;
986
987 /// Return the costs for our two available strategies for lowering a
988 /// div/rem operation which requires speculating at least one lane.
989 /// First result is for scalarization (will be invalid for scalable
990 /// vectors); second is for the masked intrinsic strategy.
991 std::pair<InstructionCost, InstructionCost>
992 getDivRemSpeculationCost(Instruction *I, ElementCount VF);
993
994 /// If \p I is a memory instruction with a consecutive pointer that can be
995 /// widened, returns the widening kind (CM_Widen or CM_Widen_Reverse) and
996 /// std::nullopt otherwise.
997 std::optional<InstWidening> memoryInstructionCanBeWidened(Instruction *I,
998 ElementCount VF);
999
1000 /// Returns true if \p I is a memory instruction in an interleaved-group
1001 /// of memory accesses that can be vectorized with wide vector loads/stores
1002 /// and shuffles.
1003 bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const;
1004
1005 /// Returns true if the target machine supports masked loads or stores
1006 /// for \p I's data type and alignment. The caller must ensure the access is
1007 /// consecutive or part of an interleave group.
1008 bool isLegalMaskedLoadOrStore(Instruction *I, ElementCount VF) const;
1009
1010 /// Returns true if the target machine supports gather or scatter for \p I's
1011 /// data type and alignment.
1012 bool isLegalGatherOrScatter(Instruction *I, ElementCount VF) const;
1013
1014 /// Check if \p Instr belongs to any interleaved access group.
1016 return InterleaveInfo.isInterleaved(Instr);
1017 }
1018
1019 /// Get the interleaved access group that \p Instr belongs to.
1022 return InterleaveInfo.getInterleaveGroup(Instr);
1023 }
1024
1025 /// Returns true if we're required to use a scalar epilogue for at least
1026 /// the final iteration of the original loop.
1027 bool requiresScalarEpilogue(bool IsVectorizing) const {
1028 if (!isEpilogueAllowed()) {
1029 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1030 return false;
1031 }
1032 // If we might exit from anywhere but the latch and early exit vectorization
1033 // is disabled, we must run the exiting iteration in scalar form.
1034 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
1035 !(EnableEarlyExitVectorization && Legal->hasUncountableEarlyExit())) {
1036 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: not exiting "
1037 "from latch block\n");
1038 return true;
1039 }
1040 if (IsVectorizing && InterleaveInfo.requiresScalarEpilogue()) {
1041 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: "
1042 "interleaved group requires scalar epilogue\n");
1043 return true;
1044 }
1045 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1046 return false;
1047 }
1048
1049 /// Returns true if an epilogue is allowed (e.g., not prevented by
1050 /// optsize or a loop hint annotation).
1051 bool isEpilogueAllowed() const {
1052 return EpilogueLoweringStatus == CM_EpilogueAllowed;
1053 }
1054
1055 /// Returns the TailFoldingStyle that is best for the current loop.
1057 return ChosenTailFoldingStyle;
1058 }
1059
1060 /// Selects and saves TailFoldingStyle.
1061 /// \param IsScalableVF true if scalable vector factors enabled.
1062 /// \param UserIC User specific interleave count.
1063 void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC) {
1064 assert(ChosenTailFoldingStyle == TailFoldingStyle::None &&
1065 "Tail folding must not be selected yet.");
1066 if (!Legal->canFoldTailByMasking()) {
1067 ChosenTailFoldingStyle = TailFoldingStyle::None;
1068 return;
1069 }
1070
1071 // Default to TTI preference, but allow command line override.
1072 ChosenTailFoldingStyle = TTI.getPreferredTailFoldingStyle();
1073 if (ForceTailFoldingStyle.getNumOccurrences())
1074 ChosenTailFoldingStyle = ForceTailFoldingStyle.getValue();
1075
1076 if (ChosenTailFoldingStyle != TailFoldingStyle::DataWithEVL)
1077 return;
1078 // Override EVL styles if needed.
1079 // FIXME: Investigate opportunity for fixed vector factor.
1080 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
1081 TTI.hasActiveVectorLength() && !EnableVPlanNativePath;
1082 if (EVLIsLegal)
1083 return;
1084 // If for some reason EVL mode is unsupported, fallback to an epilogue
1085 // if it's allowed, or DataWithoutLaneMask otherwise.
1086 if (EpilogueLoweringStatus == CM_EpilogueAllowed ||
1087 EpilogueLoweringStatus == CM_EpilogueNotNeededFoldTail)
1088 ChosenTailFoldingStyle = TailFoldingStyle::None;
1089 else
1090 ChosenTailFoldingStyle = TailFoldingStyle::DataWithoutLaneMask;
1091
1092 LLVM_DEBUG(
1093 dbgs() << "LV: Preference for VP intrinsics indicated. Will "
1094 "not try to generate VP Intrinsics "
1095 << (UserIC > 1
1096 ? "since interleave count specified is greater than 1.\n"
1097 : "due to non-interleaving reasons.\n"));
1098 }
1099
1100 /// Returns true if all loop blocks should be masked to fold tail loop.
1101 bool foldTailByMasking() const {
1103 }
1104
1106 assert(foldTailByMasking() && "Expected tail folding to be enabled!");
1108 "Did not expect to enable alias masking with EVL!");
1109 assert(PartialAliasMaskingStatus == AliasMaskingStatus::NotDecided);
1110
1111 // Assume we fail to enable alias masking (in case we early exit).
1112 PartialAliasMaskingStatus = AliasMaskingStatus::Disabled;
1113
1114 // Note: FixedOrderRecurrences are not supported yet as we cannot handle
1115 // the required `splice.right` with the alias-mask.
1117 !Legal->getFixedOrderRecurrences().empty())
1118 return;
1119
1120 const RuntimePointerChecking *Checks = Legal->getRuntimePointerChecking();
1121 if (!Checks)
1122 return;
1123
1124 auto DiffChecks = Checks->getDiffChecks();
1125 if (!DiffChecks || DiffChecks->empty())
1126 return;
1127
1128 [[maybe_unused]] auto HasPointerArgs = [](CallBase *CB) {
1129 return any_of(CB->args(), [](Value const *Arg) {
1130 return Arg->getType()->isPointerTy();
1131 });
1132 };
1133
1134 for (BasicBlock *BB : TheLoop->blocks()) {
1135 for (Instruction &I : *BB) {
1137 [[maybe_unused]] auto *Call = dyn_cast<CallInst>(&I);
1138 assert(
1139 (!I.mayReadOrWriteMemory() || (Call && !HasPointerArgs(Call))) &&
1140 "Skipped unexpected memory access");
1141 continue;
1142 }
1143
1144 Type *ScalarTy = getLoadStoreType(&I);
1146
1147 // Currently, we can't handle alias masking in reverse. Reversing the
1148 // alias mask is not correct (or necessary). When combined with
1149 // tail-folding the active lane mask should only be reversed where the
1150 // alias-mask is true.
1151 if (Legal->isConsecutivePtr(ScalarTy, Ptr) == -1)
1152 return;
1153 }
1154 }
1155
1156 PartialAliasMaskingStatus = AliasMaskingStatus::Enabled;
1157 }
1158
1159 /// Returns true if all loop blocks should have partial aliases masked.
1160 bool maskPartialAliasing() const {
1161 return PartialAliasMaskingStatus == AliasMaskingStatus::Enabled;
1162 }
1163
1164 /// Returns true if the instructions in this block requires predication
1165 /// for any reason, e.g. because tail folding now requires a predicate
1166 /// or because the block in the original loop was predicated.
1168 return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1169 }
1170
1171 /// Returns true if VP intrinsics with explicit vector length support should
1172 /// be generated in the tail folded loop.
1176
1177 /// Returns true if the predicated reduction select should be used to set the
1178 /// incoming value for the reduction phi.
1179 bool usePredicatedReductionSelect(RecurKind RecurrenceKind) const {
1180 // Force to use predicated reduction select since the EVL of the
1181 // second-to-last iteration might not be VF*UF.
1182 if (foldTailWithEVL())
1183 return true;
1184
1185 // Force a predicated select with alias-masking to avoid propagating poison
1186 // values to the header phi for lanes outside the alias-mask.
1187 if (maskPartialAliasing())
1188 return true;
1189
1190 // Note: For FindLast recurrences we prefer a predicated select to simplify
1191 // matching in handleFindLastReductions(), rather than handle multiple
1192 // cases.
1194 return true;
1195
1197 TTI.preferPredicatedReductionSelect();
1198 }
1199
1200 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1201 /// with factor VF. Return the cost of the instruction, including
1202 /// scalarization overhead if it's needed.
1203 InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1204
1205 /// Estimate cost of a call instruction CI if it were vectorized with factor
1206 /// VF. Return the cost of the instruction, including scalarization overhead
1207 /// if it's needed.
1208 InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const;
1209
1210 /// Invalidates decisions already taken by the cost model.
1212 WideningDecisions.clear();
1213 Uniforms.clear();
1214 Scalars.clear();
1215 }
1216
1217 /// Returns the expected execution cost. The unit of the cost does
1218 /// not matter because we use the 'cost' units to compare different
1219 /// vector widths. The cost that is returned is *not* normalized by
1220 /// the factor width.
1221 InstructionCost expectedCost(ElementCount VF);
1222
1223 /// Returns the execution time cost of an instruction for a given vector
1224 /// width. Vector width of one means scalar.
1225 InstructionCost getInstructionCost(Instruction *I, ElementCount VF);
1226
1227 /// Returns true if \p Op should be considered invariant and if it is
1228 /// trivially hoistable.
1229 bool shouldConsiderInvariant(Value *Op);
1230
1231 /// Returns true if \p I has been forced to be scalarized at \p VF.
1233 auto FS = ForcedScalars.find(VF);
1234 return FS != ForcedScalars.end() && FS->second.contains(I);
1235 }
1236
1237private:
1238 unsigned NumPredStores = 0;
1239
1240 /// VF selection state independent of cost-modeling decisions.
1241 VFSelectionContext &Config;
1242
1243 /// Wrapper around LoopVectorizationLegality::isUniform() that takes into
1244 /// account if alias-masking is enabled. We consider the VF to be unknown when
1245 /// alias masking.
1246 bool isUniform(Value *V, ElementCount VF) const {
1247 // With alias-masking our runtime VF is [2, VF] (and not necessarily a
1248 // power-of-two). Something that is uniform for VF may not be for the full
1249 // range.
1250 assert(PartialAliasMaskingStatus != AliasMaskingStatus::NotDecided &&
1251 "alias-mask status must be decided already");
1252 return Legal->isUniform(V, PartialAliasMaskingStatus ==
1254 ? std::optional(VF)
1255 : std::nullopt);
1256 }
1257
1258 /// Wrapper around LoopVectorizationLegality::isUniformMemOp() that takes into
1259 /// account if alias-masking is enabled. We consider the VF to be unknown when
1260 /// alias masking.
1261 bool isUniformMemOp(Instruction &I, ElementCount VF) const {
1262 assert(PartialAliasMaskingStatus != AliasMaskingStatus::NotDecided &&
1263 "alias-mask status must be decided already");
1264 return Legal->isUniformMemOp(I, PartialAliasMaskingStatus ==
1266 ? std::optional(VF)
1267 : std::nullopt);
1268 }
1269
1270 /// Calculate vectorization cost of memory instruction \p I.
1271 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1272
1273 /// The cost computation for scalarized memory instruction.
1274 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1275
1276 /// The cost computation for interleaving group of memory instructions.
1277 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF) const;
1278
1279 /// The cost computation for Gather/Scatter instruction.
1280 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF) const;
1281
1282 /// The cost computation for widening instruction \p I with consecutive
1283 /// memory access.
1284 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF,
1285 InstWidening Kind);
1286
1287 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1288 /// Load: scalar load + broadcast.
1289 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1290 /// element)
1291 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF) const;
1292
1293 /// Estimate the overhead of scalarizing an instruction. This is a
1294 /// convenience wrapper for the type-based getScalarizationOverhead API.
1296 ElementCount VF) const;
1297
1298 /// A type representing the costs for instructions if they were to be
1299 /// scalarized rather than vectorized. The entries are Instruction-Cost
1300 /// pairs.
1301 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
1302
1303 /// A set containing all BasicBlocks that are known to present after
1304 /// vectorization as a predicated block.
1305 DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1306 PredicatedBBsAfterVectorization;
1307
1308 /// Records whether it is allowed to have the original scalar loop execute at
1309 /// least once. This may be needed as a fallback loop in case runtime
1310 /// aliasing/dependence checks fail, or to handle the tail/remainder
1311 /// iterations when the trip count is unknown or doesn't divide by the VF,
1312 /// or as a peel-loop to handle gaps in interleave-groups.
1313 /// Under optsize and when the trip count is very small we don't allow any
1314 /// iterations to execute in the scalar loop.
1315 EpilogueLowering EpilogueLoweringStatus = CM_EpilogueAllowed;
1316
1317 /// Control finally chosen tail folding style.
1318 TailFoldingStyle ChosenTailFoldingStyle = TailFoldingStyle::None;
1319
1320 /// If partial alias masking is enabled/disabled or not decided.
1321 AliasMaskingStatus PartialAliasMaskingStatus = AliasMaskingStatus::NotDecided;
1322
1323 /// A map holding scalar costs for different vectorization factors. The
1324 /// presence of a cost for an instruction in the mapping indicates that the
1325 /// instruction will be scalarized when vectorizing with the associated
1326 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1327 MapVector<ElementCount, ScalarCostsTy> InstsToScalarize;
1328
1329 /// Holds the instructions known to be uniform after vectorization.
1330 /// The data is collected per VF.
1331 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1332
1333 /// Holds the instructions known to be scalar after vectorization.
1334 /// The data is collected per VF.
1335 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1336
1337 /// Holds the instructions (address computations) that are forced to be
1338 /// scalarized.
1339 DenseMap<ElementCount, SmallSetVector<Instruction *, 4>> ForcedScalars;
1340
1341 /// Returns the expected difference in cost from scalarizing the expression
1342 /// feeding a predicated instruction \p PredInst. The instructions to
1343 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1344 /// non-negative return value implies the expression will be scalarized.
1345 /// Currently, only single-use chains are considered for scalarization.
1346 InstructionCost computePredInstDiscount(Instruction *PredInst,
1347 ScalarCostsTy &ScalarCosts,
1348 ElementCount VF);
1349
1350 /// Collect the instructions that are uniform after vectorization. An
1351 /// instruction is uniform if we represent it with a single scalar value in
1352 /// the vectorized loop corresponding to each vector iteration. Examples of
1353 /// uniform instructions include pointer operands of consecutive or
1354 /// interleaved memory accesses. Note that although uniformity implies an
1355 /// instruction will be scalar, the reverse is not true. In general, a
1356 /// scalarized instruction will be represented by VF scalar values in the
1357 /// vectorized loop, each corresponding to an iteration of the original
1358 /// scalar loop.
1359 void collectLoopUniforms(ElementCount VF);
1360
1361 /// Collect the instructions that are scalar after vectorization. An
1362 /// instruction is scalar if it is known to be uniform or will be scalarized
1363 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1364 /// to the list if they are used by a load/store instruction that is marked as
1365 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1366 /// VF values in the vectorized loop, each corresponding to an iteration of
1367 /// the original scalar loop.
1368 void collectLoopScalars(ElementCount VF);
1369
1370 /// Keeps cost model vectorization decision and cost for instructions.
1371 /// Right now it is used for memory instructions only.
1372 using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1373 std::pair<InstWidening, InstructionCost>>;
1374
1375 DecisionList WideningDecisions;
1376
1377 /// Returns true if \p V is expected to be vectorized and it needs to be
1378 /// extracted.
1379 bool needsExtract(Value *V, ElementCount VF) const {
1381 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1382 TheLoop->isLoopInvariant(I) ||
1383 getWideningDecision(I, VF) == CM_Scalarize)
1384 return false;
1385
1386 // Assume we can vectorize V (and hence we need extraction) if the
1387 // scalars are not computed yet. This can happen, because it is called
1388 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1389 // the scalars are collected. That should be a safe assumption in most
1390 // cases, because we check if the operands have vectorizable types
1391 // beforehand in LoopVectorizationLegality.
1392 return !Scalars.contains(VF) || !isScalarAfterVectorization(I, VF);
1393 };
1394
1395 /// Returns a range containing only operands needing to be extracted.
1396 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1397 ElementCount VF) const {
1398
1399 SmallPtrSet<const Value *, 4> UniqueOperands;
1400 SmallVector<Value *, 4> Res;
1401 for (Value *Op : Ops) {
1402 if (isa<Constant>(Op) || !UniqueOperands.insert(Op).second ||
1403 !needsExtract(Op, VF))
1404 continue;
1405 Res.push_back(Op);
1406 }
1407 return Res;
1408 }
1409
1410public:
1411 /// The loop that we evaluate.
1413
1414 /// Predicated scalar evolution analysis.
1416
1417 /// Loop Info analysis.
1419
1420 /// Vectorization legality.
1422
1423 /// Vector target information.
1425
1426 /// Target Library Info.
1428
1429 /// Assumption cache.
1431
1432 /// Interface to emit optimization remarks.
1434
1435 /// A function to lazily fetch BlockFrequencyInfo. This avoids computing it
1436 /// unless necessary, e.g. when the loop isn't legal to vectorize or when
1437 /// there is no predication.
1438 std::function<BlockFrequencyInfo &()> GetBFI;
1439 /// The BlockFrequencyInfo returned from GetBFI.
1441 /// Returns the BlockFrequencyInfo for the function if cached, otherwise
1442 /// fetches it via GetBFI. Avoids an indirect call to the std::function.
1444 if (!BFI)
1445 BFI = &GetBFI();
1446 return *BFI;
1447 }
1448
1450
1451 /// The interleave access information contains groups of interleaved accesses
1452 /// with the same stride and close to each other.
1454
1455 /// Values to ignore in the cost model.
1457
1458 /// Values to ignore in the cost model when VF > 1.
1460};
1461} // end namespace llvm
1462
1463namespace {
1464/// Helper struct to manage generating runtime checks for vectorization.
1465///
1466/// The runtime checks are created up-front in temporary blocks to allow better
1467/// estimating the cost and un-linked from the existing IR. After deciding to
1468/// vectorize, the checks are attached to VPlan as IR or recipes. If deciding
1469/// not to vectorize, the temporary blocks are completely removed.
1470class GeneratedRTChecks {
1471 /// Basic block which contains the generated SCEV checks, if any.
1472 BasicBlock *SCEVCheckBlock = nullptr;
1473
1474 /// The value representing the result of the generated SCEV checks. If it is
1475 /// nullptr no SCEV checks have been generated.
1476 Value *SCEVCheckCond = nullptr;
1477
1478 /// Basic block which contains the generated memory runtime checks, if any.
1479 BasicBlock *MemCheckBlock = nullptr;
1480
1481 /// The value representing the result of the generated memory runtime checks.
1482 /// If it is nullptr no memory runtime checks have been generated.
1483 Value *MemRuntimeCheckCond = nullptr;
1484
1485 /// Whether checks were generated, retained after their IR is replaced or
1486 /// removed during VPlan execution.
1487 bool HasChecks = false;
1488
1489 DominatorTree *DT;
1490 LoopInfo *LI;
1492
1493 SCEVExpander SCEVExp;
1494 SCEVExpander MemCheckExp;
1495
1496 bool CostTooHigh = false;
1497
1498 Loop *OuterLoop = nullptr;
1499
1501
1502 /// The kind of cost that we are calculating
1504
1505 /// True if the loop is alias-masked (which allows us to omit diff checks).
1506 bool LoopUsesPartialAliasMasking = false;
1507
1508public:
1509 GeneratedRTChecks(PredicatedScalarEvolution &PSE, DominatorTree *DT,
1512 bool LoopUsesPartialAliasMasking)
1513 : DT(DT), LI(LI), TTI(TTI),
1514 SCEVExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1515 MemCheckExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1516 PSE(PSE), CostKind(CostKind),
1517 LoopUsesPartialAliasMasking(LoopUsesPartialAliasMasking) {}
1518
1519 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1520 /// accurately estimate the cost of the runtime checks. The blocks are
1521 /// un-linked from the IR and attached to VPlan as IR or recipes if
1522 /// profitable. Otherwise, the check blocks are removed completely.
1523 void create(Loop *L, const LoopAccessInfo &LAI,
1524 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC,
1525 OptimizationRemarkEmitter &ORE) {
1526
1527 // Hard cutoff to limit compile-time increase in case a very large number of
1528 // runtime checks needs to be generated.
1529 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1530 // profile info.
1531 CostTooHigh = LAI.getNumRuntimePointerChecks() >
1533 if (CostTooHigh) {
1534 // Mark runtime checks as never succeeding when they exceed the threshold.
1535 MemRuntimeCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1536 SCEVCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1537 ORE.emit([&]() {
1538 return OptimizationRemarkAnalysisAliasing(
1539 DEBUG_TYPE, "TooManyMemoryRuntimeChecks", L->getStartLoc(),
1540 L->getHeader())
1541 << "loop not vectorized: too many memory checks needed";
1542 });
1543 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1544 return;
1545 }
1546
1547 BasicBlock *LoopHeader = L->getHeader();
1548 BasicBlock *Preheader = L->getLoopPreheader();
1549
1550 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1551 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1552 // may be used by SCEVExpander. The blocks will be un-linked from their
1553 // predecessors and removed from LI & DT at the end of the function.
1554 if (!UnionPred.isAlwaysTrue()) {
1555 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1556 nullptr, "vector.scevcheck");
1557
1558 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1559 &UnionPred, SCEVCheckBlock->getTerminator());
1560 if (isa<Constant>(SCEVCheckCond)) {
1561 // Clean up directly after expanding the predicate to a constant, to
1562 // avoid further expansions re-using anything left over from SCEVExp.
1563 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1564 SCEVCleaner.cleanup();
1565 }
1566 }
1567
1568 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1569 // TODO: We need to estimate the cost of alias-masking in
1570 // GeneratedRTChecks::getCost(). We can't check the MemCheckBlock as the
1571 // alias-mask is generated later in VPlan.
1572 if (RtPtrChecking.Need && !LoopUsesPartialAliasMasking) {
1573 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1574 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1575 "vector.memcheck");
1576
1577 auto DiffChecks = RtPtrChecking.getDiffChecks();
1578 if (DiffChecks) {
1579 MemRuntimeCheckCond = addDiffRuntimeChecks(
1580 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp, VF, IC);
1581 } else {
1582 MemRuntimeCheckCond = addRuntimeChecks(
1583 MemCheckBlock->getTerminator(), L, RtPtrChecking.getChecks(),
1585 }
1586 assert(MemRuntimeCheckCond &&
1587 "no RT checks generated although RtPtrChecking "
1588 "claimed checks are required");
1589 }
1590
1591 SCEVExp.eraseDeadInstructions(SCEVCheckCond);
1592 HasChecks = getSCEVChecks().first || getMemRuntimeChecks().first;
1593
1594 if (!MemCheckBlock && !SCEVCheckBlock)
1595 return;
1596
1597 // Unhook the temporary block with the checks, update various places
1598 // accordingly.
1599 if (SCEVCheckBlock)
1600 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1601 if (MemCheckBlock)
1602 MemCheckBlock->replaceAllUsesWith(Preheader);
1603
1604 if (SCEVCheckBlock) {
1605 SCEVCheckBlock->getTerminator()->moveBefore(
1606 Preheader->getTerminator()->getIterator());
1607 auto *UI = new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1608 UI->setDebugLoc(DebugLoc::getTemporary());
1609 Preheader->getTerminator()->eraseFromParent();
1610 }
1611 if (MemCheckBlock) {
1612 MemCheckBlock->getTerminator()->moveBefore(
1613 Preheader->getTerminator()->getIterator());
1614 auto *UI = new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1615 UI->setDebugLoc(DebugLoc::getTemporary());
1616 Preheader->getTerminator()->eraseFromParent();
1617 }
1618
1619 DT->changeImmediateDominator(LoopHeader, Preheader);
1620 if (MemCheckBlock) {
1621 DT->eraseNode(MemCheckBlock);
1622 LI->removeBlock(MemCheckBlock);
1623 }
1624 if (SCEVCheckBlock) {
1625 DT->eraseNode(SCEVCheckBlock);
1626 LI->removeBlock(SCEVCheckBlock);
1627 }
1628
1629 // Outer loop is used as part of the later cost calculations.
1630 OuterLoop = L->getParentLoop();
1631 }
1632
1634 if (SCEVCheckBlock || MemCheckBlock)
1635 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1636
1637 if (CostTooHigh) {
1639 Cost.setInvalid();
1640 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1641 return Cost;
1642 }
1643
1644 InstructionCost RTCheckCost = 0;
1645 if (SCEVCheckBlock)
1646 for (Instruction &I : *SCEVCheckBlock) {
1647 if (SCEVCheckBlock->getTerminator() == &I)
1648 continue;
1650 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1651 RTCheckCost += C;
1652 }
1653 if (MemCheckBlock) {
1654 InstructionCost MemCheckCost = 0;
1655 for (Instruction &I : *MemCheckBlock) {
1656 if (MemCheckBlock->getTerminator() == &I)
1657 continue;
1659 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1660 MemCheckCost += C;
1661 }
1662
1663 // If the runtime memory checks are being created inside an outer loop
1664 // we should find out if these checks are outer loop invariant. If so,
1665 // the checks will likely be hoisted out and so the effective cost will
1666 // reduce according to the outer loop trip count.
1667 if (OuterLoop) {
1668 ScalarEvolution *SE = MemCheckExp.getSE();
1669 // TODO: If profitable, we could refine this further by analysing every
1670 // individual memory check, since there could be a mixture of loop
1671 // variant and invariant checks that mean the final condition is
1672 // variant.
1673 const SCEV *Cond = SE->getSCEV(MemRuntimeCheckCond);
1674 if (SE->isLoopInvariant(Cond, OuterLoop)) {
1675 // It seems reasonable to assume that we can reduce the effective
1676 // cost of the checks even when we know nothing about the trip
1677 // count. Assume that the outer loop executes at least twice.
1678 unsigned BestTripCount = 2;
1679
1680 // Get the best known TC estimate.
1681 if (auto EstimatedTC = getSmallBestKnownTC(
1682 PSE, OuterLoop, /* CanUseConstantMax = */ false))
1683 if (EstimatedTC->isFixed())
1684 BestTripCount = EstimatedTC->getFixedValue();
1685
1686 InstructionCost NewMemCheckCost = MemCheckCost / BestTripCount;
1687
1688 // Let's ensure the cost is always at least 1.
1689 NewMemCheckCost = std::max(NewMemCheckCost.getValue(),
1690 (InstructionCost::CostType)1);
1691
1692 if (BestTripCount > 1)
1694 << "We expect runtime memory checks to be hoisted "
1695 << "out of the outer loop. Cost reduced from "
1696 << MemCheckCost << " to " << NewMemCheckCost << '\n');
1697
1698 MemCheckCost = NewMemCheckCost;
1699 }
1700 }
1701
1702 RTCheckCost += MemCheckCost;
1703 }
1704
1705 if (SCEVCheckBlock || MemCheckBlock)
1706 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
1707 << "\n");
1708
1709 return RTCheckCost;
1710 }
1711
1712 /// Remove the created SCEV & memory runtime check blocks & instructions, if
1713 /// unused.
1714 ~GeneratedRTChecks() {
1715 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1716 bool SCEVChecksUsed = !SCEVCheckBlock || !pred_empty(SCEVCheckBlock);
1717 if (SCEVChecksUsed)
1718 SCEVCleaner.markResultUsed();
1719
1720 if (MemCheckBlock && pred_empty(MemCheckBlock))
1721 eraseMemCheckBlock();
1722
1723 SCEVCleaner.cleanup();
1724
1725 if (!SCEVChecksUsed)
1726 SCEVCheckBlock->eraseFromParent();
1727 }
1728
1729 /// Retrieves the SCEVCheckCond and SCEVCheckBlock that were generated as IR
1730 /// outside VPlan.
1731 std::pair<Value *, BasicBlock *> getSCEVChecks() const {
1732 using namespace llvm::PatternMatch;
1733 if (!SCEVCheckCond || match(SCEVCheckCond, m_ZeroInt()))
1734 return {nullptr, nullptr};
1735
1736 return {SCEVCheckCond, SCEVCheckBlock};
1737 }
1738
1739 /// Retrieves the MemCheckCond and MemCheckBlock that were generated as IR
1740 /// outside VPlan.
1741 std::pair<Value *, BasicBlock *> getMemRuntimeChecks() const {
1742 using namespace llvm::PatternMatch;
1743 if (MemRuntimeCheckCond && match(MemRuntimeCheckCond, m_ZeroInt()))
1744 return {nullptr, nullptr};
1745 return {MemRuntimeCheckCond, MemCheckBlock};
1746 }
1747
1748 /// Return true if any runtime checks have been added
1749 bool hasChecks() const { return HasChecks; }
1750
1751 /// Erase the memory check block, its instructions and their SCEV expansions.
1752 void eraseMemCheckBlock() {
1753 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
1754 auto &SE = *MemCheckExp.getSE();
1755 // Memory runtime check generation creates compares that use expanded
1756 // values. Remove them before running the SCEVExpanderCleaner.
1757 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
1758 if (MemCheckExp.isInsertedInstruction(&I))
1759 continue;
1760 SE.forgetValue(&I);
1761 I.eraseFromParent();
1762 }
1763 MemCheckCleaner.cleanup();
1764 MemCheckBlock->eraseFromParent();
1765 MemCheckBlock = nullptr;
1766 MemRuntimeCheckCond = nullptr;
1767 }
1768};
1769} // namespace
1770
1772 return Style == TailFoldingStyle::Data ||
1774}
1775
1779
1780// Return true if \p OuterLp is an outer loop annotated with hints for explicit
1781// vectorization. The loop needs to be annotated with #pragma omp simd
1782// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
1783// vector length information is not provided, vectorization is not considered
1784// explicit. Interleave hints are not allowed either. These limitations will be
1785// relaxed in the future.
1786// Please, note that we are currently forced to abuse the pragma 'clang
1787// vectorize' semantics. This pragma provides *auto-vectorization hints*
1788// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
1789// provides *explicit vectorization hints* (LV can bypass legal checks and
1790// assume that vectorization is legal). However, both hints are implemented
1791// using the same metadata (llvm.loop.vectorize, processed by
1792// LoopVectorizeHints). This will be fixed in the future when the native IR
1793// representation for pragma 'omp simd' is introduced.
1794static bool isExplicitVecOuterLoop(Loop *OuterLp,
1796 assert(!OuterLp->isInnermost() && "This is not an outer loop");
1797 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
1798
1799 // Only outer loops with an explicit vectorization hint are supported.
1800 // Unannotated outer loops are ignored.
1802 return false;
1803
1804 Function *Fn = OuterLp->getHeader()->getParent();
1805 if (!Hints.allowVectorization(Fn, OuterLp,
1806 true /*VectorizeOnlyWhenForced*/)) {
1807 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
1808 return false;
1809 }
1810
1811 if (Hints.getInterleave() > 1) {
1812 // TODO: Interleave support is future work.
1813 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
1814 "outer loops.\n");
1815 Hints.emitRemarkWithHints();
1816 return false;
1817 }
1818
1819 return true;
1820}
1821
1825 // Collect inner loops and outer loops without irreducible control flow. For
1826 // now, only collect outer loops that have explicit vectorization hints. If we
1827 // are stress testing the VPlan H-CFG construction, we collect the outermost
1828 // loop of every loop nest.
1829 if (L.isInnermost() || VPlanBuildOuterloopStressTest ||
1831 LoopBlocksRPO RPOT(&L);
1832 RPOT.perform(LI);
1834 V.push_back(&L);
1835 // TODO: Collect inner loops inside marked outer loops in case
1836 // vectorization fails for the outer loop. Do not invoke
1837 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
1838 // already known to be reducible. We can use an inherited attribute for
1839 // that.
1840 return;
1841 }
1842 }
1843 for (Loop *InnerL : L)
1844 collectSupportedLoops(*InnerL, LI, ORE, V);
1845}
1846
1847//===----------------------------------------------------------------------===//
1848// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1849// LoopVectorizationCostModel and LoopVectorizationPlanner.
1850//===----------------------------------------------------------------------===//
1851
1852/// For the given VF and UF and maximum trip count computed for the loop, return
1853/// whether the induction variable might overflow in the vectorized loop. If not,
1854/// then we know a runtime overflow check always evaluates to false and can be
1855/// removed.
1857 const LoopVectorizationCostModel *Cost,
1858 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
1859 // Always be conservative if we don't know the exact unroll factor.
1860 uint64_t MaxUF = UF ? *UF
1861 : std::max(Cost->TTI.getMaxInterleaveFactor(VF, false),
1862 Cost->TTI.getMaxInterleaveFactor(VF, true));
1863
1864 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
1865 APInt MaxUIntTripCount = IdxTy->getMask();
1866
1867 // We know the runtime overflow check is known false iff the (max) trip-count
1868 // is known and (max) trip-count + (VF * UF) does not overflow in the type of
1869 // the vector loop induction variable.
1870 if (std::optional<ElementCount> TC = getSmallBestKnownTC(
1871 Cost->PSE, Cost->TheLoop,
1872 /*CanUseConstantMax=*/true, /*CanExcludeZeroTrips=*/false,
1873 /*ComputeUpperBoundOnly=*/true)) {
1874 // Compute the maximum runtime values of VF and the trip count.
1875 std::optional<uint64_t> MaxStep =
1876 getMaxRuntimeElementCount(VF * MaxUF, *Cost->TheFunction);
1877 std::optional<uint64_t> MaxTC =
1878 getMaxRuntimeElementCount(*TC, *Cost->TheFunction);
1879 if (!MaxStep || !MaxTC)
1880 return false;
1881
1882 // Bail out if the maximum trip count is not representable in the induction
1883 // variable's type.
1884 if (MaxUIntTripCount.ult(*MaxTC))
1885 return false;
1886
1887 return (MaxUIntTripCount - *MaxTC).ugt(*MaxStep);
1888 }
1889
1890 return false;
1891}
1892
1893// Return whether we allow using masked interleave-groups (for dealing with
1894// strided loads/stores that reside in predicated blocks, or for dealing
1895// with gaps).
1897 // If an override option has been passed in for interleaved accesses, use it.
1898 if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
1900
1901 return TTI.enableMaskedInterleavedAccessVectorization();
1902}
1903
1904/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
1905/// VPBB are moved to the end of the newly created VPIRBasicBlock. All
1906/// predecessors and successors of VPBB, if any, are rewired to the new
1907/// VPIRBasicBlock. If \p VPBB may be unreachable, \p Plan must be passed.
1909 BasicBlock *IRBB,
1910 VPlan *Plan = nullptr) {
1911 if (!Plan)
1912 Plan = VPBB->getPlan();
1913 VPIRBasicBlock *IRVPBB = Plan->createEmptyVPIRBasicBlock(IRBB);
1914 auto IP = IRVPBB->begin();
1915 for (auto &R : make_early_inc_range(VPBB->phis()))
1916 R.moveBefore(*IRVPBB, IP);
1917
1918 for (auto &R :
1920 R.moveBefore(*IRVPBB, IRVPBB->end());
1921
1922 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB);
1923 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
1924 return IRVPBB;
1925}
1926
1928 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
1929 assert(VectorPH && "Invalid loop structure");
1930
1931 // NOTE: The Plan's scalar preheader VPBB isn't replaced with a VPIRBasicBlock
1932 // wrapping the newly created scalar preheader here at the moment, because the
1933 // Plan's scalar preheader may be unreachable at this point. Instead it is
1934 // replaced in executePlan.
1935 return SplitBlock(VectorPH, VectorPH->getTerminator(), DT, LI, nullptr,
1936 Twine(Prefix) + "scalar.ph");
1937}
1938
1939/// Knowing that loop \p L executes a single vector iteration, add instructions
1940/// that will get simplified and thus should not have any cost to \p
1941/// InstsToIgnore.
1944 SmallPtrSetImpl<Instruction *> &InstsToIgnore) {
1945 auto *Cmp = L->getLatchCmpInst();
1946 if (Cmp)
1947 InstsToIgnore.insert(Cmp);
1948 for (const auto &KV : IL) {
1949 // Extract the key by hand so that it can be used in the lambda below. Note
1950 // that captured structured bindings are a C++20 extension.
1951 PHINode *IV = KV.first;
1952
1953 // The induction is free: a widened induction generates a vector phi with
1954 // its start value and an increment that is dead without a backedge.
1955 InstsToIgnore.insert(IV);
1956
1957 // Get next iteration value of the induction variable.
1958 Instruction *IVInst =
1959 cast<Instruction>(IV->getIncomingValueForBlock(L->getLoopLatch()));
1960 if (all_of(IVInst->users(),
1961 [&](const User *U) { return U == IV || U == Cmp; }))
1962 InstsToIgnore.insert(IVInst);
1963 }
1964}
1965
1967 // Create a new IR basic block for the scalar preheader.
1968 BasicBlock *ScalarPH = createScalarPreheader("");
1969 return ScalarPH->getSinglePredecessor();
1970}
1971
1972namespace {
1973
1974struct CSEDenseMapInfo {
1975 static bool canHandle(const Instruction *I) {
1978 }
1979
1980 static unsigned getHashValue(const Instruction *I) {
1981 assert(canHandle(I) && "Unknown instruction!");
1982 return hash_combine(I->getOpcode(),
1983 hash_combine_range(I->operand_values()));
1984 }
1985
1986 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
1987 return LHS->isIdenticalTo(RHS);
1988 }
1989};
1990
1991} // end anonymous namespace
1992
1993/// FIXME: This legacy common-subexpression-elimination routine is scheduled for
1994/// removal, in favor of the VPlan-based one.
1995static void legacyCSE(BasicBlock *BB) {
1996 // Perform simple cse.
1998 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
1999 if (!CSEDenseMapInfo::canHandle(&In))
2000 continue;
2001
2002 // Check if we can replace this instruction with any of the
2003 // visited instructions.
2004 if (Instruction *V = CSEMap.lookup(&In)) {
2005 In.replaceAllUsesWith(V);
2006 In.eraseFromParent();
2007 continue;
2008 }
2009
2010 CSEMap[&In] = &In;
2011 }
2012}
2013
2014/// This function attempts to return a value that represents the ElementCount
2015/// at runtime. For fixed-width VFs we know this precisely at compile
2016/// time, but for scalable VFs we calculate it based on an estimate of the
2017/// vscale value.
2019 std::optional<unsigned> VScale) {
2020 unsigned EstimatedVF = VF.getKnownMinValue();
2021 if (VF.isScalable())
2022 if (VScale)
2023 EstimatedVF *= *VScale;
2024 assert(EstimatedVF >= 1 && "Estimated VF shouldn't be less than 1");
2025 return EstimatedVF;
2026}
2027
2028/// Returns the vector library variant function of \p CI usable at \p VF,
2029/// respecting \p MaskRequired, or nullptr if none is found: a mapping with
2030/// matching VF, masked if required, whose vector function is declared in the
2031/// module.
2033 bool MaskRequired,
2034 const TargetLibraryInfo *TLI) {
2035 if (!TLI || CI.isNoBuiltin())
2036 return nullptr;
2037 for (const VFInfo &Info : VFDatabase::getMappings(CI))
2038 if (Info.Shape.VF == VF && (!MaskRequired || Info.isMasked()))
2039 if (Function *F = CI.getModule()->getFunction(Info.VectorName))
2040 return F;
2041 return nullptr;
2042}
2043
2044/// Returns true iff \p CI has a library vector variant usable at \p VF.
2046 bool MaskRequired,
2047 const TargetLibraryInfo *TLI) {
2048 return getVectorLibraryVariantFor(CI, VF, MaskRequired, TLI) != nullptr;
2049}
2050
2053 ElementCount VF) const {
2054 Type *RetTy = CI->getType();
2056 for (auto &ArgOp : CI->args())
2057 Tys.push_back(ArgOp->getType());
2058
2059 InstructionCost ScalarCallCost = TTI.getCallInstrCost(
2060 CI->getCalledFunction(), RetTy, Tys, Config.CostKind);
2061
2062 // Cost of the scalar call (scalar VF) or its scalarization (vector VF). The
2063 // scalarization cost is only meaningful for fixed VFs.
2066 : ScalarCallCost * VF.getKnownMinValue() +
2067 getScalarizationOverhead(CI, VF);
2068
2069 // The call may be vectorized at this VF, via a vector intrinsic or a vector
2070 // library variant.
2072 Cost = std::min(Cost, getVectorIntrinsicCost(CI, VF));
2073
2074 if (Function *Variant =
2076 Cost = std::min(Cost,
2077 TTI.getCallInstrCost(
2078 /*F=*/nullptr, Variant->getReturnType(),
2079 Variant->getFunctionType()->params(), Config.CostKind));
2080
2081 return Cost;
2082}
2083
2085 if (VF.isScalar() || !canVectorizeTy(Ty))
2086 return Ty;
2087 return toVectorizedTy(Ty, VF);
2088}
2089
2092 ElementCount VF) const {
2094 assert(ID && "Expected intrinsic call!");
2095 Type *RetTy = maybeVectorizeType(CI->getType(), VF);
2096 FastMathFlags FMF;
2097 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2098 FMF = FPMO->getFastMathFlags();
2099
2102 SmallVector<Type *> ParamTys;
2103 std::transform(FTy->param_begin(), FTy->param_end(),
2104 std::back_inserter(ParamTys),
2105 [&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
2106
2107 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
2110 return TTI.getIntrinsicInstrCost(CostAttrs, Config.CostKind);
2111}
2112
2114 // Don't apply optimizations below when no (vector) loop remains, as they all
2115 // require one at the moment.
2116 VPBasicBlock *HeaderVPBB =
2117 vputils::getFirstLoopHeader(*State.Plan, State.VPDT);
2118 if (!HeaderVPBB)
2119 return;
2120
2121 BasicBlock *HeaderBB = State.CFG.VPBB2IRBB[HeaderVPBB];
2122
2123 // Remove redundant induction instructions.
2124 legacyCSE(HeaderBB);
2125}
2126
2127void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
2128 // We should not collect Scalars more than once per VF. Right now, this
2129 // function is called from collectUniformsAndScalars(), which already does
2130 // this check. Collecting Scalars for VF=1 does not make any sense.
2131 assert(VF.isVector() && !Scalars.contains(VF) &&
2132 "This function should not be visited twice for the same VF");
2133
2134 // This avoids any chances of creating a REPLICATE recipe during planning
2135 // since that would result in generation of scalarized code during execution,
2136 // which is not supported for scalable vectors.
2137 if (VF.isScalable()) {
2138 Scalars[VF].insert_range(Uniforms[VF]);
2139 return;
2140 }
2141
2143
2144 // These sets are used to seed the analysis with pointers used by memory
2145 // accesses that will remain scalar.
2147 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
2148 auto *Latch = TheLoop->getLoopLatch();
2149
2150 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
2151 // The pointer operands of loads and stores will be scalar as long as the
2152 // memory access is not a gather/scatter or histogram operation. The value
2153 // operand of a store will remain scalar if the store is scalarized.
2154 auto IsScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
2155 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
2156 assert(WideningDecision != CM_Unknown &&
2157 "Widening decision should be ready at this moment");
2158 auto *Store = dyn_cast<StoreInst>(MemAccess);
2159 if (Store && Ptr == Store->getValueOperand())
2160 return WideningDecision == CM_Scalarize;
2161 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
2162 "Ptr is neither a value or pointer operand");
2163 return WideningDecision != CM_GatherScatter &&
2164 !(Store && Legal->getHistogramInfo(Store));
2165 };
2166
2167 // A helper that returns true if the given value is a getelementptr
2168 // instruction contained in the loop.
2169 auto IsLoopVaryingGEP = [&](Value *V) {
2170 return isa<GetElementPtrInst>(V) && !TheLoop->isLoopInvariant(V);
2171 };
2172
2173 // A helper that evaluates a memory access's use of a pointer. If the use will
2174 // be a scalar use and the pointer is only used by memory accesses, we place
2175 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
2176 // PossibleNonScalarPtrs.
2177 auto EvaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
2178 // We only care about bitcast and getelementptr instructions contained in
2179 // the loop.
2180 if (!IsLoopVaryingGEP(Ptr))
2181 return;
2182
2183 // If the pointer has already been identified as scalar (e.g., if it was
2184 // also identified as uniform), there's nothing to do.
2185 auto *I = cast<Instruction>(Ptr);
2186 if (Worklist.count(I))
2187 return;
2188
2189 // If the use of the pointer will be a scalar use, and all users of the
2190 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
2191 // place the pointer in PossibleNonScalarPtrs.
2192 if (IsScalarUse(MemAccess, Ptr) &&
2194 ScalarPtrs.insert(I);
2195 else
2196 PossibleNonScalarPtrs.insert(I);
2197 };
2198
2199 // We seed the scalars analysis with three classes of instructions: (1)
2200 // instructions marked uniform-after-vectorization and (2) bitcast,
2201 // getelementptr and (pointer) phi instructions used by memory accesses
2202 // requiring a scalar use.
2203 //
2204 // (1) Add to the worklist all instructions that have been identified as
2205 // uniform-after-vectorization.
2206 Worklist.insert_range(Uniforms[VF]);
2207
2208 // (2) Add to the worklist all bitcast and getelementptr instructions used by
2209 // memory accesses requiring a scalar use. The pointer operands of loads and
2210 // stores will be scalar unless the operation is a gather or scatter.
2211 // The value operand of a store will remain scalar if the store is scalarized.
2212 for (auto *BB : TheLoop->blocks())
2213 for (auto &I : *BB) {
2214 if (auto *Load = dyn_cast<LoadInst>(&I)) {
2215 EvaluatePtrUse(Load, Load->getPointerOperand());
2216 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2217 EvaluatePtrUse(Store, Store->getPointerOperand());
2218 EvaluatePtrUse(Store, Store->getValueOperand());
2219 }
2220 }
2221 for (auto *I : ScalarPtrs)
2222 if (!PossibleNonScalarPtrs.count(I)) {
2223 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
2224 Worklist.insert(I);
2225 }
2226
2227 // Insert the forced scalars.
2228 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
2229 // induction variable when the PHI user is scalarized.
2230 auto ForcedScalar = ForcedScalars.find(VF);
2231 if (ForcedScalar != ForcedScalars.end())
2232 for (auto *I : ForcedScalar->second) {
2233 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
2234 Worklist.insert(I);
2235 }
2236
2237 // Expand the worklist by looking through any bitcasts and getelementptr
2238 // instructions we've already identified as scalar. This is similar to the
2239 // expansion step in collectLoopUniforms(); however, here we're only
2240 // expanding to include additional bitcasts and getelementptr instructions.
2241 unsigned Idx = 0;
2242 while (Idx != Worklist.size()) {
2243 Instruction *Dst = Worklist[Idx++];
2244 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
2245 continue;
2246 auto *Src = cast<Instruction>(Dst->getOperand(0));
2247 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
2248 auto *J = cast<Instruction>(U);
2249 return !TheLoop->contains(J) || Worklist.count(J) ||
2250 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
2251 IsScalarUse(J, Src));
2252 })) {
2253 Worklist.insert(Src);
2254 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
2255 }
2256 }
2257
2258 // An induction variable will remain scalar if all users of the induction
2259 // variable and induction variable update remain scalar.
2260 for (const auto &Induction : Legal->getInductionVars()) {
2261 auto *Ind = Induction.first;
2262 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2263
2264 // If tail-folding is applied, the primary induction variable will be used
2265 // to feed a vector compare.
2266 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
2267 continue;
2268
2269 // Returns true if \p Indvar is a pointer induction that is used directly by
2270 // load/store instruction \p I.
2271 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
2272 Instruction *I) {
2273 return Induction.second.getKind() ==
2276 Indvar == getLoadStorePointerOperand(I) && IsScalarUse(I, Indvar);
2277 };
2278
2279 // Determine if all users of the induction variable are scalar after
2280 // vectorization.
2281 bool ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
2282 auto *I = cast<Instruction>(U);
2283 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2284 IsDirectLoadStoreFromPtrIndvar(Ind, I);
2285 });
2286 if (!ScalarInd)
2287 continue;
2288
2289 // If the induction variable update is a fixed-order recurrence, neither the
2290 // induction variable or its update should be marked scalar after
2291 // vectorization.
2292 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
2293 if (IndUpdatePhi && Legal->isFixedOrderRecurrence(IndUpdatePhi))
2294 continue;
2295
2296 // Determine if all users of the induction variable update instruction are
2297 // scalar after vectorization.
2298 bool ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2299 auto *I = cast<Instruction>(U);
2300 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
2301 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
2302 });
2303 if (!ScalarIndUpdate)
2304 continue;
2305
2306 // The induction variable and its update instruction will remain scalar.
2307 Worklist.insert(Ind);
2308 Worklist.insert(IndUpdate);
2309 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
2310 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
2311 << "\n");
2312 }
2313
2314 Scalars[VF].insert_range(Worklist);
2315}
2316
2324
2326 ElementCount VF) const {
2328 return Config.isLegalGatherOrScatter(isa<LoadInst>(I), getLoadStoreType(I),
2330}
2331
2333 ElementCount VF) {
2334 if (!isPredicatedInst(I))
2335 return false;
2336
2337 // Do we have a non-scalar lowering for this predicated
2338 // instruction? No - it is scalar with predication.
2339 switch(I->getOpcode()) {
2340 default:
2341 return true;
2342 case Instruction::Call: {
2343 if (VF.isScalar())
2344 return true;
2345 auto *CI = cast<CallInst>(I);
2346 // A vector intrinsic or library variant lowering avoids scalarization.
2347 return !getVectorIntrinsicIDForCall(CI, TLI) &&
2349 }
2350 case Instruction::Load:
2351 case Instruction::Store: {
2352 bool IsConsecutive = Legal->isConsecutivePtr(getLoadStoreType(I),
2354 return !(IsConsecutive && isLegalMaskedLoadOrStore(I, VF)) &&
2356 }
2357 case Instruction::UDiv:
2358 case Instruction::SDiv:
2359 case Instruction::SRem:
2360 case Instruction::URem: {
2361 // We have the option to use the llvm.masked.udiv intrinsics to avoid
2362 // predication. The cost based decision here will always select the masked
2363 // intrinsics for scalable vectors as scalarization isn't legal.
2364 const auto [ScalarCost, MaskedCost] = getDivRemSpeculationCost(I, VF);
2365 return isDivRemScalarWithPredication(ScalarCost, MaskedCost);
2366 }
2367 }
2368}
2369
2371 return Legal->isMaskRequired(I, foldTailByMasking());
2372}
2373
2374// TODO: Fold into LoopVectorizationLegality::isMaskRequired.
2376 // TODO: We can use the loop-preheader as context point here and get
2377 // context sensitive reasoning for isSafeToSpeculativelyExecute.
2381 return false;
2382
2383 // If the instruction was executed conditionally in the original scalar loop,
2384 // predication is needed with a mask whose lanes are all possibly inactive.
2385 if (Legal->blockNeedsPredication(I->getParent()))
2386 return true;
2387
2388 // If we're not folding the tail by masking and not vectorizing a loop with
2389 // uncountable exits and side effects, predication is unnecessary.
2390 if (!foldTailByMasking() && !Legal->hasUncountableExitWithSideEffects())
2391 return false;
2392
2393 // All that remain are instructions with side-effects originally executed in
2394 // the loop unconditionally, but now execute under a tail-fold mask (only)
2395 // having at least one active lane (the first). If the side-effects of the
2396 // instruction are invariant, executing it w/o (the tail-folding) mask is safe
2397 // - it will cause the same side-effects as when masked.
2398 switch(I->getOpcode()) {
2399 default:
2401 "instruction should have been considered by earlier checks");
2402 case Instruction::Call:
2403 // Side-effects of a Call are assumed to be non-invariant, needing a
2404 // (fold-tail) mask.
2406 "should have returned earlier for calls not needing a mask");
2407 return true;
2408 case Instruction::Load:
2409 // If the address is loop invariant no predication is needed.
2410 return !Legal->isInvariant(getLoadStorePointerOperand(I));
2411 case Instruction::Store: {
2412 // For stores, we need to prove both speculation safety (which follows from
2413 // the same argument as loads), but also must prove the value being stored
2414 // is correct. The easiest form of the later is to require that all values
2415 // stored are the same.
2416 return !(Legal->isInvariant(getLoadStorePointerOperand(I)) &&
2417 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()));
2418 }
2419 case Instruction::UDiv:
2420 case Instruction::URem:
2421 // If the divisor is loop-invariant no predication is needed.
2422 return !Legal->isInvariant(I->getOperand(1));
2423 case Instruction::SDiv:
2424 case Instruction::SRem:
2425 // Conservative for now, since masked-off lanes may be poison and could
2426 // trigger signed overflow.
2427 return true;
2428 }
2429}
2430
2434 return 1;
2435 // If the block wasn't originally predicated then return early to avoid
2436 // computing BlockFrequencyInfo unnecessarily.
2437 if (!Legal->blockNeedsPredication(BB))
2438 return 1;
2439
2440 uint64_t HeaderFreq =
2441 getBFI().getBlockFreq(TheLoop->getHeader()).getFrequency();
2442 uint64_t BBFreq = getBFI().getBlockFreq(BB).getFrequency();
2443 assert(HeaderFreq >= BBFreq &&
2444 "Header has smaller block freq than dominated BB?");
2445 return std::round((double)HeaderFreq / BBFreq);
2446}
2447
2449 switch (Opcode) {
2450 case Instruction::UDiv:
2451 return Intrinsic::masked_udiv;
2452 case Instruction::SDiv:
2453 return Intrinsic::masked_sdiv;
2454 case Instruction::URem:
2455 return Intrinsic::masked_urem;
2456 case Instruction::SRem:
2457 return Intrinsic::masked_srem;
2458 default:
2459 llvm_unreachable("Unexpected opcode");
2460 }
2461}
2462
2463std::pair<InstructionCost, InstructionCost>
2465 ElementCount VF) {
2466 assert(I->getOpcode() == Instruction::UDiv ||
2467 I->getOpcode() == Instruction::SDiv ||
2468 I->getOpcode() == Instruction::SRem ||
2469 I->getOpcode() == Instruction::URem);
2471
2472 // Scalarization isn't legal for scalable vector types
2473 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2474 if (!VF.isScalable()) {
2475 // Get the scalarization cost and scale this amount by the probability of
2476 // executing the predicated block. If the instruction is not predicated,
2477 // we fall through to the next case.
2478 ScalarizationCost = 0;
2479
2480 // These instructions have a non-void type, so account for the phi nodes
2481 // that we will create. This cost is likely to be zero. The phi node
2482 // cost, if any, should be scaled by the block probability because it
2483 // models a copy at the end of each predicated block.
2484 ScalarizationCost += VF.getFixedValue() *
2485 TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
2486
2487 // The cost of the non-predicated instruction.
2488 ScalarizationCost +=
2489 VF.getFixedValue() * TTI.getArithmeticInstrCost(
2490 I->getOpcode(), I->getType(), Config.CostKind);
2491
2492 // The cost of insertelement and extractelement instructions needed for
2493 // scalarization.
2494 ScalarizationCost += getScalarizationOverhead(I, VF);
2495
2496 // Scale the cost by the probability of executing the predicated blocks.
2497 // This assumes the predicated block for each vector lane is equally
2498 // likely.
2499 ScalarizationCost =
2500 ScalarizationCost /
2501 getPredBlockCostDivisor(Config.CostKind, I->getParent());
2502 }
2503
2504 auto *VecTy = toVectorTy(I->getType(), VF);
2505 auto *MaskTy = toVectorTy(Type::getInt1Ty(I->getContext()), VF);
2506 IntrinsicCostAttributes ICA(getMaskedDivRemIntrinsic(I->getOpcode()), VecTy,
2507 {VecTy, VecTy, MaskTy});
2508 InstructionCost MaskedCost = TTI.getIntrinsicInstrCost(ICA, Config.CostKind);
2509 return {ScalarizationCost, MaskedCost};
2510}
2511
2513 Instruction *I, ElementCount VF) const {
2514 assert(isAccessInterleaved(I) && "Expecting interleaved access.");
2516 "Decision should not be set yet.");
2517 auto *Group = getInterleavedAccessGroup(I);
2518 assert(Group && "Must have a group.");
2519 unsigned InterleaveFactor = Group->getFactor();
2520
2521 // If the instruction's allocated size doesn't equal its type size, it
2522 // requires padding and will be scalarized.
2523 auto &DL = I->getDataLayout();
2524 auto *ScalarTy = getLoadStoreType(I);
2525 if (hasIrregularType(ScalarTy, DL))
2526 return false;
2527
2528 // For scalable vectors, the interleave factors must be <= 8 since we require
2529 // the (de)interleaveN intrinsics instead of shufflevectors.
2530 if (VF.isScalable() && InterleaveFactor > 8)
2531 return false;
2532
2533 // If the group involves a non-integral pointer, we may not be able to
2534 // losslessly cast all values to a common type.
2535 bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
2536 for (Instruction *Member : Group->members()) {
2537 auto *MemberTy = getLoadStoreType(Member);
2538 bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
2539 // Don't coerce non-integral pointers to integers or vice versa.
2540 if (MemberNI != ScalarNI)
2541 // TODO: Consider adding special nullptr value case here
2542 return false;
2543 if (MemberNI && ScalarNI &&
2544 ScalarTy->getPointerAddressSpace() !=
2545 MemberTy->getPointerAddressSpace())
2546 return false;
2547 }
2548
2549 // Check if masking is required.
2550 // A Group may need masking for one of two reasons: it resides in a block that
2551 // needs predication, or it was decided to use masking to deal with gaps
2552 // (either a gap at the end of a load-access that may result in a speculative
2553 // load, or any gaps in a store-access).
2554 bool PredicatedAccessRequiresMasking =
2556 bool LoadAccessWithGapsRequiresEpilogMasking =
2557 isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
2559 bool StoreAccessWithGapsRequiresMasking =
2560 isa<StoreInst>(I) && !Group->isFull();
2561 if (!PredicatedAccessRequiresMasking &&
2562 !LoadAccessWithGapsRequiresEpilogMasking &&
2563 !StoreAccessWithGapsRequiresMasking)
2564 return true;
2565
2566 // If masked interleaving is required, we expect that the user/target had
2567 // enabled it, because otherwise it either wouldn't have been created or
2568 // it should have been invalidated by the CostModel.
2570 "Masked interleave-groups for predicated accesses are not enabled.");
2571
2572 if (Group->isReverse())
2573 return false;
2574
2575 // TODO: Support interleaved access that requires a gap mask for scalable VFs.
2576 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
2577 StoreAccessWithGapsRequiresMasking;
2578 if (VF.isScalable() && NeedsMaskForGaps)
2579 return false;
2580
2581 return isLegalMaskedLoadOrStore(I, VF);
2582}
2583
2584std::optional<LoopVectorizationCostModel::InstWidening>
2586 ElementCount VF) {
2587 // Get and ensure we have a valid memory instruction.
2588 assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
2589
2590 auto *Ptr = getLoadStorePointerOperand(I);
2591 auto *ScalarTy = getLoadStoreType(I);
2592
2593 // In order to be widened, the pointer should be consecutive, first of all.
2594 int Stride = Legal->isConsecutivePtr(ScalarTy, Ptr);
2595 if (!Stride)
2596 return std::nullopt;
2597
2598 // If the instruction is a store located in a predicated block, it will be
2599 // scalarized.
2600 if (isScalarWithPredication(I, VF))
2601 return std::nullopt;
2602
2603 // If the instruction's allocated size doesn't equal it's type size, it
2604 // requires padding and will be scalarized.
2605 auto &DL = I->getDataLayout();
2606 if (hasIrregularType(ScalarTy, DL))
2607 return std::nullopt;
2608
2609 return Stride == 1 ? CM_Widen : CM_Widen_Reverse;
2610}
2611
2612void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
2613 // We should not collect Uniforms more than once per VF. Right now,
2614 // this function is called from collectUniformsAndScalars(), which
2615 // already does this check. Collecting Uniforms for VF=1 does not make any
2616 // sense.
2617
2618 assert(VF.isVector() && !Uniforms.contains(VF) &&
2619 "This function should not be visited twice for the same VF");
2620
2621 // Visit the list of Uniforms. If we find no uniform value, we won't
2622 // analyze again. Uniforms.count(VF) will return 1.
2623 Uniforms[VF].clear();
2624
2625 // Now we know that the loop is vectorizable!
2626 // Collect instructions inside the loop that will remain uniform after
2627 // vectorization.
2628
2629 // Global values, params and instructions outside of current loop are out of
2630 // scope.
2631 auto IsOutOfScope = [&](Value *V) -> bool {
2633 return (!I || !TheLoop->contains(I));
2634 };
2635
2636 // Worklist containing uniform instructions demanding lane 0.
2637 SetVector<Instruction *> Worklist;
2638
2639 // Add uniform instructions demanding lane 0 to the worklist. Instructions
2640 // that require predication must not be considered uniform after
2641 // vectorization, because that would create an erroneous replicating region
2642 // where only a single instance out of VF should be formed.
2643 auto AddToWorklistIfAllowed = [&](Instruction *I) -> void {
2644 if (IsOutOfScope(I)) {
2645 LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
2646 << *I << "\n");
2647 return;
2648 }
2649 if (isPredicatedInst(I)) {
2650 LLVM_DEBUG(
2651 dbgs() << "LV: Found not uniform due to requiring predication: " << *I
2652 << "\n");
2653 return;
2654 }
2655 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
2656 Worklist.insert(I);
2657 };
2658
2659 // Start with the conditional branches exiting the loop. If the branch
2660 // condition is an instruction contained in the loop that is only used by the
2661 // branch, it is uniform. Note conditions from uncountable early exits are not
2662 // uniform.
2664 TheLoop->getExitingBlocks(Exiting);
2665 for (BasicBlock *E : Exiting) {
2666 if (Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() != E)
2667 continue;
2668 auto *Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
2669 if (!Cmp || !TheLoop->contains(Cmp) || !Cmp->hasOneUse())
2670 continue;
2671
2672 // If we have an exit condition that is actually two conditions (one
2673 // countable and the other uncountable) combined via an or, only add the
2674 // countable comparison as a uniform value.
2675 if (Legal->hasUncountableExitWithSideEffects() &&
2676 TheLoop->getLoopLatch() == E) {
2677 if (Instruction *Countable =
2678 Legal->findCountableComparisonInCombinedCondition(Cmp)) {
2679 if (Countable->hasOneUse())
2680 AddToWorklistIfAllowed(Countable);
2681 continue;
2682 }
2683 }
2684
2685 // Normal exit comparisons are uniform.
2686 AddToWorklistIfAllowed(Cmp);
2687 }
2688
2689 auto PrevVF = VF.divideCoefficientBy(2);
2690 // Return true if all lanes perform the same memory operation, and we can
2691 // thus choose to execute only one.
2692 auto IsUniformMemOpUse = [&](Instruction *I) {
2693 // If the value was already known to not be uniform for the previous
2694 // (smaller VF), it cannot be uniform for the larger VF.
2695 if (PrevVF.isVector()) {
2696 auto Iter = Uniforms.find(PrevVF);
2697 if (Iter != Uniforms.end() && !Iter->second.contains(I))
2698 return false;
2699 }
2700 if (!isUniformMemOp(*I, VF))
2701 return false;
2702 if (isa<LoadInst>(I))
2703 // Loading the same address always produces the same result - at least
2704 // assuming aliasing and ordering which have already been checked.
2705 return true;
2706 // Storing the same value on every iteration.
2707 return TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand());
2708 };
2709
2710 auto IsUniformDecision = [&](Instruction *I, ElementCount VF) {
2711 InstWidening WideningDecision = getWideningDecision(I, VF);
2712 assert(WideningDecision != CM_Unknown &&
2713 "Widening decision should be ready at this moment");
2714
2715 if (IsUniformMemOpUse(I))
2716 return true;
2717
2718 return (WideningDecision == CM_Widen ||
2719 WideningDecision == CM_Widen_Reverse ||
2720 WideningDecision == CM_Interleave);
2721 };
2722
2723 // Returns true if Ptr is the pointer operand of a memory access instruction
2724 // I, I is known to not require scalarization, and the pointer is not also
2725 // stored.
2726 auto IsVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
2727 if (isa<StoreInst>(I) && I->getOperand(0) == Ptr)
2728 return false;
2729 return getLoadStorePointerOperand(I) == Ptr &&
2730 (IsUniformDecision(I, VF) || Legal->isInvariant(Ptr));
2731 };
2732
2733 // Holds a list of values which are known to have at least one uniform use.
2734 // Note that there may be other uses which aren't uniform. A "uniform use"
2735 // here is something which only demands lane 0 of the unrolled iterations;
2736 // it does not imply that all lanes produce the same value (e.g. this is not
2737 // the usual meaning of uniform)
2738 SetVector<Value *> HasUniformUse;
2739
2740 // Scan the loop for instructions which are either a) known to have only
2741 // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
2742 for (auto *BB : TheLoop->blocks())
2743 for (auto &I : *BB) {
2744 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
2745 switch (II->getIntrinsicID()) {
2746 case Intrinsic::sideeffect:
2747 case Intrinsic::experimental_noalias_scope_decl:
2748 case Intrinsic::assume:
2749 case Intrinsic::lifetime_start:
2750 case Intrinsic::lifetime_end:
2751 if (TheLoop->hasLoopInvariantOperands(&I))
2752 AddToWorklistIfAllowed(&I);
2753 break;
2754 default:
2755 break;
2756 }
2757 }
2758
2759 if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
2760 if (IsOutOfScope(EVI->getAggregateOperand())) {
2761 AddToWorklistIfAllowed(EVI);
2762 continue;
2763 }
2764 // Only ExtractValue instructions where the aggregate value comes from a
2765 // call are allowed to be non-uniform.
2766 assert(isa<CallInst>(EVI->getAggregateOperand()) &&
2767 "Expected aggregate value to be call return value");
2768 }
2769
2770 // If there's no pointer operand, there's nothing to do.
2771 auto *Ptr = getLoadStorePointerOperand(&I);
2772 if (!Ptr)
2773 continue;
2774
2775 // If the pointer can be proven to be uniform, always add it to the
2776 // worklist.
2777 if (isa<Instruction>(Ptr) && isUniform(Ptr, VF))
2778 AddToWorklistIfAllowed(cast<Instruction>(Ptr));
2779
2780 if (IsUniformMemOpUse(&I))
2781 AddToWorklistIfAllowed(&I);
2782
2783 if (IsVectorizedMemAccessUse(&I, Ptr))
2784 HasUniformUse.insert(Ptr);
2785 }
2786
2787 // Add to the worklist any operands which have *only* uniform (e.g. lane 0
2788 // demanding) users. Since loops are assumed to be in LCSSA form, this
2789 // disallows uses outside the loop as well.
2790 for (auto *V : HasUniformUse) {
2791 if (IsOutOfScope(V))
2792 continue;
2793 auto *I = cast<Instruction>(V);
2794 bool UsersAreMemAccesses = all_of(I->users(), [&](User *U) -> bool {
2795 auto *UI = cast<Instruction>(U);
2796 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
2797 });
2798 if (UsersAreMemAccesses)
2799 AddToWorklistIfAllowed(I);
2800 }
2801
2802 // Expand Worklist in topological order: whenever a new instruction
2803 // is added , its users should be already inside Worklist. It ensures
2804 // a uniform instruction will only be used by uniform instructions.
2805 unsigned Idx = 0;
2806 while (Idx != Worklist.size()) {
2807 Instruction *I = Worklist[Idx++];
2808
2809 for (auto *OV : I->operand_values()) {
2810 // isOutOfScope operands cannot be uniform instructions.
2811 if (IsOutOfScope(OV))
2812 continue;
2813 // First order recurrence Phi's should typically be considered
2814 // non-uniform.
2815 auto *OP = dyn_cast<PHINode>(OV);
2816 if (OP && Legal->isFixedOrderRecurrence(OP))
2817 continue;
2818 // If all the users of the operand are uniform, then add the
2819 // operand into the uniform worklist.
2820 auto *OI = cast<Instruction>(OV);
2821 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
2822 auto *J = cast<Instruction>(U);
2823 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
2824 }))
2825 AddToWorklistIfAllowed(OI);
2826 }
2827 }
2828
2829 // For an instruction to be added into Worklist above, all its users inside
2830 // the loop should also be in Worklist. However, this condition cannot be
2831 // true for phi nodes that form a cyclic dependence. We must process phi
2832 // nodes separately. An induction variable will remain uniform if all users
2833 // of the induction variable and induction variable update remain uniform.
2834 // The code below handles both pointer and non-pointer induction variables.
2835 BasicBlock *Latch = TheLoop->getLoopLatch();
2836 for (const auto &Induction : Legal->getInductionVars()) {
2837 auto *Ind = Induction.first;
2838 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2839
2840 // Determine if all users of the induction variable are uniform after
2841 // vectorization.
2842 bool UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
2843 auto *I = cast<Instruction>(U);
2844 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2845 IsVectorizedMemAccessUse(I, Ind);
2846 });
2847 if (!UniformInd)
2848 continue;
2849
2850 // Determine if all users of the induction variable update instruction are
2851 // uniform after vectorization.
2852 bool UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2853 auto *I = cast<Instruction>(U);
2854 return I == Ind || Worklist.count(I) ||
2855 IsVectorizedMemAccessUse(I, IndUpdate);
2856 });
2857 if (!UniformIndUpdate)
2858 continue;
2859
2860 // The induction variable and its update instruction will remain uniform.
2861 AddToWorklistIfAllowed(Ind);
2862 AddToWorklistIfAllowed(IndUpdate);
2863 }
2864
2865 Uniforms[VF].insert_range(Worklist);
2866}
2867
2868FixedScalableVFPair
2870 // Make sure once we return PartialAliasMaskingStatus is not "NotDecided".
2871 scope_exit EnsureAliasMaskingStatusIsDecidedOnReturn([this] {
2872 if (PartialAliasMaskingStatus == AliasMaskingStatus::NotDecided)
2873 PartialAliasMaskingStatus = AliasMaskingStatus::Disabled;
2874 });
2875
2876 // For outer loops, use simple type-based heuristic VF. No cost model or
2877 // memory dependence analysis is available.
2878 if (!TheLoop->isInnermost()) {
2879 return Config.computeVPlanOuterloopVF(UserVF);
2880 }
2881
2882 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
2883 // TODO: It may be useful to do since it's still likely to be dynamically
2884 // uniform if the target can skip.
2886 "Not inserting runtime ptr check for divergent target",
2887 "runtime pointer checks needed. Not enabled for divergent target",
2888 "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
2890 }
2891
2892 ScalarEvolution *SE = PSE.getSE();
2894 unsigned MaxTC = PSE.getSmallConstantMaxTripCount();
2895 if (!MaxTC && EpilogueLoweringStatus == CM_EpilogueAllowed)
2897 LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
2898 if (TC != ElementCount::getFixed(MaxTC))
2899 LLVM_DEBUG(dbgs() << "LV: Found maximum trip count: " << MaxTC << '\n');
2900 if (TC.isScalar()) {
2902 "Single iteration (non) loop",
2903 "loop trip count is one, irrelevant for vectorization",
2904 "SingleIterationLoop", ORE, TheLoop);
2906 }
2907
2908 // If BTC matches the widest induction type and is -1 then the trip count
2909 // computation will wrap to 0 and the vector trip count will be 0. Do not try
2910 // to vectorize.
2911 const SCEV *BTC = SE->getBackedgeTakenCount(TheLoop);
2912 if (!isa<SCEVCouldNotCompute>(BTC) &&
2913 BTC->getType()->getScalarSizeInBits() >=
2914 Legal->getWidestInductionType()->getScalarSizeInBits() &&
2916 SE->getMinusOne(BTC->getType()))) {
2918 "Trip count computation wrapped",
2919 "backedge-taken count is -1, loop trip count wrapped to 0",
2920 "TripCountWrapped", ORE, TheLoop);
2922 }
2923
2924 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
2925 "No cost-modeling decisions should have been taken at this point");
2926
2927 switch (EpilogueLoweringStatus) {
2928 case CM_EpilogueAllowed:
2929 return Config.computeFeasibleMaxVF(MaxTC, UserVF, UserIC, false,
2932 [[fallthrough]];
2934 LLVM_DEBUG(dbgs() << "LV: tail-folding hint/switch found.\n"
2935 << "LV: Not allowing epilogue, creating tail-folded "
2936 << "vector loop.\n");
2937 break;
2939 // fallthrough as a special case of OptForSize
2941 if (EpilogueLoweringStatus == CM_EpilogueNotAllowedOptSize)
2942 LLVM_DEBUG(dbgs() << "LV: Not allowing epilogue due to -Os/-Oz.\n");
2943 else
2944 LLVM_DEBUG(dbgs() << "LV: Not allowing epilogue due to low trip "
2945 << "count.\n");
2946
2947 // Bail if runtime checks are required, which are not good when optimising
2948 // for size.
2949 if (Config.runtimeChecksRequired())
2951
2952 break;
2953 }
2954
2955 // Now try the tail folding
2956
2957 // Invalidate interleave groups that require an epilogue if we can't mask
2958 // the interleave-group.
2960 // Note: There is no need to invalidate any cost modeling decisions here, as
2961 // none were taken so far (see assertion above).
2962 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
2963 }
2964
2965 FixedScalableVFPair MaxFactors = Config.computeFeasibleMaxVF(
2966 MaxTC, UserVF, UserIC, true, requiresScalarEpilogue(true));
2967
2968 // Avoid tail folding if the trip count is known to be a multiple of any VF
2969 // we choose.
2970 std::optional<uint64_t> MaxPowerOf2RuntimeVF =
2971 MaxFactors.FixedVF.getFixedValue();
2972 if (MaxFactors.ScalableVF) {
2973 if (std::optional<uint64_t> MaxRuntimeScalableVF =
2975 MaxPowerOf2RuntimeVF =
2976 std::max(*MaxPowerOf2RuntimeVF, *MaxRuntimeScalableVF);
2977 else
2978 MaxPowerOf2RuntimeVF = std::nullopt; // Stick with tail-folding for now.
2979 }
2980
2981 auto NoScalarEpilogueNeeded = [this, &UserIC](uint64_t MaxRuntimeVF) {
2982 // Return false if the loop is neither a single-latch-exit loop nor an
2983 // early-exit loop as tail-folding is not supported in that case.
2984 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
2985 !Legal->hasUncountableEarlyExit())
2986 return false;
2987 uint64_t MaxVFtimesIC = MaxRuntimeVF * std::max<uint64_t>(UserIC, 1);
2988 ScalarEvolution *SE = PSE.getSE();
2989 // Calling getSymbolicMaxBackedgeTakenCount enables support for loops
2990 // with uncountable exits. For countable loops, the symbolic maximum must
2991 // remain identical to the known back-edge taken count.
2992 const SCEV *BackedgeTakenCount = PSE.getSymbolicMaxBackedgeTakenCount();
2993 assert((Legal->hasUncountableEarlyExit() ||
2994 BackedgeTakenCount == PSE.getBackedgeTakenCount()) &&
2995 "Invalid loop count");
2996 const SCEV *ExitCount = SE->getAddExpr(
2997 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2998 const SCEV *Rem = SE->getURemExpr(
2999 SE->applyLoopGuards(ExitCount, TheLoop),
3000 SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
3001 return Rem->isZero();
3002 };
3003
3004 if (MaxPowerOf2RuntimeVF > 0u) {
3005 assert((UserVF.isNonZero() || isPowerOf2_64(*MaxPowerOf2RuntimeVF)) &&
3006 "MaxFixedVF must be a power of 2");
3007 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
3008 // Accept MaxFixedVF if we do not have a tail.
3009 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
3010 return MaxFactors;
3011 }
3012 }
3013
3014 auto ExpectedTC = getSmallBestKnownTC(PSE, TheLoop);
3015 if (ExpectedTC && ExpectedTC->isFixed() &&
3016 ExpectedTC->getFixedValue() <=
3017 TTI.getMinTripCountTailFoldingThreshold()) {
3018 // If we have a low-trip-count, and the fixed-width VF is known to divide
3019 // the trip count the fixed-width factor in preference to allow the
3020 // generation of a non-predicated loop.
3021 if (EpilogueLoweringStatus == CM_EpilogueNotAllowedLowTripLoop &&
3022 NoScalarEpilogueNeeded(MaxFactors.FixedVF.getFixedValue())) {
3023 LLVM_DEBUG(dbgs() << "LV: Picking a fixed-width so that no tail will "
3024 "remain for any chosen VF.\n");
3025 MaxFactors.ScalableVF = ElementCount::getScalable(0);
3026 return MaxFactors;
3027 }
3028
3029 // Allow cases where the ExactTC == (VF * IC) + 1.
3030 //
3031 // This produces 1 vector iteration, and 1 scalar iteration with no
3032 // remainder. Later passes will eliminate the loop and leave straight-line
3033 // code as the both iteration counts are statically known.
3034 //
3035 // If a function is marked as minsize/optsize or OptForSize is set, do not
3036 // allow this form of transformation as this will increase CodeSize.
3037 //
3038 // For loops with small bodies, the cost model is not currently reliable
3039 // enough to accurately determine if vectorization is beneficial.
3040 unsigned EffectiveIC = UserIC > 0 ? UserIC : 1;
3041 unsigned MaxVFForTC = llvm::bit_floor(TC.getFixedValue());
3042 if (TC.getFixedValue() - MaxVFForTC == 1 && MaxVFForTC / EffectiveIC > 1 &&
3043 MaxVFForTC <= (MaxFactors.FixedVF.getFixedValue() * EffectiveIC) &&
3044 !Config.OptForSize) {
3045 unsigned NumOfInstructions = llvm::sum_of(
3046 llvm::map_range(TheLoop->blocks(),
3047 [](BasicBlock *BB) { return BB->size(); }),
3048 unsigned(0));
3049 if (NumOfInstructions > LowTripCountLoopBodySizeLimit) {
3050 unsigned VF = MaxVFForTC / EffectiveIC;
3051 LLVM_DEBUG(dbgs() << "LV: Picking MaxVF=" << VF
3052 << " with 1 scalar iteration remaining.\n");
3053 MaxFactors.FixedVF = ElementCount::getFixed(VF);
3054 MaxFactors.ScalableVF = ElementCount::getScalable(0);
3055 return MaxFactors;
3056 }
3057 }
3058
3060 "The trip count is below the minial threshold value.",
3061 "loop trip count is too low, avoiding vectorization", "LowTripCount",
3062 ORE, TheLoop);
3064 }
3065
3066 // If we don't know the precise trip count, or if the trip count that we
3067 // found modulo the vectorization factor is not zero, try to fold the tail
3068 // by masking.
3069 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
3070 bool ContainsScalableVF = MaxFactors.ScalableVF.isNonZero();
3071 setTailFoldingStyle(ContainsScalableVF, UserIC);
3072 if (foldTailByMasking()) {
3073 if (foldTailWithEVL()) {
3074 LLVM_DEBUG(
3075 dbgs()
3076 << "LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
3077 "try to generate VP Intrinsics with scalable vector "
3078 "factors only.\n");
3079 // Tail folded loop using VP intrinsics restricts the VF to be scalable
3080 // for now.
3081 // TODO: extend it for fixed vectors, if required.
3082 assert(ContainsScalableVF && "Expected scalable vector factor.");
3083
3084 MaxFactors.FixedVF = ElementCount::getFixed(1);
3085 } else {
3087 }
3088 return MaxFactors;
3089 }
3090
3091 // If there was a tail-folding hint/switch, but we can't fold the tail by
3092 // masking, fallback to a vectorization with an epilogue.
3093 if (EpilogueLoweringStatus == CM_EpilogueNotNeededFoldTail) {
3094 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with an "
3095 "epilogue instead.\n");
3096 EpilogueLoweringStatus = CM_EpilogueAllowed;
3097 return MaxFactors;
3098 }
3099
3100 if (EpilogueLoweringStatus == CM_EpilogueNotAllowedFoldTail) {
3101 LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
3103 }
3104
3105 if (TC.isZero()) {
3107 "unable to calculate the loop count due to complex control flow",
3108 "UnknownLoopCountComplexCFG", ORE, TheLoop);
3110 }
3111
3113 "Cannot optimize for size and vectorize at the same time.",
3114 "cannot optimize for size and vectorize at the same time. "
3115 "Enable vectorization of this loop with '#pragma clang loop "
3116 "vectorize(enable)' when compiling with -Os/-Oz",
3117 "NoTailLoopWithOptForSize", ORE, TheLoop);
3119}
3120
3123 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
3124 SmallVector<RecipeVFPair> InvalidCosts;
3125 for (const auto &Plan : VPlans) {
3126 for (ElementCount VF : Plan->vectorFactors()) {
3127 // The VPlan-based cost model is designed for computing vector cost.
3128 // Querying VPlan-based cost model with a scarlar VF will cause some
3129 // errors because we expect the VF is vector for most of the widen
3130 // recipes.
3131 if (VF.isScalar())
3132 continue;
3133
3134 VPCostContext CostCtx(*TLI, *Plan, *CM, Config,
3135 /*ReusePrintingSlotTracker=*/true);
3136 precomputeCosts(*Plan, VF, CostCtx);
3137 auto Iter = vp_depth_first_deep(Plan->getVectorLoopRegion()->getEntry());
3139 for (auto &R : *VPBB) {
3140 if (!R.cost(VF, CostCtx).isValid())
3141 InvalidCosts.emplace_back(&R, VF);
3142 }
3143 }
3144 }
3145 }
3146 if (InvalidCosts.empty())
3147 return;
3148
3149 // Emit a report of VFs with invalid costs in the loop.
3150
3151 // Group the remarks per recipe, keeping the recipe order from InvalidCosts.
3153 unsigned I = 0;
3154 for (auto &Pair : InvalidCosts)
3155 if (Numbering.try_emplace(Pair.first, I).second)
3156 ++I;
3157
3158 // Sort the list, first on recipe(number) then on VF.
3159 sort(InvalidCosts, [&Numbering](RecipeVFPair &A, RecipeVFPair &B) {
3160 unsigned NA = Numbering[A.first];
3161 unsigned NB = Numbering[B.first];
3162 if (NA != NB)
3163 return NA < NB;
3164 return ElementCount::isKnownLT(A.second, B.second);
3165 });
3166
3167 // For a list of ordered recipe-VF pairs:
3168 // [(load, VF1), (load, VF2), (store, VF1)]
3169 // group the recipes together to emit separate remarks for:
3170 // load (VF1, VF2)
3171 // store (VF1)
3172 auto Tail = ArrayRef<RecipeVFPair>(InvalidCosts);
3173 auto Subset = ArrayRef<RecipeVFPair>();
3174 do {
3175 if (Subset.empty())
3176 Subset = Tail.take_front(1);
3177
3178 VPRecipeBase *R = Subset.front().first;
3179
3180 unsigned Opcode =
3182 .Case([](const VPHeaderPHIRecipe *R) { return Instruction::PHI; })
3183 .Case(
3184 [](const VPWidenStoreRecipe *R) { return Instruction::Store; })
3185 .Case([](const VPWidenLoadRecipe *R) { return Instruction::Load; })
3186 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
3187 [](const auto *R) { return Instruction::Call; })
3190 [](const auto *R) { return R->getOpcode(); })
3191 .Case([](const VPInterleaveRecipe *R) {
3192 return R->getStoredValues().empty() ? Instruction::Load
3193 : Instruction::Store;
3194 })
3195 .Case([](const VPReductionRecipe *R) {
3196 return RecurrenceDescriptor::getOpcode(R->getRecurrenceKind());
3197 });
3198
3199 // If the next recipe is different, or if there are no other pairs,
3200 // emit a remark for the collated subset. e.g.
3201 // [(load, VF1), (load, VF2))]
3202 // to emit:
3203 // remark: invalid costs for 'load' at VF=(VF1, VF2)
3204 if (Subset == Tail || Tail[Subset.size()].first != R) {
3205 std::string OutString;
3206 raw_string_ostream OS(OutString);
3207 assert(!Subset.empty() && "Unexpected empty range");
3208 OS << "Recipe with invalid costs prevented vectorization at VF=(";
3209 for (const auto &Pair : Subset)
3210 OS << (Pair.second == Subset.front().second ? "" : ", ") << Pair.second;
3211 OS << "):";
3212 if (Opcode == Instruction::Call) {
3213 StringRef Name = "";
3214 if (auto *Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
3215 Name = Int->getIntrinsicName();
3216 } else {
3217 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
3218 Function *CalledFn =
3219 WidenCall ? WidenCall->getCalledScalarFunction()
3220 : cast<Function>(R->getOperand(R->getNumOperands() - 1)
3221 ->getLiveInIRValue());
3222 Name = CalledFn->getName();
3223 }
3224 OS << " call to " << Name;
3225 } else
3226 OS << " " << Instruction::getOpcodeName(Opcode);
3227 reportVectorizationInfo(OutString, "InvalidCost", ORE, OrigLoop, nullptr,
3228 R->getDebugLoc());
3229 Tail = Tail.drop_front(Subset.size());
3230 Subset = {};
3231 } else
3232 // Grow the subset by one element
3233 Subset = Tail.take_front(Subset.size() + 1);
3234 } while (!Tail.empty());
3235}
3236
3237/// Check if any recipe of \p Plan will generate a vector value, which will be
3238/// assigned a vector register.
3240 const TargetTransformInfo &TTI) {
3241 assert(VF.isVector() && "Checking a scalar VF?");
3242 DenseSet<VPRecipeBase *> EphemeralRecipes;
3243 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
3244 // Set of already visited types.
3245 DenseSet<Type *> Visited;
3248 for (VPRecipeBase &R : *VPBB) {
3249 if (EphemeralRecipes.contains(&R))
3250 continue;
3251 // Continue early if the recipe is considered to not produce a vector
3252 // result. Note that this includes VPInstruction where some opcodes may
3253 // produce a vector, to preserve existing behavior as VPInstructions model
3254 // aspects not directly mapped to existing IR instructions.
3255 switch (R.getVPRecipeID()) {
3256 case VPRecipeBase::VPDerivedIVSC:
3257 case VPRecipeBase::VPScalarIVStepsSC:
3258 case VPRecipeBase::VPReplicateSC:
3259 case VPRecipeBase::VPInstructionSC:
3260 case VPRecipeBase::VPCurrentIterationPHISC:
3261 case VPRecipeBase::VPVectorPointerSC:
3262 case VPRecipeBase::VPVectorEndPointerSC:
3263 case VPRecipeBase::VPExpandSCEVSC:
3264 case VPRecipeBase::VPPredInstPHISC:
3265 case VPRecipeBase::VPBranchOnMaskSC:
3266 continue;
3267 case VPRecipeBase::VPReductionSC:
3268 case VPRecipeBase::VPActiveLaneMaskPHISC:
3269 case VPRecipeBase::VPWidenCallSC:
3270 case VPRecipeBase::VPWidenCanonicalIVSC:
3271 case VPRecipeBase::VPWidenCastSC:
3272 case VPRecipeBase::VPWidenGEPSC:
3273 case VPRecipeBase::VPWidenIntrinsicSC:
3274 case VPRecipeBase::VPWidenMemIntrinsicSC:
3275 case VPRecipeBase::VPWidenSC:
3276 case VPRecipeBase::VPBlendSC:
3277 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
3278 case VPRecipeBase::VPHistogramSC:
3279 case VPRecipeBase::VPWidenPHISC:
3280 case VPRecipeBase::VPWidenIntOrFpInductionSC:
3281 case VPRecipeBase::VPWidenPointerInductionSC:
3282 case VPRecipeBase::VPReductionPHISC:
3283 case VPRecipeBase::VPInterleaveEVLSC:
3284 case VPRecipeBase::VPInterleaveSC:
3285 case VPRecipeBase::VPWidenLoadEVLSC:
3286 case VPRecipeBase::VPWidenLoadSC:
3287 case VPRecipeBase::VPWidenStoreEVLSC:
3288 case VPRecipeBase::VPWidenStoreSC:
3289 break;
3290 default:
3291 llvm_unreachable("unhandled recipe");
3292 }
3293
3294 auto WillGenerateTargetVectors = [&TTI, VF](Type *VectorTy) {
3295 unsigned NumLegalParts = TTI.getNumberOfParts(VectorTy);
3296 if (!NumLegalParts)
3297 return false;
3298 if (VF.isScalable()) {
3299 // <vscale x 1 x iN> is assumed to be profitable over iN because
3300 // scalable registers are a distinct register class from scalar
3301 // ones. If we ever find a target which wants to lower scalable
3302 // vectors back to scalars, we'll need to update this code to
3303 // explicitly ask TTI about the register class uses for each part.
3304 return NumLegalParts <= VF.getKnownMinValue();
3305 }
3306 // Two or more elements that share a register - are vectorized.
3307 return NumLegalParts < VF.getFixedValue();
3308 };
3309
3310 // If no def nor is a store, e.g., branches, continue - no value to check.
3311 if (R.getNumDefinedValues() == 0 &&
3313 continue;
3314 // For multi-def recipes, currently only interleaved loads, suffice to
3315 // check first def only.
3316 // For stores check their stored value; for interleaved stores suffice
3317 // the check first stored value only. In all cases this is the second
3318 // operand.
3319 VPValue *ToCheck =
3320 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
3321 Type *ScalarTy = ToCheck->getScalarType();
3322 if (!Visited.insert({ScalarTy}).second)
3323 continue;
3324 Type *WideTy = toVectorizedTy(ScalarTy, VF);
3325 if (any_of(getContainedTypes(WideTy), WillGenerateTargetVectors))
3326 return true;
3327 }
3328 }
3329
3330 return false;
3331}
3332
3333static bool hasReplicatorRegion(VPlan &Plan) {
3335 Plan.getVectorLoopRegion()->getEntry())),
3336 [](auto *VPRB) { return VPRB->isReplicator(); });
3337}
3338
3339/// Returns true if the VPlan contains a VPReductionPHIRecipe with
3340/// FindLast recurrence kind.
3341static bool hasFindLastReductionPhi(VPlan &Plan) {
3344 [](VPReductionPHIRecipe &RedPhi) {
3345 return RecurrenceDescriptor::isFindLastRecurrenceKind(
3346 RedPhi.getRecurrenceKind());
3347 });
3348}
3349
3350/// Determine how to lower the epilogue for the vector epilogue loop.
3351/// Check if there are any conflicts that prevent tail-folding the epilogue.
3352/// \return CM_EpilogueNotNeededFoldTail if epilogue tail-folding is possible,
3353/// otherwise CM_EpilogueAllowed.
3355 const LoopVectorizationCostModel &MainCM, const Loop *L,
3358 // Epilogue TF is only enabled when explicitly requested via command line.
3359 if (!EpilogueTailFoldingPolicy.getNumOccurrences() ||
3361 return CM_EpilogueAllowed;
3362
3365 "Options conflict, epilogue vectorization is disallowed while "
3366 "epilogue tail-folding allowed!",
3367 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
3368 return CM_EpilogueAllowed;
3369 }
3370
3371 if (!Hints.getWidth() || !hasForcedEpilogueVF()) {
3372 reportVectorizationInfo("For now, epilogue tail-folding can't be "
3373 "applied without forced main/epilogue loop VF",
3374 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
3375 return CM_EpilogueAllowed;
3376 }
3377
3379 reportVectorizationInfo("For now, epilogue tail-folding can't be applied "
3380 "when VF of the main loop <= VF of the epilogue",
3381 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
3382 return CM_EpilogueAllowed;
3383 }
3384
3385 if (!L->isInnermost()) {
3387 "Epilogue tail-folding is not supported for outer loop",
3388 "InvalidTailFoldedEpilogue", ORE, L);
3389 return CM_EpilogueAllowed;
3390 }
3391
3392 // If scalar epilogue is explicitly required, we can't apply TF.
3393 if (MainCM.requiresScalarEpilogue(/*IsVectorizing*/ true)) {
3395 "Epilogue tail-folding can't be applied because scalar epilogue is "
3396 "required. Fall back to a normal epilogue",
3397 "InvalidTailFoldedEpilogue", ORE, L);
3398 return CM_EpilogueAllowed;
3399 }
3400
3401 // If having epilogue is NOT allowed, then no epilogue to apply TF for.
3402 if (!MainCM.isEpilogueAllowed()) {
3403 reportVectorizationInfo("Not applying tail-folding to the epilogue, since "
3404 "no epilogue is allowed.",
3405 "InvalidTailFoldedEpilogue", ORE, L);
3406 return CM_EpilogueAllowed;
3407 }
3408
3409 if (L->getExitingBlock() != L->getLoopLatch() ||
3412 "Epilogue tail-folding is not supported yet for early-exit loops",
3413 "InvalidTailFoldedEpilogue", ORE, L);
3414 return CM_EpilogueAllowed;
3415 }
3416
3417 // The epilogue reuses the main loop's interleave groups, so it can't be
3418 // tail-folded if the target can't mask interleaved accesses.
3419 // TODO: Add support once the epilogue has its own IAI, separate from the main
3420 // loop's.
3421 if (MainCM.InterleaveInfo.hasGroups() &&
3424 "Epilogue tail-folding is not supported with interleaved accesses "
3425 "when masking them isn't supported",
3426 "InvalidTailFoldedEpilogue", ORE, L);
3427 return CM_EpilogueAllowed;
3428 }
3429
3432 "Epilogue tail-folding is not supported with alias masking",
3433 "InvalidTailFoldedEpilogue", ORE, L);
3434 return CM_EpilogueAllowed;
3435 }
3436
3437 if (!LVL.getReductionVars().empty()) {
3439 "Epilogue tail-folding is not supported with reductions",
3440 "InvalidTailFoldedEpilogue", ORE, L);
3441 return CM_EpilogueAllowed;
3442 }
3443
3444 if (!LVL.getFixedOrderRecurrences().empty()) {
3446 "Epilogue tail-folding is not supported with fixed-order recurrence",
3447 "InvalidTailFoldedEpilogue", ORE, L);
3448 return CM_EpilogueAllowed;
3449 }
3450
3451 // We can apply tail-folding on the vectorized epilogue loop.
3453}
3454
3456 const ElementCount VF, const unsigned IC) const {
3457 // FIXME: We need a much better cost-model to take different parameters such
3458 // as register pressure, code size increase and cost of extra branches into
3459 // account. For now we apply a very crude heuristic and only consider loops
3460 // with vectorization factors larger than a certain value.
3461
3462 // Allow the target to opt out.
3463 if (!TTI.preferEpilogueVectorization(VF * IC))
3464 return false;
3465
3466 unsigned MinVFThreshold = EpilogueVectorizationMinVF.getNumOccurrences() > 0
3468 : TTI.getEpilogueVectorizationMinVF();
3469 return estimateElementCount(VF * IC, getVScaleForTuning()) >= MinVFThreshold;
3470}
3471
3473 VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC,
3474 bool ScalarEpilogueAllowed) {
3476 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n");
3477 return nullptr;
3478 }
3479
3480 if (!ScalarEpilogueAllowed) {
3481 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because no "
3482 "epilogue is allowed.\n");
3483 return nullptr;
3484 }
3485
3486 if (vputils::findIncomingAliasMask(MainPlan)) {
3487 LLVM_DEBUG(
3488 dbgs()
3489 << "LEV: Epilogue vectorization not supported with alias masking.\n");
3490 return nullptr;
3491 }
3492
3493 // Not really a cost consideration, but check for unsupported cases here to
3494 // simplify the logic.
3495 if (!isCandidateForEpilogueVectorization(MainPlan)) {
3496 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because the loop "
3497 "is not a supported candidate.\n");
3498 return nullptr;
3499 }
3500
3501 if (hasForcedEpilogueVF()) {
3503 Config.getVScaleForTuning()) >=
3504 IC * estimateElementCount(MainLoopVF, Config.getVScaleForTuning())) {
3505 // Note that the main loop leaves IC * MainLoopVF iterations iff a scalar
3506 // epilogue is required, but then the epilogue loop also requires a scalar
3507 // epilogue.
3508 LLVM_DEBUG(dbgs() << "LEV: Forced epilogue VF results in dead epilogue "
3509 "vector loop, skipping vectorizing epilogue.\n");
3510 return nullptr;
3511 }
3512
3513 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n");
3515 std::unique_ptr<VPlan> Clone(
3517 Clone->setVF(EpilogueVectorizationForceVF);
3518 return Clone;
3519 }
3520
3521 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization forced factor is not "
3522 "viable.\n");
3523 return nullptr;
3524 }
3525
3526 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
3527 LLVM_DEBUG(
3528 dbgs() << "LEV: Epilogue vectorization skipped due to opt for size.\n");
3529 return nullptr;
3530 }
3531
3532 if (!Config.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
3533 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
3534 "this loop\n");
3535 return nullptr;
3536 }
3537
3538 // Check if a plan's vector loop processes fewer iterations than VF (e.g. when
3539 // interleave groups have been narrowed) narrowInterleaveGroups) and return
3540 // the adjusted, effective VF.
3541 using namespace VPlanPatternMatch;
3542 auto GetEffectiveVF = [](VPlan &Plan, ElementCount VF) -> ElementCount {
3543 auto *Exiting = Plan.getVectorLoopRegion()->getExitingBasicBlock();
3544 if (match(&Exiting->back(),
3545 m_BranchOnCount(m_Add(m_CanonicalIV(), m_Specific(&Plan.getUF())),
3546 m_VPValue())))
3547 return ElementCount::get(1, VF.isScalable());
3548 return VF;
3549 };
3550
3551 // Check if the main loop processes fewer than MainLoopVF elements per
3552 // iteration (e.g. due to narrowing interleave groups). Adjust MainLoopVF
3553 // as needed.
3554 MainLoopVF = GetEffectiveVF(MainPlan, MainLoopVF);
3555
3556 // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
3557 // the main loop handles 8 lanes per iteration. We could still benefit from
3558 // vectorizing the epilogue loop with VF=4.
3559 ElementCount EstimatedRuntimeVF = ElementCount::getFixed(
3560 estimateElementCount(MainLoopVF, Config.getVScaleForTuning()));
3561
3562 Type *TCType = Legal->getWidestInductionType();
3563 const SCEV *RemainingIterations = nullptr;
3564 unsigned MaxTripCount = 0;
3565 const SCEV *TC = vputils::getSCEVExprForVPValue(MainPlan.getTripCount(), PSE);
3566 assert(!isa<SCEVCouldNotCompute>(TC) && "Trip count SCEV must be computable");
3567 const SCEV *KnownMinTC;
3568 bool ScalableTC = match(TC, m_scev_c_Mul(m_SCEV(KnownMinTC), m_SCEVVScale()));
3569 bool ScalableRemIter = false;
3570 ScalarEvolution &SE = *PSE.getSE();
3571 // Use versions of TC and VF in which both are either scalable or fixed.
3572 if (ScalableTC == MainLoopVF.isScalable()) {
3573 ScalableRemIter = ScalableTC;
3574 RemainingIterations =
3575 SE.getURemExpr(TC, SE.getElementCount(TCType, MainLoopVF * IC));
3576 } else if (ScalableTC) {
3577 const SCEV *EstimatedTC = SE.getMulExpr(
3578 KnownMinTC,
3579 SE.getConstant(TCType, Config.getVScaleForTuning().value_or(1)));
3580 RemainingIterations = SE.getURemExpr(
3581 EstimatedTC, SE.getElementCount(TCType, MainLoopVF * IC));
3582 } else
3583 RemainingIterations =
3584 SE.getURemExpr(TC, SE.getElementCount(TCType, EstimatedRuntimeVF * IC));
3585
3586 // No iterations left to process in the epilogue.
3587 if (RemainingIterations->isZero())
3588 return nullptr;
3589
3590 if (MainLoopVF.isFixed()) {
3591 MaxTripCount = MainLoopVF.getFixedValue() * IC - 1;
3592 if (SE.isKnownPredicate(CmpInst::ICMP_ULT, RemainingIterations,
3593 SE.getConstant(TCType, MaxTripCount))) {
3594 MaxTripCount = SE.getUnsignedRangeMax(RemainingIterations).getZExtValue();
3595 }
3596 LLVM_DEBUG(dbgs() << "LEV: Maximum Trip Count for Epilogue: "
3597 << MaxTripCount << "\n");
3598 }
3599
3600 auto SkipVF = [&](const SCEV *VF, const SCEV *RemIter) -> bool {
3601 return SE.isKnownPredicate(CmpInst::ICMP_UGT, VF, RemIter);
3602 };
3604 VPlan *BestPlan = nullptr;
3605 for (auto &NextVF : ProfitableVFs) {
3606 // Skip candidate VFs without a corresponding VPlan.
3607 if (!hasPlanWithVF(NextVF.Width))
3608 continue;
3609
3610 VPlan &CurrentPlan = getPlanFor(NextVF.Width);
3611 ElementCount EffectiveVF = GetEffectiveVF(CurrentPlan, NextVF.Width);
3612 // Skip fixed vector VFs > than the estimated runtime VF, or any VF > than
3613 // the VF of the main loop.
3614 if ((!EffectiveVF.isScalable() && MainLoopVF.isScalable() &&
3615 ElementCount::isKnownGT(EffectiveVF, EstimatedRuntimeVF)) ||
3616 ElementCount::isKnownGT(EffectiveVF, MainLoopVF))
3617 continue;
3618
3619 // If EffectiveVF is greater than the number of remaining iterations, the
3620 // epilogue loop would be dead. Skip such factors. If the epilogue plan
3621 // also has narrowed interleave groups, use the effective VF since
3622 // the epilogue step will be reduced to its IC.
3623 // TODO: We should also consider comparing against a scalable
3624 // RemainingIterations when SCEV be able to evaluate non-canonical
3625 // vscale-based expressions.
3626 if (!ScalableRemIter) {
3627 // Handle the case where EffectiveVF and RemainingIterations are in
3628 // different numerical spaces.
3629 if (EffectiveVF.isScalable())
3630 EffectiveVF = ElementCount::getFixed(
3631 estimateElementCount(EffectiveVF, Config.getVScaleForTuning()));
3632 if (SkipVF(SE.getElementCount(TCType, EffectiveVF), RemainingIterations))
3633 continue;
3634 }
3635
3636 if (Result.Width.isScalar() ||
3637 isMoreProfitable(NextVF, Result, MaxTripCount,
3638 !MainPlan.hasTailFolded(),
3639 /*IsEpilogue*/ true)) {
3640 Result = NextVF;
3641 BestPlan = &CurrentPlan;
3642 }
3643 }
3644
3645 if (!BestPlan)
3646 return nullptr;
3647
3648 LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
3649 << Result.Width << "\n");
3650 std::unique_ptr<VPlan> Clone(BestPlan->duplicate());
3651 Clone->setVF(Result.Width);
3652 return Clone;
3653}
3654
3655unsigned
3657 InstructionCost LoopCost) {
3658 // -- The interleave heuristics --
3659 // We interleave the loop in order to expose ILP and reduce the loop overhead.
3660 // There are many micro-architectural considerations that we can't predict
3661 // at this level. For example, frontend pressure (on decode or fetch) due to
3662 // code size, or the number and capabilities of the execution ports.
3663 //
3664 // We use the following heuristics to select the interleave count:
3665 // 1. If the code has reductions, then we interleave to break the cross
3666 // iteration dependency.
3667 // 2. If the loop is really small, then we interleave to reduce the loop
3668 // overhead.
3669 // 3. We don't interleave if we think that we will spill registers to memory
3670 // due to the increased register pressure.
3671
3672 // Do not interleave tail-folded loops, as the overhead of multiple
3673 // instructions to calculate the predicate is likely not beneficial.
3674 // If an epilogue is not allowed for any other reason, do not interleave.
3675 if (!CM->isEpilogueAllowed())
3676 return 1;
3677
3680 LLVM_DEBUG(dbgs() << "LV: Loop requires variable-length step. "
3681 "Unroll factor forced to be 1.\n");
3682 return 1;
3683 }
3684
3685 // We used the distance for the interleave count.
3686 if (!Legal->isSafeForAnyVectorWidth())
3687 return 1;
3688
3689 // We don't attempt to perform interleaving for loops with uncountable early
3690 // exits because the VPInstruction::AnyOf code cannot currently handle
3691 // multiple parts.
3692 if (Plan.hasEarlyExit())
3693 return 1;
3694
3695 const bool HasReductions =
3698
3699 // FIXME: implement interleaving for FindLast transform correctly.
3700 if (hasFindLastReductionPhi(Plan))
3701 return 1;
3702
3703 VPRegisterUsage R = calculateRegisterUsageForPlan(Plan, {VF}, TTI)[0];
3704
3705 // If we did not calculate the cost for VF (because the user selected the VF)
3706 // then we calculate the cost of VF here.
3707 if (LoopCost == 0) {
3708 if (VF.isScalar())
3709 LoopCost = CM->expectedCost(VF);
3710 else
3711 LoopCost = cost(Plan, VF, &R);
3712 assert(LoopCost.isValid() && "Expected to have chosen a VF with valid cost");
3713
3714 // Loop body is free and there is no need for interleaving.
3715 if (LoopCost == 0)
3716 return 1;
3717 }
3718
3719 // We divide by these constants so assume that we have at least one
3720 // instruction that uses at least one register.
3721 for (auto &Pair : R.MaxLocalUsers) {
3722 Pair.second = std::max(Pair.second, 1U);
3723 }
3724
3725 // We calculate the interleave count using the following formula.
3726 // Subtract the number of loop invariants from the number of available
3727 // registers. These registers are used by all of the interleaved instances.
3728 // Next, divide the remaining registers by the number of registers that is
3729 // required by the loop, in order to estimate how many parallel instances
3730 // fit without causing spills. All of this is rounded down if necessary to be
3731 // a power of two. We want power of two interleave count to simplify any
3732 // addressing operations or alignment considerations.
3733 // We also want power of two interleave counts to ensure that the induction
3734 // variable of the vector loop wraps to zero, when tail is folded by masking;
3735 // this currently happens when OptForSize, in which case IC is set to 1 above.
3736 unsigned IC = UINT_MAX;
3737
3738 for (const auto &Pair : R.MaxLocalUsers) {
3739 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
3740 LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
3741 << " registers of "
3742 << TTI.getRegisterClassName(Pair.first)
3743 << " register class\n");
3744 if (VF.isScalar()) {
3745 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
3746 TargetNumRegisters = ForceTargetNumScalarRegs;
3747 } else {
3748 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
3749 TargetNumRegisters = ForceTargetNumVectorRegs;
3750 }
3751 unsigned MaxLocalUsers = Pair.second;
3752 unsigned LoopInvariantRegs = 0;
3753 if (R.LoopInvariantRegs.contains(Pair.first))
3754 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
3755
3756 unsigned TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
3757 MaxLocalUsers);
3758 // Don't count the induction variable as interleaved.
3760 TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
3761 std::max(1U, (MaxLocalUsers - 1)));
3762 }
3763
3764 IC = std::min(IC, TmpIC);
3765 }
3766
3767 // Clamp the interleave ranges to reasonable counts.
3768 bool HasUnorderedReductions =
3769 HasReductions &&
3772 [](VPReductionPHIRecipe &RedR) { return RedR.isOrdered(); });
3773 unsigned MaxInterleaveCount =
3774 TTI.getMaxInterleaveFactor(VF, HasUnorderedReductions);
3775 LLVM_DEBUG(dbgs() << "LV: MaxInterleaveFactor for the target is "
3776 << MaxInterleaveCount << "\n");
3777
3778 // Check if the user has overridden the max.
3779 if (VF.isScalar()) {
3780 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
3781 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
3782 } else {
3783 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
3784 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
3785 }
3786
3787 // Try to get the exact trip count, or an estimate based on profiling data or
3788 // ConstantMax from PSE, failing that.
3789 auto BestKnownTC =
3790 getSmallBestKnownTC(PSE, OrigLoop,
3791 /*CanUseConstantMax=*/true,
3792 /*CanExcludeZeroTrips=*/CM->isEpilogueAllowed());
3793
3794 // For fixed length VFs treat a scalable trip count as unknown.
3795 if (BestKnownTC && (BestKnownTC->isFixed() || VF.isScalable())) {
3796 // Re-evaluate trip counts and VFs to be in the same numerical space.
3797 unsigned AvailableTC =
3798 estimateElementCount(*BestKnownTC, Config.getVScaleForTuning());
3799 unsigned EstimatedVF =
3800 estimateElementCount(VF, Config.getVScaleForTuning());
3801
3802 // At least one iteration must be scalar when this constraint holds. So the
3803 // maximum available iterations for interleaving is one less.
3804 if (Plan.requiresScalarEpilogue())
3805 --AvailableTC;
3806
3807 unsigned InterleaveCountLB = bit_floor(std::max(
3808 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
3809
3810 if (getSmallConstantTripCount(PSE.getSE(), OrigLoop).isNonZero()) {
3811 // If the best known trip count is exact, we select between two
3812 // prospective ICs, where
3813 //
3814 // 1) the aggressive IC is capped by the trip count divided by VF
3815 // 2) the conservative IC is capped by the trip count divided by (VF * 2)
3816 //
3817 // The final IC is selected in a way that the epilogue loop trip count is
3818 // minimized while maximizing the IC itself, so that we either run the
3819 // vector loop at least once if it generates a small epilogue loop, or
3820 // else we run the vector loop at least twice.
3821
3822 unsigned InterleaveCountUB = bit_floor(std::max(
3823 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
3824 MaxInterleaveCount = InterleaveCountLB;
3825
3826 if (InterleaveCountUB != InterleaveCountLB) {
3827 unsigned TailTripCountUB =
3828 (AvailableTC % (EstimatedVF * InterleaveCountUB));
3829 unsigned TailTripCountLB =
3830 (AvailableTC % (EstimatedVF * InterleaveCountLB));
3831 // If both produce same scalar tail, maximize the IC to do the same work
3832 // in fewer vector loop iterations
3833 if (TailTripCountUB == TailTripCountLB)
3834 MaxInterleaveCount = InterleaveCountUB;
3835 }
3836 } else {
3837 // If trip count is an estimated compile time constant, limit the
3838 // IC to be capped by the trip count divided by VF * 2, such that the
3839 // vector loop runs at least twice to make interleaving seem profitable
3840 // when there is an epilogue loop present. Since exact Trip count is not
3841 // known we choose to be conservative in our IC estimate.
3842 MaxInterleaveCount = InterleaveCountLB;
3843 }
3844 }
3845
3846 assert(MaxInterleaveCount > 0 &&
3847 "Maximum interleave count must be greater than 0");
3848
3849 // Clamp the calculated IC to be between the 1 and the max interleave count
3850 // that the target and trip count allows.
3851 if (IC > MaxInterleaveCount)
3852 IC = MaxInterleaveCount;
3853 else
3854 // Make sure IC is greater than 0.
3855 IC = std::max(1u, IC);
3856
3857 assert(IC > 0 && "Interleave count must be greater than 0.");
3858
3859 // Interleave if we vectorized this loop and there is a reduction that could
3860 // benefit from interleaving.
3861 if (VF.isVector() && HasReductions) {
3862 LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
3863 return IC;
3864 }
3865
3866 // For any scalar loop that either requires runtime checks or tail-folding we
3867 // are better off leaving this to the unroller. Note that if we've already
3868 // vectorized the loop we will have done the runtime check and so interleaving
3869 // won't require further checks.
3870 bool ScalarInterleavingRequiresPredication =
3871 (VF.isScalar() && any_of(OrigLoop->blocks(), [this](BasicBlock *BB) {
3872 return Legal->blockNeedsPredication(BB);
3873 }));
3874 bool ScalarInterleavingRequiresRuntimePointerCheck =
3875 (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
3876
3877 // We want to interleave small loops in order to reduce the loop overhead and
3878 // potentially expose ILP opportunities.
3879 LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
3880 << "LV: IC is " << IC << '\n'
3881 << "LV: VF is " << VF << '\n');
3882 const bool AggressivelyInterleave =
3883 TTI.enableAggressiveInterleaving(HasReductions);
3884 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
3885 !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
3886 // We assume that the cost overhead is 1 and we use the cost model
3887 // to estimate the cost of the loop and interleave until the cost of the
3888 // loop overhead is about 5% of the cost of the loop.
3889 unsigned SmallIC = std::min(IC, (unsigned)llvm::bit_floor<uint64_t>(
3890 SmallLoopCost / LoopCost.getValue()));
3891
3892 // Interleave until store/load ports (estimated by max interleave count) are
3893 // saturated.
3894 unsigned NumStores = 0;
3895 unsigned NumLoads = 0;
3898 for (VPRecipeBase &R : *VPBB) {
3900 NumLoads++;
3901 continue;
3902 }
3904 NumStores++;
3905 continue;
3906 }
3907
3908 if (auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R)) {
3909 if (unsigned StoreOps = InterleaveR->getNumStoreOperands())
3910 NumStores += StoreOps;
3911 else
3912 NumLoads += InterleaveR->getNumDefinedValues();
3913 continue;
3914 }
3915 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
3916 NumLoads += isa<LoadInst>(RepR->getUnderlyingInstr());
3917 NumStores += isa<StoreInst>(RepR->getUnderlyingInstr());
3918 continue;
3919 }
3920 if (isa<VPHistogramRecipe>(&R)) {
3921 NumLoads++;
3922 NumStores++;
3923 continue;
3924 }
3925 }
3926 }
3927 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
3928 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
3929
3930 // There is little point in interleaving for reductions containing selects
3931 // and compares when VF=1 since it may just create more overhead than it's
3932 // worth for loops with small trip counts. This is because we still have to
3933 // do the final reduction after the loop.
3934 bool HasSelectCmpReductions =
3935 HasReductions &&
3938 [](VPReductionPHIRecipe &RedR) {
3939 return RecurrenceDescriptor::isAnyOfRecurrenceKind(
3940 RedR.getRecurrenceKind()) ||
3941 RecurrenceDescriptor::isFindIVRecurrenceKind(
3942 RedR.getRecurrenceKind());
3943 });
3944 if (HasSelectCmpReductions) {
3945 LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
3946 return 1;
3947 }
3948
3949 // If we have a scalar reduction (vector reductions are already dealt with
3950 // by this point), we can increase the critical path length if the loop
3951 // we're interleaving is inside another loop. For tree-wise reductions
3952 // set the limit to 2, and for ordered reductions it's best to disable
3953 // interleaving entirely.
3954 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
3955 bool HasOrderedReductions =
3958 [](VPReductionPHIRecipe &RedR) { return RedR.isOrdered(); });
3959 if (HasOrderedReductions) {
3960 LLVM_DEBUG(
3961 dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
3962 return 1;
3963 }
3964
3965 unsigned F = MaxNestedScalarReductionIC;
3966 SmallIC = std::min(SmallIC, F);
3967 StoresIC = std::min(StoresIC, F);
3968 LoadsIC = std::min(LoadsIC, F);
3969 }
3970
3972 std::max(StoresIC, LoadsIC) > SmallIC) {
3973 LLVM_DEBUG(
3974 dbgs() << "LV: Interleaving to saturate store or load ports.\n");
3975 return std::max(StoresIC, LoadsIC);
3976 }
3977
3978 // If there are scalar reductions and TTI has enabled aggressive
3979 // interleaving for reductions, we will interleave to expose ILP.
3980 if (VF.isScalar() && AggressivelyInterleave) {
3981 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
3982 // Interleave no less than SmallIC but not as aggressive as the normal IC
3983 // to satisfy the rare situation when resources are too limited.
3984 return std::max(IC / 2, SmallIC);
3985 }
3986
3987 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
3988 return SmallIC;
3989 }
3990
3991 // Interleave if this is a large loop (small loops are already dealt with by
3992 // this point) that could benefit from interleaving.
3993 if (AggressivelyInterleave) {
3994 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
3995 return IC;
3996 }
3997
3998 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
3999 return 1;
4000}
4001
4003 Instruction *I, ElementCount VF) const {
4004 // TODO: Cost model for emulated masked load/store is completely
4005 // broken. This hack guides the cost model to use an artificially
4006 // high enough value to practically disable vectorization with such
4007 // operations, except where previously deployed legality hack allowed
4008 // using very low cost values. This is to avoid regressions coming simply
4009 // from moving "masked load/store" check from legality to cost model.
4010 // Masked Load/Gather emulation was previously never allowed.
4011 // Limited number of Masked Store/Scatter emulation was allowed.
4013 "Expecting a scalar emulated instruction");
4014 return isa<LoadInst>(I) ||
4015 (isa<StoreInst>(I) &&
4016 NumPredStores > NumberOfStoresToPredicate);
4017}
4018
4020 assert(VF.isVector() && "Expected VF >= 2");
4021
4022 // If we've already collected the instructions to scalarize or the predicated
4023 // BBs after vectorization, there's nothing to do. Collection may already have
4024 // occurred if we have a user-selected VF and are now computing the expected
4025 // cost for interleaving.
4026 if (InstsToScalarize.contains(VF) ||
4027 PredicatedBBsAfterVectorization.contains(VF))
4028 return;
4029
4030 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
4031 // not profitable to scalarize any instructions, the presence of VF in the
4032 // map will indicate that we've analyzed it already.
4033 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
4034
4035 // Find all the instructions that are scalar with predication in the loop and
4036 // determine if it would be better to not if-convert the blocks they are in.
4037 // If so, we also record the instructions to scalarize.
4038 for (BasicBlock *BB : TheLoop->blocks()) {
4040 continue;
4041 for (Instruction &I : *BB)
4042 if (isScalarWithPredication(&I, VF)) {
4043 ScalarCostsTy ScalarCosts;
4044 // Do not apply discount logic for:
4045 // 1. Scalars after vectorization, as there will only be a single copy
4046 // of the instruction.
4047 // 2. Scalable VF, as that would lead to invalid scalarization costs.
4048 // 3. Emulated masked memrefs, if a hacked cost is needed.
4049 if (!isScalarAfterVectorization(&I, VF) && !VF.isScalable() &&
4051 computePredInstDiscount(&I, ScalarCosts, VF) >= 0) {
4052 for (const auto &[I, IC] : ScalarCosts)
4053 ScalarCostsVF.insert({I, IC});
4054 }
4055 // Remember that BB will remain after vectorization.
4056 PredicatedBBsAfterVectorization[VF].insert(BB);
4057 for (auto *Pred : predecessors(BB)) {
4058 if (Pred->getSingleSuccessor() == BB)
4059 PredicatedBBsAfterVectorization[VF].insert(Pred);
4060 }
4061 }
4062 }
4063}
4064
4065InstructionCost LoopVectorizationCostModel::computePredInstDiscount(
4066 Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
4067 assert(!isUniformAfterVectorization(PredInst, VF) &&
4068 "Instruction marked uniform-after-vectorization will be predicated");
4069
4070 // Initialize the discount to zero, meaning that the scalar version and the
4071 // vector version cost the same.
4072 InstructionCost Discount = 0;
4073
4074 // Holds instructions to analyze. The instructions we visit are mapped in
4075 // ScalarCosts. Those instructions are the ones that would be scalarized if
4076 // we find that the scalar version costs less.
4078
4079 // Returns true if the given instruction can be scalarized.
4080 auto CanBeScalarized = [&](Instruction *I) -> bool {
4081 // We only attempt to scalarize instructions forming a single-use chain
4082 // from the original predicated block that would otherwise be vectorized.
4083 // Although not strictly necessary, we give up on instructions we know will
4084 // already be scalar to avoid traversing chains that are unlikely to be
4085 // beneficial.
4086 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
4087 isScalarAfterVectorization(I, VF))
4088 return false;
4089
4090 // If the instruction is scalar with predication, it will be analyzed
4091 // separately. We ignore it within the context of PredInst.
4092 if (isScalarWithPredication(I, VF))
4093 return false;
4094
4095 // If any of the instruction's operands are uniform after vectorization,
4096 // the instruction cannot be scalarized. This prevents, for example, a
4097 // masked load from being scalarized.
4098 //
4099 // We assume we will only emit a value for lane zero of an instruction
4100 // marked uniform after vectorization, rather than VF identical values.
4101 // Thus, if we scalarize an instruction that uses a uniform, we would
4102 // create uses of values corresponding to the lanes we aren't emitting code
4103 // for. This behavior can be changed by allowing getScalarValue to clone
4104 // the lane zero values for uniforms rather than asserting.
4105 for (Use &U : I->operands())
4106 if (auto *J = dyn_cast<Instruction>(U.get()))
4107 if (isUniformAfterVectorization(J, VF))
4108 return false;
4109
4110 // Otherwise, we can scalarize the instruction.
4111 return true;
4112 };
4113
4114 // Compute the expected cost discount from scalarizing the entire expression
4115 // feeding the predicated instruction. We currently only consider expressions
4116 // that are single-use instruction chains.
4117 Worklist.push_back(PredInst);
4118 while (!Worklist.empty()) {
4119 Instruction *I = Worklist.pop_back_val();
4120
4121 // If we've already analyzed the instruction, there's nothing to do.
4122 if (ScalarCosts.contains(I))
4123 continue;
4124
4125 // Cannot scalarize fixed-order recurrence phis at the moment.
4126 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
4127 continue;
4128
4129 // Compute the cost of the vector instruction. Note that this cost already
4130 // includes the scalarization overhead of the predicated instruction.
4131 InstructionCost VectorCost = getInstructionCost(I, VF);
4132
4133 // Compute the cost of the scalarized instruction. This cost is the cost of
4134 // the instruction as if it wasn't if-converted and instead remained in the
4135 // predicated block. We will scale this cost by block probability after
4136 // computing the scalarization overhead.
4137 InstructionCost ScalarCost =
4138 VF.getFixedValue() * getInstructionCost(I, ElementCount::getFixed(1));
4139
4140 // Compute the scalarization overhead of needed insertelement instructions
4141 // and phi nodes.
4142 if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
4143 Type *WideTy = toVectorizedTy(I->getType(), VF);
4144 for (Type *VectorTy : getContainedTypes(WideTy)) {
4145 ScalarCost += TTI.getScalarizationOverhead(
4147 /*Insert=*/true,
4148 /*Extract=*/false, Config.CostKind);
4149 }
4150 ScalarCost += VF.getFixedValue() *
4151 TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
4152 }
4153
4154 // Compute the scalarization overhead of needed extractelement
4155 // instructions. For each of the instruction's operands, if the operand can
4156 // be scalarized, add it to the worklist; otherwise, account for the
4157 // overhead.
4158 for (Use &U : I->operands())
4159 if (auto *J = dyn_cast<Instruction>(U.get())) {
4160 assert(canVectorizeTy(J->getType()) &&
4161 "Instruction has non-scalar type");
4162 if (CanBeScalarized(J))
4163 Worklist.push_back(J);
4164 else if (needsExtract(J, VF)) {
4165 Type *WideTy = toVectorizedTy(J->getType(), VF);
4166 for (Type *VectorTy : getContainedTypes(WideTy)) {
4167 ScalarCost += TTI.getScalarizationOverhead(
4168 cast<VectorType>(VectorTy),
4169 APInt::getAllOnes(VF.getFixedValue()), /*Insert*/ false,
4170 /*Extract*/ true, Config.CostKind);
4171 }
4172 }
4173 }
4174
4175 // Scale the total scalar cost by block probability.
4176 ScalarCost /= getPredBlockCostDivisor(Config.CostKind, I->getParent());
4177
4178 // Compute the discount. A non-negative discount means the vector version
4179 // of the instruction costs more, and scalarizing would be beneficial.
4180 Discount += VectorCost - ScalarCost;
4181 ScalarCosts[I] = ScalarCost;
4182 }
4183
4184 return Discount;
4185}
4186
4189 assert(VF.isScalar() && "must only be called for scalar VFs");
4190
4191 // For each block.
4192 for (BasicBlock *BB : TheLoop->blocks()) {
4193 InstructionCost BlockCost;
4194
4195 // For each instruction in the old loop.
4196 for (Instruction &I : *BB) {
4197 // Skip ignored values.
4198 if (ValuesToIgnore.count(&I) ||
4199 (VF.isVector() && VecValuesToIgnore.count(&I)))
4200 continue;
4201
4203
4204 // Check if we should override the cost.
4205 if (C.isValid() && ForceTargetInstructionCost.getNumOccurrences() > 0)
4207
4208 BlockCost += C;
4209 LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF "
4210 << VF << " For instruction: " << I << '\n');
4211 }
4212
4213 // In the scalar loop, we may not always execute the predicated block, if it
4214 // is an if-else block. Thus, scale the block's cost by the probability of
4215 // executing it. getPredBlockCostDivisor will return 1 for blocks that are
4216 // only predicated by the header mask when folding the tail.
4217 Cost += BlockCost / getPredBlockCostDivisor(Config.CostKind, BB);
4218 }
4219
4220 return Cost;
4221}
4222
4223/// Gets the address access SCEV for Ptr, if it should be used for cost modeling
4224/// according to isAddressSCEVForCost.
4225///
4226/// This SCEV can be sent to the Target in order to estimate the address
4227/// calculation cost.
4229 Value *Ptr,
4231 const Loop *TheLoop) {
4232 const SCEV *Addr = PSE.getSCEV(Ptr);
4233 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), TheLoop) ? Addr
4234 : nullptr;
4235}
4236
4238LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
4239 ElementCount VF) {
4240 assert(VF.isVector() &&
4241 "Scalarization cost of instruction implies vectorization.");
4242 if (VF.isScalable())
4243 return InstructionCost::getInvalid();
4244
4245 Type *ValTy = getLoadStoreType(I);
4246 auto *SE = PSE.getSE();
4247
4248 unsigned AS = getLoadStoreAddressSpace(I);
4250 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
4251 // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
4252 // that it is being called from this specific place.
4253
4254 // Figure out whether the access is strided and get the stride value
4255 // if it's known in compile time
4256 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, PSE, TheLoop);
4257
4258 // Get the cost of the scalar memory instruction and address computation.
4260 VF.getFixedValue() *
4261 TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV, Config.CostKind);
4262
4263 // Don't pass *I here, since it is scalar but will actually be part of a
4264 // vectorized loop where the user of it is a vectorized instruction.
4266 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4267 Cost += VF.getFixedValue() *
4268 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
4269 AS, Config.CostKind, OpInfo);
4270
4271 // Get the overhead of the extractelement and insertelement instructions
4272 // we might create due to scalarization.
4274
4275 // If we have a predicated load/store, it will need extra i1 extracts and
4276 // conditional branches, but may not be executed for each vector lane. Scale
4277 // the cost by the probability of executing the predicated block.
4278 if (isPredicatedInst(I)) {
4279 Cost /= getPredBlockCostDivisor(Config.CostKind, I->getParent());
4280
4281 // Add the cost of an i1 extract and a branch
4282 auto *VecI1Ty =
4283 VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
4285 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4286 /*Insert=*/false, /*Extract=*/true, Config.CostKind);
4287 Cost += TTI.getCFInstrCost(Instruction::CondBr, Config.CostKind);
4288
4289 if (useEmulatedMaskMemRefHack(I, VF))
4290 // Artificially setting to a high enough value to practically disable
4291 // vectorization with such operations.
4292 Cost = 3000000;
4293 }
4294
4295 return Cost;
4296}
4297
4298InstructionCost LoopVectorizationCostModel::getConsecutiveMemOpCost(
4299 Instruction *I, ElementCount VF, InstWidening Kind) {
4300 assert((Kind == CM_Widen || Kind == CM_Widen_Reverse) &&
4301 "Expected a consecutive widening decision");
4302 Type *ValTy = getLoadStoreType(I);
4303 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4304 unsigned AS = getLoadStoreAddressSpace(I);
4305
4308 if (isMaskRequired(I)) {
4309 unsigned IID = I->getOpcode() == Instruction::Load
4310 ? Intrinsic::masked_load
4311 : Intrinsic::masked_store;
4313 MemIntrinsicCostAttributes(IID, VectorTy, Alignment, AS),
4314 Config.CostKind);
4315 } else {
4316 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4317 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
4318 Config.CostKind, OpInfo, I);
4319 }
4320
4321 if (Kind == CM_Widen_Reverse)
4323 VectorTy, Config.CostKind, {}, 0);
4324 return Cost;
4325}
4326
4328LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
4329 ElementCount VF) const {
4330 assert(isUniformMemOp(*I, VF));
4331
4332 Type *ValTy = getLoadStoreType(I);
4334 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4336 unsigned AS = getLoadStoreAddressSpace(I);
4337 if (isa<LoadInst>(I)) {
4338 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4339 Config.CostKind) +
4340 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
4341 Config.CostKind) +
4343 VectorTy, Config.CostKind);
4344 }
4345 StoreInst *SI = cast<StoreInst>(I);
4346
4347 bool IsLoopInvariantStoreValue = Legal->isInvariant(SI->getValueOperand());
4348 // TODO: We have existing tests that request the cost of extracting element
4349 // VF.getKnownMinValue() - 1 from a scalable vector. This does not represent
4350 // the actual generated code, which involves extracting the last element of
4351 // a scalable vector where the lane to extract is unknown at compile time.
4353 TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, Config.CostKind) +
4354 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
4355 Config.CostKind);
4356 if (!IsLoopInvariantStoreValue)
4357 Cost += TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
4358 VectorTy, Config.CostKind, 0);
4359 return Cost;
4360}
4361
4363LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
4364 ElementCount VF) const {
4365 Type *ValTy = getLoadStoreType(I);
4366 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4369 Type *PtrTy = Ptr->getType();
4370
4371 if (!isUniform(Ptr, VF))
4372 PtrTy = toVectorTy(PtrTy, VF);
4373
4374 unsigned IID = I->getOpcode() == Instruction::Load
4375 ? Intrinsic::masked_gather
4376 : Intrinsic::masked_scatter;
4377 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4378 Config.CostKind) +
4380 MemIntrinsicCostAttributes(IID, VectorTy, Ptr, isMaskRequired(I),
4381 Alignment, I),
4382 Config.CostKind);
4383}
4384
4386LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
4387 ElementCount VF) const {
4388 const auto *Group = getInterleavedAccessGroup(I);
4389 assert(Group && "Fail to get an interleaved access group.");
4390
4391 Instruction *InsertPos = Group->getInsertPos();
4392 Type *ValTy = getLoadStoreType(InsertPos);
4393 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4394 unsigned AS = getLoadStoreAddressSpace(InsertPos);
4395
4396 unsigned InterleaveFactor = Group->getFactor();
4397 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4398
4399 // Holds the indices of existing members in the interleaved group.
4400 SmallVector<unsigned, 4> Indices;
4401 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4402 if (Group->getMember(IF))
4403 Indices.push_back(IF);
4404
4405 // Calculate the cost of the whole interleaved group.
4406 bool UseMaskForGaps =
4407 (Group->requiresScalarEpilogue() && !isEpilogueAllowed()) ||
4408 (isa<StoreInst>(I) && !Group->isFull());
4410 InsertPos->getOpcode(), WideVecTy, Group->getFactor(), Indices,
4411 Group->getAlign(), AS, Config.CostKind, isMaskRequired(I),
4412 UseMaskForGaps);
4413
4414 if (Group->isReverse()) {
4415 // TODO: Add support for reversed masked interleaved access.
4416 assert(!isMaskRequired(I) &&
4417 "Reverse masked interleaved access not supported.");
4418 Cost += Group->getNumMembers() *
4420 VectorTy, Config.CostKind, {}, 0);
4421 }
4422 return Cost;
4423}
4424
4426LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
4427 ElementCount VF) {
4428 // Calculate scalar cost only. Vectorization cost should be ready at this
4429 // moment.
4430 if (VF.isScalar()) {
4431 Type *ValTy = getLoadStoreType(I);
4434 unsigned AS = getLoadStoreAddressSpace(I);
4435
4436 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4437 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4438 Config.CostKind) +
4439 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
4440 Config.CostKind, OpInfo, I);
4441 }
4442 return getWideningCost(I, VF);
4443}
4444
4446LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
4447 ElementCount VF) const {
4448
4449 // There is no mechanism yet to create a scalable scalarization loop,
4450 // so this is currently Invalid.
4451 if (VF.isScalable())
4452 return InstructionCost::getInvalid();
4453
4454 if (VF.isScalar())
4455 return 0;
4456
4458 Type *RetTy = toVectorizedTy(I->getType(), VF);
4459 if (!RetTy->isVoidTy() &&
4461
4463 if (isa<LoadInst>(I))
4464 VIC = TTI::VectorInstrContext::Load;
4465 else if (isa<StoreInst>(I))
4466 VIC = TTI::VectorInstrContext::Store;
4467
4468 for (Type *VectorTy : getContainedTypes(RetTy)) {
4471 /*Insert=*/true, /*Extract=*/false, Config.CostKind,
4472 /*ForPoisonSrc=*/true, {}, VIC);
4473 }
4474 }
4475
4476 // Some targets keep addresses scalar.
4478 return Cost;
4479
4480 // Some targets support efficient element stores.
4482 return Cost;
4483
4484 // Collect operands to consider.
4485 CallInst *CI = dyn_cast<CallInst>(I);
4486 Instruction::op_range Ops = CI ? CI->args() : I->operands();
4487
4488 // Skip operands that do not require extraction/scalarization and do not incur
4489 // any overhead.
4491 for (auto *V : filterExtractingOperands(Ops, VF))
4492 Tys.push_back(maybeVectorizeType(V->getType(), VF));
4493
4495 ? TTI::VectorInstrContext::Store
4497 return Cost +
4498 TTI.getOperandsScalarizationOverhead(Tys, Config.CostKind, OperandVIC);
4499}
4500
4502 if (VF.isScalar())
4503 return;
4504
4505 // TODO: We should generate better code and update the cost model for
4506 // predicated uniform stores. Today they are treated as any other
4507 // predicated store (see added test cases in
4508 // invariant-store-vectorization.ll).
4509 NumPredStores = 0;
4510 for (BasicBlock *BB : TheLoop->blocks())
4511 for (Instruction &I : *BB)
4513 ++NumPredStores;
4514
4515 for (BasicBlock *BB : TheLoop->blocks()) {
4516 // For each instruction in the old loop.
4517 for (Instruction &I : *BB) {
4519 if (!Ptr)
4520 continue;
4521
4522 LLVM_DEBUG(dbgs() << "LV: Memory widening: calculating best strategy for "
4523 << I << '\n');
4524 if (isUniformMemOp(I, VF)) {
4525 auto IsLegalToScalarize = [&]() {
4526 if (!VF.isScalable())
4527 // Scalarization of fixed length vectors "just works".
4528 return true;
4529
4530 // We have dedicated lowering for unpredicated uniform loads and
4531 // stores. Note that even with tail folding we know that at least
4532 // one lane is active (i.e. generalized predication is not possible
4533 // here), and the logic below depends on this fact.
4534 if (!foldTailByMasking())
4535 return true;
4536
4537 // For scalable vectors, a uniform memop load is always
4538 // uniform-by-parts and we know how to scalarize that.
4539 if (isa<LoadInst>(I))
4540 return true;
4541
4542 // A uniform store isn't neccessarily uniform-by-part
4543 // and we can't assume scalarization.
4544 auto &SI = cast<StoreInst>(I);
4545 return TheLoop->isLoopInvariant(SI.getValueOperand());
4546 };
4547
4548 const InstructionCost GatherScatterCost =
4549 isLegalGatherOrScatter(&I, VF) ? getGatherScatterCost(&I, VF)
4551
4552 // Load: Scalar load + broadcast
4553 // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
4554 // FIXME: This cost is a significant under-estimate for tail folded
4555 // memory ops.
4556 const InstructionCost ScalarizationCost =
4557 IsLegalToScalarize() ? getUniformMemOpCost(&I, VF)
4559
4560 // Choose better solution for the current VF, Note that Invalid
4561 // costs compare as maximumal large. If both are invalid, we get
4562 // scalable invalid which signals a failure and a vectorization abort.
4563 LLVM_DEBUG(dbgs() << "LV: Memory widening: uniform memory op has "
4564 "GatherScatterCost = "
4565 << GatherScatterCost << ", ScalarizationCost = "
4566 << ScalarizationCost << '\n');
4567 if (GatherScatterCost < ScalarizationCost)
4568 setWideningDecision(&I, VF, CM_GatherScatter, GatherScatterCost);
4569 else
4570 setWideningDecision(&I, VF, CM_Scalarize, ScalarizationCost);
4571 continue;
4572 }
4573
4574 // We assume that widening is the best solution when possible.
4575 if (std::optional<InstWidening> Decision =
4577 InstructionCost WidenCost = getConsecutiveMemOpCost(&I, VF, *Decision);
4578 LLVM_DEBUG(
4579 dbgs() << "LV: Memory widening: can be widened normally with cost "
4580 << WidenCost << '\n');
4581 setWideningDecision(&I, VF, *Decision, WidenCost);
4582 continue;
4583 }
4584
4585 // Choose between Interleaving, Gather/Scatter or Scalarization.
4587 unsigned NumAccesses = 1;
4588 if (isAccessInterleaved(&I)) {
4589 const auto *Group = getInterleavedAccessGroup(&I);
4590 assert(Group && "Fail to get an interleaved access group.");
4591
4592 // Make one decision for the whole group.
4593 if (getWideningDecision(&I, VF) != CM_Unknown)
4594 continue;
4595
4596 NumAccesses = Group->getNumMembers();
4598 InterleaveCost = getInterleaveGroupCost(&I, VF);
4599 }
4600
4601 InstructionCost GatherScatterCost =
4603 ? getGatherScatterCost(&I, VF) * NumAccesses
4605
4606 InstructionCost ScalarizationCost =
4607 getMemInstScalarizationCost(&I, VF) * NumAccesses;
4608
4609 // Choose better solution for the current VF,
4610 // write down this decision and use it during vectorization.
4612 InstWidening Decision;
4613 if (InterleaveCost <= GatherScatterCost &&
4614 InterleaveCost < ScalarizationCost) {
4615 Decision = CM_Interleave;
4616 Cost = InterleaveCost;
4617 } else if (GatherScatterCost < ScalarizationCost) {
4618 Decision = CM_GatherScatter;
4619 Cost = GatherScatterCost;
4620 } else {
4621 Decision = CM_Scalarize;
4622 Cost = ScalarizationCost;
4623 }
4624 LLVM_DEBUG(
4625 dbgs() << "LV: Memory widening: InterleaveCost = " << InterleaveCost
4626 << ", GatherScatterCost = " << GatherScatterCost
4627 << ", ScalarizationCost = " << ScalarizationCost << '\n');
4628
4629 // If the instructions belongs to an interleave group, the whole group
4630 // receives the same decision. The whole group receives the cost, but
4631 // the cost will actually be assigned to one instruction.
4632 if (const auto *Group = getInterleavedAccessGroup(&I)) {
4633 if (Decision == CM_Scalarize) {
4634 for (Instruction *I : Group->members())
4635 setWideningDecision(I, VF, Decision,
4636 getMemInstScalarizationCost(I, VF));
4637 } else {
4638 setWideningDecision(Group, VF, Decision, Cost);
4639 }
4640 } else
4641 setWideningDecision(&I, VF, Decision, Cost);
4642 }
4643 }
4644
4645 // Make sure that any load of address and any other address computation
4646 // remains scalar unless there is gather/scatter support. This avoids
4647 // inevitable extracts into address registers, and also has the benefit of
4648 // activating LSR more, since that pass can't optimize vectorized
4649 // addresses.
4650 if (TTI.prefersVectorizedAddressing())
4651 return;
4652
4653 // Start with all scalar pointer uses.
4655 for (BasicBlock *BB : TheLoop->blocks())
4656 for (Instruction &I : *BB) {
4657 Instruction *PtrDef =
4659 if (PtrDef && TheLoop->contains(PtrDef) &&
4661 AddrDefs.insert(PtrDef);
4662 }
4663
4664 // Add all instructions used to generate the addresses.
4666 append_range(Worklist, AddrDefs);
4667 while (!Worklist.empty()) {
4668 Instruction *I = Worklist.pop_back_val();
4669 for (auto &Op : I->operands())
4670 if (auto *InstOp = dyn_cast<Instruction>(Op))
4671 if (TheLoop->contains(InstOp) && !isa<PHINode>(InstOp) &&
4672 AddrDefs.insert(InstOp))
4673 Worklist.push_back(InstOp);
4674 }
4675
4676 auto UpdateMemOpUserCost = [this, VF](LoadInst *LI) {
4677 // If there are direct memory op users of the newly scalarized load,
4678 // their cost may have changed because there's no scalarization
4679 // overhead for the operand. Update it.
4680 for (User *U : LI->users()) {
4682 continue;
4684 continue;
4685 auto UI = cast<Instruction>(U);
4686 LLVM_DEBUG(
4687 dbgs() << "LV: Memory widening: updating decision for load user "
4688 << *UI << '\n');
4690 UI, VF, CM_Scalarize,
4691 getMemInstScalarizationCost(cast<Instruction>(U), VF));
4692 }
4693 };
4694 for (auto *I : AddrDefs) {
4695 if (isa<LoadInst>(I)) {
4696 // Setting the desired widening decision should ideally be handled in
4697 // by cost functions, but since this involves the task of finding out
4698 // if the loaded register is involved in an address computation, it is
4699 // instead changed here when we know this is the case.
4700 InstWidening Decision = getWideningDecision(I, VF);
4701 if (!isPredicatedInst(I) &&
4702 (Decision == CM_Widen || Decision == CM_Widen_Reverse ||
4703 (!isUniformMemOp(*I, VF) && Decision == CM_Scalarize))) {
4704 // Scalarize a widened load of address or update the cost of a scalar
4705 // load of an address.
4706 LLVM_DEBUG(dbgs() << "LV: Memory widening: updating decision for load "
4707 << *I << '\n');
4709 I, VF, CM_Scalarize,
4710 (VF.getKnownMinValue() *
4711 getMemoryInstructionCost(I, ElementCount::getFixed(1))));
4712 UpdateMemOpUserCost(cast<LoadInst>(I));
4713 } else if (const auto *Group = getInterleavedAccessGroup(I)) {
4714 // Scalarize all members of this interleaved group when any member
4715 // is used as an address. The address-used load skips scalarization
4716 // overhead, other members include it.
4717 for (Instruction *Member : Group->members()) {
4718 InstructionCost Cost = AddrDefs.contains(Member)
4719 ? (VF.getKnownMinValue() *
4720 getMemoryInstructionCost(
4721 Member, ElementCount::getFixed(1)))
4722 : getMemInstScalarizationCost(Member, VF);
4723 LLVM_DEBUG(
4724 dbgs()
4725 << "LV: Memory widening: updating decision for interleave member "
4726 << *Member << '\n');
4728 UpdateMemOpUserCost(cast<LoadInst>(Member));
4729 }
4730 }
4731 } else {
4732 // Cannot scalarize fixed-order recurrence phis at the moment.
4733 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
4734 continue;
4735
4736 // Make sure I gets scalarized and a cost estimate without
4737 // scalarization overhead.
4738 ForcedScalars[VF].insert(I);
4739 }
4740 }
4741}
4742
4744 if (!Legal->isInvariant(Op))
4745 return false;
4746 // Consider Op invariant, if it or its operands aren't predicated
4747 // instruction in the loop. In that case, it is not trivially hoistable.
4748 auto *OpI = dyn_cast<Instruction>(Op);
4749 return !OpI || !TheLoop->contains(OpI) ||
4750 (!isPredicatedInst(OpI) &&
4751 (!isa<PHINode>(OpI) || OpI->getParent() != TheLoop->getHeader()) &&
4752 all_of(OpI->operands(),
4753 [this](Value *Op) { return shouldConsiderInvariant(Op); }));
4754}
4755
4758 ElementCount VF) {
4759 // If we know that this instruction will remain uniform, check the cost of
4760 // the scalar version.
4762 VF = ElementCount::getFixed(1);
4763
4764 if (VF.isVector() && isProfitableToScalarize(I, VF))
4765 return InstsToScalarize[VF][I];
4766
4767 // Forced scalars do not have any scalarization overhead.
4768 auto ForcedScalar = ForcedScalars.find(VF);
4769 if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
4770 auto InstSet = ForcedScalar->second;
4771 if (InstSet.count(I))
4773 VF.getKnownMinValue();
4774 }
4775
4776 const auto &MinBWs = Config.getMinimalBitwidths();
4777 uint64_t InstrMinBWs = MinBWs.lookup(I);
4778 Type *RetTy = I->getType();
4780 RetTy = IntegerType::get(RetTy->getContext(), InstrMinBWs);
4781 auto *SE = PSE.getSE();
4782
4783 Type *VectorTy;
4784 if (isScalarAfterVectorization(I, VF)) {
4785 [[maybe_unused]] auto HasSingleCopyAfterVectorization =
4786 [this](Instruction *I, ElementCount VF) -> bool {
4787 if (VF.isScalar())
4788 return true;
4789
4790 auto Scalarized = InstsToScalarize.find(VF);
4791 assert(Scalarized != InstsToScalarize.end() &&
4792 "VF not yet analyzed for scalarization profitability");
4793 return !Scalarized->second.count(I) &&
4794 llvm::all_of(I->users(), [&](User *U) {
4795 auto *UI = cast<Instruction>(U);
4796 return !Scalarized->second.count(UI);
4797 });
4798 };
4799
4800 // With the exception of GEPs and PHIs, after scalarization there should
4801 // only be one copy of the instruction generated in the loop. This is
4802 // because the VF is either 1, or any instructions that need scalarizing
4803 // have already been dealt with by the time we get here. As a result,
4804 // it means we don't have to multiply the instruction cost by VF.
4805 assert(I->getOpcode() == Instruction::GetElementPtr ||
4806 I->getOpcode() == Instruction::PHI ||
4807 (I->getOpcode() == Instruction::BitCast &&
4808 I->getType()->isPointerTy()) ||
4809 HasSingleCopyAfterVectorization(I, VF));
4810 VectorTy = RetTy;
4811 } else
4812 VectorTy = toVectorizedTy(RetTy, VF);
4813
4814 if (VF.isVector() && VectorTy->isVectorTy() &&
4815 !TTI.getNumberOfParts(VectorTy))
4817
4818 // TODO: We need to estimate the cost of intrinsic calls.
4819 switch (I->getOpcode()) {
4820 case Instruction::GetElementPtr:
4821 // We mark this instruction as zero-cost because the cost of GEPs in
4822 // vectorized code depends on whether the corresponding memory instruction
4823 // is scalarized or not. Therefore, we handle GEPs with the memory
4824 // instruction cost.
4825 return 0;
4826 case Instruction::UncondBr:
4827 case Instruction::CondBr: {
4828 // In cases of scalarized and predicated instructions, there will be VF
4829 // predicated blocks in the vectorized loop. Each branch around these
4830 // blocks requires also an extract of its vector compare i1 element.
4831 // Note that the conditional branch from the loop latch will be replaced by
4832 // a single branch controlling the loop, so there is no extra overhead from
4833 // scalarization.
4834 bool ScalarPredicatedBB = false;
4836 if (VF.isVector() && BI &&
4837 (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
4838 PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))) &&
4839 BI->getParent() != TheLoop->getLoopLatch())
4840 ScalarPredicatedBB = true;
4841
4842 if (ScalarPredicatedBB) {
4843 // Not possible to scalarize scalable vector with predicated instructions.
4844 if (VF.isScalable())
4846 // Return cost for branches around scalarized and predicated blocks.
4847 auto *VecI1Ty =
4849 return (TTI.getScalarizationOverhead(
4850 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4851 /*Insert*/ false, /*Extract*/ true, Config.CostKind) +
4852 (TTI.getCFInstrCost(Instruction::CondBr, Config.CostKind) *
4853 VF.getFixedValue()));
4854 }
4855
4856 if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
4857 // The back-edge branch will remain, as will all scalar branches.
4858 return TTI.getCFInstrCost(Instruction::UncondBr, Config.CostKind);
4859
4860 // This branch will be eliminated by if-conversion.
4861 return 0;
4862 // Note: We currently assume zero cost for an unconditional branch inside
4863 // a predicated block since it will become a fall-through, although we
4864 // may decide in the future to call TTI for all branches.
4865 }
4866 case Instruction::Switch: {
4867 if (VF.isScalar())
4868 return TTI.getCFInstrCost(Instruction::Switch, Config.CostKind);
4869 auto *Switch = cast<SwitchInst>(I);
4870 return Switch->getNumCases() *
4871 TTI.getCmpSelInstrCost(
4872 Instruction::ICmp,
4873 toVectorTy(Switch->getCondition()->getType(), VF),
4874 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
4875 CmpInst::ICMP_EQ, Config.CostKind);
4876 }
4877 case Instruction::PHI: {
4878 auto *Phi = cast<PHINode>(I);
4879
4880 // First-order recurrences are replaced by vector shuffles inside the loop.
4881 if (VF.isVector() && Legal->isFixedOrderRecurrence(Phi)) {
4882 return TTI.getShuffleCost(
4884 cast<VectorType>(VectorTy), Config.CostKind, {}, -1);
4885 }
4886
4887 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
4888 // converted into select instructions. We require N - 1 selects per phi
4889 // node, where N is the number of incoming values.
4890 if (VF.isVector() && Phi->getParent() != TheLoop->getHeader()) {
4891 Type *ResultTy = Phi->getType();
4892
4893 // All instructions in an Any-of reduction chain are narrowed to bool.
4894 // Check if that is the case for this phi node.
4895 auto *HeaderUser = cast_if_present<PHINode>(
4896 find_singleton<User>(Phi->users(), [this](User *U, bool) -> User * {
4897 auto *Phi = dyn_cast<PHINode>(U);
4898 if (Phi && Phi->getParent() == TheLoop->getHeader())
4899 return Phi;
4900 return nullptr;
4901 }));
4902 if (HeaderUser) {
4903 auto &ReductionVars = Legal->getReductionVars();
4904 auto Iter = ReductionVars.find(HeaderUser);
4905 if (Iter != ReductionVars.end() &&
4907 Iter->second.getRecurrenceKind()))
4908 ResultTy = Type::getInt1Ty(Phi->getContext());
4909 }
4910 return (Phi->getNumIncomingValues() - 1) *
4911 TTI.getCmpSelInstrCost(
4912 Instruction::Select, toVectorTy(ResultTy, VF),
4913 toVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
4914 CmpInst::BAD_ICMP_PREDICATE, Config.CostKind);
4915 }
4916
4917 // When tail folding with EVL, if the phi is part of an out of loop
4918 // reduction then it will be transformed into a wide vp_merge.
4919 if (VF.isVector() && foldTailWithEVL() &&
4920 Legal->getReductionVars().contains(Phi) &&
4921 !Config.isInLoopReduction(Phi)) {
4923 Intrinsic::vp_merge, toVectorTy(Phi->getType(), VF),
4924 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
4925 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind);
4926 }
4927
4928 return TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
4929 }
4930 case Instruction::UDiv:
4931 case Instruction::SDiv:
4932 case Instruction::URem:
4933 case Instruction::SRem:
4934 if (VF.isVector() && isPredicatedInst(I)) {
4935 const auto [ScalarCost, MaskedCost] = getDivRemSpeculationCost(I, VF);
4936 return isDivRemScalarWithPredication(ScalarCost, MaskedCost) ? ScalarCost
4937 : MaskedCost;
4938 }
4939 // We've proven all lanes safe to speculate, fall through.
4940 [[fallthrough]];
4941 case Instruction::Add:
4942 case Instruction::Sub: {
4943 auto Info = Legal->getHistogramInfo(I);
4944 if (Info && VF.isVector()) {
4945 const HistogramInfo *HGram = Info.value();
4946 // Assume that a non-constant update value (or a constant != 1) requires
4947 // a multiply, and add that into the cost.
4949 ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1));
4950 if (!RHS || RHS->getZExtValue() != 1)
4951 MulCost = TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
4952 Config.CostKind);
4953
4954 // Find the cost of the histogram operation itself.
4955 Type *PtrTy = VectorType::get(HGram->Load->getPointerOperandType(), VF);
4956 Type *ScalarTy = I->getType();
4957 Type *MaskTy = VectorType::get(Type::getInt1Ty(I->getContext()), VF);
4958 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
4959 Type::getVoidTy(I->getContext()),
4960 {PtrTy, ScalarTy, MaskTy});
4961
4962 // Add the costs together with the add/sub operation.
4963 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind) + MulCost +
4964 TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy,
4965 Config.CostKind);
4966 }
4967 [[fallthrough]];
4968 }
4969 case Instruction::FAdd:
4970 case Instruction::FSub:
4971 case Instruction::Mul:
4972 case Instruction::FMul:
4973 case Instruction::FDiv:
4974 case Instruction::FRem:
4975 case Instruction::Shl:
4976 case Instruction::LShr:
4977 case Instruction::AShr:
4978 case Instruction::And:
4979 case Instruction::Or:
4980 case Instruction::Xor: {
4981 // If we're speculating on the stride being 1, the multiplication may
4982 // fold away. We can generalize this for all operations using the notion
4983 // of neutral elements. (TODO)
4984 if (I->getOpcode() == Instruction::Mul &&
4985 ((TheLoop->isLoopInvariant(I->getOperand(0)) &&
4986 PSE.getSCEV(I->getOperand(0))->isOne()) ||
4987 (TheLoop->isLoopInvariant(I->getOperand(1)) &&
4988 PSE.getSCEV(I->getOperand(1))->isOne())))
4989 return 0;
4990
4991 // Certain instructions can be cheaper to vectorize if they have a constant
4992 // second vector operand. One example of this are shifts on x86.
4993 Value *Op2 = I->getOperand(1);
4994 if (!isa<Constant>(Op2) && TheLoop->isLoopInvariant(Op2) &&
4995 PSE.getSE()->isSCEVable(Op2->getType()) &&
4996 isa<SCEVConstant>(PSE.getSCEV(Op2))) {
4997 Op2 = cast<SCEVConstant>(PSE.getSCEV(Op2))->getValue();
4998 }
4999 auto Op2Info = TTI.getOperandInfo(Op2);
5000 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
5003
5004 SmallVector<const Value *, 4> Operands(I->operand_values());
5005 return TTI.getArithmeticInstrCost(
5006 I->getOpcode(), VectorTy, Config.CostKind,
5007 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
5008 Op2Info, Operands, I, TLI);
5009 }
5010 case Instruction::FNeg: {
5011 return TTI.getArithmeticInstrCost(
5012 I->getOpcode(), VectorTy, Config.CostKind,
5013 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
5014 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
5015 I->getOperand(0), I);
5016 }
5017 case Instruction::Select: {
5019 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5020 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5021
5022 const Value *Op0, *Op1;
5023 using namespace llvm::PatternMatch;
5024 if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
5025 match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
5026 // select x, y, false --> x & y
5027 // select x, true, y --> x | y
5028 const auto [Op1VK, Op1VP] = TTI::getOperandInfo(Op0);
5029 const auto [Op2VK, Op2VP] = TTI::getOperandInfo(Op1);
5030 assert(Op0->getType()->getScalarSizeInBits() == 1 &&
5031 Op1->getType()->getScalarSizeInBits() == 1);
5032
5033 return TTI.getArithmeticInstrCost(
5034 match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And,
5035 VectorTy, Config.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, {Op0, Op1},
5036 I);
5037 }
5038
5039 Type *CondTy = SI->getCondition()->getType();
5040 if (!ScalarCond)
5041 CondTy = VectorType::get(CondTy, VF);
5042
5044 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
5045 Pred = Cmp->getPredicate();
5046 return TTI.getCmpSelInstrCost(
5047 I->getOpcode(), VectorTy, CondTy, Pred, Config.CostKind,
5048 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
5049 }
5050 case Instruction::ICmp:
5051 case Instruction::FCmp: {
5052 Type *ValTy = I->getOperand(0)->getType();
5053
5055 [[maybe_unused]] Instruction *Op0AsInstruction =
5056 dyn_cast<Instruction>(I->getOperand(0));
5057 assert((!canTruncateToMinimalBitwidth(Op0AsInstruction, VF) ||
5058 InstrMinBWs == MinBWs.lookup(Op0AsInstruction)) &&
5059 "if both the operand and the compare are marked for "
5060 "truncation, they must have the same bitwidth");
5061 ValTy = IntegerType::get(ValTy->getContext(), InstrMinBWs);
5062 }
5063
5064 VectorTy = toVectorTy(ValTy, VF);
5065 return TTI.getCmpSelInstrCost(
5066 I->getOpcode(), VectorTy, CmpInst::makeCmpResultType(VectorTy),
5067 cast<CmpInst>(I)->getPredicate(), Config.CostKind,
5068 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
5069 }
5070 case Instruction::Store:
5071 case Instruction::Load: {
5072 ElementCount Width = VF;
5073 if (Width.isVector()) {
5074 InstWidening Decision = getWideningDecision(I, Width);
5075 assert(Decision != CM_Unknown &&
5076 "CM decision should be taken at this point");
5079 if (Decision == CM_Scalarize)
5080 Width = ElementCount::getFixed(1);
5081 }
5082 VectorTy = toVectorTy(getLoadStoreType(I), Width);
5083 return getMemoryInstructionCost(I, VF);
5084 }
5085 case Instruction::BitCast:
5086 if (I->getType()->isPointerTy())
5087 return 0;
5088 [[fallthrough]];
5089 case Instruction::ZExt:
5090 case Instruction::SExt:
5091 case Instruction::FPToUI:
5092 case Instruction::FPToSI:
5093 case Instruction::FPExt:
5094 case Instruction::PtrToInt:
5095 case Instruction::IntToPtr:
5096 case Instruction::SIToFP:
5097 case Instruction::UIToFP:
5098 case Instruction::Trunc:
5099 case Instruction::FPTrunc: {
5100 // Computes the CastContextHint from a Load/Store instruction.
5101 auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
5103 "Expected a load or a store!");
5104
5105 if (VF.isScalar() || !TheLoop->contains(I))
5107
5108 switch (getWideningDecision(I, VF)) {
5120 llvm_unreachable("Instr did not go through cost modelling?");
5123 }
5124
5125 llvm_unreachable("Unhandled case!");
5126 };
5127
5128 unsigned Opcode = I->getOpcode();
5130 // For Trunc, the context is the only user, which must be a StoreInst.
5131 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
5132 if (I->hasOneUse())
5133 if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
5134 CCH = ComputeCCH(Store);
5135 }
5136 // For Z/Sext, the context is the operand, which must be a LoadInst.
5137 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
5138 Opcode == Instruction::FPExt) {
5139 if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
5140 CCH = ComputeCCH(Load);
5141 }
5142
5143 // We optimize the truncation of induction variables having constant
5144 // integer steps. The cost of these truncations is the same as the scalar
5145 // operation.
5146 if (isOptimizableIVTruncate(I, VF)) {
5147 auto *Trunc = cast<TruncInst>(I);
5148 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
5149 Trunc->getSrcTy(), CCH, Config.CostKind,
5150 Trunc);
5151 }
5152
5153 Type *SrcScalarTy = I->getOperand(0)->getType();
5154 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
5155 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
5156 SrcScalarTy = IntegerType::get(SrcScalarTy->getContext(),
5157 MinBWs.lookup(Op0AsInstruction));
5158 Type *SrcVecTy =
5159 VectorTy->isVectorTy() ? toVectorTy(SrcScalarTy, VF) : SrcScalarTy;
5160
5162 // If the result type is <= the source type, there will be no extend
5163 // after truncating the users to the minimal required bitwidth.
5164 if (VectorTy->getScalarSizeInBits() <= SrcVecTy->getScalarSizeInBits() &&
5165 (I->getOpcode() == Instruction::ZExt ||
5166 I->getOpcode() == Instruction::SExt))
5167 return 0;
5168 }
5169
5170 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH,
5171 Config.CostKind, I);
5172 }
5173 case Instruction::Call:
5174 return getVectorCallCost(cast<CallInst>(I), VF);
5175 case Instruction::ExtractValue:
5176 return TTI.getInstructionCost(I, Config.CostKind);
5177 case Instruction::Alloca:
5178 // We cannot easily widen alloca to a scalable alloca, as
5179 // the result would need to be a vector of pointers.
5180 if (VF.isScalable())
5182 return TTI.getArithmeticInstrCost(Instruction::Mul, RetTy, Config.CostKind);
5183 case Instruction::Freeze:
5184 return TTI::TCC_Free;
5185 default:
5186 // This opcode is unknown. Assume that it is the same as 'mul'.
5187 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
5188 Config.CostKind);
5189 } // end of switch.
5190}
5191
5193 // Ignore ephemeral values.
5195
5196 SmallVector<Value *, 4> DeadInterleavePointerOps;
5198
5199 // If a scalar epilogue is required, users outside the loop won't use
5200 // live-outs from the vector loop but from the scalar epilogue. Ignore them if
5201 // that is the case.
5202 bool RequiresScalarEpilogue = requiresScalarEpilogue(true);
5203 auto IsLiveOutDead = [this, RequiresScalarEpilogue](User *U) {
5204 return RequiresScalarEpilogue &&
5205 !TheLoop->contains(cast<Instruction>(U)->getParent());
5206 };
5207
5209 DFS.perform(LI);
5210 for (BasicBlock *BB : reverse(make_range(DFS.beginRPO(), DFS.endRPO())))
5211 for (Instruction &I : reverse(*BB)) {
5212 if (VecValuesToIgnore.contains(&I) || ValuesToIgnore.contains(&I))
5213 continue;
5214
5215 // Add instructions that would be trivially dead and are only used by
5216 // values already ignored to DeadOps to seed worklist.
5218 all_of(I.users(), [this, IsLiveOutDead](User *U) {
5219 return VecValuesToIgnore.contains(U) ||
5220 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
5221 }))
5222 DeadOps.push_back(&I);
5223
5224 // For interleave groups, we only create a pointer for the start of the
5225 // interleave group. Queue up addresses of group members except the insert
5226 // position for further processing.
5227 if (isAccessInterleaved(&I)) {
5228 auto *Group = getInterleavedAccessGroup(&I);
5229 if (Group->getInsertPos() == &I)
5230 continue;
5231 Value *PointerOp = getLoadStorePointerOperand(&I);
5232 DeadInterleavePointerOps.push_back(PointerOp);
5233 }
5234
5235 // Queue branches for analysis. They are dead, if their successors only
5236 // contain dead instructions.
5237 if (isa<CondBrInst>(&I))
5238 DeadOps.push_back(&I);
5239 }
5240
5241 // Mark ops feeding interleave group members as free, if they are only used
5242 // by other dead computations.
5243 for (unsigned I = 0; I != DeadInterleavePointerOps.size(); ++I) {
5244 auto *Op = dyn_cast<Instruction>(DeadInterleavePointerOps[I]);
5245 if (!Op || !TheLoop->contains(Op) || any_of(Op->users(), [this](User *U) {
5246 Instruction *UI = cast<Instruction>(U);
5247 return !VecValuesToIgnore.contains(U) &&
5248 (!isAccessInterleaved(UI) ||
5249 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
5250 }))
5251 continue;
5252 VecValuesToIgnore.insert(Op);
5253 append_range(DeadInterleavePointerOps, Op->operands());
5254 }
5255
5256 // Mark ops that would be trivially dead and are only used by ignored
5257 // instructions as free.
5258 BasicBlock *Header = TheLoop->getHeader();
5259
5260 // Returns true if the block contains only dead instructions. Such blocks will
5261 // be removed by VPlan-to-VPlan transforms and won't be considered by the
5262 // VPlan-based cost model, so skip them in the legacy cost-model as well.
5263 auto IsEmptyBlock = [this](BasicBlock *BB) {
5264 return all_of(*BB, [this](Instruction &I) {
5265 return ValuesToIgnore.contains(&I) || VecValuesToIgnore.contains(&I) ||
5267 });
5268 };
5269 SmallPtrSet<Instruction *, 16> ProcessedDeadOps;
5270 for (unsigned I = 0; I != DeadOps.size(); ++I) {
5271 auto *Op = dyn_cast<Instruction>(DeadOps[I]);
5272
5273 // Check if the branch should be considered dead.
5274 if (auto *Br = dyn_cast_or_null<CondBrInst>(Op)) {
5275 BasicBlock *ThenBB = Br->getSuccessor(0);
5276 BasicBlock *ElseBB = Br->getSuccessor(1);
5277 // Don't considers branches leaving the loop for simplification.
5278 if (!TheLoop->contains(ThenBB) || !TheLoop->contains(ElseBB))
5279 continue;
5280 bool ThenEmpty = IsEmptyBlock(ThenBB);
5281 bool ElseEmpty = IsEmptyBlock(ElseBB);
5282 if ((ThenEmpty && ElseEmpty) ||
5283 (ThenEmpty && ThenBB->getSingleSuccessor() == ElseBB &&
5284 ElseBB->phis().empty()) ||
5285 (ElseEmpty && ElseBB->getSingleSuccessor() == ThenBB &&
5286 ThenBB->phis().empty())) {
5287 VecValuesToIgnore.insert(Br);
5288 DeadOps.push_back(Br->getCondition());
5289 }
5290 continue;
5291 }
5292
5293 // Skip any op that shouldn't be considered dead.
5294 if (!Op || !TheLoop->contains(Op) ||
5295 (isa<PHINode>(Op) && Op->getParent() == Header) ||
5297 any_of(Op->users(), [this, IsLiveOutDead](User *U) {
5298 return !VecValuesToIgnore.contains(U) &&
5299 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
5300 }))
5301 continue;
5302
5303 // If all of Op's users are in ValuesToIgnore, add it to ValuesToIgnore
5304 // which applies for both scalar and vector versions. Otherwise it is only
5305 // dead in vector versions, so only add it to VecValuesToIgnore.
5306 bool BecameScalarDead = false;
5307 if (all_of(Op->users(),
5308 [this](User *U) { return ValuesToIgnore.contains(U); }))
5309 BecameScalarDead = ValuesToIgnore.insert(Op).second;
5310
5311 VecValuesToIgnore.insert(Op);
5312 // Shared operands may be queued more than once. Propagate deadness once,
5313 // and again if an instruction previously dead only in the vector loop
5314 // becomes dead in the scalar loop too.
5315 if (ProcessedDeadOps.insert(Op).second || BecameScalarDead)
5316 append_range(DeadOps, Op->operands());
5317 }
5318
5319 // Ignore type-promoting instructions we identified during reduction
5320 // detection.
5321 for (const auto &Reduction : Legal->getReductionVars()) {
5322 const RecurrenceDescriptor &RedDes = Reduction.second;
5323 const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
5324 VecValuesToIgnore.insert_range(Casts);
5325 }
5326 // Ignore type-casting instructions we identified during induction
5327 // detection.
5328 for (const auto &Induction : Legal->getInductionVars()) {
5329 const InductionDescriptor &IndDes = Induction.second;
5330 VecValuesToIgnore.insert_range(IndDes.getCastInsts());
5331 }
5332}
5333
5334void LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
5335 CM->collectValuesToIgnore();
5336 Config.collectElementTypesForWidening(&CM->ValuesToIgnore);
5337
5338 FixedScalableVFPair MaxFactors = CM->computeMaxVF(UserVF, UserIC);
5339 if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
5340 return;
5341
5342 Config.collectInLoopReductions();
5343 // Cases that may be vectorized may be optimized by unit stride predicates.
5344 // TODO: Currently unit stride predicates are added unconditionally, even if
5345 // they are not used for the selected VF (e.g. when only interleaving).
5346 if (MaxFactors.FixedVF.isVector() || MaxFactors.ScalableVF.isVector())
5347 Legal->collectUnitStridePredicates();
5348
5349 auto VPlan1 = tryToBuildVPlan1();
5350 if (!VPlan1)
5351 return;
5352
5353 LLVM_DEBUG(dbgs() << "LV: VPlan created successfully. Loop can be "
5354 "vectorized.\n");
5355
5356 if (!OrigLoop->isInnermost()) {
5357 // For outer loops, computeMaxVF returns a single non-scalar VF; build a
5358 // plan for that VF only.
5359 ElementCount VF =
5360 MaxFactors.FixedVF ? MaxFactors.FixedVF : MaxFactors.ScalableVF;
5361 buildVPlans(*VPlan1, VF, VF);
5363 return;
5364 }
5365
5366 // Compute the minimal bitwidths required for integer operations in the loop
5367 // for later use by the cost model.
5368 Config.computeMinimalBitwidths();
5369
5370 // Invalidate interleave groups if all blocks of loop will be predicated.
5371 if (CM->blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
5373 LLVM_DEBUG(
5374 dbgs()
5375 << "LV: Invalidate all interleaved groups due to fold-tail by masking "
5376 "which requires masked-interleaved support.\n");
5377 if (CM->InterleaveInfo.invalidateGroups())
5378 // Invalidating interleave groups also requires invalidating all decisions
5379 // based on them, which includes widening decisions and uniform and scalar
5380 // values.
5381 CM->invalidateCostModelingDecisions();
5382 }
5383
5384 if (CM->foldTailByMasking())
5385 Legal->prepareToFoldTailByMasking();
5386
5387 ElementCount MaxUserVF =
5388 UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
5389 if (UserVF) {
5390 if (!ElementCount::isKnownLE(UserVF, MaxUserVF)) {
5392 "UserVF ignored because it may be larger than the maximal safe VF",
5393 "InvalidUserVF", ORE, OrigLoop);
5394 } else {
5396 "VF needs to be a power of two");
5397 // Collect the instructions (and their associated costs) that will be more
5398 // profitable to scalarize.
5399 CM->collectNonVectorizedAndSetWideningDecisions(UserVF);
5400 buildVPlans(*VPlan1, UserVF, UserVF);
5402 if (EpilogueUserVF.isVector() &&
5403 ElementCount::isKnownLT(EpilogueUserVF, UserVF)) {
5404 CM->collectNonVectorizedAndSetWideningDecisions(EpilogueUserVF);
5405 buildVPlans(*VPlan1, EpilogueUserVF, EpilogueUserVF);
5406 }
5407 if (!VPlans.empty() && VPlans.front()->getSingleVF() == UserVF) {
5408 // For scalar VF, skip VPlan cost check as VPlan cost is designed for
5409 // vector VFs only.
5410 if (UserVF.isScalar() ||
5411 cost(*VPlans.front(), UserVF, /*RU=*/nullptr).isValid()) {
5412 LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5414 return;
5415 }
5416 }
5417 VPlans.clear();
5418 reportVectorizationInfo("UserVF ignored because of invalid costs.",
5419 "InvalidCost", ORE, OrigLoop);
5420 }
5421 }
5422
5423 // Collect the Vectorization Factor Candidates.
5424 SmallVector<ElementCount> VFCandidates;
5425 for (auto VF = ElementCount::getFixed(1);
5426 ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
5427 VFCandidates.push_back(VF);
5428 for (auto VF = ElementCount::getScalable(1);
5429 ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
5430 VFCandidates.push_back(VF);
5431
5432 for (const auto &VF : VFCandidates) {
5433 // Collect Uniform and Scalar instructions after vectorization with VF.
5434 CM->collectNonVectorizedAndSetWideningDecisions(VF);
5435 }
5436
5437 buildVPlans(*VPlan1, ElementCount::getFixed(1), MaxFactors.FixedVF);
5438 buildVPlans(*VPlan1, ElementCount::getScalable(1), MaxFactors.ScalableVF);
5439
5441}
5442
5446 bool ReusePrintingSlotTracker)
5447 : TTI(Config.getTTI()), TLI(TLI), LLVMCtx(Plan.getContext()), CM(CM),
5449 L(Config.getLoop()) {
5450#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5451 if (ReusePrintingSlotTracker)
5452 PlanForSlotTracker = &Plan;
5453#endif
5454}
5455
5457 ElementCount VF) const {
5458 InstructionCost Cost = CM.getInstructionCost(UI, VF);
5459 if (Cost.isValid() && ForceTargetInstructionCost.getNumOccurrences())
5461 return Cost;
5462}
5463
5464bool VPCostContext::skipCostComputation(Instruction *UI, bool IsVector) const {
5465 return CM.ValuesToIgnore.contains(UI) ||
5466 (IsVector && CM.VecValuesToIgnore.contains(UI)) ||
5467 SkipCostComputation.contains(UI);
5468}
5469
5475
5477 return CM.isScalarWithPredication(I, VF) ||
5478 CM.isUniformAfterVectorization(I, VF) || CM.isForcedScalar(I, VF) ||
5479 (VF.isVector() && CM.isProfitableToScalarize(I, VF));
5480}
5481
5483 return CM.isMaskRequired(I);
5484}
5485
5489 return TC && TC->getValue().ule(VF.getKnownMinValue());
5490}
5491
5493LoopVectorizationPlanner::precomputeCosts(VPlan &Plan, ElementCount VF,
5494 VPCostContext &CostCtx) const {
5496
5497 // If the vector loop gets executed exactly once with the given VF, ignore the
5498 // costs of comparison and induction instructions, as they'll get simplified
5499 // away.
5500 // TODO: Remove this code after stepping away from the legacy cost model and
5501 // adding code to simplify VPlans before calculating their costs.
5502 auto TC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
5503 if (TC == VF && !Plan.hasTailFolded())
5504 addFullyUnrolledInstructionsToIgnore(OrigLoop, Legal->getInductionVars(),
5505 CostCtx.SkipCostComputation);
5506
5507 // Pre-compute the costs for branches except for the backedge, as the number
5508 // of replicate regions in a VPlan may not directly match the number of
5509 // branches, which would lead to different decisions.
5510 // TODO: Compute cost of branches for each replicate region in the VPlan,
5511 // which is more accurate than the legacy cost model.
5512 for (BasicBlock *BB : OrigLoop->blocks()) {
5513 if (CostCtx.skipCostComputation(BB->getTerminator(), VF.isVector()))
5514 continue;
5515 CostCtx.SkipCostComputation.insert(BB->getTerminator());
5516 if (BB == OrigLoop->getLoopLatch())
5517 continue;
5518 auto BranchCost = CostCtx.getLegacyCost(BB->getTerminator(), VF);
5519 Cost += BranchCost;
5520 }
5521
5522 // Don't apply special costs when instruction cost is forced to make sure the
5523 // forced cost is used for each recipe.
5524 if (ForceTargetInstructionCost.getNumOccurrences())
5525 return Cost;
5526
5527 // Pre-compute costs for instructions that are forced-scalar or profitable to
5528 // scalarize. For most such instructions, their scalarization costs are
5529 // accounted for here using the legacy cost model. However, some opcodes
5530 // are excluded from these precomputed scalarization costs and are instead
5531 // modeled later by the VPlan cost model (see UseVPlanCostModel below).
5532 for (Instruction *ForcedScalar : CostCtx.CM.ForcedScalars[VF]) {
5533 if (CostCtx.skipCostComputation(ForcedScalar, VF.isVector()))
5534 continue;
5535 CostCtx.SkipCostComputation.insert(ForcedScalar);
5536 InstructionCost ForcedCost = CostCtx.getLegacyCost(ForcedScalar, VF);
5537 LLVM_DEBUG({
5538 dbgs() << "Cost of " << ForcedCost << " for VF " << VF
5539 << ": forced scalar " << *ForcedScalar << "\n";
5540 });
5541 Cost += ForcedCost;
5542 }
5543
5544 // Don't apply legacy scalarization costs if nothing remains scalar &
5545 // predicated.
5546 if (!hasReplicatorRegion(Plan))
5547 return Cost;
5548
5549 auto UseVPlanCostModel = [](Instruction *I) -> bool {
5550 switch (I->getOpcode()) {
5551 case Instruction::SDiv:
5552 case Instruction::UDiv:
5553 case Instruction::SRem:
5554 case Instruction::URem:
5555 return true;
5556 default:
5557 return false;
5558 }
5559 };
5560 for (const auto &[Scalarized, ScalarCost] : CostCtx.CM.InstsToScalarize[VF]) {
5561 if (UseVPlanCostModel(Scalarized) ||
5562 CostCtx.skipCostComputation(Scalarized, VF.isVector()))
5563 continue;
5564 CostCtx.SkipCostComputation.insert(Scalarized);
5565 LLVM_DEBUG({
5566 dbgs() << "Cost of " << ScalarCost << " for VF " << VF
5567 << ": profitable to scalarize " << *Scalarized << "\n";
5568 });
5569 Cost += ScalarCost;
5570 }
5571
5572 return Cost;
5573}
5574
5575#ifndef NDEBUG
5576/// Returns the frequency with which \p VPBB executes, as recorded on its
5577/// recipes. All recipes of a block share the same frequency.
5578static std::optional<VPExecutionFrequency>
5580 if (VPBB->empty())
5581 return std::nullopt;
5582 return cast<VPInstruction>(&VPBB->front())->getExecutionFrequency();
5583}
5584#endif
5585
5586InstructionCost LoopVectorizationPlanner::cost(VPlan &Plan, ElementCount VF,
5587 VPRegisterUsage *RU) const {
5588 VPCostContext CostCtx(*TLI, Plan, *CM, Config,
5589 /*ReusePrintingSlotTracker=*/true);
5590 InstructionCost Cost = precomputeCosts(Plan, VF, CostCtx);
5591 LLVM_DEBUG(dbgs() << "Precomputed costs for VF " << VF << ": " << Cost
5592 << '\n');
5593
5594 // Now compute and add the VPlan-based cost.
5595 Cost += Plan.cost(VF, CostCtx);
5596
5597 // Add the cost of spills due to excess register usage
5598 if (RU && Config.shouldConsiderRegPressureForVF(VF)) {
5599 InstructionCost SpillCost =
5600 RU->spillCost(TTI, Config.CostKind, ForceTargetNumVectorRegs);
5601 LLVM_DEBUG(dbgs() << "Spill costs for VF " << VF << ": " << SpillCost
5602 << '\n');
5603 Cost += SpillCost;
5604 }
5605
5606#ifndef NDEBUG
5607 unsigned EstimatedWidth =
5608 estimateElementCount(VF, Config.getVScaleForTuning());
5609 LLVM_DEBUG(dbgs() << "Cost for VF " << VF << ": " << Cost
5610 << " (Estimated cost per lane: ");
5611 if (Cost.isValid()) {
5612 APFloat CostPerLane(APFloat::IEEEdouble());
5613 APFloat EstimatedWidthAsAPFloat(APFloat::IEEEdouble());
5614 (void)CostPerLane.convertFromAPInt(APInt(64, (uint64_t)Cost.getValue()),
5615 false, APFloat::rmTowardZero);
5616 (void)EstimatedWidthAsAPFloat.convertFromAPInt(
5617 APInt(64, (uint64_t)EstimatedWidth), false, APFloat::rmTowardZero);
5618 (void)CostPerLane.divide(EstimatedWidthAsAPFloat, APFloat::rmTowardZero);
5619
5620 SmallString<16> Str;
5621 CostPerLane.toString(Str, 3);
5622 LLVM_DEBUG(dbgs() << Str);
5623 } else /* No point dividing an invalid cost - it will still be invalid */
5624 LLVM_DEBUG(dbgs() << "Invalid");
5625 LLVM_DEBUG(dbgs() << ")\n");
5626#endif
5627 return Cost;
5628}
5629
5630std::pair<VectorizationFactor, VPlan *>
5632 if (VPlans.empty())
5633 return {VectorizationFactor::Disabled(), nullptr};
5634 // If there is a single VPlan with a single VF, return it directly.
5635 VPlan &FirstPlan = *VPlans[0];
5636
5637 ElementCount UserVF = Config.getHints().getWidth();
5638 if (VPlans.size() == 1) {
5639 // For outer loops, the plan has a single vector VF determined by the
5640 // heuristic.
5641 assert((FirstPlan.hasScalarVFOnly() || hasPlanWithVF(UserVF) ||
5642 FirstPlan.isOuterLoop()) &&
5643 "must have a single scalar VF, UserVF or an outer loop");
5644 return {VectorizationFactor(FirstPlan.getSingleVF(), 0, 0), &FirstPlan};
5645 }
5646
5647 if (hasPlanWithVF(UserVF) && hasForcedEpilogueVF() && VPlans.size() == 2) {
5648 assert(VPlans[0]->getSingleVF() == UserVF &&
5649 "expected second plan to be for the forced UserVF");
5650 assert(VPlans[1]->getSingleVF() == EpilogueVectorizationForceVF &&
5651 "expected first plan to be for the forced epilogue VF");
5652 return {VectorizationFactor(UserVF, 0, 0), VPlans[0].get()};
5653 }
5654
5655 LLVM_DEBUG(dbgs() << "LV: Computing best VF using cost kind: "
5656 << (Config.CostKind == TTI::TCK_RecipThroughput
5657 ? "Reciprocal Throughput\n"
5658 : Config.CostKind == TTI::TCK_Latency
5659 ? "Instruction Latency\n"
5660 : Config.CostKind == TTI::TCK_CodeSize ? "Code Size\n"
5661 : Config.CostKind == TTI::TCK_SizeAndLatency
5662 ? "Code Size and Latency\n"
5663 : "Unknown\n"));
5664
5666 assert(FirstPlan.hasVF(ScalarVF) &&
5667 "More than a single plan/VF w/o any plan having scalar VF");
5668
5669 // TODO: Compute scalar cost using VPlan-based cost model.
5670 InstructionCost ScalarCost = CM->expectedCost(ScalarVF);
5671 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ScalarCost << ".\n");
5672 VectorizationFactor ScalarFactor(ScalarVF, ScalarCost, ScalarCost);
5673 VectorizationFactor BestFactor = ScalarFactor;
5674
5675 bool ForceVectorization =
5676 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled;
5677 if (ForceVectorization) {
5678 // Ignore scalar width, because the user explicitly wants vectorization.
5679 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5680 // evaluation.
5681 BestFactor.Cost = InstructionCost::getMax();
5682 }
5683
5684 VPlan *PlanForBestVF = &FirstPlan;
5685 ElementCount ExactTC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
5686
5687 for (auto &P : VPlans) {
5688 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
5689 P->vectorFactors().end());
5690
5691 // For loops where the Trip Count is below the TailFoldingThreshold, only
5692 // consider the largest VF to result in at most one vector iteration, and at
5693 // most one scalar iteration.
5694 // FIXME: Encode this decision directly in LVPlanner.
5695 if (!ForceVectorization && P->hasScalarTail() && ExactTC.isFixed() &&
5696 ExactTC.getFixedValue() > 0 &&
5697 ExactTC.getFixedValue() <= TTI.getMinTripCountTailFoldingThreshold()) {
5698 VFs = VFs.take_back(1);
5699 }
5700
5702 bool ConsiderRegPressure = any_of(VFs, [this](ElementCount VF) {
5703 return Config.shouldConsiderRegPressureForVF(VF);
5704 });
5706 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI);
5707
5708 for (unsigned I = 0; I < VFs.size(); I++) {
5709 ElementCount VF = VFs[I];
5710 if (VF.isScalar())
5711 continue;
5712 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
5713 LLVM_DEBUG(
5714 dbgs()
5715 << "LV: Not considering vector loop of width " << VF
5716 << " because it will not generate any vector instructions.\n");
5717 continue;
5718 }
5719 if (Config.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
5720 LLVM_DEBUG(
5721 dbgs()
5722 << "LV: Not considering vector loop of width " << VF
5723 << " because it would cause replicated blocks to be generated,"
5724 << " which isn't allowed when optimizing for size.\n");
5725 continue;
5726 }
5727
5729 cost(*P, VF, ConsiderRegPressure ? &RUs[I] : nullptr);
5730 VectorizationFactor CurrentFactor(VF, Cost, ScalarCost);
5731
5732 if (isMoreProfitable(CurrentFactor, BestFactor, P->hasScalarTail())) {
5733 BestFactor = CurrentFactor;
5734 PlanForBestVF = P.get();
5735 }
5736
5737 // If profitable add it to ProfitableVF list.
5738 if (isMoreProfitable(CurrentFactor, ScalarFactor, P->hasScalarTail()))
5739 ProfitableVFs.push_back(CurrentFactor);
5740 }
5741 }
5742
5743 VPlan &BestPlan = *PlanForBestVF;
5744
5745 assert((BestFactor.Width.isScalar() || BestFactor.ScalarCost > 0) &&
5746 "when vectorizing, the scalar cost must be computed.");
5747
5748 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << BestFactor.Width << ".\n");
5749 return {BestFactor, &BestPlan};
5750}
5751
5753 Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
5755 std::unique_ptr<LoopVectorizationCostModel> CM, VFSelectionContext &Config,
5758 std::function<const BranchProbabilityInfo &()> GetBPI)
5759 : OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI), Legal(Legal),
5760 CM(std::move(CM)), Config(Config), IAI(IAI), PSE(PSE), ORE(ORE),
5761 GetBPI(GetBPI) {}
5762
5764
5766
5768 ElementCount BestVF, unsigned BestUF, VPlan &BestVPlan,
5770 EpilogueVectorizationKind EpilogueVecKind) {
5771 assert(BestVPlan.hasVF(BestVF) &&
5772 "Trying to execute plan with unsupported VF");
5773 assert(BestVPlan.hasUF(BestUF) &&
5774 "Trying to execute plan with unsupported UF");
5775 if (BestVPlan.hasEarlyExit())
5776 ++LoopsEarlyExitVectorized;
5777
5779 *PSE.getSE(), TTI, Config.CostKind, BestVF, BestUF);
5780 if (!BestVPlan.hasTailFolded() &&
5781 TTI.hasMultiVectorLoadStore(BestUF,
5784 BestUF, TTI);
5785 // TODO: Move to VPlan transform stage once the transition to the VPlan-based
5786 // cost model is complete for better cost estimates.
5787 RUN_VPLAN_PASS(VPlanTransforms::unrollByUF, BestVPlan, BestUF);
5791 bool HasBranchWeights =
5792 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator());
5793 if (HasBranchWeights) {
5794 std::optional<unsigned> VScale = Config.getVScaleForTuning();
5796 BestVPlan, BestVF, VScale);
5797 }
5798
5799 if (vputils::findIncomingAliasMask(BestVPlan)) {
5800 assert(BestVPlan.hasTailFolded() && "Expected tail folding to be enabled");
5802 *Legal->getRuntimePointerChecking()->getDiffChecks(),
5803 HasBranchWeights);
5804 ++LoopsPartialAliasVectorized;
5805 }
5806
5807 // Retrieving VectorPH now when it's easier while VPlan still has Regions.
5808 VPBasicBlock *VectorPH = cast<VPBasicBlock>(BestVPlan.getVectorPreheader());
5809
5811 BestVF, BestUF, PSE);
5812 RUN_VPLAN_PASS(VPlanTransforms::optimizeForVFAndUF, BestVPlan, BestVF, BestUF,
5813 PSE);
5815 // Check if scalar epilogue is required, before simplifying constant branches.
5816 const bool RequiresScalarEpilogue = BestVPlan.requiresScalarEpilogue();
5817 if (EpilogueVecKind == EpilogueVectorizationKind::None)
5819 /*OnlyLatches=*/false);
5820 if (BestVPlan.getEntry()->getSingleSuccessor() ==
5821 BestVPlan.getScalarPreheader()) {
5822 // TODO: The vector loop would be dead, should not even try to vectorize.
5823 ORE->emit([&]() {
5824 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationDead",
5825 OrigLoop->getStartLoc(),
5826 OrigLoop->getHeader())
5827 << "Created vector loop never executes due to insufficient trip "
5828 "count.";
5829 });
5831 }
5832
5834
5836 // Convert the exit condition to AVLNext == 0 for EVL tail folded loops.
5838 // Regions are dissolved after optimizing for VF and UF, which completely
5839 // removes unneeded loop regions first.
5840 const bool HasTailFolded = BestVPlan.hasTailFolded();
5842 // Expand BranchOnTwoConds after dissolution, when latch has direct access to
5843 // its successors.
5845 // Convert loops with variable-length stepping after regions are dissolved.
5847 // Remove dead back-edges for single-iteration loops with BranchOnCond(true).
5848 // Only process loop latches to avoid removing edges from the middle block,
5849 // which may be needed for epilogue vectorization.
5851 /*OnlyLatches=*/true);
5853 VectorPH);
5854 std::optional<uint64_t> MaxRuntimeStep = getMaxRuntimeElementCount(
5855 BestVF * BestUF, *OrigLoop->getHeader()->getParent());
5856
5857 assert((LI->getUniqueLatchExitBlock(*OrigLoop) || RequiresScalarEpilogue) &&
5858 "loops not exiting via the latch without required epilogue?");
5860 VectorPH, HasTailFolded, RequiresScalarEpilogue,
5861 &BestVPlan.getVFxUF(), MaxRuntimeStep);
5863 BestVF);
5864 // Limit expansions to VPInstruction to when not vectorizing the epilogue.
5865 // Currently this code path still relies on code re-using SCEVs expanded
5866 // directly to IR instructions.
5867 if (EpilogueVecKind == EpilogueVectorizationKind::None)
5869 *PSE.getSE());
5872 // Removing branches and incoming values may expose additional simplification
5873 // opportunities.
5875 /*OnlyLatches=*/EpilogueVecKind !=
5878 RUN_VPLAN_PASS(VPlanTransforms::simplifyKnownEVL, BestVPlan, BestVF, PSE);
5879
5880 // 0. Generate SCEV-dependent code in the entry, including TripCount, before
5881 // making any changes to the CFG.
5882 DenseMap<const SCEV *, Value *> ExpandedSCEVs =
5883 RUN_VPLAN_PASS(VPlanTransforms::expandSCEVs, BestVPlan, *PSE.getSE());
5884
5885 // Perform the actual loop transformation.
5886 VPTransformState State(&TTI, BestVF, LI, DT, ILV.AC, ILV.Builder, &BestVPlan,
5887 OrigLoop->getParentLoop());
5888
5889#ifdef EXPENSIVE_CHECKS
5890 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
5891#endif
5892
5893 // 1. Set up the skeleton for vectorization, including vector pre-header and
5894 // middle block. The vector loop is created during VPlan execution.
5895 State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
5896 if (VPBasicBlock *ScalarPH = BestVPlan.getScalarPreheader())
5897 replaceVPBBWithIRVPBB(ScalarPH, State.CFG.PrevBB->getSingleSuccessor(),
5898 &BestVPlan);
5900
5901 assert(verifyVPlanIsValid(BestVPlan) && "final VPlan is invalid");
5902
5903 // After vectorization, the exit blocks of the original loop will have
5904 // additional predecessors. Invalidate SCEVs for the exit phis in case SE
5905 // looked through single-entry phis.
5906 ScalarEvolution &SE = *PSE.getSE();
5907 for (VPIRBasicBlock *Exit : BestVPlan.getExitBlocks()) {
5908 if (!Exit->hasPredecessors())
5909 continue;
5910 for (VPRecipeBase &PhiR : Exit->phis())
5912 &cast<VPIRPhi>(PhiR).getIRPhi());
5913 }
5914
5915 // Query whether the target wants loops it vectorizes to remain eligible for
5916 // runtime unrolling. Do this here, on the original loop and before its SCEV
5917 // is forgotten below.
5919 TTI.getUnrollingPreferences(OrigLoop, SE, UP, ORE);
5920 bool UnrollVectorizedLoop = UP.UnrollVectorizedLoop;
5921
5922 // Forget the original loop and block dispositions.
5923 SE.forgetLoop(OrigLoop);
5925
5926 //===------------------------------------------------===//
5927 //
5928 // Notice: any optimization or new instruction that go
5929 // into the code below should also be implemented in
5930 // the cost-model.
5931 //
5932 //===------------------------------------------------===//
5933
5934 // Retrieve loop information before executing the plan, which may remove the
5935 // original loop, if it becomes unreachable.
5936 MDNode *LID = OrigLoop->getLoopID();
5937 unsigned OrigLoopInvocationWeight = 0;
5938 std::optional<unsigned> OrigAverageTripCount =
5939 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
5940
5941 BestVPlan.execute(&State);
5942
5943 // 2.6. Maintain Loop Hints
5944 // Keep all loop hints from the original loop on the vector loop (we'll
5945 // replace the vectorizer-specific hints below).
5946 VPBasicBlock *HeaderVPBB = vputils::getFirstLoopHeader(BestVPlan, State.VPDT);
5947 // Add metadata to disable runtime unrolling a scalar loop when there
5948 // are no runtime checks about strides and memory. A scalar loop that is
5949 // rarely used is not worth unrolling.
5950 bool DisableRuntimeUnroll = !ILV.RTChecks.hasChecks() && !BestVF.isScalar();
5952 HeaderVPBB ? LI->getLoopFor(State.CFG.VPBB2IRBB.lookup(HeaderVPBB))
5953 : nullptr,
5954 HeaderVPBB, BestVPlan,
5955 EpilogueVecKind == EpilogueVectorizationKind::Epilogue, LID,
5956 OrigAverageTripCount, OrigLoopInvocationWeight,
5957 estimateElementCount(BestVF * BestUF, Config.getVScaleForTuning()),
5958 DisableRuntimeUnroll, UnrollVectorizedLoop);
5959
5960 // 3. Fix the vectorized code: take care of header phi's, live-outs,
5961 // predication, updating analyses.
5962 ILV.fixVectorizedLoop(State);
5963
5964 // Wrap the generated blocks in VPIRBasicBlocks, so they can be used in the
5965 // epilogue plan.
5966 if (EpilogueVecKind == EpilogueVectorizationKind::MainLoop)
5968 vp_depth_first_shallow(BestVPlan.getEntry()))))
5969 if (!isa<VPIRBasicBlock>(VPBB))
5970 replaceVPBBWithIRVPBB(VPBB, State.CFG.VPBB2IRBB.at(VPBB), &BestVPlan);
5971
5972 return ExpandedSCEVs;
5973}
5974
5975//===--------------------------------------------------------------------===//
5976// EpilogueVectorizerEpilogueLoop
5977//===--------------------------------------------------------------------===//
5978
5979/// This function creates a new scalar preheader, using the previous one as
5980/// entry block to the epilogue VPlan. The minimum iteration check is being
5981/// represented in VPlan.
5983 BasicBlock *NewScalarPH = createScalarPreheader("vec.epilog.");
5984 BasicBlock *OriginalScalarPH = NewScalarPH->getSinglePredecessor();
5985 OriginalScalarPH->setName("vec.epilog.iter.check");
5986 VPIRBasicBlock *NewEntry = Plan.createVPIRBasicBlock(OriginalScalarPH);
5987 VPBasicBlock *OldEntry = Plan.getEntry();
5988 for (auto &R : make_early_inc_range(*OldEntry)) {
5989 // Skip moving VPIRInstructions (including VPIRPhis), which are unmovable by
5990 // defining.
5991 if (isa<VPIRInstruction>(&R))
5992 continue;
5993 R.moveBefore(*NewEntry, NewEntry->end());
5994 }
5995
5996 VPBlockUtils::reassociateBlocks(OldEntry, NewEntry);
5997
5999
6000 // Model the skeleton from the main vector loop in the epilogue plan.
6002 NewEntry);
6003
6004 return OriginalScalarPH;
6005}
6006
6008 return CM.isPredicatedInst(I);
6009}
6010
6012 return CM.TTI.prefersVectorizedAddressing();
6013}
6014
6016 VFRange &Range) {
6017 assert((VPI->getOpcode() == Instruction::Load ||
6018 VPI->getOpcode() == Instruction::Store) &&
6019 "Must be called with either a load or store");
6021
6022 auto WillWiden = [&](ElementCount VF) -> bool {
6024 CM.getWideningDecision(I, VF);
6026 "CM decision should be taken at this point.");
6028 return true;
6029 if (CM.isScalarAfterVectorization(I, VF) ||
6030 CM.isProfitableToScalarize(I, VF))
6031 return false;
6033 };
6034
6036 return nullptr;
6037
6038 // If a mask is not required, drop it - use unmasked version for safe loads.
6039 // TODO: Determine if mask is needed in VPlan.
6040 VPValue *Mask = CM.isMaskRequired(I) ? VPI->getMask() : nullptr;
6041
6042 // Determine if the pointer operand of the access is either consecutive or
6043 // reverse consecutive.
6045 CM.getWideningDecision(I, Range.Start);
6047 bool Consecutive =
6049
6050 VPValue *Ptr = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
6051 : VPI->getOperand(1);
6052 Builder.setInsertPoint(VPI);
6053 if (Consecutive) {
6054 Ptr = Builder.createConsecutiveVectorPointer(Ptr, getLoadStoreType(I),
6055 Reverse, VPI->getDebugLoc());
6056 }
6057
6058 if (Reverse && Mask)
6059 Mask = Builder.createNaryOp(VPInstruction::Reverse, Mask, I->getDebugLoc());
6060
6061 if (VPI->getOpcode() == Instruction::Load) {
6062 auto *Load = cast<LoadInst>(I);
6063 auto *LoadR = Builder.createWidenLoad(*Load, Ptr, Mask, Consecutive, *VPI,
6064 Load->getDebugLoc());
6065 if (Reverse)
6066 return Builder.createNaryOp(VPInstruction::Reverse, LoadR,
6067 LoadR->getDebugLoc());
6068 return LoadR;
6069 }
6070
6072 VPValue *StoredVal = VPI->getOperand(0);
6073 if (Reverse)
6074 StoredVal = Builder.createNaryOp(VPInstruction::Reverse, StoredVal,
6075 Store->getDebugLoc());
6076 return Builder.createWidenStore(*Store, Ptr, StoredVal, Mask, Consecutive,
6077 *VPI, Store->getDebugLoc());
6078}
6079
6080bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
6082 "Instruction should have been handled earlier");
6083 // Instruction should be widened, unless it is scalar after vectorization,
6084 // scalarization is profitable or it is predicated.
6085 auto WillScalarize = [this, I](ElementCount VF) -> bool {
6086 return CM.isScalarAfterVectorization(I, VF) ||
6087 CM.isProfitableToScalarize(I, VF) ||
6088 CM.isScalarWithPredication(I, VF);
6089 };
6091 Range);
6092}
6093
6094VPRecipeWithIRFlags *VPRecipeBuilder::tryToWiden(VPInstruction *VPI) {
6095 auto *I = VPI->getUnderlyingInstr();
6096 switch (VPI->getOpcode()) {
6097 default:
6098 return nullptr;
6099 case Instruction::SDiv:
6100 case Instruction::UDiv:
6101 case Instruction::SRem:
6102 case Instruction::URem:
6103 // If not provably safe, use a masked intrinsic.
6104 if (CM.isPredicatedInst(I))
6105 return new VPWidenIntrinsicRecipe(
6107 I->getType(), {}, {}, VPI->getDebugLoc());
6108 [[fallthrough]];
6109 case Instruction::Add:
6110 case Instruction::And:
6111 case Instruction::AShr:
6112 case Instruction::FAdd:
6113 case Instruction::FCmp:
6114 case Instruction::FDiv:
6115 case Instruction::FMul:
6116 case Instruction::FNeg:
6117 case Instruction::FRem:
6118 case Instruction::FSub:
6119 case Instruction::ICmp:
6120 case Instruction::LShr:
6121 case Instruction::Mul:
6122 case Instruction::Or:
6123 case Instruction::Select:
6124 case Instruction::Shl:
6125 case Instruction::Sub:
6126 case Instruction::Xor:
6127 case Instruction::Freeze:
6128 return new VPWidenRecipe(*I, VPI->operandsWithoutMask(), *VPI, *VPI,
6129 VPI->getDebugLoc());
6130 case Instruction::ExtractValue: {
6132 auto *EVI = cast<ExtractValueInst>(I);
6133 assert(EVI->getNumIndices() == 1 && "Expected one extractvalue index");
6134 unsigned Idx = EVI->getIndices()[0];
6135 NewOps.push_back(Plan.getConstantInt(32, Idx));
6136 return new VPWidenRecipe(*I, NewOps, *VPI, *VPI, VPI->getDebugLoc());
6137 }
6138 };
6139}
6140
6142 if (VPI->getOpcode() != Instruction::Store)
6143 return nullptr;
6144
6145 auto HistInfo =
6146 Legal->getHistogramInfo(cast<StoreInst>(VPI->getUnderlyingInstr()));
6147 if (!HistInfo)
6148 return nullptr;
6149
6150 const HistogramInfo *HI = *HistInfo;
6151 // FIXME: Support other operations.
6152 unsigned Opcode = HI->Update->getOpcode();
6153 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
6154 "Histogram update operation must be an Add or Sub");
6155
6157 // Bucket address.
6158 HGramOps.push_back(VPI->getOperand(1));
6159 // Increment value.
6160 HGramOps.push_back(Plan.getOrAddLiveIn(HI->Update->getOperand(1)));
6161
6162 // In case of predicated execution (due to tail-folding, or conditional
6163 // execution, or both), pass the relevant mask.
6164 if (CM.isMaskRequired(HI->Store))
6165 HGramOps.push_back(VPI->getMask());
6166
6167 return new VPHistogramRecipe(Opcode, HGramOps, cast<VPIRMetadata>(*VPI),
6168 VPI->getDebugLoc());
6169}
6170
6172 VPInstruction *VPI, VPBuilder &FinalRedStoresBuilder) {
6173 StoreInst *SI;
6174 if ((SI = dyn_cast<StoreInst>(VPI->getUnderlyingInstr())) &&
6175 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
6176 // Only create recipe for the final invariant store of the reduction.
6177 if (Legal->isInvariantStoreOfReduction(SI)) {
6178 VPValue *Val = VPI->getOperand(0);
6179 VPValue *Addr = VPI->getOperand(1);
6180 // We need to store the exiting value of the reduction, so use the blend
6181 // if tail folded.
6182 if (auto *Blend = VPlanPatternMatch::findUserOf<VPBlendRecipe>(Val))
6183 Val = Blend;
6184 [[maybe_unused]] auto *Rdx =
6186 assert((isa<VPIRValue>(Val) || !Rdx || Rdx->getBackedgeValue() == Val) &&
6187 "Store of reduction thats not the backedge value?");
6188 auto *Recipe = new VPReplicateRecipe(
6189 SI, {Val, Addr}, true /* IsUniform */, nullptr /*Mask*/, *VPI, *VPI,
6190 VPI->getDebugLoc());
6191 FinalRedStoresBuilder.insert(Recipe);
6192 }
6193 VPI->eraseFromParent();
6194 return true;
6195 }
6196
6197 return false;
6198}
6199
6201 VFRange &Range) {
6202 auto *I = VPI->getUnderlyingInstr();
6204 [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
6205 Range);
6206
6207 bool IsPredicated = CM.isPredicatedInst(I);
6208
6209 // Even if the instruction is not marked as uniform, there are certain
6210 // intrinsic calls that can be effectively treated as such, so we check for
6211 // them here. Conservatively, we only do this for scalable vectors, since
6212 // for fixed-width VFs we can always fall back on full scalarization.
6213 if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
6214 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
6215 case Intrinsic::assume:
6216 case Intrinsic::lifetime_start:
6217 case Intrinsic::lifetime_end:
6218 // For scalable vectors if one of the operands is variant then we still
6219 // want to mark as uniform, which will generate one instruction for just
6220 // the first lane of the vector. We can't scalarize the call in the same
6221 // way as for fixed-width vectors because we don't know how many lanes
6222 // there are.
6223 //
6224 // The reasons for doing it this way for scalable vectors are:
6225 // 1. For the assume intrinsic generating the instruction for the first
6226 // lane is still be better than not generating any at all. For
6227 // example, the input may be a splat across all lanes.
6228 // 2. For the lifetime start/end intrinsics the pointer operand only
6229 // does anything useful when the input comes from a stack object,
6230 // which suggests it should always be uniform. For non-stack objects
6231 // the effect is to poison the object, which still allows us to
6232 // remove the call.
6233 IsUniform = true;
6234 break;
6235 default:
6236 break;
6237 }
6238 }
6239 VPValue *BlockInMask = nullptr;
6240 if (!IsPredicated) {
6241 // Finalize the recipe for Instr, first if it is not predicated.
6242 LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
6243 } else {
6244 LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
6245 // Instructions marked for predication are replicated and a mask operand is
6246 // added initially. Masked replicate recipes will later be placed under an
6247 // if-then construct to prevent side-effects. Generate recipes to compute
6248 // the block mask for this region.
6249 BlockInMask = VPI->getMask();
6250 }
6251
6252 // Note that there is some custom logic to mark some intrinsics as uniform
6253 // manually above for scalable vectors, which this assert needs to account for
6254 // as well.
6255 assert((Range.Start.isScalar() || !IsUniform || !IsPredicated ||
6256 (Range.Start.isScalable() && isa<IntrinsicInst>(I))) &&
6257 "Should not predicate a uniform recipe");
6258 if (IsUniform) {
6260 VPI->getOpcode(), VPI->operandsWithoutMask(), BlockInMask, *VPI, *VPI,
6261 VPI->getDebugLoc(), VPI->getScalarType(), I);
6262 }
6263 auto *Recipe = new VPReplicateRecipe(I, VPI->operandsWithoutMask(),
6264 /*IsSingleScalar=*/false, BlockInMask,
6265 *VPI, *VPI, VPI->getDebugLoc());
6266 return Recipe;
6267}
6268
6271 VFRange &Range) {
6272 assert(!R->isPhi() && "phis must be handled earlier");
6273 auto *VPI = cast<VPInstruction>(R);
6274 assert(VPI->getOpcode() != Instruction::Call &&
6275 "Call should have been handled by makeCallWideningDecisions");
6276
6277 // All widen recipes below deal only with VF > 1.
6279 [&](ElementCount VF) { return VF.isScalar(); }, Range))
6280 return nullptr;
6281
6282 Instruction *Instr = R->getUnderlyingInstr();
6283 assert(!is_contained({Instruction::Load, Instruction::Store},
6284 VPI->getOpcode()) &&
6285 "Should have been handled prior to this!");
6286
6287 // We can only replicate an extractvalue if its operand generates per lane in
6288 // the same block, otherwise we would need to extract a lane from its struct
6289 // operand which is invalid.
6290 if (VPI->getOpcode() == Instruction::ExtractValue &&
6292 if (VPRecipeBase *OpR = VPI->getOperand(0)->getDefiningRecipe())
6294 OpR->getParent() != VPI->getParent())
6295 return tryToWiden(VPI);
6296
6297 if (!shouldWiden(Instr, Range))
6298 return nullptr;
6299
6300 if (VPI->getOpcode() == Instruction::GetElementPtr) {
6301 auto *GEP = cast<GetElementPtrInst>(Instr);
6302 return new VPWidenGEPRecipe(GEP->getSourceElementType(),
6303 VPI->operandsWithoutMask(), *VPI,
6304 VPI->getDebugLoc(), GEP);
6305 }
6306
6307 if (Instruction::isCast(VPI->getOpcode())) {
6308 auto *CI = cast<CastInst>(Instr);
6309 return new VPWidenCastRecipe(CI->getOpcode(), VPI->getOperand(0),
6310 VPI->getScalarType(), CI, *VPI, *VPI,
6311 VPI->getDebugLoc());
6312 }
6313
6314 return tryToWiden(VPI);
6315}
6316
6317// To allow RUN_VPLAN_PASS to print the VPlan after VF/UF independent
6318// optimizations.
6320
6321#ifndef NDEBUG
6322/// Cross-check the execution frequencies recorded in \p Plan against
6323/// BlockFrequencyInfo for the blocks of \p OrigLoop.
6324/// FIXME: Temporary verification aid, to be removed.
6325static bool verifyExecutionFrequenciesMatchBFI(VPlan &Plan, Loop *OrigLoop,
6326 LoopInfo *LI,
6328 // Limited to loops with the latch as only exiting block
6329 if (OrigLoop->getExitingBlock() != OrigLoop->getLoopLatch())
6330 return true;
6331
6332 // Visit the loop body in the same order as recordExecutionFrequencies. Both
6333 // are reverse post-orders of the same CFG, so indices correspond.
6336 assert(Blocks.size() == OrigLoop->getNumBlocks() &&
6337 "loop body and original loop must have the same blocks");
6338
6339 LoopBlocksRPO OrigRPO(OrigLoop);
6340 OrigRPO.perform(LI);
6341
6342 // Only request the expensive BFI once the cheap bail-outs are past.
6343 BlockFrequencyInfo &BFI = CM.getBFI();
6344 uint64_t HeaderFreq = BFI.getBlockFreq(OrigLoop->getHeader()).getFrequency();
6345 if (HeaderFreq == 0)
6346 return true;
6347
6348 // BFI's fixed-point mass propagation loses up to 1 ULP per edge, so bound the
6349 // error by the number of edges in the region.
6350 uint64_t Edges = 0;
6351 for (const VPBasicBlock *VPBB : Blocks)
6352 Edges += VPBB->getNumSuccessors();
6353 uint64_t Tolerance = Edges + BranchProbability::getDenominator() / HeaderFreq;
6354
6355 for (const auto &[VPBB, BB] :
6356 zip_equal(drop_begin(Blocks), drop_begin(OrigRPO))) {
6357 // Nothing to check for blocks without a recorded frequency.
6358 std::optional<VPExecutionFrequency> Freq =
6360 if (!Freq)
6361 continue;
6363
6364 // Clamp to the header's frequency, which BFI's rounding may exceed.
6367 std::min(BBFreq, HeaderFreq), HeaderFreq);
6368 if (AbsoluteDifference(Computed.getNumerator(), Expected.getNumerator()) <=
6369 Tolerance)
6370 continue;
6371
6372 errs() << "Block frequency mismatch for " << VPBB->getName() << ": VPlan "
6373 << Computed << ", BlockFrequencyInfo " << Expected << "\n";
6374 return false;
6375 }
6376 return true;
6377}
6378#endif
6379
6380VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan1() {
6381 bool IsInnerLoop = OrigLoop->isInnermost();
6382
6383 // Set up loop versioning for inner loops with memory runtime checks.
6384 // Outer loops don't have LoopAccessInfo since canVectorizeMemory() is not
6385 // called for them.
6386 std::optional<LoopVersioning> LVer;
6387 if (IsInnerLoop) {
6388 const LoopAccessInfo *LAI = Legal->getLAI();
6389 LVer.emplace(*LAI, LAI->getRuntimePointerChecking()->getChecks(), OrigLoop,
6390 LI, DT, PSE.getSE());
6391 if (!LAI->getRuntimePointerChecking()->getChecks().empty() &&
6393 // Only use noalias metadata when using memory checks guaranteeing no
6394 // overlap across all iterations.
6395 LVer->prepareNoAliasMetadata();
6396 }
6397 }
6398
6399 // Create initial base VPlan0, to serve as common starting point for all
6400 // candidates built later for specific VF ranges.
6401 auto VPlan0 = VPlanTransforms::buildVPlan0(
6402 OrigLoop, *LI, Legal->getWidestInductionType(), PSE,
6403 LVer ? &*LVer : nullptr, GetBPI);
6404
6405 VPDominatorTree VPDT(*VPlan0);
6406 if (const LoopAccessInfo *LAI = Legal->getLAI())
6408 LAI->getSymbolicStrides(), VPDT);
6411 if (IsInnerLoop) {
6413 assert(verifyExecutionFrequenciesMatchBFI(*VPlan0, OrigLoop, LI, *CM) &&
6414 "execution frequencies do not match the loop's block frequencies");
6415 }
6416
6417 // Create recipes for header phis. For outer loops, reductions, recurrences
6418 // and in-loop reductions are empty since legality doesn't detect them.
6419 if (!RUN_VPLAN_PASS(
6420 VPlanTransforms::createHeaderPhiRecipes, *VPlan0, PSE, *OrigLoop,
6421 VPDT, Legal->getInductionVars(), Legal->getReductionVars(),
6422 Legal->getFixedOrderRecurrences(), Config.getInLoopReductions(),
6423 Config.getHints().allowReordering())) {
6424 return nullptr;
6425 }
6426
6427 if (const LoopAccessInfo *LAI = Legal->getLAI())
6429 LAI->getSymbolicStrides(), VPDT);
6430
6431 // Add surviving induction predicates to PSE and check constraints.
6432 bool ForceVectorization =
6433 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled;
6434 bool OptForSize =
6435 !ForceVectorization &&
6436 (CM->EpilogueLoweringStatus == CM_EpilogueNotAllowedOptSize ||
6437 CM->EpilogueLoweringStatus == CM_EpilogueNotAllowedLowTripLoop);
6438 unsigned SCEVCheckThreshold = ForceVectorization
6442 OptForSize, SCEVCheckThreshold, ORE, OrigLoop))
6443 return nullptr;
6444
6446
6447 // If we're vectorizing a loop with an uncountable exit, make sure that the
6448 // recipes are safe to handle.
6449 // TODO: Remove this once we can properly check the VPlan itself for both
6450 // the presence of an uncountable exit and the presence of stores in
6451 // the loop inside handleUncountableEarlyExits itself.
6452 if (Legal->hasUncountableEarlyExit()) {
6454 OrigLoop))
6455 return nullptr;
6456
6457 // TODO: Check target preference for style.
6458 UncountableExitStyle EEStyle =
6459 Legal->hasUncountableExitWithSideEffects()
6463 ORE, OrigLoop, PSE, *DT, Legal->getAssumptionCache(),
6464 EEStyle)) {
6465 return nullptr;
6466 }
6467 } else {
6469 }
6470
6472 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()));
6473 if (CM->foldTailByMasking())
6475
6477
6478 return VPlan0;
6479}
6480
6481void LoopVectorizationPlanner::buildVPlans(VPlan &VPlan1, ElementCount MinVF,
6482 ElementCount MaxVF) {
6483 if (ElementCount::isKnownGT(MinVF, MaxVF))
6484 return;
6485
6486 auto MaxVFTimes2 = MaxVF * 2;
6487 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
6488 VFRange SubRange = {VF, MaxVFTimes2};
6489 auto Plan =
6490 tryToBuildVPlan(std::unique_ptr<VPlan>(VPlan1.duplicate()), SubRange);
6491 VF = SubRange.End;
6492
6493 if (!Plan)
6494 continue;
6495
6496 // Now optimize the initial VPlan.
6500 Config.getMinimalBitwidths());
6502 // TODO: try to put addExplicitVectorLength close to addActiveLaneMask
6503 if (CM->foldTailWithEVL()) {
6505 Config.getMaxSafeElements());
6507 }
6508
6509 if (auto P =
6511 VPlans.push_back(std::move(P));
6512
6513 TailFoldingStyle Style = CM->getTailFoldingStyle();
6515 useActiveLaneMask(Style),
6517
6519 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
6520 VPlans.push_back(std::move(Plan));
6521 }
6522}
6523
6524VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VPlanPtr Plan,
6525 VFRange &Range) {
6526
6527 // For outer loops, the plan only needs basic recipe conversion and induction
6528 // live-out optimization; the full inner-loop recipe building below does not
6529 // apply (no widening decisions, interleave groups, reductions, etc.).
6530 if (Plan->isOuterLoop()) {
6531 for (ElementCount VF : Range)
6532 Plan->addVF(VF);
6534 *Plan, *TLI, PSE, OrigLoop))
6535 return nullptr;
6537 OrigLoop);
6538 return Plan;
6539 }
6540
6541 using namespace llvm::VPlanPatternMatch;
6542 SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
6543
6544 // ---------------------------------------------------------------------------
6545 // Build initial VPlan: Scan the body of the loop in a topological order to
6546 // visit each basic block after having visited its predecessor basic blocks.
6547 // ---------------------------------------------------------------------------
6548
6549 bool RequiresScalarEpilogueCheck =
6551 [this](ElementCount VF) {
6552 return !CM->requiresScalarEpilogue(VF.isVector());
6553 },
6554 Range);
6555 // Update the branch in the middle block if a scalar epilogue is required.
6556 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6557 if (!RequiresScalarEpilogueCheck && MiddleVPBB->getNumSuccessors() == 2) {
6558 auto *BranchOnCond = cast<VPInstruction>(MiddleVPBB->getTerminator());
6559 assert(MiddleVPBB->getSuccessors()[1] == Plan->getScalarPreheader() &&
6560 "second successor must be scalar preheader");
6561 BranchOnCond->setOperand(0, Plan->getFalse());
6562 }
6563
6564 // Don't use getDecisionAndClampRange here, because we don't know the UF
6565 // so this function is better to be conservative, rather than to split
6566 // it up into different VPlans.
6567 // TODO: Consider using getDecisionAndClampRange here to split up VPlans.
6568 bool IVUpdateMayOverflow = false;
6569 for (ElementCount VF : Range)
6570 IVUpdateMayOverflow |= !isIndvarOverflowCheckKnownFalse(CM.get(), VF);
6571
6572 TailFoldingStyle Style = CM->getTailFoldingStyle();
6573 // Use NUW for the induction increment if we proved that it won't overflow in
6574 // the vector loop or when not folding the tail. In the later case, we know
6575 // that the canonical induction increment will not overflow as the vector trip
6576 // count is >= increment and a multiple of the increment.
6577 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
6578 bool HasNUW = !IVUpdateMayOverflow || Style == TailFoldingStyle::None;
6579 if (!HasNUW) {
6580 auto *IVInc =
6581 LoopRegion->getExitingBasicBlock()->getTerminator()->getOperand(0);
6582 assert(match(IVInc,
6583 m_VPInstruction<Instruction::Add>(
6584 m_Specific(LoopRegion->getCanonicalIV()), m_VPValue())) &&
6585 "Did not find the canonical IV increment");
6586 LoopRegion->clearCanonicalIVNUW(cast<VPInstruction>(IVInc));
6587 }
6588
6589 // ---------------------------------------------------------------------------
6590 // Pre-construction: record ingredients whose recipes we'll need to further
6591 // process after constructing the initial VPlan.
6592 // ---------------------------------------------------------------------------
6593
6594 // For each interleave group which is relevant for this (possibly trimmed)
6595 // Range, add it to the set of groups to be later applied to the VPlan and add
6596 // placeholders for its members' Recipes which we'll be replacing with a
6597 // single VPInterleaveRecipe.
6598 for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
6599 auto ApplyIG = [IG, this](ElementCount VF) -> bool {
6600 bool Result = (VF.isVector() && // Query is illegal for VF == 1
6601 CM->getWideningDecision(IG->getInsertPos(), VF) ==
6603 // For scalable vectors, the interleave factors must be <= 8 since we
6604 // require the (de)interleaveN intrinsics instead of shufflevectors.
6605 assert((!Result || !VF.isScalable() || IG->getFactor() <= 8) &&
6606 "Unsupported interleave factor for scalable vectors");
6607 return Result;
6608 };
6609 if (!getDecisionAndClampRange(ApplyIG, Range))
6610 continue;
6611 InterleaveGroups.insert(IG);
6612 }
6613
6614 // ---------------------------------------------------------------------------
6615 // Construct wide recipes and apply predication for original scalar
6616 // VPInstructions in the loop.
6617 // ---------------------------------------------------------------------------
6618 VPRecipeBuilder RecipeBuilder(*Plan, Legal, *CM, Builder);
6619
6621 Range.Start);
6622
6623 VPCostContext CostCtx(*TLI, *Plan, *CM, Config);
6624
6626 RecipeBuilder, CostCtx);
6627
6629
6631 RecipeBuilder, CostCtx);
6632
6634 PSE);
6635
6636 // Convert remaining VPInstructions to widen or replicate recipes.
6637 // TODO: This legacy code should eventually be migrated to VPlan.
6638 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
6639 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
6640 vp_depth_first_shallow(HeaderVPBB))) {
6641 // All types but VPInstructions are already widened and don't need extra
6642 // processing. We process VPInstructions below.
6643 assert(
6644 all_of(
6645 make_range(VPBB->getFirstNonPhi(), VPBB->end()),
6646 IsaPred<VPWidenCanonicalIVRecipe, VPBlendRecipe, VPReductionRecipe,
6647 VPReplicateRecipe, VPWidenLoadRecipe, VPWidenStoreRecipe,
6648 VPWidenCallRecipe, VPWidenIntrinsicRecipe,
6649 VPVectorPointerRecipe, VPVectorEndPointerRecipe,
6650 VPHistogramRecipe, VPInstruction>) &&
6651 "Unexpected recipe");
6652 for (VPInstruction &VPI :
6654 // We represent single-scalar casts directly as VPInstructions.
6655 if (Instruction::isCast(VPI.getOpcode()) &&
6657 continue;
6658
6659 // Only VPInstrutions with an underlying value need to be processed.
6660 if (!VPI.getUnderlyingValue())
6661 continue;
6662
6663 Builder.setInsertPoint(&VPI);
6664
6665 VPRecipeBase *Recipe =
6666 RecipeBuilder.tryToCreateWidenNonPhiRecipe(&VPI, Range);
6667 if (!Recipe)
6668 Recipe = RecipeBuilder.handleReplication(&VPI, Range);
6669 Builder.insert(Recipe);
6670
6671 if (Recipe->getNumDefinedValues() == 1) {
6672 VPI.replaceAllUsesWith(Recipe->getVPSingleValue());
6673 } else {
6674 assert(Recipe->getNumDefinedValues() == 0 &&
6675 "Unexpected multidef recipe");
6676 }
6677 VPI.eraseFromParent();
6678 }
6679 }
6680
6681 assert(isa<VPRegionBlock>(LoopRegion) &&
6682 !LoopRegion->getEntryBasicBlock()->empty() &&
6683 "entry block must be set to a VPRegionBlock having a non-empty entry "
6684 "VPBasicBlock");
6685
6687 Range);
6688
6689 // ---------------------------------------------------------------------------
6690 // Transform initial VPlan: Apply previously taken decisions, in order, to
6691 // bring the VPlan to its final state.
6692 // ---------------------------------------------------------------------------
6693
6694 addReductionResultComputation(Plan, Range.Start);
6695
6696 // Optimize FindIV reductions to use sentinel-based approach when possible.
6698 *OrigLoop);
6700 OrigLoop);
6701
6702 // Apply mandatory transformation to handle reductions with multiple in-loop
6703 // uses if possible, bail out otherwise.
6705 OrigLoop))
6706 return nullptr;
6707 // Apply mandatory transformation to handle FP maxnum/minnum reduction with
6708 // NaNs if possible, bail out otherwise.
6710 return nullptr;
6711
6712 // Create whole-vector selects for find-last recurrences.
6714 return nullptr;
6715
6717
6718 // Create partial reduction recipes for scaled reductions and transform
6719 // recipes to abstract recipes if it is legal and beneficial and clamp the
6720 // range for better cost estimation.
6722 Range);
6724 Range);
6725
6726 // Interleave memory: for each Interleave Group we marked earlier as relevant
6727 // for this VPlan, replace the Recipes widening its memory instructions with a
6728 // single VPInterleaveRecipe at its insertion point.
6730 InterleaveGroups, CM->isEpilogueAllowed());
6731
6732 // Convert memory recipes to strided access recipes if the strided access is
6733 // legal and profitable.
6735 *OrigLoop, CostCtx, Range);
6736
6737 // Ensure scalar VF plans only contain VF=1, as required by hasScalarVFOnly.
6738 if (Range.Start.isScalar())
6739 Range.End = Range.Start * 2;
6740
6741 for (ElementCount VF : Range)
6742 Plan->addVF(VF);
6743 Plan->setName("Initial VPlan");
6744
6746
6747 if (CM->maskPartialAliasing())
6749
6750 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
6751 return Plan;
6752}
6753
6754void LoopVectorizationPlanner::addReductionResultComputation(
6755 VPlanPtr &Plan, ElementCount MinVF) {
6756 using namespace VPlanPatternMatch;
6757 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
6758 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6759 VPBasicBlock *LatchVPBB = VectorLoopRegion->getExitingBasicBlock();
6760 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->end())));
6761 VPBasicBlock::iterator IP = MiddleVPBB->getFirstNonPhi();
6762 VPValue *HeaderMask = Plan->getVectorLoopRegion()->getHeaderMask();
6763 for (VPRecipeBase &R : make_early_inc_range(
6764 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis())) {
6765 VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
6766 if (!PhiR)
6767 continue;
6768
6769 // Clean up reductions that have become invariant.
6770 if (PhiR->getBackedgeValue() == PhiR) {
6771 PhiR->replaceAllUsesWith(PhiR->getStartValue());
6772 PhiR->eraseFromParent();
6773 continue;
6774 }
6775
6776 RecurKind RecurrenceKind = PhiR->getRecurrenceKind();
6777 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
6779 Type *PhiTy = PhiR->getScalarType();
6780
6781 // Convert a VPBlendRecipe backedge to a select.
6782 if (auto *Blend = dyn_cast<VPBlendRecipe>(PhiR->getBackedgeValue())) {
6783 if (Blend->getNumIncomingValues() == 2 &&
6784 Blend->getMask(0) == HeaderMask) {
6785 auto *Sel = VPBuilder(Blend).createSelect(
6786 Blend->getMask(0), Blend->getIncomingValue(0),
6787 Blend->getIncomingValue(1), {}, "", *Blend);
6788 Blend->replaceAllUsesWith(Sel);
6789 Blend->eraseFromParent();
6790 }
6791 }
6792
6793 auto *OrigExitingVPV = PhiR->getBackedgeValue();
6794 auto *NewExitingVPV = OrigExitingVPV;
6795
6796 // Remove the predicated select if the target doesn't want it.
6797 VPValue *V;
6798 if (!CM->usePredicatedReductionSelect(RecurrenceKind) &&
6799 match(PhiR->getBackedgeValue(),
6800 m_Select(m_Specific(HeaderMask), m_VPValue(V), m_Specific(PhiR))))
6801 PhiR->setBackedgeValue(V);
6802
6803 // We want code in the middle block to appear to execute on the location of
6804 // the scalar loop's latch terminator because: (a) it is all compiler
6805 // generated, (b) these instructions are always executed after evaluating
6806 // the latch conditional branch, and (c) other passes may add new
6807 // predecessors which terminate on this line. This is the easiest way to
6808 // ensure we don't accidentally cause an extra step back into the loop while
6809 // debugging.
6810 DebugLoc ExitDL = OrigLoop->getLoopLatch()->getTerminator()->getDebugLoc();
6811
6812 // TODO: At the moment ComputeReductionResult also drives creation of the
6813 // bc.merge.rdx phi nodes, hence it needs to be created unconditionally here
6814 // even for in-loop reductions, until the reduction resume value handling is
6815 // also modeled in VPlan.
6816 VPInstruction *FinalReductionResult;
6817 VPBuilder::InsertPointGuard Guard(Builder);
6818 Builder.setInsertPoint(MiddleVPBB, IP);
6819 // For AnyOf reductions, find the select among PhiR's users and convert
6820 // the reduction phi to operate on bools before creating the final
6821 // reduction result.
6822 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
6823 auto *AnyOfSelect = cast<VPSingleDefRecipe>(
6825 VPValue *Start = PhiR->getStartValue();
6826 bool TrueValIsPhi = AnyOfSelect->getOperand(1) == PhiR;
6827 // NewVal is the non-phi operand of the select.
6828 VPValue *NewVal = TrueValIsPhi ? AnyOfSelect->getOperand(2)
6829 : AnyOfSelect->getOperand(1);
6830
6831 // Adjust AnyOf reductions; replace the reduction phi for the selected
6832 // value with a boolean reduction phi node to check if the condition is
6833 // true in any iteration. The final value is selected by the final
6834 // ComputeReductionResult.
6835 VPValue *Cmp = AnyOfSelect->getOperand(0);
6836 // If the compare is checking the reduction PHI node, adjust it to check
6837 // the start value.
6838 if (VPRecipeBase *CmpR = Cmp->getDefiningRecipe())
6839 CmpR->replaceUsesOfWith(PhiR, PhiR->getStartValue());
6840 Builder.setInsertPoint(AnyOfSelect);
6841
6842 // If the true value of the select is the reduction phi, the new value
6843 // is selected if the negated condition is true in any iteration.
6844 if (TrueValIsPhi)
6845 Cmp = Builder.createNot(Cmp);
6846
6847 // Build a fresh i1 chain (phi, or, and i1 versions of any blend/select
6848 // the exiting value flows through).
6849 auto *NewPhiR =
6850 PhiR->cloneWithOperands(Plan->getFalse(), Plan->getFalse());
6851 NewPhiR->insertBefore(PhiR);
6852 VPValue *NewExiting = Builder.createOr(NewPhiR, Cmp);
6853
6854 // The exiting value may flow through a chain of VPBlendRecipes and
6855 // select recipes (VPInstruction, VPWidenRecipe or VPReplicateRecipe with
6856 // Select opcode) before reaching OrigExitingVPV. Clone each chain link
6857 // in topological order so each clone refers to the already-rewritten i1
6858 // operands via Substitutions.
6859 DenseMap<VPValue *, VPValue *> Substitutions = {{AnyOfSelect, NewExiting},
6860 {PhiR, NewPhiR}};
6861 std::function<void(VPSingleDefRecipe *)> CloneChain =
6862 [&](VPSingleDefRecipe *Old) {
6863 if (Substitutions.contains(Old))
6864 return;
6866 for (VPValue *Op : Old->operands()) {
6867 if (isa<VPBlendRecipe>(Op) ||
6869 CloneChain(cast<VPSingleDefRecipe>(Op));
6870 NewOps.push_back(Substitutions.lookup_or(Op, Op));
6871 }
6872 VPSingleDefRecipe *New;
6873 if (auto *B = dyn_cast<VPBlendRecipe>(Old))
6874 New = B->cloneWithOperands(NewOps);
6875 else if (auto *W = dyn_cast<VPWidenRecipe>(Old))
6876 New = W->cloneWithOperands(NewOps);
6877 else if (auto *Rep = dyn_cast<VPReplicateRecipe>(Old))
6878 New = Rep->cloneWithOperands(NewOps);
6879 else
6880 New = cast<VPInstruction>(Old)->cloneWithOperands(NewOps);
6881 New->insertBefore(Old);
6882 Substitutions[Old] = New;
6883 };
6884
6885 if (OrigExitingVPV != AnyOfSelect) {
6886 CloneChain(cast<VPSingleDefRecipe>(OrigExitingVPV));
6887 NewExiting = Substitutions.lookup(OrigExitingVPV);
6888 }
6889 NewPhiR->setOperand(1, NewExiting);
6890 PhiR->replaceAllUsesWith(Plan->getPoison(PhiR->getScalarType()));
6891
6892 Builder.setInsertPoint(MiddleVPBB, IP);
6893 FinalReductionResult =
6894 Builder.createAnyOfReduction(NewExiting, NewVal, Start, ExitDL);
6895 } else {
6896 // If the vector reduction can be performed in a smaller type, we
6897 // truncate then extend the loop exit value to enable InstCombine to
6898 // evaluate the entire expression in the smaller type.
6899 VPValue *ReductionOp = NewExitingVPV;
6900 Instruction::CastOps ExtendOpc = Instruction::CastOpsEnd;
6901 if (MinVF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
6902 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
6904 "Unexpected truncated min-max recurrence!");
6905 Type *RdxTy = RdxDesc.getRecurrenceType();
6906 ExtendOpc = RdxDesc.isSigned() ? Instruction::SExt : Instruction::ZExt;
6907 {
6908 VPBuilder::InsertPointGuard Guard(Builder);
6909 Builder.setInsertPoint(
6910 NewExitingVPV->getDefiningRecipe()->getParent(),
6911 std::next(NewExitingVPV->getDefiningRecipe()->getIterator()));
6912 ReductionOp =
6913 Builder.createWidenCast(Instruction::Trunc, NewExitingVPV, RdxTy);
6914 VPWidenCastRecipe *Extnd =
6915 Builder.createWidenCast(ExtendOpc, ReductionOp, PhiTy);
6916 if (PhiR->getOperand(1) == NewExitingVPV)
6917 PhiR->setOperand(1, Extnd);
6918 }
6919 }
6920
6921 VPIRFlags Flags(RecurrenceKind, PhiR->isOrdered(), PhiR->isInLoop(),
6922 PhiR->getFastMathFlagsOrNone());
6923 FinalReductionResult = Builder.createNaryOp(
6924 VPInstruction::ComputeReductionResult, {ReductionOp}, Flags, ExitDL);
6925 if (ExtendOpc != Instruction::CastOpsEnd)
6926 FinalReductionResult = Builder.createScalarCast(
6927 ExtendOpc, FinalReductionResult, PhiTy, {});
6928 }
6929
6930 // Update all users outside the vector region. Also replace redundant
6931 // extracts.
6932 for (auto *U : to_vector(OrigExitingVPV->users())) {
6933 auto *Parent = cast<VPRecipeBase>(U)->getParent();
6934 if (FinalReductionResult == U || Parent->getParent())
6935 continue;
6936 // Skip ComputeReductionResult and FindIV reductions when they are not the
6937 // final result.
6938 if (match(U, m_VPInstruction<VPInstruction::ComputeReductionResult>()) ||
6940 match(U, m_VPInstruction<Instruction::ICmp>())))
6941 continue;
6942 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
6943
6944 // Look through ExtractLastPart.
6946 U = cast<VPInstruction>(U)->getSingleUser();
6947
6950 cast<VPInstruction>(U)->replaceAllUsesWith(FinalReductionResult);
6951 }
6952
6953 RecurKind RK = PhiR->getRecurrenceKind();
6958 VPBuilder PHBuilder(Plan->getVectorPreheader());
6959 VPValue *Iden = Plan->getOrAddLiveIn(
6960 getRecurrenceIdentity(RK, PhiTy, PhiR->getFastMathFlagsOrNone()));
6961 auto *ScaleFactorVPV = Plan->getConstantInt(32, 1);
6962 VPValue *StartV = PHBuilder.createNaryOp(
6964 {PhiR->getStartValue(), Iden, ScaleFactorVPV}, *PhiR);
6965 PhiR->setOperand(0, StartV);
6966 }
6967 }
6968
6970}
6971
6973 VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const {
6974 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
6975 if (SCEVCheckBlock && SCEVCheckBlock->hasNPredecessors(0)) {
6976 assert((!Config.OptForSize ||
6977 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled) &&
6978 "Cannot SCEV check stride or overflow when optimizing for size");
6980 SCEVCheckBlock, HasBranchWeights);
6981 }
6982 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
6983 if (MemCheckBlock && MemCheckBlock->hasNPredecessors(0)) {
6984 // VPlan-native path does not do any analysis for runtime checks
6985 // currently.
6987 "Runtime checks are not supported for outer loops yet");
6988
6989 if (Config.OptForSize) {
6990 assert(
6991 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled &&
6992 "Cannot emit memory checks when optimizing for size, unless forced "
6993 "to vectorize.");
6994 ORE->emit([&]() {
6995 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
6996 OrigLoop->getStartLoc(),
6997 OrigLoop->getHeader())
6998 << "Code-size may be reduced by not forcing "
6999 "vectorization, or by source-code modifications "
7000 "eliminating the need for runtime checks "
7001 "(e.g., adding 'restrict').";
7002 });
7003 }
7004 // VPSCEVExpander expands AddRecs in the plan's entry, not the check block.
7005 auto IsUnsupported = IsaPred<SCEVAddRecExpr>;
7006 // Diff checks are not modelled in VPlan yet, and the VPlan expander cannot
7007 // hoist bounds out of an enclosing loop.
7008 const auto &RtPtrChecking = *Legal->getRuntimePointerChecking();
7009 if (RtPtrChecking.getDiffChecks() || OrigLoop->getParentLoop() ||
7010 any_of(RtPtrChecking.CheckingGroups,
7011 [&](const RuntimeCheckingPtrGroup &CG) {
7012 return SCEVExprContains(CG.Low, IsUnsupported) ||
7013 SCEVExprContains(CG.High, IsUnsupported);
7014 }))
7016 MemCheckCond, MemCheckBlock, HasBranchWeights);
7017
7018 // Erase the temporary IR before recipe expansion can reuse its values.
7019 RTChecks.eraseMemCheckBlock();
7021 RtPtrChecking.getChecks(), *PSE.getSE(),
7022 OrigLoop->getStartLoc(), HasBranchWeights);
7023 }
7024}
7025
7027 VPlan &Plan, ElementCount VF, unsigned UF,
7028 ElementCount MinProfitableTripCount) const {
7029 const uint32_t *BranchWeights =
7030 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator())
7032 : nullptr;
7034 MinProfitableTripCount, Plan.requiresScalarEpilogue(),
7035 Plan.hasTailFolded(), OrigLoop, BranchWeights,
7036 OrigLoop->getLoopPredecessor()->getTerminator()->getDebugLoc(),
7037 PSE, Plan.getEntry());
7038}
7039
7040// Determine how to lower the epilogue, which depends on 1) optimising
7041// for minimum code-size, 2) tail-folding compiler options, 3) loop
7042// hints forcing tail-folding, and 4) a TTI hook that analyses whether the loop
7043// is suitable for tail-folding.
7044// This function determines epilogue lowering for the main vector loop while
7045// epilogue lowering for the tail-folded epilogue path will be handled
7046// separately in getEpilogueTailLowering.
7047static EpilogueLowering
7049 bool OptForSize, TargetTransformInfo *TTI,
7051 InterleavedAccessInfo *IAI) {
7052 // 1) OptSize takes precedence over all other options, i.e. if this is set,
7053 // don't look at hints or options, and don't request an epilogue.
7054 if (F->hasOptSize() ||
7055 (OptForSize && Hints.getForce() != LoopVectorizeHints::FK_Enabled))
7057
7058 // 2) If set, obey the directives
7059 if (TailFoldingPolicy.getNumOccurrences()) {
7060 switch (TailFoldingPolicy) {
7062 return CM_EpilogueAllowed;
7067 };
7068 }
7069
7070 // 3) If set, obey the hints
7071 switch (Hints.getPredicate()) {
7075 return CM_EpilogueAllowed;
7076 };
7077
7078 // 4) if the TTI hook indicates this is profitable, request tail-folding.
7079 TailFoldingInfo TFI(TLI, &LVL, IAI);
7080 if (TTI->preferTailFoldingOverEpilogue(&TFI))
7082
7083 return CM_EpilogueAllowed;
7084}
7085
7086// Emit a remark if there are stores to floats that required a floating point
7087// extension. If the vectorized loop was generated with floating point there
7088// will be a performance penalty from the conversion overhead and the change in
7089// the vector width.
7092 for (BasicBlock *BB : L->getBlocks()) {
7093 for (Instruction &Inst : *BB) {
7094 if (auto *S = dyn_cast<StoreInst>(&Inst)) {
7095 if (S->getValueOperand()->getType()->isFloatTy())
7096 Worklist.push_back(S);
7097 }
7098 }
7099 }
7100
7101 // Traverse the floating point stores upwards searching, for floating point
7102 // conversions.
7105 while (!Worklist.empty()) {
7106 auto *I = Worklist.pop_back_val();
7107 if (!L->contains(I))
7108 continue;
7109 if (!Visited.insert(I).second)
7110 continue;
7111
7112 // Emit a remark if the floating point store required a floating
7113 // point conversion.
7114 // TODO: More work could be done to identify the root cause such as a
7115 // constant or a function return type and point the user to it.
7116 if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
7117 ORE->emit([&]() {
7118 return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
7119 I->getDebugLoc(), L->getHeader())
7120 << "floating point conversion changes vector width. "
7121 << "Mixed floating point precision requires an up/down "
7122 << "cast that will negatively impact performance.";
7123 });
7124
7125 for (Use &Op : I->operands())
7126 if (auto *OpI = dyn_cast<Instruction>(Op))
7127 Worklist.push_back(OpI);
7128 }
7129}
7130
7131/// For loops with uncountable early exits, find the cost of doing work when
7132/// exiting the loop early, such as calculating the final exit values of
7133/// variables used outside the loop.
7134/// TODO: This is currently overly pessimistic because the loop may not take
7135/// the early exit, but better to keep this conservative for now. In future,
7136/// it might be possible to relax this by using branch probabilities.
7138 VPlan &Plan, ElementCount VF) {
7139 InstructionCost Cost = 0;
7140 for (auto *ExitVPBB : Plan.getExitBlocks()) {
7141 for (auto *PredVPBB : ExitVPBB->getPredecessors()) {
7142 // If the predecessor is not the middle.block, then it must be the
7143 // vector.early.exit block, which may contain work to calculate the exit
7144 // values of variables used outside the loop.
7145 if (PredVPBB != Plan.getMiddleBlock()) {
7146 LLVM_DEBUG(dbgs() << "Calculating cost of work in exit block "
7147 << PredVPBB->getName() << ":\n");
7148 Cost += PredVPBB->cost(VF, CostCtx);
7149 }
7150 }
7151 }
7152 return Cost;
7153}
7154
7155/// This function determines whether or not it's still profitable to vectorize
7156/// the loop given the extra work we have to do outside of the loop:
7157/// 1. Perform the runtime checks before entering the loop to ensure it's safe
7158/// to vectorize.
7159/// 2. In the case of loops with uncountable early exits, we may have to do
7160/// extra work when exiting the loop early, such as calculating the final
7161/// exit values of variables used outside the loop.
7162/// 3. The middle block.
7163static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks,
7164 VectorizationFactor &VF, Loop *L,
7166 VPCostContext &CostCtx, VPlan &Plan,
7167 EpilogueLowering SEL,
7168 std::optional<unsigned> VScale) {
7169 InstructionCost RtC = Checks.getCost();
7170 if (!RtC.isValid())
7171 return false;
7172
7173 // When interleaving only scalar and vector cost will be equal, which in turn
7174 // would lead to a divide by 0. Fall back to hard threshold.
7175 if (VF.Width.isScalar()) {
7176 // TODO: Should we rename VectorizeMemoryCheckThreshold?
7178 LLVM_DEBUG(
7179 dbgs()
7180 << "LV: Interleaving only is not profitable due to runtime checks\n");
7181 return false;
7182 }
7183 return true;
7184 }
7185
7186 // The scalar cost should only be 0 when vectorizing with a user specified
7187 // VF/IC. In those cases, runtime checks should always be generated.
7188 uint64_t ScalarC = VF.ScalarCost.getValue();
7189 if (ScalarC == 0)
7190 return true;
7191
7192 InstructionCost TotalCost = RtC;
7193 // Add on the cost of any work required in the vector early exit block, if
7194 // one exists.
7195 TotalCost += calculateEarlyExitCost(CostCtx, Plan, VF.Width);
7196 TotalCost += Plan.getMiddleBlock()->cost(VF.Width, CostCtx);
7197
7198 // First, compute the minimum iteration count required so that the vector
7199 // loop outperforms the scalar loop.
7200 // The total cost of the scalar loop is
7201 // ScalarC * TC
7202 // where
7203 // * TC is the actual trip count of the loop.
7204 // * ScalarC is the cost of a single scalar iteration.
7205 //
7206 // The total cost of the vector loop is
7207 // TotalCost + VecC * (TC / VF) + EpiC
7208 // where
7209 // * TotalCost is the sum of the costs cost of
7210 // - the generated runtime checks, i.e. RtC
7211 // - performing any additional work in the vector.early.exit block for
7212 // loops with uncountable early exits.
7213 // - the middle block, if ExpectedTC <= VF.Width.
7214 // * VecC is the cost of a single vector iteration.
7215 // * TC is the actual trip count of the loop
7216 // * VF is the vectorization factor
7217 // * EpiCost is the cost of the generated epilogue, including the cost
7218 // of the remaining scalar operations.
7219 //
7220 // Vectorization is profitable once the total vector cost is less than the
7221 // total scalar cost:
7222 // TotalCost + VecC * (TC / VF) + EpiC < ScalarC * TC
7223 //
7224 // Now we can compute the minimum required trip count TC as
7225 // VF * (TotalCost + EpiC) / (ScalarC * VF - VecC) < TC
7226 //
7227 // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
7228 // the computations are performed on doubles, not integers and the result
7229 // is rounded up, hence we get an upper estimate of the TC.
7230 unsigned IntVF = estimateElementCount(VF.Width, VScale);
7231 uint64_t Div = ScalarC * IntVF - VF.Cost.getValue();
7232 uint64_t MinTC1 =
7233 Div == 0 ? 0 : divideCeil(TotalCost.getValue() * IntVF, Div);
7234
7235 // Second, compute a minimum iteration count so that the cost of the
7236 // runtime checks is only a fraction of the total scalar loop cost. This
7237 // adds a loop-dependent bound on the overhead incurred if the runtime
7238 // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
7239 // * TC. To bound the runtime check to be a fraction 1/X of the scalar
7240 // cost, compute
7241 // RtC < ScalarC * TC * (1 / X) ==> RtC * X / ScalarC < TC
7242 uint64_t MinTC2 = divideCeil(RtC.getValue() * 10, ScalarC);
7243
7244 // Now pick the larger minimum. If it is not a multiple of VF and an epilogue
7245 // is allowed, choose the next closest multiple of VF. This should partly
7246 // compensate for ignoring the epilogue cost.
7247 uint64_t MinTC = std::max(MinTC1, MinTC2);
7248 if (SEL == CM_EpilogueAllowed)
7249 MinTC = alignTo(MinTC, IntVF);
7251
7252 LLVM_DEBUG(
7253 dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
7254 << VF.MinProfitableTripCount << "\n");
7255
7256 // Skip vectorization if the expected trip count is less than the minimum
7257 // required trip count.
7258 if (auto ExpectedTC = getSmallBestKnownTC(PSE, L)) {
7259 if (ElementCount::isKnownLT(*ExpectedTC, VF.MinProfitableTripCount)) {
7260 LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
7261 "trip count < minimum profitable VF ("
7262 << *ExpectedTC << " < " << VF.MinProfitableTripCount
7263 << ")\n");
7264
7265 return false;
7266 }
7267 }
7268 return true;
7269}
7270
7272 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
7274 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
7276
7277/// ResumeForEpilogue markers in the main plan, used by the epilogue plan.
7283
7284/// Prepare \p MainPlan for vectorizing the main vector loop during epilogue
7285/// vectorization.
7287 using namespace VPlanPatternMatch;
7288 // When vectorizing the epilogue, FindFirstIV & FindLastIV reductions can
7289 // introduce multiple uses of undef/poison. If the reduction start value may
7290 // be undef or poison it needs to be frozen and the frozen start has to be
7291 // used when computing the reduction result. We also need to use the frozen
7292 // value in the resume phi generated by the main vector loop, as this is also
7293 // used to compute the reduction result after the epilogue vector loop. The
7294 // epilogue plan re-uses the frozen values.
7295 VPBuilder Builder(MainPlan.getEntry());
7296 for (VPInstruction &VPI :
7298 VPValue *OrigStart;
7299 if (!matchFindIVResult(&VPI, m_VPValue(), m_VPValue(OrigStart)))
7300 continue;
7302 continue;
7303 VPInstruction *Freeze = Builder.createFreeze(OrigStart, {}, "fr");
7304 VPI.setOperand(2, Freeze);
7305 OrigStart->replaceUsesWithIf(Freeze, IsaPred<VPPhi>);
7306 }
7307
7308 VPValue *VectorTC = nullptr;
7309 auto *Term =
7311 [[maybe_unused]] bool MatchedTC =
7312 match(Term, m_BranchOnCount(m_VPValue(), m_VPValue(VectorTC)));
7313 assert(MatchedTC && "must match vector trip count");
7314
7315 VPBasicBlock *MiddleVPBB = MainPlan.getMiddleBlock();
7316 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
7317 VPInstruction *VectorTCMarker = MiddleBuilder.createNaryOp(
7319 {VectorTC, MainPlan.getZero(VectorTC->getScalarType())});
7320
7321 // If there is a suitable resume value for the canonical induction in the
7322 // scalar (which will become vector) epilogue loop, use it and move it to the
7323 // beginning of the scalar preheader. Otherwise create it below.
7324 VPBasicBlock *MainScalarPH = MainPlan.getScalarPreheader();
7325 auto ResumePhiIter =
7326 find_if(MainScalarPH->phis(), [VectorTC](VPRecipeBase &R) {
7327 return match(&R, m_VPInstruction<Instruction::PHI>(m_Specific(VectorTC),
7328 m_ZeroInt()));
7329 });
7330 VPPhi *ResumePhi = nullptr;
7331 if (ResumePhiIter == MainScalarPH->phis().end()) {
7333 "canonical IV must exist");
7334 Type *Ty = VectorTC->getScalarType();
7335 VPBuilder ScalarPHBuilder(MainScalarPH, MainScalarPH->begin());
7336 ResumePhi = ScalarPHBuilder.createScalarPhi(
7337 {VectorTC, MainPlan.getZero(Ty)}, {}, "vec.epilog.resume.val");
7338 } else {
7339 ResumePhi = cast<VPPhi>(&*ResumePhiIter);
7340 ResumePhi->setName("vec.epilog.resume.val");
7341 if (&MainScalarPH->front() != ResumePhi)
7342 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->begin());
7343 }
7344
7345 // Create a ResumeForEpilogue for the canonical IV resume and its bypass value
7346 // as the first non-phi, to keep them alive for the epilogue.
7347 VPBuilder ResumeBuilder(MainScalarPH);
7348 VPInstruction *CanIVResume = ResumeBuilder.createNaryOp(
7349 VPInstruction::ResumeForEpilogue, {ResumePhi, ResumePhi->getOperand(1)});
7350
7351 // Create ResumeForEpilogue instructions for the resume phis of the
7352 // VPIRPhis and their bypass values in the scalar header of the main plan and
7353 // return them so they can be used as resume values when vectorizing the
7354 // epilogue.
7355 auto ResumeValues = to_vector(
7356 map_range(MainPlan.getScalarHeader()->phis(), [&](VPRecipeBase &R) {
7357 assert(isa<VPIRPhi>(R) &&
7358 "only VPIRPhis expected in the scalar header");
7359 VPValue *MainResumePhi = R.getOperand(0);
7360 VPValue *Bypass = MainResumePhi->getDefiningRecipe()->getOperand(1);
7361 return ResumeBuilder.createNaryOp(VPInstruction::ResumeForEpilogue,
7362 {MainResumePhi, Bypass});
7363 }));
7364 return {CanIVResume, VectorTCMarker, std::move(ResumeValues)};
7365}
7366
7367/// Prepare \p Plan for vectorizing the epilogue loop. That is, re-use expanded
7368/// SCEVs from \p ExpandedSCEVs and set resume values for header recipes.
7370 VPlan &MainPlan, VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs,
7371 ElementCount MainLoopVF, unsigned MainLoopUF, ElementCount EpilogueVF,
7374 // Build a map from the scalar-header PHI to the ResumeForEpilogue markers
7375 // from the main plan.
7376 // TODO: Replace the IR PHI key.
7377 DenseMap<PHINode *, VPInstruction *> IRPhiToResumeForEpi;
7378 for (auto [HeaderPhi, ResumeForEpi] :
7379 zip_equal(MainPlan.getScalarHeader()->phis(), Markers.ResumeValues))
7380 IRPhiToResumeForEpi[&cast<VPIRPhi>(HeaderPhi).getIRPhi()] = ResumeForEpi;
7381 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
7382 VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
7383 Header->setName("vec.epilog.vector.body");
7384
7385 VPValue *IV = VectorLoop->getCanonicalIV();
7386 // When vectorizing the epilogue loop, the canonical induction needs to start
7387 // at the resume value from the main vector loop. Find the resume value
7388 // created during execution of the main VPlan. Add this resume value as an
7389 // offset to the canonical IV of the epilogue loop.
7390 VPValue *VPV = Plan.getOrAddLiveIn(Markers.CanIVResume->getUnderlyingValue());
7391 assert(all_of(IV->users(),
7392 [](const VPUser *U) {
7393 if (isa<VPScalarIVStepsRecipe, VPDerivedIVRecipe>(U))
7394 return true;
7395 unsigned Opc = cast<VPInstruction>(U)->getOpcode();
7396 return Instruction::isCast(Opc) || Opc == Instruction::Add;
7397 }) &&
7398 "the canonical IV should only be used by its increment or "
7399 "ScalarIVSteps when resetting the start value");
7400 VPBuilder Builder(Header, Header->getFirstNonPhi());
7401 VPInstruction *Add = Builder.createAdd(IV, VPV);
7402 // Replace all users of the canonical IV and its increment with the offset
7403 // version, except for the Add itself and the canonical IV increment.
7405 assert(Increment && "Must have a canonical IV increment at this point");
7406 IV->replaceUsesWithIf(Add, [Add, Increment](VPUser &U) {
7407 return &U != Add && &U != Increment;
7408 });
7409 VPInstruction *OffsetIVInc =
7411 Increment->replaceAllUsesWith(OffsetIVInc);
7412 OffsetIVInc->setOperand(0, Increment);
7413
7414 // Resume values must be created in the vector preheader.
7415 VPBasicBlock *VectorPH = Plan.getVectorPreheader();
7416 VPBuilder PHBuilder(VectorPH, VectorPH->getFirstNonPhi());
7417
7418 // Ensure that the start values for all header phi recipes are updated before
7419 // vectorizing the epilogue loop.
7420 for (VPRecipeBase &R : Header->phis()) {
7421 VPValue *ResumeVPV = nullptr;
7422 // TODO: Move setting of resume values to prepareToExecute.
7423 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
7424 // Find the reduction result by searching users of the phi or its backedge
7425 // value.
7426 auto IsReductionResult = [](VPRecipeBase *R) {
7427 auto *VPI = dyn_cast<VPInstruction>(R);
7428 return VPI && VPI->getOpcode() == VPInstruction::ComputeReductionResult;
7429 };
7430 auto *RdxResult = cast<VPInstruction>(
7431 vputils::findRecipe(ReductionPhi->getBackedgeValue(), IsReductionResult));
7432 assert(RdxResult && "expected to find reduction result");
7433
7434 VPInstruction *ResumeForEpi = IRPhiToResumeForEpi.at(
7435 cast<PHINode>(ReductionPhi->getUnderlyingInstr()));
7436
7437 // Check for FindIV pattern by looking for icmp user of RdxResult.
7438 // The pattern is: select(icmp ne RdxResult, Sentinel), RdxResult, Start
7439 using namespace VPlanPatternMatch;
7440 VPValue *SentinelVPV = nullptr;
7441 bool IsFindIV = any_of(RdxResult->users(), [&](VPUser *U) {
7442 return match(U, VPlanPatternMatch::m_SpecificICmp(
7443 ICmpInst::ICMP_NE, m_Specific(RdxResult),
7444 m_VPValue(SentinelVPV)));
7445 });
7446
7447 RecurKind RK = ReductionPhi->getRecurrenceKind();
7448 ResumeVPV = Plan.getOrAddLiveIn(ResumeForEpi->getUnderlyingValue());
7449 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RK) || IsFindIV) {
7450 VPValue *BypassOp = ResumeForEpi->getOperand(1);
7451 assert((isa<VPIRValue>(BypassOp) ||
7453 BypassOp,
7455 "expected live-in or Freeze");
7456 VPValue *StartV = Plan.getOrAddLiveIn(BypassOp->getUnderlyingValue());
7458 // VPReductionPHIRecipes for AnyOf reductions expect a boolean as
7459 // start value; compare the final value from the main vector loop
7460 // to the start value.
7461 ResumeVPV = PHBuilder.createICmp(CmpInst::ICMP_NE, ResumeVPV, StartV);
7462 } else {
7463 assert(isa<VPIRValue>(SentinelVPV) &&
7464 "sentinel must be a live-in to be used in the preheader");
7465 // Use the start value frozen for the main plan, if any, when
7466 // computing the reduction result.
7467 if (match(BypassOp, m_Freeze(m_VPValue())))
7468 for (VPUser *U : RdxResult->users()) {
7469 auto *VPI = dyn_cast<VPInstruction>(U);
7470 if (VPI && matchFindIVResult(VPI, m_VPValue(), m_VPValue()))
7471 VPI->setOperand(2, StartV);
7472 }
7473
7474 // Adjust resume: select(icmp eq ResumeVPV, StartV), Sentinel,
7475 // ResumeVPV
7476 VPValue *Cmp =
7477 PHBuilder.createICmp(CmpInst::ICMP_EQ, ResumeVPV, StartV);
7478 ResumeVPV = PHBuilder.createSelect(Cmp, SentinelVPV, ResumeVPV);
7479 }
7480 // TODO: materializeBroadcasts does not cover values in the vector
7481 // preheader.
7482 ReductionPhi->setStartValue(
7483 PHBuilder.createNaryOp(VPInstruction::Broadcast, ResumeVPV));
7484 continue;
7485 }
7486 if (auto *VPI = dyn_cast<VPInstruction>(ReductionPhi->getStartValue())) {
7488 "unexpected start value");
7489 // Partial sub-reductions always start at 0 and account for the
7490 // reduction start value in a final subtraction. Update it to use the
7491 // resume value from the main vector loop.
7492 if (ReductionPhi->getVFScaleFactor() > 1 &&
7494 auto *Sub = cast<VPInstruction>(RdxResult->getSingleUser());
7495 assert((Sub->getOpcode() == Instruction::Sub ||
7496 Sub->getOpcode() == Instruction::FSub) &&
7497 "Unexpected opcode");
7498 assert(isa<VPIRValue>(Sub->getOperand(0)) &&
7499 "Expected operand to match the original start value of the "
7500 "reduction");
7501 // For integer sub-reductions, verify start value is zero.
7502 // For FP sub-reductions, verify start value is negative zero.
7503 [[maybe_unused]] auto StartValueIsIdentity = [&] {
7504 Value *IdentityValue =
7505 getRecurrenceIdentity(RK, ResumeVPV->getScalarType(),
7506 ReductionPhi->getFastMathFlagsOrNone());
7507 auto *StartValue = dyn_cast<VPIRValue>(VPI->getOperand(0));
7508 return StartValue && StartValue->getValue() == IdentityValue;
7509 };
7510 assert(StartValueIsIdentity() &&
7511 "Expected start value for partial sub-reduction to be zero "
7512 "(or negative zero)");
7513
7514 Sub->setOperand(0, ResumeVPV);
7515 } else
7516 VPI->setOperand(0, ResumeVPV);
7517 continue;
7518 }
7519 } else {
7520 // Retrieve the induction resume value via ResumeForEpilogue.
7521 PHINode *IndPhi = cast<VPWidenInductionRecipe>(&R)->getPHINode();
7522 ResumeVPV = Plan.getOrAddLiveIn(
7523 IRPhiToResumeForEpi.at(IndPhi)->getUnderlyingValue());
7524 }
7525 assert(ResumeVPV && "Must have a resume value");
7526 cast<VPHeaderPHIRecipe>(&R)->setStartValue(ResumeVPV);
7527 }
7528
7529 // Re-use the trip count and steps expanded for the main loop, as skeleton
7530 // creation needs it as a value that dominates both the scalar and vector
7531 // epilogue loops.
7532 // TODO: This is a workaround needed for epilogue vectorization and it
7533 // should be removed once induction resume value creation is done
7534 // directly in VPlan.
7537 assert(ExpandedSCEVs.contains(ExpandR.getSCEV()) &&
7538 "Epilogue plan needs a SCEV not expanded for the main loop");
7539 VPValue *ExpandedVal =
7540 Plan.getOrAddLiveIn(ExpandedSCEVs.lookup(ExpandR.getSCEV()));
7541 ExpandR.replaceAllUsesWith(ExpandedVal);
7542 if (Plan.getTripCount() == &ExpandR)
7543 Plan.resetTripCount(ExpandedVal);
7544 ExpandR.eraseFromParent();
7545 }
7546
7547 auto VScale = Config.getVScaleForTuning();
7548 unsigned MainLoopStep = estimateElementCount(MainLoopVF * MainLoopUF, VScale);
7549 unsigned EpilogueLoopStep = estimateElementCount(EpilogueVF, VScale);
7551 Plan.getOrAddLiveIn(Markers.VectorTC->getUnderlyingValue()),
7552 Plan.requiresScalarEpilogue(), EpilogueVF, MainLoopStep,
7553 EpilogueLoopStep, SE);
7554}
7555
7556static void
7558 ArrayRef<VPInstruction *> ResumeValues) {
7559 auto *ScalarPH = cast<VPIRBasicBlock>(BestEpiPlan.getScalarPreheader());
7560 BasicBlock *PH = ScalarPH->getIRBasicBlock();
7561 if (ScalarPH->hasPredecessors()) {
7562 // Fix resume values for inductions and reductions from the additional
7563 // bypass block using the incoming values from the main loop's resume phis.
7564 // ResumeValues correspond 1:1 with the scalar loop header phis.
7565 for (auto [ResumeV, HeaderPhi] :
7566 zip(ResumeValues, BestEpiPlan.getScalarHeader()->phis())) {
7567 auto *HeaderPhiR = cast<VPIRPhi>(&HeaderPhi);
7568 auto *EpiResumePhi =
7569 cast<PHINode>(HeaderPhiR->getIRPhi().getIncomingValueForBlock(PH));
7570 if (EpiResumePhi->getBasicBlockIndex(BypassBlock) == -1)
7571 continue;
7572 auto *MainResumePhi = cast<PHINode>(ResumeV->getUnderlyingValue());
7573 EpiResumePhi->setIncomingValueForBlock(
7574 BypassBlock, MainResumePhi->getIncomingValueForBlock(BypassBlock));
7575 }
7576 }
7577}
7578
7579/// Connect the epilogue vector loop generated for \p EpiPlan to the main vector
7580/// loop, after both plans have executed, updating the branch from the iteration
7581/// count check of the main loop, as well as updating various phis.
7583 VPIRBasicBlock *VecEpilogueIterCheckVPBB,
7584 ArrayRef<VPInstruction *> ResumeValues) {
7585 ArrayRef<VPBlockBase *> Preds = VecEpilogueIterCheckVPBB->getPredecessors();
7586 BasicBlock *MainLoopIterationCountCheck =
7587 cast<VPIRBasicBlock>(Preds.front())->getIRBasicBlock();
7588 BasicBlock *VecEpilogueIterationCountCheck =
7589 VecEpilogueIterCheckVPBB->getIRBasicBlock();
7590 BasicBlock *VecEpiloguePreHeader =
7591 cast<CondBrInst>(VecEpilogueIterationCountCheck->getTerminator())
7592 ->getSuccessor(1);
7593 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
7594
7595 MainLoopIterationCountCheck->getTerminator()->replaceSuccessorWith(
7596 VecEpilogueIterationCountCheck, VecEpiloguePreHeader);
7597 DTU.applyUpdates({{DominatorTree::Delete, MainLoopIterationCountCheck,
7598 VecEpilogueIterationCountCheck},
7599 {DominatorTree::Insert, MainLoopIterationCountCheck,
7600 VecEpiloguePreHeader}});
7601
7602 // The vec.epilog.iter.check block may contain Phi nodes from inductions
7603 // or reductions which merge control-flow from the latch block and the
7604 // middle block. Update the incoming values here and move the Phi into the
7605 // preheader.
7606 SmallVector<PHINode *, 4> PhisInBlock(
7607 llvm::make_pointer_range(VecEpilogueIterationCountCheck->phis()));
7608
7609 for (PHINode *Phi : PhisInBlock) {
7610 Phi->moveBefore(VecEpiloguePreHeader->getFirstNonPHIIt());
7611 Phi->replaceIncomingBlockWith(
7612 VecEpilogueIterationCountCheck->getSinglePredecessor(),
7613 VecEpilogueIterationCountCheck);
7614 }
7615
7616 // VecEpilogueIterationCountCheck conditionally skips over the epilogue loop
7617 // after executing the main loop. We need to update the resume values of
7618 // inductions and reductions during epilogue vectorization.
7619 fixScalarResumeValuesFromBypass(VecEpilogueIterationCountCheck, EpiPlan,
7620 ResumeValues);
7621
7622 // Remove dead phis that were moved to the epilogue preheader but are unused
7623 // (e.g., resume phis for inductions not widened in the epilogue vector loop).
7624 for (PHINode &Phi : make_early_inc_range(VecEpiloguePreHeader->phis()))
7625 if (Phi.use_empty())
7626 Phi.eraseFromParent();
7627}
7628
7630 assert((EnableVPlanNativePath || L->isInnermost()) &&
7631 "VPlan-native path is not enabled. Only process inner loops.");
7632
7633 LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
7634 << L->getHeader()->getParent()->getName() << "' from "
7635 << L->getLocStr() << "\n");
7636
7637 LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
7638
7639 LLVM_DEBUG(
7640 dbgs() << "LV: Loop hints:"
7641 << " force="
7643 ? "disabled"
7645 ? "enabled"
7646 : "?"))
7647 << " width=" << Hints.getWidth()
7648 << " interleave=" << Hints.getInterleave() << "\n");
7649
7650 // Function containing loop
7651 Function *F = L->getHeader()->getParent();
7652
7653 // Looking at the diagnostic output is the only way to determine if a loop
7654 // was vectorized (other than looking at the IR or machine code), so it
7655 // is important to generate an optimization remark for each loop. Most of
7656 // these messages are generated as OptimizationRemarkAnalysis. Remarks
7657 // generated as OptimizationRemark and OptimizationRemarkMissed are
7658 // less verbose reporting vectorized loops and unvectorized loops that may
7659 // benefit from vectorization, respectively.
7660
7661 if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
7662 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
7663 return false;
7664 }
7665
7666 PredicatedScalarEvolution PSE(*SE, *L);
7667
7668 // Query this against the original loop and save it here because the profile
7669 // of the original loop header may change as the transformation happens.
7670 bool OptForSize = llvm::shouldOptimizeForSize(
7671 L->getHeader(), PSI,
7672 PSI && PSI->hasProfileSummary() ? &GetBFI() : nullptr,
7674
7675 // Check if it is legal to vectorize the loop.
7676 LoopVectorizationRequirements Requirements;
7677 LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, F, *LAIs, LI, ORE,
7678 &Requirements, &Hints, DB, AC,
7679 /*AllowRuntimeSCEVChecks=*/!OptForSize, AA);
7681 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
7682 Hints.emitRemarkWithHints();
7683 return false;
7684 }
7685
7686 bool IsInnerLoop = L->isInnermost();
7687
7688 // Outer loops require a computable trip count.
7689 if (!IsInnerLoop && isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
7690 LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
7691 return false;
7692 }
7693
7694 if (LVL.hasUncountableEarlyExit()) {
7696 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
7697 "early exit is not enabled",
7698 "UncountableEarlyExitLoopsDisabled", ORE, L);
7699 return false;
7700 }
7703 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
7704 "early exit and side effects is not enabled",
7705 "UncountableEarlyExitSideEffectLoopsDisabled",
7706 ORE, L);
7707 return false;
7708 }
7709 }
7710
7711 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI(), OptForSize);
7712 bool UseInterleaved =
7713 IsInnerLoop && TTI->enableInterleavedAccessVectorization();
7714
7715 // If an override option has been passed in for interleaved accesses, use it.
7716 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
7717 UseInterleaved = IsInnerLoop && EnableInterleavedMemAccesses;
7718
7719 // Analyze interleaved memory accesses.
7720 if (UseInterleaved)
7722
7723 if (LVL.hasUncountableEarlyExit()) {
7724 BasicBlock *LoopLatch = L->getLoopLatch();
7725 if (IAI.requiresScalarEpilogue() ||
7726 any_of(LVL.getCountableExitingBlocks(), not_equal_to(LoopLatch))) {
7727 reportVectorizationFailure("Auto-vectorization of early exit loops "
7728 "requiring a scalar epilogue is unsupported",
7729 "UncountableEarlyExitUnsupported", ORE, L);
7730 return false;
7731 }
7732 }
7733
7734 // Check the function attributes and profiles to find out if this function
7735 // should be optimized for size.
7736 EpilogueLowering SEL =
7737 getEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, LVL, &IAI);
7738
7739 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
7740 // count by optimizing for size, to minimize overheads.
7741 auto ExpectedTC = getSmallBestKnownTC(PSE, L);
7742 if (ExpectedTC && ExpectedTC->isFixed() &&
7743 ExpectedTC->getFixedValue() < TinyTripCountVectorThreshold) {
7744 LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
7745 << "This loop is worth vectorizing only if no scalar "
7746 << "iteration overheads are incurred.");
7748 LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
7749 else {
7750 LLVM_DEBUG(dbgs() << "\n");
7751 // Tail-folded loops are efficient even when the loop
7752 // iteration count is low. However, setting the epilogue policy to
7753 // `CM_EpilogueNotAllowedLowTripLoop` prevents vectorizing loops
7754 // with runtime checks. It's more effective to let
7755 // `isOutsideLoopWorkProfitable` determine if vectorization is
7756 // beneficial for the loop. If the trip count is below the target's
7757 // minimum for tail-folding, the tail cannot be folded, so treat it like
7758 // any other low trip count loop.
7759 if (SEL != CM_EpilogueNotNeededFoldTail ||
7760 ExpectedTC->getFixedValue() <=
7761 TTI->getMinTripCountTailFoldingThreshold())
7763 }
7764 }
7765
7766 // Check the function attributes to see if implicit floats or vectors are
7767 // allowed.
7768 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7770 "Can't vectorize when the NoImplicitFloat attribute is used",
7771 "loop not vectorized due to NoImplicitFloat attribute",
7772 "NoImplicitFloat", ORE, L);
7773 Hints.emitRemarkWithHints();
7774 return false;
7775 }
7776
7777 // Check if the target supports potentially unsafe FP vectorization.
7778 // FIXME: Add a check for the type of safety issue (denormal, signaling)
7779 // for the target we're vectorizing for, to make sure none of the
7780 // additional fp-math flags can help.
7781 if (Hints.isPotentiallyUnsafe() &&
7782 TTI->isFPVectorizationPotentiallyUnsafe()) {
7784 "Potentially unsafe FP op prevents vectorization",
7785 "loop not vectorized due to unsafe FP support.", "UnsafeFP", ORE, L);
7786 Hints.emitRemarkWithHints();
7787 return false;
7788 }
7789
7790 bool AllowOrderedReductions;
7791 // If the flag is set, use that instead and override the TTI behaviour.
7792 if (ForceOrderedReductions.getNumOccurrences() > 0)
7793 AllowOrderedReductions = ForceOrderedReductions;
7794 else
7795 AllowOrderedReductions = TTI->enableOrderedReductions();
7796 if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
7797 ORE->emit([&]() {
7798 auto *ExactFPMathInst = Requirements.getExactFPInst();
7799 return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
7800 ExactFPMathInst->getDebugLoc(),
7801 ExactFPMathInst->getParent())
7802 << "loop not vectorized: cannot prove it is safe to reorder "
7803 "floating-point operations";
7804 });
7805 LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
7806 "reorder floating-point operations\n");
7807 Hints.emitRemarkWithHints();
7808 return false;
7809 }
7810
7811 // Use the cost model.
7812 VFSelectionContext Config(*TTI, &LVL, L, *F, PSE, DB, ORE, &Hints,
7813 OptForSize);
7814 // Use the planner for vectorization.
7816 L, LI, DT, TLI, *TTI, &LVL,
7817 std::make_unique<LoopVectorizationCostModel>(
7818 SEL, L, PSE, LI, &LVL, *TTI, TLI, AC, ORE, GetBFI, F, IAI, Config),
7819 Config, IAI, PSE, ORE, GetBPI);
7820
7821 EpilogueLowering EpilogueTailLoweringStatus =
7822 getEpilogueTailLowering(LVP.getCostModel(), L, ORE, LVL, Hints, TTI);
7823 if (EpilogueTailLoweringStatus ==
7825 // TODO: Apply tail-folding on the vectorized epilogue loop.
7826 LLVM_DEBUG(dbgs() << "LV: epilogue tail-folding is not supported yet\n");
7828 "The epilogue-tail-folding policy prefer-fold-tail is not supported "
7829 "yet, fall back to a normal epilogue",
7830 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
7831 }
7832
7833 // Get user vectorization factor and interleave count.
7834 ElementCount UserVF = Hints.getWidth();
7835 unsigned UserIC = Hints.getInterleave();
7836 // Outer loops don't have LoopAccessInfo, so skip the safety check and reset
7837 // UserIC (interleaving is not supported for outer loops).
7838 if (!IsInnerLoop)
7839 UserIC = 0;
7840 else if (UserIC > 1 && !LVL.isSafeForAnyVectorWidth())
7841 UserIC = 1;
7842
7843 // Plan how to best vectorize.
7844 LVP.plan(UserVF, UserIC);
7845 auto [VF, BestPlanPtr] = LVP.computeBestVF();
7846 unsigned IC = 1;
7847
7848 // For VPlan build stress testing of outer loops, bail after plan
7849 // construction.
7850 if (!IsInnerLoop && VPlanBuildOuterloopStressTest)
7851 return false;
7852
7853 if (IsInnerLoop && ORE->allowExtraAnalysis(LV_NAME))
7855
7856 assert((IsInnerLoop || !LVP.getCostModel().maskPartialAliasing()) &&
7857 "Did not expect to alias-mask outer loop");
7858
7859 GeneratedRTChecks Checks(PSE, DT, LI, TTI, Config.CostKind,
7861 if (IsInnerLoop && LVP.hasPlanWithVF(VF.Width)) {
7862 // Select the interleave count.
7863 IC = LVP.selectInterleaveCount(*BestPlanPtr, VF.Width, VF.Cost);
7864
7865 unsigned SelectedIC = UserIC > 0 ? UserIC : IC;
7866 // Optimistically generate runtime checks if they are needed. Drop them if
7867 // they turn out to not be profitable.
7868 if (VF.Width.isVector() || SelectedIC > 1) {
7869 Checks.create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC,
7870 *ORE);
7871
7872 // Bail out early if either the SCEV or memory runtime checks are known to
7873 // fail. In that case, the vector loop would never execute.
7874 using namespace llvm::PatternMatch;
7875 if (Checks.getSCEVChecks().first &&
7876 match(Checks.getSCEVChecks().first, m_One()))
7877 return false;
7878 if (Checks.getMemRuntimeChecks().first &&
7879 match(Checks.getMemRuntimeChecks().first, m_One()))
7880 return false;
7881 }
7882
7883 // Check if it is profitable to vectorize with runtime checks.
7884 bool ForceVectorization =
7886 VPCostContext CostCtx(*TLI, *BestPlanPtr, LVP.getCostModel(), Config,
7887 /*ReusePrintingSlotTracker=*/true);
7888 if (!ForceVectorization &&
7889 !isOutsideLoopWorkProfitable(Checks, VF, L, PSE, CostCtx, *BestPlanPtr,
7890 SEL, Config.getVScaleForTuning())) {
7891 ORE->emit([&]() {
7893 DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
7894 L->getHeader())
7895 << "loop not vectorized: cannot prove it is safe to reorder "
7896 "memory operations";
7897 });
7898 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7899 Hints.emitRemarkWithHints();
7900 return false;
7901 }
7902 }
7903
7904 // Identify the diagnostic messages that should be produced.
7905 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7906 bool VectorizeLoop = true, InterleaveLoop = true;
7907 if (VF.Width.isScalar()) {
7908 LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
7909 VecDiagMsg = {
7910 "VectorizationNotBeneficial",
7911 "the cost-model indicates that vectorization is not beneficial"};
7912 VectorizeLoop = false;
7913 }
7914
7915 if (UserIC == 1 && Hints.getInterleave() > 1) {
7917 "UserIC should only be ignored due to unsafe dependencies");
7918 LLVM_DEBUG(dbgs() << "LV: Ignoring user-specified interleave count.\n");
7919 IntDiagMsg = {"InterleavingUnsafe",
7920 "Ignoring user-specified interleave count due to possibly "
7921 "unsafe dependencies in the loop."};
7922 InterleaveLoop = false;
7923 } else if (!LVP.hasPlanWithVF(VF.Width) && UserIC > 1) {
7924 // Tell the user interleaving was avoided up-front, despite being explicitly
7925 // requested.
7926 LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
7927 "interleaving should be avoided up front\n");
7928 IntDiagMsg = {"InterleavingAvoided",
7929 "Ignoring UserIC, because interleaving was avoided up front"};
7930 InterleaveLoop = false;
7931 } else if (IC == 1 && UserIC <= 1) {
7932 // Tell the user interleaving is not beneficial.
7933 LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
7934 IntDiagMsg = {
7935 "InterleavingNotBeneficial",
7936 "the cost-model indicates that interleaving is not beneficial"};
7937 InterleaveLoop = false;
7938 if (UserIC == 1) {
7939 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
7940 IntDiagMsg.second +=
7941 " and is explicitly disabled or interleave count is set to 1";
7942 }
7943 } else if (IC > 1 && UserIC == 1) {
7944 // Tell the user interleaving is beneficial, but it explicitly disabled.
7945 LLVM_DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly "
7946 "disabled.\n");
7947 IntDiagMsg = {"InterleavingBeneficialButDisabled",
7948 "the cost-model indicates that interleaving is beneficial "
7949 "but is explicitly disabled or interleave count is set to 1"};
7950 InterleaveLoop = false;
7951 }
7952
7953 // If there is a histogram in the loop, do not just interleave without
7954 // vectorizing. The order of operations will be incorrect without the
7955 // histogram intrinsics, which are only used for recipes with VF > 1.
7956 if (!VectorizeLoop && InterleaveLoop && LVL.hasHistograms()) {
7957 LLVM_DEBUG(dbgs() << "LV: Not interleaving without vectorization due "
7958 << "to histogram operations.\n");
7959 IntDiagMsg = {
7960 "HistogramPreventsScalarInterleaving",
7961 "Unable to interleave without vectorization due to constraints on "
7962 "the order of histogram operations"};
7963 InterleaveLoop = false;
7964 }
7965
7966 // Override IC if user provided an interleave count.
7967 IC = UserIC > 0 ? UserIC : IC;
7968
7969 if (LVP.getCostModel().maskPartialAliasing()) {
7970 LLVM_DEBUG(
7971 dbgs()
7972 << "LV: Not interleaving due to partial aliasing vectorization.\n");
7973 IntDiagMsg = {
7974 "PartialAliasingVectorization",
7975 "Unable to interleave due to partial aliasing vectorization."};
7976 InterleaveLoop = false;
7977 IC = 1;
7978 }
7979
7980 // FIXME: Enable interleaving for EE-with-side-effects.
7981 if (InterleaveLoop && LVL.hasUncountableExitWithSideEffects()) {
7982 LLVM_DEBUG(dbgs() << "LV: Not interleaving due to EE with side effects.\n");
7983 IntDiagMsg = {"EEWithSideEffectsPreventsInterleaving",
7984 "Unable to interleave due to early exit with side effects."};
7985 InterleaveLoop = false;
7986 IC = 1;
7987 }
7988
7989 // Emit diagnostic messages, if any.
7990 if (!VectorizeLoop && !InterleaveLoop) {
7991 // Do not vectorize or interleaving the loop.
7992 ORE->emit([&]() {
7993 return OptimizationRemarkMissed(LV_NAME, VecDiagMsg.first,
7994 L->getStartLoc(), L->getHeader())
7995 << VecDiagMsg.second;
7996 });
7997 ORE->emit([&]() {
7998 return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
7999 L->getStartLoc(), L->getHeader())
8000 << IntDiagMsg.second;
8001 });
8002 return false;
8003 }
8004
8005 if (!VectorizeLoop && InterleaveLoop) {
8006 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8007 ORE->emit([&]() {
8008 return OptimizationRemarkAnalysis(LV_NAME, VecDiagMsg.first,
8009 L->getStartLoc(), L->getHeader())
8010 << VecDiagMsg.second;
8011 });
8012 } else if (VectorizeLoop && !InterleaveLoop) {
8013 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
8014 << ") in " << L->getLocStr() << '\n');
8015 ORE->emit([&]() {
8016 return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
8017 L->getStartLoc(), L->getHeader())
8018 << IntDiagMsg.second;
8019 });
8020 } else if (VectorizeLoop && InterleaveLoop) {
8021 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
8022 << ") in " << L->getLocStr() << '\n');
8023 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8024 }
8025
8026 // Report the vectorization decision.
8027 if (VF.Width.isScalar()) {
8028 using namespace ore;
8029 assert(IC > 1);
8030 ORE->emit([&]() {
8031 return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
8032 L->getHeader())
8033 << "interleaved loop (interleaved count: "
8034 << NV("InterleaveCount", IC) << ")";
8035 });
8036 } else {
8037 // Report the vectorization decision.
8038 reportVectorization(ORE, L, VF.Width, IC);
8039 }
8040 if (ORE->allowExtraAnalysis(LV_NAME))
8042
8043 // If we decided that it is *legal* to interleave or vectorize the loop, then
8044 // do it.
8045
8046 // Whether a scalar epilogue may be created is decided by the epilogue
8047 // lowering policy.
8048 // TODO: Also move check to be based on VPlan.
8049 bool ScalarEpilogueAllowed = LVP.getCostModel().isEpilogueAllowed();
8050
8051 // Destroy the cost model before executing any plan, so that code generation
8052 // cannot rely on cost-modeling decisions.
8053 LVP.clearCostModel();
8054
8055 VPlan &BestPlan = *BestPlanPtr;
8056 // Consider vectorizing the epilogue too if it's profitable.
8057 std::unique_ptr<VPlan> EpiPlan =
8058 LVP.selectBestEpiloguePlan(BestPlan, VF.Width, IC, ScalarEpilogueAllowed);
8059 bool HasBranchWeights =
8060 hasBranchWeightMD(*L->getLoopLatch()->getTerminator());
8061 if (EpiPlan) {
8062 VPlan &BestEpiPlan = *EpiPlan;
8063 VPlan &BestMainPlan = BestPlan;
8064 ElementCount EpilogueVF = BestEpiPlan.getSingleVF();
8065
8066 // The first pass vectorizes the main loop and creates a scalar epilogue
8067 // to be vectorized by executing the plan (potentially with a different
8068 // factor) again shortly afterwards.
8069 BestEpiPlan.getMiddleBlock()->setName("vec.epilog.middle.block");
8070 BestEpiPlan.getVectorPreheader()->setName("vec.epilog.ph");
8072
8073 // Add minimum iteration check for the epilogue plan, followed by runtime
8074 // checks for the main plan.
8075 LVP.addMinimumIterationCheck(BestMainPlan, EpilogueVF, /*UF=*/1,
8077 LVP.attachRuntimeChecks(BestMainPlan, Checks, HasBranchWeights);
8079 VF.Width, IC, BestMainPlan.requiresScalarEpilogue(), L,
8080 HasBranchWeights ? MinItersBypassWeights : nullptr,
8081 L->getLoopPredecessor()->getTerminator()->getDebugLoc(),
8082 PSE);
8083
8084 LLVM_DEBUG({
8085 dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8086 << "Main Loop VF:" << VF.Width << ", Main Loop UF:" << IC
8087 << ", Epilogue Loop VF:" << EpilogueVF << ", Epilogue Loop UF:1\n";
8088 });
8089 InnerLoopVectorizer MainILV(L, PSE, LI, DT, TTI, AC, VF.Width, IC, Checks,
8090 BestMainPlan);
8091 auto ExpandedSCEVs = LVP.executePlan(
8092 VF.Width, IC, BestMainPlan, MainILV, DT,
8094 ++LoopsVectorized;
8096 dbgs() << "intermediate fn:\n" << *L->getHeader()->getParent() << "\n";
8097 });
8098
8099 BasicBlock *EntryBB =
8100 cast<VPIRBasicBlock>(BestMainPlan.getEntry())->getIRBasicBlock();
8101 EntryBB->setName("iter.check");
8102
8103 // Second pass vectorizes the epilogue and adjusts the control flow
8104 // edges from the first pass.
8105 EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TTI, AC,
8106 EpilogueVF, /*UnrollFactor=*/1,
8107 Checks, BestEpiPlan, BestMainPlan);
8108 preparePlanForEpilogueVectorLoop(BestMainPlan, BestEpiPlan, L,
8109 ExpandedSCEVs, VF.Width, IC, EpilogueVF,
8110 LVP, Config, *PSE.getSE(), Markers);
8112 LLVM_DEBUG({
8113 dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8114 << "Epilogue Loop VF:" << EpilogueVF << ", Epilogue Loop UF:1\n";
8115 });
8116 LVP.executePlan(
8117 EpilogueVF, /*BestUF=*/1, BestEpiPlan, EpilogILV, DT,
8120 dbgs() << "final fn:\n" << *L->getHeader()->getParent() << "\n";
8121 });
8122 connectEpilogueVectorLoop(BestEpiPlan, DT,
8124 Markers.ResumeValues);
8125 ++LoopsEpilogueVectorized;
8126 } else {
8127 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, IC, Checks,
8128 BestPlan);
8129 LVP.addMinimumIterationCheck(BestPlan, VF.Width, IC,
8130 VF.MinProfitableTripCount);
8131 LVP.attachRuntimeChecks(BestPlan, Checks, HasBranchWeights);
8132
8133 if (!IsInnerLoop)
8134 LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \"" << F->getName()
8135 << "\"\n");
8136 LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
8137 ++LoopsVectorized;
8138 }
8139
8140 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
8141 "DT not preserved correctly");
8142
8143 return true;
8144}
8145
8147 CFGChanged = false;
8148
8149 // Don't attempt if
8150 // 1. the target claims to have no vector registers, and
8151 // 2. interleaving won't help ILP.
8152 //
8153 // The second condition is necessary because, even if the target has no
8154 // vector registers, loop vectorization may still enable scalar
8155 // interleaving.
8156 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
8157 (TTI->getMaxInterleaveFactor(ElementCount::getFixed(1), false) < 2 ||
8158 TTI->getMaxInterleaveFactor(ElementCount::getFixed(1), true) < 2))
8159 return LoopVectorizeResult(false, false);
8160
8161 bool Changed = false;
8162
8163 // The vectorizer requires loops to be in simplified form.
8164 // Since simplification may add new inner loops, it has to run before the
8165 // legality and profitability checks. This means running the loop vectorizer
8166 // will simplify all loops, regardless of whether anything end up being
8167 // vectorized.
8168 for (const auto &L : *LI)
8169 Changed |= CFGChanged |=
8170 simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
8171
8172 // Build up a worklist of inner-loops to vectorize. This is necessary as
8173 // the act of vectorizing or partially unrolling a loop creates new loops
8174 // and can invalidate iterators across the loops.
8175 SmallVector<Loop *, 8> Worklist;
8176
8177 for (Loop *L : *LI)
8178 collectSupportedLoops(*L, LI, ORE, Worklist);
8179
8180 LoopsAnalyzed += Worklist.size();
8181
8182 // Now walk the identified inner loops.
8183 while (!Worklist.empty()) {
8184 Loop *L = Worklist.pop_back_val();
8185
8186 // For the inner loops we actually process, form LCSSA to simplify the
8187 // transform.
8188 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
8189
8191
8192 if (Changed) {
8193 LAIs->clear();
8194
8195#ifndef NDEBUG
8196 if (VerifySCEV)
8197 SE->verify();
8198#endif
8199 }
8200 }
8201
8202 // Verify once per function rather than once per processed loop, which would
8203 // make the pass quadratic in the number of loops.
8204 assert((!Changed || !verifyFunction(F, &dbgs())) &&
8205 "Invalid IR produced by LoopVectorize");
8206
8207 // Process each loop nest in the function.
8209}
8210
8213 LI = &AM.getResult<LoopAnalysis>(F);
8214 // There are no loops in the function. Return before computing other
8215 // expensive analyses.
8216 if (LI->empty())
8217 return PreservedAnalyses::all();
8226 AA = &AM.getResult<AAManager>(F);
8227
8228 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
8229 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
8230 // CycleInfo cached by an earlier pass is invalidated when the CFG changes.
8231 // Both BlockFrequencyAnalysis and BranchProbabilityAnalysis depend on it, so
8232 // drop the stale result before either is (re-)computed.
8233 auto ClearStaleCycleInfo = [this, &AM, &F] {
8236 };
8237 GetBFI = [&AM, &F, ClearStaleCycleInfo]() -> BlockFrequencyInfo & {
8238 ClearStaleCycleInfo();
8240 };
8241 GetBPI = [&AM, &F, ClearStaleCycleInfo]() -> const BranchProbabilityInfo & {
8242 ClearStaleCycleInfo();
8244 };
8245 LoopVectorizeResult Result = runImpl(F);
8246 if (!Result.MadeAnyChange)
8247 return PreservedAnalyses::all();
8249
8250 if (isAssignmentTrackingEnabled(*F.getParent())) {
8251 for (auto &BB : F)
8253 }
8254
8255 PA.preserve<LoopAnalysis>();
8259
8260 if (Result.MadeCFGChange) {
8261 // Making CFG changes likely means a loop got vectorized. Indicate that
8262 // extra simplification passes should be run.
8263 // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
8264 // be run if runtime checks have been added.
8267 } else {
8269 }
8270 return PA;
8271}
8272
8274 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
8275 static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
8276 OS, MapClassName2PassName);
8277
8278 OS << '<';
8279 OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
8280 OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
8281 OS << '>';
8282}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Lower Kernel Arguments
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This is the interface for LLVM's primary stateless and local alias analysis.
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static InstructionCost getCost(Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:73
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
This file defines the DenseMap class.
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static cl::opt< ElementCount, true > VectorizationFactor("force-vector-width", cl::Hidden, cl::desc("Sets the SIMD width. Zero is autoselect."), cl::location(VectorizerParams::VectorizationFactor))
This header provides classes for managing per-loop analyses.
static const char * VerboseDebug
#define LV_NAME
This file defines the LoopVectorizationLegality class.
static cl::opt< bool > ConsiderRegPressure("vectorizer-consider-reg-pressure", cl::init(false), cl::Hidden, cl::desc("Discard VFs if their register pressure is too high."))
This file provides a LoopVectorizationPlanner class.
static void collectSupportedLoops(Loop &L, LoopInfo *LI, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Loop * > &V)
static cl::opt< unsigned > EpilogueVectorizationMinVF("epilogue-vectorization-minimum-VF", cl::Hidden, cl::desc("Only loops with vectorization factor equal to or larger than " "the specified value are considered for epilogue vectorization."))
static unsigned getMaxTCFromNonZeroRange(PredicatedScalarEvolution &PSE, Loop *L)
Get the maximum trip count for L from the SCEV unsigned range, excluding zero from the range.
static Type * maybeVectorizeType(Type *Ty, ElementCount VF)
static ElementCount getSmallConstantTripCount(ScalarEvolution *SE, const Loop *L)
A version of ScalarEvolution::getSmallConstantTripCount that returns an ElementCount to include loops...
static cl::opt< unsigned > TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), cl::Hidden, cl::desc("Loops with a constant trip count that is smaller than this " "value are vectorized only if no scalar iteration overheads " "are incurred."))
Loops with a known constant trip count below this number are vectorized only if no scalar iteration o...
static cl::opt< unsigned > PragmaVectorizeSCEVCheckThreshold("pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed with a " "vectorize(enable) pragma"))
static cl::opt< cl::boolOrDefault > ForceMaskedDivRem("force-widen-divrem-via-masked-intrinsic", cl::Hidden, cl::desc("Override cost based masked intrinsic widening " "for div/rem instructions"))
static void legacyCSE(BasicBlock *BB)
FIXME: This legacy common-subexpression-elimination routine is scheduled for removal,...
static VPIRBasicBlock * replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB, VPlan *Plan=nullptr)
Replace VPBB with a VPIRBasicBlock wrapping IRBB.
static void fixScalarResumeValuesFromBypass(BasicBlock *BypassBlock, VPlan &BestEpiPlan, ArrayRef< VPInstruction * > ResumeValues)
static Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
static DebugLoc getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or its operands.
static cl::opt< unsigned > LowTripCountLoopBodySizeLimit("low-trip-count-loop-body-size-limit", cl::init(20), cl::Hidden, cl::desc("Minimum number of instructions to vectorize loops with trip " "counts below tail folding threshold"))
TailFoldingPolicyTy
Option tail-folding-policy controls the tail-folding strategy and lists all available options.
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
static std::optional< VPExecutionFrequency > getRecordedExecutionFrequency(const VPBasicBlock *VPBB)
Returns the frequency with which VPBB executes, as recorded on its recipes.
static cl::opt< TailFoldingPolicyTy > EpilogueTailFoldingPolicy("epilogue-tail-folding-policy", cl::Hidden, cl::desc("Epilogue-tail-folding preferences over creating an epilogue loop."), cl::values(clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail", "Don't tail-fold loops."), clEnumValN(TailFoldingPolicyTy::PreferFoldTail, "prefer-fold-tail", "prefer tail-folding, otherwise create an epilogue when " "appropriate.")))
static cl::opt< bool > EnableEarlyExitVectorization("enable-early-exit-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits."))
static unsigned estimateElementCount(ElementCount VF, std::optional< unsigned > VScale)
This function attempts to return a value that represents the ElementCount at runtime.
static bool hasVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns true iff CI has a library vector variant usable at VF.
static constexpr uint32_t MinItersBypassWeights[]
static cl::opt< unsigned > ForceTargetNumScalarRegs("force-target-num-scalar-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of scalar registers."))
static cl::opt< unsigned > SmallLoopCost("small-loop-cost", cl::init(20), cl::Hidden, cl::desc("The cost of a loop that is considered 'small' by the interleaver."))
static cl::opt< bool > ForcePartialAliasingVectorization("force-partial-aliasing-vectorization", cl::init(false), cl::Hidden, cl::desc("Replace pointer diff checks with alias masks."))
static void preparePlanForEpilogueVectorLoop(VPlan &MainPlan, VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs, ElementCount MainLoopVF, unsigned MainLoopUF, ElementCount EpilogueVF, LoopVectorizationPlanner &LVP, VFSelectionContext &Config, ScalarEvolution &SE, const MainPlanResumeMarkers &Markers)
Prepare Plan for vectorizing the epilogue loop.
static Function * getVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns the vector library variant function of CI usable at VF, respecting MaskRequired,...
static cl::opt< unsigned > ForceTargetNumVectorRegs("force-target-num-vector-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of vector registers."))
static bool isExplicitVecOuterLoop(Loop *OuterLp, OptimizationRemarkEmitter *ORE)
static cl::opt< bool > EnableIndVarRegisterHeur("enable-ind-var-reg-heur", cl::init(true), cl::Hidden, cl::desc("Count the induction variable only once when interleaving"))
static bool hasForcedEpilogueVF()
static cl::opt< TailFoldingStyle > ForceTailFoldingStyle("force-tail-folding-style", cl::desc("Force the tail folding style"), cl::init(TailFoldingStyle::None), cl::values(clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"), clEnumValN(TailFoldingStyle::Data, "data", "Create lane mask for data only, using active.lane.mask intrinsic"), clEnumValN(TailFoldingStyle::DataWithoutLaneMask, "data-without-lane-mask", "Create lane mask with compare/stepvector"), clEnumValN(TailFoldingStyle::DataAndControlFlow, "data-and-control", "Create lane mask using active.lane.mask intrinsic, and use " "it for both data and control flow"), clEnumValN(TailFoldingStyle::DataWithEVL, "data-with-evl", "Use predicated EVL instructions for tail folding. If EVL " "is unsupported, fallback to data-without-lane-mask.")))
static cl::opt< bool > EnableVPlanNativePath("enable-vplan-native-path", cl::Hidden, cl::desc("Enable VPlan-native vectorization path with " "support for outer loop vectorization."))
static void printOptimizedVPlan(VPlan &)
static cl::opt< bool > EnableEpilogueVectorization("enable-epilogue-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of epilogue loops."))
static cl::opt< bool > PreferPredicatedReductionSelect("prefer-predicated-reduction-select", cl::init(false), cl::Hidden, cl::desc("Prefer predicating a reduction operation over an after loop select."))
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
static cl::opt< bool > EnableLoadStoreRuntimeInterleave("enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, cl::desc("Enable runtime interleaving until load/store ports are saturated"))
static cl::opt< bool > LoopVectorizeWithBlockFrequency("loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden, cl::desc("Enable the use of the block frequency analysis to access PGO " "heuristics minimizing code growth in cold regions and being more " "aggressive in hot regions."))
static EpilogueLowering getEpilogueTailLowering(const LoopVectorizationCostModel &MainCM, const Loop *L, OptimizationRemarkEmitter *ORE, LoopVectorizationLegality &LVL, const LoopVectorizeHints &Hints, TargetTransformInfo *TTI)
Determine how to lower the epilogue for the vector epilogue loop.
static bool useActiveLaneMask(TailFoldingStyle Style)
static bool hasReplicatorRegion(VPlan &Plan)
static std::optional< ElementCount > getSmallBestKnownTC(PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax=true, bool CanExcludeZeroTrips=false, bool ComputeUpperBoundOnly=false)
Returns "best known" trip count, which is either a valid positive trip count or std::nullopt when an ...
static bool isIndvarOverflowCheckKnownFalse(const LoopVectorizationCostModel *Cost, ElementCount VF, std::optional< unsigned > UF=std::nullopt)
For the given VF and UF and maximum trip count computed for the loop, return whether the induction va...
static void addFullyUnrolledInstructionsToIgnore(Loop *L, const LoopVectorizationLegality::InductionList &IL, SmallPtrSetImpl< Instruction * > &InstsToIgnore)
Knowing that loop L executes a single vector iteration, add instructions that will get simplified and...
static bool hasFindLastReductionPhi(VPlan &Plan)
Returns true if the VPlan contains a VPReductionPHIRecipe with FindLast recurrence kind.
static cl::opt< bool > EnableInterleavedMemAccesses("enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on interleaved memory accesses in a loop"))
static cl::opt< unsigned > VectorizeSCEVCheckThreshold("vectorize-scev-check-threshold", cl::init(16), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed."))
static cl::opt< bool > EnableMaskedInterleavedMemAccesses("enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"))
An interleave-group may need masking if it resides in a block that needs predication,...
static cl::opt< bool > ForceOrderedReductions("force-ordered-reductions", cl::init(false), cl::Hidden, cl::desc("Enable the vectorisation of loops with in-order (strict) " "FP reductions"))
static cl::opt< bool > EnableEarlyExitVectorizationWithSideEffects("enable-early-exit-vectorization-with-side-effects", cl::init(false), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits " "and side effects"))
static bool verifyExecutionFrequenciesMatchBFI(VPlan &Plan, Loop *OrigLoop, LoopInfo *LI, LoopVectorizationCostModel &CM)
Cross-check the execution frequencies recorded in Plan against BlockFrequencyInfo for the blocks of O...
static cl::opt< TailFoldingPolicyTy > TailFoldingPolicy("tail-folding-policy", cl::init(TailFoldingPolicyTy::None), cl::Hidden, cl::desc("Tail-folding preferences over creating an epilogue loop."), cl::values(clEnumValN(TailFoldingPolicyTy::None, "dont-fold-tail", "Don't tail-fold loops."), clEnumValN(TailFoldingPolicyTy::PreferFoldTail, "prefer-fold-tail", "prefer tail-folding, otherwise create an epilogue when " "appropriate."), clEnumValN(TailFoldingPolicyTy::MustFoldTail, "must-fold-tail", "always tail-fold, don't attempt vectorization if " "tail-folding fails.")))
static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, Loop *L, PredicatedScalarEvolution &PSE, VPCostContext &CostCtx, VPlan &Plan, EpilogueLowering SEL, std::optional< unsigned > VScale)
This function determines whether or not it's still profitable to vectorize the loop given the extra w...
static InstructionCost calculateEarlyExitCost(VPCostContext &CostCtx, VPlan &Plan, ElementCount VF)
For loops with uncountable early exits, find the cost of doing work when exiting the loop early,...
static cl::opt< unsigned > ForceTargetMaxVectorInterleaveFactor("force-target-max-vector-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "vectorized loops."))
static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI)
static EpilogueLowering getEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
static cl::opt< unsigned > MaxNestedScalarReductionIC("max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, cl::desc("The maximum interleave count to use when interleaving a scalar " "reduction in a nested loop."))
static cl::opt< unsigned > ForceTargetMaxScalarInterleaveFactor("force-target-max-scalar-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "scalar loops."))
static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE)
static cl::opt< ElementCount > EpilogueVectorizationForceVF("epilogue-vectorization-force-VF", cl::init(ElementCount::getFixed(1)), cl::Hidden, cl::desc("When epilogue vectorization is enabled, and a value greater than " "1 is specified, forces the given VF for all applicable epilogue " "loops. Note: This allows all scalable VFs >= vscale x 1."))
static void connectEpilogueVectorLoop(VPlan &EpiPlan, DominatorTree *DT, VPIRBasicBlock *VecEpilogueIterCheckVPBB, ArrayRef< VPInstruction * > ResumeValues)
Connect the epilogue vector loop generated for EpiPlan to the main vector loop, after both plans have...
static bool willGenerateVectors(VPlan &Plan, ElementCount VF, const TargetTransformInfo &TTI)
Check if any recipe of Plan will generate a vector value, which will be assigned a vector register.
static MainPlanResumeMarkers preparePlanForMainVectorLoop(VPlan &MainPlan)
Prepare MainPlan for vectorizing the main vector loop during epilogue vectorization.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
R600 Emit Clause Markers
const SmallVectorImpl< MachineOperand > & Cond
SI Fold Operands
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
#define OP(OPC)
Definition Instruction.h:46
This file defines the SmallPtrSet class.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
This pass exposes codegen information to IR-level passes.
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS(PASS,...)
#define RUN_VPLAN_PASS_NO_VERIFY(PASS,...)
This file declares the class VPlanVerifier, which contains utility functions to check the consistency...
This file contains the declarations of the Vectorization Plan base classes:
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
void clearAnalysis(IRUnitT &IR)
Directly clear a cached analysis for an IR unit.
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > take_back(size_t N=1) const
Return a copy of *this with only the last N elements.
Definition ArrayRef.h:225
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
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 * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
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...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
uint32_t getNumerator() const
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Conditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This class represents a range of values.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
Analysis pass which computes a CycleInfo.
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getTemporary()
Definition DebugLoc.h:152
static DebugLoc getUnknown()
Definition DebugLoc.h:153
An analysis that produces DemandedBits for a function.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:758
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
void insert_range(Range &&R)
Inserts range of 'std::pair<KeyT, ValueT>' values into the map.
Definition DenseMap.h:895
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:812
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:804
iterator end()
Definition DenseMap.h:687
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:794
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:320
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:308
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
A specialized derived class of inner loop vectorizer that performs vectorization of epilogue loops in...
BasicBlock * createVectorizedLoopSkeleton() final
Implements the interface for creating a vectorized skeleton using the epilogue loop strategy (i....
EpilogueVectorizerEpilogueLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, ElementCount VecWidth, unsigned UnrollFactor, GeneratedRTChecks &Checks, VPlan &Plan, VPlan &MainPlan)
Tagged union holding either a T or a Error.
Definition Error.h:485
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Class to represent function types.
param_iterator param_begin() const
param_iterator param_end() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
A struct for saving information about induction variables.
ArrayRef< Instruction * > getCastInsts() const
Returns an ArrayRef to the type cast instructions in the induction update chain, that are redundant w...
@ IK_PtrInduction
Pointer induction var. Step = C.
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
const TargetTransformInfo * TTI
Target Transform Info.
friend class LoopVectorizationPlanner
PredicatedScalarEvolution & PSE
A wrapper around ScalarEvolution used to add runtime SCEV checks.
LoopInfo * LI
Loop Info.
DominatorTree * DT
Dominator Tree.
InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, ElementCount VecWidth, unsigned UnrollFactor, GeneratedRTChecks &RTChecks, VPlan &Plan)
void fixVectorizedLoop(VPTransformState &State)
Fix the vectorized code, taking care of header phi's, and more.
virtual BasicBlock * createVectorizedLoopSkeleton()
Creates a basic block for the scalar preheader.
AssumptionCache * AC
Assumption Cache.
IRBuilder Builder
The builder that we use.
VPBasicBlock * VectorPHVPBB
The vector preheader block of Plan, used as target for check blocks introduced during skeleton creati...
unsigned UF
The vectorization unroll factor to use.
GeneratedRTChecks & RTChecks
Structure to hold information about generated runtime checks, responsible for cleaning the checks,...
virtual ~InnerLoopVectorizer()=default
ElementCount VF
The vectorization SIMD factor to use.
Loop * OrigLoop
The original loop.
BasicBlock * createScalarPreheader(StringRef Prefix)
Create and return a new IR basic block for the scalar preheader whose name is prefixed with Prefix.
static InstructionCost getInvalid(CostType Val=0)
static InstructionCost getMax()
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
bool isCast() const
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
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.
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
iterator_range< user_iterator > users()
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
LLVM_ABI APInt getMask() const
For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
Definition Type.cpp:362
The group of interleaved loads/stores sharing the same stride and close to each other.
auto members() const
Return an iterator range over the non-null members of this group, in index order.
InstTy * getInsertPos() const
uint32_t getNumMembers() const
Drive the analysis of interleaved memory accesses in the loop.
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
bool hasGroups() const
Returns true if we have any interleave groups.
LLVM_ABI void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
An instruction for reading from memory.
Type * getPointerOperandType() const
This analysis provides dependence information for the memory accesses of a loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const SymbolicStrideMap & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
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.
LLVM_ABI void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
bool isPredicatedInst(Instruction *I) const
Returns true if I is an instruction that needs to be predicated at runtime.
void collectValuesToIgnore()
Collect values we want to ignore in the cost model.
BlockFrequencyInfo * BFI
The BlockFrequencyInfo returned from GetBFI.
BlockFrequencyInfo & getBFI()
Returns the BlockFrequencyInfo for the function if cached, otherwise fetches it via GetBFI.
bool isForcedScalar(Instruction *I, ElementCount VF) const
Returns true if I has been forced to be scalarized at VF.
bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be uniform after vectorization.
void collectNonVectorizedAndSetWideningDecisions(ElementCount VF)
Collect values that will not be widened, including Uniforms, Scalars, and Instructions to Scalarize f...
static constexpr StringLiteral getInstWideningStr(InstWidening W)
bool isMaskRequired(Instruction *I) const
Wrapper function for LoopVectorizationLegality::isMaskRequired, that passes the Instruction I and if ...
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
const TargetTransformInfo & TTI
Vector target information.
LoopVectorizationLegality * Legal
Vectorization legality.
uint64_t getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind, const BasicBlock *BB)
A helper function that returns how much we should divide the cost of a predicated block by.
std::optional< InstWidening > memoryInstructionCanBeWidened(Instruction *I, ElementCount VF)
If I is a memory instruction with a consecutive pointer that can be widened, returns the widening kin...
InstructionCost getInstructionCost(Instruction *I, ElementCount VF)
Returns the execution time cost of an instruction for a given vector width.
bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const
Returns true if I is a memory instruction in an interleaved-group of memory accesses that can be vect...
const TargetLibraryInfo * TLI
Target Library Info.
const InterleaveGroup< Instruction > * getInterleavedAccessGroup(Instruction *Instr) const
Get the interleaved access group that Instr belongs to.
InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const
Estimate cost of an intrinsic call instruction CI if it were vectorized with factor VF.
bool maskPartialAliasing() const
Returns true if all loop blocks should have partial aliases masked.
bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalar after vectorization.
bool isOptimizableIVTruncate(Instruction *I, ElementCount VF)
Return True if instruction I is an optimizable truncate whose operand is an induction variable.
bool isLegalGatherOrScatter(Instruction *I, ElementCount VF) const
Returns true if the target machine supports gather or scatter for I's data type and alignment.
FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC)
Loop * TheLoop
The loop that we evaluate.
InterleavedAccessInfo & InterleaveInfo
The interleave access information contains groups of interleaved accesses with the same stride and cl...
SmallPtrSet< const Value *, 16 > ValuesToIgnore
Values to ignore in the cost model.
LoopVectorizationCostModel(EpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, const Function *F, InterleavedAccessInfo &IAI, VFSelectionContext &Config)
void invalidateCostModelingDecisions()
Invalidates decisions already taken by the cost model.
bool isAccessInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleaved access group.
void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC)
Selects and saves TailFoldingStyle.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
LoopInfo * LI
Loop Info analysis.
bool requiresScalarEpilogue(bool IsVectorizing) const
Returns true if we're required to use a scalar epilogue for at least the final iteration of the origi...
SmallPtrSet< const Value *, 16 > VecValuesToIgnore
Values to ignore in the cost model when VF > 1.
bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF) const
Returns true if an artificially high cost for emulated masked memrefs should be used.
bool isLegalMaskedLoadOrStore(Instruction *I, ElementCount VF) const
Returns true if the target machine supports masked loads or stores for I's data type and alignment.
bool isProfitableToScalarize(Instruction *I, ElementCount VF) const
void setWideningDecision(const InterleaveGroup< Instruction > *Grp, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for interleaving group Grp and vector ...
bool isEpilogueAllowed() const
Returns true if an epilogue is allowed (e.g., not prevented by optsize or a loop hint annotation).
bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const
bool shouldConsiderInvariant(Value *Op)
Returns true if Op should be considered invariant and if it is trivially hoistable.
bool foldTailByMasking() const
Returns true if all loop blocks should be masked to fold tail loop.
bool foldTailWithEVL() const
Returns true if VP intrinsics with explicit vector length support should be generated in the tail fol...
bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const
Returns true if the instructions in this block requires predication for any reason,...
AssumptionCache * AC
Assumption cache.
void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for instruction I and vector width VF.
InstWidening
Decision that was taken during cost calculation for memory instruction.
@ CM_InvalidatedDecision
A widening decision that has been invalidated after replacing the corresponding recipe during VPlan t...
bool usePredicatedReductionSelect(RecurKind RecurrenceKind) const
Returns true if the predicated reduction select should be used to set the incoming value for the redu...
std::pair< InstructionCost, InstructionCost > getDivRemSpeculationCost(Instruction *I, ElementCount VF)
Return the costs for our two available strategies for lowering a div/rem operation which requires spe...
InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const
Estimate cost of a call instruction CI if it were vectorized with factor VF.
bool isScalarWithPredication(Instruction *I, ElementCount VF)
Returns true if I is an instruction which requires predication and for which our chosen predication s...
std::function< BlockFrequencyInfo &()> GetBFI
A function to lazily fetch BlockFrequencyInfo.
InstructionCost expectedCost(ElementCount VF)
Returns the expected execution cost.
void setCostBasedWideningDecision(ElementCount VF)
Memory access instruction may be vectorized in more than one way.
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost MaskedCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
InstWidening getWideningDecision(Instruction *I, ElementCount VF) const
Return the cost model decision for the given instruction I and vector width VF.
InstructionCost getWideningCost(Instruction *I, ElementCount VF)
Return the vectorization cost for the given instruction I and vector width VF.
TailFoldingStyle getTailFoldingStyle() const
Returns the TailFoldingStyle that is best for the current loop.
void collectInstsToScalarize(ElementCount VF)
Collects the instructions to scalarize for each predicated instruction in the loop.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
MapVector< PHINode *, InductionDescriptor > InductionList
InductionList saves induction variables and maps them to the induction descriptor.
RecurrenceSet & getFixedOrderRecurrences()
Return the fixed-order recurrences found in the loop.
LLVM_ABI bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
bool hasUncountableExitWithSideEffects() const
Returns true if this is an early exit loop with state-changing or potentially-faulting operations and...
LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool hasUncountableEarlyExit() const
Returns true if the loop has uncountable early exits, i.e.
bool hasHistograms() const
Returns a list of all known histogram operations in the loop.
const LoopAccessInfo * getLAI() const
Planner drives the vectorization process after having passed Legality checks.
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, EpilogueVectorizationKind EpilogueVecKind=EpilogueVectorizationKind::None)
EpilogueVectorizationKind
Generate the IR code for the vectorized loop captured in VPlan BestPlan according to the best selecte...
@ MainLoop
Vectorizing the main loop of epilogue vectorization.
void clearCostModel()
Destroy the cost model.
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
Definition VPlan.cpp:1651
void updateLoopMetadataAndProfileInfo(Loop *VectorLoop, VPBasicBlock *HeaderVPBB, const VPlan &Plan, bool VectorizingEpilogue, MDNode *OrigLoopID, std::optional< unsigned > OrigAverageTripCount, unsigned OrigLoopInvocationWeight, unsigned EstimatedVFxUF, bool DisableRuntimeUnroll, bool UnrollVectorizedLoop)
Update loop metadata and profile info for both the scalar remainder loop and VectorLoop,...
Definition VPlan.cpp:1702
LoopVectorizationCostModel & getCostModel()
Return the cost model. Must not be called after clearCostModel().
void attachRuntimeChecks(VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const
Attach the runtime checks of RTChecks to Plan.
unsigned selectInterleaveCount(VPlan &Plan, ElementCount VF, InstructionCost LoopCost)
void emitInvalidCostRemarks(OptimizationRemarkEmitter *ORE)
Emit remarks for recipes with invalid costs in the available VPlans.
LoopVectorizationPlanner(Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal, std::unique_ptr< LoopVectorizationCostModel > CM, VFSelectionContext &Config, InterleavedAccessInfo &IAI, PredicatedScalarEvolution &PSE, OptimizationRemarkEmitter *ORE, std::function< const BranchProbabilityInfo &()> GetBPI)
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
Definition VPlan.cpp:1637
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1806
std::unique_ptr< VPlan > selectBestEpiloguePlan(VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC, bool ScalarEpilogueAllowed)
void plan(ElementCount UserVF, unsigned UserIC)
Build VPlans for the specified UserVF and UserIC if they are non-zero or all applicable candidate VFs...
void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount) const
Create a check to Plan to see if the vector loop should be executed based on its trip count.
bool hasPlanWithVF(ElementCount VF) const
Look through the existing plans and return true if we have one with vectorization factor VF.
std::pair< VectorizationFactor, VPlan * > computeBestVF()
Compute and return the most profitable vectorization factor and the corresponding best VPlan.
This holds vectorization requirements that must be verified late in the process.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
LLVM_ABI bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:235
Diagnostic information for optimization analysis remarks related to pointer aliasing.
Diagnostic information for optimization analysis remarks related to floating-point non-commutativity.
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.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
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
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Type * getRecurrenceType() const
Returns the type of the recurrence.
const SmallPtrSet< Instruction *, 8 > & getCastInsts() const
Returns a reference to the instructions used for type-promoting the recurrence.
static bool isFindLastRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
bool isSigned() const
Returns true if all source operands of the recurrence are SExtInsts.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
std::optional< ArrayRef< PointerDiffInfo > > getDiffChecks() const
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
This class uses information about analyze scalars to rewrite expressions in canonical form.
ScalarEvolution * getSE()
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
LLVM_ABI Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
LLVM_ABI void eraseDeadInstructions(Value *Root)
Remove inserted instructions that are dead, e.g.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
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 const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
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 SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
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.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:888
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool supportsEfficientVectorElementLoadStore() const
If target has efficient vector element load/store instructions, it can return true here so that inser...
LLVM_ABI bool prefersVectorizedAddressing() const
Return true if target doesn't mind addresses in vectors.
LLVM_ABI InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing operands with the given types.
LLVM_ABI InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask={}, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
LLVM_ABI InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
llvm::VectorInstrContext VectorInstrContext
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
LLVM_ABI InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing an instruction.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_Reverse
Reverse the order of the vector.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionalit...
Definition TypeSwitch.h:89
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition TypeSwitch.h:98
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
Holds state needed to make cost decisions before computing costs per-VF, including the maximum VFs.
const TTI::TargetCostKind CostKind
The kind of cost that we are calculating.
bool isEpilogueVectorizationProfitable(ElementCount VF, unsigned IC) const
Returns true if epilogue vectorization is considered profitable for a main loop with vectorization fa...
std::optional< unsigned > getVScaleForTuning() const
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4439
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4466
iterator end()
Definition VPlan.h:4476
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4474
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4527
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of this VPBasicBlock.
Definition VPlan.cpp:749
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:233
const VPRecipeBase & front() const
Definition VPlan.h:4486
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:619
bool empty() const
Definition VPlan.h:4485
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:203
void setName(const Twine &newName)
Definition VPlan.h:188
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:230
VPlan * getPlan()
Definition VPlan.h:199
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:188
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:235
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:421
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:384
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:414
static std::pair< VPBasicBlock *, VPBasicBlock * > getPlainCFGHeaderAndLatch(const VPlan &Plan)
Returns the header and latch of the outermost loop of Plan in plain CFG form (before regions are form...
static VPBuilderBase getToInsertAfter(VPRecipeBase *R)
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt, Type *ResultTy=nullptr)
Create a phi with IncomingValues, using the default flags for the result type, unless Flags is set.
T * insert(T *R)
Insert R at the current insertion point. Returns R unchanged.
VPInstruction * createAdd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt)
Create a select of TrueVal and FalseVal based on Cond, using the default flags for the result type,...
static VPSingleDefRecipe * createSingleScalarOp(unsigned Opcode, ArrayRef< VPValue * > Operands, VPValue *Mask, const VPIRFlags &Flags, const VPIRMetadata &Metadata, DebugLoc DL, Type *ResultTy, Instruction *UV)
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr)
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPInstruction * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:575
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:548
Recipe to expand a SCEV expression.
Definition VPlan.h:4052
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2458
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2505
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2508
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2494
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2180
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4592
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4616
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1300
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1573
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1412
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1405
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1363
unsigned getOpcode() const
Definition VPlan.h:1494
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1605
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1567
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3162
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:403
VPBasicBlock * getParent()
Definition VPlan.h:475
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:553
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
VPRecipeBase * tryToCreateWidenNonPhiRecipe(VPSingleDefRecipe *R, VFRange &Range)
Create and return a widened recipe for a non-phi recipe R if one can be created within the given VF R...
VPHistogramRecipe * widenIfHistogram(VPInstruction *VPI)
If VPI represents a histogram operation (as determined by LoopVectorizationLegality) make that safe f...
bool prefersVectorizedAddressing() const
Returns true if the target prefers vectorized addressing.
VPRecipeBase * tryToWidenMemory(VPInstruction *VPI, VFRange &Range)
Check if the load or store instruction VPI should widened for Range.Start and potentially masked.
bool replaceWithFinalIfReductionStore(VPInstruction *VPI, VPBuilder &FinalRedStoresBuilder)
If VPI is a store of a reduction into an invariant address, delete it.
VPSingleDefRecipe * handleReplication(VPInstruction *VPI, VFRange &Range)
Build a replicating or single-scalar recipe for VPI.
bool isPredicatedInst(Instruction *I) const
Returns true if I needs to be predicated (i.e.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:350
A recipe for handling reduction phis.
Definition VPlan.h:2873
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2944
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2947
VPReductionPHIRecipe * cloneWithOperands(VPValue *Start, VPValue *BackedgeValue)
Definition VPlan.h:2908
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2941
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3255
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4664
const VPBlockBase * getEntry() const
Definition VPlan.h:4708
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4831
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4784
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3422
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:611
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:681
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:397
operand_range operands()
Definition VPlanValue.h:470
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:443
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:438
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:147
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:141
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:128
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1464
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1470
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1895
A recipe for handling GEP instructions.
Definition VPlan.h:2228
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1828
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4851
bool hasVF(ElementCount VF) const
Definition VPlan.h:5087
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:5100
VPBasicBlock * getEntry()
Definition VPlan.h:4947
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5019
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5059
bool hasUF(unsigned UF) const
Definition VPlan.h:5112
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5013
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5137
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5163
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1042
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:5270
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1024
LLVM_ABI_FOR_TEST bool isOuterLoop() const
Returns true if this VPlan is for an outer loop, i.e., its vector loop region contains a nested loop ...
Definition VPlan.cpp:1066
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5033
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4989
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4952
bool requiresScalarEpilogue() const
Returns true if the plan requires a scalar epilogue after the vector loop.
Definition VPlan.h:4975
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5056
bool hasScalarVFOnly() const
Definition VPlan.h:5105
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5003
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:917
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:4968
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5009
LLVM_ABI_FOR_TEST VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition VPlan.cpp:1207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isNonZero() const
Definition TypeSize.h:155
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:216
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr bool isZero() const
Definition TypeSize.h:153
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:223
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
IteratorT end() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
CallInst * Call
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ Legal
The operation is expected to be selectable directly by the target, and no transformation is necessary...
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr, DebugLoc DL={})
Reports an informative message: print Msg for debugging purposes as well as an optimization remark.
void reportVectorization(OptimizationRemarkEmitter *ORE, Loop *TheLoop, ElementCount VFWidth, unsigned IC)
Report successful vectorization of the loop.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
bool matchFindIVResult(VPInstruction *VPI, Op0_t ReducedIV, Op1_t Start)
Match FindIV result pattern: select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),...
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
bool match(Val *V, const Pattern &P)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::ExtractLane, Op0_t, Op1_t > m_ExtractLane(const Op0_t &Op0, const Op1_t &Op1)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
InstructionCost getScalarizationOverhead(const TargetTransformInfo &TTI, bool ReVec, Type *ScalarTy, VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, const TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef< Value * > VL, TTI::VectorInstrContext VIC)
This is similar to TargetTransformInfo::getScalarizationOverhead, but if ScalarTy is a FixedVectorTyp...
BranchProbability getExecutionProbability(BlockFrequency Freq)
Returns Freq as a BranchProbability, relative to the full mass.
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
VPBasicBlock * getFirstLoopHeader(VPlan &Plan, VPDominatorTree &VPDT)
Returns the header block of the first, top-level loop, or null if none exist.
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
VPInstruction * findCanonicalIVIncrement(VPlan &Plan)
Find the canonical IV increment of Plan's vector loop region.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
VPValue * findIncomingAliasMask(const VPlan &Plan)
Finds the incoming alias-mask within the vector preheader.
bool doesGeneratePerAllLanes(const VPRecipeBase *R)
Returns true if R produces scalar values for all VF lanes.
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:146
LLVM_ABI_FOR_TEST const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
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:316
SmallVector< VPBasicBlock * > vp_rpo_plain_cfg_loop_body(VPBasicBlock *Header)
Returns the VPBasicBlocks forming the loop body of a plain (pre-region) VPlan in reverse post-order s...
Definition VPlanCFG.h:262
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
LLVM_ABI Value * addRuntimeChecks(Instruction *Loc, Loop *TheLoop, const SmallVectorImpl< RuntimePointerCheck > &PointerChecks, SCEVExpander &Expander, bool HoistRuntimeChecks=false)
Add code that checks at runtime if the accessed arrays in PointerChecks overlap.
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI_FOR_TEST cl::opt< bool > VerifyEachVPlan
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
VPBuilderBase<> VPBuilder
Definition VPlan.h:67
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
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
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
cl::opt< bool > VPlanBuildOuterloopStressTest
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
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.
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:649
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:250
LLVM_ABI bool VerifySCEV
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintAfterAll
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:285
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:1762
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition CFG.h:154
std::optional< uint64_t > getMaxRuntimeElementCount(ElementCount EC, const Function &F)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
cl::opt< unsigned > ForceTargetInstructionCost("force-target-instruction-cost", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's expected cost for " "an instruction to a single constant value. Mostly " "useful for getting consistent testing."))
Definition VPlan.cpp:58
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:83
@ ReadOnly
No side effects to worry about, so we can process any uncountable exits in the loop and branch either...
Definition VPlan.h:87
@ MaskedHandleExitInScalarLoop
All memory operations other than the load(s) required to determine whether an uncountable exit occurr...
Definition VPlan.h:92
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI cl::opt< bool > EnableLoopVectorization
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
LLVM_ABI_FOR_TEST cl::list< std::string > VPlanPrintAfterPasses
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:413
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...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1853
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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 raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
TargetTransformInfo TTI
@ CM_EpilogueNotAllowedLowTripLoop
@ CM_EpilogueNotNeededFoldTail
@ CM_EpilogueNotAllowedFoldTail
@ CM_EpilogueNotAllowedOptSize
@ CM_EpilogueAllowed
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
LLVM_ABI_FOR_TEST cl::list< std::string > VPlanPrintBeforePasses
RecurKind
These are the kinds of recurrences that we support.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
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 BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
cl::opt< unsigned > NumberOfStoresToPredicate("vectorize-num-stores-pred", cl::init(1), cl::Hidden, cl::desc("Max number of stores to be predicated behind an if."))
The number of stores in a loop that are allowed to need predication.
Definition VPlan.cpp:59
constexpr T AbsoluteDifference(U X, V Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition MathExtras.h:595
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintBeforeAll
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
@ None
Don't use tail folding.
@ DataWithEVL
Use predicated EVL instructions for tail-folding.
@ DataAndControlFlow
Use predicate to control both data and control flow.
@ DataWithoutLaneMask
Same as Data, but avoids using the get.active.lane.mask intrinsic to calculate the mask and instead i...
@ Data
Use predicate only to mask operations on data in the loop.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
Definition DWP.h:30
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:78
LLVM_ABI Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, ElementCount VF, unsigned IC)
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI_FOR_TEST bool verifyVPlanIsValid(const VPlan &Plan)
Verify invariants for general VPlans.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintVectorRegionScope
LLVM_ABI cl::opt< bool > EnableLoopInterleaving
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
ResumeForEpilogue markers in the main plan, used by the epilogue plan.
VPInstruction * CanIVResume
SmallVector< VPInstruction * > ResumeValues
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
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).
A class that represents two vectorization factors (initialized with 0 by default).
static FixedScalableVFPair getNone()
This holds details about a histogram operation – a load -> update -> store sequence where each lane i...
TargetLibraryInfo * TLI
LLVM_ABI LoopVectorizeResult runImpl(Function &F)
LLVM_ABI bool processLoop(Loop *L)
ProfileSummaryInfo * PSI
LoopAccessInfoManager * LAIs
std::function< const BranchProbabilityInfo &()> GetBPI
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI LoopVectorizePass(LoopVectorizeOptions Opts={})
ScalarEvolution * SE
AssumptionCache * AC
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
OptimizationRemarkEmitter * ORE
std::function< BlockFrequencyInfo &()> GetBFI
TargetTransformInfo * TTI
Storage for information about made changes.
A marker analysis to determine if extra passes should be run after loop vectorization.
static LLVM_ABI AnalysisKey Key
Parameters that control the generic loop unrolling transformation.
bool UnrollVectorizedLoop
Disable runtime unrolling by default for vectorized loops.
Holds the VFShape for a specific scalar to vector function mapping.
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
ElementCount End
Struct to hold various analysis needed for cost computations.
LLVMContext & LLVMCtx
const VFSelectionContext & Config
LoopVectorizationCostModel & CM
VPCostContext(const TargetLibraryInfo &TLI, const VPlan &Plan, LoopVectorizationCostModel &CM, VFSelectionContext &Config, bool ReusePrintingSlotTracker=false)
bool skipCostComputation(Instruction *UI, bool IsVector) const
Return true if the cost for UI shouldn't be computed, e.g.
InstructionCost getLegacyCost(Instruction *UI, ElementCount VF) const
Return the cost for UI with VF using the legacy cost model as fallback until computing the cost of al...
bool isMaskRequired(Instruction *I) const
Forwards to LoopVectorizationCostModel::isMaskRequired.
void invalidateWideningDecision(Instruction *I, ElementCount VF)
Mark the widening decision for I at VF as invalidated since a VPlan transform replaced the original r...
PredicatedScalarEvolution & PSE
bool willBeScalarized(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalarized at VF.
static bool executesAtMostOnce(const VPlan &Plan, ElementCount VF)
Returns true if the vector loop body of Plan is known to execute at most once at VF,...
TargetTransformInfo::TargetCostKind CostKind
const TargetLibraryInfo & TLI
const TargetTransformInfo & TTI
SmallPtrSet< Instruction *, 8 > SkipCostComputation
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1113
A struct that represents some properties of the register usage of a loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3839
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3944
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-ins and replace them with constants, if they can be simplified via SCEV.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, VPValue *MainVectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static void expandSCEVsToVPInstructions(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block to VPInstructions.
static void materializeBroadcasts(VPlan &Plan)
Add explicit broadcasts for live-ins and VPValues defined in Plan's entry block if they are used as v...
static void materializePacksAndUnpacks(VPlan &Plan)
Add explicit Build[Struct]Vector recipes to Pack multiple scalar values into vectors and Unpack recip...
static void createInterleaveGroups(VPlan &Plan, const SmallPtrSetImpl< const InterleaveGroup< Instruction > * > &InterleaveGroups, const bool &EpilogueAllowed)
static LLVM_ABI_FOR_TEST bool handleUncountableEarlyExits(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC, UncountableExitStyle Style)
Update Plan to account for uncountable early exits by introducing appropriate branching logic in the ...
static bool simplifyKnownEVL(VPlan &Plan, ElementCount VF, PredicatedScalarEvolution &PSE)
Try to simplify VPInstruction::ExplicitVectorLength recipes when the AVL is known to be <= VF,...
static void introduceMasksAndLinearize(VPlan &Plan)
Predicate and linearize the control-flow in the only loop region of Plan.
static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize UF, VF and VFxUF to be computed explicitly using VPInstructions.
static void foldTailByMasking(VPlan &Plan)
Adapts the vector loop region for tail folding by introducing a header mask and conditionally executi...
static void materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, const TargetLibraryInfo &TLI, PredicatedScalarEvolution &PSE, Loop *OuterLoop)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static bool handleMultiUseReductions(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Try to legalize reductions with multiple in-loop uses.
static void convertToVariableLengthStep(VPlan &Plan)
Transform loops with variable-length stepping after region dissolution.
static void materializeHeaderMask(VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow)
Materialize the abstract header mask of the loop region into concrete recipes: an active-lane-mask if...
static void recordExecutionFrequencies(VPlan &Plan)
Add execution frequencies to each recipe in the loop body of Plan.
static void addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF, std::optional< unsigned > VScaleForTuning)
Add branch weight metadata, if the Plan's middle block is terminated by a BranchOnCond recipe.
static std::unique_ptr< VPlan > narrowInterleaveGroups(VPlan &Plan, const TargetTransformInfo &TTI)
Try to find a single VF among Plan's VFs for which all interleave groups (with known minimum VF eleme...
static bool handleFindLastReductions(VPlan &Plan)
Check if Plan contains any FindLast reductions.
static void createInLoopReductionRecipes(VPlan &Plan, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static void materializeAliasMaskCheckBlock(VPlan &Plan, ArrayRef< PointerDiffInfo > DiffChecks, bool HasBranchWeights)
Materializes the alias mask within a check block before the loop.
static void modelGeneratedMainLoopBlocks(VPlan &EpiPlan, VPlan &MainPlan, VPIRBasicBlock *EnteredFrom)
Model the blocks the executed MainPlan generated for the main vector loop in EpiPlan during epilogue ...
static void unrollByUF(VPlan &Plan, unsigned UF)
Explicitly unroll Plan by UF.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand remaining VPExpandSCEVRecipes in Plan's entry block using SCEVExpander.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan, DebugLoc DL)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert load/store VPInstructions in Plan into widened or replicate recipes.
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...
static void narrowInductionTruncates(VPlan &Plan, VFRange &Range, const TargetTransformInfo &TTI, PredicatedScalarEvolution &PSE)
Replace truncates of a wide induction, or of that induction's increment, by a VPWidenIntOrFpInduction...
static LLVM_ABI_FOR_TEST bool createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, const VPDominatorTree &VPDT, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const SmallPtrSetImpl< const PHINode * > &FixedOrderRecurrences, const SmallPtrSetImpl< PHINode * > &InLoopReductions, bool AllowReordering)
Replace VPPhi recipes in Plan's header with corresponding VPHeaderPHIRecipe subclasses for inductions...
static void expandBranchOnTwoConds(VPlan &Plan)
Expand BranchOnTwoConds instructions into explicit CFG with BranchOnCond instructions.
static void materializeVectorTripCount(VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking, bool RequiresScalarEpilogue, VPValue *Step, std::optional< uint64_t > MaxRuntimeStep=std::nullopt)
Materialize vector trip count computations to a set of VPInstructions.
static void hoistPredicatedLoads(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
Hoist predicated loads from the same address to the loop entry block, if they are guaranteed to execu...
static void attachAliasMaskToHeaderMask(VPlan &Plan)
Attaches the alias-mask to the existing header-mask.
static void optimizeFindIVReductions(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L)
Optimize FindLast reductions selecting IVs (or expressions of IVs) by converting them to FindIV reduc...
static void convertToAbstractRecipes(VPlan &Plan, VPCostContext &Ctx, VFRange &Range)
This function converts initial recipes to the abstract recipes and clamps Range based on cost model f...
static void materializeConstantVectorTripCount(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
static void makeScalarizationDecisions(VPlan &Plan, VFRange &Range)
Make VPlan-based scalarization decision prior to delegating to the ones made by the legacy CM.
static void replaceWideCanonicalIVWithWideIV(VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, ElementCount VF, unsigned UF)
Replace a VPWidenCanonicalIVRecipe if it is present in Plan, with a VPWidenIntOrFpInductionRecipe,...
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr, function_ref< const BranchProbabilityInfo &()> GetBPI=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static void optimizeInductionLiveOutUsers(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
static void addExplicitVectorLength(VPlan &Plan, const std::optional< unsigned > &MaxEVLSafeElements)
Add a VPCurrentIterationPHIRecipe and related recipes to Plan and replaces all uses of the canonical ...
static void makeCallWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert call VPInstructions in Plan into widened call, vector intrinsic or replicate recipes based on...
static void adjustFirstOrderRecurrenceMiddleUsers(VPlan &Plan, VFRange &Range)
Adjust first-order recurrence users in the middle block: create penultimate element extracts for LCSS...
static void optimizeEVLMasks(VPlan &Plan)
Optimize recipes which use an EVL-based header mask to VP intrinsics, for example:
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
static LLVM_ABI_FOR_TEST void handleCountableEarlyExits(VPlan &Plan)
Disconnect countable early exits from the loop.
static void sinkPredicatedStores(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
Sink predicated stores to the same address with complementary predicates (P and NOT P) to an uncondit...
static bool finalizeSCEVPredicates(VPlan &Plan, PredicatedScalarEvolution &PSE, bool OptForSize, unsigned SCEVCheckThreshold, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Finalize SCEV predicates by adding induction predicates from Plan to PSE and checking constraints.
static void replicateByVF(VPlan &Plan, ElementCount VF)
Replace replicating VPReplicateRecipe, VPScalarIVStepsRecipe and VPInstruction in Plan with VF single...
static bool removeBranchOnConst(VPlan &Plan, bool OnlyLatches=false)
Remove BranchOnCond recipes with true or false conditions together with removing dead edges to their ...
static void convertToStridedAccesses(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L, VPCostContext &Ctx, VFRange &Range)
Transform widen memory recipes into strided access recipes when legal and profitable.
static void addIterationCountCheckBlock(VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
Add a new check block before the vector preheader to Plan to check if the main vector loop should be ...
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx, VFRange &Range)
Detect and create partial reduction recipes for scaled or unordered reductions in Plan.
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE, VPBasicBlock *CheckBlock)
static void cse(VPlan &Plan)
Perform common-subexpression-elimination on Plan.
static void replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE, const SymbolicStrideMap &StridesMap, const VPDominatorTree &VPDT)
Replace symbolic strides from StridesMap in Plan with constants when possible.
static LLVM_ABI_FOR_TEST void optimize(VPlan &Plan)
Apply VPlan-to-VPlan optimizations to Plan, including induction recipe optimizations,...
static void dissolveLoopRegions(VPlan &Plan)
Replace loop regions with explicit CFG.
static void truncateToMinimalBitwidths(VPlan &Plan, const MapVector< Instruction *, uint64_t > &MinBWs)
Insert truncates and extends for any truncated recipe.
static void dropPoisonGeneratingRecipes(VPlan &Plan)
Drop poison flags from recipes that may generate a poison value that is used after vectorization,...
static void optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Optimize Plan based on BestVF and BestUF.
static void widenMemoryAccessesByUF(VPlan &Plan, ElementCount VF, unsigned UF, const TargetTransformInfo &TTI)
Widens memory operations by a factor of UF based on a target hook.
static void convertEVLExitCond(VPlan &Plan)
Replaces the exit condition from (branch-on-cond eq CanonicalIVInc, VectorTripCount) to (branch-on-co...
static bool splitCombinedExits(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop *TheLoop)
If a single exit has multiple conditions combined together, split them and create new exiting blocks.
static void attachMemoryChecks(VPlan &Plan, ArrayRef< RuntimePointerCheck > Checks, ScalarEvolution &SE, DebugLoc DL, bool AddBranchWeights)
Generate Checks as recipes and attach the check block to Plan.
static void combineRecipes(VPlan &Plan)
Perform instcombine-like simplifications on recipes in Plan.
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class.
InstructionCost Cost
Cost of the loop with that width.
ElementCount MinProfitableTripCount
The minimum trip count required to make vectorization profitable, e.g.
ElementCount Width
Vector width with best cost.
InstructionCost ScalarCost
Cost of the scalar loop.
static VectorizationFactor Disabled()
Width 1 means no vectorization, cost 0 means uncomputed cost.
static LLVM_ABI unsigned VectorizeMemoryCheckThreshold
The maximum allowed number of runtime memory checks.
static LLVM_ABI bool HoistRuntimeChecks