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