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