LLVM  7.0.0svn
LoopVectorize.cpp
Go to the documentation of this file.
1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
14 //
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
18 //
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
28 //
29 // There is a development effort going on to migrate loop vectorizer to the
30 // VPlan infrastructure and to introduce outer loop vectorization support (see
31 // docs/Proposal/VectorizationPlan.rst and
32 // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
33 // purpose, we temporarily introduced the VPlan-native vectorization path: an
34 // alternative vectorization path that is natively implemented on top of the
35 // VPlan infrastructure. See EnableVPlanNativePath for enabling.
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // The reduction-variable vectorization is based on the paper:
40 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
41 //
42 // Variable uniformity checks are inspired by:
43 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
44 //
45 // The interleaved access vectorization is based on the paper:
46 // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
47 // Data for SIMD
48 //
49 // Other ideas/concepts are from:
50 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
51 //
52 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
53 // Vectorizing Compilers.
54 //
55 //===----------------------------------------------------------------------===//
56 
59 #include "VPRecipeBuilder.h"
60 #include "VPlanHCFGBuilder.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DenseMapInfo.h"
65 #include "llvm/ADT/Hashing.h"
66 #include "llvm/ADT/MapVector.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/SetVector.h"
71 #include "llvm/ADT/SmallPtrSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/ADT/StringRef.h"
75 #include "llvm/ADT/Twine.h"
80 #include "llvm/Analysis/CFG.h"
86 #include "llvm/Analysis/LoopInfo.h"
95 #include "llvm/IR/Attributes.h"
96 #include "llvm/IR/BasicBlock.h"
97 #include "llvm/IR/CFG.h"
98 #include "llvm/IR/Constant.h"
99 #include "llvm/IR/Constants.h"
100 #include "llvm/IR/DataLayout.h"
102 #include "llvm/IR/DebugLoc.h"
103 #include "llvm/IR/DerivedTypes.h"
104 #include "llvm/IR/DiagnosticInfo.h"
105 #include "llvm/IR/Dominators.h"
106 #include "llvm/IR/Function.h"
107 #include "llvm/IR/IRBuilder.h"
108 #include "llvm/IR/InstrTypes.h"
109 #include "llvm/IR/Instruction.h"
110 #include "llvm/IR/Instructions.h"
111 #include "llvm/IR/IntrinsicInst.h"
112 #include "llvm/IR/Intrinsics.h"
113 #include "llvm/IR/LLVMContext.h"
114 #include "llvm/IR/Metadata.h"
115 #include "llvm/IR/Module.h"
116 #include "llvm/IR/Operator.h"
117 #include "llvm/IR/Type.h"
118 #include "llvm/IR/Use.h"
119 #include "llvm/IR/User.h"
120 #include "llvm/IR/Value.h"
121 #include "llvm/IR/ValueHandle.h"
122 #include "llvm/IR/Verifier.h"
123 #include "llvm/Pass.h"
124 #include "llvm/Support/Casting.h"
126 #include "llvm/Support/Compiler.h"
127 #include "llvm/Support/Debug.h"
129 #include "llvm/Support/MathExtras.h"
136 #include <algorithm>
137 #include <cassert>
138 #include <cstdint>
139 #include <cstdlib>
140 #include <functional>
141 #include <iterator>
142 #include <limits>
143 #include <memory>
144 #include <string>
145 #include <tuple>
146 #include <utility>
147 #include <vector>
148 
149 using namespace llvm;
150 
151 #define LV_NAME "loop-vectorize"
152 #define DEBUG_TYPE LV_NAME
153 
154 STATISTIC(LoopsVectorized, "Number of loops vectorized");
155 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
156 
157 /// Loops with a known constant trip count below this number are vectorized only
158 /// if no scalar iteration overheads are incurred.
160  "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
161  cl::desc("Loops with a constant trip count that is smaller than this "
162  "value are vectorized only if no scalar iteration overheads "
163  "are incurred."));
164 
166  "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
167  cl::desc("Maximize bandwidth when selecting vectorization factor which "
168  "will be determined by the smallest type in loop."));
169 
171  "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
172  cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
173 
174 /// Maximum factor for an interleaved memory access.
176  "max-interleave-group-factor", cl::Hidden,
177  cl::desc("Maximum factor for an interleaved access group (default = 8)"),
178  cl::init(8));
179 
180 /// We don't interleave loops with a known constant trip count below this
181 /// number.
182 static const unsigned TinyTripCountInterleaveThreshold = 128;
183 
185  "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
186  cl::desc("A flag that overrides the target's number of scalar registers."));
187 
189  "force-target-num-vector-regs", cl::init(0), cl::Hidden,
190  cl::desc("A flag that overrides the target's number of vector registers."));
191 
193  "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
194  cl::desc("A flag that overrides the target's max interleave factor for "
195  "scalar loops."));
196 
198  "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
199  cl::desc("A flag that overrides the target's max interleave factor for "
200  "vectorized loops."));
201 
203  "force-target-instruction-cost", cl::init(0), cl::Hidden,
204  cl::desc("A flag that overrides the target's expected cost for "
205  "an instruction to a single constant value. Mostly "
206  "useful for getting consistent testing."));
207 
209  "small-loop-cost", cl::init(20), cl::Hidden,
210  cl::desc(
211  "The cost of a loop that is considered 'small' by the interleaver."));
212 
214  "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
215  cl::desc("Enable the use of the block frequency analysis to access PGO "
216  "heuristics minimizing code growth in cold regions and being more "
217  "aggressive in hot regions."));
218 
219 // Runtime interleave loops for load/store throughput.
221  "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
222  cl::desc(
223  "Enable runtime interleaving until load/store ports are saturated"));
224 
225 /// The number of stores in a loop that are allowed to need predication.
227  "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
228  cl::desc("Max number of stores to be predicated behind an if."));
229 
231  "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
232  cl::desc("Count the induction variable only once when interleaving"));
233 
235  "enable-cond-stores-vec", cl::init(true), cl::Hidden,
236  cl::desc("Enable if predication of stores during vectorization."));
237 
239  "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
240  cl::desc("The maximum interleave count to use when interleaving a scalar "
241  "reduction in a nested loop."));
242 
244  "enable-vplan-native-path", cl::init(false), cl::Hidden,
245  cl::desc("Enable VPlan-native vectorization path with "
246  "support for outer loop vectorization."));
247 
248 // This flag enables the stress testing of the VPlan H-CFG construction in the
249 // VPlan-native vectorization path. It must be used in conjuction with
250 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
251 // verification of the H-CFGs built.
253  "vplan-build-stress-test", cl::init(false), cl::Hidden,
254  cl::desc(
255  "Build VPlan for every supported loop nest in the function and bail "
256  "out right after the build (stress test the VPlan H-CFG construction "
257  "in the VPlan-native vectorization path)."));
258 
259 /// A helper function for converting Scalar types to vector types.
260 /// If the incoming type is void, we return void. If the VF is 1, we return
261 /// the scalar type.
262 static Type *ToVectorTy(Type *Scalar, unsigned VF) {
263  if (Scalar->isVoidTy() || VF == 1)
264  return Scalar;
265  return VectorType::get(Scalar, VF);
266 }
267 
268 // FIXME: The following helper functions have multiple implementations
269 // in the project. They can be effectively organized in a common Load/Store
270 // utilities unit.
271 
272 /// A helper function that returns the type of loaded or stored value.
274  assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
275  "Expected Load or Store instruction");
276  if (auto *LI = dyn_cast<LoadInst>(I))
277  return LI->getType();
278  return cast<StoreInst>(I)->getValueOperand()->getType();
279 }
280 
281 /// A helper function that returns the alignment of load or store instruction.
282 static unsigned getMemInstAlignment(Value *I) {
283  assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
284  "Expected Load or Store instruction");
285  if (auto *LI = dyn_cast<LoadInst>(I))
286  return LI->getAlignment();
287  return cast<StoreInst>(I)->getAlignment();
288 }
289 
290 /// A helper function that returns the address space of the pointer operand of
291 /// load or store instruction.
292 static unsigned getMemInstAddressSpace(Value *I) {
293  assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
294  "Expected Load or Store instruction");
295  if (auto *LI = dyn_cast<LoadInst>(I))
296  return LI->getPointerAddressSpace();
297  return cast<StoreInst>(I)->getPointerAddressSpace();
298 }
299 
300 /// A helper function that returns true if the given type is irregular. The
301 /// type is irregular if its allocated size doesn't equal the store size of an
302 /// element of the corresponding vector type at the given vectorization factor.
303 static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
304  // Determine if an array of VF elements of type Ty is "bitcast compatible"
305  // with a <VF x Ty> vector.
306  if (VF > 1) {
307  auto *VectorTy = VectorType::get(Ty, VF);
308  return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
309  }
310 
311  // If the vectorization factor is one, we just check if an array of type Ty
312  // requires padding between elements.
313  return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
314 }
315 
316 /// A helper function that returns the reciprocal of the block probability of
317 /// predicated blocks. If we return X, we are assuming the predicated block
318 /// will execute once for every X iterations of the loop header.
319 ///
320 /// TODO: We should use actual block probability here, if available. Currently,
321 /// we always assume predicated blocks have a 50% chance of executing.
322 static unsigned getReciprocalPredBlockProb() { return 2; }
323 
324 /// A helper function that adds a 'fast' flag to floating-point operations.
326  if (isa<FPMathOperator>(V)) {
327  FastMathFlags Flags;
328  Flags.setFast();
329  cast<Instruction>(V)->setFastMathFlags(Flags);
330  }
331  return V;
332 }
333 
334 /// A helper function that returns an integer or floating-point constant with
335 /// value C.
336 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
337  return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
338  : ConstantFP::get(Ty, C);
339 }
340 
341 namespace llvm {
342 
343 /// InnerLoopVectorizer vectorizes loops which contain only one basic
344 /// block to a specified vectorization factor (VF).
345 /// This class performs the widening of scalars into vectors, or multiple
346 /// scalars. This class also implements the following features:
347 /// * It inserts an epilogue loop for handling loops that don't have iteration
348 /// counts that are known to be a multiple of the vectorization factor.
349 /// * It handles the code generation for reduction variables.
350 /// * Scalarization (implementation using scalars) of un-vectorizable
351 /// instructions.
352 /// InnerLoopVectorizer does not perform any vectorization-legality
353 /// checks, and relies on the caller to check for the different legality
354 /// aspects. The InnerLoopVectorizer relies on the
355 /// LoopVectorizationLegality class to provide information about the induction
356 /// and reduction variables that were found to a given vectorization factor.
358 public:
361  const TargetLibraryInfo *TLI,
363  OptimizationRemarkEmitter *ORE, unsigned VecWidth,
364  unsigned UnrollFactor, LoopVectorizationLegality *LVL,
366  : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
367  AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
368  Builder(PSE.getSE()->getContext()),
369  VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
370  virtual ~InnerLoopVectorizer() = default;
371 
372  /// Create a new empty loop. Unlink the old loop and connect the new one.
373  /// Return the pre-header block of the new loop.
375 
376  /// Widen a single instruction within the innermost loop.
378 
379  /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
380  void fixVectorizedLoop();
381 
382  // Return true if any runtime check is added.
384 
385  /// A type for vectorized values in the new loop. Each value from the
386  /// original loop, when vectorized, is represented by UF vector values in the
387  /// new unrolled loop, where UF is the unroll factor.
389 
390  /// Vectorize a single PHINode in a block. This method handles the induction
391  /// variable canonicalization. It supports both VF = 1 for unrolled loops and
392  /// arbitrary length vectors.
393  void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
394 
395  /// A helper function to scalarize a single Instruction in the innermost loop.
396  /// Generates a sequence of scalar instances for each lane between \p MinLane
397  /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
398  /// inclusive..
399  void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
400  bool IfPredicateInstr);
401 
402  /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
403  /// is provided, the integer induction variable will first be truncated to
404  /// the corresponding type.
405  void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
406 
407  /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
408  /// vector or scalar value on-demand if one is not yet available. When
409  /// vectorizing a loop, we visit the definition of an instruction before its
410  /// uses. When visiting the definition, we either vectorize or scalarize the
411  /// instruction, creating an entry for it in the corresponding map. (In some
412  /// cases, such as induction variables, we will create both vector and scalar
413  /// entries.) Then, as we encounter uses of the definition, we derive values
414  /// for each scalar or vector use unless such a value is already available.
415  /// For example, if we scalarize a definition and one of its uses is vector,
416  /// we build the required vector on-demand with an insertelement sequence
417  /// when visiting the use. Otherwise, if the use is scalar, we can use the
418  /// existing scalar definition.
419  ///
420  /// Return a value in the new loop corresponding to \p V from the original
421  /// loop at unroll index \p Part. If the value has already been vectorized,
422  /// the corresponding vector entry in VectorLoopValueMap is returned. If,
423  /// however, the value has a scalar entry in VectorLoopValueMap, we construct
424  /// a new vector value on-demand by inserting the scalar values into a vector
425  /// with an insertelement sequence. If the value has been neither vectorized
426  /// nor scalarized, it must be loop invariant, so we simply broadcast the
427  /// value into a vector.
428  Value *getOrCreateVectorValue(Value *V, unsigned Part);
429 
430  /// Return a value in the new loop corresponding to \p V from the original
431  /// loop at unroll and vector indices \p Instance. If the value has been
432  /// vectorized but not scalarized, the necessary extractelement instruction
433  /// will be generated.
434  Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
435 
436  /// Construct the vector value of a scalarized value \p V one lane at a time.
437  void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
438 
439  /// Try to vectorize the interleaved access group that \p Instr belongs to.
441 
442  /// Vectorize Load and Store instructions, optionally masking the vector
443  /// operations if \p BlockInMask is non-null.
445  VectorParts *BlockInMask = nullptr);
446 
447  /// Set the debug location in the builder using the debug location in
448  /// the instruction.
449  void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
450 
451 protected:
453 
454  /// A small list of PHINodes.
456 
457  /// A type for scalarized values in the new loop. Each value from the
458  /// original loop, when scalarized, is represented by UF x VF scalar values
459  /// in the new unrolled loop, where UF is the unroll factor and VF is the
460  /// vectorization factor.
462 
463  /// Set up the values of the IVs correctly when exiting the vector loop.
464  void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
465  Value *CountRoundDown, Value *EndValue,
466  BasicBlock *MiddleBlock);
467 
468  /// Create a new induction variable inside L.
469  PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
470  Value *Step, Instruction *DL);
471 
472  /// Handle all cross-iteration phis in the header.
473  void fixCrossIterationPHIs();
474 
475  /// Fix a first-order recurrence. This is the second phase of vectorizing
476  /// this phi node.
477  void fixFirstOrderRecurrence(PHINode *Phi);
478 
479  /// Fix a reduction cross-iteration phi. This is the second phase of
480  /// vectorizing this phi node.
481  void fixReduction(PHINode *Phi);
482 
483  /// The Loop exit block may have single value PHI nodes with some
484  /// incoming value. While vectorizing we only handled real values
485  /// that were defined inside the loop and we should have one value for
486  /// each predecessor of its parent basic block. See PR14725.
487  void fixLCSSAPHIs();
488 
489  /// Iteratively sink the scalarized operands of a predicated instruction into
490  /// the block that was created for it.
491  void sinkScalarOperands(Instruction *PredInst);
492 
493  /// Shrinks vector element sizes to the smallest bitwidth they can be legally
494  /// represented as.
496 
497  /// Insert the new loop to the loop hierarchy and pass manager
498  /// and update the analysis passes.
499  void updateAnalysis();
500 
501  /// Create a broadcast instruction. This method generates a broadcast
502  /// instruction (shuffle) for loop invariant values and for the induction
503  /// value. If this is the induction variable then we extend it to N, N+1, ...
504  /// this is needed because each iteration in the loop corresponds to a SIMD
505  /// element.
506  virtual Value *getBroadcastInstrs(Value *V);
507 
508  /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
509  /// to each vector element of Val. The sequence starts at StartIndex.
510  /// \p Opcode is relevant for FP induction variable.
511  virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
512  Instruction::BinaryOps Opcode =
513  Instruction::BinaryOpsEnd);
514 
515  /// Compute scalar induction steps. \p ScalarIV is the scalar induction
516  /// variable on which to base the steps, \p Step is the size of the step, and
517  /// \p EntryVal is the value from the original loop that maps to the steps.
518  /// Note that \p EntryVal doesn't have to be an induction variable - it
519  /// can also be a truncate instruction.
520  void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
521  const InductionDescriptor &ID);
522 
523  /// Create a vector induction phi node based on an existing scalar one. \p
524  /// EntryVal is the value from the original loop that maps to the vector phi
525  /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
526  /// truncate instruction, instead of widening the original IV, we widen a
527  /// version of the IV truncated to \p EntryVal's type.
529  Value *Step, Instruction *EntryVal);
530 
531  /// Returns true if an instruction \p I should be scalarized instead of
532  /// vectorized for the chosen vectorization factor.
534 
535  /// Returns true if we should generate a scalar version of \p IV.
536  bool needsScalarInduction(Instruction *IV) const;
537 
538  /// If there is a cast involved in the induction variable \p ID, which should
539  /// be ignored in the vectorized loop body, this function records the
540  /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
541  /// cast. We had already proved that the casted Phi is equal to the uncasted
542  /// Phi in the vectorized loop (under a runtime guard), and therefore
543  /// there is no need to vectorize the cast - the same value can be used in the
544  /// vector loop for both the Phi and the cast.
545  /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
546  /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
547  ///
548  /// \p EntryVal is the value from the original loop that maps to the vector
549  /// phi node and is used to distinguish what is the IV currently being
550  /// processed - original one (if \p EntryVal is a phi corresponding to the
551  /// original IV) or the "newly-created" one based on the proof mentioned above
552  /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
553  /// latter case \p EntryVal is a TruncInst and we must not record anything for
554  /// that IV, but it's error-prone to expect callers of this routine to care
555  /// about that, hence this explicit parameter.
557  const Instruction *EntryVal,
558  Value *VectorLoopValue,
559  unsigned Part,
560  unsigned Lane = UINT_MAX);
561 
562  /// Generate a shuffle sequence that will reverse the vector Vec.
563  virtual Value *reverseVector(Value *Vec);
564 
565  /// Returns (and creates if needed) the original loop trip count.
566  Value *getOrCreateTripCount(Loop *NewLoop);
567 
568  /// Returns (and creates if needed) the trip count of the widened loop.
570 
571  /// Returns a bitcasted value to the requested vector type.
572  /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
574  const DataLayout &DL);
575 
576  /// Emit a bypass check to see if the vector trip count is zero, including if
577  /// it overflows.
579 
580  /// Emit a bypass check to see if all of the SCEV assumptions we've
581  /// had to make are correct.
582  void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
583 
584  /// Emit bypass checks to check any memory assumptions we may have made.
585  void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
586 
587  /// Add additional metadata to \p To that was not present on \p Orig.
588  ///
589  /// Currently this is used to add the noalias annotations based on the
590  /// inserted memchecks. Use this for instructions that are *cloned* into the
591  /// vector loop.
592  void addNewMetadata(Instruction *To, const Instruction *Orig);
593 
594  /// Add metadata from one instruction to another.
595  ///
596  /// This includes both the original MDs from \p From and additional ones (\see
597  /// addNewMetadata). Use this for *newly created* instructions in the vector
598  /// loop.
599  void addMetadata(Instruction *To, Instruction *From);
600 
601  /// Similar to the previous function but it adds the metadata to a
602  /// vector of instructions.
603  void addMetadata(ArrayRef<Value *> To, Instruction *From);
604 
605  /// The original loop.
607 
608  /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
609  /// dynamic knowledge to simplify SCEV expressions and converts them to a
610  /// more usable form.
612 
613  /// Loop Info.
615 
616  /// Dominator Tree.
618 
619  /// Alias Analysis.
621 
622  /// Target Library Info.
624 
625  /// Target Transform Info.
627 
628  /// Assumption Cache.
630 
631  /// Interface to emit optimization remarks.
633 
634  /// LoopVersioning. It's only set up (non-null) if memchecks were
635  /// used.
636  ///
637  /// This is currently only used to add no-alias metadata based on the
638  /// memchecks. The actually versioning is performed manually.
639  std::unique_ptr<LoopVersioning> LVer;
640 
641  /// The vectorization SIMD factor to use. Each vector will have this many
642  /// vector elements.
643  unsigned VF;
644 
645  /// The vectorization unroll factor to use. Each scalar is vectorized to this
646  /// many different vector instructions.
647  unsigned UF;
648 
649  /// The builder that we use
651 
652  // --- Vectorization state ---
653 
654  /// The vector-loop preheader.
656 
657  /// The scalar-loop preheader.
659 
660  /// Middle Block between the vector and the scalar.
662 
663  /// The ExitBlock of the scalar loop.
665 
666  /// The vector loop body.
668 
669  /// The scalar loop body.
671 
672  /// A list of all bypass blocks. The first block is the entry of the loop.
674 
675  /// The new Induction variable which was added to the new block.
676  PHINode *Induction = nullptr;
677 
678  /// The induction variable of the old basic block.
679  PHINode *OldInduction = nullptr;
680 
681  /// Maps values from the original loop to their corresponding values in the
682  /// vectorized loop. A key value can map to either vector values, scalar
683  /// values or both kinds of values, depending on whether the key was
684  /// vectorized and scalarized.
686 
687  /// Store instructions that were predicated.
689 
690  /// Trip count of the original loop.
691  Value *TripCount = nullptr;
692 
693  /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
694  Value *VectorTripCount = nullptr;
695 
696  /// The legality analysis.
698 
699  /// The profitablity analysis.
701 
702  // Record whether runtime checks are added.
703  bool AddedSafetyChecks = false;
704 
705  // Holds the end values for each induction variable. We save the end values
706  // so we can later fix-up the external users of the induction variables.
708 };
709 
711 public:
714  const TargetLibraryInfo *TLI,
716  OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
719  : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
720  UnrollFactor, LVL, CM) {}
721 
722 private:
723  Value *getBroadcastInstrs(Value *V) override;
724  Value *getStepVector(Value *Val, int StartIdx, Value *Step,
725  Instruction::BinaryOps Opcode =
726  Instruction::BinaryOpsEnd) override;
727  Value *reverseVector(Value *Vec) override;
728 };
729 
730 } // end namespace llvm
731 
732 /// Look for a meaningful debug location on the instruction or it's
733 /// operands.
735  if (!I)
736  return I;
737 
738  DebugLoc Empty;
739  if (I->getDebugLoc() != Empty)
740  return I;
741 
742  for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
743  if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
744  if (OpInst->getDebugLoc() != Empty)
745  return OpInst;
746  }
747 
748  return I;
749 }
750 
752  if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
753  const DILocation *DIL = Inst->getDebugLoc();
754  if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
755  !isa<DbgInfoIntrinsic>(Inst))
757  else
759  } else
761 }
762 
763 #ifndef NDEBUG
764 /// \return string containing a file name and a line # for the given loop.
765 static std::string getDebugLocString(const Loop *L) {
766  std::string Result;
767  if (L) {
768  raw_string_ostream OS(Result);
769  if (const DebugLoc LoopDbgLoc = L->getStartLoc())
770  LoopDbgLoc.print(OS);
771  else
772  // Just print the module name.
773  OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
774  OS.flush();
775  }
776  return Result;
777 }
778 #endif
779 
781  const Instruction *Orig) {
782  // If the loop was versioned with memchecks, add the corresponding no-alias
783  // metadata.
784  if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
785  LVer->annotateInstWithNoAlias(To, Orig);
786 }
787 
789  Instruction *From) {
790  propagateMetadata(To, From);
791  addNewMetadata(To, From);
792 }
793 
795  Instruction *From) {
796  for (Value *V : To) {
797  if (Instruction *I = dyn_cast<Instruction>(V))
798  addMetadata(I, From);
799  }
800 }
801 
802 namespace llvm {
803 
804 /// The group of interleaved loads/stores sharing the same stride and
805 /// close to each other.
806 ///
807 /// Each member in this group has an index starting from 0, and the largest
808 /// index should be less than interleaved factor, which is equal to the absolute
809 /// value of the access's stride.
810 ///
811 /// E.g. An interleaved load group of factor 4:
812 /// for (unsigned i = 0; i < 1024; i+=4) {
813 /// a = A[i]; // Member of index 0
814 /// b = A[i+1]; // Member of index 1
815 /// d = A[i+3]; // Member of index 3
816 /// ...
817 /// }
818 ///
819 /// An interleaved store group of factor 4:
820 /// for (unsigned i = 0; i < 1024; i+=4) {
821 /// ...
822 /// A[i] = a; // Member of index 0
823 /// A[i+1] = b; // Member of index 1
824 /// A[i+2] = c; // Member of index 2
825 /// A[i+3] = d; // Member of index 3
826 /// }
827 ///
828 /// Note: the interleaved load group could have gaps (missing members), but
829 /// the interleaved store group doesn't allow gaps.
831 public:
832  InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
833  : Align(Align), InsertPos(Instr) {
834  assert(Align && "The alignment should be non-zero");
835 
836  Factor = std::abs(Stride);
837  assert(Factor > 1 && "Invalid interleave factor");
838 
839  Reverse = Stride < 0;
840  Members[0] = Instr;
841  }
842 
843  bool isReverse() const { return Reverse; }
844  unsigned getFactor() const { return Factor; }
845  unsigned getAlignment() const { return Align; }
846  unsigned getNumMembers() const { return Members.size(); }
847 
848  /// Try to insert a new member \p Instr with index \p Index and
849  /// alignment \p NewAlign. The index is related to the leader and it could be
850  /// negative if it is the new leader.
851  ///
852  /// \returns false if the instruction doesn't belong to the group.
853  bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
854  assert(NewAlign && "The new member's alignment should be non-zero");
855 
856  int Key = Index + SmallestKey;
857 
858  // Skip if there is already a member with the same index.
859  if (Members.count(Key))
860  return false;
861 
862  if (Key > LargestKey) {
863  // The largest index is always less than the interleave factor.
864  if (Index >= static_cast<int>(Factor))
865  return false;
866 
867  LargestKey = Key;
868  } else if (Key < SmallestKey) {
869  // The largest index is always less than the interleave factor.
870  if (LargestKey - Key >= static_cast<int>(Factor))
871  return false;
872 
873  SmallestKey = Key;
874  }
875 
876  // It's always safe to select the minimum alignment.
877  Align = std::min(Align, NewAlign);
878  Members[Key] = Instr;
879  return true;
880  }
881 
882  /// Get the member with the given index \p Index
883  ///
884  /// \returns nullptr if contains no such member.
885  Instruction *getMember(unsigned Index) const {
886  int Key = SmallestKey + Index;
887  if (!Members.count(Key))
888  return nullptr;
889 
890  return Members.find(Key)->second;
891  }
892 
893  /// Get the index for the given member. Unlike the key in the member
894  /// map, the index starts from 0.
895  unsigned getIndex(Instruction *Instr) const {
896  for (auto I : Members)
897  if (I.second == Instr)
898  return I.first - SmallestKey;
899 
900  llvm_unreachable("InterleaveGroup contains no such member");
901  }
902 
903  Instruction *getInsertPos() const { return InsertPos; }
904  void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
905 
906  /// Add metadata (e.g. alias info) from the instructions in this group to \p
907  /// NewInst.
908  ///
909  /// FIXME: this function currently does not add noalias metadata a'la
910  /// addNewMedata. To do that we need to compute the intersection of the
911  /// noalias info from all members.
912  void addMetadata(Instruction *NewInst) const {
914  std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
915  [](std::pair<int, Instruction *> p) { return p.second; });
916  propagateMetadata(NewInst, VL);
917  }
918 
919 private:
920  unsigned Factor; // Interleave Factor.
921  bool Reverse;
922  unsigned Align;
924  int SmallestKey = 0;
925  int LargestKey = 0;
926 
927  // To avoid breaking dependences, vectorized instructions of an interleave
928  // group should be inserted at either the first load or the last store in
929  // program order.
930  //
931  // E.g. %even = load i32 // Insert Position
932  // %add = add i32 %even // Use of %even
933  // %odd = load i32
934  //
935  // store i32 %even
936  // %odd = add i32 // Def of %odd
937  // store i32 %odd // Insert Position
938  Instruction *InsertPos;
939 };
940 } // end namespace llvm
941 
942 namespace {
943 
944 /// Drive the analysis of interleaved memory accesses in the loop.
945 ///
946 /// Use this class to analyze interleaved accesses only when we can vectorize
947 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
948 /// on interleaved accesses is unsafe.
949 ///
950 /// The analysis collects interleave groups and records the relationships
951 /// between the member and the group in a map.
952 class InterleavedAccessInfo {
953 public:
954  InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
956  const LoopAccessInfo *LAI)
957  : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(LAI) {}
958 
959  ~InterleavedAccessInfo() {
961  // Avoid releasing a pointer twice.
962  for (auto &I : InterleaveGroupMap)
963  DelSet.insert(I.second);
964  for (auto *Ptr : DelSet)
965  delete Ptr;
966  }
967 
968  /// Analyze the interleaved accesses and collect them in interleave
969  /// groups. Substitute symbolic strides using \p Strides.
970  void analyzeInterleaving();
971 
972  /// Check if \p Instr belongs to any interleave group.
973  bool isInterleaved(Instruction *Instr) const {
974  return InterleaveGroupMap.count(Instr);
975  }
976 
977  /// Get the interleave group that \p Instr belongs to.
978  ///
979  /// \returns nullptr if doesn't have such group.
980  InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
981  if (InterleaveGroupMap.count(Instr))
982  return InterleaveGroupMap.find(Instr)->second;
983  return nullptr;
984  }
985 
986  /// Returns true if an interleaved group that may access memory
987  /// out-of-bounds requires a scalar epilogue iteration for correctness.
988  bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
989 
990 private:
991  /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
992  /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
993  /// The interleaved access analysis can also add new predicates (for example
994  /// by versioning strides of pointers).
996 
997  Loop *TheLoop;
998  DominatorTree *DT;
999  LoopInfo *LI;
1000  const LoopAccessInfo *LAI;
1001 
1002  /// True if the loop may contain non-reversed interleaved groups with
1003  /// out-of-bounds accesses. We ensure we don't speculatively access memory
1004  /// out-of-bounds by executing at least one scalar epilogue iteration.
1005  bool RequiresScalarEpilogue = false;
1006 
1007  /// Holds the relationships between the members and the interleave group.
1008  DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
1009 
1010  /// Holds dependences among the memory accesses in the loop. It maps a source
1011  /// access to a set of dependent sink accesses.
1013 
1014  /// The descriptor for a strided memory access.
1015  struct StrideDescriptor {
1016  StrideDescriptor() = default;
1017  StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
1018  unsigned Align)
1019  : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
1020 
1021  // The access's stride. It is negative for a reverse access.
1022  int64_t Stride = 0;
1023 
1024  // The scalar expression of this access.
1025  const SCEV *Scev = nullptr;
1026 
1027  // The size of the memory object.
1028  uint64_t Size = 0;
1029 
1030  // The alignment of this access.
1031  unsigned Align = 0;
1032  };
1033 
1034  /// A type for holding instructions and their stride descriptors.
1035  using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
1036 
1037  /// Create a new interleave group with the given instruction \p Instr,
1038  /// stride \p Stride and alignment \p Align.
1039  ///
1040  /// \returns the newly created interleave group.
1041  InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
1042  unsigned Align) {
1043  assert(!InterleaveGroupMap.count(Instr) &&
1044  "Already in an interleaved access group");
1045  InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
1046  return InterleaveGroupMap[Instr];
1047  }
1048 
1049  /// Release the group and remove all the relationships.
1050  void releaseGroup(InterleaveGroup *Group) {
1051  for (unsigned i = 0; i < Group->getFactor(); i++)
1052  if (Instruction *Member = Group->getMember(i))
1053  InterleaveGroupMap.erase(Member);
1054 
1055  delete Group;
1056  }
1057 
1058  /// Collect all the accesses with a constant stride in program order.
1059  void collectConstStrideAccesses(
1061  const ValueToValueMap &Strides);
1062 
1063  /// Returns true if \p Stride is allowed in an interleaved group.
1064  static bool isStrided(int Stride) {
1065  unsigned Factor = std::abs(Stride);
1066  return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1067  }
1068 
1069  /// Returns true if \p BB is a predicated block.
1070  bool isPredicated(BasicBlock *BB) const {
1071  return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1072  }
1073 
1074  /// Returns true if LoopAccessInfo can be used for dependence queries.
1075  bool areDependencesValid() const {
1076  return LAI && LAI->getDepChecker().getDependences();
1077  }
1078 
1079  /// Returns true if memory accesses \p A and \p B can be reordered, if
1080  /// necessary, when constructing interleaved groups.
1081  ///
1082  /// \p A must precede \p B in program order. We return false if reordering is
1083  /// not necessary or is prevented because \p A and \p B may be dependent.
1084  bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1085  StrideEntry *B) const {
1086  // Code motion for interleaved accesses can potentially hoist strided loads
1087  // and sink strided stores. The code below checks the legality of the
1088  // following two conditions:
1089  //
1090  // 1. Potentially moving a strided load (B) before any store (A) that
1091  // precedes B, or
1092  //
1093  // 2. Potentially moving a strided store (A) after any load or store (B)
1094  // that A precedes.
1095  //
1096  // It's legal to reorder A and B if we know there isn't a dependence from A
1097  // to B. Note that this determination is conservative since some
1098  // dependences could potentially be reordered safely.
1099 
1100  // A is potentially the source of a dependence.
1101  auto *Src = A->first;
1102  auto SrcDes = A->second;
1103 
1104  // B is potentially the sink of a dependence.
1105  auto *Sink = B->first;
1106  auto SinkDes = B->second;
1107 
1108  // Code motion for interleaved accesses can't violate WAR dependences.
1109  // Thus, reordering is legal if the source isn't a write.
1110  if (!Src->mayWriteToMemory())
1111  return true;
1112 
1113  // At least one of the accesses must be strided.
1114  if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1115  return true;
1116 
1117  // If dependence information is not available from LoopAccessInfo,
1118  // conservatively assume the instructions can't be reordered.
1119  if (!areDependencesValid())
1120  return false;
1121 
1122  // If we know there is a dependence from source to sink, assume the
1123  // instructions can't be reordered. Otherwise, reordering is legal.
1124  return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
1125  }
1126 
1127  /// Collect the dependences from LoopAccessInfo.
1128  ///
1129  /// We process the dependences once during the interleaved access analysis to
1130  /// enable constant-time dependence queries.
1131  void collectDependences() {
1132  if (!areDependencesValid())
1133  return;
1134  auto *Deps = LAI->getDepChecker().getDependences();
1135  for (auto Dep : *Deps)
1136  Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1137  }
1138 };
1139 
1140 } // end anonymous namespace
1141 
1143  const LoopVectorizeHints &LH,
1145  LH.emitRemarkWithHints();
1146 
1148  if (LH.getWidth() != 1)
1150  DEBUG_TYPE, "FailedRequestedVectorization",
1151  L->getStartLoc(), L->getHeader())
1152  << "loop not vectorized: "
1153  << "failed explicitly specified loop vectorization");
1154  else if (LH.getInterleave() != 1)
1156  DEBUG_TYPE, "FailedRequestedInterleaving", L->getStartLoc(),
1157  L->getHeader())
1158  << "loop not interleaved: "
1159  << "failed explicitly specified loop interleaving");
1160  }
1161 }
1162 
1163 namespace llvm {
1164 
1165 /// LoopVectorizationCostModel - estimates the expected speedups due to
1166 /// vectorization.
1167 /// In many cases vectorization is not profitable. This can happen because of
1168 /// a number of reasons. In this class we mainly attempt to predict the
1169 /// expected speedup/slowdowns due to the supported instruction set. We use the
1170 /// TargetTransformInfo to query the different backends for the cost of
1171 /// different operations.
1173 public:
1176  const TargetTransformInfo &TTI,
1177  const TargetLibraryInfo *TLI, DemandedBits *DB,
1180  const LoopVectorizeHints *Hints,
1181  InterleavedAccessInfo &IAI)
1182  : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1183  AC(AC), ORE(ORE), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {}
1184 
1185  /// \return An upper bound for the vectorization factor, or None if
1186  /// vectorization should be avoided up front.
1187  Optional<unsigned> computeMaxVF(bool OptForSize);
1188 
1189  /// \return The most profitable vectorization factor and the cost of that VF.
1190  /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1191  /// then this vectorization factor will be selected if vectorization is
1192  /// possible.
1193  VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
1194 
1195  /// Setup cost-based decisions for user vectorization factor.
1196  void selectUserVectorizationFactor(unsigned UserVF) {
1197  collectUniformsAndScalars(UserVF);
1198  collectInstsToScalarize(UserVF);
1199  }
1200 
1201  /// \return The size (in bits) of the smallest and widest types in the code
1202  /// that needs to be vectorized. We ignore values that remain scalar such as
1203  /// 64 bit loop indices.
1204  std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1205 
1206  /// \return The desired interleave count.
1207  /// If interleave count has been specified by metadata it will be returned.
1208  /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1209  /// are the selected vectorization factor and the cost of the selected VF.
1210  unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1211  unsigned LoopCost);
1212 
1213  /// Memory access instruction may be vectorized in more than one way.
1214  /// Form of instruction after vectorization depends on cost.
1215  /// This function takes cost-based decisions for Load/Store instructions
1216  /// and collects them in a map. This decisions map is used for building
1217  /// the lists of loop-uniform and loop-scalar instructions.
1218  /// The calculated cost is saved with widening decision in order to
1219  /// avoid redundant calculations.
1220  void setCostBasedWideningDecision(unsigned VF);
1221 
1222  /// A struct that represents some properties of the register usage
1223  /// of a loop.
1224  struct RegisterUsage {
1225  /// Holds the number of loop invariant values that are used in the loop.
1227 
1228  /// Holds the maximum number of concurrent live intervals in the loop.
1229  unsigned MaxLocalUsers;
1230  };
1231 
1232  /// \return Returns information about the register usages of the loop for the
1233  /// given vectorization factors.
1234  SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1235 
1236  /// Collect values we want to ignore in the cost model.
1237  void collectValuesToIgnore();
1238 
1239  /// \returns The smallest bitwidth each instruction can be represented with.
1240  /// The vector equivalents of these instructions should be truncated to this
1241  /// type.
1243  return MinBWs;
1244  }
1245 
1246  /// \returns True if it is more profitable to scalarize instruction \p I for
1247  /// vectorization factor \p VF.
1248  bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
1249  assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.");
1250  auto Scalars = InstsToScalarize.find(VF);
1251  assert(Scalars != InstsToScalarize.end() &&
1252  "VF not yet analyzed for scalarization profitability");
1253  return Scalars->second.count(I);
1254  }
1255 
1256  /// Returns true if \p I is known to be uniform after vectorization.
1257  bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
1258  if (VF == 1)
1259  return true;
1260  assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity");
1261  auto UniformsPerVF = Uniforms.find(VF);
1262  return UniformsPerVF->second.count(I);
1263  }
1264 
1265  /// Returns true if \p I is known to be scalar after vectorization.
1266  bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
1267  if (VF == 1)
1268  return true;
1269  assert(Scalars.count(VF) && "Scalar values are not calculated for VF");
1270  auto ScalarsPerVF = Scalars.find(VF);
1271  return ScalarsPerVF->second.count(I);
1272  }
1273 
1274  /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1275  /// for vectorization factor \p VF.
1276  bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
1277  return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1278  !isScalarAfterVectorization(I, VF);
1279  }
1280 
1281  /// Decision that was taken during cost calculation for memory instruction.
1284  CM_Widen, // For consecutive accesses with stride +1.
1285  CM_Widen_Reverse, // For consecutive accesses with stride -1.
1288  CM_Scalarize
1289  };
1290 
1291  /// Save vectorization decision \p W and \p Cost taken by the cost model for
1292  /// instruction \p I and vector width \p VF.
1294  unsigned Cost) {
1295  assert(VF >= 2 && "Expected VF >=2");
1296  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1297  }
1298 
1299  /// Save vectorization decision \p W and \p Cost taken by the cost model for
1300  /// interleaving group \p Grp and vector width \p VF.
1301  void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
1302  InstWidening W, unsigned Cost) {
1303  assert(VF >= 2 && "Expected VF >=2");
1304  /// Broadcast this decicion to all instructions inside the group.
1305  /// But the cost will be assigned to one instruction only.
1306  for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1307  if (auto *I = Grp->getMember(i)) {
1308  if (Grp->getInsertPos() == I)
1309  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1310  else
1311  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1312  }
1313  }
1314  }
1315 
1316  /// Return the cost model decision for the given instruction \p I and vector
1317  /// width \p VF. Return CM_Unknown if this instruction did not pass
1318  /// through the cost modeling.
1320  assert(VF >= 2 && "Expected VF >=2");
1321  std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1322  auto Itr = WideningDecisions.find(InstOnVF);
1323  if (Itr == WideningDecisions.end())
1324  return CM_Unknown;
1325  return Itr->second.first;
1326  }
1327 
1328  /// Return the vectorization cost for the given instruction \p I and vector
1329  /// width \p VF.
1330  unsigned getWideningCost(Instruction *I, unsigned VF) {
1331  assert(VF >= 2 && "Expected VF >=2");
1332  std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1333  assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated");
1334  return WideningDecisions[InstOnVF].second;
1335  }
1336 
1337  /// Return True if instruction \p I is an optimizable truncate whose operand
1338  /// is an induction variable. Such a truncate will be removed by adding a new
1339  /// induction variable with the destination type.
1340  bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
1341  // If the instruction is not a truncate, return false.
1342  auto *Trunc = dyn_cast<TruncInst>(I);
1343  if (!Trunc)
1344  return false;
1345 
1346  // Get the source and destination types of the truncate.
1347  Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1348  Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1349 
1350  // If the truncate is free for the given types, return false. Replacing a
1351  // free truncate with an induction variable would add an induction variable
1352  // update instruction to each iteration of the loop. We exclude from this
1353  // check the primary induction variable since it will need an update
1354  // instruction regardless.
1355  Value *Op = Trunc->getOperand(0);
1356  if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1357  return false;
1358 
1359  // If the truncated value is not an induction variable, return false.
1360  return Legal->isInductionPhi(Op);
1361  }
1362 
1363  /// Collects the instructions to scalarize for each predicated instruction in
1364  /// the loop.
1365  void collectInstsToScalarize(unsigned VF);
1366 
1367  /// Collect Uniform and Scalar values for the given \p VF.
1368  /// The sets depend on CM decision for Load/Store instructions
1369  /// that may be vectorized as interleave, gather-scatter or scalarized.
1370  void collectUniformsAndScalars(unsigned VF) {
1371  // Do the analysis once.
1372  if (VF == 1 || Uniforms.count(VF))
1373  return;
1374  setCostBasedWideningDecision(VF);
1375  collectLoopUniforms(VF);
1376  collectLoopScalars(VF);
1377  }
1378 
1379  /// Returns true if the target machine supports masked store operation
1380  /// for the given \p DataType and kind of access to \p Ptr.
1382  return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType);
1383  }
1384 
1385  /// Returns true if the target machine supports masked load operation
1386  /// for the given \p DataType and kind of access to \p Ptr.
1388  return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType);
1389  }
1390 
1391  /// Returns true if the target machine supports masked scatter operation
1392  /// for the given \p DataType.
1394  return TTI.isLegalMaskedScatter(DataType);
1395  }
1396 
1397  /// Returns true if the target machine supports masked gather operation
1398  /// for the given \p DataType.
1400  return TTI.isLegalMaskedGather(DataType);
1401  }
1402 
1403  /// Returns true if the target machine can represent \p V as a masked gather
1404  /// or scatter operation.
1406  bool LI = isa<LoadInst>(V);
1407  bool SI = isa<StoreInst>(V);
1408  if (!LI && !SI)
1409  return false;
1410  auto *Ty = getMemInstValueType(V);
1411  return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1412  }
1413 
1414  /// Returns true if \p I is an instruction that will be scalarized with
1415  /// predication. Such instructions include conditional stores and
1416  /// instructions that may divide by zero.
1417  bool isScalarWithPredication(Instruction *I);
1418 
1419  /// Returns true if \p I is a memory instruction with consecutive memory
1420  /// access that can be widened.
1421  bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
1422 
1423  /// Check if \p Instr belongs to any interleaved access group.
1425  return InterleaveInfo.isInterleaved(Instr);
1426  }
1427 
1428  /// Get the interleaved access group that \p Instr belongs to.
1430  return InterleaveInfo.getInterleaveGroup(Instr);
1431  }
1432 
1433  /// Returns true if an interleaved group requires a scalar iteration
1434  /// to handle accesses with gaps.
1435  bool requiresScalarEpilogue() const {
1436  return InterleaveInfo.requiresScalarEpilogue();
1437  }
1438 
1439 private:
1440  unsigned NumPredStores = 0;
1441 
1442  /// \return An upper bound for the vectorization factor, larger than zero.
1443  /// One is returned if vectorization should best be avoided due to cost.
1444  unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
1445 
1446  /// The vectorization cost is a combination of the cost itself and a boolean
1447  /// indicating whether any of the contributing operations will actually
1448  /// operate on
1449  /// vector values after type legalization in the backend. If this latter value
1450  /// is
1451  /// false, then all operations will be scalarized (i.e. no vectorization has
1452  /// actually taken place).
1453  using VectorizationCostTy = std::pair<unsigned, bool>;
1454 
1455  /// Returns the expected execution cost. The unit of the cost does
1456  /// not matter because we use the 'cost' units to compare different
1457  /// vector widths. The cost that is returned is *not* normalized by
1458  /// the factor width.
1459  VectorizationCostTy expectedCost(unsigned VF);
1460 
1461  /// Returns the execution time cost of an instruction for a given vector
1462  /// width. Vector width of one means scalar.
1463  VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
1464 
1465  /// The cost-computation logic from getInstructionCost which provides
1466  /// the vector type as an output parameter.
1467  unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
1468 
1469  /// Calculate vectorization cost of memory instruction \p I.
1470  unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
1471 
1472  /// The cost computation for scalarized memory instruction.
1473  unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
1474 
1475  /// The cost computation for interleaving group of memory instructions.
1476  unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
1477 
1478  /// The cost computation for Gather/Scatter instruction.
1479  unsigned getGatherScatterCost(Instruction *I, unsigned VF);
1480 
1481  /// The cost computation for widening instruction \p I with consecutive
1482  /// memory access.
1483  unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
1484 
1485  /// The cost calculation for Load instruction \p I with uniform pointer -
1486  /// scalar load + broadcast.
1487  unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
1488 
1489  /// Returns whether the instruction is a load or store and will be a emitted
1490  /// as a vector operation.
1491  bool isConsecutiveLoadOrStore(Instruction *I);
1492 
1493  /// Returns true if an artificially high cost for emulated masked memrefs
1494  /// should be used.
1495  bool useEmulatedMaskMemRefHack(Instruction *I);
1496 
1497  /// Create an analysis remark that explains why vectorization failed
1498  ///
1499  /// \p RemarkName is the identifier for the remark. \return the remark object
1500  /// that can be streamed to.
1501  OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
1502  return createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1503  RemarkName, TheLoop);
1504  }
1505 
1506  /// Map of scalar integer values to the smallest bitwidth they can be legally
1507  /// represented as. The vector equivalents of these values should be truncated
1508  /// to this type.
1510 
1511  /// A type representing the costs for instructions if they were to be
1512  /// scalarized rather than vectorized. The entries are Instruction-Cost
1513  /// pairs.
1515 
1516  /// A set containing all BasicBlocks that are known to present after
1517  /// vectorization as a predicated block.
1518  SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1519 
1520  /// A map holding scalar costs for different vectorization factors. The
1521  /// presence of a cost for an instruction in the mapping indicates that the
1522  /// instruction will be scalarized when vectorizing with the associated
1523  /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1524  DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
1525 
1526  /// Holds the instructions known to be uniform after vectorization.
1527  /// The data is collected per VF.
1529 
1530  /// Holds the instructions known to be scalar after vectorization.
1531  /// The data is collected per VF.
1533 
1534  /// Holds the instructions (address computations) that are forced to be
1535  /// scalarized.
1537 
1538  /// Returns the expected difference in cost from scalarizing the expression
1539  /// feeding a predicated instruction \p PredInst. The instructions to
1540  /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1541  /// non-negative return value implies the expression will be scalarized.
1542  /// Currently, only single-use chains are considered for scalarization.
1543  int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1544  unsigned VF);
1545 
1546  /// Collect the instructions that are uniform after vectorization. An
1547  /// instruction is uniform if we represent it with a single scalar value in
1548  /// the vectorized loop corresponding to each vector iteration. Examples of
1549  /// uniform instructions include pointer operands of consecutive or
1550  /// interleaved memory accesses. Note that although uniformity implies an
1551  /// instruction will be scalar, the reverse is not true. In general, a
1552  /// scalarized instruction will be represented by VF scalar values in the
1553  /// vectorized loop, each corresponding to an iteration of the original
1554  /// scalar loop.
1555  void collectLoopUniforms(unsigned VF);
1556 
1557  /// Collect the instructions that are scalar after vectorization. An
1558  /// instruction is scalar if it is known to be uniform or will be scalarized
1559  /// during vectorization. Non-uniform scalarized instructions will be
1560  /// represented by VF values in the vectorized loop, each corresponding to an
1561  /// iteration of the original scalar loop.
1562  void collectLoopScalars(unsigned VF);
1563 
1564  /// Keeps cost model vectorization decision and cost for instructions.
1565  /// Right now it is used for memory instructions only.
1567  std::pair<InstWidening, unsigned>>;
1568 
1569  DecisionList WideningDecisions;
1570 
1571 public:
1572  /// The loop that we evaluate.
1574 
1575  /// Predicated scalar evolution analysis.
1577 
1578  /// Loop Info analysis.
1580 
1581  /// Vectorization legality.
1583 
1584  /// Vector target information.
1586 
1587  /// Target Library Info.
1589 
1590  /// Demanded bits analysis.
1592 
1593  /// Assumption cache.
1595 
1596  /// Interface to emit optimization remarks.
1598 
1600 
1601  /// Loop Vectorize Hint.
1603 
1604  /// The interleave access information contains groups of interleaved accesses
1605  /// with the same stride and close to each other.
1606  InterleavedAccessInfo &InterleaveInfo;
1607 
1608  /// Values to ignore in the cost model.
1610 
1611  /// Values to ignore in the cost model when VF > 1.
1613 };
1614 
1615 } // end namespace llvm
1616 
1617 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
1618 // vectorization. The loop needs to be annotated with #pragma omp simd
1619 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
1620 // vector length information is not provided, vectorization is not considered
1621 // explicit. Interleave hints are not allowed either. These limitations will be
1622 // relaxed in the future.
1623 // Please, note that we are currently forced to abuse the pragma 'clang
1624 // vectorize' semantics. This pragma provides *auto-vectorization hints*
1625 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
1626 // provides *explicit vectorization hints* (LV can bypass legal checks and
1627 // assume that vectorization is legal). However, both hints are implemented
1628 // using the same metadata (llvm.loop.vectorize, processed by
1629 // LoopVectorizeHints). This will be fixed in the future when the native IR
1630 // representation for pragma 'omp simd' is introduced.
1631 static bool isExplicitVecOuterLoop(Loop *OuterLp,
1633  assert(!OuterLp->empty() && "This is not an outer loop");
1634  LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
1635 
1636  // Only outer loops with an explicit vectorization hint are supported.
1637  // Unannotated outer loops are ignored.
1638  if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
1639  return false;
1640 
1641  Function *Fn = OuterLp->getHeader()->getParent();
1642  if (!Hints.allowVectorization(Fn, OuterLp, false /*AlwaysVectorize*/)) {
1643  LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
1644  return false;
1645  }
1646 
1647  if (!Hints.getWidth()) {
1648  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No user vector width.\n");
1649  emitMissedWarning(Fn, OuterLp, Hints, ORE);
1650  return false;
1651  }
1652 
1653  if (Hints.getInterleave() > 1) {
1654  // TODO: Interleave support is future work.
1655  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
1656  "outer loops.\n");
1657  emitMissedWarning(Fn, OuterLp, Hints, ORE);
1658  return false;
1659  }
1660 
1661  return true;
1662 }
1663 
1667  // Collect inner loops and outer loops without irreducible control flow. For
1668  // now, only collect outer loops that have explicit vectorization hints. If we
1669  // are stress testing the VPlan H-CFG construction, we collect the outermost
1670  // loop of every loop nest.
1671  if (L.empty() || VPlanBuildStressTest ||
1673  LoopBlocksRPO RPOT(&L);
1674  RPOT.perform(LI);
1675  if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
1676  V.push_back(&L);
1677  // TODO: Collect inner loops inside marked outer loops in case
1678  // vectorization fails for the outer loop. Do not invoke
1679  // 'containsIrreducibleCFG' again for inner loops when the outer loop is
1680  // already known to be reducible. We can use an inherited attribute for
1681  // that.
1682  return;
1683  }
1684  }
1685  for (Loop *InnerL : L)
1686  collectSupportedLoops(*InnerL, LI, ORE, V);
1687 }
1688 
1689 namespace {
1690 
1691 /// The LoopVectorize Pass.
1692 struct LoopVectorize : public FunctionPass {
1693  /// Pass identification, replacement for typeid
1694  static char ID;
1695 
1696  LoopVectorizePass Impl;
1697 
1698  explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1699  : FunctionPass(ID) {
1700  Impl.DisableUnrolling = NoUnrolling;
1701  Impl.AlwaysVectorize = AlwaysVectorize;
1703  }
1704 
1705  bool runOnFunction(Function &F) override {
1706  if (skipFunction(F))
1707  return false;
1708 
1709  auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1710  auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1711  auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1712  auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1713  auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1714  auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1715  auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
1716  auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1717  auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1718  auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
1719  auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
1720  auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1721 
1722  std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1723  [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
1724 
1725  return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
1726  GetLAA, *ORE);
1727  }
1728 
1729  void getAnalysisUsage(AnalysisUsage &AU) const override {
1744  }
1745 };
1746 
1747 } // end anonymous namespace
1748 
1749 //===----------------------------------------------------------------------===//
1750 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1751 // LoopVectorizationCostModel and LoopVectorizationPlanner.
1752 //===----------------------------------------------------------------------===//
1753 
1755  // We need to place the broadcast of invariant variables outside the loop,
1756  // but only if it's proven safe to do so. Else, broadcast will be inside
1757  // vector loop body.
1758  Instruction *Instr = dyn_cast<Instruction>(V);
1759  bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
1760  (!Instr ||
1762  // Place the code for broadcasting invariant variables in the new preheader.
1764  if (SafeToHoist)
1766 
1767  // Broadcast the scalar into all locations in the vector.
1768  Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1769 
1770  return Shuf;
1771 }
1772 
1774  const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
1775  assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1776  "Expected either an induction phi-node or a truncate of it!");
1777  Value *Start = II.getStartValue();
1778 
1779  // Construct the initial value of the vector IV in the vector loop preheader
1780  auto CurrIP = Builder.saveIP();
1782  if (isa<TruncInst>(EntryVal)) {
1783  assert(Start->getType()->isIntegerTy() &&
1784  "Truncation requires an integer type");
1785  auto *TruncType = cast<IntegerType>(EntryVal->getType());
1786  Step = Builder.CreateTrunc(Step, TruncType);
1787  Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
1788  }
1789  Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
1790  Value *SteppedStart =
1791  getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
1792 
1793  // We create vector phi nodes for both integer and floating-point induction
1794  // variables. Here, we determine the kind of arithmetic we will perform.
1795  Instruction::BinaryOps AddOp;
1796  Instruction::BinaryOps MulOp;
1797  if (Step->getType()->isIntegerTy()) {
1798  AddOp = Instruction::Add;
1799  MulOp = Instruction::Mul;
1800  } else {
1801  AddOp = II.getInductionOpcode();
1802  MulOp = Instruction::FMul;
1803  }
1804 
1805  // Multiply the vectorization factor by the step using integer or
1806  // floating-point arithmetic as appropriate.
1807  Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
1808  Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
1809 
1810  // Create a vector splat to use in the induction update.
1811  //
1812  // FIXME: If the step is non-constant, we create the vector splat with
1813  // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
1814  // handle a constant vector splat.
1815  Value *SplatVF = isa<Constant>(Mul)
1816  ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
1817  : Builder.CreateVectorSplat(VF, Mul);
1818  Builder.restoreIP(CurrIP);
1819 
1820  // We may need to add the step a number of times, depending on the unroll
1821  // factor. The last of those goes into the PHI.
1822  PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
1824  VecInd->setDebugLoc(EntryVal->getDebugLoc());
1825  Instruction *LastInduction = VecInd;
1826  for (unsigned Part = 0; Part < UF; ++Part) {
1827  VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
1828 
1829  if (isa<TruncInst>(EntryVal))
1830  addMetadata(LastInduction, EntryVal);
1831  recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
1832 
1833  LastInduction = cast<Instruction>(addFastMathFlag(
1834  Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
1835  LastInduction->setDebugLoc(EntryVal->getDebugLoc());
1836  }
1837 
1838  // Move the last step to the end of the latch block. This ensures consistent
1839  // placement of all induction updates.
1840  auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
1841  auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
1842  auto *ICmp = cast<Instruction>(Br->getCondition());
1843  LastInduction->moveBefore(ICmp);
1844  LastInduction->setName("vec.ind.next");
1845 
1846  VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
1847  VecInd->addIncoming(LastInduction, LoopVectorLatch);
1848 }
1849 
1851  return Cost->isScalarAfterVectorization(I, VF) ||
1853 }
1854 
1857  return true;
1858  auto isScalarInst = [&](User *U) -> bool {
1859  auto *I = cast<Instruction>(U);
1861  };
1862  return llvm::any_of(IV->users(), isScalarInst);
1863 }
1864 
1866  const InductionDescriptor &ID, const Instruction *EntryVal,
1867  Value *VectorLoopVal, unsigned Part, unsigned Lane) {
1868  assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1869  "Expected either an induction phi-node or a truncate of it!");
1870 
1871  // This induction variable is not the phi from the original loop but the
1872  // newly-created IV based on the proof that casted Phi is equal to the
1873  // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
1874  // re-uses the same InductionDescriptor that original IV uses but we don't
1875  // have to do any recording in this case - that is done when original IV is
1876  // processed.
1877  if (isa<TruncInst>(EntryVal))
1878  return;
1879 
1880  const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
1881  if (Casts.empty())
1882  return;
1883  // Only the first Cast instruction in the Casts vector is of interest.
1884  // The rest of the Casts (if exist) have no uses outside the
1885  // induction update chain itself.
1886  Instruction *CastInst = *Casts.begin();
1887  if (Lane < UINT_MAX)
1888  VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
1889  else
1890  VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
1891 }
1892 
1894  assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
1895  "Primary induction variable must have an integer type");
1896 
1897  auto II = Legal->getInductionVars()->find(IV);
1898  assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
1899 
1900  auto ID = II->second;
1901  assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
1902 
1903  // The scalar value to broadcast. This will be derived from the canonical
1904  // induction variable.
1905  Value *ScalarIV = nullptr;
1906 
1907  // The value from the original loop to which we are mapping the new induction
1908  // variable.
1909  Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
1910 
1911  // True if we have vectorized the induction variable.
1912  auto VectorizedIV = false;
1913 
1914  // Determine if we want a scalar version of the induction variable. This is
1915  // true if the induction variable itself is not widened, or if it has at
1916  // least one user in the loop that is not widened.
1917  auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
1918 
1919  // Generate code for the induction step. Note that induction steps are
1920  // required to be loop-invariant
1921  assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
1922  "Induction step should be loop invariant");
1923  auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
1924  Value *Step = nullptr;
1925  if (PSE.getSE()->isSCEVable(IV->getType())) {
1926  SCEVExpander Exp(*PSE.getSE(), DL, "induction");
1927  Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
1929  } else {
1930  Step = cast<SCEVUnknown>(ID.getStep())->getValue();
1931  }
1932 
1933  // Try to create a new independent vector induction variable. If we can't
1934  // create the phi node, we will splat the scalar induction variable in each
1935  // loop iteration.
1936  if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
1937  createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
1938  VectorizedIV = true;
1939  }
1940 
1941  // If we haven't yet vectorized the induction variable, or if we will create
1942  // a scalar one, we need to define the scalar induction variable and step
1943  // values. If we were given a truncation type, truncate the canonical
1944  // induction variable and step. Otherwise, derive these values from the
1945  // induction descriptor.
1946  if (!VectorizedIV || NeedsScalarIV) {
1947  ScalarIV = Induction;
1948  if (IV != OldInduction) {
1949  ScalarIV = IV->getType()->isIntegerTy()
1951  : Builder.CreateCast(Instruction::SIToFP, Induction,
1952  IV->getType());
1953  ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
1954  ScalarIV->setName("offset.idx");
1955  }
1956  if (Trunc) {
1957  auto *TruncType = cast<IntegerType>(Trunc->getType());
1958  assert(Step->getType()->isIntegerTy() &&
1959  "Truncation requires an integer step");
1960  ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
1961  Step = Builder.CreateTrunc(Step, TruncType);
1962  }
1963  }
1964 
1965  // If we haven't yet vectorized the induction variable, splat the scalar
1966  // induction variable, and build the necessary step vectors.
1967  // TODO: Don't do it unless the vectorized IV is really required.
1968  if (!VectorizedIV) {
1969  Value *Broadcasted = getBroadcastInstrs(ScalarIV);
1970  for (unsigned Part = 0; Part < UF; ++Part) {
1971  Value *EntryPart =
1972  getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
1973  VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
1974  if (Trunc)
1975  addMetadata(EntryPart, Trunc);
1976  recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
1977  }
1978  }
1979 
1980  // If an induction variable is only used for counting loop iterations or
1981  // calculating addresses, it doesn't need to be widened. Create scalar steps
1982  // that can be used by instructions we will later scalarize. Note that the
1983  // addition of the scalar steps will not increase the number of instructions
1984  // in the loop in the common case prior to InstCombine. We will be trading
1985  // one vector extract for each scalar step.
1986  if (NeedsScalarIV)
1987  buildScalarSteps(ScalarIV, Step, EntryVal, ID);
1988 }
1989 
1991  Instruction::BinaryOps BinOp) {
1992  // Create and check the types.
1993  assert(Val->getType()->isVectorTy() && "Must be a vector");
1994  int VLen = Val->getType()->getVectorNumElements();
1995 
1996  Type *STy = Val->getType()->getScalarType();
1997  assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
1998  "Induction Step must be an integer or FP");
1999  assert(Step->getType() == STy && "Step has wrong type");
2000 
2002 
2003  if (STy->isIntegerTy()) {
2004  // Create a vector of consecutive numbers from zero to VF.
2005  for (int i = 0; i < VLen; ++i)
2006  Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2007 
2008  // Add the consecutive indices to the vector value.
2009  Constant *Cv = ConstantVector::get(Indices);
2010  assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2011  Step = Builder.CreateVectorSplat(VLen, Step);
2012  assert(Step->getType() == Val->getType() && "Invalid step vec");
2013  // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2014  // which can be found from the original scalar operations.
2015  Step = Builder.CreateMul(Cv, Step);
2016  return Builder.CreateAdd(Val, Step, "induction");
2017  }
2018 
2019  // Floating point induction.
2020  assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2021  "Binary Opcode should be specified for FP induction");
2022  // Create a vector of consecutive numbers from zero to VF.
2023  for (int i = 0; i < VLen; ++i)
2024  Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2025 
2026  // Add the consecutive indices to the vector value.
2027  Constant *Cv = ConstantVector::get(Indices);
2028 
2029  Step = Builder.CreateVectorSplat(VLen, Step);
2030 
2031  // Floating point operations had to be 'fast' to enable the induction.
2032  FastMathFlags Flags;
2033  Flags.setFast();
2034 
2035  Value *MulOp = Builder.CreateFMul(Cv, Step);
2036  if (isa<Instruction>(MulOp))
2037  // Have to check, MulOp may be a constant
2038  cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2039 
2040  Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2041  if (isa<Instruction>(BOp))
2042  cast<Instruction>(BOp)->setFastMathFlags(Flags);
2043  return BOp;
2044 }
2045 
2047  Instruction *EntryVal,
2048  const InductionDescriptor &ID) {
2049  // We shouldn't have to build scalar steps if we aren't vectorizing.
2050  assert(VF > 1 && "VF should be greater than one");
2051 
2052  // Get the value type and ensure it and the step have the same integer type.
2053  Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2054  assert(ScalarIVTy == Step->getType() &&
2055  "Val and Step should have the same type");
2056 
2057  // We build scalar steps for both integer and floating-point induction
2058  // variables. Here, we determine the kind of arithmetic we will perform.
2059  Instruction::BinaryOps AddOp;
2060  Instruction::BinaryOps MulOp;
2061  if (ScalarIVTy->isIntegerTy()) {
2062  AddOp = Instruction::Add;
2063  MulOp = Instruction::Mul;
2064  } else {
2065  AddOp = ID.getInductionOpcode();
2066  MulOp = Instruction::FMul;
2067  }
2068 
2069  // Determine the number of scalars we need to generate for each unroll
2070  // iteration. If EntryVal is uniform, we only need to generate the first
2071  // lane. Otherwise, we generate all VF values.
2072  unsigned Lanes =
2073  Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
2074  : VF;
2075  // Compute the scalar steps and save the results in VectorLoopValueMap.
2076  for (unsigned Part = 0; Part < UF; ++Part) {
2077  for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2078  auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2079  auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2080  auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2081  VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
2082  recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
2083  }
2084  }
2085 }
2086 
2088  assert(V != Induction && "The new induction variable should not be used.");
2089  assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2090  assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2091 
2092  // If we have a stride that is replaced by one, do it here.
2093  if (Legal->hasStride(V))
2094  V = ConstantInt::get(V->getType(), 1);
2095 
2096  // If we have a vector mapped to this value, return it.
2097  if (VectorLoopValueMap.hasVectorValue(V, Part))
2098  return VectorLoopValueMap.getVectorValue(V, Part);
2099 
2100  // If the value has not been vectorized, check if it has been scalarized
2101  // instead. If it has been scalarized, and we actually need the value in
2102  // vector form, we will construct the vector values on demand.
2104  Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
2105 
2106  // If we've scalarized a value, that value should be an instruction.
2107  auto *I = cast<Instruction>(V);
2108 
2109  // If we aren't vectorizing, we can just copy the scalar map values over to
2110  // the vector map.
2111  if (VF == 1) {
2112  VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2113  return ScalarValue;
2114  }
2115 
2116  // Get the last scalar instruction we generated for V and Part. If the value
2117  // is known to be uniform after vectorization, this corresponds to lane zero
2118  // of the Part unroll iteration. Otherwise, the last instruction is the one
2119  // we created for the last vector lane of the Part unroll iteration.
2120  unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2121  auto *LastInst = cast<Instruction>(
2122  VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
2123 
2124  // Set the insert point after the last scalarized instruction. This ensures
2125  // the insertelement sequence will directly follow the scalar definitions.
2126  auto OldIP = Builder.saveIP();
2127  auto NewIP = std::next(BasicBlock::iterator(LastInst));
2128  Builder.SetInsertPoint(&*NewIP);
2129 
2130  // However, if we are vectorizing, we need to construct the vector values.
2131  // If the value is known to be uniform after vectorization, we can just
2132  // broadcast the scalar value corresponding to lane zero for each unroll
2133  // iteration. Otherwise, we construct the vector values using insertelement
2134  // instructions. Since the resulting vectors are stored in
2135  // VectorLoopValueMap, we will only generate the insertelements once.
2136  Value *VectorValue = nullptr;
2138  VectorValue = getBroadcastInstrs(ScalarValue);
2139  VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2140  } else {
2141  // Initialize packing with insertelements to start from undef.
2143  VectorLoopValueMap.setVectorValue(V, Part, Undef);
2144  for (unsigned Lane = 0; Lane < VF; ++Lane)
2145  packScalarIntoVectorValue(V, {Part, Lane});
2146  VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2147  }
2148  Builder.restoreIP(OldIP);
2149  return VectorValue;
2150  }
2151 
2152  // If this scalar is unknown, assume that it is a constant or that it is
2153  // loop invariant. Broadcast V and save the value for future uses.
2154  Value *B = getBroadcastInstrs(V);
2155  VectorLoopValueMap.setVectorValue(V, Part, B);
2156  return B;
2157 }
2158 
2159 Value *
2161  const VPIteration &Instance) {
2162  // If the value is not an instruction contained in the loop, it should
2163  // already be scalar.
2164  if (OrigLoop->isLoopInvariant(V))
2165  return V;
2166 
2167  assert(Instance.Lane > 0
2168  ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2169  : true && "Uniform values only have lane zero");
2170 
2171  // If the value from the original loop has not been vectorized, it is
2172  // represented by UF x VF scalar values in the new loop. Return the requested
2173  // scalar value.
2174  if (VectorLoopValueMap.hasScalarValue(V, Instance))
2175  return VectorLoopValueMap.getScalarValue(V, Instance);
2176 
2177  // If the value has not been scalarized, get its entry in VectorLoopValueMap
2178  // for the given unroll part. If this entry is not a vector type (i.e., the
2179  // vectorization factor is one), there is no need to generate an
2180  // extractelement instruction.
2181  auto *U = getOrCreateVectorValue(V, Instance.Part);
2182  if (!U->getType()->isVectorTy()) {
2183  assert(VF == 1 && "Value not scalarized has non-vector type");
2184  return U;
2185  }
2186 
2187  // Otherwise, the value from the original loop has been vectorized and is
2188  // represented by UF vector values. Extract and return the requested scalar
2189  // value from the appropriate vector lane.
2190  return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2191 }
2192 
2194  Value *V, const VPIteration &Instance) {
2195  assert(V != Induction && "The new induction variable should not be used.");
2196  assert(!V->getType()->isVectorTy() && "Can't pack a vector");
2197  assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2198 
2199  Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2200  Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2201  VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2202  Builder.getInt32(Instance.Lane));
2203  VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2204 }
2205 
2207  assert(Vec->getType()->isVectorTy() && "Invalid type");
2208  SmallVector<Constant *, 8> ShuffleMask;
2209  for (unsigned i = 0; i < VF; ++i)
2210  ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2211 
2212  return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2213  ConstantVector::get(ShuffleMask),
2214  "reverse");
2215 }
2216 
2217 // Try to vectorize the interleave group that \p Instr belongs to.
2218 //
2219 // E.g. Translate following interleaved load group (factor = 3):
2220 // for (i = 0; i < N; i+=3) {
2221 // R = Pic[i]; // Member of index 0
2222 // G = Pic[i+1]; // Member of index 1
2223 // B = Pic[i+2]; // Member of index 2
2224 // ... // do something to R, G, B
2225 // }
2226 // To:
2227 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2228 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2229 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2230 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2231 //
2232 // Or translate following interleaved store group (factor = 3):
2233 // for (i = 0; i < N; i+=3) {
2234 // ... do something to R, G, B
2235 // Pic[i] = R; // Member of index 0
2236 // Pic[i+1] = G; // Member of index 1
2237 // Pic[i+2] = B; // Member of index 2
2238 // }
2239 // To:
2240 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2241 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2242 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2243 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2244 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2246  const InterleaveGroup *Group = Cost->getInterleavedAccessGroup(Instr);
2247  assert(Group && "Fail to get an interleaved access group.");
2248 
2249  // Skip if current instruction is not the insert position.
2250  if (Instr != Group->getInsertPos())
2251  return;
2252 
2253  const DataLayout &DL = Instr->getModule()->getDataLayout();
2254  Value *Ptr = getLoadStorePointerOperand(Instr);
2255 
2256  // Prepare for the vector type of the interleaved load/store.
2257  Type *ScalarTy = getMemInstValueType(Instr);
2258  unsigned InterleaveFactor = Group->getFactor();
2259  Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2260  Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2261 
2262  // Prepare for the new pointers.
2264  SmallVector<Value *, 2> NewPtrs;
2265  unsigned Index = Group->getIndex(Instr);
2266 
2267  // If the group is reverse, adjust the index to refer to the last vector lane
2268  // instead of the first. We adjust the index from the first vector lane,
2269  // rather than directly getting the pointer for lane VF - 1, because the
2270  // pointer operand of the interleaved access is supposed to be uniform. For
2271  // uniform instructions, we're only required to generate a value for the
2272  // first vector lane in each unroll iteration.
2273  if (Group->isReverse())
2274  Index += (VF - 1) * Group->getFactor();
2275 
2276  bool InBounds = false;
2277  if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2278  InBounds = gep->isInBounds();
2279 
2280  for (unsigned Part = 0; Part < UF; Part++) {
2281  Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
2282 
2283  // Notice current instruction could be any index. Need to adjust the address
2284  // to the member of index 0.
2285  //
2286  // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2287  // b = A[i]; // Member of index 0
2288  // Current pointer is pointed to A[i+1], adjust it to A[i].
2289  //
2290  // E.g. A[i+1] = a; // Member of index 1
2291  // A[i] = b; // Member of index 0
2292  // A[i+2] = c; // Member of index 2 (Current instruction)
2293  // Current pointer is pointed to A[i+2], adjust it to A[i].
2294  NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2295  if (InBounds)
2296  cast<GetElementPtrInst>(NewPtr)->setIsInBounds(true);
2297 
2298  // Cast to the vector pointer type.
2299  NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2300  }
2301 
2302  setDebugLocFromInst(Builder, Instr);
2303  Value *UndefVec = UndefValue::get(VecTy);
2304 
2305  // Vectorize the interleaved load group.
2306  if (isa<LoadInst>(Instr)) {
2307  // For each unroll part, create a wide load for the group.
2308  SmallVector<Value *, 2> NewLoads;
2309  for (unsigned Part = 0; Part < UF; Part++) {
2310  auto *NewLoad = Builder.CreateAlignedLoad(
2311  NewPtrs[Part], Group->getAlignment(), "wide.vec");
2312  Group->addMetadata(NewLoad);
2313  NewLoads.push_back(NewLoad);
2314  }
2315 
2316  // For each member in the group, shuffle out the appropriate data from the
2317  // wide loads.
2318  for (unsigned I = 0; I < InterleaveFactor; ++I) {
2319  Instruction *Member = Group->getMember(I);
2320 
2321  // Skip the gaps in the group.
2322  if (!Member)
2323  continue;
2324 
2325  Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2326  for (unsigned Part = 0; Part < UF; Part++) {
2327  Value *StridedVec = Builder.CreateShuffleVector(
2328  NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2329 
2330  // If this member has different type, cast the result type.
2331  if (Member->getType() != ScalarTy) {
2332  VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2333  StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2334  }
2335 
2336  if (Group->isReverse())
2337  StridedVec = reverseVector(StridedVec);
2338 
2339  VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2340  }
2341  }
2342  return;
2343  }
2344 
2345  // The sub vector type for current instruction.
2346  VectorType *SubVT = VectorType::get(ScalarTy, VF);
2347 
2348  // Vectorize the interleaved store group.
2349  for (unsigned Part = 0; Part < UF; Part++) {
2350  // Collect the stored vector from each member.
2351  SmallVector<Value *, 4> StoredVecs;
2352  for (unsigned i = 0; i < InterleaveFactor; i++) {
2353  // Interleaved store group doesn't allow a gap, so each index has a member
2354  Instruction *Member = Group->getMember(i);
2355  assert(Member && "Fail to get a member from an interleaved store group");
2356 
2357  Value *StoredVec = getOrCreateVectorValue(
2358  cast<StoreInst>(Member)->getValueOperand(), Part);
2359  if (Group->isReverse())
2360  StoredVec = reverseVector(StoredVec);
2361 
2362  // If this member has different type, cast it to a unified type.
2363 
2364  if (StoredVec->getType() != SubVT)
2365  StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2366 
2367  StoredVecs.push_back(StoredVec);
2368  }
2369 
2370  // Concatenate all vectors into a wide vector.
2371  Value *WideVec = concatenateVectors(Builder, StoredVecs);
2372 
2373  // Interleave the elements in the wide vector.
2374  Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2375  Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2376  "interleaved.vec");
2377 
2378  Instruction *NewStoreInstr =
2379  Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2380 
2381  Group->addMetadata(NewStoreInstr);
2382  }
2383 }
2384 
2386  VectorParts *BlockInMask) {
2387  // Attempt to issue a wide load.
2388  LoadInst *LI = dyn_cast<LoadInst>(Instr);
2389  StoreInst *SI = dyn_cast<StoreInst>(Instr);
2390 
2391  assert((LI || SI) && "Invalid Load/Store instruction");
2392 
2394  Cost->getWideningDecision(Instr, VF);
2396  "CM decision should be taken at this point");
2398  return vectorizeInterleaveGroup(Instr);
2399 
2400  Type *ScalarDataTy = getMemInstValueType(Instr);
2401  Type *DataTy = VectorType::get(ScalarDataTy, VF);
2402  Value *Ptr = getLoadStorePointerOperand(Instr);
2403  unsigned Alignment = getMemInstAlignment(Instr);
2404  // An alignment of 0 means target abi alignment. We need to use the scalar's
2405  // target abi alignment in such a case.
2406  const DataLayout &DL = Instr->getModule()->getDataLayout();
2407  if (!Alignment)
2408  Alignment = DL.getABITypeAlignment(ScalarDataTy);
2409  unsigned AddressSpace = getMemInstAddressSpace(Instr);
2410 
2411  // Determine if the pointer operand of the access is either consecutive or
2412  // reverse consecutive.
2413  bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2414  bool ConsecutiveStride =
2415  Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2416  bool CreateGatherScatter =
2418 
2419  // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2420  // gather/scatter. Otherwise Decision should have been to Scalarize.
2421  assert((ConsecutiveStride || CreateGatherScatter) &&
2422  "The instruction should be scalarized");
2423 
2424  // Handle consecutive loads/stores.
2425  if (ConsecutiveStride)
2426  Ptr = getOrCreateScalarValue(Ptr, {0, 0});
2427 
2428  VectorParts Mask;
2429  bool isMaskRequired = BlockInMask;
2430  if (isMaskRequired)
2431  Mask = *BlockInMask;
2432 
2433  bool InBounds = false;
2434  if (auto *gep = dyn_cast<GetElementPtrInst>(
2435  getLoadStorePointerOperand(Instr)->stripPointerCasts()))
2436  InBounds = gep->isInBounds();
2437 
2438  const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2439  // Calculate the pointer for the specific unroll-part.
2440  GetElementPtrInst *PartPtr = nullptr;
2441 
2442  if (Reverse) {
2443  // If the address is consecutive but reversed, then the
2444  // wide store needs to start at the last vector element.
2445  PartPtr = cast<GetElementPtrInst>(
2446  Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)));
2447  PartPtr->setIsInBounds(InBounds);
2448  PartPtr = cast<GetElementPtrInst>(
2449  Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)));
2450  PartPtr->setIsInBounds(InBounds);
2451  if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2452  Mask[Part] = reverseVector(Mask[Part]);
2453  } else {
2454  PartPtr = cast<GetElementPtrInst>(
2455  Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)));
2456  PartPtr->setIsInBounds(InBounds);
2457  }
2458 
2459  return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2460  };
2461 
2462  // Handle Stores:
2463  if (SI) {
2465 
2466  for (unsigned Part = 0; Part < UF; ++Part) {
2467  Instruction *NewSI = nullptr;
2468  Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
2469  if (CreateGatherScatter) {
2470  Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
2471  Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
2472  NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2473  MaskPart);
2474  } else {
2475  if (Reverse) {
2476  // If we store to reverse consecutive memory locations, then we need
2477  // to reverse the order of elements in the stored value.
2478  StoredVal = reverseVector(StoredVal);
2479  // We don't want to update the value in the map as it might be used in
2480  // another expression. So don't call resetVectorValue(StoredVal).
2481  }
2482  auto *VecPtr = CreateVecPtr(Part, Ptr);
2483  if (isMaskRequired)
2484  NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2485  Mask[Part]);
2486  else
2487  NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2488  }
2489  addMetadata(NewSI, SI);
2490  }
2491  return;
2492  }
2493 
2494  // Handle loads.
2495  assert(LI && "Must have a load instruction");
2497  for (unsigned Part = 0; Part < UF; ++Part) {
2498  Value *NewLI;
2499  if (CreateGatherScatter) {
2500  Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
2501  Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
2502  NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2503  nullptr, "wide.masked.gather");
2504  addMetadata(NewLI, LI);
2505  } else {
2506  auto *VecPtr = CreateVecPtr(Part, Ptr);
2507  if (isMaskRequired)
2508  NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2509  UndefValue::get(DataTy),
2510  "wide.masked.load");
2511  else
2512  NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2513 
2514  // Add metadata to the load, but setVectorValue to the reverse shuffle.
2515  addMetadata(NewLI, LI);
2516  if (Reverse)
2517  NewLI = reverseVector(NewLI);
2518  }
2519  VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
2520  }
2521 }
2522 
2524  const VPIteration &Instance,
2525  bool IfPredicateInstr) {
2526  assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2527 
2528  setDebugLocFromInst(Builder, Instr);
2529 
2530  // Does this instruction return a value ?
2531  bool IsVoidRetTy = Instr->getType()->isVoidTy();
2532 
2533  Instruction *Cloned = Instr->clone();
2534  if (!IsVoidRetTy)
2535  Cloned->setName(Instr->getName() + ".cloned");
2536 
2537  // Replace the operands of the cloned instructions with their scalar
2538  // equivalents in the new loop.
2539  for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2540  auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
2541  Cloned->setOperand(op, NewOp);
2542  }
2543  addNewMetadata(Cloned, Instr);
2544 
2545  // Place the cloned scalar in the new loop.
2546  Builder.Insert(Cloned);
2547 
2548  // Add the cloned scalar to the scalar map entry.
2549  VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
2550 
2551  // If we just cloned a new assumption, add it the assumption cache.
2552  if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
2553  if (II->getIntrinsicID() == Intrinsic::assume)
2554  AC->registerAssumption(II);
2555 
2556  // End if-block.
2557  if (IfPredicateInstr)
2558  PredicatedInstructions.push_back(Cloned);
2559 }
2560 
2562  Value *End, Value *Step,
2563  Instruction *DL) {
2564  BasicBlock *Header = L->getHeader();
2565  BasicBlock *Latch = L->getLoopLatch();
2566  // As we're just creating this loop, it's possible no latch exists
2567  // yet. If so, use the header as this will be a single block loop.
2568  if (!Latch)
2569  Latch = Header;
2570 
2573  setDebugLocFromInst(Builder, OldInst);
2574  auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2575 
2577  setDebugLocFromInst(Builder, OldInst);
2578 
2579  // Create i+1 and fill the PHINode.
2580  Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2581  Induction->addIncoming(Start, L->getLoopPreheader());
2582  Induction->addIncoming(Next, Latch);
2583  // Create the compare.
2584  Value *ICmp = Builder.CreateICmpEQ(Next, End);
2585  Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2586 
2587  // Now we have two terminators. Remove the old one from the block.
2588  Latch->getTerminator()->eraseFromParent();
2589 
2590  return Induction;
2591 }
2592 
2594  if (TripCount)
2595  return TripCount;
2596 
2598  // Find the loop boundaries.
2599  ScalarEvolution *SE = PSE.getSE();
2600  const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2601  assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
2602  "Invalid loop count");
2603 
2604  Type *IdxTy = Legal->getWidestInductionType();
2605 
2606  // The exit count might have the type of i64 while the phi is i32. This can
2607  // happen if we have an induction variable that is sign extended before the
2608  // compare. The only way that we get a backedge taken count is that the
2609  // induction variable was signed and as such will not overflow. In such a case
2610  // truncation is legal.
2611  if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2612  IdxTy->getPrimitiveSizeInBits())
2613  BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2614  BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2615 
2616  // Get the total trip count from the count by adding 1.
2617  const SCEV *ExitCount = SE->getAddExpr(
2618  BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2619 
2620  const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2621 
2622  // Expand the trip count and place the new instructions in the preheader.
2623  // Notice that the pre-header does not change, only the loop body.
2624  SCEVExpander Exp(*SE, DL, "induction");
2625 
2626  // Count holds the overall loop count (N).
2627  TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2629 
2630  if (TripCount->getType()->isPointerTy())
2631  TripCount =
2632  CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2634 
2635  return TripCount;
2636 }
2637 
2639  if (VectorTripCount)
2640  return VectorTripCount;
2641 
2642  Value *TC = getOrCreateTripCount(L);
2644 
2645  // Now we need to generate the expression for the part of the loop that the
2646  // vectorized body will execute. This is equal to N - (N % Step) if scalar
2647  // iterations are not required for correctness, or N - Step, otherwise. Step
2648  // is equal to the vectorization factor (number of SIMD elements) times the
2649  // unroll factor (number of SIMD instructions).
2650  Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2651  Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2652 
2653  // If there is a non-reversed interleaved group that may speculatively access
2654  // memory out-of-bounds, we need to ensure that there will be at least one
2655  // iteration of the scalar epilogue loop. Thus, if the step evenly divides
2656  // the trip count, we set the remainder to be equal to the step. If the step
2657  // does not evenly divide the trip count, no adjustment is necessary since
2658  // there will already be scalar iterations. Note that the minimum iterations
2659  // check ensures that N >= Step.
2660  if (VF > 1 && Cost->requiresScalarEpilogue()) {
2661  auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2662  R = Builder.CreateSelect(IsZero, Step, R);
2663  }
2664 
2665  VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2666 
2667  return VectorTripCount;
2668 }
2669 
2671  const DataLayout &DL) {
2672  // Verify that V is a vector type with same number of elements as DstVTy.
2673  unsigned VF = DstVTy->getNumElements();
2674  VectorType *SrcVecTy = cast<VectorType>(V->getType());
2675  assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2676  Type *SrcElemTy = SrcVecTy->getElementType();
2677  Type *DstElemTy = DstVTy->getElementType();
2678  assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2679  "Vector elements must have same size");
2680 
2681  // Do a direct cast if element types are castable.
2682  if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2683  return Builder.CreateBitOrPointerCast(V, DstVTy);
2684  }
2685  // V cannot be directly casted to desired vector type.
2686  // May happen when V is a floating point vector but DstVTy is a vector of
2687  // pointers or vice-versa. Handle this using a two-step bitcast using an
2688  // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2689  assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2690  "Only one type should be a pointer type");
2691  assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2692  "Only one type should be a floating point type");
2693  Type *IntTy =
2695  VectorType *VecIntTy = VectorType::get(IntTy, VF);
2696  Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2697  return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
2698 }
2699 
2701  BasicBlock *Bypass) {
2702  Value *Count = getOrCreateTripCount(L);
2703  BasicBlock *BB = L->getLoopPreheader();
2705 
2706  // Generate code to check if the loop's trip count is less than VF * UF, or
2707  // equal to it in case a scalar epilogue is required; this implies that the
2708  // vector trip count is zero. This check also covers the case where adding one
2709  // to the backedge-taken count overflowed leading to an incorrect trip count
2710  // of zero. In this case we will also jump to the scalar loop.
2713  Value *CheckMinIters = Builder.CreateICmp(
2714  P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
2715 
2716  BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2717  // Update dominator tree immediately if the generated block is a
2718  // LoopBypassBlock because SCEV expansions to generate loop bypass
2719  // checks may query it before the current function is finished.
2720  DT->addNewBlock(NewBB, BB);
2721  if (L->getParentLoop())
2722  L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2724  BranchInst::Create(Bypass, NewBB, CheckMinIters));
2725  LoopBypassBlocks.push_back(BB);
2726 }
2727 
2729  BasicBlock *BB = L->getLoopPreheader();
2730 
2731  // Generate the code to check that the SCEV assumptions that we made.
2732  // We want the new basic block to start at the first instruction in a
2733  // sequence of instructions that form a check.
2734  SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
2735  "scev.check");
2736  Value *SCEVCheck =
2737  Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
2738 
2739  if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2740  if (C->isZero())
2741  return;
2742 
2743  // Create a new block containing the stride check.
2744  BB->setName("vector.scevcheck");
2745  auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2746  // Update dominator tree immediately if the generated block is a
2747  // LoopBypassBlock because SCEV expansions to generate loop bypass
2748  // checks may query it before the current function is finished.
2749  DT->addNewBlock(NewBB, BB);
2750  if (L->getParentLoop())
2751  L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2753  BranchInst::Create(Bypass, NewBB, SCEVCheck));
2754  LoopBypassBlocks.push_back(BB);
2755  AddedSafetyChecks = true;
2756 }
2757 
2759  BasicBlock *BB = L->getLoopPreheader();
2760 
2761  // Generate the code that checks in runtime if arrays overlap. We put the
2762  // checks into a separate block to make the more common case of few elements
2763  // faster.
2764  Instruction *FirstCheckInst;
2765  Instruction *MemRuntimeCheck;
2766  std::tie(FirstCheckInst, MemRuntimeCheck) =
2768  if (!MemRuntimeCheck)
2769  return;
2770 
2771  // Create a new block containing the memory check.
2772  BB->setName("vector.memcheck");
2773  auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2774  // Update dominator tree immediately if the generated block is a
2775  // LoopBypassBlock because SCEV expansions to generate loop bypass
2776  // checks may query it before the current function is finished.
2777  DT->addNewBlock(NewBB, BB);
2778  if (L->getParentLoop())
2779  L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2781  BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2782  LoopBypassBlocks.push_back(BB);
2783  AddedSafetyChecks = true;
2784 
2785  // We currently don't use LoopVersioning for the actual loop cloning but we
2786  // still use it to add the noalias metadata.
2787  LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
2788  PSE.getSE());
2789  LVer->prepareNoAliasMetadata();
2790 }
2791 
2793  /*
2794  In this function we generate a new loop. The new loop will contain
2795  the vectorized instructions while the old loop will continue to run the
2796  scalar remainder.
2797 
2798  [ ] <-- loop iteration number check.
2799  / |
2800  / v
2801  | [ ] <-- vector loop bypass (may consist of multiple blocks).
2802  | / |
2803  | / v
2804  || [ ] <-- vector pre header.
2805  |/ |
2806  | v
2807  | [ ] \
2808  | [ ]_| <-- vector loop.
2809  | |
2810  | v
2811  | -[ ] <--- middle-block.
2812  | / |
2813  | / v
2814  -|- >[ ] <--- new preheader.
2815  | |
2816  | v
2817  | [ ] \
2818  | [ ]_| <-- old scalar loop to handle remainder.
2819  \ |
2820  \ v
2821  >[ ] <-- exit block.
2822  ...
2823  */
2824 
2825  BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2826  BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2827  BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2828  assert(VectorPH && "Invalid loop structure");
2829  assert(ExitBlock && "Must have an exit block");
2830 
2831  // Some loops have a single integer induction variable, while other loops
2832  // don't. One example is c++ iterators that often have multiple pointer
2833  // induction variables. In the code below we also support a case where we
2834  // don't have a single induction variable.
2835  //
2836  // We try to obtain an induction variable from the original loop as hard
2837  // as possible. However if we don't find one that:
2838  // - is an integer
2839  // - counts from zero, stepping by one
2840  // - is the size of the widest induction variable type
2841  // then we create a new one.
2843  Type *IdxTy = Legal->getWidestInductionType();
2844 
2845  // Split the single block loop into the two loop structure described above.
2846  BasicBlock *VecBody =
2847  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2848  BasicBlock *MiddleBlock =
2849  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2850  BasicBlock *ScalarPH =
2851  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2852 
2853  // Create and register the new vector loop.
2854  Loop *Lp = LI->AllocateLoop();
2855  Loop *ParentLoop = OrigLoop->getParentLoop();
2856 
2857  // Insert the new loop into the loop nest and register the new basic blocks
2858  // before calling any utilities such as SCEV that require valid LoopInfo.
2859  if (ParentLoop) {
2860  ParentLoop->addChildLoop(Lp);
2861  ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2862  ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2863  } else {
2864  LI->addTopLevelLoop(Lp);
2865  }
2866  Lp->addBasicBlockToLoop(VecBody, *LI);
2867 
2868  // Find the loop boundaries.
2869  Value *Count = getOrCreateTripCount(Lp);
2870 
2871  Value *StartIdx = ConstantInt::get(IdxTy, 0);
2872 
2873  // Now, compare the new count to zero. If it is zero skip the vector loop and
2874  // jump to the scalar loop. This check also covers the case where the
2875  // backedge-taken count is uint##_max: adding one to it will overflow leading
2876  // to an incorrect trip count of zero. In this (rare) case we will also jump
2877  // to the scalar loop.
2878  emitMinimumIterationCountCheck(Lp, ScalarPH);
2879 
2880  // Generate the code to check any assumptions that we've made for SCEV
2881  // expressions.
2882  emitSCEVChecks(Lp, ScalarPH);
2883 
2884  // Generate the code that checks in runtime if arrays overlap. We put the
2885  // checks into a separate block to make the more common case of few elements
2886  // faster.
2887  emitMemRuntimeChecks(Lp, ScalarPH);
2888 
2889  // Generate the induction variable.
2890  // The loop step is equal to the vectorization factor (num of SIMD elements)
2891  // times the unroll factor (num of SIMD instructions).
2892  Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2893  Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2894  Induction =
2895  createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2897 
2898  // We are going to resume the execution of the scalar loop.
2899  // Go over all of the induction variables that we found and fix the
2900  // PHIs that are left in the scalar version of the loop.
2901  // The starting values of PHI nodes depend on the counter of the last
2902  // iteration in the vectorized loop.
2903  // If we come from a bypass edge then we need to start from the original
2904  // start value.
2905 
2906  // This variable saves the new starting index for the scalar loop. It is used
2907  // to test if there are any tail iterations left once the vector loop has
2908  // completed.
2910  for (auto &InductionEntry : *List) {
2911  PHINode *OrigPhi = InductionEntry.first;
2912  InductionDescriptor II = InductionEntry.second;
2913 
2914  // Create phi nodes to merge from the backedge-taken check block.
2915  PHINode *BCResumeVal = PHINode::Create(
2916  OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
2917  // Copy original phi DL over to the new one.
2918  BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
2919  Value *&EndValue = IVEndValues[OrigPhi];
2920  if (OrigPhi == OldInduction) {
2921  // We know what the end value is.
2922  EndValue = CountRoundDown;
2923  } else {
2925  Type *StepType = II.getStep()->getType();
2926  Instruction::CastOps CastOp =
2927  CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
2928  Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
2929  const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2930  EndValue = II.transform(B, CRD, PSE.getSE(), DL);
2931  EndValue->setName("ind.end");
2932  }
2933 
2934  // The new PHI merges the original incoming value, in case of a bypass,
2935  // or the value at the end of the vectorized loop.
2936  BCResumeVal->addIncoming(EndValue, MiddleBlock);
2937 
2938  // Fix the scalar body counter (PHI node).
2939  unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2940 
2941  // The old induction's phi node in the scalar body needs the truncated
2942  // value.
2943  for (BasicBlock *BB : LoopBypassBlocks)
2944  BCResumeVal->addIncoming(II.getStartValue(), BB);
2945  OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2946  }
2947 
2948  // Add a check in the middle block to see if we have completed
2949  // all of the iterations in the first vector loop.
2950  // If (N - N%VF) == N, then we *don't* need to run the remainder.
2951  Value *CmpN =
2952  CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2953  CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
2954  ReplaceInstWithInst(MiddleBlock->getTerminator(),
2955  BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2956 
2957  // Get ready to start creating new instructions into the vectorized body.
2959 
2960  // Save the state.
2962  LoopScalarPreHeader = ScalarPH;
2963  LoopMiddleBlock = MiddleBlock;
2964  LoopExitBlock = ExitBlock;
2965  LoopVectorBody = VecBody;
2966  LoopScalarBody = OldBasicBlock;
2967 
2968  // Keep all loop hints from the original loop on the vector loop (we'll
2969  // replace the vectorizer-specific hints below).
2970  if (MDNode *LID = OrigLoop->getLoopID())
2971  Lp->setLoopID(LID);
2972 
2973  LoopVectorizeHints Hints(Lp, true, *ORE);
2974  Hints.setAlreadyVectorized();
2975 
2976  return LoopVectorPreHeader;
2977 }
2978 
2979 // Fix up external users of the induction variable. At this point, we are
2980 // in LCSSA form, with all external PHIs that use the IV having one input value,
2981 // coming from the remainder loop. We need those PHIs to also have a correct
2982 // value for the IV when arriving directly from the middle block.
2984  const InductionDescriptor &II,
2985  Value *CountRoundDown, Value *EndValue,
2986  BasicBlock *MiddleBlock) {
2987  // There are two kinds of external IV usages - those that use the value
2988  // computed in the last iteration (the PHI) and those that use the penultimate
2989  // value (the value that feeds into the phi from the loop latch).
2990  // We allow both, but they, obviously, have different values.
2991 
2992  assert(OrigLoop->getExitBlock() && "Expected a single exit block");
2993 
2994  DenseMap<Value *, Value *> MissingVals;
2995 
2996  // An external user of the last iteration's value should see the value that
2997  // the remainder loop uses to initialize its own IV.
2999  for (User *U : PostInc->users()) {
3000  Instruction *UI = cast<Instruction>(U);
3001  if (!OrigLoop->contains(UI)) {
3002  assert(isa<PHINode>(UI) && "Expected LCSSA form");
3003  MissingVals[UI] = EndValue;
3004  }
3005  }
3006 
3007  // An external user of the penultimate value need to see EndValue - Step.
3008  // The simplest way to get this is to recompute it from the constituent SCEVs,
3009  // that is Start + (Step * (CRD - 1)).
3010  for (User *U : OrigPhi->users()) {
3011  auto *UI = cast<Instruction>(U);
3012  if (!OrigLoop->contains(UI)) {
3013  const DataLayout &DL =
3015  assert(isa<PHINode>(UI) && "Expected LCSSA form");
3016 
3017  IRBuilder<> B(MiddleBlock->getTerminator());
3018  Value *CountMinusOne = B.CreateSub(
3019  CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3020  Value *CMO =
3021  !II.getStep()->getType()->isIntegerTy()
3022  ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3023  II.getStep()->getType())
3024  : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3025  CMO->setName("cast.cmo");
3026  Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3027  Escape->setName("ind.escape");
3028  MissingVals[UI] = Escape;
3029  }
3030  }
3031 
3032  for (auto &I : MissingVals) {
3033  PHINode *PHI = cast<PHINode>(I.first);
3034  // One corner case we have to handle is two IVs "chasing" each-other,
3035  // that is %IV2 = phi [...], [ %IV1, %latch ]
3036  // In this case, if IV1 has an external use, we need to avoid adding both
3037  // "last value of IV1" and "penultimate value of IV2". So, verify that we
3038  // don't already have an incoming value for the middle block.
3039  if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3040  PHI->addIncoming(I.second, MiddleBlock);
3041  }
3042 }
3043 
3044 namespace {
3045 
3046 struct CSEDenseMapInfo {
3047  static bool canHandle(const Instruction *I) {
3048  return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3049  isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3050  }
3051 
3052  static inline Instruction *getEmptyKey() {
3054  }
3055 
3056  static inline Instruction *getTombstoneKey() {
3058  }
3059 
3060  static unsigned getHashValue(const Instruction *I) {
3061  assert(canHandle(I) && "Unknown instruction!");
3063  I->value_op_end()));
3064  }
3065 
3066  static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3067  if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3068  LHS == getTombstoneKey() || RHS == getTombstoneKey())
3069  return LHS == RHS;
3070  return LHS->isIdenticalTo(RHS);
3071  }
3072 };
3073 
3074 } // end anonymous namespace
3075 
3076 ///Perform cse of induction variable instructions.
3077 static void cse(BasicBlock *BB) {
3078  // Perform simple cse.
3080  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3081  Instruction *In = &*I++;
3082 
3083  if (!CSEDenseMapInfo::canHandle(In))
3084  continue;
3085 
3086  // Check if we can replace this instruction with any of the
3087  // visited instructions.
3088  if (Instruction *V = CSEMap.lookup(In)) {
3089  In->replaceAllUsesWith(V);
3090  In->eraseFromParent();
3091  continue;
3092  }
3093 
3094  CSEMap[In] = In;
3095  }
3096 }
3097 
3098 /// Estimate the overhead of scalarizing an instruction. This is a
3099 /// convenience wrapper for the type-based getScalarizationOverhead API.
3100 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3101  const TargetTransformInfo &TTI) {
3102  if (VF == 1)
3103  return 0;
3104 
3105  unsigned Cost = 0;
3106  Type *RetTy = ToVectorTy(I->getType(), VF);
3107  if (!RetTy->isVoidTy() &&
3108  (!isa<LoadInst>(I) ||
3110  Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3111 
3112  if (CallInst *CI = dyn_cast<CallInst>(I)) {
3113  SmallVector<const Value *, 4> Operands(CI->arg_operands());
3114  Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3115  }
3116  else if (!isa<StoreInst>(I) ||
3119  Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3120  }
3121 
3122  return Cost;
3123 }
3124 
3125 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3126 // Return the cost of the instruction, including scalarization overhead if it's
3127 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3128 // i.e. either vector version isn't available, or is too expensive.
3129 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3130  const TargetTransformInfo &TTI,
3131  const TargetLibraryInfo *TLI,
3132  bool &NeedToScalarize) {
3133  Function *F = CI->getCalledFunction();
3134  StringRef FnName = CI->getCalledFunction()->getName();
3135  Type *ScalarRetTy = CI->getType();
3136  SmallVector<Type *, 4> Tys, ScalarTys;
3137  for (auto &ArgOp : CI->arg_operands())
3138  ScalarTys.push_back(ArgOp->getType());
3139 
3140  // Estimate cost of scalarized vector call. The source operands are assumed
3141  // to be vectors, so we need to extract individual elements from there,
3142  // execute VF scalar calls, and then gather the result into the vector return
3143  // value.
3144  unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3145  if (VF == 1)
3146  return ScalarCallCost;
3147 
3148  // Compute corresponding vector type for return value and arguments.
3149  Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3150  for (Type *ScalarTy : ScalarTys)
3151  Tys.push_back(ToVectorTy(ScalarTy, VF));
3152 
3153  // Compute costs of unpacking argument values for the scalar calls and
3154  // packing the return values to a vector.
3155  unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3156 
3157  unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3158 
3159  // If we can't emit a vector call for this function, then the currently found
3160  // cost is the cost we need to return.
3161  NeedToScalarize = true;
3162  if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3163  return Cost;
3164 
3165  // If the corresponding vector cost is cheaper, return its cost.
3166  unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3167  if (VectorCallCost < Cost) {
3168  NeedToScalarize = false;
3169  return VectorCallCost;
3170  }
3171  return Cost;
3172 }
3173 
3174 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3175 // factor VF. Return the cost of the instruction, including scalarization
3176 // overhead if it's needed.
3177 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3178  const TargetTransformInfo &TTI,
3179  const TargetLibraryInfo *TLI) {
3181  assert(ID && "Expected intrinsic call!");
3182 
3183  FastMathFlags FMF;
3184  if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3185  FMF = FPMO->getFastMathFlags();
3186 
3187  SmallVector<Value *, 4> Operands(CI->arg_operands());
3188  return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3189 }
3190 
3192  auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3193  auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3194  return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3195 }
3197  auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3198  auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3199  return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3200 }
3201 
3203  // For every instruction `I` in MinBWs, truncate the operands, create a
3204  // truncated version of `I` and reextend its result. InstCombine runs
3205  // later and will remove any ext/trunc pairs.
3206  SmallPtrSet<Value *, 4> Erased;
3207  for (const auto &KV : Cost->getMinimalBitwidths()) {
3208  // If the value wasn't vectorized, we must maintain the original scalar
3209  // type. The absence of the value from VectorLoopValueMap indicates that it
3210  // wasn't vectorized.
3211  if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3212  continue;
3213  for (unsigned Part = 0; Part < UF; ++Part) {
3214  Value *I = getOrCreateVectorValue(KV.first, Part);
3215  if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3216  continue;
3217  Type *OriginalTy = I->getType();
3218  Type *ScalarTruncatedTy =
3219  IntegerType::get(OriginalTy->getContext(), KV.second);
3220  Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3221  OriginalTy->getVectorNumElements());
3222  if (TruncatedTy == OriginalTy)
3223  continue;
3224 
3225  IRBuilder<> B(cast<Instruction>(I));
3226  auto ShrinkOperand = [&](Value *V) -> Value * {
3227  if (auto *ZI = dyn_cast<ZExtInst>(V))
3228  if (ZI->getSrcTy() == TruncatedTy)
3229  return ZI->getOperand(0);
3230  return B.CreateZExtOrTrunc(V, TruncatedTy);
3231  };
3232 
3233  // The actual instruction modification depends on the instruction type,
3234  // unfortunately.
3235  Value *NewI = nullptr;
3236  if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3237  NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3238  ShrinkOperand(BO->getOperand(1)));
3239 
3240  // Any wrapping introduced by shrinking this operation shouldn't be
3241  // considered undefined behavior. So, we can't unconditionally copy
3242  // arithmetic wrapping flags to NewI.
3243  cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3244  } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3245  NewI =
3246  B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3247  ShrinkOperand(CI->getOperand(1)));
3248  } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3249  NewI = B.CreateSelect(SI->getCondition(),
3250  ShrinkOperand(SI->getTrueValue()),
3251  ShrinkOperand(SI->getFalseValue()));
3252  } else if (auto *CI = dyn_cast<CastInst>(I)) {
3253  switch (CI->getOpcode()) {
3254  default:
3255  llvm_unreachable("Unhandled cast!");
3256  case Instruction::Trunc:
3257  NewI = ShrinkOperand(CI->getOperand(0));
3258  break;
3259  case Instruction::SExt:
3260  NewI = B.CreateSExtOrTrunc(
3261  CI->getOperand(0),
3262  smallestIntegerVectorType(OriginalTy, TruncatedTy));
3263  break;
3264  case Instruction::ZExt:
3265  NewI = B.CreateZExtOrTrunc(
3266  CI->getOperand(0),
3267  smallestIntegerVectorType(OriginalTy, TruncatedTy));
3268  break;
3269  }
3270  } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3271  auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3272  auto *O0 = B.CreateZExtOrTrunc(
3273  SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3274  auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3275  auto *O1 = B.CreateZExtOrTrunc(
3276  SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3277 
3278  NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3279  } else if (isa<LoadInst>(I)) {
3280  // Don't do anything with the operands, just extend the result.
3281  continue;
3282  } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3283  auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3284  auto *O0 = B.CreateZExtOrTrunc(
3285  IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3286  auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3287  NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3288  } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3289  auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3290  auto *O0 = B.CreateZExtOrTrunc(
3291  EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3292  NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3293  } else {
3294  llvm_unreachable("Unhandled instruction type!");
3295  }
3296 
3297  // Lastly, extend the result.
3298  NewI->takeName(cast<Instruction>(I));
3299  Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3300  I->replaceAllUsesWith(Res);
3301  cast<Instruction>(I)->eraseFromParent();
3302  Erased.insert(I);
3303  VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3304  }
3305  }
3306 
3307  // We'll have created a bunch of ZExts that are now parentless. Clean up.
3308  for (const auto &KV : Cost->getMinimalBitwidths()) {
3309  // If the value wasn't vectorized, we must maintain the original scalar
3310  // type. The absence of the value from VectorLoopValueMap indicates that it
3311  // wasn't vectorized.
3312  if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3313  continue;
3314  for (unsigned Part = 0; Part < UF; ++Part) {
3315  Value *I = getOrCreateVectorValue(KV.first, Part);
3316  ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3317  if (Inst && Inst->use_empty()) {
3318  Value *NewI = Inst->getOperand(0);
3319  Inst->eraseFromParent();
3320  VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3321  }
3322  }
3323  }
3324 }
3325 
3327  // Insert truncates and extends for any truncated instructions as hints to
3328  // InstCombine.
3329  if (VF > 1)
3331 
3332  // At this point every instruction in the original loop is widened to a
3333  // vector form. Now we need to fix the recurrences in the loop. These PHI
3334  // nodes are currently empty because we did not want to introduce cycles.
3335  // This is the second stage of vectorizing recurrences.
3337 
3338  // Update the dominator tree.
3339  //
3340  // FIXME: After creating the structure of the new loop, the dominator tree is
3341  // no longer up-to-date, and it remains that way until we update it
3342  // here. An out-of-date dominator tree is problematic for SCEV,
3343  // because SCEVExpander uses it to guide code generation. The
3344  // vectorizer use SCEVExpanders in several places. Instead, we should
3345  // keep the dominator tree up-to-date as we go.
3346  updateAnalysis();
3347 
3348  // Fix-up external users of the induction variables.
3349  for (auto &Entry : *Legal->getInductionVars())
3350  fixupIVUsers(Entry.first, Entry.second,
3352  IVEndValues[Entry.first], LoopMiddleBlock);
3353 
3354  fixLCSSAPHIs();
3356  sinkScalarOperands(&*PI);
3357 
3358  // Remove redundant induction instructions.
3360 }
3361 
3363  // In order to support recurrences we need to be able to vectorize Phi nodes.
3364  // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3365  // stage #2: We now need to fix the recurrences by adding incoming edges to
3366  // the currently empty PHI nodes. At this point every instruction in the
3367  // original loop is widened to a vector form so we can use them to construct
3368  // the incoming edges.
3369  for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
3370  // Handle first-order recurrences and reductions that need to be fixed.
3371  if (Legal->isFirstOrderRecurrence(&Phi))
3373  else if (Legal->isReductionVariable(&Phi))
3374  fixReduction(&Phi);
3375  }
3376 }
3377 
3379  // This is the second phase of vectorizing first-order recurrences. An
3380  // overview of the transformation is described below. Suppose we have the
3381  // following loop.
3382  //
3383  // for (int i = 0; i < n; ++i)
3384  // b[i] = a[i] - a[i - 1];
3385  //
3386  // There is a first-order recurrence on "a". For this loop, the shorthand
3387  // scalar IR looks like:
3388  //
3389  // scalar.ph:
3390  // s_init = a[-1]
3391  // br scalar.body
3392  //
3393  // scalar.body:
3394  // i = phi [0, scalar.ph], [i+1, scalar.body]
3395  // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3396  // s2 = a[i]
3397  // b[i] = s2 - s1
3398  // br cond, scalar.body, ...
3399  //
3400  // In this example, s1 is a recurrence because it's value depends on the
3401  // previous iteration. In the first phase of vectorization, we created a
3402  // temporary value for s1. We now complete the vectorization and produce the
3403  // shorthand vector IR shown below (for VF = 4, UF = 1).
3404  //
3405  // vector.ph:
3406  // v_init = vector(..., ..., ..., a[-1])
3407  // br vector.body
3408  //
3409  // vector.body
3410  // i = phi [0, vector.ph], [i+4, vector.body]
3411  // v1 = phi [v_init, vector.ph], [v2, vector.body]
3412  // v2 = a[i, i+1, i+2, i+3];
3413  // v3 = vector(v1(3), v2(0, 1, 2))
3414  // b[i, i+1, i+2, i+3] = v2 - v3
3415  // br cond, vector.body, middle.block
3416  //
3417  // middle.block:
3418  // x = v2(3)
3419  // br scalar.ph
3420  //
3421  // scalar.ph:
3422  // s_init = phi [x, middle.block], [a[-1], otherwise]
3423  // br scalar.body
3424  //
3425  // After execution completes the vector loop, we extract the next value of
3426  // the recurrence (x) to use as the initial value in the scalar loop.
3427 
3428  // Get the original loop preheader and single loop latch.
3429  auto *Preheader = OrigLoop->getLoopPreheader();
3430  auto *Latch = OrigLoop->getLoopLatch();
3431 
3432  // Get the initial and previous values of the scalar recurrence.
3433  auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
3434  auto *Previous = Phi->getIncomingValueForBlock(Latch);
3435 
3436  // Create a vector from the initial value.
3437  auto *VectorInit = ScalarInit;
3438  if (VF > 1) {
3440  VectorInit = Builder.CreateInsertElement(
3441  UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
3442  Builder.getInt32(VF - 1), "vector.recur.init");
3443  }
3444 
3445  // We constructed a temporary phi node in the first phase of vectorization.
3446  // This phi node will eventually be deleted.
3448  cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
3449 
3450  // Create a phi node for the new recurrence. The current value will either be
3451  // the initial value inserted into a vector or loop-varying vector value.
3452  auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
3453  VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
3454 
3455  // Get the vectorized previous value of the last part UF - 1. It appears last
3456  // among all unrolled iterations, due to the order of their construction.
3457  Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
3458 
3459  // Set the insertion point after the previous value if it is an instruction.
3460  // Note that the previous value may have been constant-folded so it is not
3461  // guaranteed to be an instruction in the vector loop. Also, if the previous
3462  // value is a phi node, we should insert after all the phi nodes to avoid
3463  // breaking basic block verification.
3464  if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
3465  isa<PHINode>(PreviousLastPart))
3467  else
3469  &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
3470 
3471  // We will construct a vector for the recurrence by combining the values for
3472  // the current and previous iterations. This is the required shuffle mask.
3473  SmallVector<Constant *, 8> ShuffleMask(VF);
3474  ShuffleMask[0] = Builder.getInt32(VF - 1);
3475  for (unsigned I = 1; I < VF; ++I)
3476  ShuffleMask[I] = Builder.getInt32(I + VF - 1);
3477 
3478  // The vector from which to take the initial value for the current iteration
3479  // (actual or unrolled). Initially, this is the vector phi node.
3480  Value *Incoming = VecPhi;
3481 
3482  // Shuffle the current and previous vector and update the vector parts.
3483  for (unsigned Part = 0; Part < UF; ++Part) {
3484  Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
3485  Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
3486  auto *Shuffle =
3487  VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
3488  ConstantVector::get(ShuffleMask))
3489  : Incoming;
3490  PhiPart->replaceAllUsesWith(Shuffle);
3491  cast<Instruction>(PhiPart)->eraseFromParent();
3492  VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
3493  Incoming = PreviousPart;
3494  }
3495 
3496  // Fix the latch value of the new recurrence in the vector loop.
3497  VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3498 
3499  // Extract the last vector element in the middle block. This will be the
3500  // initial value for the recurrence when jumping to the scalar loop.
3501  auto *ExtractForScalar = Incoming;
3502  if (VF > 1) {
3504  ExtractForScalar = Builder.CreateExtractElement(
3505  ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
3506  }
3507  // Extract the second last element in the middle block if the
3508  // Phi is used outside the loop. We need to extract the phi itself
3509  // and not the last element (the phi update in the current iteration). This
3510  // will be the value when jumping to the exit block from the LoopMiddleBlock,
3511  // when the scalar loop is not run at all.
3512  Value *ExtractForPhiUsedOutsideLoop = nullptr;
3513  if (VF > 1)
3514  ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3515  Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
3516  // When loop is unrolled without vectorizing, initialize
3517  // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
3518  // `Incoming`. This is analogous to the vectorized case above: extracting the
3519  // second last element when VF > 1.
3520  else if (UF > 1)
3521  ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
3522 
3523  // Fix the initial value of the original recurrence in the scalar loop.
3525  auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3526  for (auto *BB : predecessors(LoopScalarPreHeader)) {
3527  auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3528  Start->addIncoming(Incoming, BB);
3529  }
3530 
3532  Phi->setName("scalar.recur");
3533 
3534  // Finally, fix users of the recurrence outside the loop. The users will need
3535  // either the last value of the scalar recurrence or the last value of the
3536  // vector recurrence we extracted in the middle block. Since the loop is in
3537  // LCSSA form, we just need to find all the phi nodes for the original scalar
3538  // recurrence in the exit block, and then add an edge for the middle block.
3539  for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3540  if (LCSSAPhi.getIncomingValue(0) == Phi) {
3541  LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3542  }
3543  }
3544 }
3545 
3547  Constant *Zero = Builder.getInt32(0);
3548 
3549  // Get it's reduction variable descriptor.
3551  "Unable to find the reduction variable");
3552  RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
3553 
3555  TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3556  Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3558  RdxDesc.getMinMaxRecurrenceKind();
3559  setDebugLocFromInst(Builder, ReductionStartValue);
3560 
3561  // We need to generate a reduction vector from the incoming scalar.
3562  // To do so, we need to generate the 'identity' vector and override
3563  // one of the elements with the incoming scalar reduction. We need
3564  // to do it in the vector-loop preheader.
3566 
3567  // This is the vector-clone of the value that leaves the loop.
3568  Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
3569 
3570  // Find the reduction identity variable. Zero for addition, or, xor,
3571  // one for multiplication, -1 for And.
3572  Value *Identity;
3573  Value *VectorStart;
3576  // MinMax reduction have the start value as their identify.
3577  if (VF == 1) {
3578  VectorStart = Identity = ReductionStartValue;
3579  } else {
3580  VectorStart = Identity =
3581  Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3582  }
3583  } else {
3584  // Handle other reduction kinds:
3586  RK, VecTy->getScalarType());
3587  if (VF == 1) {
3588  Identity = Iden;
3589  // This vector is the Identity vector where the first element is the
3590  // incoming scalar reduction.
3591  VectorStart = ReductionStartValue;
3592  } else {
3593  Identity = ConstantVector::getSplat(VF, Iden);
3594 
3595  // This vector is the Identity vector where the first element is the
3596  // incoming scalar reduction.
3597  VectorStart =
3598  Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3599  }
3600  }
3601 
3602  // Fix the vector-loop phi.
3603 
3604  // Reductions do not have to start at zero. They can start with
3605  // any loop invariant values.
3606  BasicBlock *Latch = OrigLoop->getLoopLatch();
3607  Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
3608  for (unsigned Part = 0; Part < UF; ++Part) {
3609  Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
3610  Value *Val = getOrCreateVectorValue(LoopVal, Part);
3611  // Make sure to add the reduction stat value only to the
3612  // first unroll part.
3613  Value *StartVal = (Part == 0) ? VectorStart : Identity;
3614  cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
3615  cast<PHINode>(VecRdxPhi)
3616  ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3617  }
3618 
3619  // Before each round, move the insertion point right between
3620  // the PHIs and the values we are going to write.
3621  // This allows us to write both PHINodes and the extractelement
3622  // instructions.
3624 
3625  setDebugLocFromInst(Builder, LoopExitInst);
3626 
3627  // If the vector reduction can be performed in a smaller type, we truncate
3628  // then extend the loop exit value to enable InstCombine to evaluate the
3629  // entire expression in the smaller type.
3630  if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
3631  Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3634  VectorParts RdxParts(UF);
3635  for (unsigned Part = 0; Part < UF; ++Part) {
3636  RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
3637  Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3638  Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3639  : Builder.CreateZExt(Trunc, VecTy);
3640  for (Value::user_iterator UI = RdxParts[Part]->user_begin();
3641  UI != RdxParts[Part]->user_end();)
3642  if (*UI != Trunc) {
3643  (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
3644  RdxParts[Part] = Extnd;
3645  } else {
3646  ++UI;
3647  }
3648  }
3650  for (unsigned Part = 0; Part < UF; ++Part) {
3651  RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3652  VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
3653  }
3654  }
3655 
3656  // Reduce all of the unrolled parts into a single vector.
3657  Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
3659  setDebugLocFromInst(Builder, ReducedPartRdx);
3660  for (unsigned Part = 1; Part < UF; ++Part) {
3661  Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
3662  if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3663  // Floating point operations had to be 'fast' to enable the reduction.
3664  ReducedPartRdx = addFastMathFlag(
3666  ReducedPartRdx, "bin.rdx"));
3667  else
3668  ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3669  Builder, MinMaxKind, ReducedPartRdx, RdxPart);
3670  }
3671 
3672  if (VF > 1) {
3673  bool NoNaN = Legal->hasFunNoNaNAttr();
3674  ReducedPartRdx =
3675  createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
3676  // If the reduction can be performed in a smaller type, we need to extend
3677  // the reduction to the wider type before we branch to the original loop.
3678  if (Phi->getType() != RdxDesc.getRecurrenceType())
3679  ReducedPartRdx =
3680  RdxDesc.isSigned()
3681  ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
3682  : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
3683  }
3684 
3685  // Create a phi node that merges control-flow from the backedge-taken check
3686  // block and the middle block.
3687  PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
3689  for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3690  BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3691  BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3692 
3693  // Now, we need to fix the users of the reduction variable
3694  // inside and outside of the scalar remainder loop.
3695  // We know that the loop is in LCSSA form. We need to update the
3696  // PHI nodes in the exit blocks.
3697  for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3698  // All PHINodes need to have a single entry edge, or two if
3699  // we already fixed them.
3700  assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3701 
3702  // We found a reduction value exit-PHI. Update it with the
3703  // incoming bypass edge.
3704  if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
3705  LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
3706  } // end of the LCSSA phi scan.
3707 
3708  // Fix the scalar loop reduction variable with the incoming reduction sum
3709  // from the vector body and from the backedge value.
3710  int IncomingEdgeBlockIdx =
3712  assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3713  // Pick the other block.
3714  int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3715  Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3716  Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3717 }
3718 
3720  for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3721  if (LCSSAPhi.getNumIncomingValues() == 1) {
3722  assert(OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) &&
3723  "Incoming value isn't loop invariant");
3724  LCSSAPhi.addIncoming(LCSSAPhi.getIncomingValue(0), LoopMiddleBlock);
3725  }
3726  }
3727 }
3728 
3730  // The basic block and loop containing the predicated instruction.
3731  auto *PredBB = PredInst->getParent();
3732  auto *VectorLoop = LI->getLoopFor(PredBB);
3733 
3734  // Initialize a worklist with the operands of the predicated instruction.
3735  SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
3736 
3737  // Holds instructions that we need to analyze again. An instruction may be
3738  // reanalyzed if we don't yet know if we can sink it or not.
3739  SmallVector<Instruction *, 8> InstsToReanalyze;
3740 
3741  // Returns true if a given use occurs in the predicated block. Phi nodes use
3742  // their operands in their corresponding predecessor blocks.
3743  auto isBlockOfUsePredicated = [&](Use &U) -> bool {
3744  auto *I = cast<Instruction>(U.getUser());
3745  BasicBlock *BB = I->getParent();
3746  if (auto *Phi = dyn_cast<PHINode>(I))
3747  BB = Phi->getIncomingBlock(
3748  PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3749  return BB == PredBB;
3750  };
3751 
3752  // Iteratively sink the scalarized operands of the predicated instruction
3753  // into the block we created for it. When an instruction is sunk, it's
3754  // operands are then added to the worklist. The algorithm ends after one pass
3755  // through the worklist doesn't sink a single instruction.
3756  bool Changed;
3757  do {
3758  // Add the instructions that need to be reanalyzed to the worklist, and
3759  // reset the changed indicator.
3760  Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
3761  InstsToReanalyze.clear();
3762  Changed = false;
3763 
3764  while (!Worklist.empty()) {
3765  auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
3766 
3767  // We can't sink an instruction if it is a phi node, is already in the
3768  // predicated block, is not in the loop, or may have side effects.
3769  if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
3770  !VectorLoop->contains(I) || I->mayHaveSideEffects())
3771  continue;
3772 
3773  // It's legal to sink the instruction if all its uses occur in the
3774  // predicated block. Otherwise, there's nothing to do yet, and we may
3775  // need to reanalyze the instruction.
3776  if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
3777  InstsToReanalyze.push_back(I);
3778  continue;
3779  }
3780 
3781  // Move the instruction to the beginning of the predicated block, and add
3782  // it's operands to the worklist.
3783  I->moveBefore(&*PredBB->getFirstInsertionPt());
3784  Worklist.insert(I->op_begin(), I->op_end());
3785 
3786  // The sinking may have enabled other instructions to be sunk, so we will
3787  // need to iterate.
3788  Changed = true;
3789  }
3790  } while (Changed);
3791 }
3792 
3794  unsigned VF) {
3795  assert(PN->getParent() == OrigLoop->getHeader() &&
3796  "Non-header phis should have been handled elsewhere");
3797 
3798  PHINode *P = cast<PHINode>(PN);
3799  // In order to support recurrences we need to be able to vectorize Phi nodes.
3800  // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3801  // stage #1: We create a new vector PHI node with no incoming edges. We'll use
3802  // this value when we vectorize all of the instructions that use the PHI.
3804  for (unsigned Part = 0; Part < UF; ++Part) {
3805  // This is phase one of vectorizing PHIs.
3806  Type *VecTy =
3807  (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
3808  Value *EntryPart = PHINode::Create(
3809  VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
3810  VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
3811  }
3812  return;
3813  }
3814 
3816 
3817  // This PHINode must be an induction variable.
3818  // Make sure that we know about it.
3819  assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
3820 
3822  const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3823 
3824  // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3825  // which can be found from the original scalar operations.
3826  switch (II.getKind()) {
3828  llvm_unreachable("Unknown induction");
3831  llvm_unreachable("Integer/fp induction is handled elsewhere.");
3833  // Handle the pointer induction variable case.
3834  assert(P->getType()->isPointerTy() && "Unexpected type.");
3835  // This is the normalized GEP that starts counting at zero.
3836  Value *PtrInd = Induction;
3837  PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
3838  // Determine the number of scalars we need to generate for each unroll
3839  // iteration. If the instruction is uniform, we only need to generate the
3840  // first lane. Otherwise, we generate all VF values.
3841  unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
3842  // These are the scalar results. Notice that we don't generate vector GEPs
3843  // because scalar GEPs result in better code.
3844  for (unsigned Part = 0; Part < UF; ++Part) {
3845  for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
3846  Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
3847  Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3848  Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
3849  SclrGep->setName("next.gep");
3850  VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
3851  }
3852  }
3853  return;
3854  }
3855  }
3856 }
3857 
3858 /// A helper function for checking whether an integer division-related
3859 /// instruction may divide by zero (in which case it must be predicated if
3860 /// executed conditionally in the scalar code).
3861 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
3862 /// Non-zero divisors that are non compile-time constants will not be
3863 /// converted into multiplication, so we will still end up scalarizing
3864 /// the division, but can do so w/o predication.
3866  assert((I.getOpcode() == Instruction::UDiv ||
3867  I.getOpcode() == Instruction::SDiv ||
3868  I.getOpcode() == Instruction::URem ||
3869  I.getOpcode() == Instruction::SRem) &&
3870  "Unexpected instruction");
3871  Value *Divisor = I.getOperand(1);
3872  auto *CInt = dyn_cast<ConstantInt>(Divisor);
3873  return !CInt || CInt->isZero();
3874 }
3875 
3877  switch (I.getOpcode()) {
3878  case Instruction::Br:
3879  case Instruction::PHI:
3880  llvm_unreachable("This instruction is handled by a different recipe.");
3881  case Instruction::GetElementPtr: {
3882  // Construct a vector GEP by widening the operands of the scalar GEP as
3883  // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
3884  // results in a vector of pointers when at least one operand of the GEP
3885  // is vector-typed. Thus, to keep the representation compact, we only use
3886  // vector-typed operands for loop-varying values.
3887  auto *GEP = cast<GetElementPtrInst>(&I);
3888 
3889  if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
3890  // If we are vectorizing, but the GEP has only loop-invariant operands,
3891  // the GEP we build (by only using vector-typed operands for
3892  // loop-varying values) would be a scalar pointer. Thus, to ensure we
3893  // produce a vector of pointers, we need to either arbitrarily pick an
3894  // operand to broadcast, or broadcast a clone of the original GEP.
3895  // Here, we broadcast a clone of the original.
3896  //
3897  // TODO: If at some point we decide to scalarize instructions having
3898  // loop-invariant operands, this special case will no longer be
3899  // required. We would add the scalarization decision to
3900  // collectLoopScalars() and teach getVectorValue() to broadcast
3901  // the lane-zero scalar value.
3902  auto *Clone = Builder.Insert(GEP->clone());
3903  for (unsigned Part = 0; Part < UF; ++Part) {
3904  Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
3905  VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
3906  addMetadata(EntryPart, GEP);
3907  }
3908  } else {
3909  // If the GEP has at least one loop-varying operand, we are sure to
3910  // produce a vector of pointers. But if we are only unrolling, we want
3911  // to produce a scalar GEP for each unroll part. Thus, the GEP we
3912  // produce with the code below will be scalar (if VF == 1) or vector
3913  // (otherwise). Note that for the unroll-only case, we still maintain
3914  // values in the vector mapping with initVector, as we do for other
3915  // instructions.
3916  for (unsigned Part = 0; Part < UF; ++Part) {
3917  // The pointer operand of the new GEP. If it's loop-invariant, we
3918  // won't broadcast it.
3919  auto *Ptr =
3920  OrigLoop->isLoopInvariant(GEP->getPointerOperand())
3921  ? GEP->getPointerOperand()
3922  : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
3923 
3924  // Collect all the indices for the new GEP. If any index is
3925  // loop-invariant, we won't broadcast it.
3926  SmallVector<Value *, 4> Indices;
3927  for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
3928  if (OrigLoop->isLoopInvariant(U.get()))
3929  Indices.push_back(U.get());
3930  else
3931  Indices.push_back(getOrCreateVectorValue(U.get(), Part));
3932  }
3933 
3934  // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
3935  // but it should be a vector, otherwise.
3936  auto *NewGEP = GEP->isInBounds()
3937  ? Builder.CreateInBoundsGEP(Ptr, Indices)
3938  : Builder.CreateGEP(Ptr, Indices);
3939  assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
3940  "NewGEP is not a pointer vector");
3941  VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
3942  addMetadata(NewGEP, GEP);
3943  }
3944  }
3945 
3946  break;
3947  }
3948  case Instruction::UDiv:
3949  case Instruction::SDiv:
3950  case Instruction::SRem:
3951  case Instruction::URem:
3952  case Instruction::Add:
3953  case Instruction::FAdd:
3954  case Instruction::Sub:
3955  case Instruction::FSub:
3956  case Instruction::Mul:
3957  case Instruction::FMul:
3958  case Instruction::FDiv:
3959  case Instruction::FRem:
3960  case Instruction::Shl:
3961  case Instruction::LShr:
3962  case Instruction::AShr:
3963  case Instruction::And:
3964  case Instruction::Or:
3965  case Instruction::Xor: {
3966  // Just widen binops.
3967  auto *BinOp = cast<BinaryOperator>(&I);
3968  setDebugLocFromInst(Builder, BinOp);
3969 
3970  for (unsigned Part = 0; Part < UF; ++Part) {
3971  Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
3972  Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
3973  Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
3974 
3975  if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3976  VecOp->copyIRFlags(BinOp);
3977 
3978  // Use this vector value for all users of the original instruction.
3979  VectorLoopValueMap.setVectorValue(&I, Part, V);
3980  addMetadata(V, BinOp);
3981  }
3982 
3983  break;
3984  }
3985  case Instruction::Select: {
3986  // Widen selects.
3987  // If the selector is loop invariant we can create a select
3988  // instruction with a scalar condition. Otherwise, use vector-select.
3989  auto *SE = PSE.getSE();
3990  bool InvariantCond =
3993 
3994  // The condition can be loop invariant but still defined inside the
3995  // loop. This means that we can't just use the original 'cond' value.
3996  // We have to take the 'vectorized' value and pick the first lane.
3997  // Instcombine will make this a no-op.
3998 
3999  auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
4000 
4001  for (unsigned Part = 0; Part < UF; ++Part) {
4002  Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
4003  Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
4004  Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
4005  Value *Sel =
4006  Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
4007  VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4008  addMetadata(Sel, &I);
4009  }
4010 
4011  break;
4012  }
4013 
4014  case Instruction::ICmp:
4015  case Instruction::FCmp: {
4016  // Widen compares. Generate vector compares.
4017  bool FCmp = (I.getOpcode() == Instruction::FCmp);
4018  auto *Cmp = dyn_cast<CmpInst>(&I);
4020  for (unsigned Part = 0; Part < UF; ++Part) {
4021  Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
4022  Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
4023  Value *C = nullptr;
4024  if (FCmp) {
4025  // Propagate fast math flags.
4027  Builder.setFastMathFlags(Cmp->getFastMathFlags());
4028  C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4029  } else {
4030  C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4031  }
4032  VectorLoopValueMap.setVectorValue(&I, Part, C);
4033  addMetadata(C, &I);
4034  }
4035 
4036  break;
4037  }
4038 
4039  case Instruction::ZExt:
4040  case Instruction::SExt:
4041  case Instruction::FPToUI:
4042  case Instruction::FPToSI:
4043  case Instruction::FPExt:
4044  case Instruction::PtrToInt:
4045  case Instruction::IntToPtr:
4046  case Instruction::SIToFP:
4047  case Instruction::UIToFP:
4048  case Instruction::Trunc:
4049  case Instruction::FPTrunc:
4050  case Instruction::BitCast: {
4051  auto *CI = dyn_cast<CastInst>(&I);
4053 
4054  /// Vectorize casts.
4055  Type *DestTy =
4056  (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4057 
4058  for (unsigned Part = 0; Part < UF; ++Part) {
4059  Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4060  Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4061  VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4062  addMetadata(Cast, &I);
4063  }
4064  break;
4065  }
4066 
4067  case Instruction::Call: {
4068  // Ignore dbg intrinsics.
4069  if (isa<DbgInfoIntrinsic>(I))
4070  break;
4072 
4073  Module *M = I.getParent()->getParent()->getParent();
4074  auto *CI = cast<CallInst>(&I);
4075 
4076  StringRef FnName = CI->getCalledFunction()->getName();
4077  Function *F = CI->getCalledFunction();
4078  Type *RetTy = ToVectorTy(CI->getType(), VF);
4080  for (Value *ArgOperand : CI->arg_operands())
4081  Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4082 
4084 
4085  // The flag shows whether we use Intrinsic or a usual Call for vectorized
4086  // version of the instruction.
4087  // Is it beneficial to perform intrinsic call compared to lib call?
4088  bool NeedToScalarize;
4089  unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4090  bool UseVectorIntrinsic =
4091  ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4092  assert((UseVectorIntrinsic || !NeedToScalarize) &&
4093  "Instruction should be scalarized elsewhere.");
4094 
4095  for (unsigned Part = 0; Part < UF; ++Part) {
4097  for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4098  Value *Arg = CI->getArgOperand(i);
4099  // Some intrinsics have a scalar argument - don't replace it with a
4100  // vector.
4101  if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
4102  Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4103  Args.push_back(Arg);
4104  }
4105 
4106  Function *VectorF;
4107  if (UseVectorIntrinsic) {
4108  // Use vector version of the intrinsic.
4109  Type *TysForDecl[] = {CI->getType()};
4110  if (VF > 1)
4111  TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4112  VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4113  } else {
4114  // Use vector version of the library call.
4115  StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4116  assert(!VFnName.empty() && "Vector function name is empty.");
4117  VectorF = M->getFunction(VFnName);
4118  if (!VectorF) {
4119  // Generate a declaration
4120  FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4121  VectorF =
4122  Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4123  VectorF->copyAttributesFrom(F);
4124  }
4125  }
4126  assert(VectorF && "Can't create vector function.");
4127 
4129  CI->getOperandBundlesAsDefs(OpBundles);
4130  CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4131 
4132  if (isa<FPMathOperator>(V))
4133  V->copyFastMathFlags(CI);
4134 
4135  VectorLoopValueMap.setVectorValue(&I, Part, V);
4136  addMetadata(V, &I);
4137  }
4138 
4139  break;
4140  }
4141 
4142  default:
4143  // This instruction is not vectorized by simple widening.
4144  LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4145  llvm_unreachable("Unhandled instruction!");
4146  } // end of switch.
4147 }
4148 
4150  // Forget the original basic block.
4152 
4153  // Update the dominator tree information.
4155  "Entry does not dominate exit.");
4156 
4163 }
4164 
4165 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
4166  // We should not collect Scalars more than once per VF. Right now, this
4167  // function is called from collectUniformsAndScalars(), which already does
4168  // this check. Collecting Scalars for VF=1 does not make any sense.
4169  assert(VF >= 2 && !Scalars.count(VF) &&
4170  "This function should not be visited twice for the same VF");
4171 
4173 
4174  // These sets are used to seed the analysis with pointers used by memory
4175  // accesses that will remain scalar.
4177  SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4178 
4179  // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4180  // The pointer operands of loads and stores will be scalar as long as the
4181  // memory access is not a gather or scatter operation. The value operand of a
4182  // store will remain scalar if the store is scalarized.
4183  auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4184  InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4185  assert(WideningDecision != CM_Unknown &&
4186  "Widening decision should be ready at this moment");
4187  if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4188  if (Ptr == Store->getValueOperand())
4189  return WideningDecision == CM_Scalarize;
4190  assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4191  "Ptr is neither a value or pointer operand");
4192  return WideningDecision != CM_GatherScatter;
4193  };
4194 
4195  // A helper that returns true if the given value is a bitcast or
4196  // getelementptr instruction contained in the loop.
4197  auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4198  return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4199  isa<GetElementPtrInst>(V)) &&
4200  !TheLoop->isLoopInvariant(V);
4201  };
4202 
4203  // A helper that evaluates a memory access's use of a pointer. If the use
4204  // will be a scalar use, and the pointer is only used by memory accesses, we
4205  // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4206  // PossibleNonScalarPtrs.
4207  auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4208  // We only care about bitcast and getelementptr instructions contained in
4209  // the loop.
4210  if (!isLoopVaryingBitCastOrGEP(Ptr))
4211  return;
4212 
4213  // If the pointer has already been identified as scalar (e.g., if it was
4214  // also identified as uniform), there's nothing to do.
4215  auto *I = cast<Instruction>(Ptr);
4216  if (Worklist.count(I))
4217  return;
4218 
4219  // If the use of the pointer will be a scalar use, and all users of the
4220  // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4221  // place the pointer in PossibleNonScalarPtrs.
4222  if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4223  return isa<LoadInst>(U) || isa<StoreInst>(U);
4224  }))
4225  ScalarPtrs.insert(I);
4226  else
4227  PossibleNonScalarPtrs.insert(I);
4228  };
4229 
4230  // We seed the scalars analysis with three classes of instructions: (1)
4231  // instructions marked uniform-after-vectorization, (2) bitcast and
4232  // getelementptr instructions used by memory accesses requiring a scalar use,
4233  // and (3) pointer induction variables and their update instructions (we
4234  // currently only scalarize these).
4235  //
4236  // (1) Add to the worklist all instructions that have been identified as
4237  // uniform-after-vectorization.
4238  Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4239 
4240  // (2) Add to the worklist all bitcast and getelementptr instructions used by
4241  // memory accesses requiring a scalar use. The pointer operands of loads and
4242  // stores will be scalar as long as the memory accesses is not a gather or
4243  // scatter operation. The value operand of a store will remain scalar if the
4244  // store is scalarized.
4245  for (auto *BB : TheLoop->blocks())
4246  for (auto &I : *BB) {
4247  if (auto *Load = dyn_cast<LoadInst>(&I)) {
4248  evaluatePtrUse(Load, Load->getPointerOperand());
4249  } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4250  evaluatePtrUse(Store, Store->getPointerOperand());
4251  evaluatePtrUse(Store, Store->getValueOperand());
4252  }
4253  }
4254  for (auto *I : ScalarPtrs)
4255  if (!PossibleNonScalarPtrs.count(I)) {
4256  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4257  Worklist.insert(I);
4258  }
4259 
4260  // (3) Add to the worklist all pointer induction variables and their update
4261  // instructions.
4262  //
4263  // TODO: Once we are able to vectorize pointer induction variables we should
4264  // no longer insert them into the worklist here.
4265  auto *Latch = TheLoop->getLoopLatch();
4266  for (auto &Induction : *Legal->getInductionVars()) {
4267  auto *Ind = Induction.first;
4268  auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4269  if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
4270  continue;
4271  Worklist.insert(Ind);
4272  Worklist.insert(IndUpdate);
4273  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4274  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4275  << "\n");
4276  }
4277 
4278  // Insert the forced scalars.
4279  // FIXME: Currently widenPHIInstruction() often creates a dead vector
4280  // induction variable when the PHI user is scalarized.
4281  if (ForcedScalars.count(VF))
4282  for (auto *I : ForcedScalars.find(VF)->second)
4283  Worklist.insert(I);
4284 
4285  // Expand the worklist by looking through any bitcasts and getelementptr
4286  // instructions we've already identified as scalar. This is similar to the
4287  // expansion step in collectLoopUniforms(); however, here we're only
4288  // expanding to include additional bitcasts and getelementptr instructions.
4289  unsigned Idx = 0;
4290  while (Idx != Worklist.size()) {
4291  Instruction *Dst = Worklist[Idx++];
4292  if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4293  continue;
4294  auto *Src = cast<Instruction>(Dst->getOperand(0));
4295  if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4296  auto *J = cast<Instruction>(U);
4297  return !TheLoop->contains(J) || Worklist.count(J) ||
4298  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4299  isScalarUse(J, Src));
4300  })) {
4301  Worklist.insert(Src);
4302  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4303  }
4304  }
4305 
4306  // An induction variable will remain scalar if all users of the induction
4307  // variable and induction variable update remain scalar.
4308  for (auto &Induction : *Legal->getInductionVars()) {
4309  auto *Ind = Induction.first;
4310  auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4311 
4312  // We already considered pointer induction variables, so there's no reason
4313  // to look at their users again.
4314  //
4315  // TODO: Once we are able to vectorize pointer induction variables we
4316  // should no longer skip over them here.
4317  if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
4318  continue;
4319 
4320  // Determine if all users of the induction variable are scalar after
4321  // vectorization.
4322  auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4323  auto *I = cast<Instruction>(U);
4324  return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
4325  });
4326  if (!ScalarInd)
4327  continue;
4328 
4329  // Determine if all users of the induction variable update instruction are
4330  // scalar after vectorization.
4331  auto ScalarIndUpdate =
4332  llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4333  auto *I = cast<Instruction>(U);
4334  return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
4335  });
4336  if (!ScalarIndUpdate)
4337  continue;
4338 
4339  // The induction variable and its update instruction will remain scalar.
4340  Worklist.insert(Ind);
4341  Worklist.insert(IndUpdate);
4342  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4343  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4344  << "\n");
4345  }
4346 
4347  Scalars[VF].insert(Worklist.begin(), Worklist.end());
4348 }
4349 
4352  return false;
4353  switch(I->getOpcode()) {
4354  default:
4355  break;
4356  case Instruction::Load:
4357  case Instruction::Store: {
4358  if (!Legal->isMaskRequired(I))
4359  return false;
4360  auto *Ptr = getLoadStorePointerOperand(I);
4361  auto *Ty = getMemInstValueType(I);
4362  return isa<LoadInst>(I) ?
4363  !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty))
4364  : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
4365  }
4366  case Instruction::UDiv:
4367  case Instruction::SDiv:
4368  case Instruction::SRem:
4369  case Instruction::URem:
4370  return mayDivideByZero(*I);
4371  }
4372  return false;
4373 }
4374 
4376  unsigned VF) {
4377  // Get and ensure we have a valid memory instruction.
4378  LoadInst *LI = dyn_cast<LoadInst>(I);
4380  assert((LI || SI) && "Invalid memory instruction");
4381 
4382  auto *Ptr = getLoadStorePointerOperand(I);
4383 
4384  // In order to be widened, the pointer should be consecutive, first of all.
4385  if (!Legal->isConsecutivePtr(Ptr))
4386  return false;
4387 
4388  // If the instruction is a store located in a predicated block, it will be
4389  // scalarized.
4390  if (isScalarWithPredication(I))
4391  return false;
4392 
4393  // If the instruction's allocated size doesn't equal it's type size, it
4394  // requires padding and will be scalarized.
4395  auto &DL = I->getModule()->getDataLayout();
4396  auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
4397  if (hasIrregularType(ScalarTy, DL, VF))
4398  return false;
4399 
4400  return true;
4401 }
4402 
4403 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
4404  // We should not collect Uniforms more than once per VF. Right now,
4405  // this function is called from collectUniformsAndScalars(), which
4406  // already does this check. Collecting Uniforms for VF=1 does not make any
4407  // sense.
4408 
4409  assert(VF >= 2 && !Uniforms.count(VF) &&
4410  "This function should not be visited twice for the same VF");
4411 
4412  // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4413  // not analyze again. Uniforms.count(VF) will return 1.
4414  Uniforms[VF].clear();
4415 
4416  // We now know that the loop is vectorizable!
4417  // Collect instructions inside the loop that will remain uniform after
4418  // vectorization.
4419 
4420  // Global values, params and instructions outside of current loop are out of
4421  // scope.
4422  auto isOutOfScope = [&](Value *V) -> bool {
4424  return (!I || !TheLoop->contains(I));
4425  };
4426 
4427  SetVector<Instruction *> Worklist;
4428  BasicBlock *Latch = TheLoop->getLoopLatch();
4429 
4430  // Start with the conditional branch. If the branch condition is an
4431  // instruction contained in the loop that is only used by the branch, it is
4432  // uniform.
4433  auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4434  if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
4435  Worklist.insert(Cmp);
4436  LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
4437  }
4438 
4439  // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
4440  // are pointers that are treated like consecutive pointers during
4441  // vectorization. The pointer operands of interleaved accesses are an
4442  // example.
4443  SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
4444 
4445  // Holds pointer operands of instructions that are possibly non-uniform.
4446  SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
4447 
4448  auto isUniformDecision = [&](Instruction *I, unsigned VF) {
4449  InstWidening WideningDecision = getWideningDecision(I, VF);
4450  assert(WideningDecision != CM_Unknown &&
4451  "Widening decision should be ready at this moment");
4452 
4453  return (WideningDecision == CM_Widen ||
4454  WideningDecision == CM_Widen_Reverse ||
4455  WideningDecision == CM_Interleave);
4456  };
4457  // Iterate over the instructions in the loop, and collect all
4458  // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
4459  // that a consecutive-like pointer operand will be scalarized, we collect it
4460  // in PossibleNonUniformPtrs instead. We use two sets here because a single
4461  // getelementptr instruction can be used by both vectorized and scalarized
4462  // memory instructions. For example, if a loop loads and stores from the same
4463  // location, but the store is conditional, the store will be scalarized, and
4464  // the getelementptr won't remain uniform.
4465  for (auto *BB : TheLoop->blocks())
4466  for (auto &I : *BB) {
4467  // If there's no pointer operand, there's nothing to do.
4468  auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
4469  if (!Ptr)
4470  continue;
4471 
4472  // True if all users of Ptr are memory accesses that have Ptr as their
4473  // pointer operand.
4474  auto UsersAreMemAccesses =
4475  llvm::all_of(Ptr->users(), [&](User *U) -> bool {
4476  return getLoadStorePointerOperand(U) == Ptr;
4477  });
4478 
4479  // Ensure the memory instruction will not be scalarized or used by
4480  // gather/scatter, making its pointer operand non-uniform. If the pointer
4481  // operand is used by any instruction other than a memory access, we
4482  // conservatively assume the pointer operand may be non-uniform.
4483  if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
4484  PossibleNonUniformPtrs.insert(Ptr);
4485 
4486  // If the memory instruction will be vectorized and its pointer operand
4487  // is consecutive-like, or interleaving - the pointer operand should
4488  // remain uniform.
4489  else
4490  ConsecutiveLikePtrs.insert(Ptr);
4491  }
4492 
4493  // Add to the Worklist all consecutive and consecutive-like pointers that
4494  // aren't also identified as possibly non-uniform.
4495  for (auto *V : ConsecutiveLikePtrs)
4496  if (!PossibleNonUniformPtrs.count(V)) {
4497  LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
4498  Worklist.insert(V);
4499  }
4500 
4501  // Expand Worklist in topological order: whenever a new instruction
4502  // is added , its users should be either already inside Worklist, or
4503  // out of scope. It ensures a uniform instruction will only be used
4504  // by uniform instructions or out of scope instructions.
4505  unsigned idx = 0;
4506  while (idx != Worklist.size()) {
4507  Instruction *I = Worklist[idx++];
4508 
4509  for (auto OV : I->operand_values()) {
4510  if (isOutOfScope(OV))
4511  continue;
4512  auto *OI = cast<Instruction>(OV);
4513  if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4514  auto *J = cast<Instruction>(U);
4515  return !TheLoop->contains(J) || Worklist.count(J) ||
4516  (OI == getLoadStorePointerOperand(J) &&
4517  isUniformDecision(J, VF));
4518  })) {
4519  Worklist.insert(OI);
4520  LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
4521  }
4522  }
4523  }
4524 
4525  // Returns true if Ptr is the pointer operand of a memory access instruction
4526  // I, and I is known to not require scalarization.
4527  auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4528  return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4529  };
4530 
4531  // For an instruction to be added into Worklist above, all its users inside
4532  // the loop should also be in Worklist. However, this condition cannot be
4533  // true for phi nodes that form a cyclic dependence. We must process phi
4534  // nodes separately. An induction variable will remain uniform if all users
4535  // of the induction variable and induction variable update remain uniform.
4536  // The code below handles both pointer and non-pointer induction variables.
4537  for (auto &Induction : *Legal->getInductionVars()) {
4538  auto *Ind = Induction.first;
4539  auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4540 
4541  // Determine if all users of the induction variable are uniform after
4542  // vectorization.
4543  auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4544  auto *I = cast<Instruction>(U);
4545  return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4546  isVectorizedMemAccessUse(I, Ind);
4547  });
4548  if (!UniformInd)
4549  continue;
4550 
4551  // Determine if all users of the induction variable update instruction are
4552  // uniform after vectorization.
4553  auto UniformIndUpdate =
4554  llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4555  auto *I = cast<Instruction>(U);
4556  return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4557  isVectorizedMemAccessUse(I, IndUpdate);
4558  });
4559  if (!UniformIndUpdate)
4560  continue;
4561 
4562  // The induction variable and its update instruction will remain uniform.
4563  Worklist.insert(Ind);
4564  Worklist.insert(IndUpdate);
4565  LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
4566  LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate
4567  << "\n");
4568  }
4569 
4570  Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4571 }
4572 
4573 void InterleavedAccessInfo::collectConstStrideAccesses(
4575  const ValueToValueMap &Strides) {
4576  auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4577 
4578  // Since it's desired that the load/store instructions be maintained in
4579  // "program order" for the interleaved access analysis, we have to visit the
4580  // blocks in the loop in reverse postorder (i.e., in a topological order).
4581  // Such an ordering will ensure that any load/store that may be executed
4582  // before a second load/store will precede the second load/store in
4583  // AccessStrideInfo.
4584  LoopBlocksDFS DFS(TheLoop);
4585  DFS.perform(LI);
4586  for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
4587  for (auto &I : *BB) {
4588  auto *LI = dyn_cast<LoadInst>(&I);
4589  auto *SI = dyn_cast<StoreInst>(&I);
4590  if (!LI && !SI)
4591  continue;
4592 
4594  // We don't check wrapping here because we don't know yet if Ptr will be
4595  // part of a full group or a group with gaps. Checking wrapping for all
4596  // pointers (even those that end up in groups with no gaps) will be overly
4597  // conservative. For full groups, wrapping should be ok since if we would
4598  // wrap around the address space we would do a memory access at nullptr
4599  // even without the transformation. The wrapping checks are therefore
4600  // deferred until after we've formed the interleaved groups.
4601  int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
4602  /*Assume=*/true, /*ShouldCheckWrap=*/false);
4603 
4604  const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
4605  PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4606  uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
4607 
4608  // An alignment of 0 means target ABI alignment.
4609  unsigned Align = getMemInstAlignment(&I);
4610  if (!Align)
4611  Align = DL.getABITypeAlignment(PtrTy->getElementType());
4612 
4613  AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
4614  }
4615 }
4616 
4617 // Analyze interleaved accesses and collect them into interleaved load and
4618 // store groups.
4619 //
4620 // When generating code for an interleaved load group, we effectively hoist all
4621 // loads in the group to the location of the first load in program order. When
4622 // generating code for an interleaved store group, we sink all stores to the
4623 // location of the last store. This code motion can change the order of load
4624 // and store instructions and may break dependences.
4625 //
4626 // The code generation strategy mentioned above ensures that we won't violate
4627 // any write-after-read (WAR) dependences.
4628 //
4629 // E.g., for the WAR dependence: a = A[i]; // (1)
4630 // A[i] = b; // (2)
4631 //
4632 // The store group of (2) is always inserted at or below (2), and the load
4633 // group of (1) is always inserted at or above (1). Thus, the instructions will
4634 // never be reordered. All other dependences are checked to ensure the
4635 // correctness of the instruction reordering.
4636 //
4637 // The algorithm visits all memory accesses in the loop in bottom-up program
4638 // order. Program order is established by traversing the blocks in the loop in
4639 // reverse postorder when collecting the accesses.
4640 //
4641 // We visit the memory accesses in bottom-up order because it can simplify the
4642 // construction of store groups in the presence of write-after-write (WAW)
4643 // dependences.
4644 //
4645 // E.g., for the WAW dependence: A[i] = a; // (1)
4646 // A[i] = b; // (2)
4647 // A[i + 1] = c; // (3)
4648 //
4649 // We will first create a store group with (3) and (2). (1) can't be added to
4650 // this group because it and (2) are dependent. However, (1) can be grouped
4651 // with other accesses that may precede it in program order. Note that a
4652 // bottom-up order does not imply that WAW dependences should not be checked.
4653 void InterleavedAccessInfo::analyzeInterleaving() {
4654  LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4655  const ValueToValueMap &Strides = LAI->getSymbolicStrides();
4656 
4657  // Holds all accesses with a constant stride.
4659  collectConstStrideAccesses(AccessStrideInfo, Strides);
4660 
4661  if (AccessStrideInfo.empty())
4662  return;
4663 
4664  // Collect the dependences in the loop.
4665  collectDependences();
4666 
4667  // Holds all interleaved store groups temporarily.
4669  // Holds all interleaved load groups temporarily.
4671 
4672  // Search in bottom-up program order for pairs of accesses (A and B) that can
4673  // form interleaved load or store groups. In the algorithm below, access A
4674  // precedes access B in program order. We initialize a group for B in the
4675  // outer loop of the algorithm, and then in the inner loop, we attempt to
4676  // insert each A into B's group if:
4677  //
4678  // 1. A and B have the same stride,
4679  // 2. A and B have the same memory object size, and
4680  // 3. A belongs in B's group according to its distance from B.
4681  //
4682  // Special care is taken to ensure group formation will not break any
4683  // dependences.
4684  for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
4685  BI != E; ++BI) {
4686  Instruction *B = BI->first;
4687  StrideDescriptor DesB = BI->second;
4688 
4689  // Initialize a group for B if it has an allowable stride. Even if we don't
4690  // create a group for B, we continue with the bottom-up algorithm to ensure
4691  // we don't break any of B's dependences.
4692  InterleaveGroup *Group = nullptr;
4693  if (isStrided(DesB.Stride)) {
4694  Group = getInterleaveGroup(B);
4695  if (!Group) {
4696  LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
4697  << '\n');
4698  Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
4699  }
4700  if (B->mayWriteToMemory())
4701  StoreGroups.insert(Group);
4702  else
4703  LoadGroups.insert(Group);
4704  }
4705 
4706  for (auto AI = std::next(BI); AI != E; ++AI) {
4707  Instruction *A = AI->first;
4708  StrideDescriptor DesA = AI->second;
4709 
4710  // Our code motion strategy implies that we can't have dependences
4711  // between accesses in an interleaved group and other accesses located
4712  // between the first and last member of the group. Note that this also
4713  // means that a group can't have more than one member at a given offset.
4714  // The accesses in a group can have dependences with other accesses, but
4715  // we must ensure we don't extend the boundaries of the group such that
4716  // we encompass those dependent accesses.
4717  //
4718  // For example, assume we have the sequence of accesses shown below in a
4719  // stride-2 loop:
4720  //
4721  // (1, 2) is a group | A[i] = a; // (1)
4722  // | A[i-1] = b; // (2) |
4723  // A[i-3] = c; // (3)
4724  // A[i] = d; // (4) | (2, 4) is not a group
4725  //
4726  // Because accesses (2) and (3) are dependent, we can group (2) with (1)
4727  // but not with (4). If we did, the dependent access (3) would be within
4728  // the boundaries of the (2, 4) group.
4729  if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
4730  // If a dependence exists and A is already in a group, we know that A
4731  // must be a store since A precedes B and WAR dependences are allowed.
4732  // Thus, A would be sunk below B. We release A's group to prevent this
4733  // illegal code motion. A will then be free to form another group with
4734  // instructions that precede it.
4735  if (isInterleaved(A)) {
4736  InterleaveGroup *StoreGroup = getInterleaveGroup(A);
4737  StoreGroups.remove(StoreGroup);
4738  releaseGroup(StoreGroup);
4739  }
4740 
4741  // If a dependence exists and A is not already in a group (or it was
4742  // and we just released it), B might be hoisted above A (if B is a
4743  // load) or another store might be sunk below A (if B is a store). In
4744  // either case, we can't add additional instructions to B's group. B
4745  // will only form a group with instructions that it precedes.
4746  break;
4747  }
4748 
4749  // At this point, we've checked for illegal code motion. If either A or B
4750  // isn't strided, there's nothing left to do.
4751  if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
4752  continue;
4753 
4754  // Ignore A if it's already in a group or isn't the same kind of memory
4755  // operation as B.
4756  // Note that mayReadFromMemory() isn't mutually exclusive to mayWriteToMemory
4757  // in the case of atomic loads. We shouldn't see those here, canVectorizeMemory()
4758  // should have returned false - except for the case we asked for optimization
4759  // remarks.
4760  if (isInterleaved(A) || (A->mayReadFromMemory() != B->mayReadFromMemory())
4761  || (A->mayWriteToMemory() != B->mayWriteToMemory()))
4762  continue;
4763 
4764  // Check rules 1 and 2. Ignore A if its stride or size is different from
4765  // that of B.
4766  if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
4767  continue;
4768 
4769  // Ignore A if the memory object of A and B don't belong to the same
4770  // address space
4772  continue;
4773 
4774  // Calculate the distance from A to B.
4775  const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
4776  PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
4777  if (!DistToB)
4778  continue;
4779  int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
4780 
4781  // Check rule 3. Ignore A if its distance to B is not a multiple of the
4782  // size.
4783  if (DistanceToB % static_cast<int64_t>(DesB.Size))
4784  continue;
4785 
4786  // Ignore A if either A or B is in a predicated block. Although we
4787  // currently prevent group formation for predicated accesses, we may be
4788  // able to relax this limitation in the future once we handle more
4789  // complicated blocks.
4790  if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
4791  continue;
4792 
4793  // The index of A is the index of B plus A's distance to B in multiples
4794  // of the size.
4795  int IndexA =
4796  Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
4797 
4798  // Try to insert A into B's group.
4799  if (Group->insertMember(A, IndexA, DesA.Align)) {
4800  LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
4801  << " into the interleave group with" << *B
4802  << '\n');
4803  InterleaveGroupMap[A] = Group;
4804 
4805  // Set the first load in program order as the insert position.
4806  if (A->mayReadFromMemory())
4807  Group->setInsertPos(A);
4808  }
4809  } // Iteration over A accesses.
4810  } // Iteration over B accesses.
4811 
4812  // Remove interleaved store groups with gaps.
4813  for (InterleaveGroup *Group : StoreGroups)
4814  if (Group->getNumMembers() != Group->getFactor()) {
4815  LLVM_DEBUG(
4816  dbgs() << "LV: Invalidate candidate interleaved store group due "
4817  "to gaps.\n");
4818  releaseGroup(Group);
4819  }
4820  // Remove interleaved groups with gaps (currently only loads) whose memory
4821  // accesses may wrap around. We have to revisit the getPtrStride analysis,
4822  // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
4823  // not check wrapping (see documentation there).
4824  // FORNOW we use Assume=false;
4825  // TODO: Change to Assume=true but making sure we don't exceed the threshold
4826  // of runtime SCEV assumptions checks (thereby potentially failing to
4827  // vectorize altogether).
4828  // Additional optional optimizations:
4829  // TODO: If we are peeling the loop and we know that the first pointer doesn't
4830  // wrap then we can deduce that all pointers in the group don't wrap.
4831  // This means that we can forcefully peel the loop in order to only have to
4832  // check the first pointer for no-wrap. When we'll change to use Assume=true
4833  // we'll only need at most one runtime check per interleaved group.
4834  for (InterleaveGroup *Group : LoadGroups) {
4835  // Case 1: A full group. Can Skip the checks; For full groups, if the wide
4836  // load would wrap around the address space we would do a memory access at
4837  // nullptr even without the transformation.
4838  if (Group->getNumMembers() == Group->getFactor())
4839  continue;
4840 
4841  // Case 2: If first and last members of the group don't wrap this implies
4842  // that all the pointers in the group don't wrap.
4843  // So we check only group member 0 (which is always guaranteed to exist),
4844  // and group member Factor - 1; If the latter doesn't exist we rely on
4845  // peeling (if it is a non-reveresed accsess -- see Case 3).
4846  Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
4847  if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
4848  /*ShouldCheckWrap=*/true)) {
4849  LLVM_DEBUG(
4850  dbgs() << "LV: Invalidate candidate interleaved group due to "
4851  "first group member potentially pointer-wrapping.\n");
4852  releaseGroup(Group);
4853  continue;
4854  }
4855  Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
4856  if (LastMember) {
4857  Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
4858  if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
4859  /*ShouldCheckWrap=*/true)) {
4860  LLVM_DEBUG(
4861  dbgs() << "LV: Invalidate candidate interleaved group due to "
4862  "last group member potentially pointer-wrapping.\n");
4863  releaseGroup(Group);
4864  }
4865  } else {
4866  // Case 3: A non-reversed interleaved load group with gaps: We need
4867  // to execute at least one scalar epilogue iteration. This will ensure
4868  // we don't speculatively access memory out-of-bounds. We only need
4869  // to look for a member at index factor - 1, since every group must have
4870  // a member at index zero.
4871  if (Group->isReverse()) {
4872  LLVM_DEBUG(
4873  dbgs() << "LV: Invalidate candidate interleaved group due to "
4874  "a reverse access with gaps.\n");
4875  releaseGroup(Group);
4876  continue;
4877  }
4878  LLVM_DEBUG(
4879  dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
4880  RequiresScalarEpilogue = true;
4881  }
4882  }
4883 }
4884 
4887  // TODO: It may by useful to do since it's still likely to be dynamically
4888  // uniform if the target can skip.
4889  LLVM_DEBUG(
4890  dbgs() << "LV: Not inserting runtime ptr check for divergent target");
4891 
4892  ORE->emit(
4893  createMissedAnalysis("CantVersionLoopWithDivergentTarget")
4894  << "runtime pointer checks needed. Not enabled for divergent target");
4895 
4896  return None;
4897  }
4898 
4899  unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
4900  if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
4901  return computeFeasibleMaxVF(OptForSize, TC);
4902 
4904  ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
4905  << "runtime pointer checks needed. Enable vectorization of this "
4906  "loop with '#pragma clang loop vectorize(enable)' when "
4907  "compiling with -Os/-Oz");
4908  LLVM_DEBUG(
4909  dbgs()
4910  << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4911  return None;
4912  }
4913 
4914  // If we optimize the program for size, avoid creating the tail loop.
4915  LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4916 
4917  // If we don't know the precise trip count, don't try to vectorize.
4918  if (TC < 2) {
4919  ORE->emit(
4920  createMissedAnalysis("UnknownLoopCountComplexCFG")
4921  << "unable to calculate the loop count due to complex control flow");
4922  LLVM_DEBUG(
4923  dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4924  return None;
4925  }
4926 
4927  unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
4928 
4929  if (TC % MaxVF != 0) {
4930  // If the trip count that we found modulo the vectorization factor is not
4931  // zero then we require a tail.
4932  // FIXME: look for a smaller MaxVF that does divide TC rather than give up.
4933  // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a
4934  // smaller MaxVF that does not require a scalar epilog.
4935 
4936  ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
4937  << "cannot optimize for size and vectorize at the "
4938  "same time. Enable vectorization of this loop "
4939  "with '#pragma clang loop vectorize(enable)' "
4940  "when compiling with -Os/-Oz");
4941  LLVM_DEBUG(
4942  dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4943  return None;
4944  }
4945 
4946  return MaxVF;
4947 }
4948 
4949 unsigned
4950 LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
4951  unsigned ConstTripCount) {
4952  MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4953  unsigned SmallestType, WidestType;
4954  std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4955  unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4956 
4957  // Get the maximum safe dependence distance in bits computed by LAA.
4958  // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4959  // the memory accesses that is most restrictive (involved in the smallest
4960  // dependence distance).
4961  unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
4962 
4963  WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
4964 
4965  unsigned MaxVectorSize = WidestRegister / WidestType;
4966 
4967  LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
4968  << " / " << WidestType << " bits.\n");
4969  LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
4970  << WidestRegister << " bits.\n");
4971 
4972  assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"
4973  " into one vector!");
4974  if (MaxVectorSize == 0) {
4975  LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4976  MaxVectorSize = 1;
4977  return MaxVectorSize;
4978  } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
4979  isPowerOf2_32(ConstTripCount)) {
4980  // We need to clamp the VF to be the ConstTripCount. There is no point in
4981  // choosing a higher viable VF as done in the loop below.
4982  LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
4983  << ConstTripCount << "\n");
4984  MaxVectorSize = ConstTripCount;
4985  return MaxVectorSize;
4986  }
4987 
4988  unsigned MaxVF = MaxVectorSize;
4989  if (TTI.shouldMaximizeVectorBandwidth(OptForSize) ||
4990  (MaximizeBandwidth && !OptForSize)) {
4991  // Collect all viable vectorization factors larger than the default MaxVF
4992  // (i.e. MaxVectorSize).
4994  unsigned NewMaxVectorSize = WidestRegister / SmallestType;
4995  for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
4996  VFs.push_back(VS);
4997 
4998  // For each VF calculate its register usage.
4999  auto RUs = calculateRegisterUsage(VFs);
5000 
5001  // Select the largest VF which doesn't require more registers than existing
5002  // ones.
5003  unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
5004  for (int i = RUs.size() - 1; i >= 0; --i) {
5005  if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
5006  MaxVF = VFs[i];
5007  break;
5008  }
5009  }
5010  if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
5011  if (MaxVF < MinVF) {
5012  LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5013  << ") with target's minimum: " << MinVF << '\n');
5014  MaxVF = MinVF;
5015  }
5016  }
5017  }
5018  return MaxVF;
5019 }
5020 
5023  float Cost = expectedCost(1).first;
5024  const float ScalarCost = Cost;
5025  unsigned Width = 1;
5026  LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5027 
5028  bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5029  if (ForceVectorization && MaxVF > 1) {
5030