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