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