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;
161
162#define LV_NAME "loop-vectorize"
163#define DEBUG_TYPE LV_NAME
164
165#ifndef NDEBUG
166const char VerboseDebug[] = DEBUG_TYPE "-verbose";
167#endif
168
169STATISTIC(LoopsVectorized, "Number of loops vectorized");
170STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
171STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
172STATISTIC(LoopsEarlyExitVectorized, "Number of early exit loops vectorized");
173
175 "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
176 cl::desc("Enable vectorization of epilogue loops."));
177
179 "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
180 cl::desc("When epilogue vectorization is enabled, and a value greater than "
181 "1 is specified, forces the given VF for all applicable epilogue "
182 "loops."));
183
185 "epilogue-vectorization-minimum-VF", cl::Hidden,
186 cl::desc("Only loops with vectorization factor equal to or larger than "
187 "the specified value are considered for epilogue vectorization."));
188
189/// Loops with a known constant trip count below this number are vectorized only
190/// if no scalar iteration overheads are incurred.
192 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
193 cl::desc("Loops with a constant trip count that is smaller than this "
194 "value are vectorized only if no scalar iteration overheads "
195 "are incurred."));
196
198 "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
199 cl::desc("The maximum allowed number of runtime memory checks"));
200
201/// Note: This currently only applies to `llvm.masked.load` and
202/// `llvm.masked.store`. TODO: Extend this to cover other operations as needed.
204 "force-target-supports-masked-memory-ops", cl::init(false), cl::Hidden,
205 cl::desc("Assume the target supports masked memory operations (used for "
206 "testing)."));
207
208// Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
209// that predication is preferred, and this lists all options. I.e., the
210// vectorizer will try to fold the tail-loop (epilogue) into the vector body
211// and predicate the instructions accordingly. If tail-folding fails, there are
212// different fallback strategies depending on these values:
219} // namespace PreferPredicateTy
220
222 "prefer-predicate-over-epilogue",
225 cl::desc("Tail-folding and predication preferences over creating a scalar "
226 "epilogue loop."),
228 "scalar-epilogue",
229 "Don't tail-predicate loops, create scalar epilogue"),
231 "predicate-else-scalar-epilogue",
232 "prefer tail-folding, create scalar epilogue if tail "
233 "folding fails."),
235 "predicate-dont-vectorize",
236 "prefers tail-folding, don't attempt vectorization if "
237 "tail-folding fails.")));
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 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
264 cl::desc("Maximize bandwidth when selecting vectorization factor which "
265 "will be determined by the smallest type in loop."));
266
268 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
269 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
270
271/// An interleave-group may need masking if it resides in a block that needs
272/// predication, or in order to mask away gaps.
274 "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
275 cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
276
278 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
279 cl::desc("A flag that overrides the target's number of scalar registers."));
280
282 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
283 cl::desc("A flag that overrides the target's number of vector registers."));
284
286 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
287 cl::desc("A flag that overrides the target's max interleave factor for "
288 "scalar loops."));
289
291 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
292 cl::desc("A flag that overrides the target's max interleave factor for "
293 "vectorized loops."));
294
296 "force-target-instruction-cost", cl::init(0), cl::Hidden,
297 cl::desc("A flag that overrides the target's expected cost for "
298 "an instruction to a single constant value. Mostly "
299 "useful for getting consistent testing."));
300
302 "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
303 cl::desc(
304 "Pretend that scalable vectors are supported, even if the target does "
305 "not support them. This flag should only be used for testing."));
306
308 "small-loop-cost", cl::init(20), cl::Hidden,
309 cl::desc(
310 "The cost of a loop that is considered 'small' by the interleaver."));
311
313 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
314 cl::desc("Enable the use of the block frequency analysis to access PGO "
315 "heuristics minimizing code growth in cold regions and being more "
316 "aggressive in hot regions."));
317
318// Runtime interleave loops for load/store throughput.
320 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
321 cl::desc(
322 "Enable runtime interleaving until load/store ports are saturated"));
323
324/// The number of stores in a loop that are allowed to need predication.
326 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
327 cl::desc("Max number of stores to be predicated behind an if."));
328
330 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
331 cl::desc("Count the induction variable only once when interleaving"));
332
334 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
335 cl::desc("Enable if predication of stores during vectorization."));
336
338 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
339 cl::desc("The maximum interleave count to use when interleaving a scalar "
340 "reduction in a nested loop."));
341
342static cl::opt<bool>
343 PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
345 cl::desc("Prefer in-loop vector reductions, "
346 "overriding the targets preference."));
347
349 "force-ordered-reductions", cl::init(false), cl::Hidden,
350 cl::desc("Enable the vectorisation of loops with in-order (strict) "
351 "FP reductions"));
352
354 "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
355 cl::desc(
356 "Prefer predicating a reduction operation over an after loop select."));
357
359 "enable-vplan-native-path", cl::Hidden,
360 cl::desc("Enable VPlan-native vectorization path with "
361 "support for outer loop vectorization."));
362
364 llvm::VerifyEachVPlan("vplan-verify-each",
365#ifdef EXPENSIVE_CHECKS
366 cl::init(true),
367#else
368 cl::init(false),
369#endif
371 cl::desc("Verify VPlans after VPlan transforms."));
372
373#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
375 "vplan-print-after-all", cl::init(false), cl::Hidden,
376 cl::desc("Print VPlans after all VPlan transformations."));
377
379 "vplan-print-after", cl::Hidden,
380 cl::desc("Print VPlans after specified VPlan transformations (regexp)."));
381
383 "vplan-print-vector-region-scope", cl::init(false), cl::Hidden,
384 cl::desc("Limit VPlan printing to vector loop region in "
385 "`-vplan-print-after*` if the plan has one."));
386#endif
387
388// This flag enables the stress testing of the VPlan H-CFG construction in the
389// VPlan-native vectorization path. It must be used in conjuction with
390// -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
391// verification of the H-CFGs built.
393 "vplan-build-stress-test", cl::init(false), cl::Hidden,
394 cl::desc(
395 "Build VPlan for every supported loop nest in the function and bail "
396 "out right after the build (stress test the VPlan H-CFG construction "
397 "in the VPlan-native vectorization path)."));
398
400 "interleave-loops", cl::init(true), cl::Hidden,
401 cl::desc("Enable loop interleaving in Loop vectorization passes"));
403 "vectorize-loops", cl::init(true), cl::Hidden,
404 cl::desc("Run the Loop vectorization passes"));
405
407 "force-widen-divrem-via-safe-divisor", cl::Hidden,
408 cl::desc(
409 "Override cost based safe divisor widening for div/rem instructions"));
410
412 "vectorizer-maximize-bandwidth-for-vector-calls", cl::init(true),
414 cl::desc("Try wider VFs if they enable the use of vector variants"));
415
417 "enable-early-exit-vectorization", cl::init(true), cl::Hidden,
418 cl::desc(
419 "Enable vectorization of early exit loops with uncountable exits."));
420
422 "vectorizer-consider-reg-pressure", cl::init(false), cl::Hidden,
423 cl::desc("Discard VFs if their register pressure is too high."));
424
425// Likelyhood of bypassing the vectorized loop because there are zero trips left
426// after prolog. See `emitIterationCountCheck`.
427static constexpr uint32_t MinItersBypassWeights[] = {1, 127};
428
429/// A helper function that returns true if the given type is irregular. The
430/// type is irregular if its allocated size doesn't equal the store size of an
431/// element of the corresponding vector type.
432static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
433 // Determine if an array of N elements of type Ty is "bitcast compatible"
434 // with a <N x Ty> vector.
435 // This is only true if there is no padding between the array elements.
436 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
437}
438
439/// A version of ScalarEvolution::getSmallConstantTripCount that returns an
440/// ElementCount to include loops whose trip count is a function of vscale.
442 const Loop *L) {
443 if (unsigned ExpectedTC = SE->getSmallConstantTripCount(L))
444 return ElementCount::getFixed(ExpectedTC);
445
446 const SCEV *BTC = SE->getBackedgeTakenCount(L);
448 return ElementCount::getFixed(0);
449
450 const SCEV *ExitCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
451 if (isa<SCEVVScale>(ExitCount))
453
454 const APInt *Scale;
455 if (match(ExitCount, m_scev_Mul(m_scev_APInt(Scale), m_SCEVVScale())))
456 if (cast<SCEVMulExpr>(ExitCount)->hasNoUnsignedWrap())
457 if (Scale->getActiveBits() <= 32)
459
460 return ElementCount::getFixed(0);
461}
462
463/// Get the maximum trip count for \p L from the SCEV unsigned range, excluding
464/// zero from the range. Only valid when not folding the tail, as the minimum
465/// iteration count check guards against a zero trip count. Returns 0 if
466/// unknown.
468 Loop *L) {
469 const SCEV *BTC = PSE.getBackedgeTakenCount();
471 return 0;
472 ScalarEvolution *SE = PSE.getSE();
473 const SCEV *TripCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
474 ConstantRange TCRange = SE->getUnsignedRange(TripCount);
475 APInt MaxTCFromRange = TCRange.getUnsignedMax();
476 if (!MaxTCFromRange.isZero() && MaxTCFromRange.getActiveBits() <= 32)
477 return MaxTCFromRange.getZExtValue();
478 return 0;
479}
480
481/// Returns "best known" trip count, which is either a valid positive trip count
482/// or std::nullopt when an estimate cannot be made (including when the trip
483/// count would overflow), for the specified loop \p L as defined by the
484/// following procedure:
485/// 1) Returns exact trip count if it is known.
486/// 2) Returns expected trip count according to profile data if any.
487/// 3) Returns upper bound estimate if known, and if \p CanUseConstantMax.
488/// 4) Returns the maximum trip count from the SCEV range excluding zero,
489/// if \p CanUseConstantMax and \p CanExcludeZeroTrips.
490/// 5) Returns std::nullopt if all of the above failed.
491static std::optional<ElementCount>
493 bool CanUseConstantMax = true,
494 bool CanExcludeZeroTrips = false) {
495 // Check if exact trip count is known.
496 if (auto ExpectedTC = getSmallConstantTripCount(PSE.getSE(), L))
497 return ExpectedTC;
498
499 // Check if there is an expected trip count available from profile data.
501 if (auto EstimatedTC = getLoopEstimatedTripCount(L))
502 return ElementCount::getFixed(*EstimatedTC);
503
504 if (!CanUseConstantMax)
505 return std::nullopt;
506
507 // Check if upper bound estimate is known.
508 if (unsigned ExpectedTC = PSE.getSmallConstantMaxTripCount())
509 return ElementCount::getFixed(ExpectedTC);
510
511 // Get the maximum trip count from the SCEV range excluding zero. This is
512 // only safe when not folding the tail, as the minimum iteration count check
513 // prevents entering the vector loop with a zero trip count.
514 if (CanUseConstantMax && CanExcludeZeroTrips)
515 if (unsigned RefinedTC = getMaxTCFromNonZeroRange(PSE, L))
516 return ElementCount::getFixed(RefinedTC);
517
518 return std::nullopt;
519}
520
521namespace {
522// Forward declare GeneratedRTChecks.
523class GeneratedRTChecks;
524
525using SCEV2ValueTy = DenseMap<const SCEV *, Value *>;
526} // namespace
527
528namespace llvm {
529
531
532/// InnerLoopVectorizer vectorizes loops which contain only one basic
533/// block to a specified vectorization factor (VF).
534/// This class performs the widening of scalars into vectors, or multiple
535/// scalars. This class also implements the following features:
536/// * It inserts an epilogue loop for handling loops that don't have iteration
537/// counts that are known to be a multiple of the vectorization factor.
538/// * It handles the code generation for reduction variables.
539/// * Scalarization (implementation using scalars) of un-vectorizable
540/// instructions.
541/// InnerLoopVectorizer does not perform any vectorization-legality
542/// checks, and relies on the caller to check for the different legality
543/// aspects. The InnerLoopVectorizer relies on the
544/// LoopVectorizationLegality class to provide information about the induction
545/// and reduction variables that were found to a given vectorization factor.
547public:
551 ElementCount VecWidth, unsigned UnrollFactor,
553 GeneratedRTChecks &RTChecks, VPlan &Plan)
554 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TTI(TTI), AC(AC),
555 VF(VecWidth), UF(UnrollFactor), Builder(PSE.getSE()->getContext()),
558 Plan.getVectorLoopRegion()->getSinglePredecessor())) {}
559
560 virtual ~InnerLoopVectorizer() = default;
561
562 /// Creates a basic block for the scalar preheader. Both
563 /// EpilogueVectorizerMainLoop and EpilogueVectorizerEpilogueLoop overwrite
564 /// the method to create additional blocks and checks needed for epilogue
565 /// vectorization.
567
568 /// Fix the vectorized code, taking care of header phi's, and more.
570
571 /// Fix the non-induction PHIs in \p Plan.
573
574protected:
576
577 /// Create and return a new IR basic block for the scalar preheader whose name
578 /// is prefixed with \p Prefix.
580
581 /// Allow subclasses to override and print debug traces before/after vplan
582 /// execution, when trace information is requested.
583 virtual void printDebugTracesAtStart() {}
584 virtual void printDebugTracesAtEnd() {}
585
586 /// The original loop.
588
589 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
590 /// dynamic knowledge to simplify SCEV expressions and converts them to a
591 /// more usable form.
593
594 /// Loop Info.
596
597 /// Dominator Tree.
599
600 /// Target Transform Info.
602
603 /// Assumption Cache.
605
606 /// The vectorization SIMD factor to use. Each vector will have this many
607 /// vector elements.
609
610 /// The vectorization unroll factor to use. Each scalar is vectorized to this
611 /// many different vector instructions.
612 unsigned UF;
613
614 /// The builder that we use
616
617 // --- Vectorization state ---
618
619 /// The profitablity analysis.
621
622 /// Structure to hold information about generated runtime checks, responsible
623 /// for cleaning the checks, if vectorization turns out unprofitable.
624 GeneratedRTChecks &RTChecks;
625
627
628 /// The vector preheader block of \p Plan, used as target for check blocks
629 /// introduced during skeleton creation.
631};
632
633/// Encapsulate information regarding vectorization of a loop and its epilogue.
634/// This information is meant to be updated and used across two stages of
635/// epilogue vectorization.
638 unsigned MainLoopUF = 0;
640 unsigned EpilogueUF = 0;
645
647 ElementCount EVF, unsigned EUF,
649 : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF),
651 assert(EUF == 1 &&
652 "A high UF for the epilogue loop is likely not beneficial.");
653 }
654};
655
656/// An extension of the inner loop vectorizer that creates a skeleton for a
657/// vectorized loop that has its epilogue (residual) also vectorized.
658/// The idea is to run the vplan on a given loop twice, firstly to setup the
659/// skeleton and vectorize the main loop, and secondly to complete the skeleton
660/// from the first step and vectorize the epilogue. This is achieved by
661/// deriving two concrete strategy classes from this base class and invoking
662/// them in succession from the loop vectorizer planner.
664public:
674
675 /// Holds and updates state information required to vectorize the main loop
676 /// and its epilogue in two separate passes. This setup helps us avoid
677 /// regenerating and recomputing runtime safety checks. It also helps us to
678 /// shorten the iteration-count-check path length for the cases where the
679 /// iteration count of the loop is so small that the main vector loop is
680 /// completely skipped.
682
683protected:
685};
686
687/// A specialized derived class of inner loop vectorizer that performs
688/// vectorization of *main* loops in the process of vectorizing loops and their
689/// epilogues.
691public:
702
703protected:
704 void printDebugTracesAtStart() override;
705 void printDebugTracesAtEnd() override;
706};
707
708// A specialized derived class of inner loop vectorizer that performs
709// vectorization of *epilogue* loops in the process of vectorizing loops and
710// their epilogues.
712public:
719 GeneratedRTChecks &Checks, VPlan &Plan)
721 Checks, Plan, EPI.EpilogueVF,
722 EPI.EpilogueVF, EPI.EpilogueUF) {}
723 /// Implements the interface for creating a vectorized skeleton using the
724 /// *epilogue loop* strategy (i.e., the second pass of VPlan execution).
726
727protected:
728 void printDebugTracesAtStart() override;
729 void printDebugTracesAtEnd() override;
730};
731} // end namespace llvm
732
733/// Look for a meaningful debug location on the instruction or its operands.
735 if (!I)
736 return DebugLoc::getUnknown();
737
739 if (I->getDebugLoc() != Empty)
740 return I->getDebugLoc();
741
742 for (Use &Op : I->operands()) {
743 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
744 if (OpInst->getDebugLoc() != Empty)
745 return OpInst->getDebugLoc();
746 }
747
748 return I->getDebugLoc();
749}
750
751/// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
752/// is passed, the message relates to that particular instruction.
753#ifndef NDEBUG
754static void debugVectorizationMessage(const StringRef Prefix,
755 const StringRef DebugMsg,
756 Instruction *I) {
757 dbgs() << "LV: " << Prefix << DebugMsg;
758 if (I != nullptr)
759 dbgs() << " " << *I;
760 else
761 dbgs() << '.';
762 dbgs() << '\n';
763}
764#endif
765
766/// Create an analysis remark that explains why vectorization failed
767///
768/// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
769/// RemarkName is the identifier for the remark. If \p I is passed it is an
770/// instruction that prevents vectorization. Otherwise \p TheLoop is used for
771/// the location of the remark. If \p DL is passed, use it as debug location for
772/// the remark. \return the remark object that can be streamed to.
773static OptimizationRemarkAnalysis
774createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
775 Instruction *I, DebugLoc DL = {}) {
776 BasicBlock *CodeRegion = I ? I->getParent() : TheLoop->getHeader();
777 // If debug location is attached to the instruction, use it. Otherwise if DL
778 // was not provided, use the loop's.
779 if (I && I->getDebugLoc())
780 DL = I->getDebugLoc();
781 else if (!DL)
782 DL = TheLoop->getStartLoc();
783
784 return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
785}
786
787namespace llvm {
788
789/// Return the runtime value for VF.
791 return B.CreateElementCount(Ty, VF);
792}
793
795 const StringRef OREMsg, const StringRef ORETag,
796 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
797 Instruction *I) {
798 LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
799 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
800 ORE->emit(
801 createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
802 << "loop not vectorized: " << OREMsg);
803}
804
805/// Reports an informative message: print \p Msg for debugging purposes as well
806/// as an optimization remark. Uses either \p I as location of the remark, or
807/// otherwise \p TheLoop. If \p DL is passed, use it as debug location for the
808/// remark. If \p DL is passed, use it as debug location for the remark.
809static void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
811 Loop *TheLoop, Instruction *I = nullptr,
812 DebugLoc DL = {}) {
814 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
815 ORE->emit(createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop,
816 I, DL)
817 << Msg);
818}
819
820/// Report successful vectorization of the loop. In case an outer loop is
821/// vectorized, prepend "outer" to the vectorization remark.
823 VectorizationFactor VF, unsigned IC) {
825 "Vectorizing: ", TheLoop->isInnermost() ? "innermost loop" : "outer loop",
826 nullptr));
827 StringRef LoopType = TheLoop->isInnermost() ? "" : "outer ";
828 ORE->emit([&]() {
829 return OptimizationRemark(LV_NAME, "Vectorized", TheLoop->getStartLoc(),
830 TheLoop->getHeader())
831 << "vectorized " << LoopType << "loop (vectorization width: "
832 << ore::NV("VectorizationFactor", VF.Width)
833 << ", interleaved count: " << ore::NV("InterleaveCount", IC) << ")";
834 });
835}
836
837} // end namespace llvm
838
839namespace llvm {
840
841// Loop vectorization cost-model hints how the scalar epilogue loop should be
842// lowered.
844
845 // The default: allowing scalar epilogues.
847
848 // Vectorization with OptForSize: don't allow epilogues.
850
851 // A special case of vectorisation with OptForSize: loops with a very small
852 // trip count are considered for vectorization under OptForSize, thereby
853 // making sure the cost of their loop body is dominant, free of runtime
854 // guards and scalar iteration overheads.
856
857 // Loop hint predicate indicating an epilogue is undesired.
859
860 // Directive indicating we must either tail fold or not vectorize
862};
863
864/// LoopVectorizationCostModel - estimates the expected speedups due to
865/// vectorization.
866/// In many cases vectorization is not profitable. This can happen because of
867/// a number of reasons. In this class we mainly attempt to predict the
868/// expected speedup/slowdowns due to the supported instruction set. We use the
869/// TargetTransformInfo to query the different backends for the cost of
870/// different operations.
873
874public:
882 std::function<BlockFrequencyInfo &()> GetBFI,
883 const Function *F, const LoopVectorizeHints *Hints,
885 : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
886 TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), GetBFI(GetBFI),
889 if (TTI.supportsScalableVectors() || ForceTargetSupportsScalableVectors)
890 initializeVScaleForTuning();
892 }
893
894 /// \return An upper bound for the vectorization factors (both fixed and
895 /// scalable). If the factors are 0, vectorization and interleaving should be
896 /// avoided up front.
897 FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
898
899 /// \return True if runtime checks are required for vectorization, and false
900 /// otherwise.
901 bool runtimeChecksRequired();
902
903 /// Setup cost-based decisions for user vectorization factor.
904 /// \return true if the UserVF is a feasible VF to be chosen.
907 return expectedCost(UserVF).isValid();
908 }
909
910 /// \return True if maximizing vector bandwidth is enabled by the target or
911 /// user options, for the given register kind.
912 bool useMaxBandwidth(TargetTransformInfo::RegisterKind RegKind);
913
914 /// \return True if register pressure should be considered for the given VF.
915 bool shouldConsiderRegPressureForVF(ElementCount VF);
916
917 /// \return The size (in bits) of the smallest and widest types in the code
918 /// that needs to be vectorized. We ignore values that remain scalar such as
919 /// 64 bit loop indices.
920 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
921
922 /// Memory access instruction may be vectorized in more than one way.
923 /// Form of instruction after vectorization depends on cost.
924 /// This function takes cost-based decisions for Load/Store instructions
925 /// and collects them in a map. This decisions map is used for building
926 /// the lists of loop-uniform and loop-scalar instructions.
927 /// The calculated cost is saved with widening decision in order to
928 /// avoid redundant calculations.
929 void setCostBasedWideningDecision(ElementCount VF);
930
931 /// A call may be vectorized in different ways depending on whether we have
932 /// vectorized variants available and whether the target supports masking.
933 /// This function analyzes all calls in the function at the supplied VF,
934 /// makes a decision based on the costs of available options, and stores that
935 /// decision in a map for use in planning and plan execution.
936 void setVectorizedCallDecision(ElementCount VF);
937
938 /// Collect values we want to ignore in the cost model.
939 void collectValuesToIgnore();
940
941 /// Collect all element types in the loop for which widening is needed.
942 void collectElementTypesForWidening();
943
944 /// Split reductions into those that happen in the loop, and those that happen
945 /// outside. In loop reductions are collected into InLoopReductions.
946 void collectInLoopReductions();
947
948 /// Returns true if we should use strict in-order reductions for the given
949 /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
950 /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
951 /// of FP operations.
952 bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
953 return !Hints->allowReordering() && RdxDesc.isOrdered();
954 }
955
956 /// \returns The smallest bitwidth each instruction can be represented with.
957 /// The vector equivalents of these instructions should be truncated to this
958 /// type.
960 return MinBWs;
961 }
962
963 /// \returns True if it is more profitable to scalarize instruction \p I for
964 /// vectorization factor \p VF.
966 assert(VF.isVector() &&
967 "Profitable to scalarize relevant only for VF > 1.");
968 assert(
969 TheLoop->isInnermost() &&
970 "cost-model should not be used for outer loops (in VPlan-native path)");
971
972 auto Scalars = InstsToScalarize.find(VF);
973 assert(Scalars != InstsToScalarize.end() &&
974 "VF not yet analyzed for scalarization profitability");
975 return Scalars->second.contains(I);
976 }
977
978 /// Returns true if \p I is known to be uniform after vectorization.
980 assert(
981 TheLoop->isInnermost() &&
982 "cost-model should not be used for outer loops (in VPlan-native path)");
983
984 // If VF is scalar, then all instructions are trivially uniform.
985 if (VF.isScalar())
986 return true;
987
988 // Pseudo probes must be duplicated per vector lane so that the
989 // profiled loop trip count is not undercounted.
991 return false;
992
993 auto UniformsPerVF = Uniforms.find(VF);
994 assert(UniformsPerVF != Uniforms.end() &&
995 "VF not yet analyzed for uniformity");
996 return UniformsPerVF->second.count(I);
997 }
998
999 /// Returns true if \p I is known to be scalar after vectorization.
1001 assert(
1002 TheLoop->isInnermost() &&
1003 "cost-model should not be used for outer loops (in VPlan-native path)");
1004 if (VF.isScalar())
1005 return true;
1006
1007 auto ScalarsPerVF = Scalars.find(VF);
1008 assert(ScalarsPerVF != Scalars.end() &&
1009 "Scalar values are not calculated for VF");
1010 return ScalarsPerVF->second.count(I);
1011 }
1012
1013 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1014 /// for vectorization factor \p VF.
1016 // Truncs must truncate at most to their destination type.
1017 if (isa_and_nonnull<TruncInst>(I) && MinBWs.contains(I) &&
1018 I->getType()->getScalarSizeInBits() < MinBWs.lookup(I))
1019 return false;
1020 return VF.isVector() && MinBWs.contains(I) &&
1021 !isProfitableToScalarize(I, VF) &&
1023 }
1024
1025 /// Decision that was taken during cost calculation for memory instruction.
1028 CM_Widen, // For consecutive accesses with stride +1.
1029 CM_Widen_Reverse, // For consecutive accesses with stride -1.
1035 };
1036
1037 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1038 /// instruction \p I and vector width \p VF.
1041 assert(VF.isVector() && "Expected VF >=2");
1042 WideningDecisions[{I, VF}] = {W, Cost};
1043 }
1044
1045 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1046 /// interleaving group \p Grp and vector width \p VF.
1050 assert(VF.isVector() && "Expected VF >=2");
1051 /// Broadcast this decicion to all instructions inside the group.
1052 /// When interleaving, the cost will only be assigned one instruction, the
1053 /// insert position. For other cases, add the appropriate fraction of the
1054 /// total cost to each instruction. This ensures accurate costs are used,
1055 /// even if the insert position instruction is not used.
1056 InstructionCost InsertPosCost = Cost;
1057 InstructionCost OtherMemberCost = 0;
1058 if (W != CM_Interleave)
1059 OtherMemberCost = InsertPosCost = Cost / Grp->getNumMembers();
1060 ;
1061 for (unsigned Idx = 0; Idx < Grp->getFactor(); ++Idx) {
1062 if (auto *I = Grp->getMember(Idx)) {
1063 if (Grp->getInsertPos() == I)
1064 WideningDecisions[{I, VF}] = {W, InsertPosCost};
1065 else
1066 WideningDecisions[{I, VF}] = {W, OtherMemberCost};
1067 }
1068 }
1069 }
1070
1071 /// Return the cost model decision for the given instruction \p I and vector
1072 /// width \p VF. Return CM_Unknown if this instruction did not pass
1073 /// through the cost modeling.
1075 assert(VF.isVector() && "Expected VF to be a vector VF");
1076 assert(
1077 TheLoop->isInnermost() &&
1078 "cost-model should not be used for outer loops (in VPlan-native path)");
1079
1080 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
1081 auto Itr = WideningDecisions.find(InstOnVF);
1082 if (Itr == WideningDecisions.end())
1083 return CM_Unknown;
1084 return Itr->second.first;
1085 }
1086
1087 /// Return the vectorization cost for the given instruction \p I and vector
1088 /// width \p VF.
1090 assert(VF.isVector() && "Expected VF >=2");
1091 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
1092 assert(WideningDecisions.contains(InstOnVF) &&
1093 "The cost is not calculated");
1094 return WideningDecisions[InstOnVF].second;
1095 }
1096
1104
1106 Function *Variant, Intrinsic::ID IID,
1107 std::optional<unsigned> MaskPos,
1109 assert(!VF.isScalar() && "Expected vector VF");
1110 CallWideningDecisions[{CI, VF}] = {Kind, Variant, IID, MaskPos, Cost};
1111 }
1112
1114 ElementCount VF) const {
1115 assert(!VF.isScalar() && "Expected vector VF");
1116 auto I = CallWideningDecisions.find({CI, VF});
1117 if (I == CallWideningDecisions.end())
1118 return {CM_Unknown, nullptr, Intrinsic::not_intrinsic, std::nullopt, 0};
1119 return I->second;
1120 }
1121
1122 /// Return True if instruction \p I is an optimizable truncate whose operand
1123 /// is an induction variable. Such a truncate will be removed by adding a new
1124 /// induction variable with the destination type.
1126 // If the instruction is not a truncate, return false.
1127 auto *Trunc = dyn_cast<TruncInst>(I);
1128 if (!Trunc)
1129 return false;
1130
1131 // Get the source and destination types of the truncate.
1132 Type *SrcTy = toVectorTy(Trunc->getSrcTy(), VF);
1133 Type *DestTy = toVectorTy(Trunc->getDestTy(), VF);
1134
1135 // If the truncate is free for the given types, return false. Replacing a
1136 // free truncate with an induction variable would add an induction variable
1137 // update instruction to each iteration of the loop. We exclude from this
1138 // check the primary induction variable since it will need an update
1139 // instruction regardless.
1140 Value *Op = Trunc->getOperand(0);
1141 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1142 return false;
1143
1144 // If the truncated value is not an induction variable, return false.
1145 return Legal->isInductionPhi(Op);
1146 }
1147
1148 /// Collects the instructions to scalarize for each predicated instruction in
1149 /// the loop.
1150 void collectInstsToScalarize(ElementCount VF);
1151
1152 /// Collect values that will not be widened, including Uniforms, Scalars, and
1153 /// Instructions to Scalarize for the given \p VF.
1154 /// The sets depend on CM decision for Load/Store instructions
1155 /// that may be vectorized as interleave, gather-scatter or scalarized.
1156 /// Also make a decision on what to do about call instructions in the loop
1157 /// at that VF -- scalarize, call a known vector routine, or call a
1158 /// vector intrinsic.
1160 // Do the analysis once.
1161 if (VF.isScalar() || Uniforms.contains(VF))
1162 return;
1164 collectLoopUniforms(VF);
1166 collectLoopScalars(VF);
1168 }
1169
1170 /// Returns true if the target machine supports masked store operation
1171 /// for the given \p DataType and kind of access to \p Ptr.
1172 bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment,
1173 unsigned AddressSpace) const {
1174 return Legal->isConsecutivePtr(DataType, Ptr) &&
1176 TTI.isLegalMaskedStore(DataType, Alignment, AddressSpace));
1177 }
1178
1179 /// Returns true if the target machine supports masked load operation
1180 /// for the given \p DataType and kind of access to \p Ptr.
1181 bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment,
1182 unsigned AddressSpace) const {
1183 return Legal->isConsecutivePtr(DataType, Ptr) &&
1185 TTI.isLegalMaskedLoad(DataType, Alignment, AddressSpace));
1186 }
1187
1188 /// Returns true if the target machine can represent \p V as a masked gather
1189 /// or scatter operation.
1191 bool LI = isa<LoadInst>(V);
1192 bool SI = isa<StoreInst>(V);
1193 if (!LI && !SI)
1194 return false;
1195 auto *Ty = getLoadStoreType(V);
1197 if (VF.isVector())
1198 Ty = VectorType::get(Ty, VF);
1199 return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1200 (SI && TTI.isLegalMaskedScatter(Ty, Align));
1201 }
1202
1203 /// Returns true if the target machine supports all of the reduction
1204 /// variables found for the given VF.
1206 return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1207 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1208 return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1209 }));
1210 }
1211
1212 /// Given costs for both strategies, return true if the scalar predication
1213 /// lowering should be used for div/rem. This incorporates an override
1214 /// option so it is not simply a cost comparison.
1216 InstructionCost SafeDivisorCost) const {
1217 switch (ForceSafeDivisor) {
1218 case cl::BOU_UNSET:
1219 return ScalarCost < SafeDivisorCost;
1220 case cl::BOU_TRUE:
1221 return false;
1222 case cl::BOU_FALSE:
1223 return true;
1224 }
1225 llvm_unreachable("impossible case value");
1226 }
1227
1228 /// Returns true if \p I is an instruction which requires predication and
1229 /// for which our chosen predication strategy is scalarization (i.e. we
1230 /// don't have an alternate strategy such as masking available).
1231 /// \p VF is the vectorization factor that will be used to vectorize \p I.
1232 bool isScalarWithPredication(Instruction *I, ElementCount VF);
1233
1234 /// Wrapper function for LoopVectorizationLegality::isMaskRequired,
1235 /// that passes the Instruction \p I and if we fold tail.
1236 bool isMaskRequired(Instruction *I) const;
1237
1238 /// Returns true if \p I is an instruction that needs to be predicated
1239 /// at runtime. The result is independent of the predication mechanism.
1240 /// Superset of instructions that return true for isScalarWithPredication.
1241 bool isPredicatedInst(Instruction *I) const;
1242
1243 /// A helper function that returns how much we should divide the cost of a
1244 /// predicated block by. Typically this is the reciprocal of the block
1245 /// probability, i.e. if we return X we are assuming the predicated block will
1246 /// execute once for every X iterations of the loop header so the block should
1247 /// only contribute 1/X of its cost to the total cost calculation, but when
1248 /// optimizing for code size it will just be 1 as code size costs don't depend
1249 /// on execution probabilities.
1250 ///
1251 /// Note that if a block wasn't originally predicated but was predicated due
1252 /// to tail folding, the divisor will still be 1 because it will execute for
1253 /// every iteration of the loop header.
1254 inline uint64_t
1255 getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind,
1256 const BasicBlock *BB);
1257
1258 /// Returns true if an artificially high cost for emulated masked memrefs
1259 /// should be used.
1260 bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1261
1262 /// Return the costs for our two available strategies for lowering a
1263 /// div/rem operation which requires speculating at least one lane.
1264 /// First result is for scalarization (will be invalid for scalable
1265 /// vectors); second is for the safe-divisor strategy.
1266 std::pair<InstructionCost, InstructionCost>
1267 getDivRemSpeculationCost(Instruction *I, ElementCount VF);
1268
1269 /// Returns true if \p I is a memory instruction with consecutive memory
1270 /// access that can be widened.
1271 bool memoryInstructionCanBeWidened(Instruction *I, ElementCount VF);
1272
1273 /// Returns true if \p I is a memory instruction in an interleaved-group
1274 /// of memory accesses that can be vectorized with wide vector loads/stores
1275 /// and shuffles.
1276 bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const;
1277
1278 /// Check if \p Instr belongs to any interleaved access group.
1280 return InterleaveInfo.isInterleaved(Instr);
1281 }
1282
1283 /// Get the interleaved access group that \p Instr belongs to.
1286 return InterleaveInfo.getInterleaveGroup(Instr);
1287 }
1288
1289 /// Returns true if we're required to use a scalar epilogue for at least
1290 /// the final iteration of the original loop.
1291 bool requiresScalarEpilogue(bool IsVectorizing) const {
1292 if (!isScalarEpilogueAllowed()) {
1293 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1294 return false;
1295 }
1296 // If we might exit from anywhere but the latch and early exit vectorization
1297 // is disabled, we must run the exiting iteration in scalar form.
1298 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
1299 !(EnableEarlyExitVectorization && Legal->hasUncountableEarlyExit())) {
1300 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: not exiting "
1301 "from latch block\n");
1302 return true;
1303 }
1304 if (IsVectorizing && InterleaveInfo.requiresScalarEpilogue()) {
1305 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: "
1306 "interleaved group requires scalar epilogue\n");
1307 return true;
1308 }
1309 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1310 return false;
1311 }
1312
1313 /// Returns true if a scalar epilogue is allowed (e.g.., not prevented by
1314 /// optsize or a loop hint annotation).
1316 return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1317 }
1318
1319 /// Returns true if tail-folding is preferred over a scalar epilogue.
1321 return ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate ||
1322 ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate;
1323 }
1324
1325 /// Returns the TailFoldingStyle that is best for the current loop.
1327 return ChosenTailFoldingStyle;
1328 }
1329
1330 /// Selects and saves TailFoldingStyle.
1331 /// \param IsScalableVF true if scalable vector factors enabled.
1332 /// \param UserIC User specific interleave count.
1333 void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC) {
1334 assert(ChosenTailFoldingStyle == TailFoldingStyle::None &&
1335 "Tail folding must not be selected yet.");
1336 if (!Legal->canFoldTailByMasking()) {
1337 ChosenTailFoldingStyle = TailFoldingStyle::None;
1338 return;
1339 }
1340
1341 // Default to TTI preference, but allow command line override.
1342 ChosenTailFoldingStyle = TTI.getPreferredTailFoldingStyle();
1343 if (ForceTailFoldingStyle.getNumOccurrences())
1344 ChosenTailFoldingStyle = ForceTailFoldingStyle.getValue();
1345
1346 if (ChosenTailFoldingStyle != TailFoldingStyle::DataWithEVL)
1347 return;
1348 // Override EVL styles if needed.
1349 // FIXME: Investigate opportunity for fixed vector factor.
1350 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
1351 TTI.hasActiveVectorLength() && !EnableVPlanNativePath;
1352 if (EVLIsLegal)
1353 return;
1354 // If for some reason EVL mode is unsupported, fallback to a scalar epilogue
1355 // if it's allowed, or DataWithoutLaneMask otherwise.
1356 if (ScalarEpilogueStatus == CM_ScalarEpilogueAllowed ||
1357 ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate)
1358 ChosenTailFoldingStyle = TailFoldingStyle::None;
1359 else
1360 ChosenTailFoldingStyle = TailFoldingStyle::DataWithoutLaneMask;
1361
1362 LLVM_DEBUG(
1363 dbgs() << "LV: Preference for VP intrinsics indicated. Will "
1364 "not try to generate VP Intrinsics "
1365 << (UserIC > 1
1366 ? "since interleave count specified is greater than 1.\n"
1367 : "due to non-interleaving reasons.\n"));
1368 }
1369
1370 /// Returns true if all loop blocks should be masked to fold tail loop.
1371 bool foldTailByMasking() const {
1373 }
1374
1375 /// Returns true if the use of wide lane masks is requested and the loop is
1376 /// using tail-folding with a lane mask for control flow.
1379 return false;
1380
1382 }
1383
1384 /// Return maximum safe number of elements to be processed per vector
1385 /// iteration, which do not prevent store-load forwarding and are safe with
1386 /// regard to the memory dependencies. Required for EVL-based VPlans to
1387 /// correctly calculate AVL (application vector length) as min(remaining AVL,
1388 /// MaxSafeElements).
1389 /// TODO: need to consider adjusting cost model to use this value as a
1390 /// vectorization factor for EVL-based vectorization.
1391 std::optional<unsigned> getMaxSafeElements() const { return MaxSafeElements; }
1392
1393 /// Returns true if the instructions in this block requires predication
1394 /// for any reason, e.g. because tail folding now requires a predicate
1395 /// or because the block in the original loop was predicated.
1397 return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1398 }
1399
1400 /// Returns true if VP intrinsics with explicit vector length support should
1401 /// be generated in the tail folded loop.
1405
1406 /// Returns true if the Phi is part of an inloop reduction.
1407 bool isInLoopReduction(PHINode *Phi) const {
1408 return InLoopReductions.contains(Phi);
1409 }
1410
1411 /// Returns the set of in-loop reduction PHIs.
1413 return InLoopReductions;
1414 }
1415
1416 /// Returns true if the predicated reduction select should be used to set the
1417 /// incoming value for the reduction phi.
1418 bool usePredicatedReductionSelect(RecurKind RecurrenceKind) const {
1419 // Force to use predicated reduction select since the EVL of the
1420 // second-to-last iteration might not be VF*UF.
1421 if (foldTailWithEVL())
1422 return true;
1423
1424 // Note: For FindLast recurrences we prefer a predicated select to simplify
1425 // matching in handleFindLastReductions(), rather than handle multiple
1426 // cases.
1428 return true;
1429
1431 TTI.preferPredicatedReductionSelect();
1432 }
1433
1434 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1435 /// with factor VF. Return the cost of the instruction, including
1436 /// scalarization overhead if it's needed.
1437 InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1438
1439 /// Estimate cost of a call instruction CI if it were vectorized with factor
1440 /// VF. Return the cost of the instruction, including scalarization overhead
1441 /// if it's needed.
1442 InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const;
1443
1444 /// Invalidates decisions already taken by the cost model.
1446 WideningDecisions.clear();
1447 CallWideningDecisions.clear();
1448 Uniforms.clear();
1449 Scalars.clear();
1450 }
1451
1452 /// Returns the expected execution cost. The unit of the cost does
1453 /// not matter because we use the 'cost' units to compare different
1454 /// vector widths. The cost that is returned is *not* normalized by
1455 /// the factor width.
1456 InstructionCost expectedCost(ElementCount VF);
1457
1458 bool hasPredStores() const { return NumPredStores > 0; }
1459
1460 /// Returns true if epilogue vectorization is considered profitable, and
1461 /// false otherwise.
1462 /// \p VF is the vectorization factor chosen for the original loop.
1463 /// \p Multiplier is an aditional scaling factor applied to VF before
1464 /// comparing to EpilogueVectorizationMinVF.
1465 bool isEpilogueVectorizationProfitable(const ElementCount VF,
1466 const unsigned IC) const;
1467
1468 /// Returns the execution time cost of an instruction for a given vector
1469 /// width. Vector width of one means scalar.
1470 InstructionCost getInstructionCost(Instruction *I, ElementCount VF);
1471
1472 /// Return the cost of instructions in an inloop reduction pattern, if I is
1473 /// part of that pattern.
1474 std::optional<InstructionCost> getReductionPatternCost(Instruction *I,
1475 ElementCount VF,
1476 Type *VectorTy) const;
1477
1478 /// Returns true if \p Op should be considered invariant and if it is
1479 /// trivially hoistable.
1480 bool shouldConsiderInvariant(Value *Op);
1481
1482 /// Return the value of vscale used for tuning the cost model.
1483 std::optional<unsigned> getVScaleForTuning() const { return VScaleForTuning; }
1484
1485private:
1486 unsigned NumPredStores = 0;
1487
1488 /// Used to store the value of vscale used for tuning the cost model. It is
1489 /// initialized during object construction.
1490 std::optional<unsigned> VScaleForTuning;
1491
1492 /// Initializes the value of vscale used for tuning the cost model. If
1493 /// vscale_range.min == vscale_range.max then return vscale_range.max, else
1494 /// return the value returned by the corresponding TTI method.
1495 void initializeVScaleForTuning() {
1496 const Function *Fn = TheLoop->getHeader()->getParent();
1497 if (Fn->hasFnAttribute(Attribute::VScaleRange)) {
1498 auto Attr = Fn->getFnAttribute(Attribute::VScaleRange);
1499 auto Min = Attr.getVScaleRangeMin();
1500 auto Max = Attr.getVScaleRangeMax();
1501 if (Max && Min == Max) {
1502 VScaleForTuning = Max;
1503 return;
1504 }
1505 }
1506
1507 VScaleForTuning = TTI.getVScaleForTuning();
1508 }
1509
1510 /// \return An upper bound for the vectorization factors for both
1511 /// fixed and scalable vectorization, where the minimum-known number of
1512 /// elements is a power-of-2 larger than zero. If scalable vectorization is
1513 /// disabled or unsupported, then the scalable part will be equal to
1514 /// ElementCount::getScalable(0).
1515 FixedScalableVFPair computeFeasibleMaxVF(unsigned MaxTripCount,
1516 ElementCount UserVF, unsigned UserIC,
1517 bool FoldTailByMasking);
1518
1519 /// If \p VF * \p UserIC > MaxTripcount, clamps VF to the next lower VF that
1520 /// results in VF * UserIC <= MaxTripCount.
1521 ElementCount clampVFByMaxTripCount(ElementCount VF, unsigned MaxTripCount,
1522 unsigned UserIC,
1523 bool FoldTailByMasking) const;
1524
1525 /// \return the maximized element count based on the targets vector
1526 /// registers and the loop trip-count, but limited to a maximum safe VF.
1527 /// This is a helper function of computeFeasibleMaxVF.
1528 ElementCount getMaximizedVFForTarget(unsigned MaxTripCount,
1529 unsigned SmallestType,
1530 unsigned WidestType,
1531 ElementCount MaxSafeVF, unsigned UserIC,
1532 bool FoldTailByMasking);
1533
1534 /// Checks if scalable vectorization is supported and enabled. Caches the
1535 /// result to avoid repeated debug dumps for repeated queries.
1536 bool isScalableVectorizationAllowed();
1537
1538 /// \return the maximum legal scalable VF, based on the safe max number
1539 /// of elements.
1540 ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1541
1542 /// Calculate vectorization cost of memory instruction \p I.
1543 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1544
1545 /// The cost computation for scalarized memory instruction.
1546 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1547
1548 /// The cost computation for interleaving group of memory instructions.
1549 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1550
1551 /// The cost computation for Gather/Scatter instruction.
1552 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1553
1554 /// The cost computation for widening instruction \p I with consecutive
1555 /// memory access.
1556 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1557
1558 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1559 /// Load: scalar load + broadcast.
1560 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1561 /// element)
1562 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1563
1564 /// Estimate the overhead of scalarizing an instruction. This is a
1565 /// convenience wrapper for the type-based getScalarizationOverhead API.
1567 ElementCount VF) const;
1568
1569 /// Map of scalar integer values to the smallest bitwidth they can be legally
1570 /// represented as. The vector equivalents of these values should be truncated
1571 /// to this type.
1572 MapVector<Instruction *, uint64_t> MinBWs;
1573
1574 /// A type representing the costs for instructions if they were to be
1575 /// scalarized rather than vectorized. The entries are Instruction-Cost
1576 /// pairs.
1577 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
1578
1579 /// A set containing all BasicBlocks that are known to present after
1580 /// vectorization as a predicated block.
1581 DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1582 PredicatedBBsAfterVectorization;
1583
1584 /// Records whether it is allowed to have the original scalar loop execute at
1585 /// least once. This may be needed as a fallback loop in case runtime
1586 /// aliasing/dependence checks fail, or to handle the tail/remainder
1587 /// iterations when the trip count is unknown or doesn't divide by the VF,
1588 /// or as a peel-loop to handle gaps in interleave-groups.
1589 /// Under optsize and when the trip count is very small we don't allow any
1590 /// iterations to execute in the scalar loop.
1591 ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1592
1593 /// Control finally chosen tail folding style.
1594 TailFoldingStyle ChosenTailFoldingStyle = TailFoldingStyle::None;
1595
1596 /// true if scalable vectorization is supported and enabled.
1597 std::optional<bool> IsScalableVectorizationAllowed;
1598
1599 /// Maximum safe number of elements to be processed per vector iteration,
1600 /// which do not prevent store-load forwarding and are safe with regard to the
1601 /// memory dependencies. Required for EVL-based veectorization, where this
1602 /// value is used as the upper bound of the safe AVL.
1603 std::optional<unsigned> MaxSafeElements;
1604
1605 /// A map holding scalar costs for different vectorization factors. The
1606 /// presence of a cost for an instruction in the mapping indicates that the
1607 /// instruction will be scalarized when vectorizing with the associated
1608 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1609 MapVector<ElementCount, ScalarCostsTy> InstsToScalarize;
1610
1611 /// Holds the instructions known to be uniform after vectorization.
1612 /// The data is collected per VF.
1613 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1614
1615 /// Holds the instructions known to be scalar after vectorization.
1616 /// The data is collected per VF.
1617 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1618
1619 /// Holds the instructions (address computations) that are forced to be
1620 /// scalarized.
1621 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1622
1623 /// PHINodes of the reductions that should be expanded in-loop.
1624 SmallPtrSet<PHINode *, 4> InLoopReductions;
1625
1626 /// A Map of inloop reduction operations and their immediate chain operand.
1627 /// FIXME: This can be removed once reductions can be costed correctly in
1628 /// VPlan. This was added to allow quick lookup of the inloop operations.
1629 DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1630
1631 /// Returns the expected difference in cost from scalarizing the expression
1632 /// feeding a predicated instruction \p PredInst. The instructions to
1633 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1634 /// non-negative return value implies the expression will be scalarized.
1635 /// Currently, only single-use chains are considered for scalarization.
1636 InstructionCost computePredInstDiscount(Instruction *PredInst,
1637 ScalarCostsTy &ScalarCosts,
1638 ElementCount VF);
1639
1640 /// Collect the instructions that are uniform after vectorization. An
1641 /// instruction is uniform if we represent it with a single scalar value in
1642 /// the vectorized loop corresponding to each vector iteration. Examples of
1643 /// uniform instructions include pointer operands of consecutive or
1644 /// interleaved memory accesses. Note that although uniformity implies an
1645 /// instruction will be scalar, the reverse is not true. In general, a
1646 /// scalarized instruction will be represented by VF scalar values in the
1647 /// vectorized loop, each corresponding to an iteration of the original
1648 /// scalar loop.
1649 void collectLoopUniforms(ElementCount VF);
1650
1651 /// Collect the instructions that are scalar after vectorization. An
1652 /// instruction is scalar if it is known to be uniform or will be scalarized
1653 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1654 /// to the list if they are used by a load/store instruction that is marked as
1655 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1656 /// VF values in the vectorized loop, each corresponding to an iteration of
1657 /// the original scalar loop.
1658 void collectLoopScalars(ElementCount VF);
1659
1660 /// Keeps cost model vectorization decision and cost for instructions.
1661 /// Right now it is used for memory instructions only.
1662 using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1663 std::pair<InstWidening, InstructionCost>>;
1664
1665 DecisionList WideningDecisions;
1666
1667 using CallDecisionList =
1668 DenseMap<std::pair<CallInst *, ElementCount>, CallWideningDecision>;
1669
1670 CallDecisionList CallWideningDecisions;
1671
1672 /// Returns true if \p V is expected to be vectorized and it needs to be
1673 /// extracted.
1674 bool needsExtract(Value *V, ElementCount VF) const {
1676 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1677 TheLoop->isLoopInvariant(I) ||
1678 getWideningDecision(I, VF) == CM_Scalarize ||
1679 (isa<CallInst>(I) &&
1680 getCallWideningDecision(cast<CallInst>(I), VF).Kind == CM_Scalarize))
1681 return false;
1682
1683 // Assume we can vectorize V (and hence we need extraction) if the
1684 // scalars are not computed yet. This can happen, because it is called
1685 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1686 // the scalars are collected. That should be a safe assumption in most
1687 // cases, because we check if the operands have vectorizable types
1688 // beforehand in LoopVectorizationLegality.
1689 return !Scalars.contains(VF) || !isScalarAfterVectorization(I, VF);
1690 };
1691
1692 /// Returns a range containing only operands needing to be extracted.
1693 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1694 ElementCount VF) const {
1695
1696 SmallPtrSet<const Value *, 4> UniqueOperands;
1697 SmallVector<Value *, 4> Res;
1698 for (Value *Op : Ops) {
1699 if (isa<Constant>(Op) || !UniqueOperands.insert(Op).second ||
1700 !needsExtract(Op, VF))
1701 continue;
1702 Res.push_back(Op);
1703 }
1704 return Res;
1705 }
1706
1707public:
1708 /// The loop that we evaluate.
1710
1711 /// Predicated scalar evolution analysis.
1713
1714 /// Loop Info analysis.
1716
1717 /// Vectorization legality.
1719
1720 /// Vector target information.
1722
1723 /// Target Library Info.
1725
1726 /// Demanded bits analysis.
1728
1729 /// Assumption cache.
1731
1732 /// Interface to emit optimization remarks.
1734
1735 /// A function to lazily fetch BlockFrequencyInfo. This avoids computing it
1736 /// unless necessary, e.g. when the loop isn't legal to vectorize or when
1737 /// there is no predication.
1738 std::function<BlockFrequencyInfo &()> GetBFI;
1739 /// The BlockFrequencyInfo returned from GetBFI.
1741 /// Returns the BlockFrequencyInfo for the function if cached, otherwise
1742 /// fetches it via GetBFI. Avoids an indirect call to the std::function.
1744 if (!BFI)
1745 BFI = &GetBFI();
1746 return *BFI;
1747 }
1748
1750
1751 /// Loop Vectorize Hint.
1753
1754 /// The interleave access information contains groups of interleaved accesses
1755 /// with the same stride and close to each other.
1757
1758 /// Values to ignore in the cost model.
1760
1761 /// Values to ignore in the cost model when VF > 1.
1763
1764 /// All element types found in the loop.
1766
1767 /// The kind of cost that we are calculating
1769
1770 /// Whether this loop should be optimized for size based on function attribute
1771 /// or profile information.
1773
1774 /// The highest VF possible for this loop, without using MaxBandwidth.
1776};
1777} // end namespace llvm
1778
1779namespace {
1780/// Helper struct to manage generating runtime checks for vectorization.
1781///
1782/// The runtime checks are created up-front in temporary blocks to allow better
1783/// estimating the cost and un-linked from the existing IR. After deciding to
1784/// vectorize, the checks are moved back. If deciding not to vectorize, the
1785/// temporary blocks are completely removed.
1786class GeneratedRTChecks {
1787 /// Basic block which contains the generated SCEV checks, if any.
1788 BasicBlock *SCEVCheckBlock = nullptr;
1789
1790 /// The value representing the result of the generated SCEV checks. If it is
1791 /// nullptr no SCEV checks have been generated.
1792 Value *SCEVCheckCond = nullptr;
1793
1794 /// Basic block which contains the generated memory runtime checks, if any.
1795 BasicBlock *MemCheckBlock = nullptr;
1796
1797 /// The value representing the result of the generated memory runtime checks.
1798 /// If it is nullptr no memory runtime checks have been generated.
1799 Value *MemRuntimeCheckCond = nullptr;
1800
1801 DominatorTree *DT;
1802 LoopInfo *LI;
1804
1805 SCEVExpander SCEVExp;
1806 SCEVExpander MemCheckExp;
1807
1808 bool CostTooHigh = false;
1809
1810 Loop *OuterLoop = nullptr;
1811
1813
1814 /// The kind of cost that we are calculating
1816
1817public:
1818 GeneratedRTChecks(PredicatedScalarEvolution &PSE, DominatorTree *DT,
1821 : DT(DT), LI(LI), TTI(TTI),
1822 SCEVExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1823 MemCheckExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1824 PSE(PSE), CostKind(CostKind) {}
1825
1826 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1827 /// accurately estimate the cost of the runtime checks. The blocks are
1828 /// un-linked from the IR and are added back during vector code generation. If
1829 /// there is no vector code generation, the check blocks are removed
1830 /// completely.
1831 void create(Loop *L, const LoopAccessInfo &LAI,
1832 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC,
1833 OptimizationRemarkEmitter &ORE) {
1834
1835 // Hard cutoff to limit compile-time increase in case a very large number of
1836 // runtime checks needs to be generated.
1837 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1838 // profile info.
1839 CostTooHigh =
1841 if (CostTooHigh) {
1842 // Mark runtime checks as never succeeding when they exceed the threshold.
1843 MemRuntimeCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1844 SCEVCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1845 ORE.emit([&]() {
1846 return OptimizationRemarkAnalysisAliasing(
1847 DEBUG_TYPE, "TooManyMemoryRuntimeChecks", L->getStartLoc(),
1848 L->getHeader())
1849 << "loop not vectorized: too many memory checks needed";
1850 });
1851 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1852 return;
1853 }
1854
1855 BasicBlock *LoopHeader = L->getHeader();
1856 BasicBlock *Preheader = L->getLoopPreheader();
1857
1858 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1859 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1860 // may be used by SCEVExpander. The blocks will be un-linked from their
1861 // predecessors and removed from LI & DT at the end of the function.
1862 if (!UnionPred.isAlwaysTrue()) {
1863 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1864 nullptr, "vector.scevcheck");
1865
1866 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1867 &UnionPred, SCEVCheckBlock->getTerminator());
1868 if (isa<Constant>(SCEVCheckCond)) {
1869 // Clean up directly after expanding the predicate to a constant, to
1870 // avoid further expansions re-using anything left over from SCEVExp.
1871 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1872 SCEVCleaner.cleanup();
1873 }
1874 }
1875
1876 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1877 if (RtPtrChecking.Need) {
1878 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1879 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1880 "vector.memcheck");
1881
1882 auto DiffChecks = RtPtrChecking.getDiffChecks();
1883 if (DiffChecks) {
1884 Value *RuntimeVF = nullptr;
1885 MemRuntimeCheckCond = addDiffRuntimeChecks(
1886 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp,
1887 [VF, &RuntimeVF](IRBuilderBase &B, unsigned Bits) {
1888 if (!RuntimeVF)
1889 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1890 return RuntimeVF;
1891 },
1892 IC);
1893 } else {
1894 MemRuntimeCheckCond = addRuntimeChecks(
1895 MemCheckBlock->getTerminator(), L, RtPtrChecking.getChecks(),
1897 }
1898 assert(MemRuntimeCheckCond &&
1899 "no RT checks generated although RtPtrChecking "
1900 "claimed checks are required");
1901 }
1902
1903 SCEVExp.eraseDeadInstructions(SCEVCheckCond);
1904
1905 if (!MemCheckBlock && !SCEVCheckBlock)
1906 return;
1907
1908 // Unhook the temporary block with the checks, update various places
1909 // accordingly.
1910 if (SCEVCheckBlock)
1911 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1912 if (MemCheckBlock)
1913 MemCheckBlock->replaceAllUsesWith(Preheader);
1914
1915 if (SCEVCheckBlock) {
1916 SCEVCheckBlock->getTerminator()->moveBefore(
1917 Preheader->getTerminator()->getIterator());
1918 auto *UI = new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1919 UI->setDebugLoc(DebugLoc::getTemporary());
1920 Preheader->getTerminator()->eraseFromParent();
1921 }
1922 if (MemCheckBlock) {
1923 MemCheckBlock->getTerminator()->moveBefore(
1924 Preheader->getTerminator()->getIterator());
1925 auto *UI = new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1926 UI->setDebugLoc(DebugLoc::getTemporary());
1927 Preheader->getTerminator()->eraseFromParent();
1928 }
1929
1930 DT->changeImmediateDominator(LoopHeader, Preheader);
1931 if (MemCheckBlock) {
1932 DT->eraseNode(MemCheckBlock);
1933 LI->removeBlock(MemCheckBlock);
1934 }
1935 if (SCEVCheckBlock) {
1936 DT->eraseNode(SCEVCheckBlock);
1937 LI->removeBlock(SCEVCheckBlock);
1938 }
1939
1940 // Outer loop is used as part of the later cost calculations.
1941 OuterLoop = L->getParentLoop();
1942 }
1943
1945 if (SCEVCheckBlock || MemCheckBlock)
1946 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1947
1948 if (CostTooHigh) {
1950 Cost.setInvalid();
1951 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1952 return Cost;
1953 }
1954
1955 InstructionCost RTCheckCost = 0;
1956 if (SCEVCheckBlock)
1957 for (Instruction &I : *SCEVCheckBlock) {
1958 if (SCEVCheckBlock->getTerminator() == &I)
1959 continue;
1961 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1962 RTCheckCost += C;
1963 }
1964 if (MemCheckBlock) {
1965 InstructionCost MemCheckCost = 0;
1966 for (Instruction &I : *MemCheckBlock) {
1967 if (MemCheckBlock->getTerminator() == &I)
1968 continue;
1970 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1971 MemCheckCost += C;
1972 }
1973
1974 // If the runtime memory checks are being created inside an outer loop
1975 // we should find out if these checks are outer loop invariant. If so,
1976 // the checks will likely be hoisted out and so the effective cost will
1977 // reduce according to the outer loop trip count.
1978 if (OuterLoop) {
1979 ScalarEvolution *SE = MemCheckExp.getSE();
1980 // TODO: If profitable, we could refine this further by analysing every
1981 // individual memory check, since there could be a mixture of loop
1982 // variant and invariant checks that mean the final condition is
1983 // variant.
1984 const SCEV *Cond = SE->getSCEV(MemRuntimeCheckCond);
1985 if (SE->isLoopInvariant(Cond, OuterLoop)) {
1986 // It seems reasonable to assume that we can reduce the effective
1987 // cost of the checks even when we know nothing about the trip
1988 // count. Assume that the outer loop executes at least twice.
1989 unsigned BestTripCount = 2;
1990
1991 // Get the best known TC estimate.
1992 if (auto EstimatedTC = getSmallBestKnownTC(
1993 PSE, OuterLoop, /* CanUseConstantMax = */ false))
1994 if (EstimatedTC->isFixed())
1995 BestTripCount = EstimatedTC->getFixedValue();
1996
1997 InstructionCost NewMemCheckCost = MemCheckCost / BestTripCount;
1998
1999 // Let's ensure the cost is always at least 1.
2000 NewMemCheckCost = std::max(NewMemCheckCost.getValue(),
2001 (InstructionCost::CostType)1);
2002
2003 if (BestTripCount > 1)
2005 << "We expect runtime memory checks to be hoisted "
2006 << "out of the outer loop. Cost reduced from "
2007 << MemCheckCost << " to " << NewMemCheckCost << '\n');
2008
2009 MemCheckCost = NewMemCheckCost;
2010 }
2011 }
2012
2013 RTCheckCost += MemCheckCost;
2014 }
2015
2016 if (SCEVCheckBlock || MemCheckBlock)
2017 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
2018 << "\n");
2019
2020 return RTCheckCost;
2021 }
2022
2023 /// Remove the created SCEV & memory runtime check blocks & instructions, if
2024 /// unused.
2025 ~GeneratedRTChecks() {
2026 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2027 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2028 bool SCEVChecksUsed = !SCEVCheckBlock || !pred_empty(SCEVCheckBlock);
2029 bool MemChecksUsed = !MemCheckBlock || !pred_empty(MemCheckBlock);
2030 if (SCEVChecksUsed)
2031 SCEVCleaner.markResultUsed();
2032
2033 if (MemChecksUsed) {
2034 MemCheckCleaner.markResultUsed();
2035 } else {
2036 auto &SE = *MemCheckExp.getSE();
2037 // Memory runtime check generation creates compares that use expanded
2038 // values. Remove them before running the SCEVExpanderCleaners.
2039 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2040 if (MemCheckExp.isInsertedInstruction(&I))
2041 continue;
2042 SE.forgetValue(&I);
2043 I.eraseFromParent();
2044 }
2045 }
2046 MemCheckCleaner.cleanup();
2047 SCEVCleaner.cleanup();
2048
2049 if (!SCEVChecksUsed)
2050 SCEVCheckBlock->eraseFromParent();
2051 if (!MemChecksUsed)
2052 MemCheckBlock->eraseFromParent();
2053 }
2054
2055 /// Retrieves the SCEVCheckCond and SCEVCheckBlock that were generated as IR
2056 /// outside VPlan.
2057 std::pair<Value *, BasicBlock *> getSCEVChecks() const {
2058 using namespace llvm::PatternMatch;
2059 if (!SCEVCheckCond || match(SCEVCheckCond, m_ZeroInt()))
2060 return {nullptr, nullptr};
2061
2062 return {SCEVCheckCond, SCEVCheckBlock};
2063 }
2064
2065 /// Retrieves the MemCheckCond and MemCheckBlock that were generated as IR
2066 /// outside VPlan.
2067 std::pair<Value *, BasicBlock *> getMemRuntimeChecks() const {
2068 using namespace llvm::PatternMatch;
2069 if (MemRuntimeCheckCond && match(MemRuntimeCheckCond, m_ZeroInt()))
2070 return {nullptr, nullptr};
2071 return {MemRuntimeCheckCond, MemCheckBlock};
2072 }
2073
2074 /// Return true if any runtime checks have been added
2075 bool hasChecks() const {
2076 return getSCEVChecks().first || getMemRuntimeChecks().first;
2077 }
2078};
2079} // namespace
2080
2082 return Style == TailFoldingStyle::Data ||
2084}
2085
2089
2090// Return true if \p OuterLp is an outer loop annotated with hints for explicit
2091// vectorization. The loop needs to be annotated with #pragma omp simd
2092// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2093// vector length information is not provided, vectorization is not considered
2094// explicit. Interleave hints are not allowed either. These limitations will be
2095// relaxed in the future.
2096// Please, note that we are currently forced to abuse the pragma 'clang
2097// vectorize' semantics. This pragma provides *auto-vectorization hints*
2098// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2099// provides *explicit vectorization hints* (LV can bypass legal checks and
2100// assume that vectorization is legal). However, both hints are implemented
2101// using the same metadata (llvm.loop.vectorize, processed by
2102// LoopVectorizeHints). This will be fixed in the future when the native IR
2103// representation for pragma 'omp simd' is introduced.
2104static bool isExplicitVecOuterLoop(Loop *OuterLp,
2106 assert(!OuterLp->isInnermost() && "This is not an outer loop");
2107 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2108
2109 // Only outer loops with an explicit vectorization hint are supported.
2110 // Unannotated outer loops are ignored.
2112 return false;
2113
2114 Function *Fn = OuterLp->getHeader()->getParent();
2115 if (!Hints.allowVectorization(Fn, OuterLp,
2116 true /*VectorizeOnlyWhenForced*/)) {
2117 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2118 return false;
2119 }
2120
2121 if (Hints.getInterleave() > 1) {
2122 // TODO: Interleave support is future work.
2123 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2124 "outer loops.\n");
2125 Hints.emitRemarkWithHints();
2126 return false;
2127 }
2128
2129 return true;
2130}
2131
2135 // Collect inner loops and outer loops without irreducible control flow. For
2136 // now, only collect outer loops that have explicit vectorization hints. If we
2137 // are stress testing the VPlan H-CFG construction, we collect the outermost
2138 // loop of every loop nest.
2139 if (L.isInnermost() || VPlanBuildStressTest ||
2141 LoopBlocksRPO RPOT(&L);
2142 RPOT.perform(LI);
2144 V.push_back(&L);
2145 // TODO: Collect inner loops inside marked outer loops in case
2146 // vectorization fails for the outer loop. Do not invoke
2147 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2148 // already known to be reducible. We can use an inherited attribute for
2149 // that.
2150 return;
2151 }
2152 }
2153 for (Loop *InnerL : L)
2154 collectSupportedLoops(*InnerL, LI, ORE, V);
2155}
2156
2157//===----------------------------------------------------------------------===//
2158// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2159// LoopVectorizationCostModel and LoopVectorizationPlanner.
2160//===----------------------------------------------------------------------===//
2161
2162/// FIXME: The newly created binary instructions should contain nsw/nuw
2163/// flags, which can be found from the original scalar operations.
2164Value *
2166 Value *Step,
2168 const BinaryOperator *InductionBinOp) {
2169 using namespace llvm::PatternMatch;
2170 Type *StepTy = Step->getType();
2171 Value *CastedIndex = StepTy->isIntegerTy()
2172 ? B.CreateSExtOrTrunc(Index, StepTy)
2173 : B.CreateCast(Instruction::SIToFP, Index, StepTy);
2174 if (CastedIndex != Index) {
2175 CastedIndex->setName(CastedIndex->getName() + ".cast");
2176 Index = CastedIndex;
2177 }
2178
2179 // Note: the IR at this point is broken. We cannot use SE to create any new
2180 // SCEV and then expand it, hoping that SCEV's simplification will give us
2181 // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2182 // lead to various SCEV crashes. So all we can do is to use builder and rely
2183 // on InstCombine for future simplifications. Here we handle some trivial
2184 // cases only.
2185 auto CreateAdd = [&B](Value *X, Value *Y) {
2186 assert(X->getType() == Y->getType() && "Types don't match!");
2187 if (match(X, m_ZeroInt()))
2188 return Y;
2189 if (match(Y, m_ZeroInt()))
2190 return X;
2191 return B.CreateAdd(X, Y);
2192 };
2193
2194 // We allow X to be a vector type, in which case Y will potentially be
2195 // splatted into a vector with the same element count.
2196 auto CreateMul = [&B](Value *X, Value *Y) {
2197 assert(X->getType()->getScalarType() == Y->getType() &&
2198 "Types don't match!");
2199 if (match(X, m_One()))
2200 return Y;
2201 if (match(Y, m_One()))
2202 return X;
2203 VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2204 if (XVTy && !isa<VectorType>(Y->getType()))
2205 Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2206 return B.CreateMul(X, Y);
2207 };
2208
2209 switch (InductionKind) {
2211 assert(!isa<VectorType>(Index->getType()) &&
2212 "Vector indices not supported for integer inductions yet");
2213 assert(Index->getType() == StartValue->getType() &&
2214 "Index type does not match StartValue type");
2215 if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2216 return B.CreateSub(StartValue, Index);
2217 auto *Offset = CreateMul(Index, Step);
2218 return CreateAdd(StartValue, Offset);
2219 }
2221 return B.CreatePtrAdd(StartValue, CreateMul(Index, Step));
2223 assert(!isa<VectorType>(Index->getType()) &&
2224 "Vector indices not supported for FP inductions yet");
2225 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2226 assert(InductionBinOp &&
2227 (InductionBinOp->getOpcode() == Instruction::FAdd ||
2228 InductionBinOp->getOpcode() == Instruction::FSub) &&
2229 "Original bin op should be defined for FP induction");
2230
2231 Value *MulExp = B.CreateFMul(Step, Index);
2232 return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2233 "induction");
2234 }
2236 return nullptr;
2237 }
2238 llvm_unreachable("invalid enum");
2239}
2240
2241static std::optional<unsigned> getMaxVScale(const Function &F,
2242 const TargetTransformInfo &TTI) {
2243 if (std::optional<unsigned> MaxVScale = TTI.getMaxVScale())
2244 return MaxVScale;
2245
2246 if (F.hasFnAttribute(Attribute::VScaleRange))
2247 return F.getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
2248
2249 return std::nullopt;
2250}
2251
2252/// For the given VF and UF and maximum trip count computed for the loop, return
2253/// whether the induction variable might overflow in the vectorized loop. If not,
2254/// then we know a runtime overflow check always evaluates to false and can be
2255/// removed.
2257 const LoopVectorizationCostModel *Cost,
2258 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
2259 // Always be conservative if we don't know the exact unroll factor.
2260 unsigned MaxUF = UF ? *UF : Cost->TTI.getMaxInterleaveFactor(VF);
2261
2262 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
2263 APInt MaxUIntTripCount = IdxTy->getMask();
2264
2265 // We know the runtime overflow check is known false iff the (max) trip-count
2266 // is known and (max) trip-count + (VF * UF) does not overflow in the type of
2267 // the vector loop induction variable.
2268 if (unsigned TC = Cost->PSE.getSmallConstantMaxTripCount()) {
2269 uint64_t MaxVF = VF.getKnownMinValue();
2270 if (VF.isScalable()) {
2271 std::optional<unsigned> MaxVScale =
2272 getMaxVScale(*Cost->TheFunction, Cost->TTI);
2273 if (!MaxVScale)
2274 return false;
2275 MaxVF *= *MaxVScale;
2276 }
2277
2278 return (MaxUIntTripCount - TC).ugt(MaxVF * MaxUF);
2279 }
2280
2281 return false;
2282}
2283
2284// Return whether we allow using masked interleave-groups (for dealing with
2285// strided loads/stores that reside in predicated blocks, or for dealing
2286// with gaps).
2288 // If an override option has been passed in for interleaved accesses, use it.
2289 if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2291
2292 return TTI.enableMaskedInterleavedAccessVectorization();
2293}
2294
2295/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
2296/// VPBB are moved to the end of the newly created VPIRBasicBlock. All
2297/// predecessors and successors of VPBB, if any, are rewired to the new
2298/// VPIRBasicBlock. If \p VPBB may be unreachable, \p Plan must be passed.
2300 BasicBlock *IRBB,
2301 VPlan *Plan = nullptr) {
2302 if (!Plan)
2303 Plan = VPBB->getPlan();
2304 VPIRBasicBlock *IRVPBB = Plan->createVPIRBasicBlock(IRBB);
2305 auto IP = IRVPBB->begin();
2306 for (auto &R : make_early_inc_range(VPBB->phis()))
2307 R.moveBefore(*IRVPBB, IP);
2308
2309 for (auto &R :
2311 R.moveBefore(*IRVPBB, IRVPBB->end());
2312
2313 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB);
2314 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
2315 return IRVPBB;
2316}
2317
2319 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2320 assert(VectorPH && "Invalid loop structure");
2321 assert((OrigLoop->getUniqueLatchExitBlock() ||
2322 Cost->requiresScalarEpilogue(VF.isVector())) &&
2323 "loops not exiting via the latch without required epilogue?");
2324
2325 // NOTE: The Plan's scalar preheader VPBB isn't replaced with a VPIRBasicBlock
2326 // wrapping the newly created scalar preheader here at the moment, because the
2327 // Plan's scalar preheader may be unreachable at this point. Instead it is
2328 // replaced in executePlan.
2329 return SplitBlock(VectorPH, VectorPH->getTerminator(), DT, LI, nullptr,
2330 Twine(Prefix) + "scalar.ph");
2331}
2332
2333/// Knowing that loop \p L executes a single vector iteration, add instructions
2334/// that will get simplified and thus should not have any cost to \p
2335/// InstsToIgnore.
2338 SmallPtrSetImpl<Instruction *> &InstsToIgnore) {
2339 auto *Cmp = L->getLatchCmpInst();
2340 if (Cmp)
2341 InstsToIgnore.insert(Cmp);
2342 for (const auto &KV : IL) {
2343 // Extract the key by hand so that it can be used in the lambda below. Note
2344 // that captured structured bindings are a C++20 extension.
2345 const PHINode *IV = KV.first;
2346
2347 // Get next iteration value of the induction variable.
2348 Instruction *IVInst =
2349 cast<Instruction>(IV->getIncomingValueForBlock(L->getLoopLatch()));
2350 if (all_of(IVInst->users(),
2351 [&](const User *U) { return U == IV || U == Cmp; }))
2352 InstsToIgnore.insert(IVInst);
2353 }
2354}
2355
2357 // Create a new IR basic block for the scalar preheader.
2358 BasicBlock *ScalarPH = createScalarPreheader("");
2359 return ScalarPH->getSinglePredecessor();
2360}
2361
2362namespace {
2363
2364struct CSEDenseMapInfo {
2365 static bool canHandle(const Instruction *I) {
2368 }
2369
2370 static inline Instruction *getEmptyKey() {
2372 }
2373
2374 static inline Instruction *getTombstoneKey() {
2375 return DenseMapInfo<Instruction *>::getTombstoneKey();
2376 }
2377
2378 static unsigned getHashValue(const Instruction *I) {
2379 assert(canHandle(I) && "Unknown instruction!");
2380 return hash_combine(I->getOpcode(),
2381 hash_combine_range(I->operand_values()));
2382 }
2383
2384 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
2385 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2386 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2387 return LHS == RHS;
2388 return LHS->isIdenticalTo(RHS);
2389 }
2390};
2391
2392} // end anonymous namespace
2393
2394/// FIXME: This legacy common-subexpression-elimination routine is scheduled for
2395/// removal, in favor of the VPlan-based one.
2396static void legacyCSE(BasicBlock *BB) {
2397 // Perform simple cse.
2399 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
2400 if (!CSEDenseMapInfo::canHandle(&In))
2401 continue;
2402
2403 // Check if we can replace this instruction with any of the
2404 // visited instructions.
2405 if (Instruction *V = CSEMap.lookup(&In)) {
2406 In.replaceAllUsesWith(V);
2407 In.eraseFromParent();
2408 continue;
2409 }
2410
2411 CSEMap[&In] = &In;
2412 }
2413}
2414
2415/// This function attempts to return a value that represents the ElementCount
2416/// at runtime. For fixed-width VFs we know this precisely at compile
2417/// time, but for scalable VFs we calculate it based on an estimate of the
2418/// vscale value.
2420 std::optional<unsigned> VScale) {
2421 unsigned EstimatedVF = VF.getKnownMinValue();
2422 if (VF.isScalable())
2423 if (VScale)
2424 EstimatedVF *= *VScale;
2425 assert(EstimatedVF >= 1 && "Estimated VF shouldn't be less than 1");
2426 return EstimatedVF;
2427}
2428
2431 ElementCount VF) const {
2432 // We only need to calculate a cost if the VF is scalar; for actual vectors
2433 // we should already have a pre-calculated cost at each VF.
2434 if (!VF.isScalar())
2435 return getCallWideningDecision(CI, VF).Cost;
2436
2437 Type *RetTy = CI->getType();
2439 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy))
2440 return *RedCost;
2441
2443 for (auto &ArgOp : CI->args())
2444 Tys.push_back(ArgOp->getType());
2445
2446 InstructionCost ScalarCallCost =
2447 TTI.getCallInstrCost(CI->getCalledFunction(), RetTy, Tys, CostKind);
2448
2449 // If this is an intrinsic we may have a lower cost for it.
2452 return std::min(ScalarCallCost, IntrinsicCost);
2453 }
2454 return ScalarCallCost;
2455}
2456
2458 if (VF.isScalar() || !canVectorizeTy(Ty))
2459 return Ty;
2460 return toVectorizedTy(Ty, VF);
2461}
2462
2465 ElementCount VF) const {
2467 assert(ID && "Expected intrinsic call!");
2468 Type *RetTy = maybeVectorizeType(CI->getType(), VF);
2469 FastMathFlags FMF;
2470 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2471 FMF = FPMO->getFastMathFlags();
2472
2475 SmallVector<Type *> ParamTys;
2476 std::transform(FTy->param_begin(), FTy->param_end(),
2477 std::back_inserter(ParamTys),
2478 [&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
2479
2480 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
2483 return TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
2484}
2485
2487 // Fix widened non-induction PHIs by setting up the PHI operands.
2488 fixNonInductionPHIs(State);
2489
2490 // Don't apply optimizations below when no (vector) loop remains, as they all
2491 // require one at the moment.
2492 VPBasicBlock *HeaderVPBB =
2493 vputils::getFirstLoopHeader(*State.Plan, State.VPDT);
2494 if (!HeaderVPBB)
2495 return;
2496
2497 BasicBlock *HeaderBB = State.CFG.VPBB2IRBB[HeaderVPBB];
2498
2499 // Remove redundant induction instructions.
2500 legacyCSE(HeaderBB);
2501}
2502
2504 auto Iter = vp_depth_first_shallow(Plan.getEntry());
2506 for (VPRecipeBase &P : VPBB->phis()) {
2508 if (!VPPhi)
2509 continue;
2510 PHINode *NewPhi = cast<PHINode>(State.get(VPPhi));
2511 // Make sure the builder has a valid insert point.
2512 Builder.SetInsertPoint(NewPhi);
2513 for (const auto &[Inc, VPBB] : VPPhi->incoming_values_and_blocks())
2514 NewPhi->addIncoming(State.get(Inc), State.CFG.VPBB2IRBB[VPBB]);
2515 }
2516 }
2517}
2518
2519void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
2520 // We should not collect Scalars more than once per VF. Right now, this
2521 // function is called from collectUniformsAndScalars(), which already does
2522 // this check. Collecting Scalars for VF=1 does not make any sense.
2523 assert(VF.isVector() && !Scalars.contains(VF) &&
2524 "This function should not be visited twice for the same VF");
2525
2526 // This avoids any chances of creating a REPLICATE recipe during planning
2527 // since that would result in generation of scalarized code during execution,
2528 // which is not supported for scalable vectors.
2529 if (VF.isScalable()) {
2530 Scalars[VF].insert_range(Uniforms[VF]);
2531 return;
2532 }
2533
2535
2536 // These sets are used to seed the analysis with pointers used by memory
2537 // accesses that will remain scalar.
2539 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
2540 auto *Latch = TheLoop->getLoopLatch();
2541
2542 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
2543 // The pointer operands of loads and stores will be scalar as long as the
2544 // memory access is not a gather or scatter operation. The value operand of a
2545 // store will remain scalar if the store is scalarized.
2546 auto IsScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
2547 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
2548 assert(WideningDecision != CM_Unknown &&
2549 "Widening decision should be ready at this moment");
2550 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
2551 if (Ptr == Store->getValueOperand())
2552 return WideningDecision == CM_Scalarize;
2553 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
2554 "Ptr is neither a value or pointer operand");
2555 return WideningDecision != CM_GatherScatter;
2556 };
2557
2558 // A helper that returns true if the given value is a getelementptr
2559 // instruction contained in the loop.
2560 auto IsLoopVaryingGEP = [&](Value *V) {
2561 return isa<GetElementPtrInst>(V) && !TheLoop->isLoopInvariant(V);
2562 };
2563
2564 // A helper that evaluates a memory access's use of a pointer. If the use will
2565 // be a scalar use and the pointer is only used by memory accesses, we place
2566 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
2567 // PossibleNonScalarPtrs.
2568 auto EvaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
2569 // We only care about bitcast and getelementptr instructions contained in
2570 // the loop.
2571 if (!IsLoopVaryingGEP(Ptr))
2572 return;
2573
2574 // If the pointer has already been identified as scalar (e.g., if it was
2575 // also identified as uniform), there's nothing to do.
2576 auto *I = cast<Instruction>(Ptr);
2577 if (Worklist.count(I))
2578 return;
2579
2580 // If the use of the pointer will be a scalar use, and all users of the
2581 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
2582 // place the pointer in PossibleNonScalarPtrs.
2583 if (IsScalarUse(MemAccess, Ptr) &&
2585 ScalarPtrs.insert(I);
2586 else
2587 PossibleNonScalarPtrs.insert(I);
2588 };
2589
2590 // We seed the scalars analysis with three classes of instructions: (1)
2591 // instructions marked uniform-after-vectorization and (2) bitcast,
2592 // getelementptr and (pointer) phi instructions used by memory accesses
2593 // requiring a scalar use.
2594 //
2595 // (1) Add to the worklist all instructions that have been identified as
2596 // uniform-after-vectorization.
2597 Worklist.insert_range(Uniforms[VF]);
2598
2599 // (2) Add to the worklist all bitcast and getelementptr instructions used by
2600 // memory accesses requiring a scalar use. The pointer operands of loads and
2601 // stores will be scalar unless the operation is a gather or scatter.
2602 // The value operand of a store will remain scalar if the store is scalarized.
2603 for (auto *BB : TheLoop->blocks())
2604 for (auto &I : *BB) {
2605 if (auto *Load = dyn_cast<LoadInst>(&I)) {
2606 EvaluatePtrUse(Load, Load->getPointerOperand());
2607 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2608 EvaluatePtrUse(Store, Store->getPointerOperand());
2609 EvaluatePtrUse(Store, Store->getValueOperand());
2610 }
2611 }
2612 for (auto *I : ScalarPtrs)
2613 if (!PossibleNonScalarPtrs.count(I)) {
2614 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
2615 Worklist.insert(I);
2616 }
2617
2618 // Insert the forced scalars.
2619 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
2620 // induction variable when the PHI user is scalarized.
2621 auto ForcedScalar = ForcedScalars.find(VF);
2622 if (ForcedScalar != ForcedScalars.end())
2623 for (auto *I : ForcedScalar->second) {
2624 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
2625 Worklist.insert(I);
2626 }
2627
2628 // Expand the worklist by looking through any bitcasts and getelementptr
2629 // instructions we've already identified as scalar. This is similar to the
2630 // expansion step in collectLoopUniforms(); however, here we're only
2631 // expanding to include additional bitcasts and getelementptr instructions.
2632 unsigned Idx = 0;
2633 while (Idx != Worklist.size()) {
2634 Instruction *Dst = Worklist[Idx++];
2635 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
2636 continue;
2637 auto *Src = cast<Instruction>(Dst->getOperand(0));
2638 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
2639 auto *J = cast<Instruction>(U);
2640 return !TheLoop->contains(J) || Worklist.count(J) ||
2641 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
2642 IsScalarUse(J, Src));
2643 })) {
2644 Worklist.insert(Src);
2645 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
2646 }
2647 }
2648
2649 // An induction variable will remain scalar if all users of the induction
2650 // variable and induction variable update remain scalar.
2651 for (const auto &Induction : Legal->getInductionVars()) {
2652 auto *Ind = Induction.first;
2653 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2654
2655 // If tail-folding is applied, the primary induction variable will be used
2656 // to feed a vector compare.
2657 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
2658 continue;
2659
2660 // Returns true if \p Indvar is a pointer induction that is used directly by
2661 // load/store instruction \p I.
2662 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
2663 Instruction *I) {
2664 return Induction.second.getKind() ==
2667 Indvar == getLoadStorePointerOperand(I) && IsScalarUse(I, Indvar);
2668 };
2669
2670 // Determine if all users of the induction variable are scalar after
2671 // vectorization.
2672 bool ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
2673 auto *I = cast<Instruction>(U);
2674 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2675 IsDirectLoadStoreFromPtrIndvar(Ind, I);
2676 });
2677 if (!ScalarInd)
2678 continue;
2679
2680 // If the induction variable update is a fixed-order recurrence, neither the
2681 // induction variable or its update should be marked scalar after
2682 // vectorization.
2683 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
2684 if (IndUpdatePhi && Legal->isFixedOrderRecurrence(IndUpdatePhi))
2685 continue;
2686
2687 // Determine if all users of the induction variable update instruction are
2688 // scalar after vectorization.
2689 bool ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2690 auto *I = cast<Instruction>(U);
2691 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
2692 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
2693 });
2694 if (!ScalarIndUpdate)
2695 continue;
2696
2697 // The induction variable and its update instruction will remain scalar.
2698 Worklist.insert(Ind);
2699 Worklist.insert(IndUpdate);
2700 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
2701 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
2702 << "\n");
2703 }
2704
2705 Scalars[VF].insert_range(Worklist);
2706}
2707
2709 ElementCount VF) {
2710 if (!isPredicatedInst(I))
2711 return false;
2712
2713 // Do we have a non-scalar lowering for this predicated
2714 // instruction? No - it is scalar with predication.
2715 switch(I->getOpcode()) {
2716 default:
2717 return true;
2718 case Instruction::Call:
2719 if (VF.isScalar())
2720 return true;
2722 case Instruction::Load:
2723 case Instruction::Store: {
2724 auto *Ptr = getLoadStorePointerOperand(I);
2725 auto *Ty = getLoadStoreType(I);
2726 unsigned AS = getLoadStoreAddressSpace(I);
2727 Type *VTy = Ty;
2728 if (VF.isVector())
2729 VTy = VectorType::get(Ty, VF);
2730 const Align Alignment = getLoadStoreAlignment(I);
2731 return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment, AS) ||
2732 TTI.isLegalMaskedGather(VTy, Alignment))
2733 : !(isLegalMaskedStore(Ty, Ptr, Alignment, AS) ||
2734 TTI.isLegalMaskedScatter(VTy, Alignment));
2735 }
2736 case Instruction::UDiv:
2737 case Instruction::SDiv:
2738 case Instruction::SRem:
2739 case Instruction::URem: {
2740 // We have the option to use the safe-divisor idiom to avoid predication.
2741 // The cost based decision here will always select safe-divisor for
2742 // scalable vectors as scalarization isn't legal.
2743 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
2744 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost);
2745 }
2746 }
2747}
2748
2750 return Legal->isMaskRequired(I, foldTailByMasking());
2751}
2752
2753// TODO: Fold into LoopVectorizationLegality::isMaskRequired.
2755 // TODO: We can use the loop-preheader as context point here and get
2756 // context sensitive reasoning for isSafeToSpeculativelyExecute.
2760 return false;
2761
2762 // If the instruction was executed conditionally in the original scalar loop,
2763 // predication is needed with a mask whose lanes are all possibly inactive.
2764 if (Legal->blockNeedsPredication(I->getParent()))
2765 return true;
2766
2767 // If we're not folding the tail by masking, predication is unnecessary.
2768 if (!foldTailByMasking())
2769 return false;
2770
2771 // All that remain are instructions with side-effects originally executed in
2772 // the loop unconditionally, but now execute under a tail-fold mask (only)
2773 // having at least one active lane (the first). If the side-effects of the
2774 // instruction are invariant, executing it w/o (the tail-folding) mask is safe
2775 // - it will cause the same side-effects as when masked.
2776 switch(I->getOpcode()) {
2777 default:
2779 "instruction should have been considered by earlier checks");
2780 case Instruction::Call:
2781 // Side-effects of a Call are assumed to be non-invariant, needing a
2782 // (fold-tail) mask.
2784 "should have returned earlier for calls not needing a mask");
2785 return true;
2786 case Instruction::Load:
2787 // If the address is loop invariant no predication is needed.
2788 return !Legal->isInvariant(getLoadStorePointerOperand(I));
2789 case Instruction::Store: {
2790 // For stores, we need to prove both speculation safety (which follows from
2791 // the same argument as loads), but also must prove the value being stored
2792 // is correct. The easiest form of the later is to require that all values
2793 // stored are the same.
2794 return !(Legal->isInvariant(getLoadStorePointerOperand(I)) &&
2795 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()));
2796 }
2797 case Instruction::UDiv:
2798 case Instruction::URem:
2799 // If the divisor is loop-invariant no predication is needed.
2800 return !Legal->isInvariant(I->getOperand(1));
2801 case Instruction::SDiv:
2802 case Instruction::SRem:
2803 // Conservative for now, since masked-off lanes may be poison and could
2804 // trigger signed overflow.
2805 return true;
2806 }
2807}
2808
2812 return 1;
2813 // If the block wasn't originally predicated then return early to avoid
2814 // computing BlockFrequencyInfo unnecessarily.
2815 if (!Legal->blockNeedsPredication(BB))
2816 return 1;
2817
2818 uint64_t HeaderFreq =
2819 getBFI().getBlockFreq(TheLoop->getHeader()).getFrequency();
2820 uint64_t BBFreq = getBFI().getBlockFreq(BB).getFrequency();
2821 assert(HeaderFreq >= BBFreq &&
2822 "Header has smaller block freq than dominated BB?");
2823 return std::round((double)HeaderFreq / BBFreq);
2824}
2825
2826std::pair<InstructionCost, InstructionCost>
2828 ElementCount VF) {
2829 assert(I->getOpcode() == Instruction::UDiv ||
2830 I->getOpcode() == Instruction::SDiv ||
2831 I->getOpcode() == Instruction::SRem ||
2832 I->getOpcode() == Instruction::URem);
2834
2835 // Scalarization isn't legal for scalable vector types
2836 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2837 if (!VF.isScalable()) {
2838 // Get the scalarization cost and scale this amount by the probability of
2839 // executing the predicated block. If the instruction is not predicated,
2840 // we fall through to the next case.
2841 ScalarizationCost = 0;
2842
2843 // These instructions have a non-void type, so account for the phi nodes
2844 // that we will create. This cost is likely to be zero. The phi node
2845 // cost, if any, should be scaled by the block probability because it
2846 // models a copy at the end of each predicated block.
2847 ScalarizationCost +=
2848 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
2849
2850 // The cost of the non-predicated instruction.
2851 ScalarizationCost +=
2852 VF.getFixedValue() *
2853 TTI.getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind);
2854
2855 // The cost of insertelement and extractelement instructions needed for
2856 // scalarization.
2857 ScalarizationCost += getScalarizationOverhead(I, VF);
2858
2859 // Scale the cost by the probability of executing the predicated blocks.
2860 // This assumes the predicated block for each vector lane is equally
2861 // likely.
2862 ScalarizationCost =
2863 ScalarizationCost / getPredBlockCostDivisor(CostKind, I->getParent());
2864 }
2865
2866 InstructionCost SafeDivisorCost = 0;
2867 auto *VecTy = toVectorTy(I->getType(), VF);
2868 // The cost of the select guard to ensure all lanes are well defined
2869 // after we speculate above any internal control flow.
2870 SafeDivisorCost +=
2871 TTI.getCmpSelInstrCost(Instruction::Select, VecTy,
2872 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
2874
2875 SmallVector<const Value *, 4> Operands(I->operand_values());
2876 SafeDivisorCost += TTI.getArithmeticInstrCost(
2877 I->getOpcode(), VecTy, CostKind,
2878 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
2879 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
2880 Operands, I);
2881 return {ScalarizationCost, SafeDivisorCost};
2882}
2883
2885 Instruction *I, ElementCount VF) const {
2886 assert(isAccessInterleaved(I) && "Expecting interleaved access.");
2888 "Decision should not be set yet.");
2889 auto *Group = getInterleavedAccessGroup(I);
2890 assert(Group && "Must have a group.");
2891 unsigned InterleaveFactor = Group->getFactor();
2892
2893 // If the instruction's allocated size doesn't equal its type size, it
2894 // requires padding and will be scalarized.
2895 auto &DL = I->getDataLayout();
2896 auto *ScalarTy = getLoadStoreType(I);
2897 if (hasIrregularType(ScalarTy, DL))
2898 return false;
2899
2900 // For scalable vectors, the interleave factors must be <= 8 since we require
2901 // the (de)interleaveN intrinsics instead of shufflevectors.
2902 if (VF.isScalable() && InterleaveFactor > 8)
2903 return false;
2904
2905 // If the group involves a non-integral pointer, we may not be able to
2906 // losslessly cast all values to a common type.
2907 bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
2908 for (unsigned Idx = 0; Idx < InterleaveFactor; Idx++) {
2909 Instruction *Member = Group->getMember(Idx);
2910 if (!Member)
2911 continue;
2912 auto *MemberTy = getLoadStoreType(Member);
2913 bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
2914 // Don't coerce non-integral pointers to integers or vice versa.
2915 if (MemberNI != ScalarNI)
2916 // TODO: Consider adding special nullptr value case here
2917 return false;
2918 if (MemberNI && ScalarNI &&
2919 ScalarTy->getPointerAddressSpace() !=
2920 MemberTy->getPointerAddressSpace())
2921 return false;
2922 }
2923
2924 // Check if masking is required.
2925 // A Group may need masking for one of two reasons: it resides in a block that
2926 // needs predication, or it was decided to use masking to deal with gaps
2927 // (either a gap at the end of a load-access that may result in a speculative
2928 // load, or any gaps in a store-access).
2929 bool PredicatedAccessRequiresMasking =
2931 bool LoadAccessWithGapsRequiresEpilogMasking =
2932 isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
2934 bool StoreAccessWithGapsRequiresMasking =
2935 isa<StoreInst>(I) && !Group->isFull();
2936 if (!PredicatedAccessRequiresMasking &&
2937 !LoadAccessWithGapsRequiresEpilogMasking &&
2938 !StoreAccessWithGapsRequiresMasking)
2939 return true;
2940
2941 // If masked interleaving is required, we expect that the user/target had
2942 // enabled it, because otherwise it either wouldn't have been created or
2943 // it should have been invalidated by the CostModel.
2945 "Masked interleave-groups for predicated accesses are not enabled.");
2946
2947 if (Group->isReverse())
2948 return false;
2949
2950 // TODO: Support interleaved access that requires a gap mask for scalable VFs.
2951 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
2952 StoreAccessWithGapsRequiresMasking;
2953 if (VF.isScalable() && NeedsMaskForGaps)
2954 return false;
2955
2956 auto *Ty = getLoadStoreType(I);
2957 const Align Alignment = getLoadStoreAlignment(I);
2958 unsigned AS = getLoadStoreAddressSpace(I);
2959 return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment, AS)
2960 : TTI.isLegalMaskedStore(Ty, Alignment, AS);
2961}
2962
2964 Instruction *I, ElementCount VF) {
2965 // Get and ensure we have a valid memory instruction.
2966 assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
2967
2968 auto *Ptr = getLoadStorePointerOperand(I);
2969 auto *ScalarTy = getLoadStoreType(I);
2970
2971 // In order to be widened, the pointer should be consecutive, first of all.
2972 if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
2973 return false;
2974
2975 // If the instruction is a store located in a predicated block, it will be
2976 // scalarized.
2977 if (isScalarWithPredication(I, VF))
2978 return false;
2979
2980 // If the instruction's allocated size doesn't equal it's type size, it
2981 // requires padding and will be scalarized.
2982 auto &DL = I->getDataLayout();
2983 if (hasIrregularType(ScalarTy, DL))
2984 return false;
2985
2986 return true;
2987}
2988
2989void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
2990 // We should not collect Uniforms more than once per VF. Right now,
2991 // this function is called from collectUniformsAndScalars(), which
2992 // already does this check. Collecting Uniforms for VF=1 does not make any
2993 // sense.
2994
2995 assert(VF.isVector() && !Uniforms.contains(VF) &&
2996 "This function should not be visited twice for the same VF");
2997
2998 // Visit the list of Uniforms. If we find no uniform value, we won't
2999 // analyze again. Uniforms.count(VF) will return 1.
3000 Uniforms[VF].clear();
3001
3002 // Now we know that the loop is vectorizable!
3003 // Collect instructions inside the loop that will remain uniform after
3004 // vectorization.
3005
3006 // Global values, params and instructions outside of current loop are out of
3007 // scope.
3008 auto IsOutOfScope = [&](Value *V) -> bool {
3010 return (!I || !TheLoop->contains(I));
3011 };
3012
3013 // Worklist containing uniform instructions demanding lane 0.
3014 SetVector<Instruction *> Worklist;
3015
3016 // Add uniform instructions demanding lane 0 to the worklist. Instructions
3017 // that require predication must not be considered uniform after
3018 // vectorization, because that would create an erroneous replicating region
3019 // where only a single instance out of VF should be formed.
3020 auto AddToWorklistIfAllowed = [&](Instruction *I) -> void {
3021 if (IsOutOfScope(I)) {
3022 LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
3023 << *I << "\n");
3024 return;
3025 }
3026 if (isPredicatedInst(I)) {
3027 LLVM_DEBUG(
3028 dbgs() << "LV: Found not uniform due to requiring predication: " << *I
3029 << "\n");
3030 return;
3031 }
3032 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
3033 Worklist.insert(I);
3034 };
3035
3036 // Start with the conditional branches exiting the loop. If the branch
3037 // condition is an instruction contained in the loop that is only used by the
3038 // branch, it is uniform. Note conditions from uncountable early exits are not
3039 // uniform.
3041 TheLoop->getExitingBlocks(Exiting);
3042 for (BasicBlock *E : Exiting) {
3043 if (Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() != E)
3044 continue;
3045 auto *Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
3046 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
3047 AddToWorklistIfAllowed(Cmp);
3048 }
3049
3050 auto PrevVF = VF.divideCoefficientBy(2);
3051 // Return true if all lanes perform the same memory operation, and we can
3052 // thus choose to execute only one.
3053 auto IsUniformMemOpUse = [&](Instruction *I) {
3054 // If the value was already known to not be uniform for the previous
3055 // (smaller VF), it cannot be uniform for the larger VF.
3056 if (PrevVF.isVector()) {
3057 auto Iter = Uniforms.find(PrevVF);
3058 if (Iter != Uniforms.end() && !Iter->second.contains(I))
3059 return false;
3060 }
3061 if (!Legal->isUniformMemOp(*I, VF))
3062 return false;
3063 if (isa<LoadInst>(I))
3064 // Loading the same address always produces the same result - at least
3065 // assuming aliasing and ordering which have already been checked.
3066 return true;
3067 // Storing the same value on every iteration.
3068 return TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand());
3069 };
3070
3071 auto IsUniformDecision = [&](Instruction *I, ElementCount VF) {
3072 InstWidening WideningDecision = getWideningDecision(I, VF);
3073 assert(WideningDecision != CM_Unknown &&
3074 "Widening decision should be ready at this moment");
3075
3076 if (IsUniformMemOpUse(I))
3077 return true;
3078
3079 return (WideningDecision == CM_Widen ||
3080 WideningDecision == CM_Widen_Reverse ||
3081 WideningDecision == CM_Interleave);
3082 };
3083
3084 // Returns true if Ptr is the pointer operand of a memory access instruction
3085 // I, I is known to not require scalarization, and the pointer is not also
3086 // stored.
3087 auto IsVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
3088 if (isa<StoreInst>(I) && I->getOperand(0) == Ptr)
3089 return false;
3090 return getLoadStorePointerOperand(I) == Ptr &&
3091 (IsUniformDecision(I, VF) || Legal->isInvariant(Ptr));
3092 };
3093
3094 // Holds a list of values which are known to have at least one uniform use.
3095 // Note that there may be other uses which aren't uniform. A "uniform use"
3096 // here is something which only demands lane 0 of the unrolled iterations;
3097 // it does not imply that all lanes produce the same value (e.g. this is not
3098 // the usual meaning of uniform)
3099 SetVector<Value *> HasUniformUse;
3100
3101 // Scan the loop for instructions which are either a) known to have only
3102 // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
3103 for (auto *BB : TheLoop->blocks())
3104 for (auto &I : *BB) {
3105 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
3106 switch (II->getIntrinsicID()) {
3107 case Intrinsic::sideeffect:
3108 case Intrinsic::experimental_noalias_scope_decl:
3109 case Intrinsic::assume:
3110 case Intrinsic::lifetime_start:
3111 case Intrinsic::lifetime_end:
3112 if (TheLoop->hasLoopInvariantOperands(&I))
3113 AddToWorklistIfAllowed(&I);
3114 break;
3115 default:
3116 break;
3117 }
3118 }
3119
3120 if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
3121 if (IsOutOfScope(EVI->getAggregateOperand())) {
3122 AddToWorklistIfAllowed(EVI);
3123 continue;
3124 }
3125 // Only ExtractValue instructions where the aggregate value comes from a
3126 // call are allowed to be non-uniform.
3127 assert(isa<CallInst>(EVI->getAggregateOperand()) &&
3128 "Expected aggregate value to be call return value");
3129 }
3130
3131 // If there's no pointer operand, there's nothing to do.
3132 auto *Ptr = getLoadStorePointerOperand(&I);
3133 if (!Ptr)
3134 continue;
3135
3136 // If the pointer can be proven to be uniform, always add it to the
3137 // worklist.
3138 if (isa<Instruction>(Ptr) && Legal->isUniform(Ptr, VF))
3139 AddToWorklistIfAllowed(cast<Instruction>(Ptr));
3140
3141 if (IsUniformMemOpUse(&I))
3142 AddToWorklistIfAllowed(&I);
3143
3144 if (IsVectorizedMemAccessUse(&I, Ptr))
3145 HasUniformUse.insert(Ptr);
3146 }
3147
3148 // Add to the worklist any operands which have *only* uniform (e.g. lane 0
3149 // demanding) users. Since loops are assumed to be in LCSSA form, this
3150 // disallows uses outside the loop as well.
3151 for (auto *V : HasUniformUse) {
3152 if (IsOutOfScope(V))
3153 continue;
3154 auto *I = cast<Instruction>(V);
3155 bool UsersAreMemAccesses = all_of(I->users(), [&](User *U) -> bool {
3156 auto *UI = cast<Instruction>(U);
3157 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
3158 });
3159 if (UsersAreMemAccesses)
3160 AddToWorklistIfAllowed(I);
3161 }
3162
3163 // Expand Worklist in topological order: whenever a new instruction
3164 // is added , its users should be already inside Worklist. It ensures
3165 // a uniform instruction will only be used by uniform instructions.
3166 unsigned Idx = 0;
3167 while (Idx != Worklist.size()) {
3168 Instruction *I = Worklist[Idx++];
3169
3170 for (auto *OV : I->operand_values()) {
3171 // isOutOfScope operands cannot be uniform instructions.
3172 if (IsOutOfScope(OV))
3173 continue;
3174 // First order recurrence Phi's should typically be considered
3175 // non-uniform.
3176 auto *OP = dyn_cast<PHINode>(OV);
3177 if (OP && Legal->isFixedOrderRecurrence(OP))
3178 continue;
3179 // If all the users of the operand are uniform, then add the
3180 // operand into the uniform worklist.
3181 auto *OI = cast<Instruction>(OV);
3182 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
3183 auto *J = cast<Instruction>(U);
3184 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
3185 }))
3186 AddToWorklistIfAllowed(OI);
3187 }
3188 }
3189
3190 // For an instruction to be added into Worklist above, all its users inside
3191 // the loop should also be in Worklist. However, this condition cannot be
3192 // true for phi nodes that form a cyclic dependence. We must process phi
3193 // nodes separately. An induction variable will remain uniform if all users
3194 // of the induction variable and induction variable update remain uniform.
3195 // The code below handles both pointer and non-pointer induction variables.
3196 BasicBlock *Latch = TheLoop->getLoopLatch();
3197 for (const auto &Induction : Legal->getInductionVars()) {
3198 auto *Ind = Induction.first;
3199 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
3200
3201 // Determine if all users of the induction variable are uniform after
3202 // vectorization.
3203 bool UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
3204 auto *I = cast<Instruction>(U);
3205 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
3206 IsVectorizedMemAccessUse(I, Ind);
3207 });
3208 if (!UniformInd)
3209 continue;
3210
3211 // Determine if all users of the induction variable update instruction are
3212 // uniform after vectorization.
3213 bool UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
3214 auto *I = cast<Instruction>(U);
3215 return I == Ind || Worklist.count(I) ||
3216 IsVectorizedMemAccessUse(I, IndUpdate);
3217 });
3218 if (!UniformIndUpdate)
3219 continue;
3220
3221 // The induction variable and its update instruction will remain uniform.
3222 AddToWorklistIfAllowed(Ind);
3223 AddToWorklistIfAllowed(IndUpdate);
3224 }
3225
3226 Uniforms[VF].insert_range(Worklist);
3227}
3228
3230 LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
3231
3232 if (Legal->getRuntimePointerChecking()->Need) {
3233 reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
3234 "runtime pointer checks needed. Enable vectorization of this "
3235 "loop with '#pragma clang loop vectorize(enable)' when "
3236 "compiling with -Os/-Oz",
3237 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3238 return true;
3239 }
3240
3241 if (!PSE.getPredicate().isAlwaysTrue()) {
3242 reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
3243 "runtime SCEV checks needed. Enable vectorization of this "
3244 "loop with '#pragma clang loop vectorize(enable)' when "
3245 "compiling with -Os/-Oz",
3246 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3247 return true;
3248 }
3249
3250 // FIXME: Avoid specializing for stride==1 instead of bailing out.
3251 if (!Legal->getLAI()->getSymbolicStrides().empty()) {
3252 reportVectorizationFailure("Runtime stride check for small trip count",
3253 "runtime stride == 1 checks needed. Enable vectorization of "
3254 "this loop without such check by compiling with -Os/-Oz",
3255 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3256 return true;
3257 }
3258
3259 return false;
3260}
3261
3262bool LoopVectorizationCostModel::isScalableVectorizationAllowed() {
3263 if (IsScalableVectorizationAllowed)
3264 return *IsScalableVectorizationAllowed;
3265
3266 IsScalableVectorizationAllowed = false;
3267 if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
3268 return false;
3269
3270 if (Hints->isScalableVectorizationDisabled()) {
3271 reportVectorizationInfo("Scalable vectorization is explicitly disabled",
3272 "ScalableVectorizationDisabled", ORE, TheLoop);
3273 return false;
3274 }
3275
3276 LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
3277
3278 auto MaxScalableVF = ElementCount::getScalable(
3279 std::numeric_limits<ElementCount::ScalarTy>::max());
3280
3281 // Test that the loop-vectorizer can legalize all operations for this MaxVF.
3282 // FIXME: While for scalable vectors this is currently sufficient, this should
3283 // be replaced by a more detailed mechanism that filters out specific VFs,
3284 // instead of invalidating vectorization for a whole set of VFs based on the
3285 // MaxVF.
3286
3287 // Disable scalable vectorization if the loop contains unsupported reductions.
3288 if (!canVectorizeReductions(MaxScalableVF)) {
3290 "Scalable vectorization not supported for the reduction "
3291 "operations found in this loop.",
3292 "ScalableVFUnfeasible", ORE, TheLoop);
3293 return false;
3294 }
3295
3296 // Disable scalable vectorization if the loop contains any instructions
3297 // with element types not supported for scalable vectors.
3298 if (any_of(ElementTypesInLoop, [&](Type *Ty) {
3299 return !Ty->isVoidTy() &&
3301 })) {
3302 reportVectorizationInfo("Scalable vectorization is not supported "
3303 "for all element types found in this loop.",
3304 "ScalableVFUnfeasible", ORE, TheLoop);
3305 return false;
3306 }
3307
3308 if (!Legal->isSafeForAnyVectorWidth() && !getMaxVScale(*TheFunction, TTI)) {
3309 reportVectorizationInfo("The target does not provide maximum vscale value "
3310 "for safe distance analysis.",
3311 "ScalableVFUnfeasible", ORE, TheLoop);
3312 return false;
3313 }
3314
3315 IsScalableVectorizationAllowed = true;
3316 return true;
3317}
3318
3319ElementCount
3320LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
3321 if (!isScalableVectorizationAllowed())
3322 return ElementCount::getScalable(0);
3323
3324 auto MaxScalableVF = ElementCount::getScalable(
3325 std::numeric_limits<ElementCount::ScalarTy>::max());
3326 if (Legal->isSafeForAnyVectorWidth())
3327 return MaxScalableVF;
3328
3329 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3330 // Limit MaxScalableVF by the maximum safe dependence distance.
3331 MaxScalableVF = ElementCount::getScalable(MaxSafeElements / *MaxVScale);
3332
3333 if (!MaxScalableVF)
3335 "Max legal vector width too small, scalable vectorization "
3336 "unfeasible.",
3337 "ScalableVFUnfeasible", ORE, TheLoop);
3338
3339 return MaxScalableVF;
3340}
3341
3342FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
3343 unsigned MaxTripCount, ElementCount UserVF, unsigned UserIC,
3344 bool FoldTailByMasking) {
3345 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
3346 unsigned SmallestType, WidestType;
3347 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
3348
3349 // Get the maximum safe dependence distance in bits computed by LAA.
3350 // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
3351 // the memory accesses that is most restrictive (involved in the smallest
3352 // dependence distance).
3353 unsigned MaxSafeElementsPowerOf2 =
3354 bit_floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
3355 if (!Legal->isSafeForAnyStoreLoadForwardDistances()) {
3356 unsigned SLDist = Legal->getMaxStoreLoadForwardSafeDistanceInBits();
3357 MaxSafeElementsPowerOf2 =
3358 std::min(MaxSafeElementsPowerOf2, SLDist / WidestType);
3359 }
3360 auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElementsPowerOf2);
3361 auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElementsPowerOf2);
3362
3363 if (!Legal->isSafeForAnyVectorWidth())
3364 this->MaxSafeElements = MaxSafeElementsPowerOf2;
3365
3366 LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
3367 << ".\n");
3368 LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
3369 << ".\n");
3370
3371 // First analyze the UserVF, fall back if the UserVF should be ignored.
3372 if (UserVF) {
3373 auto MaxSafeUserVF =
3374 UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
3375
3376 if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
3377 // If `VF=vscale x N` is safe, then so is `VF=N`
3378 if (UserVF.isScalable())
3379 return FixedScalableVFPair(
3380 ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
3381
3382 return UserVF;
3383 }
3384
3385 assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
3386
3387 // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
3388 // is better to ignore the hint and let the compiler choose a suitable VF.
3389 if (!UserVF.isScalable()) {
3390 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3391 << " is unsafe, clamping to max safe VF="
3392 << MaxSafeFixedVF << ".\n");
3393 ORE->emit([&]() {
3394 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3395 TheLoop->getStartLoc(),
3396 TheLoop->getHeader())
3397 << "User-specified vectorization factor "
3398 << ore::NV("UserVectorizationFactor", UserVF)
3399 << " is unsafe, clamping to maximum safe vectorization factor "
3400 << ore::NV("VectorizationFactor", MaxSafeFixedVF);
3401 });
3402 return MaxSafeFixedVF;
3403 }
3404
3406 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3407 << " is ignored because scalable vectors are not "
3408 "available.\n");
3409 ORE->emit([&]() {
3410 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3411 TheLoop->getStartLoc(),
3412 TheLoop->getHeader())
3413 << "User-specified vectorization factor "
3414 << ore::NV("UserVectorizationFactor", UserVF)
3415 << " is ignored because the target does not support scalable "
3416 "vectors. The compiler will pick a more suitable value.";
3417 });
3418 } else {
3419 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3420 << " is unsafe. Ignoring scalable UserVF.\n");
3421 ORE->emit([&]() {
3422 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3423 TheLoop->getStartLoc(),
3424 TheLoop->getHeader())
3425 << "User-specified vectorization factor "
3426 << ore::NV("UserVectorizationFactor", UserVF)
3427 << " is unsafe. Ignoring the hint to let the compiler pick a "
3428 "more suitable value.";
3429 });
3430 }
3431 }
3432
3433 LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
3434 << " / " << WidestType << " bits.\n");
3435
3436 FixedScalableVFPair Result(ElementCount::getFixed(1),
3438 if (auto MaxVF =
3439 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3440 MaxSafeFixedVF, UserIC, FoldTailByMasking))
3441 Result.FixedVF = MaxVF;
3442
3443 if (auto MaxVF =
3444 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3445 MaxSafeScalableVF, UserIC, FoldTailByMasking))
3446 if (MaxVF.isScalable()) {
3447 Result.ScalableVF = MaxVF;
3448 LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
3449 << "\n");
3450 }
3451
3452 return Result;
3453}
3454
3455FixedScalableVFPair
3457 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
3458 // TODO: It may be useful to do since it's still likely to be dynamically
3459 // uniform if the target can skip.
3461 "Not inserting runtime ptr check for divergent target",
3462 "runtime pointer checks needed. Not enabled for divergent target",
3463 "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
3465 }
3466
3467 ScalarEvolution *SE = PSE.getSE();
3469 unsigned MaxTC = PSE.getSmallConstantMaxTripCount();
3470 if (!MaxTC && ScalarEpilogueStatus == CM_ScalarEpilogueAllowed)
3472 LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
3473 if (TC != ElementCount::getFixed(MaxTC))
3474 LLVM_DEBUG(dbgs() << "LV: Found maximum trip count: " << MaxTC << '\n');
3475 if (TC.isScalar()) {
3476 reportVectorizationFailure("Single iteration (non) loop",
3477 "loop trip count is one, irrelevant for vectorization",
3478 "SingleIterationLoop", ORE, TheLoop);
3480 }
3481
3482 // If BTC matches the widest induction type and is -1 then the trip count
3483 // computation will wrap to 0 and the vector trip count will be 0. Do not try
3484 // to vectorize.
3485 const SCEV *BTC = SE->getBackedgeTakenCount(TheLoop);
3486 if (!isa<SCEVCouldNotCompute>(BTC) &&
3487 BTC->getType()->getScalarSizeInBits() >=
3488 Legal->getWidestInductionType()->getScalarSizeInBits() &&
3490 SE->getMinusOne(BTC->getType()))) {
3492 "Trip count computation wrapped",
3493 "backedge-taken count is -1, loop trip count wrapped to 0",
3494 "TripCountWrapped", ORE, TheLoop);
3496 }
3497
3498 switch (ScalarEpilogueStatus) {
3500 return computeFeasibleMaxVF(MaxTC, UserVF, UserIC, false);
3502 [[fallthrough]];
3504 LLVM_DEBUG(
3505 dbgs() << "LV: vector predicate hint/switch found.\n"
3506 << "LV: Not allowing scalar epilogue, creating predicated "
3507 << "vector loop.\n");
3508 break;
3510 // fallthrough as a special case of OptForSize
3512 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
3513 LLVM_DEBUG(
3514 dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
3515 else
3516 LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
3517 << "count.\n");
3518
3519 // Bail if runtime checks are required, which are not good when optimising
3520 // for size.
3523
3524 break;
3525 }
3526
3527 // Now try the tail folding
3528
3529 // Invalidate interleave groups that require an epilogue if we can't mask
3530 // the interleave-group.
3532 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
3533 "No decisions should have been taken at this point");
3534 // Note: There is no need to invalidate any cost modeling decisions here, as
3535 // none were taken so far.
3536 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
3537 }
3538
3539 FixedScalableVFPair MaxFactors =
3540 computeFeasibleMaxVF(MaxTC, UserVF, UserIC, true);
3541
3542 // Avoid tail folding if the trip count is known to be a multiple of any VF
3543 // we choose.
3544 std::optional<unsigned> MaxPowerOf2RuntimeVF =
3545 MaxFactors.FixedVF.getFixedValue();
3546 if (MaxFactors.ScalableVF) {
3547 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3548 if (MaxVScale) {
3549 MaxPowerOf2RuntimeVF = std::max<unsigned>(
3550 *MaxPowerOf2RuntimeVF,
3551 *MaxVScale * MaxFactors.ScalableVF.getKnownMinValue());
3552 } else
3553 MaxPowerOf2RuntimeVF = std::nullopt; // Stick with tail-folding for now.
3554 }
3555
3556 auto NoScalarEpilogueNeeded = [this, &UserIC](unsigned MaxVF) {
3557 // Return false if the loop is neither a single-latch-exit loop nor an
3558 // early-exit loop as tail-folding is not supported in that case.
3559 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
3560 !Legal->hasUncountableEarlyExit())
3561 return false;
3562 unsigned MaxVFtimesIC = UserIC ? MaxVF * UserIC : MaxVF;
3563 ScalarEvolution *SE = PSE.getSE();
3564 // Calling getSymbolicMaxBackedgeTakenCount enables support for loops
3565 // with uncountable exits. For countable loops, the symbolic maximum must
3566 // remain identical to the known back-edge taken count.
3567 const SCEV *BackedgeTakenCount = PSE.getSymbolicMaxBackedgeTakenCount();
3568 assert((Legal->hasUncountableEarlyExit() ||
3569 BackedgeTakenCount == PSE.getBackedgeTakenCount()) &&
3570 "Invalid loop count");
3571 const SCEV *ExitCount = SE->getAddExpr(
3572 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3573 const SCEV *Rem = SE->getURemExpr(
3574 SE->applyLoopGuards(ExitCount, TheLoop),
3575 SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
3576 return Rem->isZero();
3577 };
3578
3579 if (MaxPowerOf2RuntimeVF > 0u) {
3580 assert((UserVF.isNonZero() || isPowerOf2_32(*MaxPowerOf2RuntimeVF)) &&
3581 "MaxFixedVF must be a power of 2");
3582 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
3583 // Accept MaxFixedVF if we do not have a tail.
3584 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
3585 return MaxFactors;
3586 }
3587 }
3588
3589 auto ExpectedTC = getSmallBestKnownTC(PSE, TheLoop);
3590 if (ExpectedTC && ExpectedTC->isFixed() &&
3591 ExpectedTC->getFixedValue() <=
3592 TTI.getMinTripCountTailFoldingThreshold()) {
3593 if (MaxPowerOf2RuntimeVF > 0u) {
3594 // If we have a low-trip-count, and the fixed-width VF is known to divide
3595 // the trip count but the scalable factor does not, use the fixed-width
3596 // factor in preference to allow the generation of a non-predicated loop.
3597 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedLowTripLoop &&
3598 NoScalarEpilogueNeeded(MaxFactors.FixedVF.getFixedValue())) {
3599 LLVM_DEBUG(dbgs() << "LV: Picking a fixed-width so that no tail will "
3600 "remain for any chosen VF.\n");
3601 MaxFactors.ScalableVF = ElementCount::getScalable(0);
3602 return MaxFactors;
3603 }
3604 }
3605
3607 "The trip count is below the minial threshold value.",
3608 "loop trip count is too low, avoiding vectorization", "LowTripCount",
3609 ORE, TheLoop);
3611 }
3612
3613 // If we don't know the precise trip count, or if the trip count that we
3614 // found modulo the vectorization factor is not zero, try to fold the tail
3615 // by masking.
3616 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
3617 bool ContainsScalableVF = MaxFactors.ScalableVF.isNonZero();
3618 setTailFoldingStyle(ContainsScalableVF, UserIC);
3619 if (foldTailByMasking()) {
3620 if (foldTailWithEVL()) {
3621 LLVM_DEBUG(
3622 dbgs()
3623 << "LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
3624 "try to generate VP Intrinsics with scalable vector "
3625 "factors only.\n");
3626 // Tail folded loop using VP intrinsics restricts the VF to be scalable
3627 // for now.
3628 // TODO: extend it for fixed vectors, if required.
3629 assert(ContainsScalableVF && "Expected scalable vector factor.");
3630
3631 MaxFactors.FixedVF = ElementCount::getFixed(1);
3632 }
3633 return MaxFactors;
3634 }
3635
3636 // If there was a tail-folding hint/switch, but we can't fold the tail by
3637 // masking, fallback to a vectorization with a scalar epilogue.
3638 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
3639 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
3640 "scalar epilogue instead.\n");
3641 ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
3642 return MaxFactors;
3643 }
3644
3645 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
3646 LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
3648 }
3649
3650 if (TC.isZero()) {
3652 "unable to calculate the loop count due to complex control flow",
3653 "UnknownLoopCountComplexCFG", ORE, TheLoop);
3655 }
3656
3658 "Cannot optimize for size and vectorize at the same time.",
3659 "cannot optimize for size and vectorize at the same time. "
3660 "Enable vectorization of this loop with '#pragma clang loop "
3661 "vectorize(enable)' when compiling with -Os/-Oz",
3662 "NoTailLoopWithOptForSize", ORE, TheLoop);
3664}
3665
3667 ElementCount VF) {
3668 if (ConsiderRegPressure.getNumOccurrences())
3669 return ConsiderRegPressure;
3670
3671 // TODO: We should eventually consider register pressure for all targets. The
3672 // TTI hook is temporary whilst target-specific issues are being fixed.
3673 if (TTI.shouldConsiderVectorizationRegPressure())
3674 return true;
3675
3676 if (!useMaxBandwidth(VF.isScalable()
3679 return false;
3680 // Only calculate register pressure for VFs enabled by MaxBandwidth.
3682 VF, VF.isScalable() ? MaxPermissibleVFWithoutMaxBW.ScalableVF
3684}
3685
3688 return MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
3689 (TTI.shouldMaximizeVectorBandwidth(RegKind) ||
3691 Legal->hasVectorCallVariants())));
3692}
3693
3694ElementCount LoopVectorizationCostModel::clampVFByMaxTripCount(
3695 ElementCount VF, unsigned MaxTripCount, unsigned UserIC,
3696 bool FoldTailByMasking) const {
3697 unsigned EstimatedVF = VF.getKnownMinValue();
3698 if (VF.isScalable() && TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
3699 auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
3700 auto Min = Attr.getVScaleRangeMin();
3701 EstimatedVF *= Min;
3702 }
3703
3704 // When a scalar epilogue is required, at least one iteration of the scalar
3705 // loop has to execute. Adjust MaxTripCount accordingly to avoid picking a
3706 // max VF that results in a dead vector loop.
3707 if (MaxTripCount > 0 && requiresScalarEpilogue(true))
3708 MaxTripCount -= 1;
3709
3710 // When the user specifies an interleave count, we need to ensure that
3711 // VF * UserIC <= MaxTripCount to avoid a dead vector loop.
3712 unsigned IC = UserIC > 0 ? UserIC : 1;
3713 unsigned EstimatedVFTimesIC = EstimatedVF * IC;
3714
3715 if (MaxTripCount && MaxTripCount <= EstimatedVFTimesIC &&
3716 (!FoldTailByMasking || isPowerOf2_32(MaxTripCount))) {
3717 // If upper bound loop trip count (TC) is known at compile time there is no
3718 // point in choosing VF greater than TC / IC (as done in the loop below).
3719 // Select maximum power of two which doesn't exceed TC / IC. If VF is
3720 // scalable, we only fall back on a fixed VF when the TC is less than or
3721 // equal to the known number of lanes.
3722 auto ClampedUpperTripCount = llvm::bit_floor(MaxTripCount / IC);
3723 if (ClampedUpperTripCount == 0)
3724 ClampedUpperTripCount = 1;
3725 LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
3726 "exceeding the constant trip count"
3727 << (UserIC > 0 ? " divided by UserIC" : "") << ": "
3728 << ClampedUpperTripCount << "\n");
3729 return ElementCount::get(ClampedUpperTripCount,
3730 FoldTailByMasking ? VF.isScalable() : false);
3731 }
3732 return VF;
3733}
3734
3735ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
3736 unsigned MaxTripCount, unsigned SmallestType, unsigned WidestType,
3737 ElementCount MaxSafeVF, unsigned UserIC, bool FoldTailByMasking) {
3738 bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
3739 const TypeSize WidestRegister = TTI.getRegisterBitWidth(
3740 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3742
3743 // Convenience function to return the minimum of two ElementCounts.
3744 auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
3745 assert((LHS.isScalable() == RHS.isScalable()) &&
3746 "Scalable flags must match");
3747 return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
3748 };
3749
3750 // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
3751 // Note that both WidestRegister and WidestType may not be a powers of 2.
3752 auto MaxVectorElementCount = ElementCount::get(
3753 llvm::bit_floor(WidestRegister.getKnownMinValue() / WidestType),
3754 ComputeScalableMaxVF);
3755 MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
3756 LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
3757 << (MaxVectorElementCount * WidestType) << " bits.\n");
3758
3759 if (!MaxVectorElementCount) {
3760 LLVM_DEBUG(dbgs() << "LV: The target has no "
3761 << (ComputeScalableMaxVF ? "scalable" : "fixed")
3762 << " vector registers.\n");
3763 return ElementCount::getFixed(1);
3764 }
3765
3766 ElementCount MaxVF = clampVFByMaxTripCount(
3767 MaxVectorElementCount, MaxTripCount, UserIC, FoldTailByMasking);
3768 // If the MaxVF was already clamped, there's no point in trying to pick a
3769 // larger one.
3770 if (MaxVF != MaxVectorElementCount)
3771 return MaxVF;
3772
3774 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3776
3777 if (MaxVF.isScalable())
3778 MaxPermissibleVFWithoutMaxBW.ScalableVF = MaxVF;
3779 else
3780 MaxPermissibleVFWithoutMaxBW.FixedVF = MaxVF;
3781
3782 if (useMaxBandwidth(RegKind)) {
3783 auto MaxVectorElementCountMaxBW = ElementCount::get(
3784 llvm::bit_floor(WidestRegister.getKnownMinValue() / SmallestType),
3785 ComputeScalableMaxVF);
3786 MaxVF = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
3787
3788 if (ElementCount MinVF =
3789 TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
3790 if (ElementCount::isKnownLT(MaxVF, MinVF)) {
3791 LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
3792 << ") with target's minimum: " << MinVF << '\n');
3793 MaxVF = MinVF;
3794 }
3795 }
3796
3797 MaxVF =
3798 clampVFByMaxTripCount(MaxVF, MaxTripCount, UserIC, FoldTailByMasking);
3799
3800 assert((MaxVectorElementCount == MaxVF ||
3801 (WideningDecisions.empty() && CallWideningDecisions.empty() &&
3802 Uniforms.empty() && Scalars.empty())) &&
3803 "No decisions should have been taken at this point");
3804 }
3805 return MaxVF;
3806}
3807
3808bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3809 const VectorizationFactor &B,
3810 const unsigned MaxTripCount,
3811 bool HasTail,
3812 bool IsEpilogue) const {
3813 InstructionCost CostA = A.Cost;
3814 InstructionCost CostB = B.Cost;
3815
3816 // Improve estimate for the vector width if it is scalable.
3817 unsigned EstimatedWidthA = A.Width.getKnownMinValue();
3818 unsigned EstimatedWidthB = B.Width.getKnownMinValue();
3819 if (std::optional<unsigned> VScale = CM.getVScaleForTuning()) {
3820 if (A.Width.isScalable())
3821 EstimatedWidthA *= *VScale;
3822 if (B.Width.isScalable())
3823 EstimatedWidthB *= *VScale;
3824 }
3825
3826 // When optimizing for size choose whichever is smallest, which will be the
3827 // one with the smallest cost for the whole loop. On a tie pick the larger
3828 // vector width, on the assumption that throughput will be greater.
3829 if (CM.CostKind == TTI::TCK_CodeSize)
3830 return CostA < CostB ||
3831 (CostA == CostB && EstimatedWidthA > EstimatedWidthB);
3832
3833 // Assume vscale may be larger than 1 (or the value being tuned for),
3834 // so that scalable vectorization is slightly favorable over fixed-width
3835 // vectorization.
3836 bool PreferScalable = !TTI.preferFixedOverScalableIfEqualCost(IsEpilogue) &&
3837 A.Width.isScalable() && !B.Width.isScalable();
3838
3839 auto CmpFn = [PreferScalable](const InstructionCost &LHS,
3840 const InstructionCost &RHS) {
3841 return PreferScalable ? LHS <= RHS : LHS < RHS;
3842 };
3843
3844 // To avoid the need for FP division:
3845 // (CostA / EstimatedWidthA) < (CostB / EstimatedWidthB)
3846 // <=> (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA)
3847 bool LowerCostWithoutTC =
3848 CmpFn(CostA * EstimatedWidthB, CostB * EstimatedWidthA);
3849 if (!MaxTripCount)
3850 return LowerCostWithoutTC;
3851
3852 auto GetCostForTC = [MaxTripCount, HasTail](unsigned VF,
3853 InstructionCost VectorCost,
3854 InstructionCost ScalarCost) {
3855 // If the trip count is a known (possibly small) constant, the trip count
3856 // will be rounded up to an integer number of iterations under
3857 // FoldTailByMasking. The total cost in that case will be
3858 // VecCost*ceil(TripCount/VF). When not folding the tail, the total
3859 // cost will be VecCost*floor(TC/VF) + ScalarCost*(TC%VF). There will be
3860 // some extra overheads, but for the purpose of comparing the costs of
3861 // different VFs we can use this to compare the total loop-body cost
3862 // expected after vectorization.
3863 if (HasTail)
3864 return VectorCost * (MaxTripCount / VF) +
3865 ScalarCost * (MaxTripCount % VF);
3866 return VectorCost * divideCeil(MaxTripCount, VF);
3867 };
3868
3869 auto RTCostA = GetCostForTC(EstimatedWidthA, CostA, A.ScalarCost);
3870 auto RTCostB = GetCostForTC(EstimatedWidthB, CostB, B.ScalarCost);
3871 bool LowerCostWithTC = CmpFn(RTCostA, RTCostB);
3872 LLVM_DEBUG(if (LowerCostWithTC != LowerCostWithoutTC) {
3873 dbgs() << "LV: VF " << (LowerCostWithTC ? A.Width : B.Width)
3874 << " has lower cost than VF "
3875 << (LowerCostWithTC ? B.Width : A.Width)
3876 << " when taking the cost of the remaining scalar loop iterations "
3877 "into consideration for a maximum trip count of "
3878 << MaxTripCount << ".\n";
3879 });
3880 return LowerCostWithTC;
3881}
3882
3883bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3884 const VectorizationFactor &B,
3885 bool HasTail,
3886 bool IsEpilogue) const {
3887 const unsigned MaxTripCount = PSE.getSmallConstantMaxTripCount();
3888 return LoopVectorizationPlanner::isMoreProfitable(A, B, MaxTripCount, HasTail,
3889 IsEpilogue);
3890}
3891
3894 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
3895 SmallVector<RecipeVFPair> InvalidCosts;
3896 for (const auto &Plan : VPlans) {
3897 for (ElementCount VF : Plan->vectorFactors()) {
3898 // The VPlan-based cost model is designed for computing vector cost.
3899 // Querying VPlan-based cost model with a scarlar VF will cause some
3900 // errors because we expect the VF is vector for most of the widen
3901 // recipes.
3902 if (VF.isScalar())
3903 continue;
3904
3905 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind, CM.PSE,
3906 OrigLoop);
3907 precomputeCosts(*Plan, VF, CostCtx);
3908 auto Iter = vp_depth_first_deep(Plan->getVectorLoopRegion()->getEntry());
3910 for (auto &R : *VPBB) {
3911 if (!R.cost(VF, CostCtx).isValid())
3912 InvalidCosts.emplace_back(&R, VF);
3913 }
3914 }
3915 }
3916 }
3917 if (InvalidCosts.empty())
3918 return;
3919
3920 // Emit a report of VFs with invalid costs in the loop.
3921
3922 // Group the remarks per recipe, keeping the recipe order from InvalidCosts.
3924 unsigned I = 0;
3925 for (auto &Pair : InvalidCosts)
3926 if (Numbering.try_emplace(Pair.first, I).second)
3927 ++I;
3928
3929 // Sort the list, first on recipe(number) then on VF.
3930 sort(InvalidCosts, [&Numbering](RecipeVFPair &A, RecipeVFPair &B) {
3931 unsigned NA = Numbering[A.first];
3932 unsigned NB = Numbering[B.first];
3933 if (NA != NB)
3934 return NA < NB;
3935 return ElementCount::isKnownLT(A.second, B.second);
3936 });
3937
3938 // For a list of ordered recipe-VF pairs:
3939 // [(load, VF1), (load, VF2), (store, VF1)]
3940 // group the recipes together to emit separate remarks for:
3941 // load (VF1, VF2)
3942 // store (VF1)
3943 auto Tail = ArrayRef<RecipeVFPair>(InvalidCosts);
3944 auto Subset = ArrayRef<RecipeVFPair>();
3945 do {
3946 if (Subset.empty())
3947 Subset = Tail.take_front(1);
3948
3949 VPRecipeBase *R = Subset.front().first;
3950
3951 unsigned Opcode =
3953 .Case([](const VPHeaderPHIRecipe *R) { return Instruction::PHI; })
3954 .Case(
3955 [](const VPWidenStoreRecipe *R) { return Instruction::Store; })
3956 .Case([](const VPWidenLoadRecipe *R) { return Instruction::Load; })
3957 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
3958 [](const auto *R) { return Instruction::Call; })
3961 [](const auto *R) { return R->getOpcode(); })
3962 .Case([](const VPInterleaveRecipe *R) {
3963 return R->getStoredValues().empty() ? Instruction::Load
3964 : Instruction::Store;
3965 })
3966 .Case([](const VPReductionRecipe *R) {
3967 return RecurrenceDescriptor::getOpcode(R->getRecurrenceKind());
3968 });
3969
3970 // If the next recipe is different, or if there are no other pairs,
3971 // emit a remark for the collated subset. e.g.
3972 // [(load, VF1), (load, VF2))]
3973 // to emit:
3974 // remark: invalid costs for 'load' at VF=(VF1, VF2)
3975 if (Subset == Tail || Tail[Subset.size()].first != R) {
3976 std::string OutString;
3977 raw_string_ostream OS(OutString);
3978 assert(!Subset.empty() && "Unexpected empty range");
3979 OS << "Recipe with invalid costs prevented vectorization at VF=(";
3980 for (const auto &Pair : Subset)
3981 OS << (Pair.second == Subset.front().second ? "" : ", ") << Pair.second;
3982 OS << "):";
3983 if (Opcode == Instruction::Call) {
3984 StringRef Name = "";
3985 if (auto *Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
3986 Name = Int->getIntrinsicName();
3987 } else {
3988 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
3989 Function *CalledFn =
3990 WidenCall ? WidenCall->getCalledScalarFunction()
3991 : cast<Function>(R->getOperand(R->getNumOperands() - 1)
3992 ->getLiveInIRValue());
3993 Name = CalledFn->getName();
3994 }
3995 OS << " call to " << Name;
3996 } else
3997 OS << " " << Instruction::getOpcodeName(Opcode);
3998 reportVectorizationInfo(OutString, "InvalidCost", ORE, OrigLoop, nullptr,
3999 R->getDebugLoc());
4000 Tail = Tail.drop_front(Subset.size());
4001 Subset = {};
4002 } else
4003 // Grow the subset by one element
4004 Subset = Tail.take_front(Subset.size() + 1);
4005 } while (!Tail.empty());
4006}
4007
4008/// Check if any recipe of \p Plan will generate a vector value, which will be
4009/// assigned a vector register.
4011 const TargetTransformInfo &TTI) {
4012 assert(VF.isVector() && "Checking a scalar VF?");
4013 VPTypeAnalysis TypeInfo(Plan);
4014 DenseSet<VPRecipeBase *> EphemeralRecipes;
4015 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
4016 // Set of already visited types.
4017 DenseSet<Type *> Visited;
4020 for (VPRecipeBase &R : *VPBB) {
4021 if (EphemeralRecipes.contains(&R))
4022 continue;
4023 // Continue early if the recipe is considered to not produce a vector
4024 // result. Note that this includes VPInstruction where some opcodes may
4025 // produce a vector, to preserve existing behavior as VPInstructions model
4026 // aspects not directly mapped to existing IR instructions.
4027 switch (R.getVPRecipeID()) {
4028 case VPRecipeBase::VPDerivedIVSC:
4029 case VPRecipeBase::VPScalarIVStepsSC:
4030 case VPRecipeBase::VPReplicateSC:
4031 case VPRecipeBase::VPInstructionSC:
4032 case VPRecipeBase::VPCanonicalIVPHISC:
4033 case VPRecipeBase::VPCurrentIterationPHISC:
4034 case VPRecipeBase::VPVectorPointerSC:
4035 case VPRecipeBase::VPVectorEndPointerSC:
4036 case VPRecipeBase::VPExpandSCEVSC:
4037 case VPRecipeBase::VPPredInstPHISC:
4038 case VPRecipeBase::VPBranchOnMaskSC:
4039 continue;
4040 case VPRecipeBase::VPReductionSC:
4041 case VPRecipeBase::VPActiveLaneMaskPHISC:
4042 case VPRecipeBase::VPWidenCallSC:
4043 case VPRecipeBase::VPWidenCanonicalIVSC:
4044 case VPRecipeBase::VPWidenCastSC:
4045 case VPRecipeBase::VPWidenGEPSC:
4046 case VPRecipeBase::VPWidenIntrinsicSC:
4047 case VPRecipeBase::VPWidenSC:
4048 case VPRecipeBase::VPBlendSC:
4049 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
4050 case VPRecipeBase::VPHistogramSC:
4051 case VPRecipeBase::VPWidenPHISC:
4052 case VPRecipeBase::VPWidenIntOrFpInductionSC:
4053 case VPRecipeBase::VPWidenPointerInductionSC:
4054 case VPRecipeBase::VPReductionPHISC:
4055 case VPRecipeBase::VPInterleaveEVLSC:
4056 case VPRecipeBase::VPInterleaveSC:
4057 case VPRecipeBase::VPWidenLoadEVLSC:
4058 case VPRecipeBase::VPWidenLoadSC:
4059 case VPRecipeBase::VPWidenStoreEVLSC:
4060 case VPRecipeBase::VPWidenStoreSC:
4061 break;
4062 default:
4063 llvm_unreachable("unhandled recipe");
4064 }
4065
4066 auto WillGenerateTargetVectors = [&TTI, VF](Type *VectorTy) {
4067 unsigned NumLegalParts = TTI.getNumberOfParts(VectorTy);
4068 if (!NumLegalParts)
4069 return false;
4070 if (VF.isScalable()) {
4071 // <vscale x 1 x iN> is assumed to be profitable over iN because
4072 // scalable registers are a distinct register class from scalar
4073 // ones. If we ever find a target which wants to lower scalable
4074 // vectors back to scalars, we'll need to update this code to
4075 // explicitly ask TTI about the register class uses for each part.
4076 return NumLegalParts <= VF.getKnownMinValue();
4077 }
4078 // Two or more elements that share a register - are vectorized.
4079 return NumLegalParts < VF.getFixedValue();
4080 };
4081
4082 // If no def nor is a store, e.g., branches, continue - no value to check.
4083 if (R.getNumDefinedValues() == 0 &&
4085 continue;
4086 // For multi-def recipes, currently only interleaved loads, suffice to
4087 // check first def only.
4088 // For stores check their stored value; for interleaved stores suffice
4089 // the check first stored value only. In all cases this is the second
4090 // operand.
4091 VPValue *ToCheck =
4092 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
4093 Type *ScalarTy = TypeInfo.inferScalarType(ToCheck);
4094 if (!Visited.insert({ScalarTy}).second)
4095 continue;
4096 Type *WideTy = toVectorizedTy(ScalarTy, VF);
4097 if (any_of(getContainedTypes(WideTy), WillGenerateTargetVectors))
4098 return true;
4099 }
4100 }
4101
4102 return false;
4103}
4104
4105static bool hasReplicatorRegion(VPlan &Plan) {
4107 Plan.getVectorLoopRegion()->getEntry())),
4108 [](auto *VPRB) { return VPRB->isReplicator(); });
4109}
4110
4111#ifndef NDEBUG
4112VectorizationFactor LoopVectorizationPlanner::selectVectorizationFactor() {
4113 InstructionCost ExpectedCost = CM.expectedCost(ElementCount::getFixed(1));
4114 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
4115 assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
4116 assert(
4117 any_of(VPlans,
4118 [](std::unique_ptr<VPlan> &P) { return P->hasScalarVFOnly(); }) &&
4119 "Expected Scalar VF to be a candidate");
4120
4121 const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost,
4122 ExpectedCost);
4123 VectorizationFactor ChosenFactor = ScalarCost;
4124
4125 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
4126 if (ForceVectorization &&
4127 (VPlans.size() > 1 || !VPlans[0]->hasScalarVFOnly())) {
4128 // Ignore scalar width, because the user explicitly wants vectorization.
4129 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
4130 // evaluation.
4131 ChosenFactor.Cost = InstructionCost::getMax();
4132 }
4133
4134 for (auto &P : VPlans) {
4135 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
4136 P->vectorFactors().end());
4137
4139 if (any_of(VFs, [this](ElementCount VF) {
4140 return CM.shouldConsiderRegPressureForVF(VF);
4141 }))
4142 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
4143
4144 for (unsigned I = 0; I < VFs.size(); I++) {
4145 ElementCount VF = VFs[I];
4146 // The cost for scalar VF=1 is already calculated, so ignore it.
4147 if (VF.isScalar())
4148 continue;
4149
4150 InstructionCost C = CM.expectedCost(VF);
4151
4152 // Add on other costs that are modelled in VPlan, but not in the legacy
4153 // cost model.
4154 VPCostContext CostCtx(CM.TTI, *CM.TLI, *P, CM, CM.CostKind, CM.PSE,
4155 OrigLoop);
4156 VPRegionBlock *VectorRegion = P->getVectorLoopRegion();
4157 assert(VectorRegion && "Expected to have a vector region!");
4158 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
4159 vp_depth_first_shallow(VectorRegion->getEntry()))) {
4160 for (VPRecipeBase &R : *VPBB) {
4161 auto *VPI = dyn_cast<VPInstruction>(&R);
4162 if (!VPI)
4163 continue;
4164 switch (VPI->getOpcode()) {
4165 // Selects are only modelled in the legacy cost model for safe
4166 // divisors.
4167 case Instruction::Select: {
4168 if (auto *WR =
4169 dyn_cast_or_null<VPWidenRecipe>(VPI->getSingleUser())) {
4170 switch (WR->getOpcode()) {
4171 case Instruction::UDiv:
4172 case Instruction::SDiv:
4173 case Instruction::URem:
4174 case Instruction::SRem:
4175 continue;
4176 default:
4177 break;
4178 }
4179 }
4180 C += VPI->cost(VF, CostCtx);
4181 break;
4182 }
4184 unsigned Multiplier =
4185 cast<VPConstantInt>(VPI->getOperand(2))->getZExtValue();
4186 C += VPI->cost(VF * Multiplier, CostCtx);
4187 break;
4188 }
4191 C += VPI->cost(VF, CostCtx);
4192 break;
4193 default:
4194 break;
4195 }
4196 }
4197 }
4198
4199 // Add the cost of any spills due to excess register usage
4200 if (CM.shouldConsiderRegPressureForVF(VF))
4201 C += RUs[I].spillCost(CostCtx, ForceTargetNumVectorRegs);
4202
4203 VectorizationFactor Candidate(VF, C, ScalarCost.ScalarCost);
4204 unsigned Width =
4205 estimateElementCount(Candidate.Width, CM.getVScaleForTuning());
4206 LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << VF
4207 << " costs: " << (Candidate.Cost / Width));
4208 if (VF.isScalable())
4209 LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
4210 << CM.getVScaleForTuning().value_or(1) << ")");
4211 LLVM_DEBUG(dbgs() << ".\n");
4212
4213 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
4214 LLVM_DEBUG(
4215 dbgs()
4216 << "LV: Not considering vector loop of width " << VF
4217 << " because it will not generate any vector instructions.\n");
4218 continue;
4219 }
4220
4221 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
4222 LLVM_DEBUG(
4223 dbgs()
4224 << "LV: Not considering vector loop of width " << VF
4225 << " because it would cause replicated blocks to be generated,"
4226 << " which isn't allowed when optimizing for size.\n");
4227 continue;
4228 }
4229
4230 if (isMoreProfitable(Candidate, ChosenFactor, P->hasScalarTail()))
4231 ChosenFactor = Candidate;
4232 }
4233 }
4234
4235 if (!EnableCondStoresVectorization && CM.hasPredStores()) {
4237 "There are conditional stores.",
4238 "store that is conditionally executed prevents vectorization",
4239 "ConditionalStore", ORE, OrigLoop);
4240 ChosenFactor = ScalarCost;
4241 }
4242
4243 LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
4244 !isMoreProfitable(ChosenFactor, ScalarCost,
4245 !CM.foldTailByMasking())) dbgs()
4246 << "LV: Vectorization seems to be not beneficial, "
4247 << "but was forced by a user.\n");
4248 return ChosenFactor;
4249}
4250#endif
4251
4252/// Returns true if the VPlan contains a VPReductionPHIRecipe with
4253/// FindLast recurrence kind.
4254static bool hasFindLastReductionPhi(VPlan &Plan) {
4256 [](VPRecipeBase &R) {
4257 auto *RedPhi = dyn_cast<VPReductionPHIRecipe>(&R);
4258 return RedPhi &&
4259 RecurrenceDescriptor::isFindLastRecurrenceKind(
4260 RedPhi->getRecurrenceKind());
4261 });
4262}
4263
4264/// Returns true if the VPlan contains header phi recipes that are not currently
4265/// supported for epilogue vectorization.
4267 return any_of(
4269 [](VPRecipeBase &R) {
4270 if (auto *WidenInd = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R))
4271 return !WidenInd->getPHINode();
4272 auto *RedPhi = dyn_cast<VPReductionPHIRecipe>(&R);
4273 if (!RedPhi)
4274 return false;
4275 if (RecurrenceDescriptor::isFindLastRecurrenceKind(
4276 RedPhi->getRecurrenceKind()) ||
4277 !RedPhi->getUnderlyingValue())
4278 return true;
4279 // FindIV reductions with sunk expressions are not yet supported for
4280 // epilogue vectorization: the resume value from the main loop is in
4281 // expression domain (e.g., mul(ReducedIV, 3)), but the epilogue tracks
4282 // raw IV values. A sunk expression is identified by a non-VPInstruction
4283 // user of ComputeReductionResult.
4284 if (RecurrenceDescriptor::isFindIVRecurrenceKind(
4285 RedPhi->getRecurrenceKind())) {
4286 auto *RdxResult = vputils::findComputeReductionResult(RedPhi);
4287 assert(RdxResult &&
4288 "FindIV reduction must have ComputeReductionResult");
4289 return any_of(RdxResult->users(),
4290 [](VPUser *U) { return !isa<VPInstruction>(U); });
4291 }
4292 return false;
4293 });
4294}
4295
4296bool LoopVectorizationPlanner::isCandidateForEpilogueVectorization(
4297 VPlan &MainPlan) const {
4298 // Cross iteration phis such as fixed-order recurrences and FMaxNum/FMinNum
4299 // reductions need special handling and are currently unsupported.
4300 if (any_of(OrigLoop->getHeader()->phis(), [&](PHINode &Phi) {
4301 if (!Legal->isReductionVariable(&Phi))
4302 return Legal->isFixedOrderRecurrence(&Phi);
4303 RecurKind Kind =
4304 Legal->getRecurrenceDescriptor(&Phi).getRecurrenceKind();
4305 return RecurrenceDescriptor::isFPMinMaxNumRecurrenceKind(Kind);
4306 }))
4307 return false;
4308
4309 // FindLast reductions and inductions without underlying PHI require special
4310 // handling and are currently not supported for epilogue vectorization.
4311 if (hasUnsupportedHeaderPhiRecipe(MainPlan))
4312 return false;
4313
4314 // Phis with uses outside of the loop require special handling and are
4315 // currently unsupported.
4316 for (const auto &Entry : Legal->getInductionVars()) {
4317 // Look for uses of the value of the induction at the last iteration.
4318 Value *PostInc =
4319 Entry.first->getIncomingValueForBlock(OrigLoop->getLoopLatch());
4320 for (User *U : PostInc->users())
4321 if (!OrigLoop->contains(cast<Instruction>(U)))
4322 return false;
4323 // Look for uses of penultimate value of the induction.
4324 for (User *U : Entry.first->users())
4325 if (!OrigLoop->contains(cast<Instruction>(U)))
4326 return false;
4327 }
4328
4329 // Epilogue vectorization code has not been auditted to ensure it handles
4330 // non-latch exits properly. It may be fine, but it needs auditted and
4331 // tested.
4332 // TODO: Add support for loops with an early exit.
4333 if (OrigLoop->getExitingBlock() != OrigLoop->getLoopLatch())
4334 return false;
4335
4336 return true;
4337}
4338
4340 const ElementCount VF, const unsigned IC) const {
4341 // FIXME: We need a much better cost-model to take different parameters such
4342 // as register pressure, code size increase and cost of extra branches into
4343 // account. For now we apply a very crude heuristic and only consider loops
4344 // with vectorization factors larger than a certain value.
4345
4346 // Allow the target to opt out.
4347 if (!TTI.preferEpilogueVectorization(VF * IC))
4348 return false;
4349
4350 unsigned MinVFThreshold = EpilogueVectorizationMinVF.getNumOccurrences() > 0
4352 : TTI.getEpilogueVectorizationMinVF();
4353 return estimateElementCount(VF * IC, VScaleForTuning) >= MinVFThreshold;
4354}
4355
4357 VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC) {
4359 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n");
4360 return nullptr;
4361 }
4362
4363 if (!CM.isScalarEpilogueAllowed()) {
4364 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because no "
4365 "epilogue is allowed.\n");
4366 return nullptr;
4367 }
4368
4369 // Not really a cost consideration, but check for unsupported cases here to
4370 // simplify the logic.
4371 if (!isCandidateForEpilogueVectorization(MainPlan)) {
4372 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because the loop "
4373 "is not a supported candidate.\n");
4374 return nullptr;
4375 }
4376
4379 IC * estimateElementCount(MainLoopVF, CM.getVScaleForTuning())) {
4380 // Note that the main loop leaves IC * MainLoopVF iterations iff a scalar
4381 // epilogue is required, but then the epilogue loop also requires a scalar
4382 // epilogue.
4383 LLVM_DEBUG(dbgs() << "LEV: Forced epilogue VF results in dead epilogue "
4384 "vector loop, skipping vectorizing epilogue.\n");
4385 return nullptr;
4386 }
4387
4388 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n");
4390 if (hasPlanWithVF(ForcedEC)) {
4391 std::unique_ptr<VPlan> Clone(getPlanFor(ForcedEC).duplicate());
4392 Clone->setVF(ForcedEC);
4393 return Clone;
4394 }
4395
4396 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization forced factor is not "
4397 "viable.\n");
4398 return nullptr;
4399 }
4400
4401 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
4402 LLVM_DEBUG(
4403 dbgs() << "LEV: Epilogue vectorization skipped due to opt for size.\n");
4404 return nullptr;
4405 }
4406
4407 if (!CM.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
4408 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
4409 "this loop\n");
4410 return nullptr;
4411 }
4412
4413 // Check if a plan's vector loop processes fewer iterations than VF (e.g. when
4414 // interleave groups have been narrowed) narrowInterleaveGroups) and return
4415 // the adjusted, effective VF.
4416 using namespace VPlanPatternMatch;
4417 auto GetEffectiveVF = [](VPlan &Plan, ElementCount VF) -> ElementCount {
4418 auto *Exiting = Plan.getVectorLoopRegion()->getExitingBasicBlock();
4419 if (match(&Exiting->back(),
4420 m_BranchOnCount(m_Add(m_CanonicalIV(), m_Specific(&Plan.getUF())),
4421 m_VPValue())))
4422 return ElementCount::get(1, VF.isScalable());
4423 return VF;
4424 };
4425
4426 // Check if the main loop processes fewer than MainLoopVF elements per
4427 // iteration (e.g. due to narrowing interleave groups). Adjust MainLoopVF
4428 // as needed.
4429 MainLoopVF = GetEffectiveVF(MainPlan, MainLoopVF);
4430
4431 // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
4432 // the main loop handles 8 lanes per iteration. We could still benefit from
4433 // vectorizing the epilogue loop with VF=4.
4434 ElementCount EstimatedRuntimeVF = ElementCount::getFixed(
4435 estimateElementCount(MainLoopVF, CM.getVScaleForTuning()));
4436
4437 Type *TCType = Legal->getWidestInductionType();
4438 const SCEV *RemainingIterations = nullptr;
4439 unsigned MaxTripCount = 0;
4440 const SCEV *TC = vputils::getSCEVExprForVPValue(MainPlan.getTripCount(), PSE);
4441 assert(!isa<SCEVCouldNotCompute>(TC) && "Trip count SCEV must be computable");
4442 const SCEV *KnownMinTC;
4443 bool ScalableTC = match(TC, m_scev_c_Mul(m_SCEV(KnownMinTC), m_SCEVVScale()));
4444 bool ScalableRemIter = false;
4445 ScalarEvolution &SE = *PSE.getSE();
4446 // Use versions of TC and VF in which both are either scalable or fixed.
4447 if (ScalableTC == MainLoopVF.isScalable()) {
4448 ScalableRemIter = ScalableTC;
4449 RemainingIterations =
4450 SE.getURemExpr(TC, SE.getElementCount(TCType, MainLoopVF * IC));
4451 } else if (ScalableTC) {
4452 const SCEV *EstimatedTC = SE.getMulExpr(
4453 KnownMinTC,
4454 SE.getConstant(TCType, CM.getVScaleForTuning().value_or(1)));
4455 RemainingIterations = SE.getURemExpr(
4456 EstimatedTC, SE.getElementCount(TCType, MainLoopVF * IC));
4457 } else
4458 RemainingIterations =
4459 SE.getURemExpr(TC, SE.getElementCount(TCType, EstimatedRuntimeVF * IC));
4460
4461 // No iterations left to process in the epilogue.
4462 if (RemainingIterations->isZero())
4463 return nullptr;
4464
4465 if (MainLoopVF.isFixed()) {
4466 MaxTripCount = MainLoopVF.getFixedValue() * IC - 1;
4467 if (SE.isKnownPredicate(CmpInst::ICMP_ULT, RemainingIterations,
4468 SE.getConstant(TCType, MaxTripCount))) {
4469 MaxTripCount = SE.getUnsignedRangeMax(RemainingIterations).getZExtValue();
4470 }
4471 LLVM_DEBUG(dbgs() << "LEV: Maximum Trip Count for Epilogue: "
4472 << MaxTripCount << "\n");
4473 }
4474
4475 auto SkipVF = [&](const SCEV *VF, const SCEV *RemIter) -> bool {
4476 return SE.isKnownPredicate(CmpInst::ICMP_UGT, VF, RemIter);
4477 };
4479 VPlan *BestPlan = nullptr;
4480 for (auto &NextVF : ProfitableVFs) {
4481 // Skip candidate VFs without a corresponding VPlan.
4482 if (!hasPlanWithVF(NextVF.Width))
4483 continue;
4484
4485 VPlan &CurrentPlan = getPlanFor(NextVF.Width);
4486 ElementCount EffectiveVF = GetEffectiveVF(CurrentPlan, NextVF.Width);
4487 // Skip candidate VFs with widths >= the (estimated) runtime VF (scalable
4488 // vectors) or > the VF of the main loop (fixed vectors).
4489 if ((!EffectiveVF.isScalable() && MainLoopVF.isScalable() &&
4490 ElementCount::isKnownGE(EffectiveVF, EstimatedRuntimeVF)) ||
4491 (EffectiveVF.isScalable() &&
4492 ElementCount::isKnownGE(EffectiveVF, MainLoopVF)) ||
4493 (!EffectiveVF.isScalable() && !MainLoopVF.isScalable() &&
4494 ElementCount::isKnownGT(EffectiveVF, MainLoopVF)))
4495 continue;
4496
4497 // If EffectiveVF is greater than the number of remaining iterations, the
4498 // epilogue loop would be dead. Skip such factors. If the epilogue plan
4499 // also has narrowed interleave groups, use the effective VF since
4500 // the epilogue step will be reduced to its IC.
4501 // TODO: We should also consider comparing against a scalable
4502 // RemainingIterations when SCEV be able to evaluate non-canonical
4503 // vscale-based expressions.
4504 if (!ScalableRemIter) {
4505 // Handle the case where EffectiveVF and RemainingIterations are in
4506 // different numerical spaces.
4507 if (EffectiveVF.isScalable())
4508 EffectiveVF = ElementCount::getFixed(
4509 estimateElementCount(EffectiveVF, CM.getVScaleForTuning()));
4510 if (SkipVF(SE.getElementCount(TCType, EffectiveVF), RemainingIterations))
4511 continue;
4512 }
4513
4514 if (Result.Width.isScalar() ||
4515 isMoreProfitable(NextVF, Result, MaxTripCount, !CM.foldTailByMasking(),
4516 /*IsEpilogue*/ true)) {
4517 Result = NextVF;
4518 BestPlan = &CurrentPlan;
4519 }
4520 }
4521
4522 if (!BestPlan)
4523 return nullptr;
4524
4525 LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
4526 << Result.Width << "\n");
4527 std::unique_ptr<VPlan> Clone(BestPlan->duplicate());
4528 Clone->setVF(Result.Width);
4529 return Clone;
4530}
4531
4532std::pair<unsigned, unsigned>
4534 unsigned MinWidth = -1U;
4535 unsigned MaxWidth = 8;
4536 const DataLayout &DL = TheFunction->getDataLayout();
4537 // For in-loop reductions, no element types are added to ElementTypesInLoop
4538 // if there are no loads/stores in the loop. In this case, check through the
4539 // reduction variables to determine the maximum width.
4540 if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
4541 for (const auto &PhiDescriptorPair : Legal->getReductionVars()) {
4542 const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
4543 // When finding the min width used by the recurrence we need to account
4544 // for casts on the input operands of the recurrence.
4545 MinWidth = std::min(
4546 MinWidth,
4547 std::min(RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
4549 MaxWidth = std::max(MaxWidth,
4551 }
4552 } else {
4553 for (Type *T : ElementTypesInLoop) {
4554 MinWidth = std::min<unsigned>(
4555 MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4556 MaxWidth = std::max<unsigned>(
4557 MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4558 }
4559 }
4560 return {MinWidth, MaxWidth};
4561}
4562
4564 ElementTypesInLoop.clear();
4565 // For each block.
4566 for (BasicBlock *BB : TheLoop->blocks()) {
4567 // For each instruction in the loop.
4568 for (Instruction &I : *BB) {
4569 Type *T = I.getType();
4570
4571 // Skip ignored values.
4572 if (ValuesToIgnore.count(&I))
4573 continue;
4574
4575 // Only examine Loads, Stores and PHINodes.
4576 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
4577 continue;
4578
4579 // Examine PHI nodes that are reduction variables. Update the type to
4580 // account for the recurrence type.
4581 if (auto *PN = dyn_cast<PHINode>(&I)) {
4582 if (!Legal->isReductionVariable(PN))
4583 continue;
4584 const RecurrenceDescriptor &RdxDesc =
4585 Legal->getRecurrenceDescriptor(PN);
4587 TTI.preferInLoopReduction(RdxDesc.getRecurrenceKind(),
4588 RdxDesc.getRecurrenceType()))
4589 continue;
4590 T = RdxDesc.getRecurrenceType();
4591 }
4592
4593 // Examine the stored values.
4594 if (auto *ST = dyn_cast<StoreInst>(&I))
4595 T = ST->getValueOperand()->getType();
4596
4597 assert(T->isSized() &&
4598 "Expected the load/store/recurrence type to be sized");
4599
4600 ElementTypesInLoop.insert(T);
4601 }
4602 }
4603}
4604
4605unsigned
4607 InstructionCost LoopCost) {
4608 // -- The interleave heuristics --
4609 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4610 // There are many micro-architectural considerations that we can't predict
4611 // at this level. For example, frontend pressure (on decode or fetch) due to
4612 // code size, or the number and capabilities of the execution ports.
4613 //
4614 // We use the following heuristics to select the interleave count:
4615 // 1. If the code has reductions, then we interleave to break the cross
4616 // iteration dependency.
4617 // 2. If the loop is really small, then we interleave to reduce the loop
4618 // overhead.
4619 // 3. We don't interleave if we think that we will spill registers to memory
4620 // due to the increased register pressure.
4621
4622 // Only interleave tail-folded loops if wide lane masks are requested, as the
4623 // overhead of multiple instructions to calculate the predicate is likely
4624 // not beneficial. If a scalar epilogue is not allowed for any other reason,
4625 // do not interleave.
4626 if (!CM.isScalarEpilogueAllowed() &&
4627 !(CM.preferPredicatedLoop() && CM.useWideActiveLaneMask()))
4628 return 1;
4629
4632 LLVM_DEBUG(dbgs() << "LV: Loop requires variable-length step. "
4633 "Unroll factor forced to be 1.\n");
4634 return 1;
4635 }
4636
4637 // We used the distance for the interleave count.
4638 if (!Legal->isSafeForAnyVectorWidth())
4639 return 1;
4640
4641 // We don't attempt to perform interleaving for loops with uncountable early
4642 // exits because the VPInstruction::AnyOf code cannot currently handle
4643 // multiple parts.
4644 if (Plan.hasEarlyExit())
4645 return 1;
4646
4647 const bool HasReductions =
4650
4651 // FIXME: implement interleaving for FindLast transform correctly.
4652 if (hasFindLastReductionPhi(Plan))
4653 return 1;
4654
4655 VPRegisterUsage R =
4656 calculateRegisterUsageForPlan(Plan, {VF}, TTI, CM.ValuesToIgnore)[0];
4657
4658 // If we did not calculate the cost for VF (because the user selected the VF)
4659 // then we calculate the cost of VF here.
4660 if (LoopCost == 0) {
4661 if (VF.isScalar())
4662 LoopCost = CM.expectedCost(VF);
4663 else
4664 LoopCost = cost(Plan, VF, &R);
4665 assert(LoopCost.isValid() && "Expected to have chosen a VF with valid cost");
4666
4667 // Loop body is free and there is no need for interleaving.
4668 if (LoopCost == 0)
4669 return 1;
4670 }
4671
4672 // We divide by these constants so assume that we have at least one
4673 // instruction that uses at least one register.
4674 for (auto &Pair : R.MaxLocalUsers) {
4675 Pair.second = std::max(Pair.second, 1U);
4676 }
4677
4678 // We calculate the interleave count using the following formula.
4679 // Subtract the number of loop invariants from the number of available
4680 // registers. These registers are used by all of the interleaved instances.
4681 // Next, divide the remaining registers by the number of registers that is
4682 // required by the loop, in order to estimate how many parallel instances
4683 // fit without causing spills. All of this is rounded down if necessary to be
4684 // a power of two. We want power of two interleave count to simplify any
4685 // addressing operations or alignment considerations.
4686 // We also want power of two interleave counts to ensure that the induction
4687 // variable of the vector loop wraps to zero, when tail is folded by masking;
4688 // this currently happens when OptForSize, in which case IC is set to 1 above.
4689 unsigned IC = UINT_MAX;
4690
4691 for (const auto &Pair : R.MaxLocalUsers) {
4692 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
4693 LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
4694 << " registers of "
4695 << TTI.getRegisterClassName(Pair.first)
4696 << " register class\n");
4697 if (VF.isScalar()) {
4698 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4699 TargetNumRegisters = ForceTargetNumScalarRegs;
4700 } else {
4701 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4702 TargetNumRegisters = ForceTargetNumVectorRegs;
4703 }
4704 unsigned MaxLocalUsers = Pair.second;
4705 unsigned LoopInvariantRegs = 0;
4706 if (R.LoopInvariantRegs.contains(Pair.first))
4707 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
4708
4709 unsigned TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
4710 MaxLocalUsers);
4711 // Don't count the induction variable as interleaved.
4713 TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
4714 std::max(1U, (MaxLocalUsers - 1)));
4715 }
4716
4717 IC = std::min(IC, TmpIC);
4718 }
4719
4720 // Clamp the interleave ranges to reasonable counts.
4721 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4722 LLVM_DEBUG(dbgs() << "LV: MaxInterleaveFactor for the target is "
4723 << MaxInterleaveCount << "\n");
4724
4725 // Check if the user has overridden the max.
4726 if (VF.isScalar()) {
4727 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4728 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4729 } else {
4730 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4731 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4732 }
4733
4734 // Try to get the exact trip count, or an estimate based on profiling data or
4735 // ConstantMax from PSE, failing that.
4736 auto BestKnownTC =
4737 getSmallBestKnownTC(PSE, OrigLoop,
4738 /*CanUseConstantMax=*/true,
4739 /*CanExcludeZeroTrips=*/CM.isScalarEpilogueAllowed());
4740
4741 // For fixed length VFs treat a scalable trip count as unknown.
4742 if (BestKnownTC && (BestKnownTC->isFixed() || VF.isScalable())) {
4743 // Re-evaluate trip counts and VFs to be in the same numerical space.
4744 unsigned AvailableTC =
4745 estimateElementCount(*BestKnownTC, CM.getVScaleForTuning());
4746 unsigned EstimatedVF = estimateElementCount(VF, CM.getVScaleForTuning());
4747
4748 // At least one iteration must be scalar when this constraint holds. So the
4749 // maximum available iterations for interleaving is one less.
4750 if (CM.requiresScalarEpilogue(VF.isVector()))
4751 --AvailableTC;
4752
4753 unsigned InterleaveCountLB = bit_floor(std::max(
4754 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
4755
4756 if (getSmallConstantTripCount(PSE.getSE(), OrigLoop).isNonZero()) {
4757 // If the best known trip count is exact, we select between two
4758 // prospective ICs, where
4759 //
4760 // 1) the aggressive IC is capped by the trip count divided by VF
4761 // 2) the conservative IC is capped by the trip count divided by (VF * 2)
4762 //
4763 // The final IC is selected in a way that the epilogue loop trip count is
4764 // minimized while maximizing the IC itself, so that we either run the
4765 // vector loop at least once if it generates a small epilogue loop, or
4766 // else we run the vector loop at least twice.
4767
4768 unsigned InterleaveCountUB = bit_floor(std::max(
4769 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
4770 MaxInterleaveCount = InterleaveCountLB;
4771
4772 if (InterleaveCountUB != InterleaveCountLB) {
4773 unsigned TailTripCountUB =
4774 (AvailableTC % (EstimatedVF * InterleaveCountUB));
4775 unsigned TailTripCountLB =
4776 (AvailableTC % (EstimatedVF * InterleaveCountLB));
4777 // If both produce same scalar tail, maximize the IC to do the same work
4778 // in fewer vector loop iterations
4779 if (TailTripCountUB == TailTripCountLB)
4780 MaxInterleaveCount = InterleaveCountUB;
4781 }
4782 } else {
4783 // If trip count is an estimated compile time constant, limit the
4784 // IC to be capped by the trip count divided by VF * 2, such that the
4785 // vector loop runs at least twice to make interleaving seem profitable
4786 // when there is an epilogue loop present. Since exact Trip count is not
4787 // known we choose to be conservative in our IC estimate.
4788 MaxInterleaveCount = InterleaveCountLB;
4789 }
4790 }
4791
4792 assert(MaxInterleaveCount > 0 &&
4793 "Maximum interleave count must be greater than 0");
4794
4795 // Clamp the calculated IC to be between the 1 and the max interleave count
4796 // that the target and trip count allows.
4797 if (IC > MaxInterleaveCount)
4798 IC = MaxInterleaveCount;
4799 else
4800 // Make sure IC is greater than 0.
4801 IC = std::max(1u, IC);
4802
4803 assert(IC > 0 && "Interleave count must be greater than 0.");
4804
4805 // Interleave if we vectorized this loop and there is a reduction that could
4806 // benefit from interleaving.
4807 if (VF.isVector() && HasReductions) {
4808 LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4809 return IC;
4810 }
4811
4812 // For any scalar loop that either requires runtime checks or predication we
4813 // are better off leaving this to the unroller. Note that if we've already
4814 // vectorized the loop we will have done the runtime check and so interleaving
4815 // won't require further checks.
4816 bool ScalarInterleavingRequiresPredication =
4817 (VF.isScalar() && any_of(OrigLoop->blocks(), [this](BasicBlock *BB) {
4818 return Legal->blockNeedsPredication(BB);
4819 }));
4820 bool ScalarInterleavingRequiresRuntimePointerCheck =
4821 (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
4822
4823 // We want to interleave small loops in order to reduce the loop overhead and
4824 // potentially expose ILP opportunities.
4825 LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
4826 << "LV: IC is " << IC << '\n'
4827 << "LV: VF is " << VF << '\n');
4828 const bool AggressivelyInterleave =
4829 TTI.enableAggressiveInterleaving(HasReductions);
4830 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
4831 !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
4832 // We assume that the cost overhead is 1 and we use the cost model
4833 // to estimate the cost of the loop and interleave until the cost of the
4834 // loop overhead is about 5% of the cost of the loop.
4835 unsigned SmallIC = std::min(IC, (unsigned)llvm::bit_floor<uint64_t>(
4836 SmallLoopCost / LoopCost.getValue()));
4837
4838 // Interleave until store/load ports (estimated by max interleave count) are
4839 // saturated.
4840 unsigned NumStores = 0;
4841 unsigned NumLoads = 0;
4844 for (VPRecipeBase &R : *VPBB) {
4846 NumLoads++;
4847 continue;
4848 }
4850 NumStores++;
4851 continue;
4852 }
4853
4854 if (auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R)) {
4855 if (unsigned StoreOps = InterleaveR->getNumStoreOperands())
4856 NumStores += StoreOps;
4857 else
4858 NumLoads += InterleaveR->getNumDefinedValues();
4859 continue;
4860 }
4861 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
4862 NumLoads += isa<LoadInst>(RepR->getUnderlyingInstr());
4863 NumStores += isa<StoreInst>(RepR->getUnderlyingInstr());
4864 continue;
4865 }
4866 if (isa<VPHistogramRecipe>(&R)) {
4867 NumLoads++;
4868 NumStores++;
4869 continue;
4870 }
4871 }
4872 }
4873 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4874 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4875
4876 // There is little point in interleaving for reductions containing selects
4877 // and compares when VF=1 since it may just create more overhead than it's
4878 // worth for loops with small trip counts. This is because we still have to
4879 // do the final reduction after the loop.
4880 bool HasSelectCmpReductions =
4881 HasReductions &&
4883 [](VPRecipeBase &R) {
4884 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4885 return RedR && (RecurrenceDescriptor::isAnyOfRecurrenceKind(
4886 RedR->getRecurrenceKind()) ||
4887 RecurrenceDescriptor::isFindIVRecurrenceKind(
4888 RedR->getRecurrenceKind()));
4889 });
4890 if (HasSelectCmpReductions) {
4891 LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
4892 return 1;
4893 }
4894
4895 // If we have a scalar reduction (vector reductions are already dealt with
4896 // by this point), we can increase the critical path length if the loop
4897 // we're interleaving is inside another loop. For tree-wise reductions
4898 // set the limit to 2, and for ordered reductions it's best to disable
4899 // interleaving entirely.
4900 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
4901 bool HasOrderedReductions =
4903 [](VPRecipeBase &R) {
4904 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4905
4906 return RedR && RedR->isOrdered();
4907 });
4908 if (HasOrderedReductions) {
4909 LLVM_DEBUG(
4910 dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
4911 return 1;
4912 }
4913
4914 unsigned F = MaxNestedScalarReductionIC;
4915 SmallIC = std::min(SmallIC, F);
4916 StoresIC = std::min(StoresIC, F);
4917 LoadsIC = std::min(LoadsIC, F);
4918 }
4919
4921 std::max(StoresIC, LoadsIC) > SmallIC) {
4922 LLVM_DEBUG(
4923 dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4924 return std::max(StoresIC, LoadsIC);
4925 }
4926
4927 // If there are scalar reductions and TTI has enabled aggressive
4928 // interleaving for reductions, we will interleave to expose ILP.
4929 if (VF.isScalar() && AggressivelyInterleave) {
4930 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4931 // Interleave no less than SmallIC but not as aggressive as the normal IC
4932 // to satisfy the rare situation when resources are too limited.
4933 return std::max(IC / 2, SmallIC);
4934 }
4935
4936 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4937 return SmallIC;
4938 }
4939
4940 // Interleave if this is a large loop (small loops are already dealt with by
4941 // this point) that could benefit from interleaving.
4942 if (AggressivelyInterleave) {
4943 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4944 return IC;
4945 }
4946
4947 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
4948 return 1;
4949}
4950
4952 ElementCount VF) {
4953 // TODO: Cost model for emulated masked load/store is completely
4954 // broken. This hack guides the cost model to use an artificially
4955 // high enough value to practically disable vectorization with such
4956 // operations, except where previously deployed legality hack allowed
4957 // using very low cost values. This is to avoid regressions coming simply
4958 // from moving "masked load/store" check from legality to cost model.
4959 // Masked Load/Gather emulation was previously never allowed.
4960 // Limited number of Masked Store/Scatter emulation was allowed.
4962 "Expecting a scalar emulated instruction");
4963 return isa<LoadInst>(I) ||
4964 (isa<StoreInst>(I) &&
4965 NumPredStores > NumberOfStoresToPredicate);
4966}
4967
4969 assert(VF.isVector() && "Expected VF >= 2");
4970
4971 // If we've already collected the instructions to scalarize or the predicated
4972 // BBs after vectorization, there's nothing to do. Collection may already have
4973 // occurred if we have a user-selected VF and are now computing the expected
4974 // cost for interleaving.
4975 if (InstsToScalarize.contains(VF) ||
4976 PredicatedBBsAfterVectorization.contains(VF))
4977 return;
4978
4979 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
4980 // not profitable to scalarize any instructions, the presence of VF in the
4981 // map will indicate that we've analyzed it already.
4982 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
4983
4984 // Find all the instructions that are scalar with predication in the loop and
4985 // determine if it would be better to not if-convert the blocks they are in.
4986 // If so, we also record the instructions to scalarize.
4987 for (BasicBlock *BB : TheLoop->blocks()) {
4989 continue;
4990 for (Instruction &I : *BB)
4991 if (isScalarWithPredication(&I, VF)) {
4992 ScalarCostsTy ScalarCosts;
4993 // Do not apply discount logic for:
4994 // 1. Scalars after vectorization, as there will only be a single copy
4995 // of the instruction.
4996 // 2. Scalable VF, as that would lead to invalid scalarization costs.
4997 // 3. Emulated masked memrefs, if a hacked cost is needed.
4998 if (!isScalarAfterVectorization(&I, VF) && !VF.isScalable() &&
5000 computePredInstDiscount(&I, ScalarCosts, VF) >= 0) {
5001 for (const auto &[I, IC] : ScalarCosts)
5002 ScalarCostsVF.insert({I, IC});
5003 // Check if we decided to scalarize a call. If so, update the widening
5004 // decision of the call to CM_Scalarize with the computed scalar cost.
5005 for (const auto &[I, Cost] : ScalarCosts) {
5006 auto *CI = dyn_cast<CallInst>(I);
5007 if (!CI || !CallWideningDecisions.contains({CI, VF}))
5008 continue;
5009 CallWideningDecisions[{CI, VF}].Kind = CM_Scalarize;
5010 CallWideningDecisions[{CI, VF}].Cost = Cost;
5011 }
5012 }
5013 // Remember that BB will remain after vectorization.
5014 PredicatedBBsAfterVectorization[VF].insert(BB);
5015 for (auto *Pred : predecessors(BB)) {
5016 if (Pred->getSingleSuccessor() == BB)
5017 PredicatedBBsAfterVectorization[VF].insert(Pred);
5018 }
5019 }
5020 }
5021}
5022
5023InstructionCost LoopVectorizationCostModel::computePredInstDiscount(
5024 Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
5025 assert(!isUniformAfterVectorization(PredInst, VF) &&
5026 "Instruction marked uniform-after-vectorization will be predicated");
5027
5028 // Initialize the discount to zero, meaning that the scalar version and the
5029 // vector version cost the same.
5030 InstructionCost Discount = 0;
5031
5032 // Holds instructions to analyze. The instructions we visit are mapped in
5033 // ScalarCosts. Those instructions are the ones that would be scalarized if
5034 // we find that the scalar version costs less.
5036
5037 // Returns true if the given instruction can be scalarized.
5038 auto CanBeScalarized = [&](Instruction *I) -> bool {
5039 // We only attempt to scalarize instructions forming a single-use chain
5040 // from the original predicated block that would otherwise be vectorized.
5041 // Although not strictly necessary, we give up on instructions we know will
5042 // already be scalar to avoid traversing chains that are unlikely to be
5043 // beneficial.
5044 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
5046 return false;
5047
5048 // If the instruction is scalar with predication, it will be analyzed
5049 // separately. We ignore it within the context of PredInst.
5050 if (isScalarWithPredication(I, VF))
5051 return false;
5052
5053 // If any of the instruction's operands are uniform after vectorization,
5054 // the instruction cannot be scalarized. This prevents, for example, a
5055 // masked load from being scalarized.
5056 //
5057 // We assume we will only emit a value for lane zero of an instruction
5058 // marked uniform after vectorization, rather than VF identical values.
5059 // Thus, if we scalarize an instruction that uses a uniform, we would
5060 // create uses of values corresponding to the lanes we aren't emitting code
5061 // for. This behavior can be changed by allowing getScalarValue to clone
5062 // the lane zero values for uniforms rather than asserting.
5063 for (Use &U : I->operands())
5064 if (auto *J = dyn_cast<Instruction>(U.get()))
5065 if (isUniformAfterVectorization(J, VF))
5066 return false;
5067
5068 // Otherwise, we can scalarize the instruction.
5069 return true;
5070 };
5071
5072 // Compute the expected cost discount from scalarizing the entire expression
5073 // feeding the predicated instruction. We currently only consider expressions
5074 // that are single-use instruction chains.
5075 Worklist.push_back(PredInst);
5076 while (!Worklist.empty()) {
5077 Instruction *I = Worklist.pop_back_val();
5078
5079 // If we've already analyzed the instruction, there's nothing to do.
5080 if (ScalarCosts.contains(I))
5081 continue;
5082
5083 // Cannot scalarize fixed-order recurrence phis at the moment.
5084 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
5085 continue;
5086
5087 // Compute the cost of the vector instruction. Note that this cost already
5088 // includes the scalarization overhead of the predicated instruction.
5089 InstructionCost VectorCost = getInstructionCost(I, VF);
5090
5091 // Compute the cost of the scalarized instruction. This cost is the cost of
5092 // the instruction as if it wasn't if-converted and instead remained in the
5093 // predicated block. We will scale this cost by block probability after
5094 // computing the scalarization overhead.
5095 InstructionCost ScalarCost =
5097
5098 // Compute the scalarization overhead of needed insertelement instructions
5099 // and phi nodes.
5100 if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
5101 Type *WideTy = toVectorizedTy(I->getType(), VF);
5102 for (Type *VectorTy : getContainedTypes(WideTy)) {
5103 ScalarCost += TTI.getScalarizationOverhead(
5105 /*Insert=*/true,
5106 /*Extract=*/false, CostKind);
5107 }
5108 ScalarCost +=
5109 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
5110 }
5111
5112 // Compute the scalarization overhead of needed extractelement
5113 // instructions. For each of the instruction's operands, if the operand can
5114 // be scalarized, add it to the worklist; otherwise, account for the
5115 // overhead.
5116 for (Use &U : I->operands())
5117 if (auto *J = dyn_cast<Instruction>(U.get())) {
5118 assert(canVectorizeTy(J->getType()) &&
5119 "Instruction has non-scalar type");
5120 if (CanBeScalarized(J))
5121 Worklist.push_back(J);
5122 else if (needsExtract(J, VF)) {
5123 Type *WideTy = toVectorizedTy(J->getType(), VF);
5124 for (Type *VectorTy : getContainedTypes(WideTy)) {
5125 ScalarCost += TTI.getScalarizationOverhead(
5126 cast<VectorType>(VectorTy),
5127 APInt::getAllOnes(VF.getFixedValue()), /*Insert*/ false,
5128 /*Extract*/ true, CostKind);
5129 }
5130 }
5131 }
5132
5133 // Scale the total scalar cost by block probability.
5134 ScalarCost /= getPredBlockCostDivisor(CostKind, I->getParent());
5135
5136 // Compute the discount. A non-negative discount means the vector version
5137 // of the instruction costs more, and scalarizing would be beneficial.
5138 Discount += VectorCost - ScalarCost;
5139 ScalarCosts[I] = ScalarCost;
5140 }
5141
5142 return Discount;
5143}
5144
5147
5148 // If the vector loop gets executed exactly once with the given VF, ignore the
5149 // costs of comparison and induction instructions, as they'll get simplified
5150 // away.
5151 SmallPtrSet<Instruction *, 2> ValuesToIgnoreForVF;
5152 auto TC = getSmallConstantTripCount(PSE.getSE(), TheLoop);
5153 if (TC == VF && !foldTailByMasking())
5155 ValuesToIgnoreForVF);
5156
5157 // For each block.
5158 for (BasicBlock *BB : TheLoop->blocks()) {
5159 InstructionCost BlockCost;
5160
5161 // For each instruction in the old loop.
5162 for (Instruction &I : *BB) {
5163 // Skip ignored values.
5164 if (ValuesToIgnore.count(&I) || ValuesToIgnoreForVF.count(&I) ||
5165 (VF.isVector() && VecValuesToIgnore.count(&I)))
5166 continue;
5167
5169
5170 // Check if we should override the cost.
5171 if (C.isValid() && ForceTargetInstructionCost.getNumOccurrences() > 0) {
5172 // For interleave groups, use ForceTargetInstructionCost once for the
5173 // whole group.
5174 if (VF.isVector() && getWideningDecision(&I, VF) == CM_Interleave) {
5175 if (getInterleavedAccessGroup(&I)->getInsertPos() == &I)
5177 else
5178 C = InstructionCost(0);
5179 } else {
5181 }
5182 }
5183
5184 BlockCost += C;
5185 LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF "
5186 << VF << " For instruction: " << I << '\n');
5187 }
5188
5189 // If we are vectorizing a predicated block, it will have been
5190 // if-converted. This means that the block's instructions (aside from
5191 // stores and instructions that may divide by zero) will now be
5192 // unconditionally executed. For the scalar case, we may not always execute
5193 // the predicated block, if it is an if-else block. Thus, scale the block's
5194 // cost by the probability of executing it.
5195 // getPredBlockCostDivisor will return 1 for blocks that are only predicated
5196 // by the header mask when folding the tail.
5197 if (VF.isScalar())
5198 BlockCost /= getPredBlockCostDivisor(CostKind, BB);
5199
5200 Cost += BlockCost;
5201 }
5202
5203 return Cost;
5204}
5205
5206/// Gets the address access SCEV for Ptr, if it should be used for cost modeling
5207/// according to isAddressSCEVForCost.
5208///
5209/// This SCEV can be sent to the Target in order to estimate the address
5210/// calculation cost.
5212 Value *Ptr,
5214 const Loop *TheLoop) {
5215 const SCEV *Addr = PSE.getSCEV(Ptr);
5216 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), TheLoop) ? Addr
5217 : nullptr;
5218}
5219
5221LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
5222 ElementCount VF) {
5223 assert(VF.isVector() &&
5224 "Scalarization cost of instruction implies vectorization.");
5225 if (VF.isScalable())
5227
5228 Type *ValTy = getLoadStoreType(I);
5229 auto *SE = PSE.getSE();
5230
5231 unsigned AS = getLoadStoreAddressSpace(I);
5233 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
5234 // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
5235 // that it is being called from this specific place.
5236
5237 // Figure out whether the access is strided and get the stride value
5238 // if it's known in compile time
5239 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, PSE, TheLoop);
5240
5241 // Get the cost of the scalar memory instruction and address computation.
5242 InstructionCost Cost = VF.getFixedValue() * TTI.getAddressComputationCost(
5243 PtrTy, SE, PtrSCEV, CostKind);
5244
5245 // Don't pass *I here, since it is scalar but will actually be part of a
5246 // vectorized loop where the user of it is a vectorized instruction.
5247 const Align Alignment = getLoadStoreAlignment(I);
5248 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5249 Cost += VF.getFixedValue() *
5250 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
5251 AS, CostKind, OpInfo);
5252
5253 // Get the overhead of the extractelement and insertelement instructions
5254 // we might create due to scalarization.
5255 Cost += getScalarizationOverhead(I, VF);
5256
5257 // If we have a predicated load/store, it will need extra i1 extracts and
5258 // conditional branches, but may not be executed for each vector lane. Scale
5259 // the cost by the probability of executing the predicated block.
5260 if (isPredicatedInst(I)) {
5261 Cost /= getPredBlockCostDivisor(CostKind, I->getParent());
5262
5263 // Add the cost of an i1 extract and a branch
5264 auto *VecI1Ty =
5266 Cost += TTI.getScalarizationOverhead(
5267 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
5268 /*Insert=*/false, /*Extract=*/true, CostKind);
5269 Cost += TTI.getCFInstrCost(Instruction::CondBr, CostKind);
5270
5272 // Artificially setting to a high enough value to practically disable
5273 // vectorization with such operations.
5274 Cost = 3000000;
5275 }
5276
5277 return Cost;
5278}
5279
5281LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
5282 ElementCount VF) {
5283 Type *ValTy = getLoadStoreType(I);
5284 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5286 unsigned AS = getLoadStoreAddressSpace(I);
5287 int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
5288
5289 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5290 "Stride should be 1 or -1 for consecutive memory access");
5291 const Align Alignment = getLoadStoreAlignment(I);
5293 if (isMaskRequired(I)) {
5294 unsigned IID = I->getOpcode() == Instruction::Load
5295 ? Intrinsic::masked_load
5296 : Intrinsic::masked_store;
5297 Cost += TTI.getMemIntrinsicInstrCost(
5298 MemIntrinsicCostAttributes(IID, VectorTy, Alignment, AS), CostKind);
5299 } else {
5300 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5301 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
5302 CostKind, OpInfo, I);
5303 }
5304
5305 bool Reverse = ConsecutiveStride < 0;
5306 if (Reverse)
5307 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
5308 VectorTy, {}, CostKind, 0);
5309 return Cost;
5310}
5311
5313LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
5314 ElementCount VF) {
5315 assert(Legal->isUniformMemOp(*I, VF));
5316
5317 Type *ValTy = getLoadStoreType(I);
5319 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5320 const Align Alignment = getLoadStoreAlignment(I);
5321 unsigned AS = getLoadStoreAddressSpace(I);
5322 if (isa<LoadInst>(I)) {
5323 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5324 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
5325 CostKind) +
5326 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy,
5327 VectorTy, {}, CostKind);
5328 }
5329 StoreInst *SI = cast<StoreInst>(I);
5330
5331 bool IsLoopInvariantStoreValue = Legal->isInvariant(SI->getValueOperand());
5332 // TODO: We have existing tests that request the cost of extracting element
5333 // VF.getKnownMinValue() - 1 from a scalable vector. This does not represent
5334 // the actual generated code, which involves extracting the last element of
5335 // a scalable vector where the lane to extract is unknown at compile time.
5337 TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5338 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS, CostKind);
5339 if (!IsLoopInvariantStoreValue)
5340 Cost += TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
5341 VectorTy, CostKind, 0);
5342 return Cost;
5343}
5344
5346LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
5347 ElementCount VF) {
5348 Type *ValTy = getLoadStoreType(I);
5349 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5350 const Align Alignment = getLoadStoreAlignment(I);
5352 Type *PtrTy = Ptr->getType();
5353
5354 if (!Legal->isUniform(Ptr, VF))
5355 PtrTy = toVectorTy(PtrTy, VF);
5356
5357 unsigned IID = I->getOpcode() == Instruction::Load
5358 ? Intrinsic::masked_gather
5359 : Intrinsic::masked_scatter;
5360 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5361 TTI.getMemIntrinsicInstrCost(
5362 MemIntrinsicCostAttributes(IID, VectorTy, Ptr, isMaskRequired(I),
5363 Alignment, I),
5364 CostKind);
5365}
5366
5368LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
5369 ElementCount VF) {
5370 const auto *Group = getInterleavedAccessGroup(I);
5371 assert(Group && "Fail to get an interleaved access group.");
5372
5373 Instruction *InsertPos = Group->getInsertPos();
5374 Type *ValTy = getLoadStoreType(InsertPos);
5375 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5376 unsigned AS = getLoadStoreAddressSpace(InsertPos);
5377
5378 unsigned InterleaveFactor = Group->getFactor();
5379 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5380
5381 // Holds the indices of existing members in the interleaved group.
5382 SmallVector<unsigned, 4> Indices;
5383 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5384 if (Group->getMember(IF))
5385 Indices.push_back(IF);
5386
5387 // Calculate the cost of the whole interleaved group.
5388 bool UseMaskForGaps =
5389 (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
5390 (isa<StoreInst>(I) && !Group->isFull());
5391 InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
5392 InsertPos->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5393 Group->getAlign(), AS, CostKind, isMaskRequired(I), UseMaskForGaps);
5394
5395 if (Group->isReverse()) {
5396 // TODO: Add support for reversed masked interleaved access.
5398 "Reverse masked interleaved access not supported.");
5399 Cost += Group->getNumMembers() *
5400 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
5401 VectorTy, {}, CostKind, 0);
5402 }
5403 return Cost;
5404}
5405
5406std::optional<InstructionCost>
5408 ElementCount VF,
5409 Type *Ty) const {
5410 using namespace llvm::PatternMatch;
5411 // Early exit for no inloop reductions
5412 if (InLoopReductions.empty() || VF.isScalar() || !isa<VectorType>(Ty))
5413 return std::nullopt;
5414 auto *VectorTy = cast<VectorType>(Ty);
5415
5416 // We are looking for a pattern of, and finding the minimal acceptable cost:
5417 // reduce(mul(ext(A), ext(B))) or
5418 // reduce(mul(A, B)) or
5419 // reduce(ext(A)) or
5420 // reduce(A).
5421 // The basic idea is that we walk down the tree to do that, finding the root
5422 // reduction instruction in InLoopReductionImmediateChains. From there we find
5423 // the pattern of mul/ext and test the cost of the entire pattern vs the cost
5424 // of the components. If the reduction cost is lower then we return it for the
5425 // reduction instruction and 0 for the other instructions in the pattern. If
5426 // it is not we return an invalid cost specifying the orignal cost method
5427 // should be used.
5428 Instruction *RetI = I;
5429 if (match(RetI, m_ZExtOrSExt(m_Value()))) {
5430 if (!RetI->hasOneUser())
5431 return std::nullopt;
5432 RetI = RetI->user_back();
5433 }
5434
5435 if (match(RetI, m_OneUse(m_Mul(m_Value(), m_Value()))) &&
5436 RetI->user_back()->getOpcode() == Instruction::Add) {
5437 RetI = RetI->user_back();
5438 }
5439
5440 // Test if the found instruction is a reduction, and if not return an invalid
5441 // cost specifying the parent to use the original cost modelling.
5442 Instruction *LastChain = InLoopReductionImmediateChains.lookup(RetI);
5443 if (!LastChain)
5444 return std::nullopt;
5445
5446 // Find the reduction this chain is a part of and calculate the basic cost of
5447 // the reduction on its own.
5448 Instruction *ReductionPhi = LastChain;
5449 while (!isa<PHINode>(ReductionPhi))
5450 ReductionPhi = InLoopReductionImmediateChains.at(ReductionPhi);
5451
5452 const RecurrenceDescriptor &RdxDesc =
5453 Legal->getRecurrenceDescriptor(cast<PHINode>(ReductionPhi));
5454
5455 InstructionCost BaseCost;
5456 RecurKind RK = RdxDesc.getRecurrenceKind();
5459 BaseCost = TTI.getMinMaxReductionCost(MinMaxID, VectorTy,
5460 RdxDesc.getFastMathFlags(), CostKind);
5461 } else {
5462 BaseCost = TTI.getArithmeticReductionCost(
5463 RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
5464 }
5465
5466 // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
5467 // normal fmul instruction to the cost of the fadd reduction.
5468 if (RK == RecurKind::FMulAdd)
5469 BaseCost +=
5470 TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
5471
5472 // If we're using ordered reductions then we can just return the base cost
5473 // here, since getArithmeticReductionCost calculates the full ordered
5474 // reduction cost when FP reassociation is not allowed.
5475 if (useOrderedReductions(RdxDesc))
5476 return BaseCost;
5477
5478 // Get the operand that was not the reduction chain and match it to one of the
5479 // patterns, returning the better cost if it is found.
5480 Instruction *RedOp = RetI->getOperand(1) == LastChain
5483
5484 VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
5485
5486 Instruction *Op0, *Op1;
5487 if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5488 match(RedOp,
5490 match(Op0, m_ZExtOrSExt(m_Value())) &&
5491 Op0->getOpcode() == Op1->getOpcode() &&
5492 Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
5493 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
5494 (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
5495
5496 // Matched reduce.add(ext(mul(ext(A), ext(B)))
5497 // Note that the extend opcodes need to all match, or if A==B they will have
5498 // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
5499 // which is equally fine.
5500 bool IsUnsigned = isa<ZExtInst>(Op0);
5501 auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
5502 auto *MulType = VectorType::get(Op0->getType(), VectorTy);
5503
5504 InstructionCost ExtCost =
5505 TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
5507 InstructionCost MulCost =
5508 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
5509 InstructionCost Ext2Cost =
5510 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
5512
5513 InstructionCost RedCost = TTI.getMulAccReductionCost(
5514 IsUnsigned, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), ExtType,
5515 CostKind);
5516
5517 if (RedCost.isValid() &&
5518 RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
5519 return I == RetI ? RedCost : 0;
5520 } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
5521 !TheLoop->isLoopInvariant(RedOp)) {
5522 // Matched reduce(ext(A))
5523 bool IsUnsigned = isa<ZExtInst>(RedOp);
5524 auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
5525 InstructionCost RedCost = TTI.getExtendedReductionCost(
5526 RdxDesc.getOpcode(), IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
5527 RdxDesc.getFastMathFlags(), CostKind);
5528
5529 InstructionCost ExtCost =
5530 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
5532 if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
5533 return I == RetI ? RedCost : 0;
5534 } else if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5535 match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
5536 if (match(Op0, m_ZExtOrSExt(m_Value())) &&
5537 Op0->getOpcode() == Op1->getOpcode() &&
5538 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
5539 bool IsUnsigned = isa<ZExtInst>(Op0);
5540 Type *Op0Ty = Op0->getOperand(0)->getType();
5541 Type *Op1Ty = Op1->getOperand(0)->getType();
5542 Type *LargestOpTy =
5543 Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
5544 : Op0Ty;
5545 auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
5546
5547 // Matched reduce.add(mul(ext(A), ext(B))), where the two ext may be of
5548 // different sizes. We take the largest type as the ext to reduce, and add
5549 // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
5550 InstructionCost ExtCost0 = TTI.getCastInstrCost(
5551 Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
5553 InstructionCost ExtCost1 = TTI.getCastInstrCost(
5554 Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
5556 InstructionCost MulCost =
5557 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5558
5559 InstructionCost RedCost = TTI.getMulAccReductionCost(
5560 IsUnsigned, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), ExtType,
5561 CostKind);
5562 InstructionCost ExtraExtCost = 0;
5563 if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
5564 Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
5565 ExtraExtCost = TTI.getCastInstrCost(
5566 ExtraExtOp->getOpcode(), ExtType,
5567 VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
5569 }
5570
5571 if (RedCost.isValid() &&
5572 (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
5573 return I == RetI ? RedCost : 0;
5574 } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
5575 // Matched reduce.add(mul())
5576 InstructionCost MulCost =
5577 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5578
5579 InstructionCost RedCost = TTI.getMulAccReductionCost(
5580 true, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), VectorTy,
5581 CostKind);
5582
5583 if (RedCost.isValid() && RedCost < MulCost + BaseCost)
5584 return I == RetI ? RedCost : 0;
5585 }
5586 }
5587
5588 return I == RetI ? std::optional<InstructionCost>(BaseCost) : std::nullopt;
5589}
5590
5592LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
5593 ElementCount VF) {
5594 // Calculate scalar cost only. Vectorization cost should be ready at this
5595 // moment.
5596 if (VF.isScalar()) {
5597 Type *ValTy = getLoadStoreType(I);
5599 const Align Alignment = getLoadStoreAlignment(I);
5600 unsigned AS = getLoadStoreAddressSpace(I);
5601
5602 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5603 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5604 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, CostKind,
5605 OpInfo, I);
5606 }
5607 return getWideningCost(I, VF);
5608}
5609
5611LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
5612 ElementCount VF) const {
5613
5614 // There is no mechanism yet to create a scalable scalarization loop,
5615 // so this is currently Invalid.
5616 if (VF.isScalable())
5618
5619 if (VF.isScalar())
5620 return 0;
5621
5623 Type *RetTy = toVectorizedTy(I->getType(), VF);
5624 if (!RetTy->isVoidTy() &&
5625 (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore())) {
5626
5628 if (isa<LoadInst>(I))
5630 else if (isa<StoreInst>(I))
5632
5633 for (Type *VectorTy : getContainedTypes(RetTy)) {
5634 Cost += TTI.getScalarizationOverhead(
5636 /*Insert=*/true, /*Extract=*/false, CostKind,
5637 /*ForPoisonSrc=*/true, {}, VIC);
5638 }
5639 }
5640
5641 // Some targets keep addresses scalar.
5642 if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
5643 return Cost;
5644
5645 // Some targets support efficient element stores.
5646 if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
5647 return Cost;
5648
5649 // Collect operands to consider.
5650 CallInst *CI = dyn_cast<CallInst>(I);
5651 Instruction::op_range Ops = CI ? CI->args() : I->operands();
5652
5653 // Skip operands that do not require extraction/scalarization and do not incur
5654 // any overhead.
5656 for (auto *V : filterExtractingOperands(Ops, VF))
5657 Tys.push_back(maybeVectorizeType(V->getType(), VF));
5658
5662 return Cost + TTI.getOperandsScalarizationOverhead(Tys, CostKind, OperandVIC);
5663}
5664
5666 if (VF.isScalar())
5667 return;
5668 NumPredStores = 0;
5669 for (BasicBlock *BB : TheLoop->blocks()) {
5670 // For each instruction in the old loop.
5671 for (Instruction &I : *BB) {
5673 if (!Ptr)
5674 continue;
5675
5676 // TODO: We should generate better code and update the cost model for
5677 // predicated uniform stores. Today they are treated as any other
5678 // predicated store (see added test cases in
5679 // invariant-store-vectorization.ll).
5681 NumPredStores++;
5682
5683 if (Legal->isUniformMemOp(I, VF)) {
5684 auto IsLegalToScalarize = [&]() {
5685 if (!VF.isScalable())
5686 // Scalarization of fixed length vectors "just works".
5687 return true;
5688
5689 // We have dedicated lowering for unpredicated uniform loads and
5690 // stores. Note that even with tail folding we know that at least
5691 // one lane is active (i.e. generalized predication is not possible
5692 // here), and the logic below depends on this fact.
5693 if (!foldTailByMasking())
5694 return true;
5695
5696 // For scalable vectors, a uniform memop load is always
5697 // uniform-by-parts and we know how to scalarize that.
5698 if (isa<LoadInst>(I))
5699 return true;
5700
5701 // A uniform store isn't neccessarily uniform-by-part
5702 // and we can't assume scalarization.
5703 auto &SI = cast<StoreInst>(I);
5704 return TheLoop->isLoopInvariant(SI.getValueOperand());
5705 };
5706
5707 const InstructionCost GatherScatterCost =
5709 getGatherScatterCost(&I, VF) : InstructionCost::getInvalid();
5710
5711 // Load: Scalar load + broadcast
5712 // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
5713 // FIXME: This cost is a significant under-estimate for tail folded
5714 // memory ops.
5715 const InstructionCost ScalarizationCost =
5716 IsLegalToScalarize() ? getUniformMemOpCost(&I, VF)
5718
5719 // Choose better solution for the current VF, Note that Invalid
5720 // costs compare as maximumal large. If both are invalid, we get
5721 // scalable invalid which signals a failure and a vectorization abort.
5722 if (GatherScatterCost < ScalarizationCost)
5723 setWideningDecision(&I, VF, CM_GatherScatter, GatherScatterCost);
5724 else
5725 setWideningDecision(&I, VF, CM_Scalarize, ScalarizationCost);
5726 continue;
5727 }
5728
5729 // We assume that widening is the best solution when possible.
5730 if (memoryInstructionCanBeWidened(&I, VF)) {
5731 InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
5732 int ConsecutiveStride = Legal->isConsecutivePtr(
5734 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5735 "Expected consecutive stride.");
5736 InstWidening Decision =
5737 ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
5738 setWideningDecision(&I, VF, Decision, Cost);
5739 continue;
5740 }
5741
5742 // Choose between Interleaving, Gather/Scatter or Scalarization.
5744 unsigned NumAccesses = 1;
5745 if (isAccessInterleaved(&I)) {
5746 const auto *Group = getInterleavedAccessGroup(&I);
5747 assert(Group && "Fail to get an interleaved access group.");
5748
5749 // Make one decision for the whole group.
5750 if (getWideningDecision(&I, VF) != CM_Unknown)
5751 continue;
5752
5753 NumAccesses = Group->getNumMembers();
5755 InterleaveCost = getInterleaveGroupCost(&I, VF);
5756 }
5757
5758 InstructionCost GatherScatterCost =
5760 ? getGatherScatterCost(&I, VF) * NumAccesses
5762
5763 InstructionCost ScalarizationCost =
5764 getMemInstScalarizationCost(&I, VF) * NumAccesses;
5765
5766 // Choose better solution for the current VF,
5767 // write down this decision and use it during vectorization.
5769 InstWidening Decision;
5770 if (InterleaveCost <= GatherScatterCost &&
5771 InterleaveCost < ScalarizationCost) {
5772 Decision = CM_Interleave;
5773 Cost = InterleaveCost;
5774 } else if (GatherScatterCost < ScalarizationCost) {
5775 Decision = CM_GatherScatter;
5776 Cost = GatherScatterCost;
5777 } else {
5778 Decision = CM_Scalarize;
5779 Cost = ScalarizationCost;
5780 }
5781 // If the instructions belongs to an interleave group, the whole group
5782 // receives the same decision. The whole group receives the cost, but
5783 // the cost will actually be assigned to one instruction.
5784 if (const auto *Group = getInterleavedAccessGroup(&I)) {
5785 if (Decision == CM_Scalarize) {
5786 for (unsigned Idx = 0; Idx < Group->getFactor(); ++Idx) {
5787 if (auto *I = Group->getMember(Idx)) {
5788 setWideningDecision(I, VF, Decision,
5789 getMemInstScalarizationCost(I, VF));
5790 }
5791 }
5792 } else {
5793 setWideningDecision(Group, VF, Decision, Cost);
5794 }
5795 } else
5796 setWideningDecision(&I, VF, Decision, Cost);
5797 }
5798 }
5799
5800 // Make sure that any load of address and any other address computation
5801 // remains scalar unless there is gather/scatter support. This avoids
5802 // inevitable extracts into address registers, and also has the benefit of
5803 // activating LSR more, since that pass can't optimize vectorized
5804 // addresses.
5805 if (TTI.prefersVectorizedAddressing())
5806 return;
5807
5808 // Start with all scalar pointer uses.
5810 for (BasicBlock *BB : TheLoop->blocks())
5811 for (Instruction &I : *BB) {
5812 Instruction *PtrDef =
5814 if (PtrDef && TheLoop->contains(PtrDef) &&
5816 AddrDefs.insert(PtrDef);
5817 }
5818
5819 // Add all instructions used to generate the addresses.
5821 append_range(Worklist, AddrDefs);
5822 while (!Worklist.empty()) {
5823 Instruction *I = Worklist.pop_back_val();
5824 for (auto &Op : I->operands())
5825 if (auto *InstOp = dyn_cast<Instruction>(Op))
5826 if (TheLoop->contains(InstOp) && !isa<PHINode>(InstOp) &&
5827 AddrDefs.insert(InstOp).second)
5828 Worklist.push_back(InstOp);
5829 }
5830
5831 auto UpdateMemOpUserCost = [this, VF](LoadInst *LI) {
5832 // If there are direct memory op users of the newly scalarized load,
5833 // their cost may have changed because there's no scalarization
5834 // overhead for the operand. Update it.
5835 for (User *U : LI->users()) {
5837 continue;
5839 continue;
5842 getMemInstScalarizationCost(cast<Instruction>(U), VF));
5843 }
5844 };
5845 for (auto *I : AddrDefs) {
5846 if (isa<LoadInst>(I)) {
5847 // Setting the desired widening decision should ideally be handled in
5848 // by cost functions, but since this involves the task of finding out
5849 // if the loaded register is involved in an address computation, it is
5850 // instead changed here when we know this is the case.
5851 InstWidening Decision = getWideningDecision(I, VF);
5852 if (!isPredicatedInst(I) &&
5853 (Decision == CM_Widen || Decision == CM_Widen_Reverse ||
5854 (!Legal->isUniformMemOp(*I, VF) && Decision == CM_Scalarize))) {
5855 // Scalarize a widened load of address or update the cost of a scalar
5856 // load of an address.
5858 I, VF, CM_Scalarize,
5859 (VF.getKnownMinValue() *
5860 getMemoryInstructionCost(I, ElementCount::getFixed(1))));
5861 UpdateMemOpUserCost(cast<LoadInst>(I));
5862 } else if (const auto *Group = getInterleavedAccessGroup(I)) {
5863 // Scalarize all members of this interleaved group when any member
5864 // is used as an address. The address-used load skips scalarization
5865 // overhead, other members include it.
5866 for (unsigned Idx = 0; Idx < Group->getFactor(); ++Idx) {
5867 if (Instruction *Member = Group->getMember(Idx)) {
5869 AddrDefs.contains(Member)
5870 ? (VF.getKnownMinValue() *
5871 getMemoryInstructionCost(Member,
5873 : getMemInstScalarizationCost(Member, VF);
5875 UpdateMemOpUserCost(cast<LoadInst>(Member));
5876 }
5877 }
5878 }
5879 } else {
5880 // Cannot scalarize fixed-order recurrence phis at the moment.
5881 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
5882 continue;
5883
5884 // Make sure I gets scalarized and a cost estimate without
5885 // scalarization overhead.
5886 ForcedScalars[VF].insert(I);
5887 }
5888 }
5889}
5890
5892 assert(!VF.isScalar() &&
5893 "Trying to set a vectorization decision for a scalar VF");
5894
5895 auto ForcedScalar = ForcedScalars.find(VF);
5896 for (BasicBlock *BB : TheLoop->blocks()) {
5897 // For each instruction in the old loop.
5898 for (Instruction &I : *BB) {
5900
5901 if (!CI)
5902 continue;
5903
5907 Function *ScalarFunc = CI->getCalledFunction();
5908 Type *ScalarRetTy = CI->getType();
5909 SmallVector<Type *, 4> Tys, ScalarTys;
5910 for (auto &ArgOp : CI->args())
5911 ScalarTys.push_back(ArgOp->getType());
5912
5913 // Estimate cost of scalarized vector call. The source operands are
5914 // assumed to be vectors, so we need to extract individual elements from
5915 // there, execute VF scalar calls, and then gather the result into the
5916 // vector return value.
5917 if (VF.isFixed()) {
5918 InstructionCost ScalarCallCost =
5919 TTI.getCallInstrCost(ScalarFunc, ScalarRetTy, ScalarTys, CostKind);
5920
5921 // Compute costs of unpacking argument values for the scalar calls and
5922 // packing the return values to a vector.
5923 InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
5924 ScalarCost = ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
5925 } else {
5926 // There is no point attempting to calculate the scalar cost for a
5927 // scalable VF as we know it will be Invalid.
5928 assert(!getScalarizationOverhead(CI, VF).isValid() &&
5929 "Unexpected valid cost for scalarizing scalable vectors");
5930 ScalarCost = InstructionCost::getInvalid();
5931 }
5932
5933 // Honor ForcedScalars and UniformAfterVectorization decisions.
5934 // TODO: For calls, it might still be more profitable to widen. Use
5935 // VPlan-based cost model to compare different options.
5936 if (VF.isVector() && ((ForcedScalar != ForcedScalars.end() &&
5937 ForcedScalar->second.contains(CI)) ||
5938 isUniformAfterVectorization(CI, VF))) {
5939 setCallWideningDecision(CI, VF, CM_Scalarize, nullptr,
5940 Intrinsic::not_intrinsic, std::nullopt,
5941 ScalarCost);
5942 continue;
5943 }
5944
5945 bool MaskRequired = isMaskRequired(CI);
5946 // Compute corresponding vector type for return value and arguments.
5947 Type *RetTy = toVectorizedTy(ScalarRetTy, VF);
5948 for (Type *ScalarTy : ScalarTys)
5949 Tys.push_back(toVectorizedTy(ScalarTy, VF));
5950
5951 // An in-loop reduction using an fmuladd intrinsic is a special case;
5952 // we don't want the normal cost for that intrinsic.
5954 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy)) {
5957 std::nullopt, *RedCost);
5958 continue;
5959 }
5960
5961 // Find the cost of vectorizing the call, if we can find a suitable
5962 // vector variant of the function.
5963 VFInfo FuncInfo;
5964 Function *VecFunc = nullptr;
5965 // Search through any available variants for one we can use at this VF.
5966 for (VFInfo &Info : VFDatabase::getMappings(*CI)) {
5967 // Must match requested VF.
5968 if (Info.Shape.VF != VF)
5969 continue;
5970
5971 // Must take a mask argument if one is required
5972 if (MaskRequired && !Info.isMasked())
5973 continue;
5974
5975 // Check that all parameter kinds are supported
5976 bool ParamsOk = true;
5977 for (VFParameter Param : Info.Shape.Parameters) {
5978 switch (Param.ParamKind) {
5980 break;
5982 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5983 // Make sure the scalar parameter in the loop is invariant.
5984 if (!PSE.getSE()->isLoopInvariant(PSE.getSCEV(ScalarParam),
5985 TheLoop))
5986 ParamsOk = false;
5987 break;
5988 }
5990 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5991 // Find the stride for the scalar parameter in this loop and see if
5992 // it matches the stride for the variant.
5993 // TODO: do we need to figure out the cost of an extract to get the
5994 // first lane? Or do we hope that it will be folded away?
5995 ScalarEvolution *SE = PSE.getSE();
5996 if (!match(SE->getSCEV(ScalarParam),
5998 m_SCEV(), m_scev_SpecificSInt(Param.LinearStepOrPos),
6000 ParamsOk = false;
6001 break;
6002 }
6004 break;
6005 default:
6006 ParamsOk = false;
6007 break;
6008 }
6009 }
6010
6011 if (!ParamsOk)
6012 continue;
6013
6014 // Found a suitable candidate, stop here.
6015 VecFunc = CI->getModule()->getFunction(Info.VectorName);
6016 FuncInfo = Info;
6017 break;
6018 }
6019
6020 if (TLI && VecFunc && !CI->isNoBuiltin())
6021 VectorCost = TTI.getCallInstrCost(nullptr, RetTy, Tys, CostKind);
6022
6023 // Find the cost of an intrinsic; some targets may have instructions that
6024 // perform the operation without needing an actual call.
6026 if (IID != Intrinsic::not_intrinsic)
6028
6029 InstructionCost Cost = ScalarCost;
6030 InstWidening Decision = CM_Scalarize;
6031
6032 if (VectorCost.isValid() && VectorCost <= Cost) {
6033 Cost = VectorCost;
6034 Decision = CM_VectorCall;
6035 }
6036
6037 if (IntrinsicCost.isValid() && IntrinsicCost <= Cost) {
6039 Decision = CM_IntrinsicCall;
6040 }
6041
6042 setCallWideningDecision(CI, VF, Decision, VecFunc, IID,
6044 }
6045 }
6046}
6047
6049 if (!Legal->isInvariant(Op))
6050 return false;
6051 // Consider Op invariant, if it or its operands aren't predicated
6052 // instruction in the loop. In that case, it is not trivially hoistable.
6053 auto *OpI = dyn_cast<Instruction>(Op);
6054 return !OpI || !TheLoop->contains(OpI) ||
6055 (!isPredicatedInst(OpI) &&
6056 (!isa<PHINode>(OpI) || OpI->getParent() != TheLoop->getHeader()) &&
6057 all_of(OpI->operands(),
6058 [this](Value *Op) { return shouldConsiderInvariant(Op); }));
6059}
6060
6063 ElementCount VF) {
6064 // If we know that this instruction will remain uniform, check the cost of
6065 // the scalar version.
6067 VF = ElementCount::getFixed(1);
6068
6069 if (VF.isVector() && isProfitableToScalarize(I, VF))
6070 return InstsToScalarize[VF][I];
6071
6072 // Forced scalars do not have any scalarization overhead.
6073 auto ForcedScalar = ForcedScalars.find(VF);
6074 if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6075 auto InstSet = ForcedScalar->second;
6076 if (InstSet.count(I))
6078 VF.getKnownMinValue();
6079 }
6080
6081 Type *RetTy = I->getType();
6083 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6084 auto *SE = PSE.getSE();
6085
6086 Type *VectorTy;
6087 if (isScalarAfterVectorization(I, VF)) {
6088 [[maybe_unused]] auto HasSingleCopyAfterVectorization =
6089 [this](Instruction *I, ElementCount VF) -> bool {
6090 if (VF.isScalar())
6091 return true;
6092
6093 auto Scalarized = InstsToScalarize.find(VF);
6094 assert(Scalarized != InstsToScalarize.end() &&
6095 "VF not yet analyzed for scalarization profitability");
6096 return !Scalarized->second.count(I) &&
6097 llvm::all_of(I->users(), [&](User *U) {
6098 auto *UI = cast<Instruction>(U);
6099 return !Scalarized->second.count(UI);
6100 });
6101 };
6102
6103 // With the exception of GEPs and PHIs, after scalarization there should
6104 // only be one copy of the instruction generated in the loop. This is
6105 // because the VF is either 1, or any instructions that need scalarizing
6106 // have already been dealt with by the time we get here. As a result,
6107 // it means we don't have to multiply the instruction cost by VF.
6108 assert(I->getOpcode() == Instruction::GetElementPtr ||
6109 I->getOpcode() == Instruction::PHI ||
6110 (I->getOpcode() == Instruction::BitCast &&
6111 I->getType()->isPointerTy()) ||
6112 HasSingleCopyAfterVectorization(I, VF));
6113 VectorTy = RetTy;
6114 } else
6115 VectorTy = toVectorizedTy(RetTy, VF);
6116
6117 if (VF.isVector() && VectorTy->isVectorTy() &&
6118 !TTI.getNumberOfParts(VectorTy))
6120
6121 // TODO: We need to estimate the cost of intrinsic calls.
6122 switch (I->getOpcode()) {
6123 case Instruction::GetElementPtr:
6124 // We mark this instruction as zero-cost because the cost of GEPs in
6125 // vectorized code depends on whether the corresponding memory instruction
6126 // is scalarized or not. Therefore, we handle GEPs with the memory
6127 // instruction cost.
6128 return 0;
6129 case Instruction::UncondBr:
6130 case Instruction::CondBr: {
6131 // In cases of scalarized and predicated instructions, there will be VF
6132 // predicated blocks in the vectorized loop. Each branch around these
6133 // blocks requires also an extract of its vector compare i1 element.
6134 // Note that the conditional branch from the loop latch will be replaced by
6135 // a single branch controlling the loop, so there is no extra overhead from
6136 // scalarization.
6137 bool ScalarPredicatedBB = false;
6139 if (VF.isVector() && BI &&
6140 (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
6141 PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))) &&
6142 BI->getParent() != TheLoop->getLoopLatch())
6143 ScalarPredicatedBB = true;
6144
6145 if (ScalarPredicatedBB) {
6146 // Not possible to scalarize scalable vector with predicated instructions.
6147 if (VF.isScalable())
6149 // Return cost for branches around scalarized and predicated blocks.
6150 auto *VecI1Ty =
6152 return (TTI.getScalarizationOverhead(
6153 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
6154 /*Insert*/ false, /*Extract*/ true, CostKind) +
6155 (TTI.getCFInstrCost(Instruction::CondBr, CostKind) *
6156 VF.getFixedValue()));
6157 }
6158
6159 if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6160 // The back-edge branch will remain, as will all scalar branches.
6161 return TTI.getCFInstrCost(Instruction::UncondBr, CostKind);
6162
6163 // This branch will be eliminated by if-conversion.
6164 return 0;
6165 // Note: We currently assume zero cost for an unconditional branch inside
6166 // a predicated block since it will become a fall-through, although we
6167 // may decide in the future to call TTI for all branches.
6168 }
6169 case Instruction::Switch: {
6170 if (VF.isScalar())
6171 return TTI.getCFInstrCost(Instruction::Switch, CostKind);
6172 auto *Switch = cast<SwitchInst>(I);
6173 return Switch->getNumCases() *
6174 TTI.getCmpSelInstrCost(
6175 Instruction::ICmp,
6176 toVectorTy(Switch->getCondition()->getType(), VF),
6177 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
6179 }
6180 case Instruction::PHI: {
6181 auto *Phi = cast<PHINode>(I);
6182
6183 // First-order recurrences are replaced by vector shuffles inside the loop.
6184 if (VF.isVector() && Legal->isFixedOrderRecurrence(Phi)) {
6186 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
6187 return TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
6188 cast<VectorType>(VectorTy),
6189 cast<VectorType>(VectorTy), Mask, CostKind,
6190 VF.getKnownMinValue() - 1);
6191 }
6192
6193 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
6194 // converted into select instructions. We require N - 1 selects per phi
6195 // node, where N is the number of incoming values.
6196 if (VF.isVector() && Phi->getParent() != TheLoop->getHeader()) {
6197 Type *ResultTy = Phi->getType();
6198
6199 // All instructions in an Any-of reduction chain are narrowed to bool.
6200 // Check if that is the case for this phi node.
6201 auto *HeaderUser = cast_if_present<PHINode>(
6202 find_singleton<User>(Phi->users(), [this](User *U, bool) -> User * {
6203 auto *Phi = dyn_cast<PHINode>(U);
6204 if (Phi && Phi->getParent() == TheLoop->getHeader())
6205 return Phi;
6206 return nullptr;
6207 }));
6208 if (HeaderUser) {
6209 auto &ReductionVars = Legal->getReductionVars();
6210 auto Iter = ReductionVars.find(HeaderUser);
6211 if (Iter != ReductionVars.end() &&
6213 Iter->second.getRecurrenceKind()))
6214 ResultTy = Type::getInt1Ty(Phi->getContext());
6215 }
6216 return (Phi->getNumIncomingValues() - 1) *
6217 TTI.getCmpSelInstrCost(
6218 Instruction::Select, toVectorTy(ResultTy, VF),
6219 toVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
6221 }
6222
6223 // When tail folding with EVL, if the phi is part of an out of loop
6224 // reduction then it will be transformed into a wide vp_merge.
6225 if (VF.isVector() && foldTailWithEVL() &&
6226 Legal->getReductionVars().contains(Phi) && !isInLoopReduction(Phi)) {
6228 Intrinsic::vp_merge, toVectorTy(Phi->getType(), VF),
6229 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
6230 return TTI.getIntrinsicInstrCost(ICA, CostKind);
6231 }
6232
6233 return TTI.getCFInstrCost(Instruction::PHI, CostKind);
6234 }
6235 case Instruction::UDiv:
6236 case Instruction::SDiv:
6237 case Instruction::URem:
6238 case Instruction::SRem:
6239 if (VF.isVector() && isPredicatedInst(I)) {
6240 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
6241 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost) ?
6242 ScalarCost : SafeDivisorCost;
6243 }
6244 // We've proven all lanes safe to speculate, fall through.
6245 [[fallthrough]];
6246 case Instruction::Add:
6247 case Instruction::Sub: {
6248 auto Info = Legal->getHistogramInfo(I);
6249 if (Info && VF.isVector()) {
6250 const HistogramInfo *HGram = Info.value();
6251 // Assume that a non-constant update value (or a constant != 1) requires
6252 // a multiply, and add that into the cost.
6254 ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1));
6255 if (!RHS || RHS->getZExtValue() != 1)
6256 MulCost =
6257 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6258
6259 // Find the cost of the histogram operation itself.
6260 Type *PtrTy = VectorType::get(HGram->Load->getPointerOperandType(), VF);
6261 Type *ScalarTy = I->getType();
6262 Type *MaskTy = VectorType::get(Type::getInt1Ty(I->getContext()), VF);
6263 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
6264 Type::getVoidTy(I->getContext()),
6265 {PtrTy, ScalarTy, MaskTy});
6266
6267 // Add the costs together with the add/sub operation.
6268 return TTI.getIntrinsicInstrCost(ICA, CostKind) + MulCost +
6269 TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, CostKind);
6270 }
6271 [[fallthrough]];
6272 }
6273 case Instruction::FAdd:
6274 case Instruction::FSub:
6275 case Instruction::Mul:
6276 case Instruction::FMul:
6277 case Instruction::FDiv:
6278 case Instruction::FRem:
6279 case Instruction::Shl:
6280 case Instruction::LShr:
6281 case Instruction::AShr:
6282 case Instruction::And:
6283 case Instruction::Or:
6284 case Instruction::Xor: {
6285 // If we're speculating on the stride being 1, the multiplication may
6286 // fold away. We can generalize this for all operations using the notion
6287 // of neutral elements. (TODO)
6288 if (I->getOpcode() == Instruction::Mul &&
6289 ((TheLoop->isLoopInvariant(I->getOperand(0)) &&
6290 PSE.getSCEV(I->getOperand(0))->isOne()) ||
6291 (TheLoop->isLoopInvariant(I->getOperand(1)) &&
6292 PSE.getSCEV(I->getOperand(1))->isOne())))
6293 return 0;
6294
6295 // Detect reduction patterns
6296 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6297 return *RedCost;
6298
6299 // Certain instructions can be cheaper to vectorize if they have a constant
6300 // second vector operand. One example of this are shifts on x86.
6301 Value *Op2 = I->getOperand(1);
6302 if (!isa<Constant>(Op2) && TheLoop->isLoopInvariant(Op2) &&
6303 PSE.getSE()->isSCEVable(Op2->getType()) &&
6304 isa<SCEVConstant>(PSE.getSCEV(Op2))) {
6305 Op2 = cast<SCEVConstant>(PSE.getSCEV(Op2))->getValue();
6306 }
6307 auto Op2Info = TTI.getOperandInfo(Op2);
6308 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
6311
6312 SmallVector<const Value *, 4> Operands(I->operand_values());
6313 return TTI.getArithmeticInstrCost(
6314 I->getOpcode(), VectorTy, CostKind,
6315 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6316 Op2Info, Operands, I, TLI);
6317 }
6318 case Instruction::FNeg: {
6319 return TTI.getArithmeticInstrCost(
6320 I->getOpcode(), VectorTy, CostKind,
6321 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6322 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6323 I->getOperand(0), I);
6324 }
6325 case Instruction::Select: {
6327 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6328 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6329
6330 const Value *Op0, *Op1;
6331 using namespace llvm::PatternMatch;
6332 if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
6333 match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
6334 // select x, y, false --> x & y
6335 // select x, true, y --> x | y
6336 const auto [Op1VK, Op1VP] = TTI::getOperandInfo(Op0);
6337 const auto [Op2VK, Op2VP] = TTI::getOperandInfo(Op1);
6338 assert(Op0->getType()->getScalarSizeInBits() == 1 &&
6339 Op1->getType()->getScalarSizeInBits() == 1);
6340
6341 return TTI.getArithmeticInstrCost(
6342 match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And,
6343 VectorTy, CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, {Op0, Op1}, I);
6344 }
6345
6346 Type *CondTy = SI->getCondition()->getType();
6347 if (!ScalarCond)
6348 CondTy = VectorType::get(CondTy, VF);
6349
6351 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
6352 Pred = Cmp->getPredicate();
6353 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
6354 CostKind, {TTI::OK_AnyValue, TTI::OP_None},
6355 {TTI::OK_AnyValue, TTI::OP_None}, I);
6356 }
6357 case Instruction::ICmp:
6358 case Instruction::FCmp: {
6359 Type *ValTy = I->getOperand(0)->getType();
6360
6362 [[maybe_unused]] Instruction *Op0AsInstruction =
6363 dyn_cast<Instruction>(I->getOperand(0));
6364 assert((!canTruncateToMinimalBitwidth(Op0AsInstruction, VF) ||
6365 MinBWs[I] == MinBWs[Op0AsInstruction]) &&
6366 "if both the operand and the compare are marked for "
6367 "truncation, they must have the same bitwidth");
6368 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[I]);
6369 }
6370
6371 VectorTy = toVectorTy(ValTy, VF);
6372 return TTI.getCmpSelInstrCost(
6373 I->getOpcode(), VectorTy, CmpInst::makeCmpResultType(VectorTy),
6374 cast<CmpInst>(I)->getPredicate(), CostKind,
6375 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
6376 }
6377 case Instruction::Store:
6378 case Instruction::Load: {
6379 ElementCount Width = VF;
6380 if (Width.isVector()) {
6381 InstWidening Decision = getWideningDecision(I, Width);
6382 assert(Decision != CM_Unknown &&
6383 "CM decision should be taken at this point");
6386 if (Decision == CM_Scalarize)
6387 Width = ElementCount::getFixed(1);
6388 }
6389 VectorTy = toVectorTy(getLoadStoreType(I), Width);
6390 return getMemoryInstructionCost(I, VF);
6391 }
6392 case Instruction::BitCast:
6393 if (I->getType()->isPointerTy())
6394 return 0;
6395 [[fallthrough]];
6396 case Instruction::ZExt:
6397 case Instruction::SExt:
6398 case Instruction::FPToUI:
6399 case Instruction::FPToSI:
6400 case Instruction::FPExt:
6401 case Instruction::PtrToInt:
6402 case Instruction::IntToPtr:
6403 case Instruction::SIToFP:
6404 case Instruction::UIToFP:
6405 case Instruction::Trunc:
6406 case Instruction::FPTrunc: {
6407 // Computes the CastContextHint from a Load/Store instruction.
6408 auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
6410 "Expected a load or a store!");
6411
6412 if (VF.isScalar() || !TheLoop->contains(I))
6414
6415 switch (getWideningDecision(I, VF)) {
6427 llvm_unreachable("Instr did not go through cost modelling?");
6430 llvm_unreachable_internal("Instr has invalid widening decision");
6431 }
6432
6433 llvm_unreachable("Unhandled case!");
6434 };
6435
6436 unsigned Opcode = I->getOpcode();
6438 // For Trunc, the context is the only user, which must be a StoreInst.
6439 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
6440 if (I->hasOneUse())
6441 if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
6442 CCH = ComputeCCH(Store);
6443 }
6444 // For Z/Sext, the context is the operand, which must be a LoadInst.
6445 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
6446 Opcode == Instruction::FPExt) {
6447 if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
6448 CCH = ComputeCCH(Load);
6449 }
6450
6451 // We optimize the truncation of induction variables having constant
6452 // integer steps. The cost of these truncations is the same as the scalar
6453 // operation.
6454 if (isOptimizableIVTruncate(I, VF)) {
6455 auto *Trunc = cast<TruncInst>(I);
6456 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
6457 Trunc->getSrcTy(), CCH, CostKind, Trunc);
6458 }
6459
6460 // Detect reduction patterns
6461 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6462 return *RedCost;
6463
6464 Type *SrcScalarTy = I->getOperand(0)->getType();
6465 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6466 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6467 SrcScalarTy =
6468 IntegerType::get(SrcScalarTy->getContext(), MinBWs[Op0AsInstruction]);
6469 Type *SrcVecTy =
6470 VectorTy->isVectorTy() ? toVectorTy(SrcScalarTy, VF) : SrcScalarTy;
6471
6473 // If the result type is <= the source type, there will be no extend
6474 // after truncating the users to the minimal required bitwidth.
6475 if (VectorTy->getScalarSizeInBits() <= SrcVecTy->getScalarSizeInBits() &&
6476 (I->getOpcode() == Instruction::ZExt ||
6477 I->getOpcode() == Instruction::SExt))
6478 return 0;
6479 }
6480
6481 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
6482 }
6483 case Instruction::Call:
6484 return getVectorCallCost(cast<CallInst>(I), VF);
6485 case Instruction::ExtractValue:
6486 return TTI.getInstructionCost(I, CostKind);
6487 case Instruction::Alloca:
6488 // We cannot easily widen alloca to a scalable alloca, as
6489 // the result would need to be a vector of pointers.
6490 if (VF.isScalable())
6492 return TTI.getArithmeticInstrCost(Instruction::Mul, RetTy, CostKind);
6493 default:
6494 // This opcode is unknown. Assume that it is the same as 'mul'.
6495 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6496 } // end of switch.
6497}
6498
6500 // Ignore ephemeral values.
6502
6503 SmallVector<Value *, 4> DeadInterleavePointerOps;
6505
6506 // If a scalar epilogue is required, users outside the loop won't use
6507 // live-outs from the vector loop but from the scalar epilogue. Ignore them if
6508 // that is the case.
6509 bool RequiresScalarEpilogue = requiresScalarEpilogue(true);
6510 auto IsLiveOutDead = [this, RequiresScalarEpilogue](User *U) {
6511 return RequiresScalarEpilogue &&
6512 !TheLoop->contains(cast<Instruction>(U)->getParent());
6513 };
6514
6516 DFS.perform(LI);
6517 for (BasicBlock *BB : reverse(make_range(DFS.beginRPO(), DFS.endRPO())))
6518 for (Instruction &I : reverse(*BB)) {
6519 if (VecValuesToIgnore.contains(&I) || ValuesToIgnore.contains(&I))
6520 continue;
6521
6522 // Add instructions that would be trivially dead and are only used by
6523 // values already ignored to DeadOps to seed worklist.
6525 all_of(I.users(), [this, IsLiveOutDead](User *U) {
6526 return VecValuesToIgnore.contains(U) ||
6527 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
6528 }))
6529 DeadOps.push_back(&I);
6530
6531 // For interleave groups, we only create a pointer for the start of the
6532 // interleave group. Queue up addresses of group members except the insert
6533 // position for further processing.
6534 if (isAccessInterleaved(&I)) {
6535 auto *Group = getInterleavedAccessGroup(&I);
6536 if (Group->getInsertPos() == &I)
6537 continue;
6538 Value *PointerOp = getLoadStorePointerOperand(&I);
6539 DeadInterleavePointerOps.push_back(PointerOp);
6540 }
6541
6542 // Queue branches for analysis. They are dead, if their successors only
6543 // contain dead instructions.
6544 if (isa<CondBrInst>(&I))
6545 DeadOps.push_back(&I);
6546 }
6547
6548 // Mark ops feeding interleave group members as free, if they are only used
6549 // by other dead computations.
6550 for (unsigned I = 0; I != DeadInterleavePointerOps.size(); ++I) {
6551 auto *Op = dyn_cast<Instruction>(DeadInterleavePointerOps[I]);
6552 if (!Op || !TheLoop->contains(Op) || any_of(Op->users(), [this](User *U) {
6553 Instruction *UI = cast<Instruction>(U);
6554 return !VecValuesToIgnore.contains(U) &&
6555 (!isAccessInterleaved(UI) ||
6556 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
6557 }))
6558 continue;
6559 VecValuesToIgnore.insert(Op);
6560 append_range(DeadInterleavePointerOps, Op->operands());
6561 }
6562
6563 // Mark ops that would be trivially dead and are only used by ignored
6564 // instructions as free.
6565 BasicBlock *Header = TheLoop->getHeader();
6566
6567 // Returns true if the block contains only dead instructions. Such blocks will
6568 // be removed by VPlan-to-VPlan transforms and won't be considered by the
6569 // VPlan-based cost model, so skip them in the legacy cost-model as well.
6570 auto IsEmptyBlock = [this](BasicBlock *BB) {
6571 return all_of(*BB, [this](Instruction &I) {
6572 return ValuesToIgnore.contains(&I) || VecValuesToIgnore.contains(&I) ||
6574 });
6575 };
6576 for (unsigned I = 0; I != DeadOps.size(); ++I) {
6577 auto *Op = dyn_cast<Instruction>(DeadOps[I]);
6578
6579 // Check if the branch should be considered dead.
6580 if (auto *Br = dyn_cast_or_null<CondBrInst>(Op)) {
6581 BasicBlock *ThenBB = Br->getSuccessor(0);
6582 BasicBlock *ElseBB = Br->getSuccessor(1);
6583 // Don't considers branches leaving the loop for simplification.
6584 if (!TheLoop->contains(ThenBB) || !TheLoop->contains(ElseBB))
6585 continue;
6586 bool ThenEmpty = IsEmptyBlock(ThenBB);
6587 bool ElseEmpty = IsEmptyBlock(ElseBB);
6588 if ((ThenEmpty && ElseEmpty) ||
6589 (ThenEmpty && ThenBB->getSingleSuccessor() == ElseBB &&
6590 ElseBB->phis().empty()) ||
6591 (ElseEmpty && ElseBB->getSingleSuccessor() == ThenBB &&
6592 ThenBB->phis().empty())) {
6593 VecValuesToIgnore.insert(Br);
6594 DeadOps.push_back(Br->getCondition());
6595 }
6596 continue;
6597 }
6598
6599 // Skip any op that shouldn't be considered dead.
6600 if (!Op || !TheLoop->contains(Op) ||
6601 (isa<PHINode>(Op) && Op->getParent() == Header) ||
6603 any_of(Op->users(), [this, IsLiveOutDead](User *U) {
6604 return !VecValuesToIgnore.contains(U) &&
6605 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
6606 }))
6607 continue;
6608
6609 // If all of Op's users are in ValuesToIgnore, add it to ValuesToIgnore
6610 // which applies for both scalar and vector versions. Otherwise it is only
6611 // dead in vector versions, so only add it to VecValuesToIgnore.
6612 if (all_of(Op->users(),
6613 [this](User *U) { return ValuesToIgnore.contains(U); }))
6614 ValuesToIgnore.insert(Op);
6615
6616 VecValuesToIgnore.insert(Op);
6617 append_range(DeadOps, Op->operands());
6618 }
6619
6620 // Ignore type-promoting instructions we identified during reduction
6621 // detection.
6622 for (const auto &Reduction : Legal->getReductionVars()) {
6623 const RecurrenceDescriptor &RedDes = Reduction.second;
6624 const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6625 VecValuesToIgnore.insert_range(Casts);
6626 }
6627 // Ignore type-casting instructions we identified during induction
6628 // detection.
6629 for (const auto &Induction : Legal->getInductionVars()) {
6630 const InductionDescriptor &IndDes = Induction.second;
6631 VecValuesToIgnore.insert_range(IndDes.getCastInsts());
6632 }
6633}
6634
6636 // Avoid duplicating work finding in-loop reductions.
6637 if (!InLoopReductions.empty())
6638 return;
6639
6640 for (const auto &Reduction : Legal->getReductionVars()) {
6641 PHINode *Phi = Reduction.first;
6642 const RecurrenceDescriptor &RdxDesc = Reduction.second;
6643
6644 // Multi-use reductions (e.g., used in FindLastIV patterns) are handled
6645 // separately and should not be considered for in-loop reductions.
6646 if (RdxDesc.hasUsesOutsideReductionChain())
6647 continue;
6648
6649 // We don't collect reductions that are type promoted (yet).
6650 if (RdxDesc.getRecurrenceType() != Phi->getType())
6651 continue;
6652
6653 // In-loop AnyOf and FindIV reductions are not yet supported.
6654 RecurKind Kind = RdxDesc.getRecurrenceKind();
6658 continue;
6659
6660 // If the target would prefer this reduction to happen "in-loop", then we
6661 // want to record it as such.
6662 if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
6663 !TTI.preferInLoopReduction(Kind, Phi->getType()))
6664 continue;
6665
6666 // Check that we can correctly put the reductions into the loop, by
6667 // finding the chain of operations that leads from the phi to the loop
6668 // exit value.
6669 SmallVector<Instruction *, 4> ReductionOperations =
6670 RdxDesc.getReductionOpChain(Phi, TheLoop);
6671 bool InLoop = !ReductionOperations.empty();
6672
6673 if (InLoop) {
6674 InLoopReductions.insert(Phi);
6675 // Add the elements to InLoopReductionImmediateChains for cost modelling.
6676 Instruction *LastChain = Phi;
6677 for (auto *I : ReductionOperations) {
6678 InLoopReductionImmediateChains[I] = LastChain;
6679 LastChain = I;
6680 }
6681 }
6682 LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
6683 << " reduction for phi: " << *Phi << "\n");
6684 }
6685}
6686
6687// This function will select a scalable VF if the target supports scalable
6688// vectors and a fixed one otherwise.
6689// TODO: we could return a pair of values that specify the max VF and
6690// min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
6691// `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
6692// doesn't have a cost model that can choose which plan to execute if
6693// more than one is generated.
6696 unsigned WidestType;
6697 std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
6698
6700 TTI.enableScalableVectorization()
6703
6704 TypeSize RegSize = TTI.getRegisterBitWidth(RegKind);
6705 unsigned N = RegSize.getKnownMinValue() / WidestType;
6706 return ElementCount::get(N, RegSize.isScalable());
6707}
6708
6711 ElementCount VF = UserVF;
6712 // Outer loop handling: They may require CFG and instruction level
6713 // transformations before even evaluating whether vectorization is profitable.
6714 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
6715 // the vectorization pipeline.
6716 if (!OrigLoop->isInnermost()) {
6717 // If the user doesn't provide a vectorization factor, determine a
6718 // reasonable one.
6719 if (UserVF.isZero()) {
6720 VF = determineVPlanVF(TTI, CM);
6721 LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
6722
6723 // Make sure we have a VF > 1 for stress testing.
6724 if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
6725 LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
6726 << "overriding computed VF.\n");
6727 VF = ElementCount::getFixed(4);
6728 }
6729 } else if (UserVF.isScalable() && !TTI.supportsScalableVectors() &&
6731 LLVM_DEBUG(dbgs() << "LV: Not vectorizing. Scalable VF requested, but "
6732 << "not supported by the target.\n");
6734 "Scalable vectorization requested but not supported by the target",
6735 "the scalable user-specified vectorization width for outer-loop "
6736 "vectorization cannot be used because the target does not support "
6737 "scalable vectors.",
6738 "ScalableVFUnfeasible", ORE, OrigLoop);
6740 }
6741 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
6743 "VF needs to be a power of two");
6744 LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
6745 << "VF " << VF << " to build VPlans.\n");
6746 buildVPlans(VF, VF);
6747
6748 if (VPlans.empty())
6750
6751 // For VPlan build stress testing, we bail out after VPlan construction.
6754
6755 return {VF, 0 /*Cost*/, 0 /* ScalarCost */};
6756 }
6757
6758 LLVM_DEBUG(
6759 dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
6760 "VPlan-native path.\n");
6762}
6763
6764void LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
6765 assert(OrigLoop->isInnermost() && "Inner loop expected.");
6766 CM.collectValuesToIgnore();
6767 CM.collectElementTypesForWidening();
6768
6769 FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
6770 if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
6771 return;
6772
6773 // Invalidate interleave groups if all blocks of loop will be predicated.
6774 if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
6776 LLVM_DEBUG(
6777 dbgs()
6778 << "LV: Invalidate all interleaved groups due to fold-tail by masking "
6779 "which requires masked-interleaved support.\n");
6780 if (CM.InterleaveInfo.invalidateGroups())
6781 // Invalidating interleave groups also requires invalidating all decisions
6782 // based on them, which includes widening decisions and uniform and scalar
6783 // values.
6784 CM.invalidateCostModelingDecisions();
6785 }
6786
6787 if (CM.foldTailByMasking())
6788 Legal->prepareToFoldTailByMasking();
6789
6790 ElementCount MaxUserVF =
6791 UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
6792 if (UserVF) {
6793 if (!ElementCount::isKnownLE(UserVF, MaxUserVF)) {
6795 "UserVF ignored because it may be larger than the maximal safe VF",
6796 "InvalidUserVF", ORE, OrigLoop);
6797 } else {
6799 "VF needs to be a power of two");
6800 // Collect the instructions (and their associated costs) that will be more
6801 // profitable to scalarize.
6802 CM.collectInLoopReductions();
6803 if (CM.selectUserVectorizationFactor(UserVF)) {
6804 LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
6805 ElementCount EpilogueUserVF =
6807 if (EpilogueUserVF.isVector() &&
6808 ElementCount::isKnownLT(EpilogueUserVF, UserVF) &&
6809 CM.selectUserVectorizationFactor(EpilogueUserVF)) {
6810 // Build a separate plan for the forced epilogue VF.
6811 buildVPlansWithVPRecipes(EpilogueUserVF, EpilogueUserVF);
6812 }
6813 buildVPlansWithVPRecipes(UserVF, UserVF);
6815 return;
6816 }
6817 reportVectorizationInfo("UserVF ignored because of invalid costs.",
6818 "InvalidCost", ORE, OrigLoop);
6819 }
6820 }
6821
6822 // Collect the Vectorization Factor Candidates.
6823 SmallVector<ElementCount> VFCandidates;
6824 for (auto VF = ElementCount::getFixed(1);
6825 ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
6826 VFCandidates.push_back(VF);
6827 for (auto VF = ElementCount::getScalable(1);
6828 ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
6829 VFCandidates.push_back(VF);
6830
6831 CM.collectInLoopReductions();
6832 for (const auto &VF : VFCandidates) {
6833 // Collect Uniform and Scalar instructions after vectorization with VF.
6834 CM.collectNonVectorizedAndSetWideningDecisions(VF);
6835 }
6836
6837 buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
6838 buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
6839
6841}
6842
6844 ElementCount VF) const {
6845 InstructionCost Cost = CM.getInstructionCost(UI, VF);
6846 if (Cost.isValid() && ForceTargetInstructionCost.getNumOccurrences())
6848 return Cost;
6849}
6850
6852 ElementCount VF) const {
6853 return CM.isUniformAfterVectorization(I, VF);
6854}
6855
6856bool VPCostContext::skipCostComputation(Instruction *UI, bool IsVector) const {
6857 return CM.ValuesToIgnore.contains(UI) ||
6858 (IsVector && CM.VecValuesToIgnore.contains(UI)) ||
6859 SkipCostComputation.contains(UI);
6860}
6861
6863 return CM.getPredBlockCostDivisor(CostKind, BB);
6864}
6865
6867LoopVectorizationPlanner::precomputeCosts(VPlan &Plan, ElementCount VF,
6868 VPCostContext &CostCtx) const {
6870 // Cost modeling for inductions is inaccurate in the legacy cost model
6871 // compared to the recipes that are generated. To match here initially during
6872 // VPlan cost model bring up directly use the induction costs from the legacy
6873 // cost model. Note that we do this as pre-processing; the VPlan may not have
6874 // any recipes associated with the original induction increment instruction
6875 // and may replace truncates with VPWidenIntOrFpInductionRecipe. We precompute
6876 // the cost of induction phis and increments (both that are represented by
6877 // recipes and those that are not), to avoid distinguishing between them here,
6878 // and skip all recipes that represent induction phis and increments (the
6879 // former case) later on, if they exist, to avoid counting them twice.
6880 // Similarly we pre-compute the cost of any optimized truncates.
6881 // TODO: Switch to more accurate costing based on VPlan.
6882 for (const auto &[IV, IndDesc] : Legal->getInductionVars()) {
6884 IV->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
6885 SmallVector<Instruction *> IVInsts = {IVInc};
6886 for (unsigned I = 0; I != IVInsts.size(); I++) {
6887 for (Value *Op : IVInsts[I]->operands()) {
6888 auto *OpI = dyn_cast<Instruction>(Op);
6889 if (Op == IV || !OpI || !OrigLoop->contains(OpI) || !Op->hasOneUse())
6890 continue;
6891 IVInsts.push_back(OpI);
6892 }
6893 }
6894 IVInsts.push_back(IV);
6895 for (User *U : IV->users()) {
6896 auto *CI = cast<Instruction>(U);
6897 if (!CostCtx.CM.isOptimizableIVTruncate(CI, VF))
6898 continue;
6899 IVInsts.push_back(CI);
6900 }
6901
6902 // If the vector loop gets executed exactly once with the given VF, ignore
6903 // the costs of comparison and induction instructions, as they'll get
6904 // simplified away.
6905 // TODO: Remove this code after stepping away from the legacy cost model and
6906 // adding code to simplify VPlans before calculating their costs.
6907 auto TC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
6908 if (TC == VF && !CM.foldTailByMasking())
6909 addFullyUnrolledInstructionsToIgnore(OrigLoop, Legal->getInductionVars(),
6910 CostCtx.SkipCostComputation);
6911
6912 for (Instruction *IVInst : IVInsts) {
6913 if (CostCtx.skipCostComputation(IVInst, VF.isVector()))
6914 continue;
6915 InstructionCost InductionCost = CostCtx.getLegacyCost(IVInst, VF);
6916 LLVM_DEBUG({
6917 dbgs() << "Cost of " << InductionCost << " for VF " << VF
6918 << ": induction instruction " << *IVInst << "\n";
6919 });
6920 Cost += InductionCost;
6921 CostCtx.SkipCostComputation.insert(IVInst);
6922 }
6923 }
6924
6925 /// Compute the cost of all exiting conditions of the loop using the legacy
6926 /// cost model. This is to match the legacy behavior, which adds the cost of
6927 /// all exit conditions. Note that this over-estimates the cost, as there will
6928 /// be a single condition to control the vector loop.
6930 CM.TheLoop->getExitingBlocks(Exiting);
6931 SetVector<Instruction *> ExitInstrs;
6932 // Collect all exit conditions.
6933 for (BasicBlock *EB : Exiting) {
6934 auto *Term = dyn_cast<CondBrInst>(EB->getTerminator());
6935 if (!Term || CostCtx.skipCostComputation(Term, VF.isVector()))
6936 continue;
6937 if (auto *CondI = dyn_cast<Instruction>(Term->getOperand(0))) {
6938 ExitInstrs.insert(CondI);
6939 }
6940 }
6941 // Compute the cost of all instructions only feeding the exit conditions.
6942 for (unsigned I = 0; I != ExitInstrs.size(); ++I) {
6943 Instruction *CondI = ExitInstrs[I];
6944 if (!OrigLoop->contains(CondI) ||
6945 !CostCtx.SkipCostComputation.insert(CondI).second)
6946 continue;
6947 InstructionCost CondICost = CostCtx.getLegacyCost(CondI, VF);
6948 LLVM_DEBUG({
6949 dbgs() << "Cost of " << CondICost << " for VF " << VF
6950 << ": exit condition instruction " << *CondI << "\n";
6951 });
6952 Cost += CondICost;
6953 for (Value *Op : CondI->operands()) {
6954 auto *OpI = dyn_cast<Instruction>(Op);
6955 if (!OpI || CostCtx.skipCostComputation(OpI, VF.isVector()) ||
6956 any_of(OpI->users(), [&ExitInstrs](User *U) {
6957 return !ExitInstrs.contains(cast<Instruction>(U));
6958 }))
6959 continue;
6960 ExitInstrs.insert(OpI);
6961 }
6962 }
6963
6964 // Pre-compute the costs for branches except for the backedge, as the number
6965 // of replicate regions in a VPlan may not directly match the number of
6966 // branches, which would lead to different decisions.
6967 // TODO: Compute cost of branches for each replicate region in the VPlan,
6968 // which is more accurate than the legacy cost model.
6969 for (BasicBlock *BB : OrigLoop->blocks()) {
6970 if (CostCtx.skipCostComputation(BB->getTerminator(), VF.isVector()))
6971 continue;
6972 CostCtx.SkipCostComputation.insert(BB->getTerminator());
6973 if (BB == OrigLoop->getLoopLatch())
6974 continue;
6975 auto BranchCost = CostCtx.getLegacyCost(BB->getTerminator(), VF);
6976 Cost += BranchCost;
6977 }
6978
6979 // Don't apply special costs when instruction cost is forced to make sure the
6980 // forced cost is used for each recipe.
6981 if (ForceTargetInstructionCost.getNumOccurrences())
6982 return Cost;
6983
6984 // Pre-compute costs for instructions that are forced-scalar or profitable to
6985 // scalarize. Their costs will be computed separately in the legacy cost
6986 // model.
6987 for (Instruction *ForcedScalar : CM.ForcedScalars[VF]) {
6988 if (CostCtx.skipCostComputation(ForcedScalar, VF.isVector()))
6989 continue;
6990 CostCtx.SkipCostComputation.insert(ForcedScalar);
6991 InstructionCost ForcedCost = CostCtx.getLegacyCost(ForcedScalar, VF);
6992 LLVM_DEBUG({
6993 dbgs() << "Cost of " << ForcedCost << " for VF " << VF
6994 << ": forced scalar " << *ForcedScalar << "\n";
6995 });
6996 Cost += ForcedCost;
6997 }
6998 for (const auto &[Scalarized, ScalarCost] : CM.InstsToScalarize[VF]) {
6999 if (CostCtx.skipCostComputation(Scalarized, VF.isVector()))
7000 continue;
7001 CostCtx.SkipCostComputation.insert(Scalarized);
7002 LLVM_DEBUG({
7003 dbgs() << "Cost of " << ScalarCost << " for VF " << VF
7004 << ": profitable to scalarize " << *Scalarized << "\n";
7005 });
7006 Cost += ScalarCost;
7007 }
7008
7009 return Cost;
7010}
7011
7012InstructionCost LoopVectorizationPlanner::cost(VPlan &Plan, ElementCount VF,
7013 VPRegisterUsage *RU) const {
7014 VPCostContext CostCtx(CM.TTI, *CM.TLI, Plan, CM, CM.CostKind, PSE, OrigLoop);
7015 InstructionCost Cost = precomputeCosts(Plan, VF, CostCtx);
7016
7017 // Now compute and add the VPlan-based cost.
7018 Cost += Plan.cost(VF, CostCtx);
7019
7020 // Add the cost of spills due to excess register usage
7021 if (CM.shouldConsiderRegPressureForVF(VF))
7022 Cost += RU->spillCost(CostCtx, ForceTargetNumVectorRegs);
7023
7024#ifndef NDEBUG
7025 unsigned EstimatedWidth = estimateElementCount(VF, CM.getVScaleForTuning());
7026 LLVM_DEBUG(dbgs() << "Cost for VF " << VF << ": " << Cost
7027 << " (Estimated cost per lane: ");
7028 if (Cost.isValid()) {
7029 double CostPerLane = double(Cost.getValue()) / EstimatedWidth;
7030 LLVM_DEBUG(dbgs() << format("%.1f", CostPerLane));
7031 } else /* No point dividing an invalid cost - it will still be invalid */
7032 LLVM_DEBUG(dbgs() << "Invalid");
7033 LLVM_DEBUG(dbgs() << ")\n");
7034#endif
7035 return Cost;
7036}
7037
7038#ifndef NDEBUG
7039/// Return true if the original loop \ TheLoop contains any instructions that do
7040/// not have corresponding recipes in \p Plan and are not marked to be ignored
7041/// in \p CostCtx. This means the VPlan contains simplification that the legacy
7042/// cost-model did not account for.
7044 VPCostContext &CostCtx,
7045 Loop *TheLoop,
7046 ElementCount VF) {
7047 using namespace VPlanPatternMatch;
7048 // First collect all instructions for the recipes in Plan.
7049 auto GetInstructionForCost = [](const VPRecipeBase *R) -> Instruction * {
7050 if (auto *S = dyn_cast<VPSingleDefRecipe>(R))
7051 return dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
7052 if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(R))
7053 return &WidenMem->getIngredient();
7054 return nullptr;
7055 };
7056
7057 // Check if a select for a safe divisor was hoisted to the pre-header. If so,
7058 // the select doesn't need to be considered for the vector loop cost; go with
7059 // the more accurate VPlan-based cost model.
7060 for (VPRecipeBase &R : *Plan.getVectorPreheader()) {
7061 auto *VPI = dyn_cast<VPInstruction>(&R);
7062 if (!VPI || VPI->getOpcode() != Instruction::Select)
7063 continue;
7064
7065 if (auto *WR = dyn_cast_or_null<VPWidenRecipe>(VPI->getSingleUser())) {
7066 switch (WR->getOpcode()) {
7067 case Instruction::UDiv:
7068 case Instruction::SDiv:
7069 case Instruction::URem:
7070 case Instruction::SRem:
7071 return true;
7072 default:
7073 break;
7074 }
7075 }
7076 }
7077
7078 DenseSet<Instruction *> SeenInstrs;
7079 auto Iter = vp_depth_first_deep(Plan.getVectorLoopRegion()->getEntry());
7081 for (VPRecipeBase &R : *VPBB) {
7082 if (auto *IR = dyn_cast<VPInterleaveRecipe>(&R)) {
7083 auto *IG = IR->getInterleaveGroup();
7084 unsigned NumMembers = IG->getNumMembers();
7085 for (unsigned I = 0; I != NumMembers; ++I) {
7086 if (Instruction *M = IG->getMember(I))
7087 SeenInstrs.insert(M);
7088 }
7089 continue;
7090 }
7091 // Unused FOR splices are removed by VPlan transforms, so the VPlan-based
7092 // cost model won't cost it whilst the legacy will.
7093 if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R)) {
7094 if (none_of(FOR->users(),
7095 match_fn(m_VPInstruction<
7097 return true;
7098 }
7099 // The VPlan-based cost model is more accurate for partial reductions and
7100 // comparing against the legacy cost isn't desirable.
7101 if (auto *VPR = dyn_cast<VPReductionRecipe>(&R))
7102 if (VPR->isPartialReduction())
7103 return true;
7104
7105 // The VPlan-based cost model can analyze if recipes are scalar
7106 // recursively, but the legacy cost model cannot.
7107 if (auto *WidenMemR = dyn_cast<VPWidenMemoryRecipe>(&R)) {
7108 auto *AddrI = dyn_cast<Instruction>(
7109 getLoadStorePointerOperand(&WidenMemR->getIngredient()));
7110 if (AddrI && vputils::isSingleScalar(WidenMemR->getAddr()) !=
7111 CostCtx.isLegacyUniformAfterVectorization(AddrI, VF))
7112 return true;
7113
7114 if (WidenMemR->isReverse()) {
7115 // If the stored value of a reverse store is invariant, LICM will
7116 // hoist the reverse operation to the preheader. In this case, the
7117 // result of the VPlan-based cost model will diverge from that of
7118 // the legacy model.
7119 if (auto *StoreR = dyn_cast<VPWidenStoreRecipe>(WidenMemR))
7120 if (StoreR->getStoredValue()->isDefinedOutsideLoopRegions())
7121 return true;
7122
7123 if (auto *StoreR = dyn_cast<VPWidenStoreEVLRecipe>(WidenMemR))
7124 if (StoreR->getStoredValue()->isDefinedOutsideLoopRegions())
7125 return true;
7126 }
7127 }
7128
7129 // The legacy cost model costs non-header phis with a scalar VF as a phi,
7130 // but scalar unrolled VPlans will have VPBlendRecipes which emit selects.
7131 if (isa<VPBlendRecipe>(&R) &&
7132 vputils::onlyFirstLaneUsed(R.getVPSingleValue()))
7133 return true;
7134
7135 // The legacy cost model won't calculate the cost of the LogicalAnd which
7136 // will be replaced with vp_merge.
7138 return true;
7139
7140 /// If a VPlan transform folded a recipe to one producing a single-scalar,
7141 /// but the original instruction wasn't uniform-after-vectorization in the
7142 /// legacy cost model, the legacy cost overestimates the actual cost.
7143 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
7144 if (RepR->isSingleScalar() &&
7146 RepR->getUnderlyingInstr(), VF))
7147 return true;
7148 }
7149 if (Instruction *UI = GetInstructionForCost(&R)) {
7150 // If we adjusted the predicate of the recipe, the cost in the legacy
7151 // cost model may be different.
7152 CmpPredicate Pred;
7153 if (match(&R, m_Cmp(Pred, m_VPValue(), m_VPValue())) &&
7154 cast<VPRecipeWithIRFlags>(R).getPredicate() !=
7155 cast<CmpInst>(UI)->getPredicate())
7156 return true;
7157
7158 // Recipes with underlying instructions being moved out of the loop
7159 // region by LICM may cause discrepancies between the legacy cost model
7160 // and the VPlan-based cost model.
7161 if (!VPBB->getEnclosingLoopRegion())
7162 return true;
7163
7164 SeenInstrs.insert(UI);
7165 }
7166 }
7167 }
7168
7169 // If a reverse recipe has been sunk to the middle block (e.g., for a load
7170 // whose result is only used as a live-out), VPlan avoids the per-iteration
7171 // reverse shuffle cost that the legacy model accounts for.
7172 if (any_of(*Plan.getMiddleBlock(), [](const VPRecipeBase &R) {
7173 return match(&R, m_VPInstruction<VPInstruction::Reverse>());
7174 }))
7175 return true;
7176
7177 // Return true if the loop contains any instructions that are not also part of
7178 // the VPlan or are skipped for VPlan-based cost computations. This indicates
7179 // that the VPlan contains extra simplifications.
7180 return any_of(TheLoop->blocks(), [&SeenInstrs, &CostCtx,
7181 TheLoop](BasicBlock *BB) {
7182 return any_of(*BB, [&SeenInstrs, &CostCtx, TheLoop, BB](Instruction &I) {
7183 // Skip induction phis when checking for simplifications, as they may not
7184 // be lowered directly be lowered to a corresponding PHI recipe.
7185 if (isa<PHINode>(&I) && BB == TheLoop->getHeader() &&
7186 CostCtx.CM.Legal->isInductionPhi(cast<PHINode>(&I)))
7187 return false;
7188 return !SeenInstrs.contains(&I) && !CostCtx.skipCostComputation(&I, true);
7189 });
7190 });
7191}
7192#endif
7193
7194std::pair<VectorizationFactor, VPlan *>
7196 if (VPlans.empty())
7197 return {VectorizationFactor::Disabled(), nullptr};
7198 // If there is a single VPlan with a single VF, return it directly.
7199 VPlan &FirstPlan = *VPlans[0];
7200 ElementCount UserVF = Hints.getWidth();
7201 if (hasPlanWithVF(UserVF)) {
7202 if (VPlans.size() == 1) {
7203 assert(FirstPlan.getSingleVF() == UserVF &&
7204 "UserVF must match single VF");
7205 return {VectorizationFactor(FirstPlan.getSingleVF(), 0, 0), &FirstPlan};
7206 }
7208 assert(VPlans.size() == 2 && "Must have exactly 2 VPlans built");
7209 assert(VPlans[0]->getSingleVF() ==
7211 "expected first plan to be for the forced epilogue VF");
7212 assert(VPlans[1]->getSingleVF() == UserVF &&
7213 "expected second plan to be for the forced UserVF");
7214 return {VectorizationFactor(UserVF, 0, 0), VPlans[1].get()};
7215 }
7216 }
7217
7218 LLVM_DEBUG(dbgs() << "LV: Computing best VF using cost kind: "
7219 << (CM.CostKind == TTI::TCK_RecipThroughput
7220 ? "Reciprocal Throughput\n"
7221 : CM.CostKind == TTI::TCK_Latency
7222 ? "Instruction Latency\n"
7223 : CM.CostKind == TTI::TCK_CodeSize ? "Code Size\n"
7224 : CM.CostKind == TTI::TCK_SizeAndLatency
7225 ? "Code Size and Latency\n"
7226 : "Unknown\n"));
7227
7229 assert(FirstPlan.hasVF(ScalarVF) &&
7230 "More than a single plan/VF w/o any plan having scalar VF");
7231
7232 // TODO: Compute scalar cost using VPlan-based cost model.
7233 InstructionCost ScalarCost = CM.expectedCost(ScalarVF);
7234 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ScalarCost << ".\n");
7235 VectorizationFactor ScalarFactor(ScalarVF, ScalarCost, ScalarCost);
7236 VectorizationFactor BestFactor = ScalarFactor;
7237
7238 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
7239 if (ForceVectorization) {
7240 // Ignore scalar width, because the user explicitly wants vectorization.
7241 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
7242 // evaluation.
7243 BestFactor.Cost = InstructionCost::getMax();
7244 }
7245
7246 VPlan *PlanForBestVF = &FirstPlan;
7247
7248 for (auto &P : VPlans) {
7249 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
7250 P->vectorFactors().end());
7251
7253 bool ConsiderRegPressure = any_of(VFs, [this](ElementCount VF) {
7254 return CM.shouldConsiderRegPressureForVF(VF);
7255 });
7257 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
7258
7259 for (unsigned I = 0; I < VFs.size(); I++) {
7260 ElementCount VF = VFs[I];
7261 if (VF.isScalar())
7262 continue;
7263 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
7264 LLVM_DEBUG(
7265 dbgs()
7266 << "LV: Not considering vector loop of width " << VF
7267 << " because it will not generate any vector instructions.\n");
7268 continue;
7269 }
7270 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
7271 LLVM_DEBUG(
7272 dbgs()
7273 << "LV: Not considering vector loop of width " << VF
7274 << " because it would cause replicated blocks to be generated,"
7275 << " which isn't allowed when optimizing for size.\n");
7276 continue;
7277 }
7278
7280 cost(*P, VF, ConsiderRegPressure ? &RUs[I] : nullptr);
7281 VectorizationFactor CurrentFactor(VF, Cost, ScalarCost);
7282
7283 if (isMoreProfitable(CurrentFactor, BestFactor, P->hasScalarTail())) {
7284 BestFactor = CurrentFactor;
7285 PlanForBestVF = P.get();
7286 }
7287
7288 // If profitable add it to ProfitableVF list.
7289 if (isMoreProfitable(CurrentFactor, ScalarFactor, P->hasScalarTail()))
7290 ProfitableVFs.push_back(CurrentFactor);
7291 }
7292 }
7293
7294 VPlan &BestPlan = *PlanForBestVF;
7295
7296#ifndef NDEBUG
7297 // Select the optimal vectorization factor according to the legacy cost-model.
7298 // This is now only used to verify the decisions by the new VPlan-based
7299 // cost-model and will be retired once the VPlan-based cost-model is
7300 // stabilized.
7301 VectorizationFactor LegacyVF = selectVectorizationFactor();
7302
7303 // Pre-compute the cost and use it to check if BestPlan contains any
7304 // simplifications not accounted for in the legacy cost model. If that's the
7305 // case, don't trigger the assertion, as the extra simplifications may cause a
7306 // different VF to be picked by the VPlan-based cost model.
7307 VPCostContext CostCtx(CM.TTI, *CM.TLI, BestPlan, CM, CM.CostKind, CM.PSE,
7308 OrigLoop);
7309 precomputeCosts(BestPlan, BestFactor.Width, CostCtx);
7310 // Verify that the VPlan-based and legacy cost models agree, except for
7311 // * VPlans with early exits,
7312 // * VPlans with additional VPlan simplifications,
7313 // * EVL-based VPlans with gather/scatters (the VPlan-based cost model uses
7314 // vp_scatter/vp_gather).
7315 // The legacy cost model doesn't properly model costs for such loops.
7316 bool UsesEVLGatherScatter =
7318 BestPlan.getVectorLoopRegion()->getEntry())),
7319 [](VPBasicBlock *VPBB) {
7320 return any_of(*VPBB, [](VPRecipeBase &R) {
7321 return isa<VPWidenLoadEVLRecipe, VPWidenStoreEVLRecipe>(&R) &&
7322 !cast<VPWidenMemoryRecipe>(&R)->isConsecutive();
7323 });
7324 });
7325 assert((BestFactor.Width == LegacyVF.Width || BestPlan.hasEarlyExit() ||
7326 !Legal->getLAI()->getSymbolicStrides().empty() ||
7327 UsesEVLGatherScatter ||
7328 planContainsAdditionalSimplifications(BestPlan, CostCtx, OrigLoop,
7329 BestFactor.Width) ||
7331 getPlanFor(LegacyVF.Width), CostCtx, OrigLoop, LegacyVF.Width)) &&
7332 " VPlan cost model and legacy cost model disagreed");
7333 assert((BestFactor.Width.isScalar() || BestFactor.ScalarCost > 0) &&
7334 "when vectorizing, the scalar cost must be computed.");
7335#endif
7336
7337 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << BestFactor.Width << ".\n");
7338 return {BestFactor, &BestPlan};
7339}
7340
7342 ElementCount BestVF, unsigned BestUF, VPlan &BestVPlan,
7344 EpilogueVectorizationKind EpilogueVecKind) {
7345 assert(BestVPlan.hasVF(BestVF) &&
7346 "Trying to execute plan with unsupported VF");
7347 assert(BestVPlan.hasUF(BestUF) &&
7348 "Trying to execute plan with unsupported UF");
7349 if (BestVPlan.hasEarlyExit())
7350 ++LoopsEarlyExitVectorized;
7351 // TODO: Move to VPlan transform stage once the transition to the VPlan-based
7352 // cost model is complete for better cost estimates.
7353 RUN_VPLAN_PASS(VPlanTransforms::unrollByUF, BestVPlan, BestUF);
7357 bool HasBranchWeights =
7358 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator());
7359 if (HasBranchWeights) {
7360 std::optional<unsigned> VScale = CM.getVScaleForTuning();
7362 BestVPlan, BestVF, VScale);
7363 }
7364
7365 // Retrieving VectorPH now when it's easier while VPlan still has Regions.
7366 VPBasicBlock *VectorPH = cast<VPBasicBlock>(BestVPlan.getVectorPreheader());
7367
7369 PSE);
7370 VPlanTransforms::optimizeForVFAndUF(BestVPlan, BestVF, BestUF, PSE);
7372 if (EpilogueVecKind == EpilogueVectorizationKind::None)
7374 if (BestVPlan.getEntry()->getSingleSuccessor() ==
7375 BestVPlan.getScalarPreheader()) {
7376 // TODO: The vector loop would be dead, should not even try to vectorize.
7377 ORE->emit([&]() {
7378 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationDead",
7379 OrigLoop->getStartLoc(),
7380 OrigLoop->getHeader())
7381 << "Created vector loop never executes due to insufficient trip "
7382 "count.";
7383 });
7385 }
7386
7388
7390 // Convert the exit condition to AVLNext == 0 for EVL tail folded loops.
7392 // Regions are dissolved after optimizing for VF and UF, which completely
7393 // removes unneeded loop regions first.
7395 // Expand BranchOnTwoConds after dissolution, when latch has direct access to
7396 // its successors.
7398 // Convert loops with variable-length stepping after regions are dissolved.
7400 // Remove dead back-edges for single-iteration loops with BranchOnCond(true).
7401 // Only process loop latches to avoid removing edges from the middle block,
7402 // which may be needed for epilogue vectorization.
7403 VPlanTransforms::removeBranchOnConst(BestVPlan, /*OnlyLatches=*/true);
7406 BestVPlan, VectorPH, CM.foldTailByMasking(),
7407 CM.requiresScalarEpilogue(BestVF.isVector()), &BestVPlan.getVFxUF());
7408 VPlanTransforms::materializeFactors(BestVPlan, VectorPH, BestVF);
7409 VPlanTransforms::cse(BestVPlan);
7411 VPlanTransforms::simplifyKnownEVL(BestVPlan, BestVF, PSE);
7412
7413 // 0. Generate SCEV-dependent code in the entry, including TripCount, before
7414 // making any changes to the CFG.
7415 DenseMap<const SCEV *, Value *> ExpandedSCEVs =
7416 VPlanTransforms::expandSCEVs(BestVPlan, *PSE.getSE());
7417
7418 // Perform the actual loop transformation.
7419 VPTransformState State(&TTI, BestVF, LI, DT, ILV.AC, ILV.Builder, &BestVPlan,
7420 OrigLoop->getParentLoop(),
7421 Legal->getWidestInductionType());
7422
7423#ifdef EXPENSIVE_CHECKS
7424 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
7425#endif
7426
7427 // 1. Set up the skeleton for vectorization, including vector pre-header and
7428 // middle block. The vector loop is created during VPlan execution.
7429 State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7431 State.CFG.PrevBB->getSingleSuccessor(), &BestVPlan);
7433
7434 assert(verifyVPlanIsValid(BestVPlan) && "final VPlan is invalid");
7435
7436 // After vectorization, the exit blocks of the original loop will have
7437 // additional predecessors. Invalidate SCEVs for the exit phis in case SE
7438 // looked through single-entry phis.
7439 ScalarEvolution &SE = *PSE.getSE();
7440 for (VPIRBasicBlock *Exit : BestVPlan.getExitBlocks()) {
7441 if (!Exit->hasPredecessors())
7442 continue;
7443 for (VPRecipeBase &PhiR : Exit->phis())
7445 &cast<VPIRPhi>(PhiR).getIRPhi());
7446 }
7447 // Forget the original loop and block dispositions.
7448 SE.forgetLoop(OrigLoop);
7450
7452
7453 //===------------------------------------------------===//
7454 //
7455 // Notice: any optimization or new instruction that go
7456 // into the code below should also be implemented in
7457 // the cost-model.
7458 //
7459 //===------------------------------------------------===//
7460
7461 // Retrieve loop information before executing the plan, which may remove the
7462 // original loop, if it becomes unreachable.
7463 MDNode *LID = OrigLoop->getLoopID();
7464 unsigned OrigLoopInvocationWeight = 0;
7465 std::optional<unsigned> OrigAverageTripCount =
7466 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
7467
7468 BestVPlan.execute(&State);
7469
7470 // 2.6. Maintain Loop Hints
7471 // Keep all loop hints from the original loop on the vector loop (we'll
7472 // replace the vectorizer-specific hints below).
7473 VPBasicBlock *HeaderVPBB = vputils::getFirstLoopHeader(BestVPlan, State.VPDT);
7474 // Add metadata to disable runtime unrolling a scalar loop when there
7475 // are no runtime checks about strides and memory. A scalar loop that is
7476 // rarely used is not worth unrolling.
7477 bool DisableRuntimeUnroll = !ILV.RTChecks.hasChecks() && !BestVF.isScalar();
7479 HeaderVPBB ? LI->getLoopFor(State.CFG.VPBB2IRBB.lookup(HeaderVPBB))
7480 : nullptr,
7481 HeaderVPBB, BestVPlan,
7482 EpilogueVecKind == EpilogueVectorizationKind::Epilogue, LID,
7483 OrigAverageTripCount, OrigLoopInvocationWeight,
7484 estimateElementCount(BestVF * BestUF, CM.getVScaleForTuning()),
7485 DisableRuntimeUnroll);
7486
7487 // 3. Fix the vectorized code: take care of header phi's, live-outs,
7488 // predication, updating analyses.
7489 ILV.fixVectorizedLoop(State);
7490
7492
7493 return ExpandedSCEVs;
7494}
7495
7496//===--------------------------------------------------------------------===//
7497// EpilogueVectorizerMainLoop
7498//===--------------------------------------------------------------------===//
7499
7501 LLVM_DEBUG({
7502 dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7503 << "Main Loop VF:" << EPI.MainLoopVF
7504 << ", Main Loop UF:" << EPI.MainLoopUF
7505 << ", Epilogue Loop VF:" << EPI.EpilogueVF
7506 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7507 });
7508}
7509
7512 dbgs() << "intermediate fn:\n"
7513 << *OrigLoop->getHeader()->getParent() << "\n";
7514 });
7515}
7516
7517//===--------------------------------------------------------------------===//
7518// EpilogueVectorizerEpilogueLoop
7519//===--------------------------------------------------------------------===//
7520
7521/// This function creates a new scalar preheader, using the previous one as
7522/// entry block to the epilogue VPlan. The minimum iteration check is being
7523/// represented in VPlan.
7525 BasicBlock *NewScalarPH = createScalarPreheader("vec.epilog.");
7526 BasicBlock *OriginalScalarPH = NewScalarPH->getSinglePredecessor();
7527 OriginalScalarPH->setName("vec.epilog.iter.check");
7528 VPIRBasicBlock *NewEntry = Plan.createVPIRBasicBlock(OriginalScalarPH);
7529 VPBasicBlock *OldEntry = Plan.getEntry();
7530 for (auto &R : make_early_inc_range(*OldEntry)) {
7531 // Skip moving VPIRInstructions (including VPIRPhis), which are unmovable by
7532 // defining.
7533 if (isa<VPIRInstruction>(&R))
7534 continue;
7535 R.moveBefore(*NewEntry, NewEntry->end());
7536 }
7537
7538 VPBlockUtils::reassociateBlocks(OldEntry, NewEntry);
7539 Plan.setEntry(NewEntry);
7540 // OldEntry is now dead and will be cleaned up when the plan gets destroyed.
7541
7542 return OriginalScalarPH;
7543}
7544
7546 LLVM_DEBUG({
7547 dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7548 << "Epilogue Loop VF:" << EPI.EpilogueVF
7549 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7550 });
7551}
7552
7555 dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
7556 });
7557}
7558
7559VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(VPInstruction *VPI,
7560 VFRange &Range) {
7561 assert((VPI->getOpcode() == Instruction::Load ||
7562 VPI->getOpcode() == Instruction::Store) &&
7563 "Must be called with either a load or store");
7565
7566 auto WillWiden = [&](ElementCount VF) -> bool {
7568 CM.getWideningDecision(I, VF);
7570 "CM decision should be taken at this point.");
7572 return true;
7573 if (CM.isScalarAfterVectorization(I, VF) ||
7574 CM.isProfitableToScalarize(I, VF))
7575 return false;
7577 };
7578
7580 return nullptr;
7581
7582 // If a mask is not required, drop it - use unmasked version for safe loads.
7583 // TODO: Determine if mask is needed in VPlan.
7584 VPValue *Mask = CM.isMaskRequired(I) ? VPI->getMask() : nullptr;
7585
7586 // Determine if the pointer operand of the access is either consecutive or
7587 // reverse consecutive.
7589 CM.getWideningDecision(I, Range.Start);
7591 bool Consecutive =
7593
7594 VPValue *Ptr = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
7595 : VPI->getOperand(1);
7596 if (Consecutive) {
7599 VPSingleDefRecipe *VectorPtr;
7600 if (Reverse) {
7601 // When folding the tail, we may compute an address that we don't in the
7602 // original scalar loop: drop the GEP no-wrap flags in this case.
7603 // Otherwise preserve existing flags without no-unsigned-wrap, as we will
7604 // emit negative indices.
7605 GEPNoWrapFlags Flags =
7606 CM.foldTailByMasking() || !GEP
7608 : GEP->getNoWrapFlags().withoutNoUnsignedWrap();
7609 VectorPtr = new VPVectorEndPointerRecipe(
7610 Ptr, &Plan.getVF(), getLoadStoreType(I),
7611 /*Stride*/ -1, Flags, VPI->getDebugLoc());
7612 } else {
7613 VectorPtr = new VPVectorPointerRecipe(Ptr, getLoadStoreType(I),
7614 GEP ? GEP->getNoWrapFlags()
7616 VPI->getDebugLoc());
7617 }
7618 Builder.insert(VectorPtr);
7619 Ptr = VectorPtr;
7620 }
7621
7622 if (VPI->getOpcode() == Instruction::Load) {
7623 auto *Load = cast<LoadInst>(I);
7624 auto *LoadR = new VPWidenLoadRecipe(*Load, Ptr, Mask, Consecutive, Reverse,
7625 *VPI, Load->getDebugLoc());
7626 if (Reverse) {
7627 Builder.insert(LoadR);
7628 return new VPInstruction(VPInstruction::Reverse, LoadR, {}, {},
7629 LoadR->getDebugLoc());
7630 }
7631 return LoadR;
7632 }
7633
7634 StoreInst *Store = cast<StoreInst>(I);
7635 VPValue *StoredVal = VPI->getOperand(0);
7636 if (Reverse)
7637 StoredVal = Builder.createNaryOp(VPInstruction::Reverse, StoredVal,
7638 Store->getDebugLoc());
7639 return new VPWidenStoreRecipe(*Store, Ptr, StoredVal, Mask, Consecutive,
7640 Reverse, *VPI, Store->getDebugLoc());
7641}
7642
7644VPRecipeBuilder::tryToOptimizeInductionTruncate(VPInstruction *VPI,
7645 VFRange &Range) {
7646 auto *I = cast<TruncInst>(VPI->getUnderlyingInstr());
7647 // Optimize the special case where the source is a constant integer
7648 // induction variable. Notice that we can only optimize the 'trunc' case
7649 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
7650 // (c) other casts depend on pointer size.
7651
7652 // Determine whether \p K is a truncation based on an induction variable that
7653 // can be optimized.
7656 I),
7657 Range))
7658 return nullptr;
7659
7661 VPI->getOperand(0)->getDefiningRecipe());
7662 PHINode *Phi = WidenIV->getPHINode();
7663 VPIRValue *Start = WidenIV->getStartValue();
7664 const InductionDescriptor &IndDesc = WidenIV->getInductionDescriptor();
7665
7666 // Wrap flags from the original induction do not apply to the truncated type,
7667 // so do not propagate them.
7668 VPIRFlags Flags = VPIRFlags::WrapFlagsTy(false, false);
7669 VPValue *Step =
7671 return new VPWidenIntOrFpInductionRecipe(
7672 Phi, Start, Step, &Plan.getVF(), IndDesc, I, Flags, VPI->getDebugLoc());
7673}
7674
7675VPSingleDefRecipe *VPRecipeBuilder::tryToWidenCall(VPInstruction *VPI,
7676 VFRange &Range) {
7677 CallInst *CI = cast<CallInst>(VPI->getUnderlyingInstr());
7679 [this, CI](ElementCount VF) {
7680 return CM.isScalarWithPredication(CI, VF);
7681 },
7682 Range);
7683
7684 if (IsPredicated)
7685 return nullptr;
7686
7688 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
7689 ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
7690 ID == Intrinsic::pseudoprobe ||
7691 ID == Intrinsic::experimental_noalias_scope_decl))
7692 return nullptr;
7693
7695 VPI->op_begin() + CI->arg_size());
7696
7697 // Is it beneficial to perform intrinsic call compared to lib call?
7698 bool ShouldUseVectorIntrinsic =
7700 [&](ElementCount VF) -> bool {
7701 return CM.getCallWideningDecision(CI, VF).Kind ==
7703 },
7704 Range);
7705 if (ShouldUseVectorIntrinsic)
7706 return new VPWidenIntrinsicRecipe(*CI, ID, Ops, CI->getType(), *VPI, *VPI,
7707 VPI->getDebugLoc());
7708
7709 Function *Variant = nullptr;
7710 std::optional<unsigned> MaskPos;
7711 // Is better to call a vectorized version of the function than to to scalarize
7712 // the call?
7713 auto ShouldUseVectorCall = LoopVectorizationPlanner::getDecisionAndClampRange(
7714 [&](ElementCount VF) -> bool {
7715 // The following case may be scalarized depending on the VF.
7716 // The flag shows whether we can use a usual Call for vectorized
7717 // version of the instruction.
7718
7719 // If we've found a variant at a previous VF, then stop looking. A
7720 // vectorized variant of a function expects input in a certain shape
7721 // -- basically the number of input registers, the number of lanes
7722 // per register, and whether there's a mask required.
7723 // We store a pointer to the variant in the VPWidenCallRecipe, so
7724 // once we have an appropriate variant it's only valid for that VF.
7725 // This will force a different vplan to be generated for each VF that
7726 // finds a valid variant.
7727 if (Variant)
7728 return false;
7729 LoopVectorizationCostModel::CallWideningDecision Decision =
7730 CM.getCallWideningDecision(CI, VF);
7732 Variant = Decision.Variant;
7733 MaskPos = Decision.MaskPos;
7734 return true;
7735 }
7736
7737 return false;
7738 },
7739 Range);
7740 if (ShouldUseVectorCall) {
7741 if (MaskPos.has_value()) {
7742 // We have 2 cases that would require a mask:
7743 // 1) The call needs to be predicated, either due to a conditional
7744 // in the scalar loop or use of an active lane mask with
7745 // tail-folding, and we use the appropriate mask for the block.
7746 // 2) No mask is required for the call instruction, but the only
7747 // available vector variant at this VF requires a mask, so we
7748 // synthesize an all-true mask.
7749 VPValue *Mask = VPI->isMasked() ? VPI->getMask() : Plan.getTrue();
7750
7751 Ops.insert(Ops.begin() + *MaskPos, Mask);
7752 }
7753
7754 Ops.push_back(VPI->getOperand(VPI->getNumOperandsWithoutMask() - 1));
7755 return new VPWidenCallRecipe(CI, Variant, Ops, *VPI, *VPI,
7756 VPI->getDebugLoc());
7757 }
7758
7759 return nullptr;
7760}
7761
7762bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
7764 "Instruction should have been handled earlier");
7765 // Instruction should be widened, unless it is scalar after vectorization,
7766 // scalarization is profitable or it is predicated.
7767 auto WillScalarize = [this, I](ElementCount VF) -> bool {
7768 return CM.isScalarAfterVectorization(I, VF) ||
7769 CM.isProfitableToScalarize(I, VF) ||
7770 CM.isScalarWithPredication(I, VF);
7771 };
7773 Range);
7774}
7775
7776VPWidenRecipe *VPRecipeBuilder::tryToWiden(VPInstruction *VPI) {
7777 auto *I = VPI->getUnderlyingInstr();
7778 switch (VPI->getOpcode()) {
7779 default:
7780 return nullptr;
7781 case Instruction::SDiv:
7782 case Instruction::UDiv:
7783 case Instruction::SRem:
7784 case Instruction::URem: {
7785 // If not provably safe, use a select to form a safe divisor before widening the
7786 // div/rem operation itself. Otherwise fall through to general handling below.
7787 if (CM.isPredicatedInst(I)) {
7789 VPValue *Mask = VPI->getMask();
7790 VPValue *One = Plan.getConstantInt(I->getType(), 1u);
7791 auto *SafeRHS =
7792 Builder.createSelect(Mask, Ops[1], One, VPI->getDebugLoc());
7793 Ops[1] = SafeRHS;
7794 return new VPWidenRecipe(*I, Ops, *VPI, *VPI, VPI->getDebugLoc());
7795 }
7796 [[fallthrough]];
7797 }
7798 case Instruction::Add:
7799 case Instruction::And:
7800 case Instruction::AShr:
7801 case Instruction::FAdd:
7802 case Instruction::FCmp:
7803 case Instruction::FDiv:
7804 case Instruction::FMul:
7805 case Instruction::FNeg:
7806 case Instruction::FRem:
7807 case Instruction::FSub:
7808 case Instruction::ICmp:
7809 case Instruction::LShr:
7810 case Instruction::Mul:
7811 case Instruction::Or:
7812 case Instruction::Select:
7813 case Instruction::Shl:
7814 case Instruction::Sub:
7815 case Instruction::Xor:
7816 case Instruction::Freeze:
7817 return new VPWidenRecipe(*I, VPI->operandsWithoutMask(), *VPI, *VPI,
7818 VPI->getDebugLoc());
7819 case Instruction::ExtractValue: {
7821 auto *EVI = cast<ExtractValueInst>(I);
7822 assert(EVI->getNumIndices() == 1 && "Expected one extractvalue index");
7823 unsigned Idx = EVI->getIndices()[0];
7824 NewOps.push_back(Plan.getConstantInt(32, Idx));
7825 return new VPWidenRecipe(*I, NewOps, *VPI, *VPI, VPI->getDebugLoc());
7826 }
7827 };
7828}
7829
7830VPHistogramRecipe *VPRecipeBuilder::tryToWidenHistogram(const HistogramInfo *HI,
7831 VPInstruction *VPI) {
7832 // FIXME: Support other operations.
7833 unsigned Opcode = HI->Update->getOpcode();
7834 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
7835 "Histogram update operation must be an Add or Sub");
7836
7838 // Bucket address.
7839 HGramOps.push_back(VPI->getOperand(1));
7840 // Increment value.
7841 HGramOps.push_back(getVPValueOrAddLiveIn(HI->Update->getOperand(1)));
7842
7843 // In case of predicated execution (due to tail-folding, or conditional
7844 // execution, or both), pass the relevant mask.
7845 if (CM.isMaskRequired(HI->Store))
7846 HGramOps.push_back(VPI->getMask());
7847
7848 return new VPHistogramRecipe(Opcode, HGramOps, VPI->getDebugLoc());
7849}
7850
7852 VFRange &Range) {
7853 auto *I = VPI->getUnderlyingInstr();
7855 [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
7856 Range);
7857
7858 bool IsPredicated = CM.isPredicatedInst(I);
7859
7860 // Even if the instruction is not marked as uniform, there are certain
7861 // intrinsic calls that can be effectively treated as such, so we check for
7862 // them here. Conservatively, we only do this for scalable vectors, since
7863 // for fixed-width VFs we can always fall back on full scalarization.
7864 if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
7865 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
7866 case Intrinsic::assume:
7867 case Intrinsic::lifetime_start:
7868 case Intrinsic::lifetime_end:
7869 // For scalable vectors if one of the operands is variant then we still
7870 // want to mark as uniform, which will generate one instruction for just
7871 // the first lane of the vector. We can't scalarize the call in the same
7872 // way as for fixed-width vectors because we don't know how many lanes
7873 // there are.
7874 //
7875 // The reasons for doing it this way for scalable vectors are:
7876 // 1. For the assume intrinsic generating the instruction for the first
7877 // lane is still be better than not generating any at all. For
7878 // example, the input may be a splat across all lanes.
7879 // 2. For the lifetime start/end intrinsics the pointer operand only
7880 // does anything useful when the input comes from a stack object,
7881 // which suggests it should always be uniform. For non-stack objects
7882 // the effect is to poison the object, which still allows us to
7883 // remove the call.
7884 IsUniform = true;
7885 break;
7886 default:
7887 break;
7888 }
7889 }
7890 VPValue *BlockInMask = nullptr;
7891 if (!IsPredicated) {
7892 // Finalize the recipe for Instr, first if it is not predicated.
7893 LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
7894 } else {
7895 LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
7896 // Instructions marked for predication are replicated and a mask operand is
7897 // added initially. Masked replicate recipes will later be placed under an
7898 // if-then construct to prevent side-effects. Generate recipes to compute
7899 // the block mask for this region.
7900 BlockInMask = VPI->getMask();
7901 }
7902
7903 // Note that there is some custom logic to mark some intrinsics as uniform
7904 // manually above for scalable vectors, which this assert needs to account for
7905 // as well.
7906 assert((Range.Start.isScalar() || !IsUniform || !IsPredicated ||
7907 (Range.Start.isScalable() && isa<IntrinsicInst>(I))) &&
7908 "Should not predicate a uniform recipe");
7909 auto *Recipe =
7910 new VPReplicateRecipe(I, VPI->operandsWithoutMask(), IsUniform,
7911 BlockInMask, *VPI, *VPI, VPI->getDebugLoc());
7912 return Recipe;
7913}
7914
7917 VFRange &Range) {
7918 assert(!R->isPhi() && "phis must be handled earlier");
7919 // First, check for specific widening recipes that deal with optimizing
7920 // truncates, calls and memory operations.
7921
7922 VPRecipeBase *Recipe;
7923 auto *VPI = cast<VPInstruction>(R);
7924 if (VPI->getOpcode() == Instruction::Trunc &&
7925 (Recipe = tryToOptimizeInductionTruncate(VPI, Range)))
7926 return Recipe;
7927
7928 // All widen recipes below deal only with VF > 1.
7930 [&](ElementCount VF) { return VF.isScalar(); }, Range))
7931 return nullptr;
7932
7933 if (VPI->getOpcode() == Instruction::Call)
7934 return tryToWidenCall(VPI, Range);
7935
7936 Instruction *Instr = R->getUnderlyingInstr();
7937 if (VPI->getOpcode() == Instruction::Store)
7938 if (auto HistInfo = Legal->getHistogramInfo(cast<StoreInst>(Instr)))
7939 return tryToWidenHistogram(*HistInfo, VPI);
7940
7941 if (VPI->getOpcode() == Instruction::Load ||
7942 VPI->getOpcode() == Instruction::Store)
7943 return tryToWidenMemory(VPI, Range);
7944
7945 if (!shouldWiden(Instr, Range))
7946 return nullptr;
7947
7948 if (VPI->getOpcode() == Instruction::GetElementPtr)
7949 return new VPWidenGEPRecipe(cast<GetElementPtrInst>(Instr),
7950 VPI->operandsWithoutMask(), *VPI,
7951 VPI->getDebugLoc());
7952
7953 if (Instruction::isCast(VPI->getOpcode())) {
7954 auto *CI = cast<CastInst>(Instr);
7955 auto *CastR = cast<VPInstructionWithType>(VPI);
7956 return new VPWidenCastRecipe(CI->getOpcode(), VPI->getOperand(0),
7957 CastR->getResultType(), CI, *VPI, *VPI,
7958 VPI->getDebugLoc());
7959 }
7960
7961 return tryToWiden(VPI);
7962}
7963
7964void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
7965 ElementCount MaxVF) {
7966 if (ElementCount::isKnownGT(MinVF, MaxVF))
7967 return;
7968
7969 assert(OrigLoop->isInnermost() && "Inner loop expected.");
7970
7971 const LoopAccessInfo *LAI = Legal->getLAI();
7973 OrigLoop, LI, DT, PSE.getSE());
7974 if (!LAI->getRuntimePointerChecking()->getChecks().empty() &&
7976 // Only use noalias metadata when using memory checks guaranteeing no
7977 // overlap across all iterations.
7978 LVer.prepareNoAliasMetadata();
7979 }
7980
7981 // Create initial base VPlan0, to serve as common starting point for all
7982 // candidates built later for specific VF ranges.
7983 auto VPlan0 = VPlanTransforms::buildVPlan0(
7984 OrigLoop, *LI, Legal->getWidestInductionType(),
7985 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE, &LVer);
7986
7987 // Create recipes for header phis.
7989 *VPlan0, PSE, *OrigLoop, Legal->getInductionVars(),
7990 Legal->getReductionVars(), Legal->getFixedOrderRecurrences(),
7991 CM.getInLoopReductions(), Hints.allowReordering());
7992
7994 // If we're vectorizing a loop with an uncountable exit, make sure that the
7995 // recipes are safe to handle.
7996 // TODO: Remove this once we can properly check the VPlan itself for both
7997 // the presence of an uncountable exit and the presence of stores in
7998 // the loop inside handleEarlyExits itself.
8000 if (Legal->hasUncountableEarlyExit())
8001 EEStyle = Legal->hasUncountableExitWithSideEffects()
8004
8005 if (!VPlanTransforms::handleEarlyExits(*VPlan0, EEStyle, OrigLoop, PSE, *DT,
8006 Legal->getAssumptionCache()))
8007 return;
8010 if (CM.foldTailByMasking())
8013 *VPlan0);
8014
8015 auto MaxVFTimes2 = MaxVF * 2;
8016 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
8017 VFRange SubRange = {VF, MaxVFTimes2};
8018 if (auto Plan = tryToBuildVPlanWithVPRecipes(
8019 std::unique_ptr<VPlan>(VPlan0->duplicate()), SubRange, &LVer)) {
8020 // Now optimize the initial VPlan.
8021 VPlanTransforms::hoistPredicatedLoads(*Plan, PSE, OrigLoop);
8022 VPlanTransforms::sinkPredicatedStores(*Plan, PSE, OrigLoop);
8024 CM.getMinimalBitwidths());
8026 // TODO: try to put addExplicitVectorLength close to addActiveLaneMask
8027 if (CM.foldTailWithEVL()) {
8029 CM.getMaxSafeElements());
8031 }
8032
8033 if (auto P = VPlanTransforms::narrowInterleaveGroups(*Plan, TTI))
8034 VPlans.push_back(std::move(P));
8035
8036 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8037 VPlans.push_back(std::move(Plan));
8038 }
8039 VF = SubRange.End;
8040 }
8041}
8042
8043VPlanPtr LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(
8044 VPlanPtr Plan, VFRange &Range, LoopVersioning *LVer) {
8045
8046 using namespace llvm::VPlanPatternMatch;
8047 SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8048
8049 // ---------------------------------------------------------------------------
8050 // Build initial VPlan: Scan the body of the loop in a topological order to
8051 // visit each basic block after having visited its predecessor basic blocks.
8052 // ---------------------------------------------------------------------------
8053
8054 bool RequiresScalarEpilogueCheck =
8056 [this](ElementCount VF) {
8057 return !CM.requiresScalarEpilogue(VF.isVector());
8058 },
8059 Range);
8060 // Update the branch in the middle block if a scalar epilogue is required.
8061 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
8062 if (!RequiresScalarEpilogueCheck && MiddleVPBB->getNumSuccessors() == 2) {
8063 auto *BranchOnCond = cast<VPInstruction>(MiddleVPBB->getTerminator());
8064 assert(MiddleVPBB->getSuccessors()[1] == Plan->getScalarPreheader() &&
8065 "second successor must be scalar preheader");
8066 BranchOnCond->setOperand(0, Plan->getFalse());
8067 }
8068
8069 // Don't use getDecisionAndClampRange here, because we don't know the UF
8070 // so this function is better to be conservative, rather than to split
8071 // it up into different VPlans.
8072 // TODO: Consider using getDecisionAndClampRange here to split up VPlans.
8073 bool IVUpdateMayOverflow = false;
8074 for (ElementCount VF : Range)
8075 IVUpdateMayOverflow |= !isIndvarOverflowCheckKnownFalse(&CM, VF);
8076
8077 TailFoldingStyle Style = CM.getTailFoldingStyle();
8078 // Use NUW for the induction increment if we proved that it won't overflow in
8079 // the vector loop or when not folding the tail. In the later case, we know
8080 // that the canonical induction increment will not overflow as the vector trip
8081 // count is >= increment and a multiple of the increment.
8082 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
8083 bool HasNUW = !IVUpdateMayOverflow || Style == TailFoldingStyle::None;
8084 if (!HasNUW) {
8085 auto *IVInc =
8086 LoopRegion->getExitingBasicBlock()->getTerminator()->getOperand(0);
8087 assert(match(IVInc,
8088 m_VPInstruction<Instruction::Add>(
8089 m_Specific(LoopRegion->getCanonicalIV()), m_VPValue())) &&
8090 "Did not find the canonical IV increment");
8091 cast<VPRecipeWithIRFlags>(IVInc)->dropPoisonGeneratingFlags();
8092 }
8093
8094 // ---------------------------------------------------------------------------
8095 // Pre-construction: record ingredients whose recipes we'll need to further
8096 // process after constructing the initial VPlan.
8097 // ---------------------------------------------------------------------------
8098
8099 // For each interleave group which is relevant for this (possibly trimmed)
8100 // Range, add it to the set of groups to be later applied to the VPlan and add
8101 // placeholders for its members' Recipes which we'll be replacing with a
8102 // single VPInterleaveRecipe.
8103 for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8104 auto ApplyIG = [IG, this](ElementCount VF) -> bool {
8105 bool Result = (VF.isVector() && // Query is illegal for VF == 1
8106 CM.getWideningDecision(IG->getInsertPos(), VF) ==
8108 // For scalable vectors, the interleave factors must be <= 8 since we
8109 // require the (de)interleaveN intrinsics instead of shufflevectors.
8110 assert((!Result || !VF.isScalable() || IG->getFactor() <= 8) &&
8111 "Unsupported interleave factor for scalable vectors");
8112 return Result;
8113 };
8114 if (!getDecisionAndClampRange(ApplyIG, Range))
8115 continue;
8116 InterleaveGroups.insert(IG);
8117 }
8118
8119 // ---------------------------------------------------------------------------
8120 // Construct wide recipes and apply predication for original scalar
8121 // VPInstructions in the loop.
8122 // ---------------------------------------------------------------------------
8123 VPRecipeBuilder RecipeBuilder(*Plan, TLI, Legal, CM, Builder);
8124
8125 // Scan the body of the loop in a topological order to visit each basic block
8126 // after having visited its predecessor basic blocks.
8127 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
8128 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> RPOT(
8129 HeaderVPBB);
8130
8131 VPBasicBlock::iterator MBIP = MiddleVPBB->getFirstNonPhi();
8132
8133 // Collect blocks that need predication for in-loop reduction recipes.
8134 DenseSet<BasicBlock *> BlocksNeedingPredication;
8135 for (BasicBlock *BB : OrigLoop->blocks())
8136 if (CM.blockNeedsPredicationForAnyReason(BB))
8137 BlocksNeedingPredication.insert(BB);
8138
8139 VPlanTransforms::createInLoopReductionRecipes(*Plan, BlocksNeedingPredication,
8140 Range.Start);
8141
8142 // Now process all other blocks and instructions.
8143 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
8144 // Convert input VPInstructions to widened recipes.
8145 for (VPRecipeBase &R : make_early_inc_range(
8146 make_range(VPBB->getFirstNonPhi(), VPBB->end()))) {
8147 // Skip recipes that do not need transforming.
8149 continue;
8150 auto *VPI = cast<VPInstruction>(&R);
8151 if (!VPI->getUnderlyingValue())
8152 continue;
8153
8154 // TODO: Gradually replace uses of underlying instruction by analyses on
8155 // VPlan. Migrate code relying on the underlying instruction from VPlan0
8156 // to construct recipes below to not use the underlying instruction.
8158 Builder.setInsertPoint(VPI);
8159
8160 // The stores with invariant address inside the loop will be deleted, and
8161 // in the exit block, a uniform store recipe will be created for the final
8162 // invariant store of the reduction.
8163 StoreInst *SI;
8164 if ((SI = dyn_cast<StoreInst>(Instr)) &&
8165 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
8166 // Only create recipe for the final invariant store of the reduction.
8167 if (Legal->isInvariantStoreOfReduction(SI)) {
8168 auto *Recipe = new VPReplicateRecipe(
8169 SI, VPI->operandsWithoutMask(), true /* IsUniform */,
8170 nullptr /*Mask*/, *VPI, *VPI, VPI->getDebugLoc());
8171 Recipe->insertBefore(*MiddleVPBB, MBIP);
8172 }
8173 R.eraseFromParent();
8174 continue;
8175 }
8176
8177 VPRecipeBase *Recipe =
8178 RecipeBuilder.tryToCreateWidenNonPhiRecipe(VPI, Range);
8179 if (!Recipe)
8180 Recipe =
8181 RecipeBuilder.handleReplication(cast<VPInstruction>(VPI), Range);
8182
8183 RecipeBuilder.setRecipe(Instr, Recipe);
8184 if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) && isa<TruncInst>(Instr)) {
8185 // Optimized a truncate to VPWidenIntOrFpInductionRecipe. It needs to be
8186 // moved to the phi section in the header.
8187 Recipe->insertBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8188 } else {
8189 Builder.insert(Recipe);
8190 }
8191 if (Recipe->getNumDefinedValues() == 1) {
8192 VPI->replaceAllUsesWith(Recipe->getVPSingleValue());
8193 } else {
8194 assert(Recipe->getNumDefinedValues() == 0 &&
8195 "Unexpected multidef recipe");
8196 }
8197 R.eraseFromParent();
8198 }
8199 }
8200
8201 assert(isa<VPRegionBlock>(LoopRegion) &&
8202 !LoopRegion->getEntryBasicBlock()->empty() &&
8203 "entry block must be set to a VPRegionBlock having a non-empty entry "
8204 "VPBasicBlock");
8205
8206 // TODO: We can't call runPass on these transforms yet, due to verifier
8207 // failures.
8209
8210 // ---------------------------------------------------------------------------
8211 // Transform initial VPlan: Apply previously taken decisions, in order, to
8212 // bring the VPlan to its final state.
8213 // ---------------------------------------------------------------------------
8214
8215 addReductionResultComputation(Plan, RecipeBuilder, Range.Start);
8216
8217 // Optimize FindIV reductions to use sentinel-based approach when possible.
8219 *OrigLoop);
8221 CM.foldTailByMasking());
8222
8223 // Apply mandatory transformation to handle reductions with multiple in-loop
8224 // uses if possible, bail out otherwise.
8226 OrigLoop))
8227 return nullptr;
8228 // Apply mandatory transformation to handle FP maxnum/minnum reduction with
8229 // NaNs if possible, bail out otherwise.
8231 return nullptr;
8232
8233 // Create whole-vector selects for find-last recurrences.
8235 return nullptr;
8236
8237 // Create partial reduction recipes for scaled reductions and transform
8238 // recipes to abstract recipes if it is legal and beneficial and clamp the
8239 // range for better cost estimation.
8240 // TODO: Enable following transform when the EVL-version of extended-reduction
8241 // and mulacc-reduction are implemented.
8242 if (!CM.foldTailWithEVL()) {
8243 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind, CM.PSE,
8244 OrigLoop);
8246 Range);
8248 Range);
8249 }
8250
8251 for (ElementCount VF : Range)
8252 Plan->addVF(VF);
8253 Plan->setName("Initial VPlan");
8254
8255 // Interleave memory: for each Interleave Group we marked earlier as relevant
8256 // for this VPlan, replace the Recipes widening its memory instructions with a
8257 // single VPInterleaveRecipe at its insertion point.
8259 InterleaveGroups, RecipeBuilder, CM.isScalarEpilogueAllowed());
8260
8261 // Replace VPValues for known constant strides.
8263 Legal->getLAI()->getSymbolicStrides());
8264
8265 auto BlockNeedsPredication = [this](BasicBlock *BB) {
8266 return Legal->blockNeedsPredication(BB);
8267 };
8269 BlockNeedsPredication);
8270
8271 // Sink users of fixed-order recurrence past the recipe defining the previous
8272 // value and introduce FirstOrderRecurrenceSplice VPInstructions.
8274 Builder))
8275 return nullptr;
8276
8277 if (useActiveLaneMask(Style)) {
8278 // TODO: Move checks to VPlanTransforms::addActiveLaneMask once
8279 // TailFoldingStyle is visible there.
8280 bool ForControlFlow = useActiveLaneMaskForControlFlow(Style);
8281 VPlanTransforms::addActiveLaneMask(*Plan, ForControlFlow);
8282 }
8283
8284 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8285 return Plan;
8286}
8287
8288VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VFRange &Range) {
8289 // Outer loop handling: They may require CFG and instruction level
8290 // transformations before even evaluating whether vectorization is profitable.
8291 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
8292 // the vectorization pipeline.
8293 assert(!OrigLoop->isInnermost());
8294 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
8295
8296 auto Plan = VPlanTransforms::buildVPlan0(
8297 OrigLoop, *LI, Legal->getWidestInductionType(),
8298 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE);
8299
8301 *Plan, PSE, *OrigLoop, Legal->getInductionVars(),
8302 MapVector<PHINode *, RecurrenceDescriptor>(),
8303 SmallPtrSet<const PHINode *, 1>(), SmallPtrSet<PHINode *, 1>(),
8304 /*AllowReordering=*/false);
8305 [[maybe_unused]] bool CanHandleExits = VPlanTransforms::handleEarlyExits(
8306 *Plan, UncountableExitStyle::NoUncountableExit, OrigLoop, PSE, *DT,
8307 Legal->getAssumptionCache());
8308 assert(CanHandleExits &&
8309 "early-exits are not supported in VPlan-native path");
8310 VPlanTransforms::addMiddleCheck(*Plan, /*TailFolded*/ false);
8311
8313
8314 for (ElementCount VF : Range)
8315 Plan->addVF(VF);
8316
8318 return nullptr;
8319
8320 // Optimize induction live-out users to use precomputed end values.
8322 /*FoldTail=*/false);
8323
8324 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8325 return Plan;
8326}
8327
8328void LoopVectorizationPlanner::addReductionResultComputation(
8329 VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
8330 using namespace VPlanPatternMatch;
8331 VPTypeAnalysis TypeInfo(*Plan);
8332 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
8333 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
8335 VPBasicBlock *LatchVPBB = VectorLoopRegion->getExitingBasicBlock();
8336 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->end())));
8337 VPBasicBlock::iterator IP = MiddleVPBB->getFirstNonPhi();
8338 for (VPRecipeBase &R :
8339 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8340 VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
8341 // TODO: Remove check for constant incoming value once removeDeadRecipes is
8342 // used on VPlan0.
8343 if (!PhiR || isa<VPIRValue>(PhiR->getOperand(1)))
8344 continue;
8345
8346 RecurKind RecurrenceKind = PhiR->getRecurrenceKind();
8347 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
8349 Type *PhiTy = TypeInfo.inferScalarType(PhiR);
8350 // If tail is folded by masking, introduce selects between the phi
8351 // and the users outside the vector region of each reduction, at the
8352 // beginning of the dedicated latch block.
8353 auto *OrigExitingVPV = PhiR->getBackedgeValue();
8354 auto *NewExitingVPV = PhiR->getBackedgeValue();
8355 // Don't output selects for partial reductions because they have an output
8356 // with fewer lanes than the VF. So the operands of the select would have
8357 // different numbers of lanes. Partial reductions mask the input instead.
8358 auto *RR = dyn_cast<VPReductionRecipe>(OrigExitingVPV->getDefiningRecipe());
8359 if (!PhiR->isInLoop() && CM.foldTailByMasking() &&
8360 (!RR || !RR->isPartialReduction())) {
8361 VPValue *Cond = vputils::findHeaderMask(*Plan);
8362 NewExitingVPV =
8363 Builder.createSelect(Cond, OrigExitingVPV, PhiR, {}, "", *PhiR);
8364 OrigExitingVPV->replaceUsesWithIf(NewExitingVPV, [](VPUser &U, unsigned) {
8365 using namespace VPlanPatternMatch;
8366 return match(
8367 &U, m_CombineOr(
8368 m_VPInstruction<VPInstruction::ComputeAnyOfResult>(),
8369 m_VPInstruction<VPInstruction::ComputeReductionResult>()));
8370 });
8371
8372 if (CM.usePredicatedReductionSelect(RecurrenceKind))
8373 PhiR->setOperand(1, NewExitingVPV);
8374 }
8375
8376 // We want code in the middle block to appear to execute on the location of
8377 // the scalar loop's latch terminator because: (a) it is all compiler
8378 // generated, (b) these instructions are always executed after evaluating
8379 // the latch conditional branch, and (c) other passes may add new
8380 // predecessors which terminate on this line. This is the easiest way to
8381 // ensure we don't accidentally cause an extra step back into the loop while
8382 // debugging.
8383 DebugLoc ExitDL = OrigLoop->getLoopLatch()->getTerminator()->getDebugLoc();
8384
8385 // TODO: At the moment ComputeReductionResult also drives creation of the
8386 // bc.merge.rdx phi nodes, hence it needs to be created unconditionally here
8387 // even for in-loop reductions, until the reduction resume value handling is
8388 // also modeled in VPlan.
8389 VPInstruction *FinalReductionResult;
8390 VPBuilder::InsertPointGuard Guard(Builder);
8391 Builder.setInsertPoint(MiddleVPBB, IP);
8392 // For AnyOf reductions, find the select among PhiR's users. This is used
8393 // both to find NewVal for ComputeAnyOfResult and to adjust the reduction.
8394 VPRecipeBase *AnyOfSelect = nullptr;
8395 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
8396 AnyOfSelect = cast<VPRecipeBase>(*find_if(PhiR->users(), [](VPUser *U) {
8397 return match(U, m_Select(m_VPValue(), m_VPValue(), m_VPValue()));
8398 }));
8399 }
8400 if (AnyOfSelect) {
8401 VPValue *Start = PhiR->getStartValue();
8402 // NewVal is the non-phi operand of the select.
8403 VPValue *NewVal = AnyOfSelect->getOperand(1) == PhiR
8404 ? AnyOfSelect->getOperand(2)
8405 : AnyOfSelect->getOperand(1);
8406 VPIRFlags OrFlags(RecurKind::Or, /*IsOrdered=*/false,
8407 /*IsInLoop=*/false, FastMathFlags());
8408 auto *OrReduce =
8409 Builder.createNaryOp(VPInstruction::ComputeReductionResult,
8410 {NewExitingVPV}, OrFlags, ExitDL);
8411 FinalReductionResult = Builder.createNaryOp(
8412 VPInstruction::ComputeAnyOfResult, {Start, NewVal, OrReduce}, ExitDL);
8413 } else {
8414 VPIRFlags Flags(RecurrenceKind, PhiR->isOrdered(), PhiR->isInLoop(),
8415 PhiR->getFastMathFlags());
8416 FinalReductionResult =
8417 Builder.createNaryOp(VPInstruction::ComputeReductionResult,
8418 {NewExitingVPV}, Flags, ExitDL);
8419 }
8420 // If the vector reduction can be performed in a smaller type, we truncate
8421 // then extend the loop exit value to enable InstCombine to evaluate the
8422 // entire expression in the smaller type.
8423 if (MinVF.isVector() && PhiTy != RdxDesc.getRecurrenceType() &&
8425 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
8427 "Unexpected truncated min-max recurrence!");
8428 Type *RdxTy = RdxDesc.getRecurrenceType();
8429 VPWidenCastRecipe *Trunc;
8430 Instruction::CastOps ExtendOpc =
8431 RdxDesc.isSigned() ? Instruction::SExt : Instruction::ZExt;
8432 VPWidenCastRecipe *Extnd;
8433 {
8434 VPBuilder::InsertPointGuard Guard(Builder);
8435 Builder.setInsertPoint(
8436 NewExitingVPV->getDefiningRecipe()->getParent(),
8437 std::next(NewExitingVPV->getDefiningRecipe()->getIterator()));
8438 Trunc =
8439 Builder.createWidenCast(Instruction::Trunc, NewExitingVPV, RdxTy);
8440 Extnd = Builder.createWidenCast(ExtendOpc, Trunc, PhiTy);
8441 }
8442 if (PhiR->getOperand(1) == NewExitingVPV)
8443 PhiR->setOperand(1, Extnd->getVPSingleValue());
8444
8445 // Update ComputeReductionResult with the truncated exiting value and
8446 // extend its result. Operand 0 provides the values to be reduced.
8447 FinalReductionResult->setOperand(0, Trunc);
8448 FinalReductionResult =
8449 Builder.createScalarCast(ExtendOpc, FinalReductionResult, PhiTy, {});
8450 }
8451
8452 // Update all users outside the vector region. Also replace redundant
8453 // extracts.
8454 for (auto *U : to_vector(OrigExitingVPV->users())) {
8455 auto *Parent = cast<VPRecipeBase>(U)->getParent();
8456 if (FinalReductionResult == U || Parent->getParent())
8457 continue;
8458 // Skip ComputeReductionResult and FindIV reductions when they are not the
8459 // final result.
8460 if (match(U, m_VPInstruction<VPInstruction::ComputeReductionResult>()) ||
8462 match(U, m_VPInstruction<Instruction::ICmp>())))
8463 continue;
8464 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
8465
8466 // Look through ExtractLastPart.
8468 U = cast<VPInstruction>(U)->getSingleUser();
8469
8472 cast<VPInstruction>(U)->replaceAllUsesWith(FinalReductionResult);
8473 }
8474
8475 // Adjust AnyOf reductions; replace the reduction phi for the selected value
8476 // with a boolean reduction phi node to check if the condition is true in
8477 // any iteration. The final value is selected by the final
8478 // ComputeReductionResult.
8479 if (AnyOfSelect) {
8480 VPValue *Cmp = AnyOfSelect->getOperand(0);
8481 // If the compare is checking the reduction PHI node, adjust it to check
8482 // the start value.
8483 if (VPRecipeBase *CmpR = Cmp->getDefiningRecipe())
8484 CmpR->replaceUsesOfWith(PhiR, PhiR->getStartValue());
8485 Builder.setInsertPoint(AnyOfSelect);
8486
8487 // If the true value of the select is the reduction phi, the new value is
8488 // selected if the negated condition is true in any iteration.
8489 if (AnyOfSelect->getOperand(1) == PhiR)
8490 Cmp = Builder.createNot(Cmp);
8491 VPValue *Or = Builder.createOr(PhiR, Cmp);
8492 AnyOfSelect->getVPSingleValue()->replaceAllUsesWith(Or);
8493 // Delete AnyOfSelect now that it has invalid types.
8494 ToDelete.push_back(AnyOfSelect);
8495
8496 // Convert the reduction phi to operate on bools.
8497 PhiR->setOperand(0, Plan->getFalse());
8498 continue;
8499 }
8500
8501 RecurKind RK = PhiR->getRecurrenceKind();
8506 VPBuilder PHBuilder(Plan->getVectorPreheader());
8507 VPValue *Iden = Plan->getOrAddLiveIn(
8508 getRecurrenceIdentity(RK, PhiTy, PhiR->getFastMathFlags()));
8509 auto *ScaleFactorVPV = Plan->getConstantInt(32, 1);
8510 VPValue *StartV = PHBuilder.createNaryOp(
8512 {PhiR->getStartValue(), Iden, ScaleFactorVPV}, *PhiR);
8513 PhiR->setOperand(0, StartV);
8514 }
8515 }
8516 for (VPRecipeBase *R : ToDelete)
8517 R->eraseFromParent();
8518
8520}
8521
8523 VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const {
8524 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
8525 if (SCEVCheckBlock && SCEVCheckBlock->hasNPredecessors(0)) {
8526 assert((!CM.OptForSize ||
8527 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled) &&
8528 "Cannot SCEV check stride or overflow when optimizing for size");
8529 VPlanTransforms::attachCheckBlock(Plan, SCEVCheckCond, SCEVCheckBlock,
8530 HasBranchWeights);
8531 }
8532 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
8533 if (MemCheckBlock && MemCheckBlock->hasNPredecessors(0)) {
8534 // VPlan-native path does not do any analysis for runtime checks
8535 // currently.
8536 assert((!EnableVPlanNativePath || OrigLoop->isInnermost()) &&
8537 "Runtime checks are not supported for outer loops yet");
8538
8539 if (CM.OptForSize) {
8540 assert(
8541 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
8542 "Cannot emit memory checks when optimizing for size, unless forced "
8543 "to vectorize.");
8544 ORE->emit([&]() {
8545 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
8546 OrigLoop->getStartLoc(),
8547 OrigLoop->getHeader())
8548 << "Code-size may be reduced by not forcing "
8549 "vectorization, or by source-code modifications "
8550 "eliminating the need for runtime checks "
8551 "(e.g., adding 'restrict').";
8552 });
8553 }
8554 VPlanTransforms::attachCheckBlock(Plan, MemCheckCond, MemCheckBlock,
8555 HasBranchWeights);
8556 }
8557}
8558
8560 VPlan &Plan, ElementCount VF, unsigned UF,
8561 ElementCount MinProfitableTripCount) const {
8562 const uint32_t *BranchWeights =
8563 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator())
8565 : nullptr;
8567 Plan, VF, UF, MinProfitableTripCount,
8568 CM.requiresScalarEpilogue(VF.isVector()), CM.foldTailByMasking(),
8569 OrigLoop, BranchWeights,
8570 OrigLoop->getLoopPredecessor()->getTerminator()->getDebugLoc(), PSE);
8571}
8572
8573// Determine how to lower the scalar epilogue, which depends on 1) optimising
8574// for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
8575// predication, and 4) a TTI hook that analyses whether the loop is suitable
8576// for predication.
8578 Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize,
8581 // 1) OptSize takes precedence over all other options, i.e. if this is set,
8582 // don't look at hints or options, and don't request a scalar epilogue.
8583 if (F->hasOptSize() ||
8584 (OptForSize && Hints.getForce() != LoopVectorizeHints::FK_Enabled))
8586
8587 // 2) If set, obey the directives
8588 if (PreferPredicateOverEpilogue.getNumOccurrences()) {
8596 };
8597 }
8598
8599 // 3) If set, obey the hints
8600 switch (Hints.getPredicate()) {
8605 };
8606
8607 // 4) if the TTI hook indicates this is profitable, request predication.
8608 TailFoldingInfo TFI(TLI, &LVL, IAI);
8609 if (TTI->preferPredicateOverEpilogue(&TFI))
8611
8613}
8614
8615// Process the loop in the VPlan-native vectorization path. This path builds
8616// VPlan upfront in the vectorization pipeline, which allows to apply
8617// VPlan-to-VPlan transformations from the very beginning without modifying the
8618// input LLVM IR.
8624 std::function<BlockFrequencyInfo &()> GetBFI, bool OptForSize,
8625 LoopVectorizeHints &Hints, LoopVectorizationRequirements &Requirements) {
8626
8628 LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
8629 return false;
8630 }
8631 assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
8632 Function *F = L->getHeader()->getParent();
8633 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
8634
8636 getScalarEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, *LVL, &IAI);
8637
8638 LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE,
8639 GetBFI, F, &Hints, IAI, OptForSize);
8640 // Use the planner for outer loop vectorization.
8641 // TODO: CM is not used at this point inside the planner. Turn CM into an
8642 // optional argument if we don't need it in the future.
8643 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, LVL, CM, IAI, PSE, Hints,
8644 ORE);
8645
8646 // Get user vectorization factor.
8647 ElementCount UserVF = Hints.getWidth();
8648
8650
8651 // Plan how to best vectorize, return the best VF and its cost.
8652 const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
8653
8654 // If we are stress testing VPlan builds, do not attempt to generate vector
8655 // code. Masked vector code generation support will follow soon.
8656 // Also, do not attempt to vectorize if no vector code will be produced.
8658 return false;
8659
8660 VPlan &BestPlan = LVP.getPlanFor(VF.Width);
8661
8662 {
8663 GeneratedRTChecks Checks(PSE, DT, LI, TTI, CM.CostKind);
8664 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, /*UF=*/1, &CM,
8665 Checks, BestPlan);
8666 LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \"" << F->getName()
8667 << "\"\n");
8668 LVP.addMinimumIterationCheck(BestPlan, VF.Width, /*UF=*/1,
8670 bool HasBranchWeights =
8671 hasBranchWeightMD(*L->getLoopLatch()->getTerminator());
8672 LVP.attachRuntimeChecks(BestPlan, Checks, HasBranchWeights);
8673
8674 reportVectorization(ORE, L, VF, 1);
8675
8676 LVP.executePlan(VF.Width, /*UF=*/1, BestPlan, LB, DT);
8677 }
8678
8679 assert(!verifyFunction(*F, &dbgs()));
8680 return true;
8681}
8682
8683// Emit a remark if there are stores to floats that required a floating point
8684// extension. If the vectorized loop was generated with floating point there
8685// will be a performance penalty from the conversion overhead and the change in
8686// the vector width.
8689 for (BasicBlock *BB : L->getBlocks()) {
8690 for (Instruction &Inst : *BB) {
8691 if (auto *S = dyn_cast<StoreInst>(&Inst)) {
8692 if (S->getValueOperand()->getType()->isFloatTy())
8693 Worklist.push_back(S);
8694 }
8695 }
8696 }
8697
8698 // Traverse the floating point stores upwards searching, for floating point
8699 // conversions.
8702 while (!Worklist.empty()) {
8703 auto *I = Worklist.pop_back_val();
8704 if (!L->contains(I))
8705 continue;
8706 if (!Visited.insert(I).second)
8707 continue;
8708
8709 // Emit a remark if the floating point store required a floating
8710 // point conversion.
8711 // TODO: More work could be done to identify the root cause such as a
8712 // constant or a function return type and point the user to it.
8713 if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
8714 ORE->emit([&]() {
8715 return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
8716 I->getDebugLoc(), L->getHeader())
8717 << "floating point conversion changes vector width. "
8718 << "Mixed floating point precision requires an up/down "
8719 << "cast that will negatively impact performance.";
8720 });
8721
8722 for (Use &Op : I->operands())
8723 if (auto *OpI = dyn_cast<Instruction>(Op))
8724 Worklist.push_back(OpI);
8725 }
8726}
8727
8728/// For loops with uncountable early exits, find the cost of doing work when
8729/// exiting the loop early, such as calculating the final exit values of
8730/// variables used outside the loop.
8731/// TODO: This is currently overly pessimistic because the loop may not take
8732/// the early exit, but better to keep this conservative for now. In future,
8733/// it might be possible to relax this by using branch probabilities.
8735 VPlan &Plan, ElementCount VF) {
8736 InstructionCost Cost = 0;
8737 for (auto *ExitVPBB : Plan.getExitBlocks()) {
8738 for (auto *PredVPBB : ExitVPBB->getPredecessors()) {
8739 // If the predecessor is not the middle.block, then it must be the
8740 // vector.early.exit block, which may contain work to calculate the exit
8741 // values of variables used outside the loop.
8742 if (PredVPBB != Plan.getMiddleBlock()) {
8743 LLVM_DEBUG(dbgs() << "Calculating cost of work in exit block "
8744 << PredVPBB->getName() << ":\n");
8745 Cost += PredVPBB->cost(VF, CostCtx);
8746 }
8747 }
8748 }
8749 return Cost;
8750}
8751
8752/// This function determines whether or not it's still profitable to vectorize
8753/// the loop given the extra work we have to do outside of the loop:
8754/// 1. Perform the runtime checks before entering the loop to ensure it's safe
8755/// to vectorize.
8756/// 2. In the case of loops with uncountable early exits, we may have to do
8757/// extra work when exiting the loop early, such as calculating the final
8758/// exit values of variables used outside the loop.
8759/// 3. The middle block.
8760static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks,
8761 VectorizationFactor &VF, Loop *L,
8763 VPCostContext &CostCtx, VPlan &Plan,
8765 std::optional<unsigned> VScale) {
8766 InstructionCost RtC = Checks.getCost();
8767 if (!RtC.isValid())
8768 return false;
8769
8770 // When interleaving only scalar and vector cost will be equal, which in turn
8771 // would lead to a divide by 0. Fall back to hard threshold.
8772 if (VF.Width.isScalar()) {
8773 // TODO: Should we rename VectorizeMemoryCheckThreshold?
8775 LLVM_DEBUG(
8776 dbgs()
8777 << "LV: Interleaving only is not profitable due to runtime checks\n");
8778 return false;
8779 }
8780 return true;
8781 }
8782
8783 // The scalar cost should only be 0 when vectorizing with a user specified
8784 // VF/IC. In those cases, runtime checks should always be generated.
8785 uint64_t ScalarC = VF.ScalarCost.getValue();
8786 if (ScalarC == 0)
8787 return true;
8788
8789 InstructionCost TotalCost = RtC;
8790 // Add on the cost of any work required in the vector early exit block, if
8791 // one exists.
8792 TotalCost += calculateEarlyExitCost(CostCtx, Plan, VF.Width);
8793 TotalCost += Plan.getMiddleBlock()->cost(VF.Width, CostCtx);
8794
8795 // First, compute the minimum iteration count required so that the vector
8796 // loop outperforms the scalar loop.
8797 // The total cost of the scalar loop is
8798 // ScalarC * TC
8799 // where
8800 // * TC is the actual trip count of the loop.
8801 // * ScalarC is the cost of a single scalar iteration.
8802 //
8803 // The total cost of the vector loop is
8804 // TotalCost + VecC * (TC / VF) + EpiC
8805 // where
8806 // * TotalCost is the sum of the costs cost of
8807 // - the generated runtime checks, i.e. RtC
8808 // - performing any additional work in the vector.early.exit block for
8809 // loops with uncountable early exits.
8810 // - the middle block, if ExpectedTC <= VF.Width.
8811 // * VecC is the cost of a single vector iteration.
8812 // * TC is the actual trip count of the loop
8813 // * VF is the vectorization factor
8814 // * EpiCost is the cost of the generated epilogue, including the cost
8815 // of the remaining scalar operations.
8816 //
8817 // Vectorization is profitable once the total vector cost is less than the
8818 // total scalar cost:
8819 // TotalCost + VecC * (TC / VF) + EpiC < ScalarC * TC
8820 //
8821 // Now we can compute the minimum required trip count TC as
8822 // VF * (TotalCost + EpiC) / (ScalarC * VF - VecC) < TC
8823 //
8824 // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
8825 // the computations are performed on doubles, not integers and the result
8826 // is rounded up, hence we get an upper estimate of the TC.
8827 unsigned IntVF = estimateElementCount(VF.Width, VScale);
8828 uint64_t Div = ScalarC * IntVF - VF.Cost.getValue();
8829 uint64_t MinTC1 =
8830 Div == 0 ? 0 : divideCeil(TotalCost.getValue() * IntVF, Div);
8831
8832 // Second, compute a minimum iteration count so that the cost of the
8833 // runtime checks is only a fraction of the total scalar loop cost. This
8834 // adds a loop-dependent bound on the overhead incurred if the runtime
8835 // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
8836 // * TC. To bound the runtime check to be a fraction 1/X of the scalar
8837 // cost, compute
8838 // RtC < ScalarC * TC * (1 / X) ==> RtC * X / ScalarC < TC
8839 uint64_t MinTC2 = divideCeil(RtC.getValue() * 10, ScalarC);
8840
8841 // Now pick the larger minimum. If it is not a multiple of VF and a scalar
8842 // epilogue is allowed, choose the next closest multiple of VF. This should
8843 // partly compensate for ignoring the epilogue cost.
8844 uint64_t MinTC = std::max(MinTC1, MinTC2);
8845 if (SEL == CM_ScalarEpilogueAllowed)
8846 MinTC = alignTo(MinTC, IntVF);
8848
8849 LLVM_DEBUG(
8850 dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
8851 << VF.MinProfitableTripCount << "\n");
8852
8853 // Skip vectorization if the expected trip count is less than the minimum
8854 // required trip count.
8855 if (auto ExpectedTC = getSmallBestKnownTC(PSE, L)) {
8856 if (ElementCount::isKnownLT(*ExpectedTC, VF.MinProfitableTripCount)) {
8857 LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
8858 "trip count < minimum profitable VF ("
8859 << *ExpectedTC << " < " << VF.MinProfitableTripCount
8860 << ")\n");
8861
8862 return false;
8863 }
8864 }
8865 return true;
8866}
8867
8869 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
8871 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
8873
8874/// Prepare \p MainPlan for vectorizing the main vector loop during epilogue
8875/// vectorization.
8878 using namespace VPlanPatternMatch;
8879 // When vectorizing the epilogue, FindFirstIV & FindLastIV reductions can
8880 // introduce multiple uses of undef/poison. If the reduction start value may
8881 // be undef or poison it needs to be frozen and the frozen start has to be
8882 // used when computing the reduction result. We also need to use the frozen
8883 // value in the resume phi generated by the main vector loop, as this is also
8884 // used to compute the reduction result after the epilogue vector loop.
8885 auto AddFreezeForFindLastIVReductions = [](VPlan &Plan,
8886 bool UpdateResumePhis) {
8887 VPBuilder Builder(Plan.getEntry());
8888 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
8889 auto *VPI = dyn_cast<VPInstruction>(&R);
8890 if (!VPI)
8891 continue;
8892 VPValue *OrigStart;
8893 if (!matchFindIVResult(VPI, m_VPValue(), m_VPValue(OrigStart)))
8894 continue;
8896 continue;
8897 VPInstruction *Freeze =
8898 Builder.createNaryOp(Instruction::Freeze, {OrigStart}, {}, "fr");
8899 VPI->setOperand(2, Freeze);
8900 if (UpdateResumePhis)
8901 OrigStart->replaceUsesWithIf(Freeze, [Freeze](VPUser &U, unsigned) {
8902 return Freeze != &U && isa<VPPhi>(&U);
8903 });
8904 }
8905 };
8906 AddFreezeForFindLastIVReductions(MainPlan, true);
8907 AddFreezeForFindLastIVReductions(EpiPlan, false);
8908
8909 VPValue *VectorTC = nullptr;
8910 auto *Term =
8912 [[maybe_unused]] bool MatchedTC =
8913 match(Term, m_BranchOnCount(m_VPValue(), m_VPValue(VectorTC)));
8914 assert(MatchedTC && "must match vector trip count");
8915
8916 // If there is a suitable resume value for the canonical induction in the
8917 // scalar (which will become vector) epilogue loop, use it and move it to the
8918 // beginning of the scalar preheader. Otherwise create it below.
8919 VPBasicBlock *MainScalarPH = MainPlan.getScalarPreheader();
8920 auto ResumePhiIter =
8921 find_if(MainScalarPH->phis(), [VectorTC](VPRecipeBase &R) {
8922 return match(&R, m_VPInstruction<Instruction::PHI>(m_Specific(VectorTC),
8923 m_ZeroInt()));
8924 });
8925 VPPhi *ResumePhi = nullptr;
8926 if (ResumePhiIter == MainScalarPH->phis().end()) {
8927 using namespace llvm::VPlanPatternMatch;
8928 assert(
8930 m_ZeroInt()) &&
8931 "canonical IV must start at 0");
8932 Type *Ty = VPTypeAnalysis(MainPlan).inferScalarType(VectorTC);
8933 VPBuilder ScalarPHBuilder(MainScalarPH, MainScalarPH->begin());
8934 ResumePhi = ScalarPHBuilder.createScalarPhi(
8935 {VectorTC, MainPlan.getZero(Ty)}, {}, "vec.epilog.resume.val");
8936 } else {
8937 ResumePhi = cast<VPPhi>(&*ResumePhiIter);
8938 ResumePhi->setName("vec.epilog.resume.val");
8939 if (&MainScalarPH->front() != ResumePhi)
8940 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->begin());
8941 }
8942
8943 // Create a ResumeForEpilogue for the canonical IV resume as the
8944 // first non-phi, to keep it alive for the epilogue.
8945 VPBuilder ResumeBuilder(MainScalarPH);
8946 ResumeBuilder.createNaryOp(VPInstruction::ResumeForEpilogue, ResumePhi);
8947
8948 // Create ResumeForEpilogue instructions for the resume phis of the
8949 // VPIRPhis in the scalar header of the main plan and return them so they can
8950 // be used as resume values when vectorizing the epilogue.
8951 return to_vector(
8952 map_range(MainPlan.getScalarHeader()->phis(), [&](VPRecipeBase &R) {
8953 assert(isa<VPIRPhi>(R) &&
8954 "only VPIRPhis expected in the scalar header");
8955 return ResumeBuilder.createNaryOp(VPInstruction::ResumeForEpilogue,
8956 R.getOperand(0));
8957 }));
8958}
8959
8960/// Prepare \p Plan for vectorizing the epilogue loop. That is, re-use expanded
8961/// SCEVs from \p ExpandedSCEVs and set resume values for header recipes. Some
8962/// reductions require creating new instructions to compute the resume values.
8963/// They are collected in a vector and returned. They must be moved to the
8964/// preheader of the vector epilogue loop, after created by the execution of \p
8965/// Plan.
8967 VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs,
8969 ScalarEvolution &SE) {
8970 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
8971 VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
8972 Header->setName("vec.epilog.vector.body");
8973
8974 VPCanonicalIVPHIRecipe *IV = VectorLoop->getCanonicalIV();
8975 // When vectorizing the epilogue loop, the canonical induction needs to start
8976 // at the resume value from the main vector loop. Find the resume value
8977 // created during execution of the main VPlan. It must be the first phi in the
8978 // loop preheader. Add this resume value as an offset to the canonical IV of
8979 // the epilogue loop.
8980 using namespace llvm::PatternMatch;
8981 PHINode *EPResumeVal = &*L->getLoopPreheader()->phis().begin();
8982 for (Value *Inc : EPResumeVal->incoming_values()) {
8983 if (match(Inc, m_SpecificInt(0)))
8984 continue;
8985 assert(!EPI.VectorTripCount &&
8986 "Must only have a single non-zero incoming value");
8987 EPI.VectorTripCount = Inc;
8988 }
8989 // If we didn't find a non-zero vector trip count, all incoming values
8990 // must be zero, which also means the vector trip count is zero. Pick the
8991 // first zero as vector trip count.
8992 // TODO: We should not choose VF * UF so the main vector loop is known to
8993 // be dead.
8994 if (!EPI.VectorTripCount) {
8995 assert(EPResumeVal->getNumIncomingValues() > 0 &&
8996 all_of(EPResumeVal->incoming_values(),
8997 [](Value *Inc) { return match(Inc, m_SpecificInt(0)); }) &&
8998 "all incoming values must be 0");
8999 EPI.VectorTripCount = EPResumeVal->getOperand(0);
9000 }
9001 VPValue *VPV = Plan.getOrAddLiveIn(EPResumeVal);
9002 assert(all_of(IV->users(),
9003 [](const VPUser *U) {
9004 return isa<VPScalarIVStepsRecipe>(U) ||
9005 isa<VPDerivedIVRecipe>(U) ||
9006 cast<VPRecipeBase>(U)->isScalarCast() ||
9007 cast<VPInstruction>(U)->getOpcode() ==
9008 Instruction::Add;
9009 }) &&
9010 "the canonical IV should only be used by its increment or "
9011 "ScalarIVSteps when resetting the start value");
9012 VPBuilder Builder(Header, Header->getFirstNonPhi());
9013 VPInstruction *Add = Builder.createAdd(IV, VPV);
9014 // Replace all users of the canonical IV and its increment with the offset
9015 // version, except for the Add itself and the canonical IV increment.
9016 auto *Increment = cast<VPInstruction>(IV->getBackedgeValue());
9017 IV->replaceUsesWithIf(Add, [Add, Increment](VPUser &U, unsigned) {
9018 return &U != Add && &U != Increment;
9019 });
9020 VPInstruction *OffsetIVInc =
9022 Increment->replaceUsesWithIf(OffsetIVInc,
9023 [IV](VPUser &U, unsigned) { return &U != IV; });
9024 OffsetIVInc->setOperand(0, Increment);
9025
9027 SmallVector<Instruction *> InstsToMove;
9028 // Ensure that the start values for all header phi recipes are updated before
9029 // vectorizing the epilogue loop. Skip the canonical IV, which has been
9030 // handled above.
9031 for (VPRecipeBase &R : drop_begin(Header->phis())) {
9032 Value *ResumeV = nullptr;
9033 // TODO: Move setting of resume values to prepareToExecute.
9034 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
9035 // Find the reduction result by searching users of the phi or its backedge
9036 // value.
9037 using namespace VPlanPatternMatch;
9038 auto IsReductionResult = [](VPRecipeBase *R) {
9039 auto *VPI = dyn_cast<VPInstruction>(R);
9040 if (!VPI)
9041 return false;
9043 return true;
9044 // ComputeReductionResult is also considered, unless it is used for the
9045 // Or reduction in AnyOf reductions and feeds a ComputeAnyOfReduction,
9046 // in which case the latter will be considered instead.
9048 return false;
9049 return !any_of(VPI->users(), [](VPUser *U) {
9050 return match(U, m_VPInstruction<VPInstruction::ComputeAnyOfResult>());
9051 });
9052 };
9053 auto *RdxResult = cast<VPInstruction>(
9054 vputils::findRecipe(ReductionPhi->getBackedgeValue(), IsReductionResult));
9055 assert(RdxResult && "expected to find reduction result");
9056
9057 ResumeV = cast<PHINode>(ReductionPhi->getUnderlyingInstr())
9058 ->getIncomingValueForBlock(L->getLoopPreheader());
9059
9060 // Check for FindIV pattern by looking for icmp user of RdxResult.
9061 // The pattern is: select(icmp ne RdxResult, Sentinel), RdxResult, Start
9062 using namespace VPlanPatternMatch;
9063 VPValue *SentinelVPV = nullptr;
9064 bool IsFindIV = any_of(RdxResult->users(), [&](VPUser *U) {
9065 return match(U, VPlanPatternMatch::m_SpecificICmp(
9066 ICmpInst::ICMP_NE, m_Specific(RdxResult),
9067 m_VPValue(SentinelVPV)));
9068 });
9069
9070 if (RdxResult->getOpcode() == VPInstruction::ComputeAnyOfResult) {
9071 Value *StartV = RdxResult->getOperand(0)->getLiveInIRValue();
9072 // VPReductionPHIRecipes for AnyOf reductions expect a boolean as
9073 // start value; compare the final value from the main vector loop
9074 // to the start value.
9075 BasicBlock *PBB = cast<Instruction>(ResumeV)->getParent();
9076 IRBuilder<> Builder(PBB, PBB->getFirstNonPHIIt());
9077 ResumeV = Builder.CreateICmpNE(ResumeV, StartV);
9078 if (auto *I = dyn_cast<Instruction>(ResumeV))
9079 InstsToMove.push_back(I);
9080 } else if (IsFindIV) {
9081 assert(SentinelVPV && "expected to find icmp using RdxResult");
9082
9083 // Get the frozen start value from the main loop.
9084 Value *FrozenStartV = cast<PHINode>(ResumeV)->getIncomingValueForBlock(
9086 if (auto *FreezeI = dyn_cast<FreezeInst>(FrozenStartV))
9087 ToFrozen[FreezeI->getOperand(0)] = FrozenStartV;
9088
9089 // Adjust resume: select(icmp eq ResumeV, FrozenStartV), Sentinel,
9090 // ResumeV
9091 BasicBlock *ResumeBB = cast<Instruction>(ResumeV)->getParent();
9092 IRBuilder<> Builder(ResumeBB, ResumeBB->getFirstNonPHIIt());
9093 Value *Cmp = Builder.CreateICmpEQ(ResumeV, FrozenStartV);
9094 if (auto *I = dyn_cast<Instruction>(Cmp))
9095 InstsToMove.push_back(I);
9096 ResumeV =
9097 Builder.CreateSelect(Cmp, SentinelVPV->getLiveInIRValue(), ResumeV);
9098 if (auto *I = dyn_cast<Instruction>(ResumeV))
9099 InstsToMove.push_back(I);
9100 } else {
9101 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9102 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9103 if (auto *VPI = dyn_cast<VPInstruction>(PhiR->getStartValue())) {
9105 "unexpected start value");
9106 // Partial sub-reductions always start at 0 and account for the
9107 // reduction start value in a final subtraction. Update it to use the
9108 // resume value from the main vector loop.
9109 if (PhiR->getVFScaleFactor() > 1 &&
9110 PhiR->getRecurrenceKind() == RecurKind::Sub) {
9111 auto *Sub = cast<VPInstruction>(RdxResult->getSingleUser());
9112 assert(Sub->getOpcode() == Instruction::Sub && "Unexpected opcode");
9113 assert(isa<VPIRValue>(Sub->getOperand(0)) &&
9114 "Expected operand to match the original start value of the "
9115 "reduction");
9118 "Expected start value for partial sub-reduction to start at "
9119 "zero");
9120 Sub->setOperand(0, StartVal);
9121 } else
9122 VPI->setOperand(0, StartVal);
9123 continue;
9124 }
9125 }
9126 } else {
9127 // Retrieve the induction resume values for wide inductions from
9128 // their original phi nodes in the scalar loop.
9129 PHINode *IndPhi = cast<VPWidenInductionRecipe>(&R)->getPHINode();
9130 // Hook up to the PHINode generated by a ResumePhi recipe of main
9131 // loop VPlan, which feeds the scalar loop.
9132 ResumeV = IndPhi->getIncomingValueForBlock(L->getLoopPreheader());
9133 }
9134 assert(ResumeV && "Must have a resume value");
9135 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9136 cast<VPHeaderPHIRecipe>(&R)->setStartValue(StartVal);
9137 }
9138
9139 // For some VPValues in the epilogue plan we must re-use the generated IR
9140 // values from the main plan. Replace them with live-in VPValues.
9141 // TODO: This is a workaround needed for epilogue vectorization and it
9142 // should be removed once induction resume value creation is done
9143 // directly in VPlan.
9144 for (auto &R : make_early_inc_range(*Plan.getEntry())) {
9145 // Re-use frozen values from the main plan for Freeze VPInstructions in the
9146 // epilogue plan. This ensures all users use the same frozen value.
9147 auto *VPI = dyn_cast<VPInstruction>(&R);
9148 if (VPI && VPI->getOpcode() == Instruction::Freeze) {
9150 ToFrozen.lookup(VPI->getOperand(0)->getLiveInIRValue())));
9151 continue;
9152 }
9153
9154 // Re-use the trip count and steps expanded for the main loop, as
9155 // skeleton creation needs it as a value that dominates both the scalar
9156 // and vector epilogue loops
9157 auto *ExpandR = dyn_cast<VPExpandSCEVRecipe>(&R);
9158 if (!ExpandR)
9159 continue;
9160 VPValue *ExpandedVal =
9161 Plan.getOrAddLiveIn(ExpandedSCEVs.lookup(ExpandR->getSCEV()));
9162 ExpandR->replaceAllUsesWith(ExpandedVal);
9163 if (Plan.getTripCount() == ExpandR)
9164 Plan.resetTripCount(ExpandedVal);
9165 ExpandR->eraseFromParent();
9166 }
9167
9168 auto VScale = CM.getVScaleForTuning();
9169 unsigned MainLoopStep =
9170 estimateElementCount(EPI.MainLoopVF * EPI.MainLoopUF, VScale);
9171 unsigned EpilogueLoopStep =
9172 estimateElementCount(EPI.EpilogueVF * EPI.EpilogueUF, VScale);
9174 Plan, EPI.VectorTripCount,
9176 EPI.EpilogueUF, MainLoopStep, EpilogueLoopStep, SE);
9177
9178 return InstsToMove;
9179}
9180
9181static void
9183 VPlan &BestEpiPlan,
9184 ArrayRef<VPInstruction *> ResumeValues) {
9185 // Fix resume values from the additional bypass block.
9186 BasicBlock *PH = L->getLoopPreheader();
9187 for (auto *Pred : predecessors(PH)) {
9188 for (PHINode &Phi : PH->phis()) {
9189 if (Phi.getBasicBlockIndex(Pred) != -1)
9190 continue;
9191 Phi.addIncoming(Phi.getIncomingValueForBlock(BypassBlock), Pred);
9192 }
9193 }
9194 auto *ScalarPH = cast<VPIRBasicBlock>(BestEpiPlan.getScalarPreheader());
9195 if (ScalarPH->hasPredecessors()) {
9196 // Fix resume values for inductions and reductions from the additional
9197 // bypass block using the incoming values from the main loop's resume phis.
9198 // ResumeValues correspond 1:1 with the scalar loop header phis.
9199 for (auto [ResumeV, HeaderPhi] :
9200 zip(ResumeValues, BestEpiPlan.getScalarHeader()->phis())) {
9201 auto *HeaderPhiR = cast<VPIRPhi>(&HeaderPhi);
9202 auto *EpiResumePhi =
9203 cast<PHINode>(HeaderPhiR->getIRPhi().getIncomingValueForBlock(PH));
9204 if (EpiResumePhi->getBasicBlockIndex(BypassBlock) == -1)
9205 continue;
9206 auto *MainResumePhi = cast<PHINode>(ResumeV->getUnderlyingValue());
9207 EpiResumePhi->setIncomingValueForBlock(
9208 BypassBlock, MainResumePhi->getIncomingValueForBlock(BypassBlock));
9209 }
9210 }
9211}
9212
9213/// Connect the epilogue vector loop generated for \p EpiPlan to the main vector
9214/// loop, after both plans have executed, updating branches from the iteration
9215/// and runtime checks of the main loop, as well as updating various phis. \p
9216/// InstsToMove contains instructions that need to be moved to the preheader of
9217/// the epilogue vector loop.
9218static void connectEpilogueVectorLoop(VPlan &EpiPlan, Loop *L,
9220 DominatorTree *DT,
9221 GeneratedRTChecks &Checks,
9222 ArrayRef<Instruction *> InstsToMove,
9223 ArrayRef<VPInstruction *> ResumeValues) {
9224 BasicBlock *VecEpilogueIterationCountCheck =
9225 cast<VPIRBasicBlock>(EpiPlan.getEntry())->getIRBasicBlock();
9226
9227 BasicBlock *VecEpiloguePreHeader =
9228 cast<CondBrInst>(VecEpilogueIterationCountCheck->getTerminator())
9229 ->getSuccessor(1);
9230 // Adjust the control flow taking the state info from the main loop
9231 // vectorization into account.
9233 "expected this to be saved from the previous pass.");
9234 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
9236 VecEpilogueIterationCountCheck, VecEpiloguePreHeader);
9237
9239 VecEpilogueIterationCountCheck},
9241 VecEpiloguePreHeader}});
9242
9243 BasicBlock *ScalarPH =
9244 cast<VPIRBasicBlock>(EpiPlan.getScalarPreheader())->getIRBasicBlock();
9246 VecEpilogueIterationCountCheck, ScalarPH);
9247 DTU.applyUpdates(
9249 VecEpilogueIterationCountCheck},
9251
9252 // Adjust the terminators of runtime check blocks and phis using them.
9253 BasicBlock *SCEVCheckBlock = Checks.getSCEVChecks().second;
9254 BasicBlock *MemCheckBlock = Checks.getMemRuntimeChecks().second;
9255 if (SCEVCheckBlock) {
9256 SCEVCheckBlock->getTerminator()->replaceUsesOfWith(
9257 VecEpilogueIterationCountCheck, ScalarPH);
9258 DTU.applyUpdates({{DominatorTree::Delete, SCEVCheckBlock,
9259 VecEpilogueIterationCountCheck},
9260 {DominatorTree::Insert, SCEVCheckBlock, ScalarPH}});
9261 }
9262 if (MemCheckBlock) {
9263 MemCheckBlock->getTerminator()->replaceUsesOfWith(
9264 VecEpilogueIterationCountCheck, ScalarPH);
9265 DTU.applyUpdates(
9266 {{DominatorTree::Delete, MemCheckBlock, VecEpilogueIterationCountCheck},
9267 {DominatorTree::Insert, MemCheckBlock, ScalarPH}});
9268 }
9269
9270 // The vec.epilog.iter.check block may contain Phi nodes from inductions
9271 // or reductions which merge control-flow from the latch block and the
9272 // middle block. Update the incoming values here and move the Phi into the
9273 // preheader.
9274 SmallVector<PHINode *, 4> PhisInBlock(
9275 llvm::make_pointer_range(VecEpilogueIterationCountCheck->phis()));
9276
9277 for (PHINode *Phi : PhisInBlock) {
9278 Phi->moveBefore(VecEpiloguePreHeader->getFirstNonPHIIt());
9279 Phi->replaceIncomingBlockWith(
9280 VecEpilogueIterationCountCheck->getSinglePredecessor(),
9281 VecEpilogueIterationCountCheck);
9282
9283 // If the phi doesn't have an incoming value from the
9284 // EpilogueIterationCountCheck, we are done. Otherwise remove the
9285 // incoming value and also those from other check blocks. This is needed
9286 // for reduction phis only.
9287 if (none_of(Phi->blocks(), [&](BasicBlock *IncB) {
9288 return EPI.EpilogueIterationCountCheck == IncB;
9289 }))
9290 continue;
9291 Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
9292 if (SCEVCheckBlock)
9293 Phi->removeIncomingValue(SCEVCheckBlock);
9294 if (MemCheckBlock)
9295 Phi->removeIncomingValue(MemCheckBlock);
9296 }
9297
9298 auto IP = VecEpiloguePreHeader->getFirstNonPHIIt();
9299 for (auto *I : InstsToMove)
9300 I->moveBefore(IP);
9301
9302 // VecEpilogueIterationCountCheck conditionally skips over the epilogue loop
9303 // after executing the main loop. We need to update the resume values of
9304 // inductions and reductions during epilogue vectorization.
9305 fixScalarResumeValuesFromBypass(VecEpilogueIterationCountCheck, L, EpiPlan,
9306 ResumeValues);
9307
9308 // Remove dead phis that were moved to the epilogue preheader but are unused
9309 // (e.g., resume phis for inductions not widened in the epilogue vector loop).
9310 for (PHINode &Phi : make_early_inc_range(VecEpiloguePreHeader->phis()))
9311 if (Phi.use_empty())
9312 Phi.eraseFromParent();
9313}
9314
9316 assert((EnableVPlanNativePath || L->isInnermost()) &&
9317 "VPlan-native path is not enabled. Only process inner loops.");
9318
9319 LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
9320 << L->getHeader()->getParent()->getName() << "' from "
9321 << L->getLocStr() << "\n");
9322
9323 LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
9324
9325 LLVM_DEBUG(
9326 dbgs() << "LV: Loop hints:"
9327 << " force="
9329 ? "disabled"
9331 ? "enabled"
9332 : "?"))
9333 << " width=" << Hints.getWidth()
9334 << " interleave=" << Hints.getInterleave() << "\n");
9335
9336 // Function containing loop
9337 Function *F = L->getHeader()->getParent();
9338
9339 // Looking at the diagnostic output is the only way to determine if a loop
9340 // was vectorized (other than looking at the IR or machine code), so it
9341 // is important to generate an optimization remark for each loop. Most of
9342 // these messages are generated as OptimizationRemarkAnalysis. Remarks
9343 // generated as OptimizationRemark and OptimizationRemarkMissed are
9344 // less verbose reporting vectorized loops and unvectorized loops that may
9345 // benefit from vectorization, respectively.
9346
9347 if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9348 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9349 return false;
9350 }
9351
9352 PredicatedScalarEvolution PSE(*SE, *L);
9353
9354 // Query this against the original loop and save it here because the profile
9355 // of the original loop header may change as the transformation happens.
9356 bool OptForSize = llvm::shouldOptimizeForSize(
9357 L->getHeader(), PSI,
9358 PSI && PSI->hasProfileSummary() ? &GetBFI() : nullptr,
9360
9361 // Check if it is legal to vectorize the loop.
9362 LoopVectorizationRequirements Requirements;
9363 LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, F, *LAIs, LI, ORE,
9364 &Requirements, &Hints, DB, AC,
9365 /*AllowRuntimeSCEVChecks=*/!OptForSize, AA);
9367 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9368 Hints.emitRemarkWithHints();
9369 return false;
9370 }
9371
9372 if (LVL.hasUncountableEarlyExit()) {
9374 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
9375 "early exit is not enabled",
9376 "UncountableEarlyExitLoopsDisabled", ORE, L);
9377 return false;
9378 }
9379 }
9380
9381 // Entrance to the VPlan-native vectorization path. Outer loops are processed
9382 // here. They may require CFG and instruction level transformations before
9383 // even evaluating whether vectorization is profitable. Since we cannot modify
9384 // the incoming IR, we need to build VPlan upfront in the vectorization
9385 // pipeline.
9386 if (!L->isInnermost())
9387 return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9388 ORE, GetBFI, OptForSize, Hints,
9389 Requirements);
9390
9391 assert(L->isInnermost() && "Inner loop expected.");
9392
9393 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
9394 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
9395
9396 // If an override option has been passed in for interleaved accesses, use it.
9397 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
9398 UseInterleaved = EnableInterleavedMemAccesses;
9399
9400 // Analyze interleaved memory accesses.
9401 if (UseInterleaved)
9403
9404 if (LVL.hasUncountableEarlyExit()) {
9405 BasicBlock *LoopLatch = L->getLoopLatch();
9406 if (IAI.requiresScalarEpilogue() ||
9408 [LoopLatch](BasicBlock *BB) { return BB != LoopLatch; })) {
9409 reportVectorizationFailure("Auto-vectorization of early exit loops "
9410 "requiring a scalar epilogue is unsupported",
9411 "UncountableEarlyExitUnsupported", ORE, L);
9412 return false;
9413 }
9414 }
9415
9416 // Check the function attributes and profiles to find out if this function
9417 // should be optimized for size.
9419 getScalarEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, LVL, &IAI);
9420
9421 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
9422 // count by optimizing for size, to minimize overheads.
9423 auto ExpectedTC = getSmallBestKnownTC(PSE, L);
9424 if (ExpectedTC && ExpectedTC->isFixed() &&
9425 ExpectedTC->getFixedValue() < TinyTripCountVectorThreshold) {
9426 LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
9427 << "This loop is worth vectorizing only if no scalar "
9428 << "iteration overheads are incurred.");
9430 LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
9431 else {
9432 LLVM_DEBUG(dbgs() << "\n");
9433 // Predicate tail-folded loops are efficient even when the loop
9434 // iteration count is low. However, setting the epilogue policy to
9435 // `CM_ScalarEpilogueNotAllowedLowTripLoop` prevents vectorizing loops
9436 // with runtime checks. It's more effective to let
9437 // `isOutsideLoopWorkProfitable` determine if vectorization is
9438 // beneficial for the loop.
9441 }
9442 }
9443
9444 // Check the function attributes to see if implicit floats or vectors are
9445 // allowed.
9446 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9448 "Can't vectorize when the NoImplicitFloat attribute is used",
9449 "loop not vectorized due to NoImplicitFloat attribute",
9450 "NoImplicitFloat", ORE, L);
9451 Hints.emitRemarkWithHints();
9452 return false;
9453 }
9454
9455 // Check if the target supports potentially unsafe FP vectorization.
9456 // FIXME: Add a check for the type of safety issue (denormal, signaling)
9457 // for the target we're vectorizing for, to make sure none of the
9458 // additional fp-math flags can help.
9459 if (Hints.isPotentiallyUnsafe() &&
9460 TTI->isFPVectorizationPotentiallyUnsafe()) {
9462 "Potentially unsafe FP op prevents vectorization",
9463 "loop not vectorized due to unsafe FP support.",
9464 "UnsafeFP", ORE, L);
9465 Hints.emitRemarkWithHints();
9466 return false;
9467 }
9468
9469 bool AllowOrderedReductions;
9470 // If the flag is set, use that instead and override the TTI behaviour.
9471 if (ForceOrderedReductions.getNumOccurrences() > 0)
9472 AllowOrderedReductions = ForceOrderedReductions;
9473 else
9474 AllowOrderedReductions = TTI->enableOrderedReductions();
9475 if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
9476 ORE->emit([&]() {
9477 auto *ExactFPMathInst = Requirements.getExactFPInst();
9478 return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
9479 ExactFPMathInst->getDebugLoc(),
9480 ExactFPMathInst->getParent())
9481 << "loop not vectorized: cannot prove it is safe to reorder "
9482 "floating-point operations";
9483 });
9484 LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
9485 "reorder floating-point operations\n");
9486 Hints.emitRemarkWithHints();
9487 return false;
9488 }
9489
9490 // Use the cost model.
9491 LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
9492 GetBFI, F, &Hints, IAI, OptForSize);
9493 // Use the planner for vectorization.
9494 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, &LVL, CM, IAI, PSE, Hints,
9495 ORE);
9496
9497 // Get user vectorization factor and interleave count.
9498 ElementCount UserVF = Hints.getWidth();
9499 unsigned UserIC = Hints.getInterleave();
9500 if (UserIC > 1 && !LVL.isSafeForAnyVectorWidth())
9501 UserIC = 1;
9502
9503 // Plan how to best vectorize.
9504 LVP.plan(UserVF, UserIC);
9505 auto [VF, BestPlanPtr] = LVP.computeBestVF();
9506 unsigned IC = 1;
9507
9508 if (ORE->allowExtraAnalysis(LV_NAME))
9510
9511 GeneratedRTChecks Checks(PSE, DT, LI, TTI, CM.CostKind);
9512 if (LVP.hasPlanWithVF(VF.Width)) {
9513 // Select the interleave count.
9514 IC = LVP.selectInterleaveCount(*BestPlanPtr, VF.Width, VF.Cost);
9515
9516 unsigned SelectedIC = std::max(IC, UserIC);
9517 // Optimistically generate runtime checks if they are needed. Drop them if
9518 // they turn out to not be profitable.
9519 if (VF.Width.isVector() || SelectedIC > 1) {
9520 Checks.create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC,
9521 *ORE);
9522
9523 // Bail out early if either the SCEV or memory runtime checks are known to
9524 // fail. In that case, the vector loop would never execute.
9525 using namespace llvm::PatternMatch;
9526 if (Checks.getSCEVChecks().first &&
9527 match(Checks.getSCEVChecks().first, m_One()))
9528 return false;
9529 if (Checks.getMemRuntimeChecks().first &&
9530 match(Checks.getMemRuntimeChecks().first, m_One()))
9531 return false;
9532 }
9533
9534 // Check if it is profitable to vectorize with runtime checks.
9535 bool ForceVectorization =
9537 VPCostContext CostCtx(CM.TTI, *CM.TLI, *BestPlanPtr, CM, CM.CostKind,
9538 CM.PSE, L);
9539 if (!ForceVectorization &&
9540 !isOutsideLoopWorkProfitable(Checks, VF, L, PSE, CostCtx, *BestPlanPtr,
9541 SEL, CM.getVScaleForTuning())) {
9542 ORE->emit([&]() {
9544 DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
9545 L->getHeader())
9546 << "loop not vectorized: cannot prove it is safe to reorder "
9547 "memory operations";
9548 });
9549 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
9550 Hints.emitRemarkWithHints();
9551 return false;
9552 }
9553 }
9554
9555 // Identify the diagnostic messages that should be produced.
9556 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
9557 bool VectorizeLoop = true, InterleaveLoop = true;
9558 if (VF.Width.isScalar()) {
9559 LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
9560 VecDiagMsg = {
9561 "VectorizationNotBeneficial",
9562 "the cost-model indicates that vectorization is not beneficial"};
9563 VectorizeLoop = false;
9564 }
9565
9566 if (UserIC == 1 && Hints.getInterleave() > 1) {
9568 "UserIC should only be ignored due to unsafe dependencies");
9569 LLVM_DEBUG(dbgs() << "LV: Ignoring user-specified interleave count.\n");
9570 IntDiagMsg = {"InterleavingUnsafe",
9571 "Ignoring user-specified interleave count due to possibly "
9572 "unsafe dependencies in the loop."};
9573 InterleaveLoop = false;
9574 } else if (!LVP.hasPlanWithVF(VF.Width) && UserIC > 1) {
9575 // Tell the user interleaving was avoided up-front, despite being explicitly
9576 // requested.
9577 LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
9578 "interleaving should be avoided up front\n");
9579 IntDiagMsg = {"InterleavingAvoided",
9580 "Ignoring UserIC, because interleaving was avoided up front"};
9581 InterleaveLoop = false;
9582 } else if (IC == 1 && UserIC <= 1) {
9583 // Tell the user interleaving is not beneficial.
9584 LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
9585 IntDiagMsg = {
9586 "InterleavingNotBeneficial",
9587 "the cost-model indicates that interleaving is not beneficial"};
9588 InterleaveLoop = false;
9589 if (UserIC == 1) {
9590 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
9591 IntDiagMsg.second +=
9592 " and is explicitly disabled or interleave count is set to 1";
9593 }
9594 } else if (IC > 1 && UserIC == 1) {
9595 // Tell the user interleaving is beneficial, but it explicitly disabled.
9596 LLVM_DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly "
9597 "disabled.\n");
9598 IntDiagMsg = {"InterleavingBeneficialButDisabled",
9599 "the cost-model indicates that interleaving is beneficial "
9600 "but is explicitly disabled or interleave count is set to 1"};
9601 InterleaveLoop = false;
9602 }
9603
9604 // If there is a histogram in the loop, do not just interleave without
9605 // vectorizing. The order of operations will be incorrect without the
9606 // histogram intrinsics, which are only used for recipes with VF > 1.
9607 if (!VectorizeLoop && InterleaveLoop && LVL.hasHistograms()) {
9608 LLVM_DEBUG(dbgs() << "LV: Not interleaving without vectorization due "
9609 << "to histogram operations.\n");
9610 IntDiagMsg = {
9611 "HistogramPreventsScalarInterleaving",
9612 "Unable to interleave without vectorization due to constraints on "
9613 "the order of histogram operations"};
9614 InterleaveLoop = false;
9615 }
9616
9617 // Override IC if user provided an interleave count.
9618 IC = UserIC > 0 ? UserIC : IC;
9619
9620 // Emit diagnostic messages, if any.
9621 const char *VAPassName = Hints.vectorizeAnalysisPassName();
9622 if (!VectorizeLoop && !InterleaveLoop) {
9623 // Do not vectorize or interleaving the loop.
9624 ORE->emit([&]() {
9625 return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
9626 L->getStartLoc(), L->getHeader())
9627 << VecDiagMsg.second;
9628 });
9629 ORE->emit([&]() {
9630 return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
9631 L->getStartLoc(), L->getHeader())
9632 << IntDiagMsg.second;
9633 });
9634 return false;
9635 }
9636
9637 if (!VectorizeLoop && InterleaveLoop) {
9638 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
9639 ORE->emit([&]() {
9640 return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
9641 L->getStartLoc(), L->getHeader())
9642 << VecDiagMsg.second;
9643 });
9644 } else if (VectorizeLoop && !InterleaveLoop) {
9645 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
9646 << ") in " << L->getLocStr() << '\n');
9647 ORE->emit([&]() {
9648 return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
9649 L->getStartLoc(), L->getHeader())
9650 << IntDiagMsg.second;
9651 });
9652 } else if (VectorizeLoop && InterleaveLoop) {
9653 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
9654 << ") in " << L->getLocStr() << '\n');
9655 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
9656 }
9657
9658 // Report the vectorization decision.
9659 if (VF.Width.isScalar()) {
9660 using namespace ore;
9661 assert(IC > 1);
9662 ORE->emit([&]() {
9663 return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
9664 L->getHeader())
9665 << "interleaved loop (interleaved count: "
9666 << NV("InterleaveCount", IC) << ")";
9667 });
9668 } else {
9669 // Report the vectorization decision.
9670 reportVectorization(ORE, L, VF, IC);
9671 }
9672 if (ORE->allowExtraAnalysis(LV_NAME))
9674
9675 // If we decided that it is *legal* to interleave or vectorize the loop, then
9676 // do it.
9677
9678 VPlan &BestPlan = *BestPlanPtr;
9679 // Consider vectorizing the epilogue too if it's profitable.
9680 std::unique_ptr<VPlan> EpiPlan =
9681 LVP.selectBestEpiloguePlan(BestPlan, VF.Width, IC);
9682 bool HasBranchWeights =
9683 hasBranchWeightMD(*L->getLoopLatch()->getTerminator());
9684 if (EpiPlan) {
9685 VPlan &BestEpiPlan = *EpiPlan;
9686 VPlan &BestMainPlan = BestPlan;
9687 ElementCount EpilogueVF = BestEpiPlan.getSingleVF();
9688
9689 // The first pass vectorizes the main loop and creates a scalar epilogue
9690 // to be vectorized by executing the plan (potentially with a different
9691 // factor) again shortly afterwards.
9692 BestEpiPlan.getMiddleBlock()->setName("vec.epilog.middle.block");
9693 BestEpiPlan.getVectorPreheader()->setName("vec.epilog.ph");
9694 SmallVector<VPInstruction *> ResumeValues =
9695 preparePlanForMainVectorLoop(BestMainPlan, BestEpiPlan);
9696 EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF, 1, BestEpiPlan);
9697
9698 // Add minimum iteration check for the epilogue plan, followed by runtime
9699 // checks for the main plan.
9700 LVP.addMinimumIterationCheck(BestMainPlan, EPI.EpilogueVF, EPI.EpilogueUF,
9702 LVP.attachRuntimeChecks(BestMainPlan, Checks, HasBranchWeights);
9704 BestMainPlan, EPI.MainLoopVF, EPI.MainLoopUF,
9706 HasBranchWeights ? MinItersBypassWeights : nullptr,
9707 L->getLoopPredecessor()->getTerminator()->getDebugLoc(), PSE);
9708
9709 EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TTI, AC, EPI, &CM,
9710 Checks, BestMainPlan);
9711 auto ExpandedSCEVs = LVP.executePlan(
9712 EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV, DT,
9714 ++LoopsVectorized;
9715
9716 // Derive EPI fields from VPlan-generated IR.
9717 BasicBlock *EntryBB =
9718 cast<VPIRBasicBlock>(BestMainPlan.getEntry())->getIRBasicBlock();
9719 EntryBB->setName("iter.check");
9720 EPI.EpilogueIterationCountCheck = EntryBB;
9721 // The check chain is: Entry -> [SCEV] -> [Mem] -> MainCheck -> VecPH.
9722 // MainCheck is the non-bypass successor of the last runtime check block
9723 // (or Entry if there are no runtime checks).
9724 BasicBlock *LastCheck = EntryBB;
9725 if (BasicBlock *MemBB = Checks.getMemRuntimeChecks().second)
9726 LastCheck = MemBB;
9727 else if (BasicBlock *SCEVBB = Checks.getSCEVChecks().second)
9728 LastCheck = SCEVBB;
9729 BasicBlock *ScalarPH = L->getLoopPreheader();
9730 auto *BI = cast<CondBrInst>(LastCheck->getTerminator());
9732 BI->getSuccessor(BI->getSuccessor(0) == ScalarPH);
9733
9734 // Second pass vectorizes the epilogue and adjusts the control flow
9735 // edges from the first pass.
9736 EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TTI, AC, EPI, &CM,
9737 Checks, BestEpiPlan);
9739 BestEpiPlan, L, ExpandedSCEVs, EPI, CM, *PSE.getSE());
9740 LVP.attachRuntimeChecks(BestEpiPlan, Checks, HasBranchWeights);
9741 LVP.executePlan(
9742 EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV, DT,
9744 connectEpilogueVectorLoop(BestEpiPlan, L, EPI, DT, Checks, InstsToMove,
9745 ResumeValues);
9746 ++LoopsEpilogueVectorized;
9747 } else {
9748 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, IC, &CM, Checks,
9749 BestPlan);
9750 LVP.addMinimumIterationCheck(BestPlan, VF.Width, IC,
9751 VF.MinProfitableTripCount);
9752 LVP.attachRuntimeChecks(BestPlan, Checks, HasBranchWeights);
9753
9754 LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
9755 ++LoopsVectorized;
9756 }
9757
9758 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
9759 "DT not preserved correctly");
9760 assert(!verifyFunction(*F, &dbgs()));
9761
9762 return true;
9763}
9764
9766
9767 // Don't attempt if
9768 // 1. the target claims to have no vector registers, and
9769 // 2. interleaving won't help ILP.
9770 //
9771 // The second condition is necessary because, even if the target has no
9772 // vector registers, loop vectorization may still enable scalar
9773 // interleaving.
9774 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
9775 TTI->getMaxInterleaveFactor(ElementCount::getFixed(1)) < 2)
9776 return LoopVectorizeResult(false, false);
9777
9778 bool Changed = false, CFGChanged = false;
9779
9780 // The vectorizer requires loops to be in simplified form.
9781 // Since simplification may add new inner loops, it has to run before the
9782 // legality and profitability checks. This means running the loop vectorizer
9783 // will simplify all loops, regardless of whether anything end up being
9784 // vectorized.
9785 for (const auto &L : *LI)
9786 Changed |= CFGChanged |=
9787 simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
9788
9789 // Build up a worklist of inner-loops to vectorize. This is necessary as
9790 // the act of vectorizing or partially unrolling a loop creates new loops
9791 // and can invalidate iterators across the loops.
9792 SmallVector<Loop *, 8> Worklist;
9793
9794 for (Loop *L : *LI)
9795 collectSupportedLoops(*L, LI, ORE, Worklist);
9796
9797 LoopsAnalyzed += Worklist.size();
9798
9799 // Now walk the identified inner loops.
9800 while (!Worklist.empty()) {
9801 Loop *L = Worklist.pop_back_val();
9802
9803 // For the inner loops we actually process, form LCSSA to simplify the
9804 // transform.
9805 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
9806
9807 Changed |= CFGChanged |= processLoop(L);
9808
9809 if (Changed) {
9810 LAIs->clear();
9811
9812#ifndef NDEBUG
9813 if (VerifySCEV)
9814 SE->verify();
9815#endif
9816 }
9817 }
9818
9819 // Process each loop nest in the function.
9820 return LoopVectorizeResult(Changed, CFGChanged);
9821}
9822
9825 LI = &AM.getResult<LoopAnalysis>(F);
9826 // There are no loops in the function. Return before computing other
9827 // expensive analyses.
9828 if (LI->empty())
9829 return PreservedAnalyses::all();
9838 AA = &AM.getResult<AAManager>(F);
9839
9840 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
9841 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
9842 GetBFI = [&AM, &F]() -> BlockFrequencyInfo & {
9844 };
9845 LoopVectorizeResult Result = runImpl(F);
9846 if (!Result.MadeAnyChange)
9847 return PreservedAnalyses::all();
9849
9850 if (isAssignmentTrackingEnabled(*F.getParent())) {
9851 for (auto &BB : F)
9853 }
9854
9855 PA.preserve<LoopAnalysis>();
9859
9860 if (Result.MadeCFGChange) {
9861 // Making CFG changes likely means a loop got vectorized. Indicate that
9862 // extra simplification passes should be run.
9863 // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
9864 // be run if runtime checks have been added.
9867 } else {
9869 }
9870 return PA;
9871}
9872
9874 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
9875 static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
9876 OS, MapClassName2PassName);
9877
9878 OS << '<';
9879 OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
9880 OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
9881 OS << '>';
9882}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static unsigned getIntrinsicID(const SDNode *N)
unsigned RegSize
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...
@ PostInc
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.
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
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[]
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:81
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 cl::opt< bool > WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true), cl::desc("Widen the loop induction variables, if possible, so " "overflow checks won't reject flattening"))
static const char * VerboseDebug
#define LV_NAME
This file defines the LoopVectorizationLegality class.
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 determineVPlanVF(const TargetTransformInfo &TTI, LoopVectorizationCostModel &CM)
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 void debugVectorizationMessage(const StringRef Prefix, const StringRef DebugMsg, Instruction *I)
Write a DebugMsg about vectorization to the debug output stream.
static cl::opt< bool > EnableCondStoresVectorization("enable-cond-stores-vec", cl::init(true), cl::Hidden, cl::desc("Enable if predication of stores during vectorization."))
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 DebugLoc getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or its operands.
static cl::opt< bool > ForceTargetSupportsScalableVectors("force-target-supports-scalable-vectors", cl::init(false), cl::Hidden, cl::desc("Pretend that scalable vectors are supported, even if the target does " "not support them. This flag should only be used for testing."))
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
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 bool processLoopInVPlanNativePath(Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, LoopVectorizationLegality *LVL, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, bool OptForSize, LoopVectorizeHints &Hints, LoopVectorizationRequirements &Requirements)
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."))
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 cl::opt< bool > UseWiderVFIfCallVariantsPresent("vectorizer-maximize-bandwidth-for-vector-calls", cl::init(true), cl::Hidden, cl::desc("Try wider VFs if they enable the use of vector variants"))
static std::optional< unsigned > getMaxVScale(const Function &F, const TargetTransformInfo &TTI)
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 bool planContainsAdditionalSimplifications(VPlan &Plan, VPCostContext &CostCtx, Loop *TheLoop, ElementCount VF)
Return true if the original loop \ TheLoop contains any instructions that do not have corresponding r...
static cl::opt< unsigned > ForceTargetNumVectorRegs("force-target-num-vector-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of vector registers."))
static bool isExplicitVecOuterLoop(Loop *OuterLp, OptimizationRemarkEmitter *ORE)
static cl::opt< bool > EnableIndVarRegisterHeur("enable-ind-var-reg-heur", cl::init(true), cl::Hidden, cl::desc("Count the induction variable only once when interleaving"))
static 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 ScalarEpilogueLowering getScalarEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
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 cl::opt< bool > PreferInLoopReductions("prefer-inloop-reductions", cl::init(false), cl::Hidden, cl::desc("Prefer in-loop vector reductions, " "overriding the targets preference."))
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 SmallVector< Instruction * > preparePlanForEpilogueVectorLoop(VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationCostModel &CM, ScalarEvolution &SE)
Prepare Plan for vectorizing the epilogue loop.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
static cl::opt< bool > EnableLoadStoreRuntimeInterleave("enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, cl::desc("Enable runtime interleaving until load/store ports are saturated"))
static cl::opt< bool > VPlanBuildStressTest("vplan-build-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 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 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 cl::opt< PreferPredicateTy::Option > PreferPredicateOverEpilogue("prefer-predicate-over-epilogue", cl::init(PreferPredicateTy::ScalarEpilogue), cl::Hidden, cl::desc("Tail-folding and predication preferences over creating a scalar " "epilogue loop."), cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue, "scalar-epilogue", "Don't tail-predicate loops, create scalar epilogue"), clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue, "predicate-else-scalar-epilogue", "prefer tail-folding, create scalar epilogue if tail " "folding fails."), clEnumValN(PreferPredicateTy::PredicateOrDontVectorize, "predicate-dont-vectorize", "prefers tail-folding, don't attempt vectorization if " "tail-folding fails.")))
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< cl::boolOrDefault > ForceSafeDivisor("force-widen-divrem-via-safe-divisor", cl::Hidden, cl::desc("Override cost based safe divisor widening for div/rem instructions"))
static InstructionCost calculateEarlyExitCost(VPCostContext &CostCtx, VPlan &Plan, ElementCount VF)
For loops with uncountable early exits, find the cost of doing work when exiting the loop early,...
static cl::opt< unsigned > ForceTargetMaxVectorInterleaveFactor("force-target-max-vector-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "vectorized loops."))
static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI)
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 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.
static cl::opt< bool > ForceTargetSupportsMaskedMemoryOps("force-target-supports-masked-memory-ops", cl::init(false), cl::Hidden, cl::desc("Assume the target supports masked memory operations (used for " "testing)."))
Note: This currently only applies to llvm.masked.load and llvm.masked.store.
static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, Loop *L, PredicatedScalarEvolution &PSE, VPCostContext &CostCtx, VPlan &Plan, ScalarEpilogueLowering SEL, std::optional< unsigned > VScale)
This function determines whether or not it's still profitable to vectorize the loop given the extra w...
static cl::opt< bool > MaximizeBandwidth("vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, cl::desc("Maximize bandwidth when selecting vectorization factor which " "will be determined by the smallest type in loop."))
static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I, DebugLoc DL={})
Create an analysis remark that explains why vectorization failed.
#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.
#define T
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 BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore, Value *FlagsOp)
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore, Value *FlagsOp)
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={})
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:114
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
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:
static const char PassName[]
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:1555
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1527
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
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
BinaryOps getOpcode() const
Definition InstrTypes.h:374
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
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.
unsigned arg_size() const
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.
Definition InstrTypes.h:986
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
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
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
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:256
bool empty() const
Definition DenseMap.h:109
iterator end()
Definition DenseMap.h:81
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:294
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
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
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:763
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:728
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:2811
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...
InductionKind
This enum represents the kinds of inductions that we support.
@ IK_NoInduction
Not an induction variable.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
InnerLoopAndEpilogueVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, 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:354
LLVM_ABI APInt getMask() const
For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
Definition Type.cpp:378
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
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.
Drive the analysis of memory accesses in the loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
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.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
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.
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.
SmallPtrSet< Type *, 16 > ElementTypesInLoop
All element types found in the loop.
bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment, unsigned AddressSpace) const
Returns true if the target machine supports masked load operation for the given DataType and kind of ...
void collectElementTypesForWidening()
Collect all element types in the loop for which widening is needed.
bool canVectorizeReductions(ElementCount VF) const
Returns true if the target machine supports all of the reduction variables found for the given VF.
bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment, unsigned AddressSpace) const
Returns true if the target machine supports masked store operation for the given DataType and kind of...
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.
void collectInLoopReductions()
Split reductions into those that happen in the loop, and those that happen outside.
BlockFrequencyInfo & getBFI()
Returns the BlockFrequencyInfo for the function if cached, otherwise fetches it via GetBFI.
std::pair< unsigned, unsigned > getSmallestAndWidestTypes()
bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be uniform after vectorization.
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.
std::optional< unsigned > getMaxSafeElements() const
Return maximum safe number of elements to be processed per vector iteration, which do not prevent sto...
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.
DemandedBits * DB
Demanded bits analysis.
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 OptForSize
Whether this loop should be optimized for size based on function attribute or profile information.
bool useMaxBandwidth(TargetTransformInfo::RegisterKind RegKind)
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)
bool shouldConsiderRegPressureForVF(ElementCount VF)
Loop * TheLoop
The loop that we evaluate.
TTI::TargetCostKind CostKind
The kind of cost that we are calculating.
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 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.
bool selectUserVectorizationFactor(ElementCount UserVF)
Setup cost-based decisions for user vectorization factor.
std::optional< unsigned > getVScaleForTuning() const
Return the value of vscale used for tuning the cost model.
void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC)
Selects and saves TailFoldingStyle.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
bool preferPredicatedLoop() const
Returns true if tail-folding is preferred over a scalar epilogue.
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 isInLoopReduction(PHINode *Phi) const
Returns true if the Phi is part of an inloop reduction.
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 ...
const MapVector< Instruction *, uint64_t > & getMinimalBitwidths() const
CallWideningDecision getCallWideningDecision(CallInst *CI, ElementCount VF) const
bool isLegalGatherOrScatter(Value *V, ElementCount VF)
Returns true if the target machine can represent V as a masked gather or scatter operation.
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,...
void setCallWideningDecision(CallInst *CI, ElementCount VF, InstWidening Kind, Function *Variant, Intrinsic::ID IID, std::optional< unsigned > MaskPos, InstructionCost Cost)
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.
bool usePredicatedReductionSelect(RecurKind RecurrenceKind) const
Returns true if the predicated reduction select should be used to set the incoming value for the redu...
std::pair< InstructionCost, InstructionCost > getDivRemSpeculationCost(Instruction *I, ElementCount VF)
Return the costs for our two available strategies for lowering a div/rem operation which requires spe...
InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const
Estimate cost of a call instruction CI if it were vectorized with factor VF.
bool isScalarWithPredication(Instruction *I, ElementCount VF)
Returns true if I is an instruction which requires predication and for which our chosen predication s...
bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const
Returns true if we should use strict in-order reductions for the given RdxDesc.
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost SafeDivisorCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
std::function< BlockFrequencyInfo &()> GetBFI
A function to lazily fetch BlockFrequencyInfo.
LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, const Function *F, const LoopVectorizeHints *Hints, InterleavedAccessInfo &IAI, bool OptForSize)
InstructionCost expectedCost(ElementCount VF)
Returns the expected execution cost.
void setCostBasedWideningDecision(ElementCount VF)
Memory access instruction may be vectorized in more than one way.
InstWidening getWideningDecision(Instruction *I, ElementCount VF) const
Return the cost model decision for the given instruction I and vector width VF.
FixedScalableVFPair MaxPermissibleVFWithoutMaxBW
The highest VF possible for this loop, without using MaxBandwidth.
const SmallPtrSetImpl< PHINode * > & getInLoopReductions() const
Returns the set of in-loop reduction PHIs.
bool isScalarEpilogueAllowed() const
Returns true if a scalar epilogue is allowed (e.g.., not prevented by optsize or a loop hint annotati...
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.
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
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:1653
VectorizationFactor planInVPlanNativePath(ElementCount UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost.
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:1704
void buildVPlans(ElementCount MinVF, ElementCount MaxVF)
Build VPlans for power-of-2 VF's between MinVF and MaxVF inclusive, according to the information gath...
Definition VPlan.cpp:1637
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:1618
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1798
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.
bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
void emitRemarkWithHints() const
Dumps all the hint information.
const char * vectorizeAnalysisPassName() const
If hints are provided that force vectorization, use the AlwaysPrint pass name to force the frontend t...
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition LoopInfo.cpp:73
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:653
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
Metadata node.
Definition Metadata.h:1080
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:124
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.
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
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,...
unsigned getMinWidthCastToRecurrenceTypeInBits() const
Returns the minimum width used by the recurrence in bits.
LLVM_ABI SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
bool isSigned() const
Returns true if all source operands of the recurrence are SExtInsts.
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
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.
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.
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 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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI std::optional< unsigned > getVScaleForTuning() const
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).
LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const
LLVM_ABI bool preferFixedOverScalableIfEqualCost(bool IsEpilogue) const
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI bool isElementTypeLegalForScalableVector(Type *Ty) const
LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
LLVM_ABI bool supportsScalableVectors() const
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
@ 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:290
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:286
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
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:236
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:310
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
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:74
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4253
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4280
iterator end()
Definition VPlan.h:4290
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4288
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4341
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of this VPBasicBlock.
Definition VPlan.cpp:778
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:232
const VPRecipeBase & front() const
Definition VPlan.h:4300
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:644
bool empty() const
Definition VPlan.h:4299
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:202
void setName(const Twine &newName)
Definition VPlan.h:183
VPlan * getPlan()
Definition VPlan.cpp:177
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:182
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:231
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:244
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:272
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})
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={})
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
Canonical scalar induction phi of the vector loop.
Definition VPlan.h:3831
VPIRValue * getStartValue() const
Returns the start value of the canonical induction.
Definition VPlan.h:3853
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:465
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:438
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2306
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2348
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2337
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2048
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4406
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1225
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the VPInstruction is masked.
Definition VPlan.h:1456
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1476
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1272
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1330
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1321
unsigned getOpcode() const
Definition VPlan.h:1405
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1504
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1470
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1446
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:2970
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:1633
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:406
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:555
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.
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...
VPValue * getVPValueOrAddLiveIn(Value *V)
VPReplicateRecipe * handleReplication(VPInstruction *VPI, VFRange &Range)
Build a VPReplicationRecipe for VPI.
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2761
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:2740
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2764
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2758
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3063
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4441
const VPBlockBase * getEntry() const
Definition VPlan.h:4477
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the region.
Definition VPlan.h:4539
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3217
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:607
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:675
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:296
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:340
operand_iterator op_begin()
Definition VPlanValue.h:360
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:335
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:46
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:137
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:127
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:70
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1449
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:1455
user_range users()
Definition VPlanValue.h:149
A recipe to compute a pointer to the last element of each part of a widened memory access for widened...
Definition VPlan.h:2154
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1840
A recipe for handling GEP instructions.
Definition VPlan.h:2090
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2454
A recipe for widened phis.
Definition VPlan.h:2590
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1784
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4571
bool hasVF(ElementCount VF) const
Definition VPlan.h:4784
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:4797
VPBasicBlock * getEntry()
Definition VPlan.h:4663
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4721
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4760
bool hasUF(unsigned UF) const
Definition VPlan.h:4809
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4711
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:4834
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:4860
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1067
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:4955
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1049
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4735
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4688
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:4757
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4702
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:922
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4707
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4668
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4753
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:1215
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 const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:709
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
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:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
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.
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.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
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
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:190
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.
auto m_Cmp()
Matches any compare instruction and ignore it.
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)
bind_ty< 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.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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)
bind_ty< 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)
int_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
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)
bool match(Val *V, const Pattern &P)
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.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
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,...
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:111
VPSingleDefRecipe * findHeaderMask(VPlan &Plan)
Collect the header mask with the pattern: (ICMP_ULE, WideCanonicalIV, backedge-taken-count) TODO: Int...
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:532
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:831
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:
static void reportVectorization(OptimizationRemarkEmitter *ORE, Loop *TheLoop, VectorizationFactor VF, unsigned IC)
Report successful vectorization of the loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
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:2208
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
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:279
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:366
constexpr auto bind_front(FnT &&Fn, BindArgsT &&...BindArgs)
C++20 bind_front.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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:1636
LLVM_ABI_FOR_TEST cl::opt< bool > EnableWideActiveLaneMask
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:83
@ ReadOnly
No side effects to worry about, so we can process any uncountable exits in the loop and branch either...
Definition VPlan.h:88
@ MaskedHandleExitInScalarLoop
All memory operations other than the load(s) required to determine whether an uncountable exit occurr...
Definition VPlan.h:93
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI cl::opt< bool > EnableLoopVectorization
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
LLVM_ABI_FOR_TEST cl::list< std::string > VPlanPrintAfterPasses
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:422
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
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:1837
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
static void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I=nullptr, DebugLoc DL={})
Reports an informative message: print Msg for debugging purposes as well as an optimization remark.
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.
@ Or
Bitwise or logical OR of integers.
@ 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.
LLVM_ABI void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
DWARFExpression::Operation Op
ScalarEpilogueLowering
@ CM_ScalarEpilogueNotAllowedLowTripLoop
@ CM_ScalarEpilogueNotNeededUsePredicate
@ CM_ScalarEpilogueNotAllowedOptSize
@ CM_ScalarEpilogueAllowed
@ CM_ScalarEpilogueNotAllowedUsePredicate
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:1772
Value * emitTransformedIndex(IRBuilderBase &B, Value *Index, Value *StartValue, Value *Step, InductionDescriptor::InductionKind InductionKind, const BinaryOperator *InductionBinOp)
Compute the transformed value of Index at offset StartValue using step StepValue.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
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:592
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:345
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:78
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.
LLVM_ABI MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock * > Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:466
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintVectorRegionScope
LLVM_ABI cl::opt< bool > EnableLoopInterleaving
#define N
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:70
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.
std::optional< unsigned > getParamIndexForOptionalMask() const
Instruction Set Architecture.
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 isLegacyUniformAfterVectorization(Instruction *I, ElementCount VF) const
Return true if I is considered uniform-after-vectorization in the legacy cost model for VF.
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...
uint64_t getPredBlockCostDivisor(BasicBlock *BB) const
TargetTransformInfo::TargetCostKind CostKind
SmallPtrSet< Instruction *, 8 > SkipCostComputation
A struct that represents some properties of the register usage of a loop.
InstructionCost spillCost(VPCostContext &Ctx, 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:3619
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3702
static LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, const TargetLibraryInfo &TLI)
Replaces the VPInstructions in Plan with corresponding widen recipes.
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=nullptr)
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 LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, DebugLoc IVDL, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
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 createInLoopReductionRecipes(VPlan &Plan, const DenseSet< BasicBlock * > &BlocksNeedingPredication, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
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 dropPoisonGeneratingRecipes(VPlan &Plan, const std::function< bool(BasicBlock *)> &BlockNeedsPredication)
Drop poison flags from recipes that may generate a poison value that is used after vectorization,...
static void convertToVariableLengthStep(VPlan &Plan)
Transform loops with variable-length stepping after region dissolution.
static void createInterleaveGroups(VPlan &Plan, const SmallPtrSetImpl< const InterleaveGroup< Instruction > * > &InterleaveGroups, VPRecipeBuilder &RecipeBuilder, const bool &ScalarEpilogueAllowed)
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 unrollByUF(VPlan &Plan, unsigned UF)
Explicitly unroll Plan by UF.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static void expandBranchOnTwoConds(VPlan &Plan)
Expand BranchOnTwoConds instructions into explicit CFG with BranchOnCond instructions.
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 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 addExitUsersForFirstOrderRecurrences(VPlan &Plan, VFRange &Range)
Handle users in the exit block for first order reductions in the original exit block.
static void 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 addExplicitVectorLength(VPlan &Plan, const std::optional< unsigned > &MaxEVLSafeElements)
Add a VPCurrentIterationPHIRecipe and related recipes to Plan and replaces all uses except the canoni...
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 LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
Wrap runtime check block CheckBlock in a VPIRBB and Cond in a VPValue and connect the block to Plan,...
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 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 cse(VPlan &Plan)
Perform common-subexpression-elimination on Plan.
static void materializeVectorTripCount(VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking, bool RequiresScalarEpilogue, VPValue *Step)
Materialize vector trip count computations to a set of VPInstructions.
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 bool adjustFixedOrderRecurrences(VPlan &Plan, VPBuilder &Builder)
Try to have all users of fixed-order recurrences appear after the recipe defining their previous valu...
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