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