LLVM 17.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/Proposal/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 "VPlanHCFGBuilder.h"
61#include "VPlanTransforms.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/Hashing.h"
67#include "llvm/ADT/MapVector.h"
68#include "llvm/ADT/STLExtras.h"
70#include "llvm/ADT/SmallSet.h"
72#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
74#include "llvm/ADT/Twine.h"
79#include "llvm/Analysis/CFG.h"
95#include "llvm/IR/Attributes.h"
96#include "llvm/IR/BasicBlock.h"
97#include "llvm/IR/CFG.h"
98#include "llvm/IR/Constant.h"
99#include "llvm/IR/Constants.h"
100#include "llvm/IR/DataLayout.h"
102#include "llvm/IR/DebugLoc.h"
103#include "llvm/IR/DerivedTypes.h"
105#include "llvm/IR/Dominators.h"
106#include "llvm/IR/Function.h"
107#include "llvm/IR/IRBuilder.h"
108#include "llvm/IR/InstrTypes.h"
109#include "llvm/IR/Instruction.h"
110#include "llvm/IR/Instructions.h"
112#include "llvm/IR/Intrinsics.h"
113#include "llvm/IR/Metadata.h"
114#include "llvm/IR/Module.h"
115#include "llvm/IR/Operator.h"
116#include "llvm/IR/PatternMatch.h"
117#include "llvm/IR/Type.h"
118#include "llvm/IR/Use.h"
119#include "llvm/IR/User.h"
120#include "llvm/IR/Value.h"
121#include "llvm/IR/ValueHandle.h"
122#include "llvm/IR/Verifier.h"
124#include "llvm/Pass.h"
125#include "llvm/Support/Casting.h"
128#include "llvm/Support/Debug.h"
141#include <algorithm>
142#include <cassert>
143#include <cmath>
144#include <cstdint>
145#include <functional>
146#include <iterator>
147#include <limits>
148#include <map>
149#include <memory>
150#include <string>
151#include <tuple>
152#include <utility>
153
154using namespace llvm;
155
156#define LV_NAME "loop-vectorize"
157#define DEBUG_TYPE LV_NAME
158
159#ifndef NDEBUG
160const char VerboseDebug[] = DEBUG_TYPE "-verbose";
161#endif
162
163/// @{
164/// Metadata attribute names
165const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
167 "llvm.loop.vectorize.followup_vectorized";
169 "llvm.loop.vectorize.followup_epilogue";
170/// @}
171
172STATISTIC(LoopsVectorized, "Number of loops vectorized");
173STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
174STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
175
177 "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
178 cl::desc("Enable vectorization of epilogue loops."));
179
181 "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
182 cl::desc("When epilogue vectorization is enabled, and a value greater than "
183 "1 is specified, forces the given VF for all applicable epilogue "
184 "loops."));
185
187 "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
188 cl::desc("Only loops with vectorization factor equal to or larger than "
189 "the specified value are considered for epilogue vectorization."));
190
191/// Loops with a known constant trip count below this number are vectorized only
192/// if no scalar iteration overheads are incurred.
194 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
195 cl::desc("Loops with a constant trip count that is smaller than this "
196 "value are vectorized only if no scalar iteration overheads "
197 "are incurred."));
198
200 "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
201 cl::desc("The maximum allowed number of runtime memory checks"));
202
203// Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
204// that predication is preferred, and this lists all options. I.e., the
205// vectorizer will try to fold the tail-loop (epilogue) into the vector body
206// and predicate the instructions accordingly. If tail-folding fails, there are
207// different fallback strategies depending on these values:
209 enum Option {
213 };
214} // namespace PreferPredicateTy
215
217 "prefer-predicate-over-epilogue",
220 cl::desc("Tail-folding and predication preferences over creating a scalar "
221 "epilogue loop."),
223 "scalar-epilogue",
224 "Don't tail-predicate loops, create scalar epilogue"),
226 "predicate-else-scalar-epilogue",
227 "prefer tail-folding, create scalar epilogue if tail "
228 "folding fails."),
230 "predicate-dont-vectorize",
231 "prefers tail-folding, don't attempt vectorization if "
232 "tail-folding fails.")));
233
235 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
236 cl::desc("Maximize bandwidth when selecting vectorization factor which "
237 "will be determined by the smallest type in loop."));
238
240 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
241 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
242
243/// An interleave-group may need masking if it resides in a block that needs
244/// predication, or in order to mask away gaps.
246 "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
247 cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
248
250 "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
251 cl::desc("We don't interleave loops with a estimated constant trip count "
252 "below this number"));
253
255 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
256 cl::desc("A flag that overrides the target's number of scalar registers."));
257
259 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
260 cl::desc("A flag that overrides the target's number of vector registers."));
261
263 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
264 cl::desc("A flag that overrides the target's max interleave factor for "
265 "scalar loops."));
266
268 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
269 cl::desc("A flag that overrides the target's max interleave factor for "
270 "vectorized loops."));
271
273 "force-target-instruction-cost", cl::init(0), cl::Hidden,
274 cl::desc("A flag that overrides the target's expected cost for "
275 "an instruction to a single constant value. Mostly "
276 "useful for getting consistent testing."));
277
279 "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
280 cl::desc(
281 "Pretend that scalable vectors are supported, even if the target does "
282 "not support them. This flag should only be used for testing."));
283
285 "small-loop-cost", cl::init(20), cl::Hidden,
286 cl::desc(
287 "The cost of a loop that is considered 'small' by the interleaver."));
288
290 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
291 cl::desc("Enable the use of the block frequency analysis to access PGO "
292 "heuristics minimizing code growth in cold regions and being more "
293 "aggressive in hot regions."));
294
295// Runtime interleave loops for load/store throughput.
297 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
298 cl::desc(
299 "Enable runtime interleaving until load/store ports are saturated"));
300
301/// Interleave small loops with scalar reductions.
303 "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
304 cl::desc("Enable interleaving for loops with small iteration counts that "
305 "contain scalar reductions to expose ILP."));
306
307/// The number of stores in a loop that are allowed to need predication.
309 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
310 cl::desc("Max number of stores to be predicated behind an if."));
311
313 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
314 cl::desc("Count the induction variable only once when interleaving"));
315
317 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
318 cl::desc("Enable if predication of stores during vectorization."));
319
321 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
322 cl::desc("The maximum interleave count to use when interleaving a scalar "
323 "reduction in a nested loop."));
324
325static cl::opt<bool>
326 PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
328 cl::desc("Prefer in-loop vector reductions, "
329 "overriding the targets preference."));
330
332 "force-ordered-reductions", cl::init(false), cl::Hidden,
333 cl::desc("Enable the vectorisation of loops with in-order (strict) "
334 "FP reductions"));
335
337 "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
338 cl::desc(
339 "Prefer predicating a reduction operation over an after loop select."));
340
342 "enable-vplan-native-path", cl::init(false), cl::Hidden,
343 cl::desc("Enable VPlan-native vectorization path with "
344 "support for outer loop vectorization."));
345
346// This flag enables the stress testing of the VPlan H-CFG construction in the
347// VPlan-native vectorization path. It must be used in conjuction with
348// -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
349// verification of the H-CFGs built.
351 "vplan-build-stress-test", cl::init(false), cl::Hidden,
352 cl::desc(
353 "Build VPlan for every supported loop nest in the function and bail "
354 "out right after the build (stress test the VPlan H-CFG construction "
355 "in the VPlan-native vectorization path)."));
356
358 "interleave-loops", cl::init(true), cl::Hidden,
359 cl::desc("Enable loop interleaving in Loop vectorization passes"));
361 "vectorize-loops", cl::init(true), cl::Hidden,
362 cl::desc("Run the Loop vectorization passes"));
363
365 "vplan-print-in-dot-format", cl::Hidden,
366 cl::desc("Use dot format instead of plain text when dumping VPlans"));
367
369 "force-widen-divrem-via-safe-divisor", cl::Hidden,
370 cl::desc(
371 "Override cost based safe divisor widening for div/rem instructions"));
372
373/// A helper function that returns true if the given type is irregular. The
374/// type is irregular if its allocated size doesn't equal the store size of an
375/// element of the corresponding vector type.
376static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
377 // Determine if an array of N elements of type Ty is "bitcast compatible"
378 // with a <N x Ty> vector.
379 // This is only true if there is no padding between the array elements.
380 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
381}
382
383/// A helper function that returns the reciprocal of the block probability of
384/// predicated blocks. If we return X, we are assuming the predicated block
385/// will execute once for every X iterations of the loop header.
386///
387/// TODO: We should use actual block probability here, if available. Currently,
388/// we always assume predicated blocks have a 50% chance of executing.
389static unsigned getReciprocalPredBlockProb() { return 2; }
390
391/// A helper function that returns an integer or floating-point constant with
392/// value C.
394 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
395 : ConstantFP::get(Ty, C);
396}
397
398/// Returns "best known" trip count for the specified loop \p L as defined by
399/// the following procedure:
400/// 1) Returns exact trip count if it is known.
401/// 2) Returns expected trip count according to profile data if any.
402/// 3) Returns upper bound estimate if it is known.
403/// 4) Returns std::nullopt if all of the above failed.
404static std::optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE,
405 Loop *L) {
406 // Check if exact trip count is known.
407 if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
408 return ExpectedTC;
409
410 // Check if there is an expected trip count available from profile data.
412 if (auto EstimatedTC = getLoopEstimatedTripCount(L))
413 return *EstimatedTC;
414
415 // Check if upper bound estimate is known.
416 if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
417 return ExpectedTC;
418
419 return std::nullopt;
420}
421
422namespace {
423// Forward declare GeneratedRTChecks.
424class GeneratedRTChecks;
425} // namespace
426
427namespace llvm {
428
430
431/// InnerLoopVectorizer vectorizes loops which contain only one basic
432/// block to a specified vectorization factor (VF).
433/// This class performs the widening of scalars into vectors, or multiple
434/// scalars. This class also implements the following features:
435/// * It inserts an epilogue loop for handling loops that don't have iteration
436/// counts that are known to be a multiple of the vectorization factor.
437/// * It handles the code generation for reduction variables.
438/// * Scalarization (implementation using scalars) of un-vectorizable
439/// instructions.
440/// InnerLoopVectorizer does not perform any vectorization-legality
441/// checks, and relies on the caller to check for the different legality
442/// aspects. The InnerLoopVectorizer relies on the
443/// LoopVectorizationLegality class to provide information about the induction
444/// and reduction variables that were found to a given vectorization factor.
446public:
449 const TargetLibraryInfo *TLI,
453 unsigned UnrollFactor, LoopVectorizationLegality *LVL,
455 ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
456 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
457 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
458 Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
460 // Query this against the original loop and save it here because the profile
461 // of the original loop header may change as the transformation happens.
464
466 this->MinProfitableTripCount = VecWidth;
467 else
468 this->MinProfitableTripCount = MinProfitableTripCount;
469 }
470
471 virtual ~InnerLoopVectorizer() = default;
472
473 /// Create a new empty loop that will contain vectorized instructions later
474 /// on, while the old loop will be used as the scalar remainder. Control flow
475 /// is generated around the vectorized (and scalar epilogue) loops consisting
476 /// of various checks and bypasses. Return the pre-header block of the new
477 /// loop and the start value for the canonical induction, if it is != 0. The
478 /// latter is the case when vectorizing the epilogue loop. In the case of
479 /// epilogue vectorization, this function is overriden to handle the more
480 /// complex control flow around the loops.
481 virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
482
483 /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
484 void fixVectorizedLoop(VPTransformState &State, VPlan &Plan);
485
486 // Return true if any runtime check is added.
488
489 /// A type for vectorized values in the new loop. Each value from the
490 /// original loop, when vectorized, is represented by UF vector values in the
491 /// new unrolled loop, where UF is the unroll factor.
493
494 /// A helper function to scalarize a single Instruction in the innermost loop.
495 /// Generates a sequence of scalar instances for each lane between \p MinLane
496 /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
497 /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
498 /// Instr's operands.
499 void scalarizeInstruction(const Instruction *Instr,
500 VPReplicateRecipe *RepRecipe,
501 const VPIteration &Instance, bool IfPredicateInstr,
502 VPTransformState &State);
503
504 /// Construct the vector value of a scalarized value \p V one lane at a time.
505 void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
506 VPTransformState &State);
507
508 /// Try to vectorize interleaved access group \p Group with the base address
509 /// given in \p Addr, optionally masking the vector operations if \p
510 /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
511 /// values in the vectorized loop.
513 ArrayRef<VPValue *> VPDefs,
515 ArrayRef<VPValue *> StoredValues,
516 VPValue *BlockInMask = nullptr);
517
518 /// Fix the non-induction PHIs in \p Plan.
519 void fixNonInductionPHIs(VPlan &Plan, VPTransformState &State);
520
521 /// Returns true if the reordering of FP operations is not allowed, but we are
522 /// able to vectorize with strict in-order reductions for the given RdxDesc.
523 bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
524
525 /// Create a broadcast instruction. This method generates a broadcast
526 /// instruction (shuffle) for loop invariant values and for the induction
527 /// value. If this is the induction variable then we extend it to N, N+1, ...
528 /// this is needed because each iteration in the loop corresponds to a SIMD
529 /// element.
530 virtual Value *getBroadcastInstrs(Value *V);
531
532 // Returns the resume value (bc.merge.rdx) for a reduction as
533 // generated by fixReduction.
535
536 /// Create a new phi node for the induction variable \p OrigPhi to resume
537 /// iteration count in the scalar epilogue, from where the vectorized loop
538 /// left off. In cases where the loop skeleton is more complicated (eg.
539 /// epilogue vectorization) and the resume values can come from an additional
540 /// bypass block, the \p AdditionalBypass pair provides information about the
541 /// bypass block and the end value on the edge from bypass to this loop.
543 PHINode *OrigPhi, const InductionDescriptor &ID,
544 ArrayRef<BasicBlock *> BypassBlocks,
545 std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
546
547protected:
549
550 /// A small list of PHINodes.
552
553 /// A type for scalarized values in the new loop. Each value from the
554 /// original loop, when scalarized, is represented by UF x VF scalar values
555 /// in the new unrolled loop, where UF is the unroll factor and VF is the
556 /// vectorization factor.
558
559 /// Set up the values of the IVs correctly when exiting the vector loop.
560 void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
561 Value *VectorTripCount, Value *EndValue,
562 BasicBlock *MiddleBlock, BasicBlock *VectorHeader,
563 VPlan &Plan);
564
565 /// Handle all cross-iteration phis in the header.
567
568 /// Create the exit value of first order recurrences in the middle block and
569 /// update their users.
571 VPTransformState &State);
572
573 /// Create code for the loop exit value of the reduction.
575
576 /// Clear NSW/NUW flags from reduction instructions if necessary.
578 VPTransformState &State);
579
580 /// Iteratively sink the scalarized operands of a predicated instruction into
581 /// the block that was created for it.
582 void sinkScalarOperands(Instruction *PredInst);
583
584 /// Shrinks vector element sizes to the smallest bitwidth they can be legally
585 /// represented as.
587
588 /// Returns (and creates if needed) the original loop trip count.
590
591 /// Returns (and creates if needed) the trip count of the widened loop.
593
594 /// Returns a bitcasted value to the requested vector type.
595 /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
597 const DataLayout &DL);
598
599 /// Emit a bypass check to see if the vector trip count is zero, including if
600 /// it overflows.
602
603 /// Emit a bypass check to see if all of the SCEV assumptions we've
604 /// had to make are correct. Returns the block containing the checks or
605 /// nullptr if no checks have been added.
607
608 /// Emit bypass checks to check any memory assumptions we may have made.
609 /// Returns the block containing the checks or nullptr if no checks have been
610 /// added.
612
613 /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
614 /// vector loop preheader, middle block and scalar preheader.
616
617 /// Create new phi nodes for the induction variables to resume iteration count
618 /// in the scalar epilogue, from where the vectorized loop left off.
619 /// In cases where the loop skeleton is more complicated (eg. epilogue
620 /// vectorization) and the resume values can come from an additional bypass
621 /// block, the \p AdditionalBypass pair provides information about the bypass
622 /// block and the end value on the edge from bypass to this loop.
624 std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
625
626 /// Complete the loop skeleton by adding debug MDs, creating appropriate
627 /// conditional branches in the middle block, preparing the builder and
628 /// running the verifier. Return the preheader of the completed vector loop.
630
631 /// Collect poison-generating recipes that may generate a poison value that is
632 /// used after vectorization, even when their operands are not poison. Those
633 /// recipes meet the following conditions:
634 /// * Contribute to the address computation of a recipe generating a widen
635 /// memory load/store (VPWidenMemoryInstructionRecipe or
636 /// VPInterleaveRecipe).
637 /// * Such a widen memory load/store has at least one underlying Instruction
638 /// that is in a basic block that needs predication and after vectorization
639 /// the generated instruction won't be predicated.
641
642 /// Allow subclasses to override and print debug traces before/after vplan
643 /// execution, when trace information is requested.
644 virtual void printDebugTracesAtStart(){};
645 virtual void printDebugTracesAtEnd(){};
646
647 /// The original loop.
649
650 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
651 /// dynamic knowledge to simplify SCEV expressions and converts them to a
652 /// more usable form.
654
655 /// Loop Info.
657
658 /// Dominator Tree.
660
661 /// Target Library Info.
663
664 /// Target Transform Info.
666
667 /// Assumption Cache.
669
670 /// Interface to emit optimization remarks.
672
673 /// The vectorization SIMD factor to use. Each vector will have this many
674 /// vector elements.
676
678
679 /// The vectorization unroll factor to use. Each scalar is vectorized to this
680 /// many different vector instructions.
681 unsigned UF;
682
683 /// The builder that we use
685
686 // --- Vectorization state ---
687
688 /// The vector-loop preheader.
690
691 /// The scalar-loop preheader.
693
694 /// Middle Block between the vector and the scalar.
696
697 /// The unique ExitBlock of the scalar loop if one exists. Note that
698 /// there can be multiple exiting edges reaching this block.
700
701 /// The scalar loop body.
703
704 /// A list of all bypass blocks. The first block is the entry of the loop.
706
707 /// Store instructions that were predicated.
709
710 /// Trip count of the original loop.
711 Value *TripCount = nullptr;
712
713 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
715
716 /// The legality analysis.
718
719 /// The profitablity analysis.
721
722 // Record whether runtime checks are added.
723 bool AddedSafetyChecks = false;
724
725 // Holds the end values for each induction variable. We save the end values
726 // so we can later fix-up the external users of the induction variables.
728
729 /// BFI and PSI are used to check for profile guided size optimizations.
732
733 // Whether this loop should be optimized for size based on profile guided size
734 // optimizatios.
736
737 /// Structure to hold information about generated runtime checks, responsible
738 /// for cleaning the checks, if vectorization turns out unprofitable.
739 GeneratedRTChecks &RTChecks;
740
741 // Holds the resume values for reductions in the loops, used to set the
742 // correct start value of reduction PHIs when vectorizing the epilogue.
745};
746
748public:
751 const TargetLibraryInfo *TLI,
753 OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
756 ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
758 ElementCount::getFixed(1),
759 ElementCount::getFixed(1), UnrollFactor, LVL, CM,
760 BFI, PSI, Check) {}
761
762private:
763 Value *getBroadcastInstrs(Value *V) override;
764};
765
766/// Encapsulate information regarding vectorization of a loop and its epilogue.
767/// This information is meant to be updated and used across two stages of
768/// epilogue vectorization.
771 unsigned MainLoopUF = 0;
773 unsigned EpilogueUF = 0;
778 Value *TripCount = nullptr;
780
782 ElementCount EVF, unsigned EUF)
783 : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
784 assert(EUF == 1 &&
785 "A high UF for the epilogue loop is likely not beneficial.");
786 }
787};
788
789/// An extension of the inner loop vectorizer that creates a skeleton for a
790/// vectorized loop that has its epilogue (residual) also vectorized.
791/// The idea is to run the vplan on a given loop twice, firstly to setup the
792/// skeleton and vectorize the main loop, and secondly to complete the skeleton
793/// from the first step and vectorize the epilogue. This is achieved by
794/// deriving two concrete strategy classes from this base class and invoking
795/// them in succession from the loop vectorizer planner.
797public:
805 GeneratedRTChecks &Checks)
807 EPI.MainLoopVF, EPI.MainLoopVF, EPI.MainLoopUF, LVL,
808 CM, BFI, PSI, Checks),
809 EPI(EPI) {}
810
811 // Override this function to handle the more complex control flow around the
812 // three loops.
813 std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton() final {
815 }
816
817 /// The interface for creating a vectorized skeleton using one of two
818 /// different strategies, each corresponding to one execution of the vplan
819 /// as described above.
820 virtual std::pair<BasicBlock *, Value *>
822
823 /// Holds and updates state information required to vectorize the main loop
824 /// and its epilogue in two separate passes. This setup helps us avoid
825 /// regenerating and recomputing runtime safety checks. It also helps us to
826 /// shorten the iteration-count-check path length for the cases where the
827 /// iteration count of the loop is so small that the main vector loop is
828 /// completely skipped.
830};
831
832/// A specialized derived class of inner loop vectorizer that performs
833/// vectorization of *main* loops in the process of vectorizing loops and their
834/// epilogues.
836public:
844 GeneratedRTChecks &Check)
846 EPI, LVL, CM, BFI, PSI, Check) {}
847 /// Implements the interface for creating a vectorized skeleton using the
848 /// *main loop* strategy (ie the first pass of vplan execution).
849 std::pair<BasicBlock *, Value *> createEpilogueVectorizedLoopSkeleton() final;
850
851protected:
852 /// Emits an iteration count bypass check once for the main loop (when \p
853 /// ForEpilogue is false) and once for the epilogue loop (when \p
854 /// ForEpilogue is true).
855 BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
856 void printDebugTracesAtStart() override;
857 void printDebugTracesAtEnd() override;
858};
859
860// A specialized derived class of inner loop vectorizer that performs
861// vectorization of *epilogue* loops in the process of vectorizing loops and
862// their epilogues.
864public:
872 GeneratedRTChecks &Checks)
874 EPI, LVL, CM, BFI, PSI, Checks) {
876 }
877 /// Implements the interface for creating a vectorized skeleton using the
878 /// *epilogue loop* strategy (ie the second pass of vplan execution).
879 std::pair<BasicBlock *, Value *> createEpilogueVectorizedLoopSkeleton() final;
880
881protected:
882 /// Emits an iteration count bypass check after the main vector loop has
883 /// finished to see if there are any iterations left to execute by either
884 /// the vector epilogue or the scalar epilogue.
885 BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
886 BasicBlock *Bypass,
887 BasicBlock *Insert);
888 void printDebugTracesAtStart() override;
889 void printDebugTracesAtEnd() override;
890};
891} // end namespace llvm
892
893/// Look for a meaningful debug location on the instruction or it's
894/// operands.
896 if (!I)
897 return I;
898
900 if (I->getDebugLoc() != Empty)
901 return I;
902
903 for (Use &Op : I->operands()) {
904 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
905 if (OpInst->getDebugLoc() != Empty)
906 return OpInst;
907 }
908
909 return I;
910}
911
912/// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
913/// is passed, the message relates to that particular instruction.
914#ifndef NDEBUG
915static void debugVectorizationMessage(const StringRef Prefix,
916 const StringRef DebugMsg,
917 Instruction *I) {
918 dbgs() << "LV: " << Prefix << DebugMsg;
919 if (I != nullptr)
920 dbgs() << " " << *I;
921 else
922 dbgs() << '.';
923 dbgs() << '\n';
924}
925#endif
926
927/// Create an analysis remark that explains why vectorization failed
928///
929/// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
930/// RemarkName is the identifier for the remark. If \p I is passed it is an
931/// instruction that prevents vectorization. Otherwise \p TheLoop is used for
932/// the location of the remark. \return the remark object that can be
933/// streamed to.
935 StringRef RemarkName, Loop *TheLoop, Instruction *I) {
936 Value *CodeRegion = TheLoop->getHeader();
937 DebugLoc DL = TheLoop->getStartLoc();
938
939 if (I) {
940 CodeRegion = I->getParent();
941 // If there is no debug location attached to the instruction, revert back to
942 // using the loop's.
943 if (I->getDebugLoc())
944 DL = I->getDebugLoc();
945 }
946
947 return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
948}
949
950namespace llvm {
951
952/// Return a value for Step multiplied by VF.
954 int64_t Step) {
955 assert(Ty->isIntegerTy() && "Expected an integer step");
956 Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
957 return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
958}
959
960/// Return the runtime value for VF.
963 return VF.isScalable() ? B.CreateVScale(EC) : EC;
964}
965
967 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
968 assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && "Invalid loop count");
969
970 ScalarEvolution &SE = *PSE.getSE();
971
972 // The exit count might have the type of i64 while the phi is i32. This can
973 // happen if we have an induction variable that is sign extended before the
974 // compare. The only way that we get a backedge taken count is that the
975 // induction variable was signed and as such will not overflow. In such a case
976 // truncation is legal.
977 if (SE.getTypeSizeInBits(BackedgeTakenCount->getType()) >
978 IdxTy->getPrimitiveSizeInBits())
979 BackedgeTakenCount = SE.getTruncateOrNoop(BackedgeTakenCount, IdxTy);
980 BackedgeTakenCount = SE.getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
981
982 // Get the total trip count from the count by adding 1.
983 return SE.getAddExpr(BackedgeTakenCount,
984 SE.getOne(BackedgeTakenCount->getType()));
985}
986
988 ElementCount VF) {
989 assert(FTy->isFloatingPointTy() && "Expected floating point type!");
990 Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
991 Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
992 return B.CreateUIToFP(RuntimeVF, FTy);
993}
994
996 const StringRef OREMsg, const StringRef ORETag,
997 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
998 Instruction *I) {
999 LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1000 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1001 ORE->emit(
1002 createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1003 << "loop not vectorized: " << OREMsg);
1004}
1005
1006void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1007 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1008 Instruction *I) {
1010 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1011 ORE->emit(
1012 createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1013 << Msg);
1014}
1015
1016} // end namespace llvm
1017
1018#ifndef NDEBUG
1019/// \return string containing a file name and a line # for the given loop.
1020static std::string getDebugLocString(const Loop *L) {
1021 std::string Result;
1022 if (L) {
1023 raw_string_ostream OS(Result);
1024 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1025 LoopDbgLoc.print(OS);
1026 else
1027 // Just print the module name.
1029 OS.flush();
1030 }
1031 return Result;
1032}
1033#endif
1034
1036 VPTransformState &State) {
1037
1038 // Collect recipes in the backward slice of `Root` that may generate a poison
1039 // value that is used after vectorization.
1041 auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1043 Worklist.push_back(Root);
1044
1045 // Traverse the backward slice of Root through its use-def chain.
1046 while (!Worklist.empty()) {
1047 VPRecipeBase *CurRec = Worklist.back();
1048 Worklist.pop_back();
1049
1050 if (!Visited.insert(CurRec).second)
1051 continue;
1052
1053 // Prune search if we find another recipe generating a widen memory
1054 // instruction. Widen memory instructions involved in address computation
1055 // will lead to gather/scatter instructions, which don't need to be
1056 // handled.
1057 if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1058 isa<VPInterleaveRecipe>(CurRec) ||
1059 isa<VPScalarIVStepsRecipe>(CurRec) ||
1060 isa<VPCanonicalIVPHIRecipe>(CurRec) ||
1061 isa<VPActiveLaneMaskPHIRecipe>(CurRec))
1062 continue;
1063
1064 // This recipe contributes to the address computation of a widen
1065 // load/store. Collect recipe if its underlying instruction has
1066 // poison-generating flags.
1067 Instruction *Instr = CurRec->getUnderlyingInstr();
1068 if (Instr && Instr->hasPoisonGeneratingFlags())
1069 State.MayGeneratePoisonRecipes.insert(CurRec);
1070
1071 // Add new definitions to the worklist.
1072 for (VPValue *operand : CurRec->operands())
1073 if (VPRecipeBase *OpDef = operand->getDefiningRecipe())
1074 Worklist.push_back(OpDef);
1075 }
1076 });
1077
1078 // Traverse all the recipes in the VPlan and collect the poison-generating
1079 // recipes in the backward slice starting at the address of a VPWidenRecipe or
1080 // VPInterleaveRecipe.
1081 auto Iter = vp_depth_first_deep(State.Plan->getEntry());
1082 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1083 for (VPRecipeBase &Recipe : *VPBB) {
1084 if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1085 Instruction &UnderlyingInstr = WidenRec->getIngredient();
1086 VPRecipeBase *AddrDef = WidenRec->getAddr()->getDefiningRecipe();
1087 if (AddrDef && WidenRec->isConsecutive() &&
1088 Legal->blockNeedsPredication(UnderlyingInstr.getParent()))
1089 collectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1090 } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1091 VPRecipeBase *AddrDef = InterleaveRec->getAddr()->getDefiningRecipe();
1092 if (AddrDef) {
1093 // Check if any member of the interleave group needs predication.
1094 const InterleaveGroup<Instruction> *InterGroup =
1095 InterleaveRec->getInterleaveGroup();
1096 bool NeedPredication = false;
1097 for (int I = 0, NumMembers = InterGroup->getNumMembers();
1098 I < NumMembers; ++I) {
1099 Instruction *Member = InterGroup->getMember(I);
1100 if (Member)
1101 NeedPredication |=
1102 Legal->blockNeedsPredication(Member->getParent());
1103 }
1104
1105 if (NeedPredication)
1106 collectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1107 }
1108 }
1109 }
1110 }
1111}
1112
1114 const RecurrenceDescriptor &RdxDesc) {
1115 auto It = ReductionResumeValues.find(&RdxDesc);
1116 assert(It != ReductionResumeValues.end() &&
1117 "Expected to find a resume value for the reduction.");
1118 return It->second;
1119}
1120
1121namespace llvm {
1122
1123// Loop vectorization cost-model hints how the scalar epilogue loop should be
1124// lowered.
1126
1127 // The default: allowing scalar epilogues.
1129
1130 // Vectorization with OptForSize: don't allow epilogues.
1132
1133 // A special case of vectorisation with OptForSize: loops with a very small
1134 // trip count are considered for vectorization under OptForSize, thereby
1135 // making sure the cost of their loop body is dominant, free of runtime
1136 // guards and scalar iteration overheads.
1138
1139 // Loop hint predicate indicating an epilogue is undesired.
1141
1142 // Directive indicating we must either tail fold or not vectorize
1145
1146/// ElementCountComparator creates a total ordering for ElementCount
1147/// for the purposes of using it in a set structure.
1149 bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1150 return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1151 std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1152 }
1153};
1155
1156/// LoopVectorizationCostModel - estimates the expected speedups due to
1157/// vectorization.
1158/// In many cases vectorization is not profitable. This can happen because of
1159/// a number of reasons. In this class we mainly attempt to predict the
1160/// expected speedup/slowdowns due to the supported instruction set. We use the
1161/// TargetTransformInfo to query the different backends for the cost of
1162/// different operations.
1164public:
1168 const TargetTransformInfo &TTI,
1169 const TargetLibraryInfo *TLI, DemandedBits *DB,
1170 AssumptionCache *AC,
1172 const LoopVectorizeHints *Hints,
1174 : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1175 TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1176 Hints(Hints), InterleaveInfo(IAI) {}
1177
1178 /// \return An upper bound for the vectorization factors (both fixed and
1179 /// scalable). If the factors are 0, vectorization and interleaving should be
1180 /// avoided up front.
1181 FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1182
1183 /// \return True if runtime checks are required for vectorization, and false
1184 /// otherwise.
1185 bool runtimeChecksRequired();
1186
1187 /// \return The most profitable vectorization factor and the cost of that VF.
1188 /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1189 /// then this vectorization factor will be selected if vectorization is
1190 /// possible.
1192 selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1193
1195 selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1196 const LoopVectorizationPlanner &LVP);
1197
1198 /// Setup cost-based decisions for user vectorization factor.
1199 /// \return true if the UserVF is a feasible VF to be chosen.
1201 collectUniformsAndScalars(UserVF);
1202 collectInstsToScalarize(UserVF);
1203 return expectedCost(UserVF).first.isValid();
1204 }
1205
1206 /// \return The size (in bits) of the smallest and widest types in the code
1207 /// that needs to be vectorized. We ignore values that remain scalar such as
1208 /// 64 bit loop indices.
1209 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1210
1211 /// \return The desired interleave count.
1212 /// If interleave count has been specified by metadata it will be returned.
1213 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1214 /// are the selected vectorization factor and the cost of the selected VF.
1215 unsigned selectInterleaveCount(ElementCount VF, InstructionCost LoopCost);
1216
1217 /// Memory access instruction may be vectorized in more than one way.
1218 /// Form of instruction after vectorization depends on cost.
1219 /// This function takes cost-based decisions for Load/Store instructions
1220 /// and collects them in a map. This decisions map is used for building
1221 /// the lists of loop-uniform and loop-scalar instructions.
1222 /// The calculated cost is saved with widening decision in order to
1223 /// avoid redundant calculations.
1224 void setCostBasedWideningDecision(ElementCount VF);
1225
1226 /// A struct that represents some properties of the register usage
1227 /// of a loop.
1229 /// Holds the number of loop invariant values that are used in the loop.
1230 /// The key is ClassID of target-provided register class.
1232 /// Holds the maximum number of concurrent live intervals in the loop.
1233 /// The key is ClassID of target-provided register class.
1235 };
1236
1237 /// \return Returns information about the register usages of the loop for the
1238 /// given vectorization factors.
1240 calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1241
1242 /// Collect values we want to ignore in the cost model.
1243 void collectValuesToIgnore();
1244
1245 /// Collect all element types in the loop for which widening is needed.
1246 void collectElementTypesForWidening();
1247
1248 /// Split reductions into those that happen in the loop, and those that happen
1249 /// outside. In loop reductions are collected into InLoopReductionChains.
1250 void collectInLoopReductions();
1251
1252 /// Returns true if we should use strict in-order reductions for the given
1253 /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1254 /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1255 /// of FP operations.
1256 bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
1257 return !Hints->allowReordering() && RdxDesc.isOrdered();
1258 }
1259
1260 /// \returns The smallest bitwidth each instruction can be represented with.
1261 /// The vector equivalents of these instructions should be truncated to this
1262 /// type.
1264 return MinBWs;
1265 }
1266
1267 /// \returns True if it is more profitable to scalarize instruction \p I for
1268 /// vectorization factor \p VF.
1270 assert(VF.isVector() &&
1271 "Profitable to scalarize relevant only for VF > 1.");
1272
1273 // Cost model is not run in the VPlan-native path - return conservative
1274 // result until this changes.
1276 return false;
1277
1278 auto Scalars = InstsToScalarize.find(VF);
1279 assert(Scalars != InstsToScalarize.end() &&
1280 "VF not yet analyzed for scalarization profitability");
1281 return Scalars->second.find(I) != Scalars->second.end();
1282 }
1283
1284 /// Returns true if \p I is known to be uniform after vectorization.
1286 if (VF.isScalar())
1287 return true;
1288
1289 // Cost model is not run in the VPlan-native path - return conservative
1290 // result until this changes.
1292 return false;
1293
1294 auto UniformsPerVF = Uniforms.find(VF);
1295 assert(UniformsPerVF != Uniforms.end() &&
1296 "VF not yet analyzed for uniformity");
1297 return UniformsPerVF->second.count(I);
1298 }
1299
1300 /// Returns true if \p I is known to be scalar after vectorization.
1302 if (VF.isScalar())
1303 return true;
1304
1305 // Cost model is not run in the VPlan-native path - return conservative
1306 // result until this changes.
1308 return false;
1309
1310 auto ScalarsPerVF = Scalars.find(VF);
1311 assert(ScalarsPerVF != Scalars.end() &&
1312 "Scalar values are not calculated for VF");
1313 return ScalarsPerVF->second.count(I);
1314 }
1315
1316 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1317 /// for vectorization factor \p VF.
1319 return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1320 !isProfitableToScalarize(I, VF) &&
1321 !isScalarAfterVectorization(I, VF);
1322 }
1323
1324 /// Decision that was taken during cost calculation for memory instruction.
1327 CM_Widen, // For consecutive accesses with stride +1.
1328 CM_Widen_Reverse, // For consecutive accesses with stride -1.
1331 CM_Scalarize
1333
1334 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1335 /// instruction \p I and vector width \p VF.
1337 InstructionCost Cost) {
1338 assert(VF.isVector() && "Expected VF >=2");
1339 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1340 }
1341
1342 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1343 /// interleaving group \p Grp and vector width \p VF.
1346 InstructionCost Cost) {
1347 assert(VF.isVector() && "Expected VF >=2");
1348 /// Broadcast this decicion to all instructions inside the group.
1349 /// But the cost will be assigned to one instruction only.
1350 for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1351 if (auto *I = Grp->getMember(i)) {
1352 if (Grp->getInsertPos() == I)
1353 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1354 else
1355 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1356 }
1357 }
1358 }
1359
1360 /// Return the cost model decision for the given instruction \p I and vector
1361 /// width \p VF. Return CM_Unknown if this instruction did not pass
1362 /// through the cost modeling.
1364 assert(VF.isVector() && "Expected VF to be a vector VF");
1365 // Cost model is not run in the VPlan-native path - return conservative
1366 // result until this changes.
1368 return CM_GatherScatter;
1369
1370 std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1371 auto Itr = WideningDecisions.find(InstOnVF);
1372 if (Itr == WideningDecisions.end())
1373 return CM_Unknown;
1374 return Itr->second.first;
1375 }
1376
1377 /// Return the vectorization cost for the given instruction \p I and vector
1378 /// width \p VF.
1380 assert(VF.isVector() && "Expected VF >=2");
1381 std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1382 assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1383 "The cost is not calculated");
1384 return WideningDecisions[InstOnVF].second;
1385 }
1386
1387 /// Return True if instruction \p I is an optimizable truncate whose operand
1388 /// is an induction variable. Such a truncate will be removed by adding a new
1389 /// induction variable with the destination type.
1391 // If the instruction is not a truncate, return false.
1392 auto *Trunc = dyn_cast<TruncInst>(I);
1393 if (!Trunc)
1394 return false;
1395
1396 // Get the source and destination types of the truncate.
1397 Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1398 Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1399
1400 // If the truncate is free for the given types, return false. Replacing a
1401 // free truncate with an induction variable would add an induction variable
1402 // update instruction to each iteration of the loop. We exclude from this
1403 // check the primary induction variable since it will need an update
1404 // instruction regardless.
1405 Value *Op = Trunc->getOperand(0);
1406 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1407 return false;
1408
1409 // If the truncated value is not an induction variable, return false.
1410 return Legal->isInductionPhi(Op);
1411 }
1412
1413 /// Collects the instructions to scalarize for each predicated instruction in
1414 /// the loop.
1415 void collectInstsToScalarize(ElementCount VF);
1416
1417 /// Collect Uniform and Scalar values for the given \p VF.
1418 /// The sets depend on CM decision for Load/Store instructions
1419 /// that may be vectorized as interleave, gather-scatter or scalarized.
1421 // Do the analysis once.
1422 if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1423 return;
1424 setCostBasedWideningDecision(VF);
1425 collectLoopUniforms(VF);
1426 collectLoopScalars(VF);
1427 }
1428
1429 /// Returns true if the target machine supports masked store operation
1430 /// for the given \p DataType and kind of access to \p Ptr.
1431 bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1432 return Legal->isConsecutivePtr(DataType, Ptr) &&
1433 TTI.isLegalMaskedStore(DataType, Alignment);
1434 }
1435
1436 /// Returns true if the target machine supports masked load operation
1437 /// for the given \p DataType and kind of access to \p Ptr.
1438 bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1439 return Legal->isConsecutivePtr(DataType, Ptr) &&
1440 TTI.isLegalMaskedLoad(DataType, Alignment);
1441 }
1442
1443 /// Returns true if the target machine can represent \p V as a masked gather
1444 /// or scatter operation.
1447 bool LI = isa<LoadInst>(V);
1448 bool SI = isa<StoreInst>(V);
1449 if (!LI && !SI)
1450 return false;
1451 auto *Ty = getLoadStoreType(V);
1453 if (VF.isVector())
1454 Ty = VectorType::get(Ty, VF);
1455 return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1456 (SI && TTI.isLegalMaskedScatter(Ty, Align));
1457 }
1458
1459 /// Returns true if the target machine supports all of the reduction
1460 /// variables found for the given VF.
1462 return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1463 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1464 return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1465 }));
1466 }
1467
1468 /// Given costs for both strategies, return true if the scalar predication
1469 /// lowering should be used for div/rem. This incorporates an override
1470 /// option so it is not simply a cost comparison.
1472 InstructionCost SafeDivisorCost) const {
1473 switch (ForceSafeDivisor) {
1474 case cl::BOU_UNSET:
1475 return ScalarCost < SafeDivisorCost;
1476 case cl::BOU_TRUE:
1477 return false;
1478 case cl::BOU_FALSE:
1479 return true;
1480 };
1481 llvm_unreachable("impossible case value");
1482 }
1483
1484 /// Returns true if \p I is an instruction which requires predication and
1485 /// for which our chosen predication strategy is scalarization (i.e. we
1486 /// don't have an alternate strategy such as masking available).
1487 /// \p VF is the vectorization factor that will be used to vectorize \p I.
1488 bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1489
1490 /// Returns true if \p I is an instruction that needs to be predicated
1491 /// at runtime. The result is independent of the predication mechanism.
1492 /// Superset of instructions that return true for isScalarWithPredication.
1493 bool isPredicatedInst(Instruction *I) const;
1494
1495 /// Return the costs for our two available strategies for lowering a
1496 /// div/rem operation which requires speculating at least one lane.
1497 /// First result is for scalarization (will be invalid for scalable
1498 /// vectors); second is for the safe-divisor strategy.
1499 std::pair<InstructionCost, InstructionCost>
1500 getDivRemSpeculationCost(Instruction *I,
1501 ElementCount VF) const;
1502
1503 /// Returns true if \p I is a memory instruction with consecutive memory
1504 /// access that can be widened.
1505 bool memoryInstructionCanBeWidened(Instruction *I, ElementCount VF);
1506
1507 /// Returns true if \p I is a memory instruction in an interleaved-group
1508 /// of memory accesses that can be vectorized with wide vector loads/stores
1509 /// and shuffles.
1510 bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF);
1511
1512 /// Check if \p Instr belongs to any interleaved access group.
1514 return InterleaveInfo.isInterleaved(Instr);
1515 }
1516
1517 /// Get the interleaved access group that \p Instr belongs to.
1520 return InterleaveInfo.getInterleaveGroup(Instr);
1521 }
1522
1523 /// Returns true if we're required to use a scalar epilogue for at least
1524 /// the final iteration of the original loop.
1526 if (!isScalarEpilogueAllowed())
1527 return false;
1528 // If we might exit from anywhere but the latch, must run the exiting
1529 // iteration in scalar form.
1530 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1531 return true;
1532 return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1533 }
1534
1535 /// Returns true if a scalar epilogue is not allowed due to optsize or a
1536 /// loop hint annotation.
1538 return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1539 }
1540
1541 /// Returns the TailFoldingStyle that is best for the current loop.
1543 if (!CanFoldTailByMasking)
1544 return TailFoldingStyle::None;
1545
1547 }
1548
1549 /// Returns true if all loop blocks should be masked to fold tail loop.
1550 bool foldTailByMasking() const {
1551 return getTailFoldingStyle() != TailFoldingStyle::None;
1552 }
1553
1554 /// Returns true if were tail-folding and want to use the active lane mask
1555 /// for vector loop control flow.
1557 return getTailFoldingStyle() == TailFoldingStyle::DataAndControlFlow;
1558 }
1559
1560 /// Returns true if the instructions in this block requires predication
1561 /// for any reason, e.g. because tail folding now requires a predicate
1562 /// or because the block in the original loop was predicated.
1564 return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1565 }
1566
1567 /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1568 /// nodes to the chain of instructions representing the reductions. Uses a
1569 /// MapVector to ensure deterministic iteration order.
1572
1573 /// Return the chain of instructions representing an inloop reduction.
1575 return InLoopReductionChains;
1576 }
1577
1578 /// Returns true if the Phi is part of an inloop reduction.
1579 bool isInLoopReduction(PHINode *Phi) const {
1580 return InLoopReductionChains.count(Phi);
1581 }
1582
1583 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1584 /// with factor VF. Return the cost of the instruction, including
1585 /// scalarization overhead if it's needed.
1586 InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1587
1588 /// Estimate cost of a call instruction CI if it were vectorized with factor
1589 /// VF. Return the cost of the instruction, including scalarization overhead
1590 /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1591 /// scalarized -
1592 /// i.e. either vector version isn't available, or is too expensive.
1593 InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1594 bool &NeedToScalarize) const;
1595
1596 /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1597 /// that of B.
1598 bool isMoreProfitable(const VectorizationFactor &A,
1599 const VectorizationFactor &B) const;
1600
1601 /// Invalidates decisions already taken by the cost model.
1603 WideningDecisions.clear();
1604 Uniforms.clear();
1605 Scalars.clear();
1606 }
1607
1608 /// Convenience function that returns the value of vscale_range iff
1609 /// vscale_range.min == vscale_range.max or otherwise returns the value
1610 /// returned by the corresponding TLI method.
1611 std::optional<unsigned> getVScaleForTuning() const;
1612
1613private:
1614 unsigned NumPredStores = 0;
1615
1616 /// \return An upper bound for the vectorization factors for both
1617 /// fixed and scalable vectorization, where the minimum-known number of
1618 /// elements is a power-of-2 larger than zero. If scalable vectorization is
1619 /// disabled or unsupported, then the scalable part will be equal to
1620 /// ElementCount::getScalable(0).
1621 FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1622 ElementCount UserVF,
1623 bool FoldTailByMasking);
1624
1625 /// \return the maximized element count based on the targets vector
1626 /// registers and the loop trip-count, but limited to a maximum safe VF.
1627 /// This is a helper function of computeFeasibleMaxVF.
1628 ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1629 unsigned SmallestType,
1630 unsigned WidestType,
1631 ElementCount MaxSafeVF,
1632 bool FoldTailByMasking);
1633
1634 /// \return the maximum legal scalable VF, based on the safe max number
1635 /// of elements.
1636 ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1637
1638 /// The vectorization cost is a combination of the cost itself and a boolean
1639 /// indicating whether any of the contributing operations will actually
1640 /// operate on vector values after type legalization in the backend. If this
1641 /// latter value is false, then all operations will be scalarized (i.e. no
1642 /// vectorization has actually taken place).
1643 using VectorizationCostTy = std::pair<InstructionCost, bool>;
1644
1645 /// Returns the expected execution cost. The unit of the cost does
1646 /// not matter because we use the 'cost' units to compare different
1647 /// vector widths. The cost that is returned is *not* normalized by
1648 /// the factor width. If \p Invalid is not nullptr, this function
1649 /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1650 /// each instruction that has an Invalid cost for the given VF.
1651 using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1652 VectorizationCostTy
1653 expectedCost(ElementCount VF,
1655
1656 /// Returns the execution time cost of an instruction for a given vector
1657 /// width. Vector width of one means scalar.
1658 VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1659
1660 /// The cost-computation logic from getInstructionCost which provides
1661 /// the vector type as an output parameter.
1662 InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1663 Type *&VectorTy);
1664
1665 /// Return the cost of instructions in an inloop reduction pattern, if I is
1666 /// part of that pattern.
1667 std::optional<InstructionCost>
1668 getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1670
1671 /// Calculate vectorization cost of memory instruction \p I.
1672 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1673
1674 /// The cost computation for scalarized memory instruction.
1675 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1676
1677 /// The cost computation for interleaving group of memory instructions.
1678 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1679
1680 /// The cost computation for Gather/Scatter instruction.
1681 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1682
1683 /// The cost computation for widening instruction \p I with consecutive
1684 /// memory access.
1685 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1686
1687 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1688 /// Load: scalar load + broadcast.
1689 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1690 /// element)
1691 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1692
1693 /// Estimate the overhead of scalarizing an instruction. This is a
1694 /// convenience wrapper for the type-based getScalarizationOverhead API.
1695 InstructionCost getScalarizationOverhead(Instruction *I, ElementCount VF,
1697
1698 /// Returns true if an artificially high cost for emulated masked memrefs
1699 /// should be used.
1700 bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1701
1702 /// Map of scalar integer values to the smallest bitwidth they can be legally
1703 /// represented as. The vector equivalents of these values should be truncated
1704 /// to this type.
1706
1707 /// A type representing the costs for instructions if they were to be
1708 /// scalarized rather than vectorized. The entries are Instruction-Cost
1709 /// pairs.
1710 using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1711
1712 /// A set containing all BasicBlocks that are known to present after
1713 /// vectorization as a predicated block.
1715 PredicatedBBsAfterVectorization;
1716
1717 /// Records whether it is allowed to have the original scalar loop execute at
1718 /// least once. This may be needed as a fallback loop in case runtime
1719 /// aliasing/dependence checks fail, or to handle the tail/remainder
1720 /// iterations when the trip count is unknown or doesn't divide by the VF,
1721 /// or as a peel-loop to handle gaps in interleave-groups.
1722 /// Under optsize and when the trip count is very small we don't allow any
1723 /// iterations to execute in the scalar loop.
1724 ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1725
1726 /// All blocks of loop are to be masked to fold tail of scalar iterations.
1727 bool CanFoldTailByMasking = false;
1728
1729 /// A map holding scalar costs for different vectorization factors. The
1730 /// presence of a cost for an instruction in the mapping indicates that the
1731 /// instruction will be scalarized when vectorizing with the associated
1732 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1734
1735 /// Holds the instructions known to be uniform after vectorization.
1736 /// The data is collected per VF.
1738
1739 /// Holds the instructions known to be scalar after vectorization.
1740 /// The data is collected per VF.
1742
1743 /// Holds the instructions (address computations) that are forced to be
1744 /// scalarized.
1746
1747 /// PHINodes of the reductions that should be expanded in-loop along with
1748 /// their associated chains of reduction operations, in program order from top
1749 /// (PHI) to bottom
1750 ReductionChainMap InLoopReductionChains;
1751
1752 /// A Map of inloop reduction operations and their immediate chain operand.
1753 /// FIXME: This can be removed once reductions can be costed correctly in
1754 /// vplan. This was added to allow quick lookup to the inloop operations,
1755 /// without having to loop through InLoopReductionChains.
1756 DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1757
1758 /// Returns the expected difference in cost from scalarizing the expression
1759 /// feeding a predicated instruction \p PredInst. The instructions to
1760 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1761 /// non-negative return value implies the expression will be scalarized.
1762 /// Currently, only single-use chains are considered for scalarization.
1763 InstructionCost computePredInstDiscount(Instruction *PredInst,
1764 ScalarCostsTy &ScalarCosts,
1765 ElementCount VF);
1766
1767 /// Collect the instructions that are uniform after vectorization. An
1768 /// instruction is uniform if we represent it with a single scalar value in
1769 /// the vectorized loop corresponding to each vector iteration. Examples of
1770 /// uniform instructions include pointer operands of consecutive or
1771 /// interleaved memory accesses. Note that although uniformity implies an
1772 /// instruction will be scalar, the reverse is not true. In general, a
1773 /// scalarized instruction will be represented by VF scalar values in the
1774 /// vectorized loop, each corresponding to an iteration of the original
1775 /// scalar loop.
1776 void collectLoopUniforms(ElementCount VF);
1777
1778 /// Collect the instructions that are scalar after vectorization. An
1779 /// instruction is scalar if it is known to be uniform or will be scalarized
1780 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1781 /// to the list if they are used by a load/store instruction that is marked as
1782 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1783 /// VF values in the vectorized loop, each corresponding to an iteration of
1784 /// the original scalar loop.
1785 void collectLoopScalars(ElementCount VF);
1786
1787 /// Keeps cost model vectorization decision and cost for instructions.
1788 /// Right now it is used for memory instructions only.
1790 std::pair<InstWidening, InstructionCost>>;
1791
1792 DecisionList WideningDecisions;
1793
1794 /// Returns true if \p V is expected to be vectorized and it needs to be
1795 /// extracted.
1796 bool needsExtract(Value *V, ElementCount VF) const {
1797 Instruction *I = dyn_cast<Instruction>(V);
1798 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1799 TheLoop->isLoopInvariant(I))
1800 return false;
1801
1802 // Assume we can vectorize V (and hence we need extraction) if the
1803 // scalars are not computed yet. This can happen, because it is called
1804 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1805 // the scalars are collected. That should be a safe assumption in most
1806 // cases, because we check if the operands have vectorizable types
1807 // beforehand in LoopVectorizationLegality.
1808 return Scalars.find(VF) == Scalars.end() ||
1809 !isScalarAfterVectorization(I, VF);
1810 };
1811
1812 /// Returns a range containing only operands needing to be extracted.
1813 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1814 ElementCount VF) const {
1816 Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1817 }
1818
1819 /// Determines if we have the infrastructure to vectorize loop \p L and its
1820 /// epilogue, assuming the main loop is vectorized by \p VF.
1821 bool isCandidateForEpilogueVectorization(const Loop &L,
1822 const ElementCount VF) const;
1823
1824 /// Returns true if epilogue vectorization is considered profitable, and
1825 /// false otherwise.
1826 /// \p VF is the vectorization factor chosen for the original loop.
1827 bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1828
1829public:
1830 /// The loop that we evaluate.
1832
1833 /// Predicated scalar evolution analysis.
1835
1836 /// Loop Info analysis.
1838
1839 /// Vectorization legality.
1841
1842 /// Vector target information.
1844
1845 /// Target Library Info.
1847
1848 /// Demanded bits analysis.
1850
1851 /// Assumption cache.
1853
1854 /// Interface to emit optimization remarks.
1856
1858
1859 /// Loop Vectorize Hint.
1861
1862 /// The interleave access information contains groups of interleaved accesses
1863 /// with the same stride and close to each other.
1865
1866 /// Values to ignore in the cost model.
1868
1869 /// Values to ignore in the cost model when VF > 1.
1871
1872 /// All element types found in the loop.
1874
1875 /// Profitable vector factors.
1877};
1878} // end namespace llvm
1879
1880namespace {
1881/// Helper struct to manage generating runtime checks for vectorization.
1882///
1883/// The runtime checks are created up-front in temporary blocks to allow better
1884/// estimating the cost and un-linked from the existing IR. After deciding to
1885/// vectorize, the checks are moved back. If deciding not to vectorize, the
1886/// temporary blocks are completely removed.
1887class GeneratedRTChecks {
1888 /// Basic block which contains the generated SCEV checks, if any.
1889 BasicBlock *SCEVCheckBlock = nullptr;
1890
1891 /// The value representing the result of the generated SCEV checks. If it is
1892 /// nullptr, either no SCEV checks have been generated or they have been used.
1893 Value *SCEVCheckCond = nullptr;
1894
1895 /// Basic block which contains the generated memory runtime checks, if any.
1896 BasicBlock *MemCheckBlock = nullptr;
1897
1898 /// The value representing the result of the generated memory runtime checks.
1899 /// If it is nullptr, either no memory runtime checks have been generated or
1900 /// they have been used.
1901 Value *MemRuntimeCheckCond = nullptr;
1902
1903 DominatorTree *DT;
1904 LoopInfo *LI;
1906
1907 SCEVExpander SCEVExp;
1908 SCEVExpander MemCheckExp;
1909
1910 bool CostTooHigh = false;
1911
1912public:
1913 GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1915 : DT(DT), LI(LI), TTI(TTI), SCEVExp(SE, DL, "scev.check"),
1916 MemCheckExp(SE, DL, "scev.check") {}
1917
1918 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1919 /// accurately estimate the cost of the runtime checks. The blocks are
1920 /// un-linked from the IR and is added back during vector code generation. If
1921 /// there is no vector code generation, the check blocks are removed
1922 /// completely.
1923 void Create(Loop *L, const LoopAccessInfo &LAI,
1924 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC) {
1925
1926 // Hard cutoff to limit compile-time increase in case a very large number of
1927 // runtime checks needs to be generated.
1928 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1929 // profile info.
1930 CostTooHigh =
1932 if (CostTooHigh)
1933 return;
1934
1935 BasicBlock *LoopHeader = L->getHeader();
1936 BasicBlock *Preheader = L->getLoopPreheader();
1937
1938 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1939 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1940 // may be used by SCEVExpander. The blocks will be un-linked from their
1941 // predecessors and removed from LI & DT at the end of the function.
1942 if (!UnionPred.isAlwaysTrue()) {
1943 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1944 nullptr, "vector.scevcheck");
1945
1946 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1947 &UnionPred, SCEVCheckBlock->getTerminator());
1948 }
1949
1950 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1951 if (RtPtrChecking.Need) {
1952 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1953 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1954 "vector.memcheck");
1955
1956 auto DiffChecks = RtPtrChecking.getDiffChecks();
1957 if (DiffChecks) {
1958 Value *RuntimeVF = nullptr;
1959 MemRuntimeCheckCond = addDiffRuntimeChecks(
1960 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp,
1961 [VF, &RuntimeVF](IRBuilderBase &B, unsigned Bits) {
1962 if (!RuntimeVF)
1963 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1964 return RuntimeVF;
1965 },
1966 IC);
1967 } else {
1968 MemRuntimeCheckCond =
1969 addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1970 RtPtrChecking.getChecks(), MemCheckExp);
1971 }
1972 assert(MemRuntimeCheckCond &&
1973 "no RT checks generated although RtPtrChecking "
1974 "claimed checks are required");
1975 }
1976
1977 if (!MemCheckBlock && !SCEVCheckBlock)
1978 return;
1979
1980 // Unhook the temporary block with the checks, update various places
1981 // accordingly.
1982 if (SCEVCheckBlock)
1983 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1984 if (MemCheckBlock)
1985 MemCheckBlock->replaceAllUsesWith(Preheader);
1986
1987 if (SCEVCheckBlock) {
1988 SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1989 new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1990 Preheader->getTerminator()->eraseFromParent();
1991 }
1992 if (MemCheckBlock) {
1993 MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1994 new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1995 Preheader->getTerminator()->eraseFromParent();
1996 }
1997
1998 DT->changeImmediateDominator(LoopHeader, Preheader);
1999 if (MemCheckBlock) {
2000 DT->eraseNode(MemCheckBlock);
2001 LI->removeBlock(MemCheckBlock);
2002 }
2003 if (SCEVCheckBlock) {
2004 DT->eraseNode(SCEVCheckBlock);
2005 LI->removeBlock(SCEVCheckBlock);
2006 }
2007 }
2008
2009 InstructionCost getCost() {
2010 if (SCEVCheckBlock || MemCheckBlock)
2011 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
2012
2013 if (CostTooHigh) {
2015 Cost.setInvalid();
2016 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
2017 return Cost;
2018 }
2019
2020 InstructionCost RTCheckCost = 0;
2021 if (SCEVCheckBlock)
2022 for (Instruction &I : *SCEVCheckBlock) {
2023 if (SCEVCheckBlock->getTerminator() == &I)
2024 continue;
2027 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
2028 RTCheckCost += C;
2029 }
2030 if (MemCheckBlock)
2031 for (Instruction &I : *MemCheckBlock) {
2032 if (MemCheckBlock->getTerminator() == &I)
2033 continue;
2036 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
2037 RTCheckCost += C;
2038 }
2039
2040 if (SCEVCheckBlock || MemCheckBlock)
2041 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
2042 << "\n");
2043
2044 return RTCheckCost;
2045 }
2046
2047 /// Remove the created SCEV & memory runtime check blocks & instructions, if
2048 /// unused.
2049 ~GeneratedRTChecks() {
2050 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2051 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2052 if (!SCEVCheckCond)
2053 SCEVCleaner.markResultUsed();
2054
2055 if (!MemRuntimeCheckCond)
2056 MemCheckCleaner.markResultUsed();
2057
2058 if (MemRuntimeCheckCond) {
2059 auto &SE = *MemCheckExp.getSE();
2060 // Memory runtime check generation creates compares that use expanded
2061 // values. Remove them before running the SCEVExpanderCleaners.
2062 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2063 if (MemCheckExp.isInsertedInstruction(&I))
2064 continue;
2065 SE.forgetValue(&I);
2066 I.eraseFromParent();
2067 }
2068 }
2069 MemCheckCleaner.cleanup();
2070 SCEVCleaner.cleanup();
2071
2072 if (SCEVCheckCond)
2073 SCEVCheckBlock->eraseFromParent();
2074 if (MemRuntimeCheckCond)
2075 MemCheckBlock->eraseFromParent();
2076 }
2077
2078 /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2079 /// adjusts the branches to branch to the vector preheader or \p Bypass,
2080 /// depending on the generated condition.
2081 BasicBlock *emitSCEVChecks(BasicBlock *Bypass,
2082 BasicBlock *LoopVectorPreHeader,
2083 BasicBlock *LoopExitBlock) {
2084 if (!SCEVCheckCond)
2085 return nullptr;
2086
2087 Value *Cond = SCEVCheckCond;
2088 // Mark the check as used, to prevent it from being removed during cleanup.
2089 SCEVCheckCond = nullptr;
2090 if (auto *C = dyn_cast<ConstantInt>(Cond))
2091 if (C->isZero())
2092 return nullptr;
2093
2094 auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2095
2096 BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2097 // Create new preheader for vector loop.
2098 if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2099 PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2100
2101 SCEVCheckBlock->getTerminator()->eraseFromParent();
2102 SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2103 Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2104 SCEVCheckBlock);
2105
2106 DT->addNewBlock(SCEVCheckBlock, Pred);
2107 DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2108
2109 ReplaceInstWithInst(SCEVCheckBlock->getTerminator(),
2110 BranchInst::Create(Bypass, LoopVectorPreHeader, Cond));
2111 return SCEVCheckBlock;
2112 }
2113
2114 /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2115 /// the branches to branch to the vector preheader or \p Bypass, depending on
2116 /// the generated condition.
2117 BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass,
2118 BasicBlock *LoopVectorPreHeader) {
2119 // Check if we generated code that checks in runtime if arrays overlap.
2120 if (!MemRuntimeCheckCond)
2121 return nullptr;
2122
2123 auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2124 Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2125 MemCheckBlock);
2126
2127 DT->addNewBlock(MemCheckBlock, Pred);
2128 DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2129 MemCheckBlock->moveBefore(LoopVectorPreHeader);
2130
2131 if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2132 PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2133
2135 MemCheckBlock->getTerminator(),
2136 BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2137 MemCheckBlock->getTerminator()->setDebugLoc(
2138 Pred->getTerminator()->getDebugLoc());
2139
2140 // Mark the check as used, to prevent it from being removed during cleanup.
2141 MemRuntimeCheckCond = nullptr;
2142 return MemCheckBlock;
2143 }
2144};
2145} // namespace
2146
2147// Return true if \p OuterLp is an outer loop annotated with hints for explicit
2148// vectorization. The loop needs to be annotated with #pragma omp simd
2149// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2150// vector length information is not provided, vectorization is not considered
2151// explicit. Interleave hints are not allowed either. These limitations will be
2152// relaxed in the future.
2153// Please, note that we are currently forced to abuse the pragma 'clang
2154// vectorize' semantics. This pragma provides *auto-vectorization hints*
2155// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2156// provides *explicit vectorization hints* (LV can bypass legal checks and
2157// assume that vectorization is legal). However, both hints are implemented
2158// using the same metadata (llvm.loop.vectorize, processed by
2159// LoopVectorizeHints). This will be fixed in the future when the native IR
2160// representation for pragma 'omp simd' is introduced.
2161static bool isExplicitVecOuterLoop(Loop *OuterLp,
2163 assert(!OuterLp->isInnermost() && "This is not an outer loop");
2164 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2165
2166 // Only outer loops with an explicit vectorization hint are supported.
2167 // Unannotated outer loops are ignored.
2169 return false;
2170
2171 Function *Fn = OuterLp->getHeader()->getParent();
2172 if (!Hints.allowVectorization(Fn, OuterLp,
2173 true /*VectorizeOnlyWhenForced*/)) {
2174 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2175 return false;
2176 }
2177
2178 if (Hints.getInterleave() > 1) {
2179 // TODO: Interleave support is future work.
2180 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2181 "outer loops.\n");
2182 Hints.emitRemarkWithHints();
2183 return false;
2184 }
2185
2186 return true;
2187}
2188
2192 // Collect inner loops and outer loops without irreducible control flow. For
2193 // now, only collect outer loops that have explicit vectorization hints. If we
2194 // are stress testing the VPlan H-CFG construction, we collect the outermost
2195 // loop of every loop nest.
2196 if (L.isInnermost() || VPlanBuildStressTest ||
2198 LoopBlocksRPO RPOT(&L);
2199 RPOT.perform(LI);
2200 if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2201 V.push_back(&L);
2202 // TODO: Collect inner loops inside marked outer loops in case
2203 // vectorization fails for the outer loop. Do not invoke
2204 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2205 // already known to be reducible. We can use an inherited attribute for
2206 // that.
2207 return;
2208 }
2209 }
2210 for (Loop *InnerL : L)
2211 collectSupportedLoops(*InnerL, LI, ORE, V);
2212}
2213
2214namespace {
2215
2216/// The LoopVectorize Pass.
2217struct LoopVectorize : public FunctionPass {
2218 /// Pass identification, replacement for typeid
2219 static char ID;
2220
2221 LoopVectorizePass Impl;
2222
2223 explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2224 bool VectorizeOnlyWhenForced = false)
2225 : FunctionPass(ID),
2226 Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2228 }
2229
2230 bool runOnFunction(Function &F) override {
2231 if (skipFunction(F))
2232 return false;
2233
2234 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2235 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2236 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2237 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2238 auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2239 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2240 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2241 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2242 auto &LAIs = getAnalysis<LoopAccessLegacyAnalysis>().getLAIs();
2243 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2244 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2245 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2246
2247 return Impl
2248 .runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AC, LAIs, *ORE, PSI)
2250 }
2251
2252 void getAnalysisUsage(AnalysisUsage &AU) const override {
2263
2264 // We currently do not preserve loopinfo/dominator analyses with outer loop
2265 // vectorization. Until this is addressed, mark these analyses as preserved
2266 // only for non-VPlan-native path.
2267 // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2268 if (!EnableVPlanNativePath) {
2271 }
2272
2276 }
2277};
2278
2279} // end anonymous namespace
2280
2281//===----------------------------------------------------------------------===//
2282// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2283// LoopVectorizationCostModel and LoopVectorizationPlanner.
2284//===----------------------------------------------------------------------===//
2285
2287 // We need to place the broadcast of invariant variables outside the loop,
2288 // but only if it's proven safe to do so. Else, broadcast will be inside
2289 // vector loop body.
2290 Instruction *Instr = dyn_cast<Instruction>(V);
2291 bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2292 (!Instr ||
2294 // Place the code for broadcasting invariant variables in the new preheader.
2296 if (SafeToHoist)
2298
2299 // Broadcast the scalar into all locations in the vector.
2300 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2301
2302 return Shuf;
2303}
2304
2305/// This function adds
2306/// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2307/// to each vector element of Val. The sequence starts at StartIndex.
2308/// \p Opcode is relevant for FP induction variable.
2309static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2312 assert(VF.isVector() && "only vector VFs are supported");
2313
2314 // Create and check the types.
2315 auto *ValVTy = cast<VectorType>(Val->getType());
2316 ElementCount VLen = ValVTy->getElementCount();
2317
2318 Type *STy = Val->getType()->getScalarType();
2319 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2320 "Induction Step must be an integer or FP");
2321 assert(Step->getType() == STy && "Step has wrong type");
2322
2324
2325 // Create a vector of consecutive numbers from zero to VF.
2326 VectorType *InitVecValVTy = ValVTy;
2327 if (STy->isFloatingPointTy()) {
2328 Type *InitVecValSTy =
2330 InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2331 }
2332 Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2333
2334 // Splat the StartIdx
2335 Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2336
2337 if (STy->isIntegerTy()) {
2338 InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2339 Step = Builder.CreateVectorSplat(VLen, Step);
2340 assert(Step->getType() == Val->getType() && "Invalid step vec");
2341 // FIXME: The newly created binary instructions should contain nsw/nuw
2342 // flags, which can be found from the original scalar operations.
2343 Step = Builder.CreateMul(InitVec, Step);
2344 return Builder.CreateAdd(Val, Step, "induction");
2345 }
2346
2347 // Floating point induction.
2348 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2349 "Binary Opcode should be specified for FP induction");
2350 InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2351 InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2352
2353 Step = Builder.CreateVectorSplat(VLen, Step);
2354 Value *MulOp = Builder.CreateFMul(InitVec, Step);
2355 return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2356}
2357
2358/// Compute scalar induction steps. \p ScalarIV is the scalar induction
2359/// variable on which to base the steps, \p Step is the size of the step.
2360static void buildScalarSteps(Value *ScalarIV, Value *Step,
2361 const InductionDescriptor &ID, VPValue *Def,
2362 VPTransformState &State) {
2363 IRBuilderBase &Builder = State.Builder;
2364
2365 // Ensure step has the same type as that of scalar IV.
2366 Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2367 if (ScalarIVTy != Step->getType()) {
2368 // TODO: Also use VPDerivedIVRecipe when only the step needs truncating, to
2369 // avoid separate truncate here.
2370 assert(Step->getType()->isIntegerTy() &&
2371 "Truncation requires an integer step");
2372 Step = State.Builder.CreateTrunc(Step, ScalarIVTy);
2373 }
2374
2375 // We build scalar steps for both integer and floating-point induction
2376 // variables. Here, we determine the kind of arithmetic we will perform.
2379 if (ScalarIVTy->isIntegerTy()) {
2380 AddOp = Instruction::Add;
2381 MulOp = Instruction::Mul;
2382 } else {
2383 AddOp = ID.getInductionOpcode();
2384 MulOp = Instruction::FMul;
2385 }
2386
2387 // Determine the number of scalars we need to generate for each unroll
2388 // iteration.
2389 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2390 // Compute the scalar steps and save the results in State.
2391 Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2392 ScalarIVTy->getScalarSizeInBits());
2393 Type *VecIVTy = nullptr;
2394 Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2395 if (!FirstLaneOnly && State.VF.isScalable()) {
2396 VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2397 UnitStepVec =
2398 Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2399 SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2400 SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2401 }
2402
2403 unsigned StartPart = 0;
2404 unsigned EndPart = State.UF;
2405 unsigned StartLane = 0;
2406 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2407 if (State.Instance) {
2408 StartPart = State.Instance->Part;
2409 EndPart = StartPart + 1;
2410 StartLane = State.Instance->Lane.getKnownLane();
2411 EndLane = StartLane + 1;
2412 }
2413 for (unsigned Part = StartPart; Part < EndPart; ++Part) {
2414 Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2415
2416 if (!FirstLaneOnly && State.VF.isScalable()) {
2417 auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2418 auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2419 if (ScalarIVTy->isFloatingPointTy())
2420 InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2421 auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2422 auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2423 State.set(Def, Add, Part);
2424 // It's useful to record the lane values too for the known minimum number
2425 // of elements so we do those below. This improves the code quality when
2426 // trying to extract the first element, for example.
2427 }
2428
2429 if (ScalarIVTy->isFloatingPointTy())
2430 StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2431
2432 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2433 Value *StartIdx = Builder.CreateBinOp(
2434 AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2435 // The step returned by `createStepForVF` is a runtime-evaluated value
2436 // when VF is scalable. Otherwise, it should be folded into a Constant.
2437 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2438 "Expected StartIdx to be folded to a constant when VF is not "
2439 "scalable");
2440 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2441 auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2442 State.set(Def, Add, VPIteration(Part, Lane));
2443 }
2444 }
2445}
2446
2447// Generate code for the induction step. Note that induction steps are
2448// required to be loop-invariant
2450 Instruction *InsertBefore,
2451 Loop *OrigLoop = nullptr) {
2452 const DataLayout &DL = SE.getDataLayout();
2453 assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2454 "Induction step should be loop invariant");
2455 if (auto *E = dyn_cast<SCEVUnknown>(Step))
2456 return E->getValue();
2457
2458 SCEVExpander Exp(SE, DL, "induction");
2459 return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2460}
2461
2462/// Compute the transformed value of Index at offset StartValue using step
2463/// StepValue.
2464/// For integer induction, returns StartValue + Index * StepValue.
2465/// For pointer induction, returns StartValue[Index * StepValue].
2466/// FIXME: The newly created binary instructions should contain nsw/nuw
2467/// flags, which can be found from the original scalar operations.
2469 Value *StartValue, Value *Step,
2470 const InductionDescriptor &ID) {
2471 Type *StepTy = Step->getType();
2472 Value *CastedIndex = StepTy->isIntegerTy()
2473 ? B.CreateSExtOrTrunc(Index, StepTy)
2474 : B.CreateCast(Instruction::SIToFP, Index, StepTy);
2475 if (CastedIndex != Index) {
2476 CastedIndex->setName(CastedIndex->getName() + ".cast");
2477 Index = CastedIndex;
2478 }
2479
2480 // Note: the IR at this point is broken. We cannot use SE to create any new
2481 // SCEV and then expand it, hoping that SCEV's simplification will give us
2482 // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2483 // lead to various SCEV crashes. So all we can do is to use builder and rely
2484 // on InstCombine for future simplifications. Here we handle some trivial
2485 // cases only.
2486 auto CreateAdd = [&B](Value *X, Value *Y) {
2487 assert(X->getType() == Y->getType() && "Types don't match!");
2488 if (auto *CX = dyn_cast<ConstantInt>(X))
2489 if (CX->isZero())
2490 return Y;
2491 if (auto *CY = dyn_cast<ConstantInt>(Y))
2492 if (CY->isZero())
2493 return X;
2494 return B.CreateAdd(X, Y);
2495 };
2496
2497 // We allow X to be a vector type, in which case Y will potentially be
2498 // splatted into a vector with the same element count.
2499 auto CreateMul = [&B](Value *X, Value *Y) {
2500 assert(X->getType()->getScalarType() == Y->getType() &&
2501 "Types don't match!");
2502 if (auto *CX = dyn_cast<ConstantInt>(X))
2503 if (CX->isOne())
2504 return Y;
2505 if (auto *CY = dyn_cast<ConstantInt>(Y))
2506 if (CY->isOne())
2507 return X;
2508 VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2509 if (XVTy && !isa<VectorType>(Y->getType()))
2510 Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2511 return B.CreateMul(X, Y);
2512 };
2513
2514 switch (ID.getKind()) {
2516 assert(!isa<VectorType>(Index->getType()) &&
2517 "Vector indices not supported for integer inductions yet");
2518 assert(Index->getType() == StartValue->getType() &&
2519 "Index type does not match StartValue type");
2520 if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2521 return B.CreateSub(StartValue, Index);
2522 auto *Offset = CreateMul(Index, Step);
2523 return CreateAdd(StartValue, Offset);
2524 }
2526 assert(isa<Constant>(Step) &&
2527 "Expected constant step for pointer induction");
2528 return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2529 }
2531 assert(!isa<VectorType>(Index->getType()) &&
2532 "Vector indices not supported for FP inductions yet");
2533 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2534 auto InductionBinOp = ID.getInductionBinOp();
2535 assert(InductionBinOp &&
2536 (InductionBinOp->getOpcode() == Instruction::FAdd ||
2537 InductionBinOp->getOpcode() == Instruction::FSub) &&
2538 "Original bin op should be defined for FP induction");
2539
2540 Value *MulExp = B.CreateFMul(Step, Index);
2541 return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2542 "induction");
2543 }
2545 return nullptr;
2546 }
2547 llvm_unreachable("invalid enum");
2548}
2549
2551 const VPIteration &Instance,
2552 VPTransformState &State) {
2553 Value *ScalarInst = State.get(Def, Instance);
2554 Value *VectorValue = State.get(Def, Instance.Part);
2555 VectorValue = Builder.CreateInsertElement(
2556 VectorValue, ScalarInst,
2557 Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2558 State.set(Def, VectorValue, Instance.Part);
2559}
2560
2561// Return whether we allow using masked interleave-groups (for dealing with
2562// strided loads/stores that reside in predicated blocks, or for dealing
2563// with gaps).
2565 // If an override option has been passed in for interleaved accesses, use it.
2568
2570}
2571
2572// Try to vectorize the interleave group that \p Instr belongs to.
2573//
2574// E.g. Translate following interleaved load group (factor = 3):
2575// for (i = 0; i < N; i+=3) {
2576// R = Pic[i]; // Member of index 0
2577// G = Pic[i+1]; // Member of index 1
2578// B = Pic[i+2]; // Member of index 2
2579// ... // do something to R, G, B
2580// }
2581// To:
2582// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2583// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
2584// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
2585// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
2586//
2587// Or translate following interleaved store group (factor = 3):
2588// for (i = 0; i < N; i+=3) {
2589// ... do something to R, G, B
2590// Pic[i] = R; // Member of index 0
2591// Pic[i+1] = G; // Member of index 1
2592// Pic[i+2] = B; // Member of index 2
2593// }
2594// To:
2595// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2596// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2597// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2598// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2599// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2602 VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2603 VPValue *BlockInMask) {
2604 Instruction *Instr = Group->getInsertPos();
2605 const DataLayout &DL = Instr->getModule()->getDataLayout();
2606
2607 // Prepare for the vector type of the interleaved load/store.
2608 Type *ScalarTy = getLoadStoreType(Instr);
2609 unsigned InterleaveFactor = Group->getFactor();
2610 assert(!VF.isScalable() && "scalable vectors not yet supported.");
2611 auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2612
2613 // Prepare for the new pointers.
2614 SmallVector<Value *, 2> AddrParts;
2615 unsigned Index = Group->getIndex(Instr);
2616
2617 // TODO: extend the masked interleaved-group support to reversed access.
2618 assert((!BlockInMask || !Group->isReverse()) &&
2619 "Reversed masked interleave-group not supported.");
2620
2621 // If the group is reverse, adjust the index to refer to the last vector lane
2622 // instead of the first. We adjust the index from the first vector lane,
2623 // rather than directly getting the pointer for lane VF - 1, because the
2624 // pointer operand of the interleaved access is supposed to be uniform. For
2625 // uniform instructions, we're only required to generate a value for the
2626 // first vector lane in each unroll iteration.
2627 if (Group->isReverse())
2628 Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2629
2630 for (unsigned Part = 0; Part < UF; Part++) {
2631 Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2632 State.setDebugLocFromInst(AddrPart);
2633
2634 // Notice current instruction could be any index. Need to adjust the address
2635 // to the member of index 0.
2636 //
2637 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2638 // b = A[i]; // Member of index 0
2639 // Current pointer is pointed to A[i+1], adjust it to A[i].
2640 //
2641 // E.g. A[i+1] = a; // Member of index 1
2642 // A[i] = b; // Member of index 0
2643 // A[i+2] = c; // Member of index 2 (Current instruction)
2644 // Current pointer is pointed to A[i+2], adjust it to A[i].
2645
2646 bool InBounds = false;
2647 if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2648 InBounds = gep->isInBounds();
2649 AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2650 cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2651
2652 // Cast to the vector pointer type.
2653 unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2654 Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2655 AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2656 }
2657
2658 State.setDebugLocFromInst(Instr);
2659 Value *PoisonVec = PoisonValue::get(VecTy);
2660
2661 Value *MaskForGaps = nullptr;
2663 MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2664 assert(MaskForGaps && "Mask for Gaps is required but it is null");
2665 }
2666
2667 // Vectorize the interleaved load group.
2668 if (isa<LoadInst>(Instr)) {
2669 // For each unroll part, create a wide load for the group.
2670 SmallVector<Value *, 2> NewLoads;
2671 for (unsigned Part = 0; Part < UF; Part++) {
2672 Instruction *NewLoad;
2673 if (BlockInMask || MaskForGaps) {
2675 "masked interleaved groups are not allowed.");
2676 Value *GroupMask = MaskForGaps;
2677 if (BlockInMask) {
2678 Value *BlockInMaskPart = State.get(BlockInMask, Part);
2679 Value *ShuffledMask = Builder.CreateShuffleVector(
2680 BlockInMaskPart,
2681 createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2682 "interleaved.mask");
2683 GroupMask = MaskForGaps
2684 ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2685 MaskForGaps)
2686 : ShuffledMask;
2687 }
2688 NewLoad =
2689 Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2690 GroupMask, PoisonVec, "wide.masked.vec");
2691 }
2692 else
2693 NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2694 Group->getAlign(), "wide.vec");
2695 Group->addMetadata(NewLoad);
2696 NewLoads.push_back(NewLoad);
2697 }
2698
2699 // For each member in the group, shuffle out the appropriate data from the
2700 // wide loads.
2701 unsigned J = 0;
2702 for (unsigned I = 0; I < InterleaveFactor; ++I) {
2703 Instruction *Member = Group->getMember(I);
2704
2705 // Skip the gaps in the group.
2706 if (!Member)
2707 continue;
2708
2709 auto StrideMask =
2710 createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2711 for (unsigned Part = 0; Part < UF; Part++) {
2712 Value *StridedVec = Builder.CreateShuffleVector(
2713 NewLoads[Part], StrideMask, "strided.vec");
2714
2715 // If this member has different type, cast the result type.
2716 if (Member->getType() != ScalarTy) {
2717 assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2718 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2719 StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2720 }
2721
2722 if (Group->isReverse())
2723 StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2724
2725 State.set(VPDefs[J], StridedVec, Part);
2726 }
2727 ++J;
2728 }
2729 return;
2730 }
2731
2732 // The sub vector type for current instruction.
2733 auto *SubVT = VectorType::get(ScalarTy, VF);
2734
2735 // Vectorize the interleaved store group.
2736 MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2737 assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2738 "masked interleaved groups are not allowed.");
2739 assert((!MaskForGaps || !VF.isScalable()) &&
2740 "masking gaps for scalable vectors is not yet supported.");
2741 for (unsigned Part = 0; Part < UF; Part++) {
2742 // Collect the stored vector from each member.
2743 SmallVector<Value *, 4> StoredVecs;
2744 unsigned StoredIdx = 0;
2745 for (unsigned i = 0; i < InterleaveFactor; i++) {
2746 assert((Group->getMember(i) || MaskForGaps) &&
2747 "Fail to get a member from an interleaved store group");
2748 Instruction *Member = Group->getMember(i);
2749
2750 // Skip the gaps in the group.
2751 if (!Member) {
2752 Value *Undef = PoisonValue::get(SubVT);
2753 StoredVecs.push_back(Undef);
2754 continue;
2755 }
2756
2757 Value *StoredVec = State.get(StoredValues[StoredIdx], Part);
2758 ++StoredIdx;
2759
2760 if (Group->isReverse())
2761 StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2762
2763 // If this member has different type, cast it to a unified type.
2764
2765 if (StoredVec->getType() != SubVT)
2766 StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2767
2768 StoredVecs.push_back(StoredVec);
2769 }
2770
2771 // Concatenate all vectors into a wide vector.
2772 Value *WideVec = concatenateVectors(Builder, StoredVecs);
2773
2774 // Interleave the elements in the wide vector.
2776 WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2777 "interleaved.vec");
2778
2779 Instruction *NewStoreInstr;
2780 if (BlockInMask || MaskForGaps) {
2781 Value *GroupMask = MaskForGaps;
2782 if (BlockInMask) {
2783 Value *BlockInMaskPart = State.get(BlockInMask, Part);
2784 Value *ShuffledMask = Builder.CreateShuffleVector(
2785 BlockInMaskPart,
2786 createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2787 "interleaved.mask");
2788 GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2789 ShuffledMask, MaskForGaps)
2790 : ShuffledMask;
2791 }
2792 NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2793 Group->getAlign(), GroupMask);
2794 } else
2795 NewStoreInstr =
2796 Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2797
2798 Group->addMetadata(NewStoreInstr);
2799 }
2800}
2801
2803 VPReplicateRecipe *RepRecipe,
2804 const VPIteration &Instance,
2805 bool IfPredicateInstr,
2806 VPTransformState &State) {
2807 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2808
2809 // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2810 // the first lane and part.
2811 if (isa<NoAliasScopeDeclInst>(Instr))
2812 if (!Instance.isFirstIteration())
2813 return;
2814
2815 // Does this instruction return a value ?
2816 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2817
2818 Instruction *Cloned = Instr->clone();
2819 if (!IsVoidRetTy)
2820 Cloned->setName(Instr->getName() + ".cloned");
2821
2822 // If the scalarized instruction contributes to the address computation of a
2823 // widen masked load/store which was in a basic block that needed predication
2824 // and is not predicated after vectorization, we can't propagate
2825 // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2826 // instruction could feed a poison value to the base address of the widen
2827 // load/store.
2828 if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2829 Cloned->dropPoisonGeneratingFlags();
2830
2831 if (Instr->getDebugLoc())
2832 State.setDebugLocFromInst(Instr);
2833
2834 // Replace the operands of the cloned instructions with their scalar
2835 // equivalents in the new loop.
2836 for (const auto &I : enumerate(RepRecipe->operands())) {
2837 auto InputInstance = Instance;
2838 VPValue *Operand = I.value();
2840 InputInstance.Lane = VPLane::getFirstLane();
2841 Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2842 }
2843 State.addNewMetadata(Cloned, Instr);
2844
2845 // Place the cloned scalar in the new loop.
2846 State.Builder.Insert(Cloned);
2847
2848 State.set(RepRecipe, Cloned, Instance);
2849
2850 // If we just cloned a new assumption, add it the assumption cache.
2851 if (auto *II = dyn_cast<AssumeInst>(Cloned))
2853
2854 // End if-block.
2855 if (IfPredicateInstr)
2856 PredicatedInstructions.push_back(Cloned);
2857}
2858
2860 if (TripCount)
2861 return TripCount;
2862
2863 assert(InsertBlock);
2864 IRBuilder<> Builder(InsertBlock->getTerminator());
2865 // Find the loop boundaries.
2866 Type *IdxTy = Legal->getWidestInductionType();
2867 assert(IdxTy && "No type for induction");
2868 const SCEV *ExitCount = createTripCountSCEV(IdxTy, PSE);
2869
2870 const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2871
2872 // Expand the trip count and place the new instructions in the preheader.
2873 // Notice that the pre-header does not change, only the loop body.
2874 SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2875
2876 // Count holds the overall loop count (N).
2877 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2878 InsertBlock->getTerminator());
2879
2880 if (TripCount->getType()->isPointerTy())
2881 TripCount =
2882 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2883 InsertBlock->getTerminator());
2884
2885 return TripCount;
2886}
2887
2888Value *
2890 if (VectorTripCount)
2891 return VectorTripCount;
2892
2893 Value *TC = getOrCreateTripCount(InsertBlock);
2894 IRBuilder<> Builder(InsertBlock->getTerminator());
2895
2896 Type *Ty = TC->getType();
2897 // This is where we can make the step a runtime constant.
2898 Value *Step = createStepForVF(Builder, Ty, VF, UF);
2899
2900 // If the tail is to be folded by masking, round the number of iterations N
2901 // up to a multiple of Step instead of rounding down. This is done by first
2902 // adding Step-1 and then rounding down. Note that it's ok if this addition
2903 // overflows: the vector induction variable will eventually wrap to zero given
2904 // that it starts at zero and its Step is a power of two; the loop will then
2905 // exit, with the last early-exit vector comparison also producing all-true.
2906 // For scalable vectors the VF is not guaranteed to be a power of 2, but this
2907 // is accounted for in emitIterationCountCheck that adds an overflow check.
2908 if (Cost->foldTailByMasking()) {
2910 "VF*UF must be a power of 2 when folding tail by masking");
2911 Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2912 TC = Builder.CreateAdd(
2913 TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2914 }
2915
2916 // Now we need to generate the expression for the part of the loop that the
2917 // vectorized body will execute. This is equal to N - (N % Step) if scalar
2918 // iterations are not required for correctness, or N - Step, otherwise. Step
2919 // is equal to the vectorization factor (number of SIMD elements) times the
2920 // unroll factor (number of SIMD instructions).
2921 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2922
2923 // There are cases where we *must* run at least one iteration in the remainder
2924 // loop. See the cost model for when this can happen. If the step evenly
2925 // divides the trip count, we set the remainder to be equal to the step. If
2926 // the step does not evenly divide the trip count, no adjustment is necessary
2927 // since there will already be scalar iterations. Note that the minimum
2928 // iterations check ensures that N >= Step.
2930 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2931 R = Builder.CreateSelect(IsZero, Step, R);
2932 }
2933
2934 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2935
2936 return VectorTripCount;
2937}
2938
2940 const DataLayout &DL) {
2941 // Verify that V is a vector type with same number of elements as DstVTy.
2942 auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2943 unsigned VF = DstFVTy->getNumElements();
2944 auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2945 assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2946 Type *SrcElemTy = SrcVecTy->getElementType();
2947 Type *DstElemTy = DstFVTy->getElementType();
2948 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2949 "Vector elements must have same size");
2950
2951 // Do a direct cast if element types are castable.
2952 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2953 return Builder.CreateBitOrPointerCast(V, DstFVTy);
2954 }
2955 // V cannot be directly casted to desired vector type.
2956 // May happen when V is a floating point vector but DstVTy is a vector of
2957 // pointers or vice-versa. Handle this using a two-step bitcast using an
2958 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2959 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2960 "Only one type should be a pointer type");
2961 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2962 "Only one type should be a floating point type");
2963 Type *IntTy =
2964 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2965 auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2966 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2967 return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2968}
2969
2972 // Reuse existing vector loop preheader for TC checks.
2973 // Note that new preheader block is generated for vector loop.
2974 BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2975 IRBuilder<> Builder(TCCheckBlock->getTerminator());
2976
2977 // Generate code to check if the loop's trip count is less than VF * UF, or
2978 // equal to it in case a scalar epilogue is required; this implies that the
2979 // vector trip count is zero. This check also covers the case where adding one
2980 // to the backedge-taken count overflowed leading to an incorrect trip count
2981 // of zero. In this case we will also jump to the scalar loop.
2984
2985 // If tail is to be folded, vector loop takes care of all iterations.
2986 Type *CountTy = Count->getType();
2987 Value *CheckMinIters = Builder.getFalse();
2988 auto CreateStep = [&]() -> Value * {
2989 // Create step with max(MinProTripCount, UF * VF).
2991 return createStepForVF(Builder, CountTy, VF, UF);
2992
2993 Value *MinProfTC =
2995 if (!VF.isScalable())
2996 return MinProfTC;
2998 Intrinsic::umax, MinProfTC, createStepForVF(Builder, CountTy, VF, UF));
2999 };
3000
3001 if (!Cost->foldTailByMasking())
3002 CheckMinIters =
3003 Builder.CreateICmp(P, Count, CreateStep(), "min.iters.check");
3004 else if (VF.isScalable()) {
3005 // vscale is not necessarily a power-of-2, which means we cannot guarantee
3006 // an overflow to zero when updating induction variables and so an
3007 // additional overflow check is required before entering the vector loop.
3008
3009 // Get the maximum unsigned value for the type.
3010 Value *MaxUIntTripCount =
3011 ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
3012 Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
3013
3014 // Don't execute the vector loop if (UMax - n) < (VF * UF).
3015 CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, CreateStep());
3016 }
3017
3018 // Create new preheader for vector loop.
3020 SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3021 "vector.ph");
3022
3023 assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3024 DT->getNode(Bypass)->getIDom()) &&
3025 "TC check is expected to dominate Bypass");
3026
3027 // Update dominator for Bypass & LoopExit (if needed).
3028 DT->changeImmediateDominator(Bypass, TCCheckBlock);
3030 // If there is an epilogue which must run, there's no edge from the
3031 // middle block to exit blocks and thus no need to update the immediate
3032 // dominator of the exit blocks.
3034
3036 TCCheckBlock->getTerminator(),
3037 BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3038 LoopBypassBlocks.push_back(TCCheckBlock);
3039}
3040
3042 BasicBlock *const SCEVCheckBlock =
3043 RTChecks.emitSCEVChecks(Bypass, LoopVectorPreHeader, LoopExitBlock);
3044 if (!SCEVCheckBlock)
3045 return nullptr;
3046
3047 assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3050 "Cannot SCEV check stride or overflow when optimizing for size");
3051
3052
3053 // Update dominator only if this is first RT check.
3054 if (LoopBypassBlocks.empty()) {
3055 DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3057 // If there is an epilogue which must run, there's no edge from the
3058 // middle block to exit blocks and thus no need to update the immediate
3059 // dominator of the exit blocks.
3060 DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3061 }
3062
3063 LoopBypassBlocks.push_back(SCEVCheckBlock);
3064 AddedSafetyChecks = true;
3065 return SCEVCheckBlock;
3066}
3067
3069 // VPlan-native path does not do any analysis for runtime checks currently.
3071 return nullptr;
3072
3073 BasicBlock *const MemCheckBlock =
3074 RTChecks.emitMemRuntimeChecks(Bypass, LoopVectorPreHeader);
3075
3076 // Check if we generated code that checks in runtime if arrays overlap. We put
3077 // the checks into a separate block to make the more common case of few
3078 // elements faster.
3079 if (!MemCheckBlock)
3080 return nullptr;
3081
3082 if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3084 "Cannot emit memory checks when optimizing for size, unless forced "
3085 "to vectorize.");
3086 ORE->emit([&]() {
3087 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3090 << "Code-size may be reduced by not forcing "
3091 "vectorization, or by source-code modifications "
3092 "eliminating the need for runtime checks "
3093 "(e.g., adding 'restrict').";
3094 });
3095 }
3096
3097 LoopBypassBlocks.push_back(MemCheckBlock);
3098
3099 AddedSafetyChecks = true;
3100
3101 return MemCheckBlock;
3102}
3103
3107 assert(LoopVectorPreHeader && "Invalid loop structure");
3108 LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3110 "multiple exit loop without required epilogue?");
3111
3114 LI, nullptr, Twine(Prefix) + "middle.block");
3117 nullptr, Twine(Prefix) + "scalar.ph");
3118
3119 auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3120
3121 // Set up the middle block terminator. Two cases:
3122 // 1) If we know that we must execute the scalar epilogue, emit an
3123 // unconditional branch.
3124 // 2) Otherwise, we must have a single unique exit block (due to how we
3125 // implement the multiple exit case). In this case, set up a conditional
3126 // branch from the middle block to the loop scalar preheader, and the
3127 // exit block. completeLoopSkeleton will update the condition to use an
3128 // iteration check, if required to decide whether to execute the remainder.
3132 Builder.getTrue());
3133 BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3135
3136 // Update dominator for loop exit. During skeleton creation, only the vector
3137 // pre-header and the middle block are created. The vector loop is entirely
3138 // created during VPlan exection.
3140 // If there is an epilogue which must run, there's no edge from the
3141 // middle block to exit blocks and thus no need to update the immediate
3142 // dominator of the exit blocks.
3144}
3145
3147 PHINode *OrigPhi, const InductionDescriptor &II,
3148 ArrayRef<BasicBlock *> BypassBlocks,
3149 std::pair<BasicBlock *, Value *> AdditionalBypass) {
3151 assert(VectorTripCount && "Expected valid arguments");
3152
3153 Instruction *OldInduction = Legal->getPrimaryInduction();
3154 Value *&EndValue = IVEndValues[OrigPhi];
3155 Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3156 if (OrigPhi == OldInduction) {
3157 // We know what the end value is.
3158 EndValue = VectorTripCount;
3159 } else {
3161
3162 // Fast-math-flags propagate from the original induction instruction.
3163 if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3164 B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3165
3166 Value *Step =
3167 CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3168 EndValue =
3170 EndValue->setName("ind.end");
3171
3172 // Compute the end value for the additional bypass (if applicable).
3173 if (AdditionalBypass.first) {
3174 B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3175 Value *Step =
3176 CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3177 EndValueFromAdditionalBypass = emitTransformedIndex(
3178 B, AdditionalBypass.second, II.getStartValue(), Step, II);
3179 EndValueFromAdditionalBypass->setName("ind.end");
3180 }
3181 }
3182
3183 // Create phi nodes to merge from the backedge-taken check block.
3184 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3186 // Copy original phi DL over to the new one.
3187 BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3188
3189 // The new PHI merges the original incoming value, in case of a bypass,
3190 // or the value at the end of the vectorized loop.
3191 BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3192
3193 // Fix the scalar body counter (PHI node).
3194 // The old induction's phi node in the scalar body needs the truncated
3195 // value.
3196 for (BasicBlock *BB : BypassBlocks)
3197 BCResumeVal->addIncoming(II.getStartValue(), BB);
3198
3199 if (AdditionalBypass.first)
3200 BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3201 EndValueFromAdditionalBypass);
3202 return BCResumeVal;
3203}
3204
3206 std::pair<BasicBlock *, Value *> AdditionalBypass) {
3207 assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3208 (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3209 "Inconsistent information about additional bypass.");
3210 // We are going to resume the execution of the scalar loop.
3211 // Go over all of the induction variables that we found and fix the
3212 // PHIs that are left in the scalar version of the loop.
3213 // The starting values of PHI nodes depend on the counter of the last
3214 // iteration in the vectorized loop.
3215 // If we come from a bypass edge then we need to start from the original
3216 // start value.
3217 for (const auto &InductionEntry : Legal->getInductionVars()) {
3218 PHINode *OrigPhi = InductionEntry.first;
3219 const InductionDescriptor &II = InductionEntry.second;
3220 PHINode *BCResumeVal = createInductionResumeValue(
3221 OrigPhi, II, LoopBypassBlocks, AdditionalBypass);
3222 OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3223 }
3224}
3225
3227 // The trip counts should be cached by now.
3230
3231 auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3232
3233 // Add a check in the middle block to see if we have completed
3234 // all of the iterations in the first vector loop. Three cases:
3235 // 1) If we require a scalar epilogue, there is no conditional branch as
3236 // we unconditionally branch to the scalar preheader. Do nothing.
3237 // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3238 // Thus if tail is to be folded, we know we don't need to run the
3239 // remainder and we can use the previous value for the condition (true).
3240 // 3) Otherwise, construct a runtime check.
3242 Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3243 Count, VectorTripCount, "cmp.n",
3245
3246 // Here we use the same DebugLoc as the scalar loop latch terminator instead
3247 // of the corresponding compare because they may have ended up with
3248 // different line numbers and we want to avoid awkward line stepping while
3249 // debugging. Eg. if the compare has got a line number inside the loop.
3250 CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3251 cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3252 }
3253
3254#ifdef EXPENSIVE_CHECKS
3255 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3256#endif
3257
3258 return LoopVectorPreHeader;
3259}
3260
3261std::pair<BasicBlock *, Value *>
3263 /*
3264 In this function we generate a new loop. The new loop will contain
3265 the vectorized instructions while the old loop will continue to run the
3266 scalar remainder.
3267
3268 [ ] <-- loop iteration number check.
3269 / |
3270 / v
3271 | [ ] <-- vector loop bypass (may consist of multiple blocks).
3272 | / |
3273 | / v
3274 || [ ] <-- vector pre header.
3275 |/ |
3276 | v
3277 | [ ] \
3278 | [ ]_| <-- vector loop (created during VPlan execution).
3279 | |
3280 | v
3281 \ -[ ] <--- middle-block.
3282 \/ |
3283 /\ v
3284 | ->[ ] <--- new preheader.
3285 | |
3286 (opt) v <-- edge from middle to exit iff epilogue is not required.
3287 | [ ] \
3288 | [ ]_| <-- old scalar loop to handle remainder (scalar epilogue).
3289 \ |
3290 \ v
3291 >[ ] <-- exit block(s).
3292 ...
3293 */
3294
3295 // Create an empty vector loop, and prepare basic blocks for the runtime
3296 // checks.
3298
3299 // Now, compare the new count to zero. If it is zero skip the vector loop and
3300 // jump to the scalar loop. This check also covers the case where the
3301 // backedge-taken count is uint##_max: adding one to it will overflow leading
3302 // to an incorrect trip count of zero. In this (rare) case we will also jump
3303 // to the scalar loop.
3305
3306 // Generate the code to check any assumptions that we've made for SCEV
3307 // expressions.
3309
3310 // Generate the code that checks in runtime if arrays overlap. We put the
3311 // checks into a separate block to make the more common case of few elements
3312 // faster.
3314
3315 // Emit phis for the new starting index of the scalar loop.
3317
3318 return {completeLoopSkeleton(), nullptr};
3319}
3320
3321// Fix up external users of the induction variable. At this point, we are
3322// in LCSSA form, with all external PHIs that use the IV having one input value,
3323// coming from the remainder loop. We need those PHIs to also have a correct
3324// value for the IV when arriving directly from the middle block.
3326 const InductionDescriptor &II,
3327 Value *VectorTripCount, Value *EndValue,
3328 BasicBlock *MiddleBlock,
3329 BasicBlock *VectorHeader, VPlan &Plan) {
3330 // There are two kinds of external IV usages - those that use the value
3331 // computed in the last iteration (the PHI) and those that use the penultimate
3332 // value (the value that feeds into the phi from the loop latch).
3333 // We allow both, but they, obviously, have different values.
3334
3335 assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3336
3337 DenseMap<Value *, Value *> MissingVals;
3338
3339 // An external user of the last iteration's value should see the value that
3340 // the remainder loop uses to initialize its own IV.
3342 for (User *U : PostInc->users()) {
3343 Instruction *UI = cast<Instruction>(U);
3344 if (!OrigLoop->contains(UI)) {
3345 assert(isa<PHINode>(UI) && "Expected LCSSA form");
3346 MissingVals[UI] = EndValue;
3347 }
3348 }
3349
3350 // An external user of the penultimate value need to see EndValue - Step.
3351 // The simplest way to get this is to recompute it from the constituent SCEVs,
3352 // that is Start + (Step * (CRD - 1)).
3353 for (User *U : OrigPhi->users()) {
3354 auto *UI = cast<Instruction>(U);
3355 if (!OrigLoop->contains(UI)) {
3356 assert(isa<PHINode>(UI) && "Expected LCSSA form");
3357
3358 IRBuilder<> B(MiddleBlock->getTerminator());
3359
3360 // Fast-math-flags propagate from the original induction instruction.
3361 if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3362 B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3363
3364 Value *CountMinusOne = B.CreateSub(
3366 CountMinusOne->setName("cmo");
3367 Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3368 VectorHeader->getTerminator());
3369 Value *Escape =
3370 emitTransformedIndex(B, CountMinusOne, II.getStartValue(), Step, II);
3371 Escape->setName("ind.escape");
3372 MissingVals[UI] = Escape;
3373 }
3374 }
3375
3376 for (auto &I : MissingVals) {
3377 PHINode *PHI = cast<PHINode>(I.first);
3378 // One corner case we have to handle is two IVs "chasing" each-other,
3379 // that is %IV2 = phi [...], [ %IV1, %latch ]
3380 // In this case, if IV1 has an external use, we need to avoid adding both
3381 // "last value of IV1" and "penultimate value of IV2". So, verify that we
3382 // don't already have an incoming value for the middle block.
3383 if (PHI->getBasicBlockIndex(MiddleBlock) == -1) {
3384 PHI->addIncoming(I.second, MiddleBlock);
3385 Plan.removeLiveOut(PHI);
3386 }
3387 }
3388}
3389
3390namespace {
3391
3392struct CSEDenseMapInfo {
3393 static bool canHandle(const Instruction *I) {
3394 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3395 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3396 }
3397
3398 static inline Instruction *getEmptyKey() {
3400 }
3401
3402 static inline Instruction *getTombstoneKey() {
3404 }
3405
3406 static unsigned getHashValue(const Instruction *I) {
3407 assert(canHandle(I) && "Unknown instruction!");
3408 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3409 I->value_op_end()));
3410 }
3411
3412 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3413 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3414 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3415 return LHS == RHS;
3416 return LHS->isIdenticalTo(RHS);
3417 }
3418};
3419
3420} // end anonymous namespace
3421
3422///Perform cse of induction variable instructions.
3423static void cse(BasicBlock *BB) {
3424 // Perform simple cse.
3426 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3427 if (!CSEDenseMapInfo::canHandle(&In))
3428 continue;
3429
3430 // Check if we can replace this instruction with any of the
3431 // visited instructions.
3432 if (Instruction *V = CSEMap.lookup(&In)) {
3433 In.replaceAllUsesWith(V);
3434 In.eraseFromParent();
3435 continue;
3436 }
3437
3438 CSEMap[&In] = &In;
3439 }
3440}
3441
3444 bool &NeedToScalarize) const {
3445 Function *F = CI->getCalledFunction();
3446 Type *ScalarRetTy = CI->getType();
3447 SmallVector<Type *, 4> Tys, ScalarTys;
3448 for (auto &ArgOp : CI->args())
3449 ScalarTys.push_back(ArgOp->getType());
3450
3451 // Estimate cost of scalarized vector call. The source operands are assumed
3452 // to be vectors, so we need to extract individual elements from there,
3453 // execute VF scalar calls, and then gather the result into the vector return
3454 // value.
3456 InstructionCost ScalarCallCost =
3457 TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, CostKind);
3458 if (VF.isScalar())
3459 return ScalarCallCost;
3460
3461 // Compute corresponding vector type for return value and arguments.
3462 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3463 for (Type *ScalarTy : ScalarTys)
3464 Tys.push_back(ToVectorTy(ScalarTy, VF));
3465
3466 // Compute costs of unpacking argument values for the scalar calls and
3467 // packing the return values to a vector.
3468 InstructionCost ScalarizationCost =
3469 getScalarizationOverhead(CI, VF, CostKind);
3470
3472 ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3473
3474 // If we can't emit a vector call for this function, then the currently found
3475 // cost is the cost we need to return.
3476 NeedToScalarize = true;
3477 VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3478 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3479
3480 if (!TLI || CI->isNoBuiltin() || !VecFunc)
3481 return Cost;
3482
3483 // If the corresponding vector cost is cheaper, return its cost.
3484 InstructionCost VectorCallCost =
3485 TTI.getCallInstrCost(nullptr, RetTy, Tys, CostKind);
3486 if (VectorCallCost < Cost) {
3487 NeedToScalarize = false;
3488 Cost = VectorCallCost;
3489 }
3490 return Cost;
3491}
3492
3494 if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3495 return Elt;
3496 return VectorType::get(Elt, VF);
3497}
3498
3501 ElementCount VF) const {
3503 assert(ID && "Expected intrinsic call!");
3505 FastMathFlags FMF;
3506 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3507 FMF = FPMO->getFastMathFlags();
3508
3511 SmallVector<Type *> ParamTys;
3512 std::transform(FTy->param_begin(), FTy->param_end(),
3513 std::back_inserter(ParamTys),
3514 [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3515
3516 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3517 dyn_cast<IntrinsicInst>(CI));
3518 return TTI.getIntrinsicInstrCost(CostAttrs,
3520}
3521
3523 auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3524 auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3525 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3526}
3527
3529 auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3530 auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3531 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3532}
3533
3535 // For every instruction `I` in MinBWs, truncate the operands, create a
3536 // truncated version of `I` and reextend its result. InstCombine runs
3537 // later and will remove any ext/trunc pairs.
3539 for (const auto &KV : Cost->getMinimalBitwidths()) {
3540 // If the value wasn't vectorized, we must maintain the original scalar
3541 // type. The absence of the value from State indicates that it
3542 // wasn't vectorized.
3543 // FIXME: Should not rely on getVPValue at this point.
3544 VPValue *Def = State.Plan->getVPValue(KV.first, true);
3545 if (!State.hasAnyVectorValue(Def))
3546 continue;
3547 for (unsigned Part = 0; Part < UF; ++Part) {
3548 Value *I = State.get(Def, Part);
3549 if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3550 continue;
3551 Type *OriginalTy = I->getType();
3552 Type *ScalarTruncatedTy =
3553 IntegerType::get(OriginalTy->getContext(), KV.second);
3554 auto *TruncatedTy = VectorType::get(
3555 ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3556 if (TruncatedTy == OriginalTy)
3557 continue;
3558
3559 IRBuilder<> B(cast<Instruction>(I));
3560 auto ShrinkOperand = [&](Value *V) -> Value * {
3561 if (auto *ZI = dyn_cast<ZExtInst>(V))
3562 if (ZI->getSrcTy() == TruncatedTy)
3563 return ZI->getOperand(0);
3564 return B.CreateZExtOrTrunc(V, TruncatedTy);
3565 };
3566
3567 // The actual instruction modification depends on the instruction type,
3568 // unfortunately.
3569 Value *NewI = nullptr;
3570 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3571 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3572 ShrinkOperand(BO->getOperand(1)));
3573
3574 // Any wrapping introduced by shrinking this operation shouldn't be
3575 // considered undefined behavior. So, we can't unconditionally copy
3576 // arithmetic wrapping flags to NewI.
3577 cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3578 } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3579 NewI =
3580 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3581 ShrinkOperand(CI->getOperand(1)));
3582 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3583 NewI = B.CreateSelect(SI->getCondition(),
3584 ShrinkOperand(SI->getTrueValue()),
3585 ShrinkOperand(SI->getFalseValue()));
3586 } else if (auto *CI = dyn_cast<CastInst>(I)) {
3587 switch (CI->getOpcode()) {
3588 default:
3589 llvm_unreachable("Unhandled cast!");
3590 case Instruction::Trunc:
3591 NewI = ShrinkOperand(CI->getOperand(0));
3592 break;
3593 case Instruction::SExt:
3594 NewI = B.CreateSExtOrTrunc(
3595 CI->getOperand(0),
3596 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3597 break;
3598 case Instruction::ZExt:
3599 NewI = B.CreateZExtOrTrunc(
3600 CI->getOperand(0),
3601 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3602 break;
3603 }
3604 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3605 auto Elements0 =
3606 cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3607 auto *O0 = B.CreateZExtOrTrunc(
3608 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3609 auto Elements1 =
3610 cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3611 auto *O1 = B.CreateZExtOrTrunc(
3612 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3613
3614 NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3615 } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3616 // Don't do anything with the operands, just extend the result.
3617 continue;
3618 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3619 auto Elements =
3620 cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3621 auto *O0 = B.CreateZExtOrTrunc(
3622 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3623 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3624 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3625 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3626 auto Elements =
3627 cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3628 auto *O0 = B.CreateZExtOrTrunc(
3629 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3630 NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3631 } else {
3632 // If we don't know what to do, be conservative and don't do anything.
3633 continue;
3634 }
3635
3636 // Lastly, extend the result.
3637 NewI->takeName(cast<Instruction>(I));
3638 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3639 I->replaceAllUsesWith(Res);
3640 cast<Instruction>(I)->eraseFromParent();
3641 Erased.insert(I);
3642 State.reset(Def, Res, Part);
3643 }
3644 }
3645
3646 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3647 for (const auto &KV : Cost->getMinimalBitwidths()) {
3648 // If the value wasn't vectorized, we must maintain the original scalar
3649 // type. The absence of the value from State indicates that it
3650 // wasn't vectorized.
3651 // FIXME: Should not rely on getVPValue at this point.
3652 VPValue *Def = State.Plan->getVPValue(KV.first, true);
3653 if (!State.hasAnyVectorValue(Def))
3654 continue;
3655 for (unsigned Part = 0; Part < UF; ++Part) {
3656 Value *I = State.get(Def, Part);
3657 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3658 if (Inst && Inst->use_empty()) {
3659 Value *NewI = Inst->getOperand(0);
3660 Inst->eraseFromParent();
3661 State.reset(Def, NewI, Part);
3662 }
3663 }
3664 }
3665}
3666
3668 VPlan &Plan) {
3669 // Insert truncates and extends for any truncated instructions as hints to
3670 // InstCombine.
3671 if (VF.isVector())
3673
3674 // Fix widened non-induction PHIs by setting up the PHI operands.
3676 fixNonInductionPHIs(Plan, State);
3677
3678 // At this point every instruction in the original loop is widened to a
3679 // vector form. Now we need to fix the recurrences in the loop. These PHI
3680 // nodes are currently empty because we did not want to introduce cycles.
3681 // This is the second stage of vectorizing recurrences.
3682 fixCrossIterationPHIs(State);
3683
3684 // Forget the original basic block.
3686
3688 Loop *VectorLoop = LI->getLoopFor(State.CFG.VPBB2IRBB[LatchVPBB]);
3690 // No edge from the middle block to the unique exit block has been inserted
3691 // and there is nothing to fix from vector loop; phis should have incoming
3692 // from scalar loop only.
3693 Plan.clearLiveOuts();
3694 } else {
3695 // If we inserted an edge from the middle block to the unique exit block,
3696 // update uses outside the loop (phis) to account for the newly inserted
3697 // edge.
3698
3699 // Fix-up external users of the induction variables.
3700 for (const auto &Entry : Legal->getInductionVars())
3701 fixupIVUsers(Entry.first, Entry.second,
3703 IVEndValues[Entry.first], LoopMiddleBlock,
3704 VectorLoop->getHeader(), Plan);
3705 }
3706
3707 // Fix LCSSA phis not already fixed earlier. Extracts may need to be generated
3708 // in the exit block, so update the builder.
3710 for (const auto &KV : Plan.getLiveOuts())
3711 KV.second->fixPhi(Plan, State);
3712
3714 sinkScalarOperands(&*PI);
3715
3716 // Remove redundant induction instructions.
3717 cse(VectorLoop->getHeader());
3718
3719 // Set/update profile weights for the vector and remainder loops as original
3720 // loop iterations are now distributed among them. Note that original loop
3721 // represented by LoopScalarBody becomes remainder loop after vectorization.
3722 //
3723 // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3724 // end up getting slightly roughened result but that should be OK since
3725 // profile is not inherently precise anyway. Note also possible bypass of
3726 // vector code caused by legality checks is ignored, assigning all the weight
3727 // to the vector loop, optimistically.
3728 //
3729 // For scalable vectorization we can't know at compile time how many iterations
3730 // of the loop are handled in one vector iteration, so instead assume a pessimistic
3731 // vscale of '1'.
3734 VF.getKnownMinValue() * UF);
3735}
3736
3738 // In order to support recurrences we need to be able to vectorize Phi nodes.
3739 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3740 // stage #2: We now need to fix the recurrences by adding incoming edges to
3741 // the currently empty PHI nodes. At this point every instruction in the
3742 // original loop is widened to a vector form so we can use them to construct
3743 // the incoming edges.
3744 VPBasicBlock *Header =
3746 for (VPRecipeBase &R : Header->phis()) {
3747 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3748 fixReduction(ReductionPhi, State);
3749 else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3750 fixFixedOrderRecurrence(FOR, State);
3751 }
3752}
3753
3756 // This is the second phase of vectorizing first-order recurrences. An
3757 // overview of the transformation is described below. Suppose we have the
3758 // following loop.
3759 //
3760 // for (int i = 0; i < n; ++i)
3761 // b[i] = a[i] - a[i - 1];
3762 //
3763 // There is a first-order recurrence on "a". For this loop, the shorthand
3764 // scalar IR looks like:
3765 //
3766 // scalar.ph:
3767 // s_init = a[-1]
3768 // br scalar.body
3769 //
3770 // scalar.body:
3771 // i = phi [0, scalar.ph], [i+1, scalar.body]
3772 // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3773 // s2 = a[i]
3774 // b[i] = s2 - s1
3775 // br cond, scalar.body, ...
3776 //
3777 // In this example, s1 is a recurrence because it's value depends on the
3778 // previous iteration. In the first phase of vectorization, we created a
3779 // vector phi v1 for s1. We now complete the vectorization and produce the
3780 // shorthand vector IR shown below (for VF = 4, UF = 1).
3781 //
3782 // vector.ph:
3783 // v_init = vector(..., ..., ..., a[-1])
3784 // br vector.body
3785 //
3786 // vector.body
3787 // i = phi [0, vector.ph], [i+4, vector.body]
3788 // v1 = phi [v_init, vector.ph], [v2, vector.body]
3789 // v2 = a[i, i+1, i+2, i+3];
3790 // v3 = vector(v1(3), v2(0, 1, 2))
3791 // b[i, i+1, i+2, i+3] = v2 - v3
3792 // br cond, vector.body, middle.block
3793 //
3794 // middle.block:
3795 // x = v2(3)
3796 // br scalar.ph
3797 //
3798 // scalar.ph:
3799 // s_init = phi [x, middle.block], [a[-1], otherwise]
3800 // br scalar.body
3801 //
3802 // After execution completes the vector loop, we extract the next value of
3803 // the recurrence (x) to use as the initial value in the scalar loop.
3804
3805 // Extract the last vector element in the middle block. This will be the
3806 // initial value for the recurrence when jumping to the scalar loop.
3807 VPValue *PreviousDef = PhiR->getBackedgeValue();
3808 Value *Incoming = State.get(PreviousDef, UF - 1);
3809 auto *ExtractForScalar = Incoming;
3810 auto *IdxTy = Builder.getInt32Ty();
3811 if (VF.isVector()) {
3812 auto *One = ConstantInt::get(IdxTy, 1);
3814 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3815 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3816 ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3817 "vector.recur.extract");
3818 }
3819 // Extract the second last element in the middle block if the
3820 // Phi is used outside the loop. We need to extract the phi itself
3821 // and not the last element (the phi update in the current iteration). This
3822 // will be the value when jumping to the exit block from the LoopMiddleBlock,
3823 // when the scalar loop is not run at all.
3824 Value *ExtractForPhiUsedOutsideLoop = nullptr;
3825 if (VF.isVector()) {
3826 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3827 auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3828 ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3829 Incoming, Idx, "vector.recur.extract.for.phi");
3830 } else if (UF > 1)
3831 // When loop is unrolled without vectorizing, initialize
3832 // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3833 // of `Incoming`. This is analogous to the vectorized case above: extracting
3834 // the second last element when VF > 1.
3835 ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3836
3837 // Fix the initial value of the original recurrence in the scalar loop.
3839 PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3840 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3841 auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3842 for (auto *BB : predecessors(LoopScalarPreHeader)) {
3843 auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3844 Start->addIncoming(Incoming, BB);
3845 }
3846
3848 Phi->setName("scalar.recur");
3849
3850 // Finally, fix users of the recurrence outside the loop. The users will need
3851 // either the last value of the scalar recurrence or the last value of the
3852 // vector recurrence we extracted in the middle block. Since the loop is in
3853 // LCSSA form, we just need to find all the phi nodes for the original scalar
3854 // recurrence in the exit block, and then add an edge for the middle block.
3855 // Note that LCSSA does not imply single entry when the original scalar loop
3856 // had multiple exiting edges (as we always run the last iteration in the
3857 // scalar epilogue); in that case, there is no edge from middle to exit and
3858 // and thus no phis which needed updated.
3860 for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3861 if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi)) {
3862 LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3863 State.Plan->removeLiveOut(&LCSSAPhi);
3864 }
3865}
3866
3868 VPTransformState &State) {
3869 PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3870 // Get it's reduction variable descriptor.
3871 assert(Legal->isReductionVariable(OrigPhi) &&
3872 "Unable to find the reduction variable");
3873 const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3874
3875 RecurKind RK = RdxDesc.getRecurrenceKind();
3876 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3877 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3878 State.setDebugLocFromInst(ReductionStartValue);
3879
3880 VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3881 // This is the vector-clone of the value that leaves the loop.
3882 Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3883
3884 // Wrap flags are in general invalid after vectorization, clear them.
3885 clearReductionWrapFlags(PhiR, State);
3886
3887 // Before each round, move the insertion point right between
3888 // the PHIs and the values we are going to write.
3889 // This allows us to write both PHINodes and the extractelement
3890 // instructions.
3892
3893 State.setDebugLocFromInst(LoopExitInst);
3894
3895 Type *PhiTy = OrigPhi->getType();
3896
3897 VPBasicBlock *LatchVPBB =
3899 BasicBlock *VectorLoopLatch = State.CFG.VPBB2IRBB[LatchVPBB];
3900 // If tail is folded by masking, the vector value to leave the loop should be
3901 // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3902 // instead of the former. For an inloop reduction the reduction will already
3903 // be predicated, and does not need to be handled here.
3904 if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3905 for (unsigned Part = 0; Part < UF; ++Part) {
3906 Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3907 SelectInst *Sel = nullptr;
3908 for (User *U : VecLoopExitInst->users()) {
3909 if (isa<SelectInst>(U)) {
3910 assert(!Sel && "Reduction exit feeding two selects");
3911 Sel = cast<SelectInst>(U);
3912 } else
3913 assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3914 }
3915 assert(Sel && "Reduction exit feeds no select");
3916 State.reset(LoopExitInstDef, Sel, Part);
3917
3918 if (isa<FPMathOperator>(Sel))
3919 Sel->setFastMathFlags(RdxDesc.getFastMathFlags());
3920
3921 // If the target can create a predicated operator for the reduction at no
3922 // extra cost in the loop (for example a predicated vadd), it can be
3923 // cheaper for the select to remain in the loop than be sunk out of it,
3924 // and so use the select value for the phi instead of the old
3925 // LoopExitValue.
3928 RdxDesc.getOpcode(), PhiTy,
3930 auto *VecRdxPhi =
3931 cast<PHINode>(State.get(PhiR, Part));
3932 VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3933 }
3934 }
3935 }
3936
3937 // If the vector reduction can be performed in a smaller type, we truncate
3938 // then extend the loop exit value to enable InstCombine to evaluate the
3939 // entire expression in the smaller type.
3940 if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3941 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3942 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3943 Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3944 VectorParts RdxParts(UF);
3945 for (unsigned Part = 0; Part < UF; ++Part) {
3946 RdxParts[Part] = State.get(LoopExitInstDef, Part);
3947 Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3948 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3949 : Builder.CreateZExt(Trunc, VecTy);
3950 for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3951 if (U != Trunc) {
3952 U->replaceUsesOfWith(RdxParts[Part], Extnd);
3953 RdxParts[Part] = Extnd;
3954 }
3955 }
3957 for (unsigned Part = 0; Part < UF; ++Part) {
3958 RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3959 State.reset(LoopExitInstDef, RdxParts[Part], Part);
3960 }
3961 }
3962
3963 // Reduce all of the unrolled parts into a single vector.
3964 Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3965 unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3966
3967 // The middle block terminator has already been assigned a DebugLoc here (the
3968 // OrigLoop's single latch terminator). We want the whole middle block to
3969 // appear to execute on this line because: (a) it is all compiler generated,
3970 // (b) these instructions are always executed after evaluating the latch
3971 // conditional branch, and (c) other passes may add new predecessors which
3972 // terminate on this line. This is the easiest way to ensure we don't
3973 // accidentally cause an extra step back into the loop while debugging.
3975 if (PhiR->isOrdered())
3976 ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3977 else {
3978 // Floating-point operations should have some FMF to enable the reduction.
3981 for (unsigned Part = 1; Part < UF; ++Part) {
3982 Value *RdxPart = State.get(LoopExitInstDef, Part);
3983 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3984 ReducedPartRdx = Builder.CreateBinOp(
3985 (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3987 ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3988 ReducedPartRdx, RdxPart);
3989 else
3990 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
3991 }
3992 }
3993
3994 // Create the reduction after the loop. Note that inloop reductions create the
3995 // target reduction in the loop using a Reduction recipe.
3996 if (VF.isVector() && !PhiR->isInLoop()) {
3997 ReducedPartRdx =
3998 createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
3999 // If the reduction can be performed in a smaller type, we need to extend
4000 // the reduction to the wider type before we branch to the original loop.
4001 if (PhiTy != RdxDesc.getRecurrenceType())
4002 ReducedPartRdx = RdxDesc.isSigned()
4003 ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4004 : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4005 }
4006
4007 PHINode *ResumePhi =
4008 dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
4009
4010 // Create a phi node that merges control-flow from the backedge-taken check
4011 // block and the middle block.
4012 PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4014
4015 // If we are fixing reductions in the epilogue loop then we should already
4016 // have created a bc.merge.rdx Phi after the main vector body. Ensure that
4017 // we carry over the incoming values correctly.
4018 for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
4019 if (Incoming == LoopMiddleBlock)
4020 BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
4021 else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
4022 BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
4023 Incoming);
4024 else
4025 BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4026 }
4027
4028 // Set the resume value for this reduction
4029 ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4030
4031 // If there were stores of the reduction value to a uniform memory address
4032 // inside the loop, create the final store here.
4033 if (StoreInst *SI = RdxDesc.IntermediateStore) {
4034 StoreInst *NewSI =
4035 Builder.CreateStore(ReducedPartRdx, SI->getPointerOperand());
4036 propagateMetadata(NewSI, SI);
4037
4038 // If the reduction value is used in other places,
4039 // then let the code below create PHI's for that.
4040 }
4041
4042 // Now, we need to fix the users of the reduction variable
4043 // inside and outside of the scalar remainder loop.
4044
4045 // We know that the loop is in LCSSA form. We need to update the PHI nodes
4046 // in the exit blocks. See comment on analogous loop in
4047 // fixFixedOrderRecurrence for a more complete explaination of the logic.
4049 for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4050 if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst)) {
4051 LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4052 State.Plan->removeLiveOut(&LCSSAPhi);
4053 }
4054
4055 // Fix the scalar loop reduction variable with the incoming reduction sum
4056 // from the vector body and from the backedge value.
4057 int IncomingEdgeBlockIdx =
4059 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4060 // Pick the other block.
4061 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4062 OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4063 OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4064}
4065
4067 VPTransformState &State) {
4068 const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4069 RecurKind RK = RdxDesc.getRecurrenceKind();
4070 if (RK != RecurKind::Add && RK != RecurKind::Mul)
4071 return;
4072
4075 Worklist.push_back(PhiR);
4076 Visited.insert(PhiR);
4077
4078 while (!Worklist.empty()) {
4079 VPValue *Cur = Worklist.pop_back_val();
4080 for (unsigned Part = 0; Part < UF; ++Part) {
4081 Value *V = State.get(Cur, Part);
4082 if (!isa<OverflowingBinaryOperator>(V))
4083 break;
4084 cast<Instruction>(V)->dropPoisonGeneratingFlags();
4085 }
4086
4087 for (VPUser *U : Cur->users()) {
4088 auto *UserRecipe = dyn_cast<VPRecipeBase>(U);
4089 if (!UserRecipe)
4090 continue;
4091 for (VPValue *V : UserRecipe->definedValues())
4092 if (Visited.insert(V).second)
4093 Worklist.push_back(V);
4094 }
4095 }
4096}
4097
4099 // The basic block and loop containing the predicated instruction.
4100 auto *PredBB = PredInst->getParent();
4101 auto *VectorLoop = LI->getLoopFor(PredBB);
4102
4103 // Initialize a worklist with the operands of the predicated instruction.
4104 SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4105
4106 // Holds instructions that we need to analyze again. An instruction may be
4107 // reanalyzed if we don't yet know if we can sink it or not.
4108 SmallVector<Instruction *, 8> InstsToReanalyze;
4109
4110 // Returns true if a given use occurs in the predicated block. Phi nodes use
4111 // their operands in their corresponding predecessor blocks.
4112 auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4113 auto *I = cast<Instruction>(U.getUser());
4114 BasicBlock *BB = I->getParent();
4115 if (auto *Phi = dyn_cast<PHINode>(I))
4116 BB = Phi->getIncomingBlock(
4117 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4118 return BB == PredBB;
4119 };
4120
4121 // Iteratively sink the scalarized operands of the predicated instruction
4122 // into the block we created for it. When an instruction is sunk, it's
4123 // operands are then added to the worklist. The algorithm ends after one pass
4124 // through the worklist doesn't sink a single instruction.
4125 bool Changed;
4126 do {
4127 // Add the instructions that need to be reanalyzed to the worklist, and
4128 // reset the changed indicator.
4129 Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4130 InstsToReanalyze.clear();
4131 Changed = false;
4132
4133 while (!Worklist.empty()) {
4134 auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4135
4136 // We can't sink an instruction if it is a phi node, is not in the loop,
4137 // or may have side effects.
4138 if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4139 I->mayHaveSideEffects())
4140 continue;
4141
4142 // If the instruction is already in PredBB, check if we can sink its
4143 // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4144 // sinking the scalar instruction I, hence it appears in PredBB; but it
4145 // may have failed to sink I's operands (recursively), which we try
4146 // (again) here.
4147 if (I->getParent() == PredBB) {
4148 Worklist.insert(I->op_begin(), I->op_end());
4149 continue;
4150 }
4151
4152 // It's legal to sink the instruction if all its uses occur in the
4153 // predicated block. Otherwise, there's nothing to do yet, and we may
4154 // need to reanalyze the instruction.
4155 if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4156 InstsToReanalyze.push_back(I);
4157 continue;
4158 }
4159
4160 // Move the instruction to the beginning of the predicated block, and add
4161 // it's operands to the worklist.
4162 I->moveBefore(&*PredBB->getFirstInsertionPt());
4163 Worklist.insert(I->op_begin(), I->op_end());
4164
4165 // The sinking may have enabled other instructions to be sunk, so we will
4166 // need to iterate.
4167 Changed = true;
4168 }
4169 } while (Changed);
4170}
4171
4173 VPTransformState &State) {
4174 auto Iter = vp_depth_first_deep(Plan.getEntry());
4175 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
4176 for (VPRecipeBase &P : VPBB->phis()) {
4177 VPWidenPHIRecipe *VPPhi = dyn_cast<VPWidenPHIRecipe>(&P);
4178 if (!VPPhi)
4179 continue;
4180 PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4181 // Make sure the builder has a valid insert point.
4182 Builder.SetInsertPoint(NewPhi);
4183 for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4184 VPValue *Inc = VPPhi->getIncomingValue(i);
4185 VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4186 NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4187 }
4188 }
4189 }
4190}
4191
4193 const RecurrenceDescriptor &RdxDesc) {
4194 return Cost->useOrderedReductions(RdxDesc);
4195}
4196
4197void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4198 // We should not collect Scalars more than once per VF. Right now, this
4199 // function is called from collectUniformsAndScalars(), which already does
4200 // this check. Collecting Scalars for VF=1 does not make any sense.
4201 assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4202 "This function should not be visited twice for the same VF");
4203
4204 // This avoids any chances of creating a REPLICATE recipe during planning
4205 // since that would result in generation of scalarized code during execution,
4206 // which is not supported for scalable vectors.
4207 if (VF.isScalable()) {
4208 Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4209 return;
4210 }
4211
4213
4214 // These sets are used to seed the analysis with pointers used by memory
4215 // accesses that will remain scalar.
4217 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4218 auto *Latch = TheLoop->getLoopLatch();
4219
4220 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4221 // The pointer operands of loads and stores will be scalar as long as the
4222 // memory access is not a gather or scatter operation. The value operand of a
4223 // store will remain scalar if the store is scalarized.
4224 auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4225 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4226 assert(WideningDecision != CM_Unknown &&
4227 "Widening decision should be ready at this moment");
4228 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4229 if (Ptr == Store->getValueOperand())
4230 return WideningDecision == CM_Scalarize;
4231 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4232 "Ptr is neither a value or pointer operand");
4233 return WideningDecision != CM_GatherScatter;
4234 };
4235
4236 // A helper that returns true if the given value is a bitcast or
4237 // getelementptr instruction contained in the loop.
4238 auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4239 return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4240 isa<GetElementPtrInst>(V)) &&
4241 !TheLoop->isLoopInvariant(V);
4242 };
4243
4244 // A helper that evaluates a memory access's use of a pointer. If the use will
4245 // be a scalar use and the pointer is only used by memory accesses, we place
4246 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4247 // PossibleNonScalarPtrs.
4248 auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4249 // We only care about bitcast and getelementptr instructions contained in
4250 // the loop.
4251 if (!isLoopVaryingBitCastOrGEP(Ptr))
4252 return;
4253
4254 // If the pointer has already been identified as scalar (e.g., if it was
4255 // also identified as uniform), there's nothing to do.
4256 auto *I = cast<Instruction>(Ptr);
4257 if (Worklist.count(I))
4258 return;
4259
4260 // If the use of the pointer will be a scalar use, and all users of the
4261 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4262 // place the pointer in PossibleNonScalarPtrs.
4263 if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4264 return isa<LoadInst>(U) || isa<StoreInst>(U);
4265 }))
4266 ScalarPtrs.insert(I);
4267 else
4268 PossibleNonScalarPtrs.insert(I);
4269 };
4270
4271 // We seed the scalars analysis with three classes of instructions: (1)
4272 // instructions marked uniform-after-vectorization and (2) bitcast,
4273 // getelementptr and (pointer) phi instructions used by memory accesses
4274 // requiring a scalar use.
4275 //
4276 // (1) Add to the worklist all instructions that have been identified as
4277 // uniform-after-vectorization.
4278 Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4279
4280 // (2) Add to the worklist all bitcast and getelementptr instructions used by
4281 // memory accesses requiring a scalar use. The pointer operands of loads and
4282 // stores will be scalar as long as the memory accesses is not a gather or
4283 // scatter operation. The value operand of a store will remain scalar if the
4284 // store is scalarized.
4285 for (auto *BB : TheLoop->blocks())
4286 for (auto &I : *BB) {
4287 if (auto *Load = dyn_cast<LoadInst>(&I)) {
4288 evaluatePtrUse(Load, Load->getPointerOperand());
4289 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4290 evaluatePtrUse(Store, Store->getPointerOperand());
4291 evaluatePtrUse(Store, Store->getValueOperand());
4292 }
4293 }
4294 for (auto *I : ScalarPtrs)
4295 if (!PossibleNonScalarPtrs.count(I)) {
4296 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4297 Worklist.insert(I);
4298 }
4299
4300 // Insert the forced scalars.
4301 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
4302 // induction variable when the PHI user is scalarized.
4303 auto ForcedScalar = ForcedScalars.find(VF);
4304 if (ForcedScalar != ForcedScalars.end())
4305 for (auto *I : ForcedScalar->second) {
4306 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
4307 Worklist.insert(I);
4308 }
4309
4310 // Expand the worklist by looking through any bitcasts and getelementptr
4311 // instructions we've already identified as scalar. This is similar to the
4312 // expansion step in collectLoopUniforms(); however, here we're only
4313 // expanding to include additional bitcasts and getelementptr instructions.
4314 unsigned Idx = 0;
4315 while (Idx != Worklist.size()) {
4316 Instruction *Dst = Worklist[Idx++];
4317 if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4318 continue;
4319 auto *Src = cast<Instruction>(Dst->getOperand(0));
4320 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4321 auto *J = cast<Instruction>(U);
4322 return !TheLoop->contains(J) || Worklist.count(J) ||
4323 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4324 isScalarUse(J, Src));
4325 })) {
4326 Worklist.insert(Src);
4327 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4328 }
4329 }
4330
4331 // An induction variable will remain scalar if all users of the induction
4332 // variable and induction variable update remain scalar.
4333 for (const auto &Induction : Legal->getInductionVars()) {
4334 auto *Ind = Induction.first;
4335 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4336
4337 // If tail-folding is applied, the primary induction variable will be used
4338 // to feed a vector compare.
4339 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4340 continue;
4341
4342 // Returns true if \p Indvar is a pointer induction that is used directly by
4343 // load/store instruction \p I.
4344 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4345 Instruction *I) {
4346 return Induction.second.getKind() ==
4348 (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4349 Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4350 };
4351
4352 // Determine if all users of the induction variable are scalar after
4353 // vectorization.
4354 auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4355 auto *I = cast<Instruction>(U);
4356 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4357 IsDirectLoadStoreFromPtrIndvar(Ind, I);
4358 });
4359 if (!ScalarInd)
4360 continue;
4361
4362 // Determine if all users of the induction variable update instruction are
4363 // scalar after vectorization.
4364 auto ScalarIndUpdate =
4365 llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4366 auto *I = cast<Instruction>(U);
4367 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4368 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4369 });
4370 if (!ScalarIndUpdate)
4371 continue;
4372
4373 // The induction variable and its update instruction will remain scalar.
4374 Worklist.insert(Ind);
4375 Worklist.insert(IndUpdate);
4376 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4377 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4378 << "\n");
4379 }
4380
4381 Scalars[VF].insert(Worklist.begin(), Worklist.end());
4382}
4383
4385 Instruction *I, ElementCount VF) const {
4386 if (!isPredicatedInst(I))
4387 return false;
4388
4389 // Do we have a non-scalar lowering for this predicated
4390 // instruction? No - it is scalar with predication.
4391 switch(I->getOpcode()) {
4392 default:
4393 return true;
4394 case Instruction::Load:
4395 case Instruction::Store: {
4397 auto *Ty = getLoadStoreType(I);
4398 Type *VTy = Ty;
4399 if (VF.isVector())
4400 VTy = VectorType::get(Ty, VF);
4401 const Align Alignment = getLoadStoreAlignment(I);
4402 return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4403 TTI.isLegalMaskedGather(VTy, Alignment))
4404 : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4405 TTI.isLegalMaskedScatter(VTy, Alignment));
4406 }
4407 case Instruction::UDiv:
4408 case Instruction::SDiv:
4409 case Instruction::SRem:
4410 case Instruction::URem: {
4411 // We have the option to use the safe-divisor idiom to avoid predication.
4412 // The cost based decision here will always select safe-divisor for
4413 // scalable vectors as scalarization isn't legal.
4414 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
4415 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost);
4416 }
4417 }
4418}
4419
4421 if (!blockNeedsPredicationForAnyReason(I->getParent()))
4422 return false;
4423
4424 // Can we prove this instruction is safe to unconditionally execute?
4425 // If not, we must use some form of predication.
4426 switch(I->getOpcode()) {
4427 default:
4428 return false;
4429 case Instruction::Load:
4430 case Instruction::Store: {
4431 if (!Legal->isMaskRequired(I))
4432 return false;
4433 // When we know the load's address is loop invariant and the instruction
4434 // in the original scalar loop was unconditionally executed then we
4435 // don't need to mark it as a predicated instruction. Tail folding may
4436 // introduce additional predication, but we're guaranteed to always have
4437 // at least one active lane. We call Legal->blockNeedsPredication here
4438 // because it doesn't query tail-folding. For stores, we need to prove
4439 // both speculation safety (which follows from the same argument as loads),
4440 // but also must prove the value being stored is correct. The easiest
4441 // form of the later is to require that all values stored are the same.
4442 if (Legal->isUniformMemOp(*I) &&
4443 (isa<LoadInst>(I) ||
4444 (isa<StoreInst>(I) &&
4445 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()))) &&
4446 !Legal->blockNeedsPredication(I->getParent()))
4447 return false;
4448 return true;
4449 }
4450 case Instruction::UDiv:
4451 case Instruction::SDiv:
4452 case Instruction::SRem:
4453 case Instruction::URem:
4454 // TODO: We can use the loop-preheader as context point here and get
4455 // context sensitive reasoning
4457 }
4458}
4459
4460std::pair<InstructionCost, InstructionCost>
4462 ElementCount VF) const {
4463 assert(I->getOpcode() == Instruction::UDiv ||
4464 I->getOpcode() == Instruction::SDiv ||
4465 I->getOpcode() == Instruction::SRem ||
4466 I->getOpcode() == Instruction::URem);
4468
4470
4471 // Scalarization isn't legal for scalable vector types
4472 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
4473 if (!VF.isScalable()) {
4474 // Get the scalarization cost and scale this amount by the probability of
4475 // executing the predicated block. If the instruction is not predicated,
4476 // we fall through to the next case.
4477 ScalarizationCost = 0;
4478
4479 // These instructions have a non-void type, so account for the phi nodes
4480 // that we will create. This cost is likely to be zero. The phi node
4481 // cost, if any, should be scaled by the block probability because it
4482 // models a copy at the end of each predicated block.
4483 ScalarizationCost += VF.getKnownMinValue() *
4484 TTI.getCFInstrCost(Instruction::PHI, CostKind);
4485
4486 // The cost of the non-predicated instruction.
4487 ScalarizationCost += VF.getKnownMinValue() *
4488 TTI.getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind);
4489
4490 // The cost of insertelement and extractelement instructions needed for
4491 // scalarization.
4492 ScalarizationCost += getScalarizationOverhead(I, VF, CostKind);
4493
4494 // Scale the cost by the probability of executing the predicated blocks.
4495 // This as