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