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