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