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