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