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