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