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 
57 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
58 #include "LoopVectorizationPlanner.h"
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"
76 #include "llvm/ADT/iterator_range.h"
77 #include "llvm/Analysis/AssumptionCache.h"
78 #include "llvm/Analysis/BasicAliasAnalysis.h"
79 #include "llvm/Analysis/BlockFrequencyInfo.h"
80 #include "llvm/Analysis/CFG.h"
81 #include "llvm/Analysis/CodeMetrics.h"
82 #include "llvm/Analysis/DemandedBits.h"
83 #include "llvm/Analysis/GlobalsModRef.h"
84 #include "llvm/Analysis/LoopAccessAnalysis.h"
85 #include "llvm/Analysis/LoopAnalysisManager.h"
86 #include "llvm/Analysis/LoopInfo.h"
87 #include "llvm/Analysis/LoopIterator.h"
88 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
89 #include "llvm/Analysis/ScalarEvolution.h"
90 #include "llvm/Analysis/ScalarEvolutionExpander.h"
91 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
92 #include "llvm/Analysis/TargetLibraryInfo.h"
93 #include "llvm/Analysis/TargetTransformInfo.h"
94 #include "llvm/Analysis/VectorUtils.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"
101 #include "llvm/IR/DebugInfoMetadata.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"
125 #include "llvm/Support/CommandLine.h"
126 #include "llvm/Support/Compiler.h"
127 #include "llvm/Support/Debug.h"
128 #include "llvm/Support/ErrorHandling.h"
129 #include "llvm/Support/MathExtras.h"
130 #include "llvm/Support/raw_ostream.h"
131 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
132 #include "llvm/Transforms/Utils/LoopSimplify.h"
133 #include "llvm/Transforms/Utils/LoopUtils.h"
134 #include "llvm/Transforms/Utils/LoopVersioning.h"
135 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.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.
159 static cl::opt<unsigned> TinyTripCountVectorThreshold(
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 
165 static cl::opt<bool> MaximizeBandwidth(
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 
170 static cl::opt<bool> EnableInterleavedMemAccesses(
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.
175 static cl::opt<unsigned> MaxInterleaveGroupFactor(
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 
184 static cl::opt<unsigned> ForceTargetNumScalarRegs(
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 
188 static cl::opt<unsigned> ForceTargetNumVectorRegs(
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 
192 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
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 
197 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
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 
202 static cl::opt<unsigned> ForceTargetInstructionCost(
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 
208 static cl::opt<unsigned> SmallLoopCost(
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 
213 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
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.
220 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
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.
226 static cl::opt<unsigned> NumberOfStoresToPredicate(
227     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
228     cl::desc("Max number of stores to be predicated behind an if."));
229 
230 static cl::opt<bool> EnableIndVarRegisterHeur(
231     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
232     cl::desc("Count the induction variable only once when interleaving"));
233 
234 static cl::opt<bool> EnableCondStoresVectorization(
235     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
236     cl::desc("Enable if predication of stores during vectorization."));
237 
238 static cl::opt<unsigned> MaxNestedScalarReductionIC(
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 
243 static cl::opt<bool> EnableVPlanNativePath(
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.
252 static cl::opt<bool> VPlanBuildStressTest(
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.
273 static Type *getMemInstValueType(Value *I) {
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.
325 static Value *addFastMathFlag(Value *V) {
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.
357 class InnerLoopVectorizer {
358 public:
359   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
360                       LoopInfo *LI, DominatorTree *DT,
361                       const TargetLibraryInfo *TLI,
362                       const TargetTransformInfo *TTI, AssumptionCache *AC,
363                       OptimizationRemarkEmitter *ORE, unsigned VecWidth,
364                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
365                       LoopVectorizationCostModel *CM)
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.
374   BasicBlock *createVectorizedLoopSkeleton();
375 
376   /// Widen a single instruction within the innermost loop.
377   void widenInstruction(Instruction &I);
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.
383   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
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.
388   using VectorParts = SmallVector<Value *, 2>;
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.
440   void vectorizeInterleaveGroup(Instruction *Instr);
441 
442   /// Vectorize Load and Store instructions, optionally masking the vector
443   /// operations if \p BlockInMask is non-null.
444   void vectorizeMemoryInstruction(Instruction *Instr,
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:
452   friend class LoopVectorizationPlanner;
453 
454   /// A small list of PHINodes.
455   using PhiVector = SmallVector<PHINode *, 4>;
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.
461   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
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.
495   void truncateToMinimalBitwidths();
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.
528   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
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.
533   bool shouldScalarizeInstruction(Instruction *I) const;
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.
556   void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID,
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.
569   Value *getOrCreateVectorTripCount(Loop *NewLoop);
570 
571   /// Returns a bitcasted value to the requested vector type.
572   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
573   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
574                                 const DataLayout &DL);
575 
576   /// Emit a bypass check to see if the vector trip count is zero, including if
577   /// it overflows.
578   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
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.
606   Loop *OrigLoop;
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.
611   PredicatedScalarEvolution &PSE;
612 
613   /// Loop Info.
614   LoopInfo *LI;
615 
616   /// Dominator Tree.
617   DominatorTree *DT;
618 
619   /// Alias Analysis.
620   AliasAnalysis *AA;
621 
622   /// Target Library Info.
623   const TargetLibraryInfo *TLI;
624 
625   /// Target Transform Info.
626   const TargetTransformInfo *TTI;
627 
628   /// Assumption Cache.
629   AssumptionCache *AC;
630 
631   /// Interface to emit optimization remarks.
632   OptimizationRemarkEmitter *ORE;
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
650   IRBuilder<> Builder;
651 
652   // --- Vectorization state ---
653 
654   /// The vector-loop preheader.
655   BasicBlock *LoopVectorPreHeader;
656 
657   /// The scalar-loop preheader.
658   BasicBlock *LoopScalarPreHeader;
659 
660   /// Middle Block between the vector and the scalar.
661   BasicBlock *LoopMiddleBlock;
662 
663   /// The ExitBlock of the scalar loop.
664   BasicBlock *LoopExitBlock;
665 
666   /// The vector loop body.
667   BasicBlock *LoopVectorBody;
668 
669   /// The scalar loop body.
670   BasicBlock *LoopScalarBody;
671 
672   /// A list of all bypass blocks. The first block is the entry of the loop.
673   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
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.
685   VectorizerValueMap VectorLoopValueMap;
686 
687   /// Store instructions that were predicated.
688   SmallVector<Instruction *, 4> PredicatedInstructions;
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.
697   LoopVectorizationLegality *Legal;
698 
699   /// The profitablity analysis.
700   LoopVectorizationCostModel *Cost;
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.
707   DenseMap<PHINode *, Value *> IVEndValues;
708 };
709 
710 class InnerLoopUnroller : public InnerLoopVectorizer {
711 public:
712   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
713                     LoopInfo *LI, DominatorTree *DT,
714                     const TargetLibraryInfo *TLI,
715                     const TargetTransformInfo *TTI, AssumptionCache *AC,
716                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
717                     LoopVectorizationLegality *LVL,
718                     LoopVectorizationCostModel *CM)
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.
734 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
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 
751 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
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))
756       B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
757     else
758       B.SetCurrentDebugLocation(DIL);
759   } else
760     B.SetCurrentDebugLocation(DebugLoc());
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 
780 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
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 
788 void InnerLoopVectorizer::addMetadata(Instruction *To,
789                                       Instruction *From) {
790   propagateMetadata(To, From);
791   addNewMetadata(To, From);
792 }
793 
794 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
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.
830 class InterleaveGroup {
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 {
913     SmallVector<Value *, 4> VL;
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;
923   DenseMap<int, Instruction *> Members;
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,
955                         DominatorTree *DT, LoopInfo *LI,
956                         const LoopAccessInfo *LAI)
957     : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(LAI) {}
958 
959   ~InterleavedAccessInfo() {
960     SmallPtrSet<InterleaveGroup *, 4> DelSet;
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).
995   PredicatedScalarEvolution &PSE;
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.
1012   DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
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(
1060       MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
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 
1142 static void emitMissedWarning(Function *F, Loop *L,
1143                               const LoopVectorizeHints &LH,
1144                               OptimizationRemarkEmitter *ORE) {
1145   LH.emitRemarkWithHints();
1146 
1147   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1148     if (LH.getWidth() != 1)
1149       ORE->emit(DiagnosticInfoOptimizationFailure(
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)
1155       ORE->emit(DiagnosticInfoOptimizationFailure(
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.
1172 class LoopVectorizationCostModel {
1173 public:
1174   LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1175                              LoopInfo *LI, LoopVectorizationLegality *Legal,
1176                              const TargetTransformInfo &TTI,
1177                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1178                              AssumptionCache *AC,
1179                              OptimizationRemarkEmitter *ORE, const Function *F,
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.
1226     unsigned LoopInvariantRegs;
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.
1242   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
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.
1282   enum InstWidening {
1283     CM_Unknown,
1284     CM_Widen,         // For consecutive accesses with stride +1.
1285     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1286     CM_Interleave,
1287     CM_GatherScatter,
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.
1293   void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
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.
1319   InstWidening getWideningDecision(Instruction *I, unsigned VF) {
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.
1381   bool isLegalMaskedStore(Type *DataType, Value *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.
1387   bool isLegalMaskedLoad(Type *DataType, Value *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.
1393   bool isLegalMaskedScatter(Type *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.
1399   bool isLegalMaskedGather(Type *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.
1405   bool isLegalGatherOrScatter(Value *V) {
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.
1424   bool isAccessInterleaved(Instruction *Instr) {
1425     return InterleaveInfo.isInterleaved(Instr);
1426   }
1427 
1428   /// Get the interleaved access group that \p Instr belongs to.
1429   const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
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.
1509   MapVector<Instruction *, uint64_t> MinBWs;
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.
1514   using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
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.
1528   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
1529 
1530   /// Holds the instructions known to be scalar after vectorization.
1531   /// The data is collected per VF.
1532   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
1533 
1534   /// Holds the instructions (address computations) that are forced to be
1535   /// scalarized.
1536   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
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.
1566   using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
1567                                 std::pair<InstWidening, unsigned>>;
1568 
1569   DecisionList WideningDecisions;
1570 
1571 public:
1572   /// The loop that we evaluate.
1573   Loop *TheLoop;
1574 
1575   /// Predicated scalar evolution analysis.
1576   PredicatedScalarEvolution &PSE;
1577 
1578   /// Loop Info analysis.
1579   LoopInfo *LI;
1580 
1581   /// Vectorization legality.
1582   LoopVectorizationLegality *Legal;
1583 
1584   /// Vector target information.
1585   const TargetTransformInfo &TTI;
1586 
1587   /// Target Library Info.
1588   const TargetLibraryInfo *TLI;
1589 
1590   /// Demanded bits analysis.
1591   DemandedBits *DB;
1592 
1593   /// Assumption cache.
1594   AssumptionCache *AC;
1595 
1596   /// Interface to emit optimization remarks.
1597   OptimizationRemarkEmitter *ORE;
1598 
1599   const Function *TheFunction;
1600 
1601   /// Loop Vectorize Hint.
1602   const LoopVectorizeHints *Hints;
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.
1609   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1610 
1611   /// Values to ignore in the cost model when VF > 1.
1612   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
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,
1632                                    OptimizationRemarkEmitter *ORE) {
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 
1664 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
1665                                   OptimizationRemarkEmitter *ORE,
1666                                   SmallVectorImpl<Loop *> &V) {
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 ||
1672       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
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;
1702     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
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 {
1730     AU.addRequired<AssumptionCacheTracker>();
1731     AU.addRequired<BlockFrequencyInfoWrapperPass>();
1732     AU.addRequired<DominatorTreeWrapperPass>();
1733     AU.addRequired<LoopInfoWrapperPass>();
1734     AU.addRequired<ScalarEvolutionWrapperPass>();
1735     AU.addRequired<TargetTransformInfoWrapperPass>();
1736     AU.addRequired<AAResultsWrapperPass>();
1737     AU.addRequired<LoopAccessLegacyAnalysis>();
1738     AU.addRequired<DemandedBitsWrapperPass>();
1739     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1740     AU.addPreserved<LoopInfoWrapperPass>();
1741     AU.addPreserved<DominatorTreeWrapperPass>();
1742     AU.addPreserved<BasicAAWrapperPass>();
1743     AU.addPreserved<GlobalsAAWrapperPass>();
1744   }
1745 };
1746 
1747 } // end anonymous namespace
1748 
1749 //===----------------------------------------------------------------------===//
1750 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1751 // LoopVectorizationCostModel and LoopVectorizationPlanner.
1752 //===----------------------------------------------------------------------===//
1753 
1754 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
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 ||
1761                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
1762   // Place the code for broadcasting invariant variables in the new preheader.
1763   IRBuilder<>::InsertPointGuard Guard(Builder);
1764   if (SafeToHoist)
1765     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
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 
1773 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
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();
1781   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
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",
1823                                     &*LoopVectorBody->getFirstInsertionPt());
1824   Instruction *LastInduction = VecInd;
1825   for (unsigned Part = 0; Part < UF; ++Part) {
1826     VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
1827 
1828     if (isa<TruncInst>(EntryVal))
1829       addMetadata(LastInduction, EntryVal);
1830     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
1831 
1832     LastInduction = cast<Instruction>(addFastMathFlag(
1833         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
1834   }
1835 
1836   // Move the last step to the end of the latch block. This ensures consistent
1837   // placement of all induction updates.
1838   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
1839   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
1840   auto *ICmp = cast<Instruction>(Br->getCondition());
1841   LastInduction->moveBefore(ICmp);
1842   LastInduction->setName("vec.ind.next");
1843 
1844   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
1845   VecInd->addIncoming(LastInduction, LoopVectorLatch);
1846 }
1847 
1848 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
1849   return Cost->isScalarAfterVectorization(I, VF) ||
1850          Cost->isProfitableToScalarize(I, VF);
1851 }
1852 
1853 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
1854   if (shouldScalarizeInstruction(IV))
1855     return true;
1856   auto isScalarInst = [&](User *U) -> bool {
1857     auto *I = cast<Instruction>(U);
1858     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
1859   };
1860   return llvm::any_of(IV->users(), isScalarInst);
1861 }
1862 
1863 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
1864     const InductionDescriptor &ID, const Instruction *EntryVal,
1865     Value *VectorLoopVal, unsigned Part, unsigned Lane) {
1866   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1867          "Expected either an induction phi-node or a truncate of it!");
1868 
1869   // This induction variable is not the phi from the original loop but the
1870   // newly-created IV based on the proof that casted Phi is equal to the
1871   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
1872   // re-uses the same InductionDescriptor that original IV uses but we don't
1873   // have to do any recording in this case - that is done when original IV is
1874   // processed.
1875   if (isa<TruncInst>(EntryVal))
1876     return;
1877 
1878   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
1879   if (Casts.empty())
1880     return;
1881   // Only the first Cast instruction in the Casts vector is of interest.
1882   // The rest of the Casts (if exist) have no uses outside the
1883   // induction update chain itself.
1884   Instruction *CastInst = *Casts.begin();
1885   if (Lane < UINT_MAX)
1886     VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
1887   else
1888     VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
1889 }
1890 
1891 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
1892   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
1893          "Primary induction variable must have an integer type");
1894 
1895   auto II = Legal->getInductionVars()->find(IV);
1896   assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
1897 
1898   auto ID = II->second;
1899   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
1900 
1901   // The scalar value to broadcast. This will be derived from the canonical
1902   // induction variable.
1903   Value *ScalarIV = nullptr;
1904 
1905   // The value from the original loop to which we are mapping the new induction
1906   // variable.
1907   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
1908 
1909   // True if we have vectorized the induction variable.
1910   auto VectorizedIV = false;
1911 
1912   // Determine if we want a scalar version of the induction variable. This is
1913   // true if the induction variable itself is not widened, or if it has at
1914   // least one user in the loop that is not widened.
1915   auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
1916 
1917   // Generate code for the induction step. Note that induction steps are
1918   // required to be loop-invariant
1919   assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
1920          "Induction step should be loop invariant");
1921   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
1922   Value *Step = nullptr;
1923   if (PSE.getSE()->isSCEVable(IV->getType())) {
1924     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
1925     Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
1926                              LoopVectorPreHeader->getTerminator());
1927   } else {
1928     Step = cast<SCEVUnknown>(ID.getStep())->getValue();
1929   }
1930 
1931   // Try to create a new independent vector induction variable. If we can't
1932   // create the phi node, we will splat the scalar induction variable in each
1933   // loop iteration.
1934   if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
1935     createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
1936     VectorizedIV = true;
1937   }
1938 
1939   // If we haven't yet vectorized the induction variable, or if we will create
1940   // a scalar one, we need to define the scalar induction variable and step
1941   // values. If we were given a truncation type, truncate the canonical
1942   // induction variable and step. Otherwise, derive these values from the
1943   // induction descriptor.
1944   if (!VectorizedIV || NeedsScalarIV) {
1945     ScalarIV = Induction;
1946     if (IV != OldInduction) {
1947       ScalarIV = IV->getType()->isIntegerTy()
1948                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
1949                      : Builder.CreateCast(Instruction::SIToFP, Induction,
1950                                           IV->getType());
1951       ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
1952       ScalarIV->setName("offset.idx");
1953     }
1954     if (Trunc) {
1955       auto *TruncType = cast<IntegerType>(Trunc->getType());
1956       assert(Step->getType()->isIntegerTy() &&
1957              "Truncation requires an integer step");
1958       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
1959       Step = Builder.CreateTrunc(Step, TruncType);
1960     }
1961   }
1962 
1963   // If we haven't yet vectorized the induction variable, splat the scalar
1964   // induction variable, and build the necessary step vectors.
1965   // TODO: Don't do it unless the vectorized IV is really required.
1966   if (!VectorizedIV) {
1967     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
1968     for (unsigned Part = 0; Part < UF; ++Part) {
1969       Value *EntryPart =
1970           getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
1971       VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
1972       if (Trunc)
1973         addMetadata(EntryPart, Trunc);
1974       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
1975     }
1976   }
1977 
1978   // If an induction variable is only used for counting loop iterations or
1979   // calculating addresses, it doesn't need to be widened. Create scalar steps
1980   // that can be used by instructions we will later scalarize. Note that the
1981   // addition of the scalar steps will not increase the number of instructions
1982   // in the loop in the common case prior to InstCombine. We will be trading
1983   // one vector extract for each scalar step.
1984   if (NeedsScalarIV)
1985     buildScalarSteps(ScalarIV, Step, EntryVal, ID);
1986 }
1987 
1988 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
1989                                           Instruction::BinaryOps BinOp) {
1990   // Create and check the types.
1991   assert(Val->getType()->isVectorTy() && "Must be a vector");
1992   int VLen = Val->getType()->getVectorNumElements();
1993 
1994   Type *STy = Val->getType()->getScalarType();
1995   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
1996          "Induction Step must be an integer or FP");
1997   assert(Step->getType() == STy && "Step has wrong type");
1998 
1999   SmallVector<Constant *, 8> Indices;
2000 
2001   if (STy->isIntegerTy()) {
2002     // Create a vector of consecutive numbers from zero to VF.
2003     for (int i = 0; i < VLen; ++i)
2004       Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2005 
2006     // Add the consecutive indices to the vector value.
2007     Constant *Cv = ConstantVector::get(Indices);
2008     assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2009     Step = Builder.CreateVectorSplat(VLen, Step);
2010     assert(Step->getType() == Val->getType() && "Invalid step vec");
2011     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2012     // which can be found from the original scalar operations.
2013     Step = Builder.CreateMul(Cv, Step);
2014     return Builder.CreateAdd(Val, Step, "induction");
2015   }
2016 
2017   // Floating point induction.
2018   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2019          "Binary Opcode should be specified for FP induction");
2020   // Create a vector of consecutive numbers from zero to VF.
2021   for (int i = 0; i < VLen; ++i)
2022     Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2023 
2024   // Add the consecutive indices to the vector value.
2025   Constant *Cv = ConstantVector::get(Indices);
2026 
2027   Step = Builder.CreateVectorSplat(VLen, Step);
2028 
2029   // Floating point operations had to be 'fast' to enable the induction.
2030   FastMathFlags Flags;
2031   Flags.setFast();
2032 
2033   Value *MulOp = Builder.CreateFMul(Cv, Step);
2034   if (isa<Instruction>(MulOp))
2035     // Have to check, MulOp may be a constant
2036     cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2037 
2038   Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2039   if (isa<Instruction>(BOp))
2040     cast<Instruction>(BOp)->setFastMathFlags(Flags);
2041   return BOp;
2042 }
2043 
2044 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2045                                            Instruction *EntryVal,
2046                                            const InductionDescriptor &ID) {
2047   // We shouldn't have to build scalar steps if we aren't vectorizing.
2048   assert(VF > 1 && "VF should be greater than one");
2049 
2050   // Get the value type and ensure it and the step have the same integer type.
2051   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2052   assert(ScalarIVTy == Step->getType() &&
2053          "Val and Step should have the same type");
2054 
2055   // We build scalar steps for both integer and floating-point induction
2056   // variables. Here, we determine the kind of arithmetic we will perform.
2057   Instruction::BinaryOps AddOp;
2058   Instruction::BinaryOps MulOp;
2059   if (ScalarIVTy->isIntegerTy()) {
2060     AddOp = Instruction::Add;
2061     MulOp = Instruction::Mul;
2062   } else {
2063     AddOp = ID.getInductionOpcode();
2064     MulOp = Instruction::FMul;
2065   }
2066 
2067   // Determine the number of scalars we need to generate for each unroll
2068   // iteration. If EntryVal is uniform, we only need to generate the first
2069   // lane. Otherwise, we generate all VF values.
2070   unsigned Lanes =
2071       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
2072                                                                          : VF;
2073   // Compute the scalar steps and save the results in VectorLoopValueMap.
2074   for (unsigned Part = 0; Part < UF; ++Part) {
2075     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2076       auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2077       auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2078       auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2079       VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
2080       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
2081     }
2082   }
2083 }
2084 
2085 Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
2086   assert(V != Induction && "The new induction variable should not be used.");
2087   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2088   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2089 
2090   // If we have a stride that is replaced by one, do it here.
2091   if (Legal->hasStride(V))
2092     V = ConstantInt::get(V->getType(), 1);
2093 
2094   // If we have a vector mapped to this value, return it.
2095   if (VectorLoopValueMap.hasVectorValue(V, Part))
2096     return VectorLoopValueMap.getVectorValue(V, Part);
2097 
2098   // If the value has not been vectorized, check if it has been scalarized
2099   // instead. If it has been scalarized, and we actually need the value in
2100   // vector form, we will construct the vector values on demand.
2101   if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2102     Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
2103 
2104     // If we've scalarized a value, that value should be an instruction.
2105     auto *I = cast<Instruction>(V);
2106 
2107     // If we aren't vectorizing, we can just copy the scalar map values over to
2108     // the vector map.
2109     if (VF == 1) {
2110       VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2111       return ScalarValue;
2112     }
2113 
2114     // Get the last scalar instruction we generated for V and Part. If the value
2115     // is known to be uniform after vectorization, this corresponds to lane zero
2116     // of the Part unroll iteration. Otherwise, the last instruction is the one
2117     // we created for the last vector lane of the Part unroll iteration.
2118     unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2119     auto *LastInst = cast<Instruction>(
2120         VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
2121 
2122     // Set the insert point after the last scalarized instruction. This ensures
2123     // the insertelement sequence will directly follow the scalar definitions.
2124     auto OldIP = Builder.saveIP();
2125     auto NewIP = std::next(BasicBlock::iterator(LastInst));
2126     Builder.SetInsertPoint(&*NewIP);
2127 
2128     // However, if we are vectorizing, we need to construct the vector values.
2129     // If the value is known to be uniform after vectorization, we can just
2130     // broadcast the scalar value corresponding to lane zero for each unroll
2131     // iteration. Otherwise, we construct the vector values using insertelement
2132     // instructions. Since the resulting vectors are stored in
2133     // VectorLoopValueMap, we will only generate the insertelements once.
2134     Value *VectorValue = nullptr;
2135     if (Cost->isUniformAfterVectorization(I, VF)) {
2136       VectorValue = getBroadcastInstrs(ScalarValue);
2137       VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2138     } else {
2139       // Initialize packing with insertelements to start from undef.
2140       Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
2141       VectorLoopValueMap.setVectorValue(V, Part, Undef);
2142       for (unsigned Lane = 0; Lane < VF; ++Lane)
2143         packScalarIntoVectorValue(V, {Part, Lane});
2144       VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2145     }
2146     Builder.restoreIP(OldIP);
2147     return VectorValue;
2148   }
2149 
2150   // If this scalar is unknown, assume that it is a constant or that it is
2151   // loop invariant. Broadcast V and save the value for future uses.
2152   Value *B = getBroadcastInstrs(V);
2153   VectorLoopValueMap.setVectorValue(V, Part, B);
2154   return B;
2155 }
2156 
2157 Value *
2158 InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
2159                                             const VPIteration &Instance) {
2160   // If the value is not an instruction contained in the loop, it should
2161   // already be scalar.
2162   if (OrigLoop->isLoopInvariant(V))
2163     return V;
2164 
2165   assert(Instance.Lane > 0
2166              ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2167              : true && "Uniform values only have lane zero");
2168 
2169   // If the value from the original loop has not been vectorized, it is
2170   // represented by UF x VF scalar values in the new loop. Return the requested
2171   // scalar value.
2172   if (VectorLoopValueMap.hasScalarValue(V, Instance))
2173     return VectorLoopValueMap.getScalarValue(V, Instance);
2174 
2175   // If the value has not been scalarized, get its entry in VectorLoopValueMap
2176   // for the given unroll part. If this entry is not a vector type (i.e., the
2177   // vectorization factor is one), there is no need to generate an
2178   // extractelement instruction.
2179   auto *U = getOrCreateVectorValue(V, Instance.Part);
2180   if (!U->getType()->isVectorTy()) {
2181     assert(VF == 1 && "Value not scalarized has non-vector type");
2182     return U;
2183   }
2184 
2185   // Otherwise, the value from the original loop has been vectorized and is
2186   // represented by UF vector values. Extract and return the requested scalar
2187   // value from the appropriate vector lane.
2188   return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2189 }
2190 
2191 void InnerLoopVectorizer::packScalarIntoVectorValue(
2192     Value *V, const VPIteration &Instance) {
2193   assert(V != Induction && "The new induction variable should not be used.");
2194   assert(!V->getType()->isVectorTy() && "Can't pack a vector");
2195   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2196 
2197   Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2198   Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2199   VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2200                                             Builder.getInt32(Instance.Lane));
2201   VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2202 }
2203 
2204 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2205   assert(Vec->getType()->isVectorTy() && "Invalid type");
2206   SmallVector<Constant *, 8> ShuffleMask;
2207   for (unsigned i = 0; i < VF; ++i)
2208     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2209 
2210   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2211                                      ConstantVector::get(ShuffleMask),
2212                                      "reverse");
2213 }
2214 
2215 // Try to vectorize the interleave group that \p Instr belongs to.
2216 //
2217 // E.g. Translate following interleaved load group (factor = 3):
2218 //   for (i = 0; i < N; i+=3) {
2219 //     R = Pic[i];             // Member of index 0
2220 //     G = Pic[i+1];           // Member of index 1
2221 //     B = Pic[i+2];           // Member of index 2
2222 //     ... // do something to R, G, B
2223 //   }
2224 // To:
2225 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2226 //   %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9>   ; R elements
2227 //   %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10>  ; G elements
2228 //   %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11>  ; B elements
2229 //
2230 // Or translate following interleaved store group (factor = 3):
2231 //   for (i = 0; i < N; i+=3) {
2232 //     ... do something to R, G, B
2233 //     Pic[i]   = R;           // Member of index 0
2234 //     Pic[i+1] = G;           // Member of index 1
2235 //     Pic[i+2] = B;           // Member of index 2
2236 //   }
2237 // To:
2238 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2239 //   %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2240 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2241 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2242 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2243 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2244   const InterleaveGroup *Group = Cost->getInterleavedAccessGroup(Instr);
2245   assert(Group && "Fail to get an interleaved access group.");
2246 
2247   // Skip if current instruction is not the insert position.
2248   if (Instr != Group->getInsertPos())
2249     return;
2250 
2251   const DataLayout &DL = Instr->getModule()->getDataLayout();
2252   Value *Ptr = getLoadStorePointerOperand(Instr);
2253 
2254   // Prepare for the vector type of the interleaved load/store.
2255   Type *ScalarTy = getMemInstValueType(Instr);
2256   unsigned InterleaveFactor = Group->getFactor();
2257   Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2258   Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2259 
2260   // Prepare for the new pointers.
2261   setDebugLocFromInst(Builder, Ptr);
2262   SmallVector<Value *, 2> NewPtrs;
2263   unsigned Index = Group->getIndex(Instr);
2264 
2265   // If the group is reverse, adjust the index to refer to the last vector lane
2266   // instead of the first. We adjust the index from the first vector lane,
2267   // rather than directly getting the pointer for lane VF - 1, because the
2268   // pointer operand of the interleaved access is supposed to be uniform. For
2269   // uniform instructions, we're only required to generate a value for the
2270   // first vector lane in each unroll iteration.
2271   if (Group->isReverse())
2272     Index += (VF - 1) * Group->getFactor();
2273 
2274   bool InBounds = false;
2275   if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2276     InBounds = gep->isInBounds();
2277 
2278   for (unsigned Part = 0; Part < UF; Part++) {
2279     Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
2280 
2281     // Notice current instruction could be any index. Need to adjust the address
2282     // to the member of index 0.
2283     //
2284     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2285     //       b = A[i];       // Member of index 0
2286     // Current pointer is pointed to A[i+1], adjust it to A[i].
2287     //
2288     // E.g.  A[i+1] = a;     // Member of index 1
2289     //       A[i]   = b;     // Member of index 0
2290     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2291     // Current pointer is pointed to A[i+2], adjust it to A[i].
2292     NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2293     if (InBounds)
2294       cast<GetElementPtrInst>(NewPtr)->setIsInBounds(true);
2295 
2296     // Cast to the vector pointer type.
2297     NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2298   }
2299 
2300   setDebugLocFromInst(Builder, Instr);
2301   Value *UndefVec = UndefValue::get(VecTy);
2302 
2303   // Vectorize the interleaved load group.
2304   if (isa<LoadInst>(Instr)) {
2305     // For each unroll part, create a wide load for the group.
2306     SmallVector<Value *, 2> NewLoads;
2307     for (unsigned Part = 0; Part < UF; Part++) {
2308       auto *NewLoad = Builder.CreateAlignedLoad(
2309           NewPtrs[Part], Group->getAlignment(), "wide.vec");
2310       Group->addMetadata(NewLoad);
2311       NewLoads.push_back(NewLoad);
2312     }
2313 
2314     // For each member in the group, shuffle out the appropriate data from the
2315     // wide loads.
2316     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2317       Instruction *Member = Group->getMember(I);
2318 
2319       // Skip the gaps in the group.
2320       if (!Member)
2321         continue;
2322 
2323       Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2324       for (unsigned Part = 0; Part < UF; Part++) {
2325         Value *StridedVec = Builder.CreateShuffleVector(
2326             NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2327 
2328         // If this member has different type, cast the result type.
2329         if (Member->getType() != ScalarTy) {
2330           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2331           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2332         }
2333 
2334         if (Group->isReverse())
2335           StridedVec = reverseVector(StridedVec);
2336 
2337         VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2338       }
2339     }
2340     return;
2341   }
2342 
2343   // The sub vector type for current instruction.
2344   VectorType *SubVT = VectorType::get(ScalarTy, VF);
2345 
2346   // Vectorize the interleaved store group.
2347   for (unsigned Part = 0; Part < UF; Part++) {
2348     // Collect the stored vector from each member.
2349     SmallVector<Value *, 4> StoredVecs;
2350     for (unsigned i = 0; i < InterleaveFactor; i++) {
2351       // Interleaved store group doesn't allow a gap, so each index has a member
2352       Instruction *Member = Group->getMember(i);
2353       assert(Member && "Fail to get a member from an interleaved store group");
2354 
2355       Value *StoredVec = getOrCreateVectorValue(
2356           cast<StoreInst>(Member)->getValueOperand(), Part);
2357       if (Group->isReverse())
2358         StoredVec = reverseVector(StoredVec);
2359 
2360       // If this member has different type, cast it to a unified type.
2361 
2362       if (StoredVec->getType() != SubVT)
2363         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2364 
2365       StoredVecs.push_back(StoredVec);
2366     }
2367 
2368     // Concatenate all vectors into a wide vector.
2369     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2370 
2371     // Interleave the elements in the wide vector.
2372     Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2373     Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2374                                               "interleaved.vec");
2375 
2376     Instruction *NewStoreInstr =
2377         Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2378 
2379     Group->addMetadata(NewStoreInstr);
2380   }
2381 }
2382 
2383 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
2384                                                      VectorParts *BlockInMask) {
2385   // Attempt to issue a wide load.
2386   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2387   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2388 
2389   assert((LI || SI) && "Invalid Load/Store instruction");
2390 
2391   LoopVectorizationCostModel::InstWidening Decision =
2392       Cost->getWideningDecision(Instr, VF);
2393   assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
2394          "CM decision should be taken at this point");
2395   if (Decision == LoopVectorizationCostModel::CM_Interleave)
2396     return vectorizeInterleaveGroup(Instr);
2397 
2398   Type *ScalarDataTy = getMemInstValueType(Instr);
2399   Type *DataTy = VectorType::get(ScalarDataTy, VF);
2400   Value *Ptr = getLoadStorePointerOperand(Instr);
2401   unsigned Alignment = getMemInstAlignment(Instr);
2402   // An alignment of 0 means target abi alignment. We need to use the scalar's
2403   // target abi alignment in such a case.
2404   const DataLayout &DL = Instr->getModule()->getDataLayout();
2405   if (!Alignment)
2406     Alignment = DL.getABITypeAlignment(ScalarDataTy);
2407   unsigned AddressSpace = getMemInstAddressSpace(Instr);
2408 
2409   // Determine if the pointer operand of the access is either consecutive or
2410   // reverse consecutive.
2411   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2412   bool ConsecutiveStride =
2413       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2414   bool CreateGatherScatter =
2415       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2416 
2417   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2418   // gather/scatter. Otherwise Decision should have been to Scalarize.
2419   assert((ConsecutiveStride || CreateGatherScatter) &&
2420          "The instruction should be scalarized");
2421 
2422   // Handle consecutive loads/stores.
2423   if (ConsecutiveStride)
2424     Ptr = getOrCreateScalarValue(Ptr, {0, 0});
2425 
2426   VectorParts Mask;
2427   bool isMaskRequired = BlockInMask;
2428   if (isMaskRequired)
2429     Mask = *BlockInMask;
2430 
2431   bool InBounds = false;
2432   if (auto *gep = dyn_cast<GetElementPtrInst>(
2433           getLoadStorePointerOperand(Instr)->stripPointerCasts()))
2434     InBounds = gep->isInBounds();
2435 
2436   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2437     // Calculate the pointer for the specific unroll-part.
2438     GetElementPtrInst *PartPtr = nullptr;
2439 
2440     if (Reverse) {
2441       // If the address is consecutive but reversed, then the
2442       // wide store needs to start at the last vector element.
2443       PartPtr = cast<GetElementPtrInst>(
2444           Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)));
2445       PartPtr->setIsInBounds(InBounds);
2446       PartPtr = cast<GetElementPtrInst>(
2447           Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)));
2448       PartPtr->setIsInBounds(InBounds);
2449       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2450         Mask[Part] = reverseVector(Mask[Part]);
2451     } else {
2452       PartPtr = cast<GetElementPtrInst>(
2453           Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)));
2454       PartPtr->setIsInBounds(InBounds);
2455     }
2456 
2457     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2458   };
2459 
2460   // Handle Stores:
2461   if (SI) {
2462     setDebugLocFromInst(Builder, SI);
2463 
2464     for (unsigned Part = 0; Part < UF; ++Part) {
2465       Instruction *NewSI = nullptr;
2466       Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
2467       if (CreateGatherScatter) {
2468         Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
2469         Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
2470         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2471                                             MaskPart);
2472       } else {
2473         if (Reverse) {
2474           // If we store to reverse consecutive memory locations, then we need
2475           // to reverse the order of elements in the stored value.
2476           StoredVal = reverseVector(StoredVal);
2477           // We don't want to update the value in the map as it might be used in
2478           // another expression. So don't call resetVectorValue(StoredVal).
2479         }
2480         auto *VecPtr = CreateVecPtr(Part, Ptr);
2481         if (isMaskRequired)
2482           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2483                                             Mask[Part]);
2484         else
2485           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2486       }
2487       addMetadata(NewSI, SI);
2488     }
2489     return;
2490   }
2491 
2492   // Handle loads.
2493   assert(LI && "Must have a load instruction");
2494   setDebugLocFromInst(Builder, LI);
2495   for (unsigned Part = 0; Part < UF; ++Part) {
2496     Value *NewLI;
2497     if (CreateGatherScatter) {
2498       Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
2499       Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
2500       NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2501                                          nullptr, "wide.masked.gather");
2502       addMetadata(NewLI, LI);
2503     } else {
2504       auto *VecPtr = CreateVecPtr(Part, Ptr);
2505       if (isMaskRequired)
2506         NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2507                                          UndefValue::get(DataTy),
2508                                          "wide.masked.load");
2509       else
2510         NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2511 
2512       // Add metadata to the load, but setVectorValue to the reverse shuffle.
2513       addMetadata(NewLI, LI);
2514       if (Reverse)
2515         NewLI = reverseVector(NewLI);
2516     }
2517     VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
2518   }
2519 }
2520 
2521 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2522                                                const VPIteration &Instance,
2523                                                bool IfPredicateInstr) {
2524   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2525 
2526   setDebugLocFromInst(Builder, Instr);
2527 
2528   // Does this instruction return a value ?
2529   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2530 
2531   Instruction *Cloned = Instr->clone();
2532   if (!IsVoidRetTy)
2533     Cloned->setName(Instr->getName() + ".cloned");
2534 
2535   // Replace the operands of the cloned instructions with their scalar
2536   // equivalents in the new loop.
2537   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2538     auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
2539     Cloned->setOperand(op, NewOp);
2540   }
2541   addNewMetadata(Cloned, Instr);
2542 
2543   // Place the cloned scalar in the new loop.
2544   Builder.Insert(Cloned);
2545 
2546   // Add the cloned scalar to the scalar map entry.
2547   VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
2548 
2549   // If we just cloned a new assumption, add it the assumption cache.
2550   if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
2551     if (II->getIntrinsicID() == Intrinsic::assume)
2552       AC->registerAssumption(II);
2553 
2554   // End if-block.
2555   if (IfPredicateInstr)
2556     PredicatedInstructions.push_back(Cloned);
2557 }
2558 
2559 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2560                                                       Value *End, Value *Step,
2561                                                       Instruction *DL) {
2562   BasicBlock *Header = L->getHeader();
2563   BasicBlock *Latch = L->getLoopLatch();
2564   // As we're just creating this loop, it's possible no latch exists
2565   // yet. If so, use the header as this will be a single block loop.
2566   if (!Latch)
2567     Latch = Header;
2568 
2569   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2570   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
2571   setDebugLocFromInst(Builder, OldInst);
2572   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2573 
2574   Builder.SetInsertPoint(Latch->getTerminator());
2575   setDebugLocFromInst(Builder, OldInst);
2576 
2577   // Create i+1 and fill the PHINode.
2578   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2579   Induction->addIncoming(Start, L->getLoopPreheader());
2580   Induction->addIncoming(Next, Latch);
2581   // Create the compare.
2582   Value *ICmp = Builder.CreateICmpEQ(Next, End);
2583   Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2584 
2585   // Now we have two terminators. Remove the old one from the block.
2586   Latch->getTerminator()->eraseFromParent();
2587 
2588   return Induction;
2589 }
2590 
2591 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2592   if (TripCount)
2593     return TripCount;
2594 
2595   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2596   // Find the loop boundaries.
2597   ScalarEvolution *SE = PSE.getSE();
2598   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2599   assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
2600          "Invalid loop count");
2601 
2602   Type *IdxTy = Legal->getWidestInductionType();
2603 
2604   // The exit count might have the type of i64 while the phi is i32. This can
2605   // happen if we have an induction variable that is sign extended before the
2606   // compare. The only way that we get a backedge taken count is that the
2607   // induction variable was signed and as such will not overflow. In such a case
2608   // truncation is legal.
2609   if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2610       IdxTy->getPrimitiveSizeInBits())
2611     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2612   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2613 
2614   // Get the total trip count from the count by adding 1.
2615   const SCEV *ExitCount = SE->getAddExpr(
2616       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2617 
2618   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2619 
2620   // Expand the trip count and place the new instructions in the preheader.
2621   // Notice that the pre-header does not change, only the loop body.
2622   SCEVExpander Exp(*SE, DL, "induction");
2623 
2624   // Count holds the overall loop count (N).
2625   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2626                                 L->getLoopPreheader()->getTerminator());
2627 
2628   if (TripCount->getType()->isPointerTy())
2629     TripCount =
2630         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2631                                     L->getLoopPreheader()->getTerminator());
2632 
2633   return TripCount;
2634 }
2635 
2636 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2637   if (VectorTripCount)
2638     return VectorTripCount;
2639 
2640   Value *TC = getOrCreateTripCount(L);
2641   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2642 
2643   // Now we need to generate the expression for the part of the loop that the
2644   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2645   // iterations are not required for correctness, or N - Step, otherwise. Step
2646   // is equal to the vectorization factor (number of SIMD elements) times the
2647   // unroll factor (number of SIMD instructions).
2648   Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2649   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2650 
2651   // If there is a non-reversed interleaved group that may speculatively access
2652   // memory out-of-bounds, we need to ensure that there will be at least one
2653   // iteration of the scalar epilogue loop. Thus, if the step evenly divides
2654   // the trip count, we set the remainder to be equal to the step. If the step
2655   // does not evenly divide the trip count, no adjustment is necessary since
2656   // there will already be scalar iterations. Note that the minimum iterations
2657   // check ensures that N >= Step.
2658   if (VF > 1 && Cost->requiresScalarEpilogue()) {
2659     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2660     R = Builder.CreateSelect(IsZero, Step, R);
2661   }
2662 
2663   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2664 
2665   return VectorTripCount;
2666 }
2667 
2668 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2669                                                    const DataLayout &DL) {
2670   // Verify that V is a vector type with same number of elements as DstVTy.
2671   unsigned VF = DstVTy->getNumElements();
2672   VectorType *SrcVecTy = cast<VectorType>(V->getType());
2673   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2674   Type *SrcElemTy = SrcVecTy->getElementType();
2675   Type *DstElemTy = DstVTy->getElementType();
2676   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2677          "Vector elements must have same size");
2678 
2679   // Do a direct cast if element types are castable.
2680   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2681     return Builder.CreateBitOrPointerCast(V, DstVTy);
2682   }
2683   // V cannot be directly casted to desired vector type.
2684   // May happen when V is a floating point vector but DstVTy is a vector of
2685   // pointers or vice-versa. Handle this using a two-step bitcast using an
2686   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2687   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2688          "Only one type should be a pointer type");
2689   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2690          "Only one type should be a floating point type");
2691   Type *IntTy =
2692       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2693   VectorType *VecIntTy = VectorType::get(IntTy, VF);
2694   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2695   return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
2696 }
2697 
2698 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2699                                                          BasicBlock *Bypass) {
2700   Value *Count = getOrCreateTripCount(L);
2701   BasicBlock *BB = L->getLoopPreheader();
2702   IRBuilder<> Builder(BB->getTerminator());
2703 
2704   // Generate code to check if the loop's trip count is less than VF * UF, or
2705   // equal to it in case a scalar epilogue is required; this implies that the
2706   // vector trip count is zero. This check also covers the case where adding one
2707   // to the backedge-taken count overflowed leading to an incorrect trip count
2708   // of zero. In this case we will also jump to the scalar loop.
2709   auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
2710                                           : ICmpInst::ICMP_ULT;
2711   Value *CheckMinIters = Builder.CreateICmp(
2712       P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
2713 
2714   BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2715   // Update dominator tree immediately if the generated block is a
2716   // LoopBypassBlock because SCEV expansions to generate loop bypass
2717   // checks may query it before the current function is finished.
2718   DT->addNewBlock(NewBB, BB);
2719   if (L->getParentLoop())
2720     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2721   ReplaceInstWithInst(BB->getTerminator(),
2722                       BranchInst::Create(Bypass, NewBB, CheckMinIters));
2723   LoopBypassBlocks.push_back(BB);
2724 }
2725 
2726 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
2727   BasicBlock *BB = L->getLoopPreheader();
2728 
2729   // Generate the code to check that the SCEV assumptions that we made.
2730   // We want the new basic block to start at the first instruction in a
2731   // sequence of instructions that form a check.
2732   SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
2733                    "scev.check");
2734   Value *SCEVCheck =
2735       Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
2736 
2737   if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2738     if (C->isZero())
2739       return;
2740 
2741   // Create a new block containing the stride check.
2742   BB->setName("vector.scevcheck");
2743   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2744   // Update dominator tree immediately if the generated block is a
2745   // LoopBypassBlock because SCEV expansions to generate loop bypass
2746   // checks may query it before the current function is finished.
2747   DT->addNewBlock(NewBB, BB);
2748   if (L->getParentLoop())
2749     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2750   ReplaceInstWithInst(BB->getTerminator(),
2751                       BranchInst::Create(Bypass, NewBB, SCEVCheck));
2752   LoopBypassBlocks.push_back(BB);
2753   AddedSafetyChecks = true;
2754 }
2755 
2756 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
2757   BasicBlock *BB = L->getLoopPreheader();
2758 
2759   // Generate the code that checks in runtime if arrays overlap. We put the
2760   // checks into a separate block to make the more common case of few elements
2761   // faster.
2762   Instruction *FirstCheckInst;
2763   Instruction *MemRuntimeCheck;
2764   std::tie(FirstCheckInst, MemRuntimeCheck) =
2765       Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2766   if (!MemRuntimeCheck)
2767     return;
2768 
2769   // Create a new block containing the memory check.
2770   BB->setName("vector.memcheck");
2771   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2772   // Update dominator tree immediately if the generated block is a
2773   // LoopBypassBlock because SCEV expansions to generate loop bypass
2774   // checks may query it before the current function is finished.
2775   DT->addNewBlock(NewBB, BB);
2776   if (L->getParentLoop())
2777     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2778   ReplaceInstWithInst(BB->getTerminator(),
2779                       BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2780   LoopBypassBlocks.push_back(BB);
2781   AddedSafetyChecks = true;
2782 
2783   // We currently don't use LoopVersioning for the actual loop cloning but we
2784   // still use it to add the noalias metadata.
2785   LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
2786                                            PSE.getSE());
2787   LVer->prepareNoAliasMetadata();
2788 }
2789 
2790 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
2791   /*
2792    In this function we generate a new loop. The new loop will contain
2793    the vectorized instructions while the old loop will continue to run the
2794    scalar remainder.
2795 
2796        [ ] <-- loop iteration number check.
2797     /   |
2798    /    v
2799   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
2800   |  /  |
2801   | /   v
2802   ||   [ ]     <-- vector pre header.
2803   |/    |
2804   |     v
2805   |    [  ] \
2806   |    [  ]_|   <-- vector loop.
2807   |     |
2808   |     v
2809   |   -[ ]   <--- middle-block.
2810   |  /  |
2811   | /   v
2812   -|- >[ ]     <--- new preheader.
2813    |    |
2814    |    v
2815    |   [ ] \
2816    |   [ ]_|   <-- old scalar loop to handle remainder.
2817     \   |
2818      \  v
2819       >[ ]     <-- exit block.
2820    ...
2821    */
2822 
2823   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2824   BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2825   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2826   assert(VectorPH && "Invalid loop structure");
2827   assert(ExitBlock && "Must have an exit block");
2828 
2829   // Some loops have a single integer induction variable, while other loops
2830   // don't. One example is c++ iterators that often have multiple pointer
2831   // induction variables. In the code below we also support a case where we
2832   // don't have a single induction variable.
2833   //
2834   // We try to obtain an induction variable from the original loop as hard
2835   // as possible. However if we don't find one that:
2836   //   - is an integer
2837   //   - counts from zero, stepping by one
2838   //   - is the size of the widest induction variable type
2839   // then we create a new one.
2840   OldInduction = Legal->getPrimaryInduction();
2841   Type *IdxTy = Legal->getWidestInductionType();
2842 
2843   // Split the single block loop into the two loop structure described above.
2844   BasicBlock *VecBody =
2845       VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2846   BasicBlock *MiddleBlock =
2847       VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2848   BasicBlock *ScalarPH =
2849       MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2850 
2851   // Create and register the new vector loop.
2852   Loop *Lp = LI->AllocateLoop();
2853   Loop *ParentLoop = OrigLoop->getParentLoop();
2854 
2855   // Insert the new loop into the loop nest and register the new basic blocks
2856   // before calling any utilities such as SCEV that require valid LoopInfo.
2857   if (ParentLoop) {
2858     ParentLoop->addChildLoop(Lp);
2859     ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2860     ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2861   } else {
2862     LI->addTopLevelLoop(Lp);
2863   }
2864   Lp->addBasicBlockToLoop(VecBody, *LI);
2865 
2866   // Find the loop boundaries.
2867   Value *Count = getOrCreateTripCount(Lp);
2868 
2869   Value *StartIdx = ConstantInt::get(IdxTy, 0);
2870 
2871   // Now, compare the new count to zero. If it is zero skip the vector loop and
2872   // jump to the scalar loop. This check also covers the case where the
2873   // backedge-taken count is uint##_max: adding one to it will overflow leading
2874   // to an incorrect trip count of zero. In this (rare) case we will also jump
2875   // to the scalar loop.
2876   emitMinimumIterationCountCheck(Lp, ScalarPH);
2877 
2878   // Generate the code to check any assumptions that we've made for SCEV
2879   // expressions.
2880   emitSCEVChecks(Lp, ScalarPH);
2881 
2882   // Generate the code that checks in runtime if arrays overlap. We put the
2883   // checks into a separate block to make the more common case of few elements
2884   // faster.
2885   emitMemRuntimeChecks(Lp, ScalarPH);
2886 
2887   // Generate the induction variable.
2888   // The loop step is equal to the vectorization factor (num of SIMD elements)
2889   // times the unroll factor (num of SIMD instructions).
2890   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2891   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2892   Induction =
2893       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2894                               getDebugLocFromInstOrOperands(OldInduction));
2895 
2896   // We are going to resume the execution of the scalar loop.
2897   // Go over all of the induction variables that we found and fix the
2898   // PHIs that are left in the scalar version of the loop.
2899   // The starting values of PHI nodes depend on the counter of the last
2900   // iteration in the vectorized loop.
2901   // If we come from a bypass edge then we need to start from the original
2902   // start value.
2903 
2904   // This variable saves the new starting index for the scalar loop. It is used
2905   // to test if there are any tail iterations left once the vector loop has
2906   // completed.
2907   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2908   for (auto &InductionEntry : *List) {
2909     PHINode *OrigPhi = InductionEntry.first;
2910     InductionDescriptor II = InductionEntry.second;
2911 
2912     // Create phi nodes to merge from the  backedge-taken check block.
2913     PHINode *BCResumeVal = PHINode::Create(
2914         OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
2915     Value *&EndValue = IVEndValues[OrigPhi];
2916     if (OrigPhi == OldInduction) {
2917       // We know what the end value is.
2918       EndValue = CountRoundDown;
2919     } else {
2920       IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
2921       Type *StepType = II.getStep()->getType();
2922       Instruction::CastOps CastOp =
2923         CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
2924       Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
2925       const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2926       EndValue = II.transform(B, CRD, PSE.getSE(), DL);
2927       EndValue->setName("ind.end");
2928     }
2929 
2930     // The new PHI merges the original incoming value, in case of a bypass,
2931     // or the value at the end of the vectorized loop.
2932     BCResumeVal->addIncoming(EndValue, MiddleBlock);
2933 
2934     // Fix the scalar body counter (PHI node).
2935     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2936 
2937     // The old induction's phi node in the scalar body needs the truncated
2938     // value.
2939     for (BasicBlock *BB : LoopBypassBlocks)
2940       BCResumeVal->addIncoming(II.getStartValue(), BB);
2941     OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2942   }
2943 
2944   // Add a check in the middle block to see if we have completed
2945   // all of the iterations in the first vector loop.
2946   // If (N - N%VF) == N, then we *don't* need to run the remainder.
2947   Value *CmpN =
2948       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2949                       CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
2950   ReplaceInstWithInst(MiddleBlock->getTerminator(),
2951                       BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2952 
2953   // Get ready to start creating new instructions into the vectorized body.
2954   Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
2955 
2956   // Save the state.
2957   LoopVectorPreHeader = Lp->getLoopPreheader();
2958   LoopScalarPreHeader = ScalarPH;
2959   LoopMiddleBlock = MiddleBlock;
2960   LoopExitBlock = ExitBlock;
2961   LoopVectorBody = VecBody;
2962   LoopScalarBody = OldBasicBlock;
2963 
2964   // Keep all loop hints from the original loop on the vector loop (we'll
2965   // replace the vectorizer-specific hints below).
2966   if (MDNode *LID = OrigLoop->getLoopID())
2967     Lp->setLoopID(LID);
2968 
2969   LoopVectorizeHints Hints(Lp, true, *ORE);
2970   Hints.setAlreadyVectorized();
2971 
2972   return LoopVectorPreHeader;
2973 }
2974 
2975 // Fix up external users of the induction variable. At this point, we are
2976 // in LCSSA form, with all external PHIs that use the IV having one input value,
2977 // coming from the remainder loop. We need those PHIs to also have a correct
2978 // value for the IV when arriving directly from the middle block.
2979 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
2980                                        const InductionDescriptor &II,
2981                                        Value *CountRoundDown, Value *EndValue,
2982                                        BasicBlock *MiddleBlock) {
2983   // There are two kinds of external IV usages - those that use the value
2984   // computed in the last iteration (the PHI) and those that use the penultimate
2985   // value (the value that feeds into the phi from the loop latch).
2986   // We allow both, but they, obviously, have different values.
2987 
2988   assert(OrigLoop->getExitBlock() && "Expected a single exit block");
2989 
2990   DenseMap<Value *, Value *> MissingVals;
2991 
2992   // An external user of the last iteration's value should see the value that
2993   // the remainder loop uses to initialize its own IV.
2994   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
2995   for (User *U : PostInc->users()) {
2996     Instruction *UI = cast<Instruction>(U);
2997     if (!OrigLoop->contains(UI)) {
2998       assert(isa<PHINode>(UI) && "Expected LCSSA form");
2999       MissingVals[UI] = EndValue;
3000     }
3001   }
3002 
3003   // An external user of the penultimate value need to see EndValue - Step.
3004   // The simplest way to get this is to recompute it from the constituent SCEVs,
3005   // that is Start + (Step * (CRD - 1)).
3006   for (User *U : OrigPhi->users()) {
3007     auto *UI = cast<Instruction>(U);
3008     if (!OrigLoop->contains(UI)) {
3009       const DataLayout &DL =
3010           OrigLoop->getHeader()->getModule()->getDataLayout();
3011       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3012 
3013       IRBuilder<> B(MiddleBlock->getTerminator());
3014       Value *CountMinusOne = B.CreateSub(
3015           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3016       Value *CMO =
3017           !II.getStep()->getType()->isIntegerTy()
3018               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3019                              II.getStep()->getType())
3020               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3021       CMO->setName("cast.cmo");
3022       Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3023       Escape->setName("ind.escape");
3024       MissingVals[UI] = Escape;
3025     }
3026   }
3027 
3028   for (auto &I : MissingVals) {
3029     PHINode *PHI = cast<PHINode>(I.first);
3030     // One corner case we have to handle is two IVs "chasing" each-other,
3031     // that is %IV2 = phi [...], [ %IV1, %latch ]
3032     // In this case, if IV1 has an external use, we need to avoid adding both
3033     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3034     // don't already have an incoming value for the middle block.
3035     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3036       PHI->addIncoming(I.second, MiddleBlock);
3037   }
3038 }
3039 
3040 namespace {
3041 
3042 struct CSEDenseMapInfo {
3043   static bool canHandle(const Instruction *I) {
3044     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3045            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3046   }
3047 
3048   static inline Instruction *getEmptyKey() {
3049     return DenseMapInfo<Instruction *>::getEmptyKey();
3050   }
3051 
3052   static inline Instruction *getTombstoneKey() {
3053     return DenseMapInfo<Instruction *>::getTombstoneKey();
3054   }
3055 
3056   static unsigned getHashValue(const Instruction *I) {
3057     assert(canHandle(I) && "Unknown instruction!");
3058     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3059                                                            I->value_op_end()));
3060   }
3061 
3062   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3063     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3064         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3065       return LHS == RHS;
3066     return LHS->isIdenticalTo(RHS);
3067   }
3068 };
3069 
3070 } // end anonymous namespace
3071 
3072 ///Perform cse of induction variable instructions.
3073 static void cse(BasicBlock *BB) {
3074   // Perform simple cse.
3075   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3076   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3077     Instruction *In = &*I++;
3078 
3079     if (!CSEDenseMapInfo::canHandle(In))
3080       continue;
3081 
3082     // Check if we can replace this instruction with any of the
3083     // visited instructions.
3084     if (Instruction *V = CSEMap.lookup(In)) {
3085       In->replaceAllUsesWith(V);
3086       In->eraseFromParent();
3087       continue;
3088     }
3089 
3090     CSEMap[In] = In;
3091   }
3092 }
3093 
3094 /// Estimate the overhead of scalarizing an instruction. This is a
3095 /// convenience wrapper for the type-based getScalarizationOverhead API.
3096 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3097                                          const TargetTransformInfo &TTI) {
3098   if (VF == 1)
3099     return 0;
3100 
3101   unsigned Cost = 0;
3102   Type *RetTy = ToVectorTy(I->getType(), VF);
3103   if (!RetTy->isVoidTy() &&
3104       (!isa<LoadInst>(I) ||
3105        !TTI.supportsEfficientVectorElementLoadStore()))
3106     Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3107 
3108   if (CallInst *CI = dyn_cast<CallInst>(I)) {
3109     SmallVector<const Value *, 4> Operands(CI->arg_operands());
3110     Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3111   }
3112   else if (!isa<StoreInst>(I) ||
3113            !TTI.supportsEfficientVectorElementLoadStore()) {
3114     SmallVector<const Value *, 4> Operands(I->operand_values());
3115     Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3116   }
3117 
3118   return Cost;
3119 }
3120 
3121 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3122 // Return the cost of the instruction, including scalarization overhead if it's
3123 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3124 // i.e. either vector version isn't available, or is too expensive.
3125 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3126                                   const TargetTransformInfo &TTI,
3127                                   const TargetLibraryInfo *TLI,
3128                                   bool &NeedToScalarize) {
3129   Function *F = CI->getCalledFunction();
3130   StringRef FnName = CI->getCalledFunction()->getName();
3131   Type *ScalarRetTy = CI->getType();
3132   SmallVector<Type *, 4> Tys, ScalarTys;
3133   for (auto &ArgOp : CI->arg_operands())
3134     ScalarTys.push_back(ArgOp->getType());
3135 
3136   // Estimate cost of scalarized vector call. The source operands are assumed
3137   // to be vectors, so we need to extract individual elements from there,
3138   // execute VF scalar calls, and then gather the result into the vector return
3139   // value.
3140   unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3141   if (VF == 1)
3142     return ScalarCallCost;
3143 
3144   // Compute corresponding vector type for return value and arguments.
3145   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3146   for (Type *ScalarTy : ScalarTys)
3147     Tys.push_back(ToVectorTy(ScalarTy, VF));
3148 
3149   // Compute costs of unpacking argument values for the scalar calls and
3150   // packing the return values to a vector.
3151   unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3152 
3153   unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3154 
3155   // If we can't emit a vector call for this function, then the currently found
3156   // cost is the cost we need to return.
3157   NeedToScalarize = true;
3158   if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3159     return Cost;
3160 
3161   // If the corresponding vector cost is cheaper, return its cost.
3162   unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3163   if (VectorCallCost < Cost) {
3164     NeedToScalarize = false;
3165     return VectorCallCost;
3166   }
3167   return Cost;
3168 }
3169 
3170 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3171 // factor VF.  Return the cost of the instruction, including scalarization
3172 // overhead if it's needed.
3173 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3174                                        const TargetTransformInfo &TTI,
3175                                        const TargetLibraryInfo *TLI) {
3176   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3177   assert(ID && "Expected intrinsic call!");
3178 
3179   FastMathFlags FMF;
3180   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3181     FMF = FPMO->getFastMathFlags();
3182 
3183   SmallVector<Value *, 4> Operands(CI->arg_operands());
3184   return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3185 }
3186 
3187 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3188   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3189   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3190   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3191 }
3192 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3193   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3194   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3195   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3196 }
3197 
3198 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3199   // For every instruction `I` in MinBWs, truncate the operands, create a
3200   // truncated version of `I` and reextend its result. InstCombine runs
3201   // later and will remove any ext/trunc pairs.
3202   SmallPtrSet<Value *, 4> Erased;
3203   for (const auto &KV : Cost->getMinimalBitwidths()) {
3204     // If the value wasn't vectorized, we must maintain the original scalar
3205     // type. The absence of the value from VectorLoopValueMap indicates that it
3206     // wasn't vectorized.
3207     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3208       continue;
3209     for (unsigned Part = 0; Part < UF; ++Part) {
3210       Value *I = getOrCreateVectorValue(KV.first, Part);
3211       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3212         continue;
3213       Type *OriginalTy = I->getType();
3214       Type *ScalarTruncatedTy =
3215           IntegerType::get(OriginalTy->getContext(), KV.second);
3216       Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3217                                           OriginalTy->getVectorNumElements());
3218       if (TruncatedTy == OriginalTy)
3219         continue;
3220 
3221       IRBuilder<> B(cast<Instruction>(I));
3222       auto ShrinkOperand = [&](Value *V) -> Value * {
3223         if (auto *ZI = dyn_cast<ZExtInst>(V))
3224           if (ZI->getSrcTy() == TruncatedTy)
3225             return ZI->getOperand(0);
3226         return B.CreateZExtOrTrunc(V, TruncatedTy);
3227       };
3228 
3229       // The actual instruction modification depends on the instruction type,
3230       // unfortunately.
3231       Value *NewI = nullptr;
3232       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3233         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3234                              ShrinkOperand(BO->getOperand(1)));
3235 
3236         // Any wrapping introduced by shrinking this operation shouldn't be
3237         // considered undefined behavior. So, we can't unconditionally copy
3238         // arithmetic wrapping flags to NewI.
3239         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3240       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3241         NewI =
3242             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3243                          ShrinkOperand(CI->getOperand(1)));
3244       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3245         NewI = B.CreateSelect(SI->getCondition(),
3246                               ShrinkOperand(SI->getTrueValue()),
3247                               ShrinkOperand(SI->getFalseValue()));
3248       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3249         switch (CI->getOpcode()) {
3250         default:
3251           llvm_unreachable("Unhandled cast!");
3252         case Instruction::Trunc:
3253           NewI = ShrinkOperand(CI->getOperand(0));
3254           break;
3255         case Instruction::SExt:
3256           NewI = B.CreateSExtOrTrunc(
3257               CI->getOperand(0),
3258               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3259           break;
3260         case Instruction::ZExt:
3261           NewI = B.CreateZExtOrTrunc(
3262               CI->getOperand(0),
3263               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3264           break;
3265         }
3266       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3267         auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3268         auto *O0 = B.CreateZExtOrTrunc(
3269             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3270         auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3271         auto *O1 = B.CreateZExtOrTrunc(
3272             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3273 
3274         NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3275       } else if (isa<LoadInst>(I)) {
3276         // Don't do anything with the operands, just extend the result.
3277         continue;
3278       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3279         auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3280         auto *O0 = B.CreateZExtOrTrunc(
3281             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3282         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3283         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3284       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3285         auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3286         auto *O0 = B.CreateZExtOrTrunc(
3287             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3288         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3289       } else {
3290         llvm_unreachable("Unhandled instruction type!");
3291       }
3292 
3293       // Lastly, extend the result.
3294       NewI->takeName(cast<Instruction>(I));
3295       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3296       I->replaceAllUsesWith(Res);
3297       cast<Instruction>(I)->eraseFromParent();
3298       Erased.insert(I);
3299       VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3300     }
3301   }
3302 
3303   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3304   for (const auto &KV : Cost->getMinimalBitwidths()) {
3305     // If the value wasn't vectorized, we must maintain the original scalar
3306     // type. The absence of the value from VectorLoopValueMap indicates that it
3307     // wasn't vectorized.
3308     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3309       continue;
3310     for (unsigned Part = 0; Part < UF; ++Part) {
3311       Value *I = getOrCreateVectorValue(KV.first, Part);
3312       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3313       if (Inst && Inst->use_empty()) {
3314         Value *NewI = Inst->getOperand(0);
3315         Inst->eraseFromParent();
3316         VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3317       }
3318     }
3319   }
3320 }
3321 
3322 void InnerLoopVectorizer::fixVectorizedLoop() {
3323   // Insert truncates and extends for any truncated instructions as hints to
3324   // InstCombine.
3325   if (VF > 1)
3326     truncateToMinimalBitwidths();
3327 
3328   // At this point every instruction in the original loop is widened to a
3329   // vector form. Now we need to fix the recurrences in the loop. These PHI
3330   // nodes are currently empty because we did not want to introduce cycles.
3331   // This is the second stage of vectorizing recurrences.
3332   fixCrossIterationPHIs();
3333 
3334   // Update the dominator tree.
3335   //
3336   // FIXME: After creating the structure of the new loop, the dominator tree is
3337   //        no longer up-to-date, and it remains that way until we update it
3338   //        here. An out-of-date dominator tree is problematic for SCEV,
3339   //        because SCEVExpander uses it to guide code generation. The
3340   //        vectorizer use SCEVExpanders in several places. Instead, we should
3341   //        keep the dominator tree up-to-date as we go.
3342   updateAnalysis();
3343 
3344   // Fix-up external users of the induction variables.
3345   for (auto &Entry : *Legal->getInductionVars())
3346     fixupIVUsers(Entry.first, Entry.second,
3347                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3348                  IVEndValues[Entry.first], LoopMiddleBlock);
3349 
3350   fixLCSSAPHIs();
3351   for (Instruction *PI : PredicatedInstructions)
3352     sinkScalarOperands(&*PI);
3353 
3354   // Remove redundant induction instructions.
3355   cse(LoopVectorBody);
3356 }
3357 
3358 void InnerLoopVectorizer::fixCrossIterationPHIs() {
3359   // In order to support recurrences we need to be able to vectorize Phi nodes.
3360   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3361   // stage #2: We now need to fix the recurrences by adding incoming edges to
3362   // the currently empty PHI nodes. At this point every instruction in the
3363   // original loop is widened to a vector form so we can use them to construct
3364   // the incoming edges.
3365   for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
3366     // Handle first-order recurrences and reductions that need to be fixed.
3367     if (Legal->isFirstOrderRecurrence(&Phi))
3368       fixFirstOrderRecurrence(&Phi);
3369     else if (Legal->isReductionVariable(&Phi))
3370       fixReduction(&Phi);
3371   }
3372 }
3373 
3374 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3375   // This is the second phase of vectorizing first-order recurrences. An
3376   // overview of the transformation is described below. Suppose we have the
3377   // following loop.
3378   //
3379   //   for (int i = 0; i < n; ++i)
3380   //     b[i] = a[i] - a[i - 1];
3381   //
3382   // There is a first-order recurrence on "a". For this loop, the shorthand
3383   // scalar IR looks like:
3384   //
3385   //   scalar.ph:
3386   //     s_init = a[-1]
3387   //     br scalar.body
3388   //
3389   //   scalar.body:
3390   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3391   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3392   //     s2 = a[i]
3393   //     b[i] = s2 - s1
3394   //     br cond, scalar.body, ...
3395   //
3396   // In this example, s1 is a recurrence because it's value depends on the
3397   // previous iteration. In the first phase of vectorization, we created a
3398   // temporary value for s1. We now complete the vectorization and produce the
3399   // shorthand vector IR shown below (for VF = 4, UF = 1).
3400   //
3401   //   vector.ph:
3402   //     v_init = vector(..., ..., ..., a[-1])
3403   //     br vector.body
3404   //
3405   //   vector.body
3406   //     i = phi [0, vector.ph], [i+4, vector.body]
3407   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3408   //     v2 = a[i, i+1, i+2, i+3];
3409   //     v3 = vector(v1(3), v2(0, 1, 2))
3410   //     b[i, i+1, i+2, i+3] = v2 - v3
3411   //     br cond, vector.body, middle.block
3412   //
3413   //   middle.block:
3414   //     x = v2(3)
3415   //     br scalar.ph
3416   //
3417   //   scalar.ph:
3418   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3419   //     br scalar.body
3420   //
3421   // After execution completes the vector loop, we extract the next value of
3422   // the recurrence (x) to use as the initial value in the scalar loop.
3423 
3424   // Get the original loop preheader and single loop latch.
3425   auto *Preheader = OrigLoop->getLoopPreheader();
3426   auto *Latch = OrigLoop->getLoopLatch();
3427 
3428   // Get the initial and previous values of the scalar recurrence.
3429   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
3430   auto *Previous = Phi->getIncomingValueForBlock(Latch);
3431 
3432   // Create a vector from the initial value.
3433   auto *VectorInit = ScalarInit;
3434   if (VF > 1) {
3435     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3436     VectorInit = Builder.CreateInsertElement(
3437         UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
3438         Builder.getInt32(VF - 1), "vector.recur.init");
3439   }
3440 
3441   // We constructed a temporary phi node in the first phase of vectorization.
3442   // This phi node will eventually be deleted.
3443   Builder.SetInsertPoint(
3444       cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
3445 
3446   // Create a phi node for the new recurrence. The current value will either be
3447   // the initial value inserted into a vector or loop-varying vector value.
3448   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
3449   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
3450 
3451   // Get the vectorized previous value of the last part UF - 1. It appears last
3452   // among all unrolled iterations, due to the order of their construction.
3453   Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
3454 
3455   // Set the insertion point after the previous value if it is an instruction.
3456   // Note that the previous value may have been constant-folded so it is not
3457   // guaranteed to be an instruction in the vector loop. Also, if the previous
3458   // value is a phi node, we should insert after all the phi nodes to avoid
3459   // breaking basic block verification.
3460   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
3461       isa<PHINode>(PreviousLastPart))
3462     Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3463   else
3464     Builder.SetInsertPoint(
3465         &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
3466 
3467   // We will construct a vector for the recurrence by combining the values for
3468   // the current and previous iterations. This is the required shuffle mask.
3469   SmallVector<Constant *, 8> ShuffleMask(VF);
3470   ShuffleMask[0] = Builder.getInt32(VF - 1);
3471   for (unsigned I = 1; I < VF; ++I)
3472     ShuffleMask[I] = Builder.getInt32(I + VF - 1);
3473 
3474   // The vector from which to take the initial value for the current iteration
3475   // (actual or unrolled). Initially, this is the vector phi node.
3476   Value *Incoming = VecPhi;
3477 
3478   // Shuffle the current and previous vector and update the vector parts.
3479   for (unsigned Part = 0; Part < UF; ++Part) {
3480     Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
3481     Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
3482     auto *Shuffle =
3483         VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
3484                                              ConstantVector::get(ShuffleMask))
3485                : Incoming;
3486     PhiPart->replaceAllUsesWith(Shuffle);
3487     cast<Instruction>(PhiPart)->eraseFromParent();
3488     VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
3489     Incoming = PreviousPart;
3490   }
3491 
3492   // Fix the latch value of the new recurrence in the vector loop.
3493   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3494 
3495   // Extract the last vector element in the middle block. This will be the
3496   // initial value for the recurrence when jumping to the scalar loop.
3497   auto *ExtractForScalar = Incoming;
3498   if (VF > 1) {
3499     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3500     ExtractForScalar = Builder.CreateExtractElement(
3501         ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
3502   }
3503   // Extract the second last element in the middle block if the
3504   // Phi is used outside the loop. We need to extract the phi itself
3505   // and not the last element (the phi update in the current iteration). This
3506   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3507   // when the scalar loop is not run at all.
3508   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3509   if (VF > 1)
3510     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3511         Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
3512   // When loop is unrolled without vectorizing, initialize
3513   // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
3514   // `Incoming`. This is analogous to the vectorized case above: extracting the
3515   // second last element when VF > 1.
3516   else if (UF > 1)
3517     ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
3518 
3519   // Fix the initial value of the original recurrence in the scalar loop.
3520   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3521   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3522   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3523     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3524     Start->addIncoming(Incoming, BB);
3525   }
3526 
3527   Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
3528   Phi->setName("scalar.recur");
3529 
3530   // Finally, fix users of the recurrence outside the loop. The users will need
3531   // either the last value of the scalar recurrence or the last value of the
3532   // vector recurrence we extracted in the middle block. Since the loop is in
3533   // LCSSA form, we just need to find all the phi nodes for the original scalar
3534   // recurrence in the exit block, and then add an edge for the middle block.
3535   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3536     if (LCSSAPhi.getIncomingValue(0) == Phi) {
3537       LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3538     }
3539   }
3540 }
3541 
3542 void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
3543   Constant *Zero = Builder.getInt32(0);
3544 
3545   // Get it's reduction variable descriptor.
3546   assert(Legal->isReductionVariable(Phi) &&
3547          "Unable to find the reduction variable");
3548   RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
3549 
3550   RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3551   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3552   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3553   RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3554     RdxDesc.getMinMaxRecurrenceKind();
3555   setDebugLocFromInst(Builder, ReductionStartValue);
3556 
3557   // We need to generate a reduction vector from the incoming scalar.
3558   // To do so, we need to generate the 'identity' vector and override
3559   // one of the elements with the incoming scalar reduction. We need
3560   // to do it in the vector-loop preheader.
3561   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3562 
3563   // This is the vector-clone of the value that leaves the loop.
3564   Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
3565 
3566   // Find the reduction identity variable. Zero for addition, or, xor,
3567   // one for multiplication, -1 for And.
3568   Value *Identity;
3569   Value *VectorStart;
3570   if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3571       RK == RecurrenceDescriptor::RK_FloatMinMax) {
3572     // MinMax reduction have the start value as their identify.
3573     if (VF == 1) {
3574       VectorStart = Identity = ReductionStartValue;
3575     } else {
3576       VectorStart = Identity =
3577         Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3578     }
3579   } else {
3580     // Handle other reduction kinds:
3581     Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3582         RK, VecTy->getScalarType());
3583     if (VF == 1) {
3584       Identity = Iden;
3585       // This vector is the Identity vector where the first element is the
3586       // incoming scalar reduction.
3587       VectorStart = ReductionStartValue;
3588     } else {
3589       Identity = ConstantVector::getSplat(VF, Iden);
3590 
3591       // This vector is the Identity vector where the first element is the
3592       // incoming scalar reduction.
3593       VectorStart =
3594         Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3595     }
3596   }
3597 
3598   // Fix the vector-loop phi.
3599 
3600   // Reductions do not have to start at zero. They can start with
3601   // any loop invariant values.
3602   BasicBlock *Latch = OrigLoop->getLoopLatch();
3603   Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
3604   for (unsigned Part = 0; Part < UF; ++Part) {
3605     Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
3606     Value *Val = getOrCreateVectorValue(LoopVal, Part);
3607     // Make sure to add the reduction stat value only to the
3608     // first unroll part.
3609     Value *StartVal = (Part == 0) ? VectorStart : Identity;
3610     cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
3611     cast<PHINode>(VecRdxPhi)
3612       ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3613   }
3614 
3615   // Before each round, move the insertion point right between
3616   // the PHIs and the values we are going to write.
3617   // This allows us to write both PHINodes and the extractelement
3618   // instructions.
3619   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3620 
3621   setDebugLocFromInst(Builder, LoopExitInst);
3622 
3623   // If the vector reduction can be performed in a smaller type, we truncate
3624   // then extend the loop exit value to enable InstCombine to evaluate the
3625   // entire expression in the smaller type.
3626   if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
3627     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3628     Builder.SetInsertPoint(
3629         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
3630     VectorParts RdxParts(UF);
3631     for (unsigned Part = 0; Part < UF; ++Part) {
3632       RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
3633       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3634       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3635                                         : Builder.CreateZExt(Trunc, VecTy);
3636       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
3637            UI != RdxParts[Part]->user_end();)
3638         if (*UI != Trunc) {
3639           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
3640           RdxParts[Part] = Extnd;
3641         } else {
3642           ++UI;
3643         }
3644     }
3645     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3646     for (unsigned Part = 0; Part < UF; ++Part) {
3647       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3648       VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
3649     }
3650   }
3651 
3652   // Reduce all of the unrolled parts into a single vector.
3653   Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
3654   unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3655   setDebugLocFromInst(Builder, ReducedPartRdx);
3656   for (unsigned Part = 1; Part < UF; ++Part) {
3657     Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
3658     if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3659       // Floating point operations had to be 'fast' to enable the reduction.
3660       ReducedPartRdx = addFastMathFlag(
3661           Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
3662                               ReducedPartRdx, "bin.rdx"));
3663     else
3664       ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3665           Builder, MinMaxKind, ReducedPartRdx, RdxPart);
3666   }
3667 
3668   if (VF > 1) {
3669     bool NoNaN = Legal->hasFunNoNaNAttr();
3670     ReducedPartRdx =
3671         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
3672     // If the reduction can be performed in a smaller type, we need to extend
3673     // the reduction to the wider type before we branch to the original loop.
3674     if (Phi->getType() != RdxDesc.getRecurrenceType())
3675       ReducedPartRdx =
3676         RdxDesc.isSigned()
3677         ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
3678         : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
3679   }
3680 
3681   // Create a phi node that merges control-flow from the backedge-taken check
3682   // block and the middle block.
3683   PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
3684                                         LoopScalarPreHeader->getTerminator());
3685   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3686     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3687   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3688 
3689   // Now, we need to fix the users of the reduction variable
3690   // inside and outside of the scalar remainder loop.
3691   // We know that the loop is in LCSSA form. We need to update the
3692   // PHI nodes in the exit blocks.
3693   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3694     // All PHINodes need to have a single entry edge, or two if
3695     // we already fixed them.
3696     assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3697 
3698     // We found a reduction value exit-PHI. Update it with the
3699     // incoming bypass edge.
3700     if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
3701       LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
3702   } // end of the LCSSA phi scan.
3703 
3704     // Fix the scalar loop reduction variable with the incoming reduction sum
3705     // from the vector body and from the backedge value.
3706   int IncomingEdgeBlockIdx =
3707     Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
3708   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3709   // Pick the other block.
3710   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3711   Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3712   Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3713 }
3714 
3715 void InnerLoopVectorizer::fixLCSSAPHIs() {
3716   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3717     if (LCSSAPhi.getNumIncomingValues() == 1) {
3718       assert(OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) &&
3719              "Incoming value isn't loop invariant");
3720       LCSSAPhi.addIncoming(LCSSAPhi.getIncomingValue(0), LoopMiddleBlock);
3721     }
3722   }
3723 }
3724 
3725 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
3726   // The basic block and loop containing the predicated instruction.
3727   auto *PredBB = PredInst->getParent();
3728   auto *VectorLoop = LI->getLoopFor(PredBB);
3729 
3730   // Initialize a worklist with the operands of the predicated instruction.
3731   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
3732 
3733   // Holds instructions that we need to analyze again. An instruction may be
3734   // reanalyzed if we don't yet know if we can sink it or not.
3735   SmallVector<Instruction *, 8> InstsToReanalyze;
3736 
3737   // Returns true if a given use occurs in the predicated block. Phi nodes use
3738   // their operands in their corresponding predecessor blocks.
3739   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
3740     auto *I = cast<Instruction>(U.getUser());
3741     BasicBlock *BB = I->getParent();
3742     if (auto *Phi = dyn_cast<PHINode>(I))
3743       BB = Phi->getIncomingBlock(
3744           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3745     return BB == PredBB;
3746   };
3747 
3748   // Iteratively sink the scalarized operands of the predicated instruction
3749   // into the block we created for it. When an instruction is sunk, it's
3750   // operands are then added to the worklist. The algorithm ends after one pass
3751   // through the worklist doesn't sink a single instruction.
3752   bool Changed;
3753   do {
3754     // Add the instructions that need to be reanalyzed to the worklist, and
3755     // reset the changed indicator.
3756     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
3757     InstsToReanalyze.clear();
3758     Changed = false;
3759 
3760     while (!Worklist.empty()) {
3761       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
3762 
3763       // We can't sink an instruction if it is a phi node, is already in the
3764       // predicated block, is not in the loop, or may have side effects.
3765       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
3766           !VectorLoop->contains(I) || I->mayHaveSideEffects())
3767         continue;
3768 
3769       // It's legal to sink the instruction if all its uses occur in the
3770       // predicated block. Otherwise, there's nothing to do yet, and we may
3771       // need to reanalyze the instruction.
3772       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
3773         InstsToReanalyze.push_back(I);
3774         continue;
3775       }
3776 
3777       // Move the instruction to the beginning of the predicated block, and add
3778       // it's operands to the worklist.
3779       I->moveBefore(&*PredBB->getFirstInsertionPt());
3780       Worklist.insert(I->op_begin(), I->op_end());
3781 
3782       // The sinking may have enabled other instructions to be sunk, so we will
3783       // need to iterate.
3784       Changed = true;
3785     }
3786   } while (Changed);
3787 }
3788 
3789 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
3790                                               unsigned VF) {
3791   assert(PN->getParent() == OrigLoop->getHeader() &&
3792          "Non-header phis should have been handled elsewhere");
3793 
3794   PHINode *P = cast<PHINode>(PN);
3795   // In order to support recurrences we need to be able to vectorize Phi nodes.
3796   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3797   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
3798   // this value when we vectorize all of the instructions that use the PHI.
3799   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
3800     for (unsigned Part = 0; Part < UF; ++Part) {
3801       // This is phase one of vectorizing PHIs.
3802       Type *VecTy =
3803           (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
3804       Value *EntryPart = PHINode::Create(
3805           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
3806       VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
3807     }
3808     return;
3809   }
3810 
3811   setDebugLocFromInst(Builder, P);
3812 
3813   // This PHINode must be an induction variable.
3814   // Make sure that we know about it.
3815   assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
3816 
3817   InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3818   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3819 
3820   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3821   // which can be found from the original scalar operations.
3822   switch (II.getKind()) {
3823   case InductionDescriptor::IK_NoInduction:
3824     llvm_unreachable("Unknown induction");
3825   case InductionDescriptor::IK_IntInduction:
3826   case InductionDescriptor::IK_FpInduction:
3827     llvm_unreachable("Integer/fp induction is handled elsewhere.");
3828   case InductionDescriptor::IK_PtrInduction: {
3829     // Handle the pointer induction variable case.
3830     assert(P->getType()->isPointerTy() && "Unexpected type.");
3831     // This is the normalized GEP that starts counting at zero.
3832     Value *PtrInd = Induction;
3833     PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
3834     // Determine the number of scalars we need to generate for each unroll
3835     // iteration. If the instruction is uniform, we only need to generate the
3836     // first lane. Otherwise, we generate all VF values.
3837     unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
3838     // These are the scalar results. Notice that we don't generate vector GEPs
3839     // because scalar GEPs result in better code.
3840     for (unsigned Part = 0; Part < UF; ++Part) {
3841       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
3842         Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
3843         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3844         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
3845         SclrGep->setName("next.gep");
3846         VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
3847       }
3848     }
3849     return;
3850   }
3851   }
3852 }
3853 
3854 /// A helper function for checking whether an integer division-related
3855 /// instruction may divide by zero (in which case it must be predicated if
3856 /// executed conditionally in the scalar code).
3857 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
3858 /// Non-zero divisors that are non compile-time constants will not be
3859 /// converted into multiplication, so we will still end up scalarizing
3860 /// the division, but can do so w/o predication.
3861 static bool mayDivideByZero(Instruction &I) {
3862   assert((I.getOpcode() == Instruction::UDiv ||
3863           I.getOpcode() == Instruction::SDiv ||
3864           I.getOpcode() == Instruction::URem ||
3865           I.getOpcode() == Instruction::SRem) &&
3866          "Unexpected instruction");
3867   Value *Divisor = I.getOperand(1);
3868   auto *CInt = dyn_cast<ConstantInt>(Divisor);
3869   return !CInt || CInt->isZero();
3870 }
3871 
3872 void InnerLoopVectorizer::widenInstruction(Instruction &I) {
3873   switch (I.getOpcode()) {
3874   case Instruction::Br:
3875   case Instruction::PHI:
3876     llvm_unreachable("This instruction is handled by a different recipe.");
3877   case Instruction::GetElementPtr: {
3878     // Construct a vector GEP by widening the operands of the scalar GEP as
3879     // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
3880     // results in a vector of pointers when at least one operand of the GEP
3881     // is vector-typed. Thus, to keep the representation compact, we only use
3882     // vector-typed operands for loop-varying values.
3883     auto *GEP = cast<GetElementPtrInst>(&I);
3884 
3885     if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
3886       // If we are vectorizing, but the GEP has only loop-invariant operands,
3887       // the GEP we build (by only using vector-typed operands for
3888       // loop-varying values) would be a scalar pointer. Thus, to ensure we
3889       // produce a vector of pointers, we need to either arbitrarily pick an
3890       // operand to broadcast, or broadcast a clone of the original GEP.
3891       // Here, we broadcast a clone of the original.
3892       //
3893       // TODO: If at some point we decide to scalarize instructions having
3894       //       loop-invariant operands, this special case will no longer be
3895       //       required. We would add the scalarization decision to
3896       //       collectLoopScalars() and teach getVectorValue() to broadcast
3897       //       the lane-zero scalar value.
3898       auto *Clone = Builder.Insert(GEP->clone());
3899       for (unsigned Part = 0; Part < UF; ++Part) {
3900         Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
3901         VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
3902         addMetadata(EntryPart, GEP);
3903       }
3904     } else {
3905       // If the GEP has at least one loop-varying operand, we are sure to
3906       // produce a vector of pointers. But if we are only unrolling, we want
3907       // to produce a scalar GEP for each unroll part. Thus, the GEP we
3908       // produce with the code below will be scalar (if VF == 1) or vector
3909       // (otherwise). Note that for the unroll-only case, we still maintain
3910       // values in the vector mapping with initVector, as we do for other
3911       // instructions.
3912       for (unsigned Part = 0; Part < UF; ++Part) {
3913         // The pointer operand of the new GEP. If it's loop-invariant, we
3914         // won't broadcast it.
3915         auto *Ptr =
3916             OrigLoop->isLoopInvariant(GEP->getPointerOperand())
3917                 ? GEP->getPointerOperand()
3918                 : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
3919 
3920         // Collect all the indices for the new GEP. If any index is
3921         // loop-invariant, we won't broadcast it.
3922         SmallVector<Value *, 4> Indices;
3923         for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
3924           if (OrigLoop->isLoopInvariant(U.get()))
3925             Indices.push_back(U.get());
3926           else
3927             Indices.push_back(getOrCreateVectorValue(U.get(), Part));
3928         }
3929 
3930         // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
3931         // but it should be a vector, otherwise.
3932         auto *NewGEP = GEP->isInBounds()
3933                            ? Builder.CreateInBoundsGEP(Ptr, Indices)
3934                            : Builder.CreateGEP(Ptr, Indices);
3935         assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
3936                "NewGEP is not a pointer vector");
3937         VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
3938         addMetadata(NewGEP, GEP);
3939       }
3940     }
3941 
3942     break;
3943   }
3944   case Instruction::UDiv:
3945   case Instruction::SDiv:
3946   case Instruction::SRem:
3947   case Instruction::URem:
3948   case Instruction::Add:
3949   case Instruction::FAdd:
3950   case Instruction::Sub:
3951   case Instruction::FSub:
3952   case Instruction::Mul:
3953   case Instruction::FMul:
3954   case Instruction::FDiv:
3955   case Instruction::FRem:
3956   case Instruction::Shl:
3957   case Instruction::LShr:
3958   case Instruction::AShr:
3959   case Instruction::And:
3960   case Instruction::Or:
3961   case Instruction::Xor: {
3962     // Just widen binops.
3963     auto *BinOp = cast<BinaryOperator>(&I);
3964     setDebugLocFromInst(Builder, BinOp);
3965 
3966     for (unsigned Part = 0; Part < UF; ++Part) {
3967       Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
3968       Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
3969       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
3970 
3971       if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3972         VecOp->copyIRFlags(BinOp);
3973 
3974       // Use this vector value for all users of the original instruction.
3975       VectorLoopValueMap.setVectorValue(&I, Part, V);
3976       addMetadata(V, BinOp);
3977     }
3978 
3979     break;
3980   }
3981   case Instruction::Select: {
3982     // Widen selects.
3983     // If the selector is loop invariant we can create a select
3984     // instruction with a scalar condition. Otherwise, use vector-select.
3985     auto *SE = PSE.getSE();
3986     bool InvariantCond =
3987         SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
3988     setDebugLocFromInst(Builder, &I);
3989 
3990     // The condition can be loop invariant  but still defined inside the
3991     // loop. This means that we can't just use the original 'cond' value.
3992     // We have to take the 'vectorized' value and pick the first lane.
3993     // Instcombine will make this a no-op.
3994 
3995     auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
3996 
3997     for (unsigned Part = 0; Part < UF; ++Part) {
3998       Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
3999       Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
4000       Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
4001       Value *Sel =
4002           Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
4003       VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4004       addMetadata(Sel, &I);
4005     }
4006 
4007     break;
4008   }
4009 
4010   case Instruction::ICmp:
4011   case Instruction::FCmp: {
4012     // Widen compares. Generate vector compares.
4013     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4014     auto *Cmp = dyn_cast<CmpInst>(&I);
4015     setDebugLocFromInst(Builder, Cmp);
4016     for (unsigned Part = 0; Part < UF; ++Part) {
4017       Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
4018       Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
4019       Value *C = nullptr;
4020       if (FCmp) {
4021         // Propagate fast math flags.
4022         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4023         Builder.setFastMathFlags(Cmp->getFastMathFlags());
4024         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4025       } else {
4026         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4027       }
4028       VectorLoopValueMap.setVectorValue(&I, Part, C);
4029       addMetadata(C, &I);
4030     }
4031 
4032     break;
4033   }
4034 
4035   case Instruction::ZExt:
4036   case Instruction::SExt:
4037   case Instruction::FPToUI:
4038   case Instruction::FPToSI:
4039   case Instruction::FPExt:
4040   case Instruction::PtrToInt:
4041   case Instruction::IntToPtr:
4042   case Instruction::SIToFP:
4043   case Instruction::UIToFP:
4044   case Instruction::Trunc:
4045   case Instruction::FPTrunc:
4046   case Instruction::BitCast: {
4047     auto *CI = dyn_cast<CastInst>(&I);
4048     setDebugLocFromInst(Builder, CI);
4049 
4050     /// Vectorize casts.
4051     Type *DestTy =
4052         (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4053 
4054     for (unsigned Part = 0; Part < UF; ++Part) {
4055       Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4056       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4057       VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4058       addMetadata(Cast, &I);
4059     }
4060     break;
4061   }
4062 
4063   case Instruction::Call: {
4064     // Ignore dbg intrinsics.
4065     if (isa<DbgInfoIntrinsic>(I))
4066       break;
4067     setDebugLocFromInst(Builder, &I);
4068 
4069     Module *M = I.getParent()->getParent()->getParent();
4070     auto *CI = cast<CallInst>(&I);
4071 
4072     StringRef FnName = CI->getCalledFunction()->getName();
4073     Function *F = CI->getCalledFunction();
4074     Type *RetTy = ToVectorTy(CI->getType(), VF);
4075     SmallVector<Type *, 4> Tys;
4076     for (Value *ArgOperand : CI->arg_operands())
4077       Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4078 
4079     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4080 
4081     // The flag shows whether we use Intrinsic or a usual Call for vectorized
4082     // version of the instruction.
4083     // Is it beneficial to perform intrinsic call compared to lib call?
4084     bool NeedToScalarize;
4085     unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4086     bool UseVectorIntrinsic =
4087         ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4088     assert((UseVectorIntrinsic || !NeedToScalarize) &&
4089            "Instruction should be scalarized elsewhere.");
4090 
4091     for (unsigned Part = 0; Part < UF; ++Part) {
4092       SmallVector<Value *, 4> Args;
4093       for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4094         Value *Arg = CI->getArgOperand(i);
4095         // Some intrinsics have a scalar argument - don't replace it with a
4096         // vector.
4097         if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
4098           Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4099         Args.push_back(Arg);
4100       }
4101 
4102       Function *VectorF;
4103       if (UseVectorIntrinsic) {
4104         // Use vector version of the intrinsic.
4105         Type *TysForDecl[] = {CI->getType()};
4106         if (VF > 1)
4107           TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4108         VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4109       } else {
4110         // Use vector version of the library call.
4111         StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4112         assert(!VFnName.empty() && "Vector function name is empty.");
4113         VectorF = M->getFunction(VFnName);
4114         if (!VectorF) {
4115           // Generate a declaration
4116           FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4117           VectorF =
4118               Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4119           VectorF->copyAttributesFrom(F);
4120         }
4121       }
4122       assert(VectorF && "Can't create vector function.");
4123 
4124       SmallVector<OperandBundleDef, 1> OpBundles;
4125       CI->getOperandBundlesAsDefs(OpBundles);
4126       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4127 
4128       if (isa<FPMathOperator>(V))
4129         V->copyFastMathFlags(CI);
4130 
4131       VectorLoopValueMap.setVectorValue(&I, Part, V);
4132       addMetadata(V, &I);
4133     }
4134 
4135     break;
4136   }
4137 
4138   default:
4139     // This instruction is not vectorized by simple widening.
4140     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4141     llvm_unreachable("Unhandled instruction!");
4142   } // end of switch.
4143 }
4144 
4145 void InnerLoopVectorizer::updateAnalysis() {
4146   // Forget the original basic block.
4147   PSE.getSE()->forgetLoop(OrigLoop);
4148 
4149   // Update the dominator tree information.
4150   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
4151          "Entry does not dominate exit.");
4152 
4153   DT->addNewBlock(LoopMiddleBlock,
4154                   LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4155   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4156   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4157   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4158   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
4159 }
4160 
4161 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
4162   // We should not collect Scalars more than once per VF. Right now, this
4163   // function is called from collectUniformsAndScalars(), which already does
4164   // this check. Collecting Scalars for VF=1 does not make any sense.
4165   assert(VF >= 2 && !Scalars.count(VF) &&
4166          "This function should not be visited twice for the same VF");
4167 
4168   SmallSetVector<Instruction *, 8> Worklist;
4169 
4170   // These sets are used to seed the analysis with pointers used by memory
4171   // accesses that will remain scalar.
4172   SmallSetVector<Instruction *, 8> ScalarPtrs;
4173   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4174 
4175   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4176   // The pointer operands of loads and stores will be scalar as long as the
4177   // memory access is not a gather or scatter operation. The value operand of a
4178   // store will remain scalar if the store is scalarized.
4179   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4180     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4181     assert(WideningDecision != CM_Unknown &&
4182            "Widening decision should be ready at this moment");
4183     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4184       if (Ptr == Store->getValueOperand())
4185         return WideningDecision == CM_Scalarize;
4186     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4187            "Ptr is neither a value or pointer operand");
4188     return WideningDecision != CM_GatherScatter;
4189   };
4190 
4191   // A helper that returns true if the given value is a bitcast or
4192   // getelementptr instruction contained in the loop.
4193   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4194     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4195             isa<GetElementPtrInst>(V)) &&
4196            !TheLoop->isLoopInvariant(V);
4197   };
4198 
4199   // A helper that evaluates a memory access's use of a pointer. If the use
4200   // will be a scalar use, and the pointer is only used by memory accesses, we
4201   // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4202   // PossibleNonScalarPtrs.
4203   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4204     // We only care about bitcast and getelementptr instructions contained in
4205     // the loop.
4206     if (!isLoopVaryingBitCastOrGEP(Ptr))
4207       return;
4208 
4209     // If the pointer has already been identified as scalar (e.g., if it was
4210     // also identified as uniform), there's nothing to do.
4211     auto *I = cast<Instruction>(Ptr);
4212     if (Worklist.count(I))
4213       return;
4214 
4215     // If the use of the pointer will be a scalar use, and all users of the
4216     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4217     // place the pointer in PossibleNonScalarPtrs.
4218     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4219           return isa<LoadInst>(U) || isa<StoreInst>(U);
4220         }))
4221       ScalarPtrs.insert(I);
4222     else
4223       PossibleNonScalarPtrs.insert(I);
4224   };
4225 
4226   // We seed the scalars analysis with three classes of instructions: (1)
4227   // instructions marked uniform-after-vectorization, (2) bitcast and
4228   // getelementptr instructions used by memory accesses requiring a scalar use,
4229   // and (3) pointer induction variables and their update instructions (we
4230   // currently only scalarize these).
4231   //
4232   // (1) Add to the worklist all instructions that have been identified as
4233   // uniform-after-vectorization.
4234   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4235 
4236   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4237   // memory accesses requiring a scalar use. The pointer operands of loads and
4238   // stores will be scalar as long as the memory accesses is not a gather or
4239   // scatter operation. The value operand of a store will remain scalar if the
4240   // store is scalarized.
4241   for (auto *BB : TheLoop->blocks())
4242     for (auto &I : *BB) {
4243       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4244         evaluatePtrUse(Load, Load->getPointerOperand());
4245       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4246         evaluatePtrUse(Store, Store->getPointerOperand());
4247         evaluatePtrUse(Store, Store->getValueOperand());
4248       }
4249     }
4250   for (auto *I : ScalarPtrs)
4251     if (!PossibleNonScalarPtrs.count(I)) {
4252       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4253       Worklist.insert(I);
4254     }
4255 
4256   // (3) Add to the worklist all pointer induction variables and their update
4257   // instructions.
4258   //
4259   // TODO: Once we are able to vectorize pointer induction variables we should
4260   //       no longer insert them into the worklist here.
4261   auto *Latch = TheLoop->getLoopLatch();
4262   for (auto &Induction : *Legal->getInductionVars()) {
4263     auto *Ind = Induction.first;
4264     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4265     if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
4266       continue;
4267     Worklist.insert(Ind);
4268     Worklist.insert(IndUpdate);
4269     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4270     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4271                       << "\n");
4272   }
4273 
4274   // Insert the forced scalars.
4275   // FIXME: Currently widenPHIInstruction() often creates a dead vector
4276   // induction variable when the PHI user is scalarized.
4277   if (ForcedScalars.count(VF))
4278     for (auto *I : ForcedScalars.find(VF)->second)
4279       Worklist.insert(I);
4280 
4281   // Expand the worklist by looking through any bitcasts and getelementptr
4282   // instructions we've already identified as scalar. This is similar to the
4283   // expansion step in collectLoopUniforms(); however, here we're only
4284   // expanding to include additional bitcasts and getelementptr instructions.
4285   unsigned Idx = 0;
4286   while (Idx != Worklist.size()) {
4287     Instruction *Dst = Worklist[Idx++];
4288     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4289       continue;
4290     auto *Src = cast<Instruction>(Dst->getOperand(0));
4291     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4292           auto *J = cast<Instruction>(U);
4293           return !TheLoop->contains(J) || Worklist.count(J) ||
4294                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4295                   isScalarUse(J, Src));
4296         })) {
4297       Worklist.insert(Src);
4298       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4299     }
4300   }
4301 
4302   // An induction variable will remain scalar if all users of the induction
4303   // variable and induction variable update remain scalar.
4304   for (auto &Induction : *Legal->getInductionVars()) {
4305     auto *Ind = Induction.first;
4306     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4307 
4308     // We already considered pointer induction variables, so there's no reason
4309     // to look at their users again.
4310     //
4311     // TODO: Once we are able to vectorize pointer induction variables we
4312     //       should no longer skip over them here.
4313     if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
4314       continue;
4315 
4316     // Determine if all users of the induction variable are scalar after
4317     // vectorization.
4318     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4319       auto *I = cast<Instruction>(U);
4320       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
4321     });
4322     if (!ScalarInd)
4323       continue;
4324 
4325     // Determine if all users of the induction variable update instruction are
4326     // scalar after vectorization.
4327     auto ScalarIndUpdate =
4328         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4329           auto *I = cast<Instruction>(U);
4330           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
4331         });
4332     if (!ScalarIndUpdate)
4333       continue;
4334 
4335     // The induction variable and its update instruction will remain scalar.
4336     Worklist.insert(Ind);
4337     Worklist.insert(IndUpdate);
4338     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4339     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4340                       << "\n");
4341   }
4342 
4343   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4344 }
4345 
4346 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) {
4347   if (!Legal->blockNeedsPredication(I->getParent()))
4348     return false;
4349   switch(I->getOpcode()) {
4350   default:
4351     break;
4352   case Instruction::Load:
4353   case Instruction::Store: {
4354     if (!Legal->isMaskRequired(I))
4355       return false;
4356     auto *Ptr = getLoadStorePointerOperand(I);
4357     auto *Ty = getMemInstValueType(I);
4358     return isa<LoadInst>(I) ?
4359         !(isLegalMaskedLoad(Ty, Ptr)  || isLegalMaskedGather(Ty))
4360       : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
4361   }
4362   case Instruction::UDiv:
4363   case Instruction::SDiv:
4364   case Instruction::SRem:
4365   case Instruction::URem:
4366     return mayDivideByZero(*I);
4367   }
4368   return false;
4369 }
4370 
4371 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I,
4372                                                                unsigned VF) {
4373   // Get and ensure we have a valid memory instruction.
4374   LoadInst *LI = dyn_cast<LoadInst>(I);
4375   StoreInst *SI = dyn_cast<StoreInst>(I);
4376   assert((LI || SI) && "Invalid memory instruction");
4377 
4378   auto *Ptr = getLoadStorePointerOperand(I);
4379 
4380   // In order to be widened, the pointer should be consecutive, first of all.
4381   if (!Legal->isConsecutivePtr(Ptr))
4382     return false;
4383 
4384   // If the instruction is a store located in a predicated block, it will be
4385   // scalarized.
4386   if (isScalarWithPredication(I))
4387     return false;
4388 
4389   // If the instruction's allocated size doesn't equal it's type size, it
4390   // requires padding and will be scalarized.
4391   auto &DL = I->getModule()->getDataLayout();
4392   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
4393   if (hasIrregularType(ScalarTy, DL, VF))
4394     return false;
4395 
4396   return true;
4397 }
4398 
4399 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
4400   // We should not collect Uniforms more than once per VF. Right now,
4401   // this function is called from collectUniformsAndScalars(), which
4402   // already does this check. Collecting Uniforms for VF=1 does not make any
4403   // sense.
4404 
4405   assert(VF >= 2 && !Uniforms.count(VF) &&
4406          "This function should not be visited twice for the same VF");
4407 
4408   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4409   // not analyze again.  Uniforms.count(VF) will return 1.
4410   Uniforms[VF].clear();
4411 
4412   // We now know that the loop is vectorizable!
4413   // Collect instructions inside the loop that will remain uniform after
4414   // vectorization.
4415 
4416   // Global values, params and instructions outside of current loop are out of
4417   // scope.
4418   auto isOutOfScope = [&](Value *V) -> bool {
4419     Instruction *I = dyn_cast<Instruction>(V);
4420     return (!I || !TheLoop->contains(I));
4421   };
4422 
4423   SetVector<Instruction *> Worklist;
4424   BasicBlock *Latch = TheLoop->getLoopLatch();
4425 
4426   // Start with the conditional branch. If the branch condition is an
4427   // instruction contained in the loop that is only used by the branch, it is
4428   // uniform.
4429   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4430   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
4431     Worklist.insert(Cmp);
4432     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
4433   }
4434 
4435   // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
4436   // are pointers that are treated like consecutive pointers during
4437   // vectorization. The pointer operands of interleaved accesses are an
4438   // example.
4439   SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
4440 
4441   // Holds pointer operands of instructions that are possibly non-uniform.
4442   SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
4443 
4444   auto isUniformDecision = [&](Instruction *I, unsigned VF) {
4445     InstWidening WideningDecision = getWideningDecision(I, VF);
4446     assert(WideningDecision != CM_Unknown &&
4447            "Widening decision should be ready at this moment");
4448 
4449     return (WideningDecision == CM_Widen ||
4450             WideningDecision == CM_Widen_Reverse ||
4451             WideningDecision == CM_Interleave);
4452   };
4453   // Iterate over the instructions in the loop, and collect all
4454   // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
4455   // that a consecutive-like pointer operand will be scalarized, we collect it
4456   // in PossibleNonUniformPtrs instead. We use two sets here because a single
4457   // getelementptr instruction can be used by both vectorized and scalarized
4458   // memory instructions. For example, if a loop loads and stores from the same
4459   // location, but the store is conditional, the store will be scalarized, and
4460   // the getelementptr won't remain uniform.
4461   for (auto *BB : TheLoop->blocks())
4462     for (auto &I : *BB) {
4463       // If there's no pointer operand, there's nothing to do.
4464       auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
4465       if (!Ptr)
4466         continue;
4467 
4468       // True if all users of Ptr are memory accesses that have Ptr as their
4469       // pointer operand.
4470       auto UsersAreMemAccesses =
4471           llvm::all_of(Ptr->users(), [&](User *U) -> bool {
4472             return getLoadStorePointerOperand(U) == Ptr;
4473           });
4474 
4475       // Ensure the memory instruction will not be scalarized or used by
4476       // gather/scatter, making its pointer operand non-uniform. If the pointer
4477       // operand is used by any instruction other than a memory access, we
4478       // conservatively assume the pointer operand may be non-uniform.
4479       if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
4480         PossibleNonUniformPtrs.insert(Ptr);
4481 
4482       // If the memory instruction will be vectorized and its pointer operand
4483       // is consecutive-like, or interleaving - the pointer operand should
4484       // remain uniform.
4485       else
4486         ConsecutiveLikePtrs.insert(Ptr);
4487     }
4488 
4489   // Add to the Worklist all consecutive and consecutive-like pointers that
4490   // aren't also identified as possibly non-uniform.
4491   for (auto *V : ConsecutiveLikePtrs)
4492     if (!PossibleNonUniformPtrs.count(V)) {
4493       LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
4494       Worklist.insert(V);
4495     }
4496 
4497   // Expand Worklist in topological order: whenever a new instruction
4498   // is added , its users should be either already inside Worklist, or
4499   // out of scope. It ensures a uniform instruction will only be used
4500   // by uniform instructions or out of scope instructions.
4501   unsigned idx = 0;
4502   while (idx != Worklist.size()) {
4503     Instruction *I = Worklist[idx++];
4504 
4505     for (auto OV : I->operand_values()) {
4506       if (isOutOfScope(OV))
4507         continue;
4508       auto *OI = cast<Instruction>(OV);
4509       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4510             auto *J = cast<Instruction>(U);
4511             return !TheLoop->contains(J) || Worklist.count(J) ||
4512                    (OI == getLoadStorePointerOperand(J) &&
4513                     isUniformDecision(J, VF));
4514           })) {
4515         Worklist.insert(OI);
4516         LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
4517       }
4518     }
4519   }
4520 
4521   // Returns true if Ptr is the pointer operand of a memory access instruction
4522   // I, and I is known to not require scalarization.
4523   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4524     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4525   };
4526 
4527   // For an instruction to be added into Worklist above, all its users inside
4528   // the loop should also be in Worklist. However, this condition cannot be
4529   // true for phi nodes that form a cyclic dependence. We must process phi
4530   // nodes separately. An induction variable will remain uniform if all users
4531   // of the induction variable and induction variable update remain uniform.
4532   // The code below handles both pointer and non-pointer induction variables.
4533   for (auto &Induction : *Legal->getInductionVars()) {
4534     auto *Ind = Induction.first;
4535     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4536 
4537     // Determine if all users of the induction variable are uniform after
4538     // vectorization.
4539     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4540       auto *I = cast<Instruction>(U);
4541       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4542              isVectorizedMemAccessUse(I, Ind);
4543     });
4544     if (!UniformInd)
4545       continue;
4546 
4547     // Determine if all users of the induction variable update instruction are
4548     // uniform after vectorization.
4549     auto UniformIndUpdate =
4550         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4551           auto *I = cast<Instruction>(U);
4552           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4553                  isVectorizedMemAccessUse(I, IndUpdate);
4554         });
4555     if (!UniformIndUpdate)
4556       continue;
4557 
4558     // The induction variable and its update instruction will remain uniform.
4559     Worklist.insert(Ind);
4560     Worklist.insert(IndUpdate);
4561     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
4562     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate
4563                       << "\n");
4564   }
4565 
4566   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4567 }
4568 
4569 void InterleavedAccessInfo::collectConstStrideAccesses(
4570     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
4571     const ValueToValueMap &Strides) {
4572   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4573 
4574   // Since it's desired that the load/store instructions be maintained in
4575   // "program order" for the interleaved access analysis, we have to visit the
4576   // blocks in the loop in reverse postorder (i.e., in a topological order).
4577   // Such an ordering will ensure that any load/store that may be executed
4578   // before a second load/store will precede the second load/store in
4579   // AccessStrideInfo.
4580   LoopBlocksDFS DFS(TheLoop);
4581   DFS.perform(LI);
4582   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
4583     for (auto &I : *BB) {
4584       auto *LI = dyn_cast<LoadInst>(&I);
4585       auto *SI = dyn_cast<StoreInst>(&I);
4586       if (!LI && !SI)
4587         continue;
4588 
4589       Value *Ptr = getLoadStorePointerOperand(&I);
4590       // We don't check wrapping here because we don't know yet if Ptr will be
4591       // part of a full group or a group with gaps. Checking wrapping for all
4592       // pointers (even those that end up in groups with no gaps) will be overly
4593       // conservative. For full groups, wrapping should be ok since if we would
4594       // wrap around the address space we would do a memory access at nullptr
4595       // even without the transformation. The wrapping checks are therefore
4596       // deferred until after we've formed the interleaved groups.
4597       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
4598                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
4599 
4600       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
4601       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4602       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
4603 
4604       // An alignment of 0 means target ABI alignment.
4605       unsigned Align = getMemInstAlignment(&I);
4606       if (!Align)
4607         Align = DL.getABITypeAlignment(PtrTy->getElementType());
4608 
4609       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
4610     }
4611 }
4612 
4613 // Analyze interleaved accesses and collect them into interleaved load and
4614 // store groups.
4615 //
4616 // When generating code for an interleaved load group, we effectively hoist all
4617 // loads in the group to the location of the first load in program order. When
4618 // generating code for an interleaved store group, we sink all stores to the
4619 // location of the last store. This code motion can change the order of load
4620 // and store instructions and may break dependences.
4621 //
4622 // The code generation strategy mentioned above ensures that we won't violate
4623 // any write-after-read (WAR) dependences.
4624 //
4625 // E.g., for the WAR dependence:  a = A[i];      // (1)
4626 //                                A[i] = b;      // (2)
4627 //
4628 // The store group of (2) is always inserted at or below (2), and the load
4629 // group of (1) is always inserted at or above (1). Thus, the instructions will
4630 // never be reordered. All other dependences are checked to ensure the
4631 // correctness of the instruction reordering.
4632 //
4633 // The algorithm visits all memory accesses in the loop in bottom-up program
4634 // order. Program order is established by traversing the blocks in the loop in
4635 // reverse postorder when collecting the accesses.
4636 //
4637 // We visit the memory accesses in bottom-up order because it can simplify the
4638 // construction of store groups in the presence of write-after-write (WAW)
4639 // dependences.
4640 //
4641 // E.g., for the WAW dependence:  A[i] = a;      // (1)
4642 //                                A[i] = b;      // (2)
4643 //                                A[i + 1] = c;  // (3)
4644 //
4645 // We will first create a store group with (3) and (2). (1) can't be added to
4646 // this group because it and (2) are dependent. However, (1) can be grouped
4647 // with other accesses that may precede it in program order. Note that a
4648 // bottom-up order does not imply that WAW dependences should not be checked.
4649 void InterleavedAccessInfo::analyzeInterleaving() {
4650   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4651   const ValueToValueMap &Strides = LAI->getSymbolicStrides();
4652 
4653   // Holds all accesses with a constant stride.
4654   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
4655   collectConstStrideAccesses(AccessStrideInfo, Strides);
4656 
4657   if (AccessStrideInfo.empty())
4658     return;
4659 
4660   // Collect the dependences in the loop.
4661   collectDependences();
4662 
4663   // Holds all interleaved store groups temporarily.
4664   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4665   // Holds all interleaved load groups temporarily.
4666   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
4667 
4668   // Search in bottom-up program order for pairs of accesses (A and B) that can
4669   // form interleaved load or store groups. In the algorithm below, access A
4670   // precedes access B in program order. We initialize a group for B in the
4671   // outer loop of the algorithm, and then in the inner loop, we attempt to
4672   // insert each A into B's group if:
4673   //
4674   //  1. A and B have the same stride,
4675   //  2. A and B have the same memory object size, and
4676   //  3. A belongs in B's group according to its distance from B.
4677   //
4678   // Special care is taken to ensure group formation will not break any
4679   // dependences.
4680   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
4681        BI != E; ++BI) {
4682     Instruction *B = BI->first;
4683     StrideDescriptor DesB = BI->second;
4684 
4685     // Initialize a group for B if it has an allowable stride. Even if we don't
4686     // create a group for B, we continue with the bottom-up algorithm to ensure
4687     // we don't break any of B's dependences.
4688     InterleaveGroup *Group = nullptr;
4689     if (isStrided(DesB.Stride)) {
4690       Group = getInterleaveGroup(B);
4691       if (!Group) {
4692         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
4693                           << '\n');
4694         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
4695       }
4696       if (B->mayWriteToMemory())
4697         StoreGroups.insert(Group);
4698       else
4699         LoadGroups.insert(Group);
4700     }
4701 
4702     for (auto AI = std::next(BI); AI != E; ++AI) {
4703       Instruction *A = AI->first;
4704       StrideDescriptor DesA = AI->second;
4705 
4706       // Our code motion strategy implies that we can't have dependences
4707       // between accesses in an interleaved group and other accesses located
4708       // between the first and last member of the group. Note that this also
4709       // means that a group can't have more than one member at a given offset.
4710       // The accesses in a group can have dependences with other accesses, but
4711       // we must ensure we don't extend the boundaries of the group such that
4712       // we encompass those dependent accesses.
4713       //
4714       // For example, assume we have the sequence of accesses shown below in a
4715       // stride-2 loop:
4716       //
4717       //  (1, 2) is a group | A[i]   = a;  // (1)
4718       //                    | A[i-1] = b;  // (2) |
4719       //                      A[i-3] = c;  // (3)
4720       //                      A[i]   = d;  // (4) | (2, 4) is not a group
4721       //
4722       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
4723       // but not with (4). If we did, the dependent access (3) would be within
4724       // the boundaries of the (2, 4) group.
4725       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
4726         // If a dependence exists and A is already in a group, we know that A
4727         // must be a store since A precedes B and WAR dependences are allowed.
4728         // Thus, A would be sunk below B. We release A's group to prevent this
4729         // illegal code motion. A will then be free to form another group with
4730         // instructions that precede it.
4731         if (isInterleaved(A)) {
4732           InterleaveGroup *StoreGroup = getInterleaveGroup(A);
4733           StoreGroups.remove(StoreGroup);
4734           releaseGroup(StoreGroup);
4735         }
4736 
4737         // If a dependence exists and A is not already in a group (or it was
4738         // and we just released it), B might be hoisted above A (if B is a
4739         // load) or another store might be sunk below A (if B is a store). In
4740         // either case, we can't add additional instructions to B's group. B
4741         // will only form a group with instructions that it precedes.
4742         break;
4743       }
4744 
4745       // At this point, we've checked for illegal code motion. If either A or B
4746       // isn't strided, there's nothing left to do.
4747       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
4748         continue;
4749 
4750       // Ignore A if it's already in a group or isn't the same kind of memory
4751       // operation as B.
4752       // Note that mayReadFromMemory() isn't mutually exclusive to mayWriteToMemory
4753       // in the case of atomic loads. We shouldn't see those here, canVectorizeMemory()
4754       // should have returned false - except for the case we asked for optimization
4755       // remarks.
4756       if (isInterleaved(A) || (A->mayReadFromMemory() != B->mayReadFromMemory())
4757           || (A->mayWriteToMemory() != B->mayWriteToMemory()))
4758         continue;
4759 
4760       // Check rules 1 and 2. Ignore A if its stride or size is different from
4761       // that of B.
4762       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
4763         continue;
4764 
4765       // Ignore A if the memory object of A and B don't belong to the same
4766       // address space
4767       if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
4768         continue;
4769 
4770       // Calculate the distance from A to B.
4771       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
4772           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
4773       if (!DistToB)
4774         continue;
4775       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
4776 
4777       // Check rule 3. Ignore A if its distance to B is not a multiple of the
4778       // size.
4779       if (DistanceToB % static_cast<int64_t>(DesB.Size))
4780         continue;
4781 
4782       // Ignore A if either A or B is in a predicated block. Although we
4783       // currently prevent group formation for predicated accesses, we may be
4784       // able to relax this limitation in the future once we handle more
4785       // complicated blocks.
4786       if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
4787         continue;
4788 
4789       // The index of A is the index of B plus A's distance to B in multiples
4790       // of the size.
4791       int IndexA =
4792           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
4793 
4794       // Try to insert A into B's group.
4795       if (Group->insertMember(A, IndexA, DesA.Align)) {
4796         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
4797                           << "    into the interleave group with" << *B
4798                           << '\n');
4799         InterleaveGroupMap[A] = Group;
4800 
4801         // Set the first load in program order as the insert position.
4802         if (A->mayReadFromMemory())
4803           Group->setInsertPos(A);
4804       }
4805     } // Iteration over A accesses.
4806   } // Iteration over B accesses.
4807 
4808   // Remove interleaved store groups with gaps.
4809   for (InterleaveGroup *Group : StoreGroups)
4810     if (Group->getNumMembers() != Group->getFactor()) {
4811       LLVM_DEBUG(
4812           dbgs() << "LV: Invalidate candidate interleaved store group due "
4813                     "to gaps.\n");
4814       releaseGroup(Group);
4815     }
4816   // Remove interleaved groups with gaps (currently only loads) whose memory
4817   // accesses may wrap around. We have to revisit the getPtrStride analysis,
4818   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
4819   // not check wrapping (see documentation there).
4820   // FORNOW we use Assume=false;
4821   // TODO: Change to Assume=true but making sure we don't exceed the threshold
4822   // of runtime SCEV assumptions checks (thereby potentially failing to
4823   // vectorize altogether).
4824   // Additional optional optimizations:
4825   // TODO: If we are peeling the loop and we know that the first pointer doesn't
4826   // wrap then we can deduce that all pointers in the group don't wrap.
4827   // This means that we can forcefully peel the loop in order to only have to
4828   // check the first pointer for no-wrap. When we'll change to use Assume=true
4829   // we'll only need at most one runtime check per interleaved group.
4830   for (InterleaveGroup *Group : LoadGroups) {
4831     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
4832     // load would wrap around the address space we would do a memory access at
4833     // nullptr even without the transformation.
4834     if (Group->getNumMembers() == Group->getFactor())
4835       continue;
4836 
4837     // Case 2: If first and last members of the group don't wrap this implies
4838     // that all the pointers in the group don't wrap.
4839     // So we check only group member 0 (which is always guaranteed to exist),
4840     // and group member Factor - 1; If the latter doesn't exist we rely on
4841     // peeling (if it is a non-reveresed accsess -- see Case 3).
4842     Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
4843     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
4844                       /*ShouldCheckWrap=*/true)) {
4845       LLVM_DEBUG(
4846           dbgs() << "LV: Invalidate candidate interleaved group due to "
4847                     "first group member potentially pointer-wrapping.\n");
4848       releaseGroup(Group);
4849       continue;
4850     }
4851     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
4852     if (LastMember) {
4853       Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
4854       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
4855                         /*ShouldCheckWrap=*/true)) {
4856         LLVM_DEBUG(
4857             dbgs() << "LV: Invalidate candidate interleaved group due to "
4858                       "last group member potentially pointer-wrapping.\n");
4859         releaseGroup(Group);
4860       }
4861     } else {
4862       // Case 3: A non-reversed interleaved load group with gaps: We need
4863       // to execute at least one scalar epilogue iteration. This will ensure
4864       // we don't speculatively access memory out-of-bounds. We only need
4865       // to look for a member at index factor - 1, since every group must have
4866       // a member at index zero.
4867       if (Group->isReverse()) {
4868         LLVM_DEBUG(
4869             dbgs() << "LV: Invalidate candidate interleaved group due to "
4870                       "a reverse access with gaps.\n");
4871         releaseGroup(Group);
4872         continue;
4873       }
4874       LLVM_DEBUG(
4875           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
4876       RequiresScalarEpilogue = true;
4877     }
4878   }
4879 }
4880 
4881 Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
4882   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
4883     // TODO: It may by useful to do since it's still likely to be dynamically
4884     // uniform if the target can skip.
4885     LLVM_DEBUG(
4886         dbgs() << "LV: Not inserting runtime ptr check for divergent target");
4887 
4888     ORE->emit(
4889       createMissedAnalysis("CantVersionLoopWithDivergentTarget")
4890       << "runtime pointer checks needed. Not enabled for divergent target");
4891 
4892     return None;
4893   }
4894 
4895   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
4896   if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
4897     return computeFeasibleMaxVF(OptForSize, TC);
4898 
4899   if (Legal->getRuntimePointerChecking()->Need) {
4900     ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
4901               << "runtime pointer checks needed. Enable vectorization of this "
4902                  "loop with '#pragma clang loop vectorize(enable)' when "
4903                  "compiling with -Os/-Oz");
4904     LLVM_DEBUG(
4905         dbgs()
4906         << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4907     return None;
4908   }
4909 
4910   // If we optimize the program for size, avoid creating the tail loop.
4911   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4912 
4913   // If we don't know the precise trip count, don't try to vectorize.
4914   if (TC < 2) {
4915     ORE->emit(
4916         createMissedAnalysis("UnknownLoopCountComplexCFG")
4917         << "unable to calculate the loop count due to complex control flow");
4918     LLVM_DEBUG(
4919         dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4920     return None;
4921   }
4922 
4923   unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
4924 
4925   if (TC % MaxVF != 0) {
4926     // If the trip count that we found modulo the vectorization factor is not
4927     // zero then we require a tail.
4928     // FIXME: look for a smaller MaxVF that does divide TC rather than give up.
4929     // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a
4930     //        smaller MaxVF that does not require a scalar epilog.
4931 
4932     ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
4933               << "cannot optimize for size and vectorize at the "
4934                  "same time. Enable vectorization of this loop "
4935                  "with '#pragma clang loop vectorize(enable)' "
4936                  "when compiling with -Os/-Oz");
4937     LLVM_DEBUG(
4938         dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4939     return None;
4940   }
4941 
4942   return MaxVF;
4943 }
4944 
4945 unsigned
4946 LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
4947                                                  unsigned ConstTripCount) {
4948   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4949   unsigned SmallestType, WidestType;
4950   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4951   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4952 
4953   // Get the maximum safe dependence distance in bits computed by LAA.
4954   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4955   // the memory accesses that is most restrictive (involved in the smallest
4956   // dependence distance).
4957   unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
4958 
4959   WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
4960 
4961   unsigned MaxVectorSize = WidestRegister / WidestType;
4962 
4963   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
4964                     << " / " << WidestType << " bits.\n");
4965   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
4966                     << WidestRegister << " bits.\n");
4967 
4968   assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"
4969                                  " into one vector!");
4970   if (MaxVectorSize == 0) {
4971     LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4972     MaxVectorSize = 1;
4973     return MaxVectorSize;
4974   } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
4975              isPowerOf2_32(ConstTripCount)) {
4976     // We need to clamp the VF to be the ConstTripCount. There is no point in
4977     // choosing a higher viable VF as done in the loop below.
4978     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
4979                       << ConstTripCount << "\n");
4980     MaxVectorSize = ConstTripCount;
4981     return MaxVectorSize;
4982   }
4983 
4984   unsigned MaxVF = MaxVectorSize;
4985   if (TTI.shouldMaximizeVectorBandwidth(OptForSize) ||
4986       (MaximizeBandwidth && !OptForSize)) {
4987     // Collect all viable vectorization factors larger than the default MaxVF
4988     // (i.e. MaxVectorSize).
4989     SmallVector<unsigned, 8> VFs;
4990     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
4991     for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
4992       VFs.push_back(VS);
4993 
4994     // For each VF calculate its register usage.
4995     auto RUs = calculateRegisterUsage(VFs);
4996 
4997     // Select the largest VF which doesn't require more registers than existing
4998     // ones.
4999     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
5000     for (int i = RUs.size() - 1; i >= 0; --i) {
5001       if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
5002         MaxVF = VFs[i];
5003         break;
5004       }
5005     }
5006     if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
5007       if (MaxVF < MinVF) {
5008         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5009                           << ") with target's minimum: " << MinVF << '\n');
5010         MaxVF = MinVF;
5011       }
5012     }
5013   }
5014   return MaxVF;
5015 }
5016 
5017 VectorizationFactor
5018 LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
5019   float Cost = expectedCost(1).first;
5020   const float ScalarCost = Cost;
5021   unsigned Width = 1;
5022   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5023 
5024   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5025   if (ForceVectorization && MaxVF > 1) {
5026     // Ignore scalar width, because the user explicitly wants vectorization.
5027     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5028     // evaluation.
5029     Cost = std::numeric_limits<float>::max();
5030   }
5031 
5032   for (unsigned i = 2; i <= MaxVF; i *= 2) {
5033     // Notice that the vector loop needs to be executed less times, so
5034     // we need to divide the cost of the vector loops by the width of
5035     // the vector elements.
5036     VectorizationCostTy C = expectedCost(i);
5037     float VectorCost = C.first / (float)i;
5038     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5039                       << " costs: " << (int)VectorCost << ".\n");
5040     if (!C.second && !ForceVectorization) {
5041       LLVM_DEBUG(
5042           dbgs() << "LV: Not considering vector loop of width " << i
5043                  << " because it will not generate any vector instructions.\n");
5044       continue;
5045     }
5046     if (VectorCost < Cost) {
5047       Cost = VectorCost;
5048       Width = i;
5049     }
5050   }
5051 
5052   if (!EnableCondStoresVectorization && NumPredStores) {
5053     ORE->emit(createMissedAnalysis("ConditionalStore")
5054               << "store that is conditionally executed prevents vectorization");
5055     LLVM_DEBUG(
5056         dbgs() << "LV: No vectorization. There are conditional stores.\n");
5057     Width = 1;
5058     Cost = ScalarCost;
5059   }
5060 
5061   LLVM_DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5062              << "LV: Vectorization seems to be not beneficial, "
5063              << "but was forced by a user.\n");
5064   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
5065   VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
5066   return Factor;
5067 }
5068 
5069 std::pair<unsigned, unsigned>
5070 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5071   unsigned MinWidth = -1U;
5072   unsigned MaxWidth = 8;
5073   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5074 
5075   // For each block.
5076   for (BasicBlock *BB : TheLoop->blocks()) {
5077     // For each instruction in the loop.
5078     for (Instruction &I : *BB) {
5079       Type *T = I.getType();
5080 
5081       // Skip ignored values.
5082       if (ValuesToIgnore.count(&I))
5083         continue;
5084 
5085       // Only examine Loads, Stores and PHINodes.
5086       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5087         continue;
5088 
5089       // Examine PHI nodes that are reduction variables. Update the type to
5090       // account for the recurrence type.
5091       if (auto *PN = dyn_cast<PHINode>(&I)) {
5092         if (!Legal->isReductionVariable(PN))
5093           continue;
5094         RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
5095         T = RdxDesc.getRecurrenceType();
5096       }
5097 
5098       // Examine the stored values.
5099       if (auto *ST = dyn_cast<StoreInst>(&I))
5100         T = ST->getValueOperand()->getType();
5101 
5102       // Ignore loaded pointer types and stored pointer types that are not
5103       // vectorizable.
5104       //
5105       // FIXME: The check here attempts to predict whether a load or store will
5106       //        be vectorized. We only know this for certain after a VF has
5107       //        been selected. Here, we assume that if an access can be
5108       //        vectorized, it will be. We should also look at extending this
5109       //        optimization to non-pointer types.
5110       //
5111       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
5112           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
5113         continue;
5114 
5115       MinWidth = std::min(MinWidth,
5116                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5117       MaxWidth = std::max(MaxWidth,
5118                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5119     }
5120   }
5121 
5122   return {MinWidth, MaxWidth};
5123 }
5124 
5125 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
5126                                                            unsigned VF,
5127                                                            unsigned LoopCost) {
5128   // -- The interleave heuristics --
5129   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5130   // There are many micro-architectural considerations that we can't predict
5131   // at this level. For example, frontend pressure (on decode or fetch) due to
5132   // code size, or the number and capabilities of the execution ports.
5133   //
5134   // We use the following heuristics to select the interleave count:
5135   // 1. If the code has reductions, then we interleave to break the cross
5136   // iteration dependency.
5137   // 2. If the loop is really small, then we interleave to reduce the loop
5138   // overhead.
5139   // 3. We don't interleave if we think that we will spill registers to memory
5140   // due to the increased register pressure.
5141 
5142   // When we optimize for size, we don't interleave.
5143   if (OptForSize)
5144     return 1;
5145 
5146   // We used the distance for the interleave count.
5147   if (Legal->getMaxSafeDepDistBytes() != -1U)
5148     return 1;
5149 
5150   // Do not interleave loops with a relatively small trip count.
5151   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5152   if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
5153     return 1;
5154 
5155   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5156   LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5157                     << " registers\n");
5158 
5159   if (VF == 1) {
5160     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5161       TargetNumRegisters = ForceTargetNumScalarRegs;
5162   } else {
5163     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5164       TargetNumRegisters = ForceTargetNumVectorRegs;
5165   }
5166 
5167   RegisterUsage R = calculateRegisterUsage({VF})[0];
5168   // We divide by these constants so assume that we have at least one
5169   // instruction that uses at least one register.
5170   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5171 
5172   // We calculate the interleave count using the following formula.
5173   // Subtract the number of loop invariants from the number of available
5174   // registers. These registers are used by all of the interleaved instances.
5175   // Next, divide the remaining registers by the number of registers that is
5176   // required by the loop, in order to estimate how many parallel instances
5177   // fit without causing spills. All of this is rounded down if necessary to be
5178   // a power of two. We want power of two interleave count to simplify any
5179   // addressing operations or alignment considerations.
5180   unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5181                               R.MaxLocalUsers);
5182 
5183   // Don't count the induction variable as interleaved.
5184   if (EnableIndVarRegisterHeur)
5185     IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5186                        std::max(1U, (R.MaxLocalUsers - 1)));
5187 
5188   // Clamp the interleave ranges to reasonable counts.
5189   unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
5190 
5191   // Check if the user has overridden the max.
5192   if (VF == 1) {
5193     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5194       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5195   } else {
5196     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5197       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5198   }
5199 
5200   // If we did not calculate the cost for VF (because the user selected the VF)
5201   // then we calculate the cost of VF here.
5202   if (LoopCost == 0)
5203     LoopCost = expectedCost(VF).first;
5204 
5205   // Clamp the calculated IC to be between the 1 and the max interleave count
5206   // that the target allows.
5207   if (IC > MaxInterleaveCount)
5208     IC = MaxInterleaveCount;
5209   else if (IC < 1)
5210     IC = 1;
5211 
5212   // Interleave if we vectorized this loop and there is a reduction that could
5213   // benefit from interleaving.
5214   if (VF > 1 && !Legal->getReductionVars()->empty()) {
5215     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5216     return IC;
5217   }
5218 
5219   // Note that if we've already vectorized the loop we will have done the
5220   // runtime check and so interleaving won't require further checks.
5221   bool InterleavingRequiresRuntimePointerCheck =
5222       (VF == 1 && Legal->getRuntimePointerChecking()->Need);
5223 
5224   // We want to interleave small loops in order to reduce the loop overhead and
5225   // potentially expose ILP opportunities.
5226   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5227   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
5228     // We assume that the cost overhead is 1 and we use the cost model
5229     // to estimate the cost of the loop and interleave until the cost of the
5230     // loop overhead is about 5% of the cost of the loop.
5231     unsigned SmallIC =
5232         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5233 
5234     // Interleave until store/load ports (estimated by max interleave count) are
5235     // saturated.
5236     unsigned NumStores = Legal->getNumStores();
5237     unsigned NumLoads = Legal->getNumLoads();
5238     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5239     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5240 
5241     // If we have a scalar reduction (vector reductions are already dealt with
5242     // by this point), we can increase the critical path length if the loop
5243     // we're interleaving is inside another loop. Limit, by default to 2, so the
5244     // critical path only gets increased by one reduction operation.
5245     if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) {
5246       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5247       SmallIC = std::min(SmallIC, F);
5248       StoresIC = std::min(StoresIC, F);
5249       LoadsIC = std::min(LoadsIC, F);
5250     }
5251 
5252     if (EnableLoadStoreRuntimeInterleave &&
5253         std::max(StoresIC, LoadsIC) > SmallIC) {
5254       LLVM_DEBUG(
5255           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5256       return std::max(StoresIC, LoadsIC);
5257     }
5258 
5259     LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5260     return SmallIC;
5261   }
5262 
5263   // Interleave if this is a large loop (small loops are already dealt with by
5264   // this point) that could benefit from interleaving.
5265   bool HasReductions = !Legal->getReductionVars()->empty();
5266   if (TTI.enableAggressiveInterleaving(HasReductions)) {
5267     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5268     return IC;
5269   }
5270 
5271   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5272   return 1;
5273 }
5274 
5275 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5276 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
5277   // This function calculates the register usage by measuring the highest number
5278   // of values that are alive at a single location. Obviously, this is a very
5279   // rough estimation. We scan the loop in a topological order in order and
5280   // assign a number to each instruction. We use RPO to ensure that defs are
5281   // met before their users. We assume that each instruction that has in-loop
5282   // users starts an interval. We record every time that an in-loop value is
5283   // used, so we have a list of the first and last occurrences of each
5284   // instruction. Next, we transpose this data structure into a multi map that
5285   // holds the list of intervals that *end* at a specific location. This multi
5286   // map allows us to perform a linear search. We scan the instructions linearly
5287   // and record each time that a new interval starts, by placing it in a set.
5288   // If we find this value in the multi-map then we remove it from the set.
5289   // The max register usage is the maximum size of the set.
5290   // We also search for instructions that are defined outside the loop, but are
5291   // used inside the loop. We need this number separately from the max-interval
5292   // usage number because when we unroll, loop-invariant values do not take
5293   // more register.
5294   LoopBlocksDFS DFS(TheLoop);
5295   DFS.perform(LI);
5296 
5297   RegisterUsage RU;
5298 
5299   // Each 'key' in the map opens a new interval. The values
5300   // of the map are the index of the 'last seen' usage of the
5301   // instruction that is the key.
5302   using IntervalMap = DenseMap<Instruction *, unsigned>;
5303 
5304   // Maps instruction to its index.
5305   DenseMap<unsigned, Instruction *> IdxToInstr;
5306   // Marks the end of each interval.
5307   IntervalMap EndPoint;
5308   // Saves the list of instruction indices that are used in the loop.
5309   SmallPtrSet<Instruction *, 8> Ends;
5310   // Saves the list of values that are used in the loop but are
5311   // defined outside the loop, such as arguments and constants.
5312   SmallPtrSet<Value *, 8> LoopInvariants;
5313 
5314   unsigned Index = 0;
5315   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5316     for (Instruction &I : *BB) {
5317       IdxToInstr[Index++] = &I;
5318 
5319       // Save the end location of each USE.
5320       for (Value *U : I.operands()) {
5321         auto *Instr = dyn_cast<Instruction>(U);
5322 
5323         // Ignore non-instruction values such as arguments, constants, etc.
5324         if (!Instr)
5325           continue;
5326 
5327         // If this instruction is outside the loop then record it and continue.
5328         if (!TheLoop->contains(Instr)) {
5329           LoopInvariants.insert(Instr);
5330           continue;
5331         }
5332 
5333         // Overwrite previous end points.
5334         EndPoint[Instr] = Index;
5335         Ends.insert(Instr);
5336       }
5337     }
5338   }
5339 
5340   // Saves the list of intervals that end with the index in 'key'.
5341   using InstrList = SmallVector<Instruction *, 2>;
5342   DenseMap<unsigned, InstrList> TransposeEnds;
5343 
5344   // Transpose the EndPoints to a list of values that end at each index.
5345   for (auto &Interval : EndPoint)
5346     TransposeEnds[Interval.second].push_back(Interval.first);
5347 
5348   SmallPtrSet<Instruction *, 8> OpenIntervals;
5349 
5350   // Get the size of the widest register.
5351   unsigned MaxSafeDepDist = -1U;
5352   if (Legal->getMaxSafeDepDistBytes() != -1U)
5353     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5354   unsigned WidestRegister =
5355       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
5356   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5357 
5358   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5359   SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
5360 
5361   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5362 
5363   // A lambda that gets the register usage for the given type and VF.
5364   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
5365     if (Ty->isTokenTy())
5366       return 0U;
5367     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5368     return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5369   };
5370 
5371   for (unsigned int i = 0; i < Index; ++i) {
5372     Instruction *I = IdxToInstr[i];
5373 
5374     // Remove all of the instructions that end at this location.
5375     InstrList &List = TransposeEnds[i];
5376     for (Instruction *ToRemove : List)
5377       OpenIntervals.erase(ToRemove);
5378 
5379     // Ignore instructions that are never used within the loop.
5380     if (!Ends.count(I))
5381       continue;
5382 
5383     // Skip ignored values.
5384     if (ValuesToIgnore.count(I))
5385       continue;
5386 
5387     // For each VF find the maximum usage of registers.
5388     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5389       if (VFs[j] == 1) {
5390         MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
5391         continue;
5392       }
5393       collectUniformsAndScalars(VFs[j]);
5394       // Count the number of live intervals.
5395       unsigned RegUsage = 0;
5396       for (auto Inst : OpenIntervals) {
5397         // Skip ignored values for VF > 1.
5398         if (VecValuesToIgnore.count(Inst) ||
5399             isScalarAfterVectorization(Inst, VFs[j]))
5400           continue;
5401         RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
5402       }
5403       MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
5404     }
5405 
5406     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
5407                       << OpenIntervals.size() << '\n');
5408 
5409     // Add the current instruction to the list of open intervals.
5410     OpenIntervals.insert(I);
5411   }
5412 
5413   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
5414     unsigned Invariant = 0;
5415     if (VFs[i] == 1)
5416       Invariant = LoopInvariants.size();
5417     else {
5418       for (auto Inst : LoopInvariants)
5419         Invariant += GetRegUsage(Inst->getType(), VFs[i]);
5420     }
5421 
5422     LLVM_DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
5423     LLVM_DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
5424     LLVM_DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant
5425                       << '\n');
5426 
5427     RU.LoopInvariantRegs = Invariant;
5428     RU.MaxLocalUsers = MaxUsages[i];
5429     RUs[i] = RU;
5430   }
5431 
5432   return RUs;
5433 }
5434 
5435 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
5436   // TODO: Cost model for emulated masked load/store is completely
5437   // broken. This hack guides the cost model to use an artificially
5438   // high enough value to practically disable vectorization with such
5439   // operations, except where previously deployed legality hack allowed
5440   // using very low cost values. This is to avoid regressions coming simply
5441   // from moving "masked load/store" check from legality to cost model.
5442   // Masked Load/Gather emulation was previously never allowed.
5443   // Limited number of Masked Store/Scatter emulation was allowed.
5444   assert(isScalarWithPredication(I) &&
5445          "Expecting a scalar emulated instruction");
5446   return isa<LoadInst>(I) ||
5447          (isa<StoreInst>(I) &&
5448           NumPredStores > NumberOfStoresToPredicate);
5449 }
5450 
5451 void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
5452   // If we aren't vectorizing the loop, or if we've already collected the
5453   // instructions to scalarize, there's nothing to do. Collection may already
5454   // have occurred if we have a user-selected VF and are now computing the
5455   // expected cost for interleaving.
5456   if (VF < 2 || InstsToScalarize.count(VF))
5457     return;
5458 
5459   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
5460   // not profitable to scalarize any instructions, the presence of VF in the
5461   // map will indicate that we've analyzed it already.
5462   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
5463 
5464   // Find all the instructions that are scalar with predication in the loop and
5465   // determine if it would be better to not if-convert the blocks they are in.
5466   // If so, we also record the instructions to scalarize.
5467   for (BasicBlock *BB : TheLoop->blocks()) {
5468     if (!Legal->blockNeedsPredication(BB))
5469       continue;
5470     for (Instruction &I : *BB)
5471       if (isScalarWithPredication(&I)) {
5472         ScalarCostsTy ScalarCosts;
5473         // Do not apply discount logic if hacked cost is needed
5474         // for emulated masked memrefs.
5475         if (!useEmulatedMaskMemRefHack(&I) &&
5476             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
5477           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
5478         // Remember that BB will remain after vectorization.
5479         PredicatedBBsAfterVectorization.insert(BB);
5480       }
5481   }
5482 }
5483 
5484 int LoopVectorizationCostModel::computePredInstDiscount(
5485     Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
5486     unsigned VF) {
5487   assert(!isUniformAfterVectorization(PredInst, VF) &&
5488          "Instruction marked uniform-after-vectorization will be predicated");
5489 
5490   // Initialize the discount to zero, meaning that the scalar version and the
5491   // vector version cost the same.
5492   int Discount = 0;
5493 
5494   // Holds instructions to analyze. The instructions we visit are mapped in
5495   // ScalarCosts. Those instructions are the ones that would be scalarized if
5496   // we find that the scalar version costs less.
5497   SmallVector<Instruction *, 8> Worklist;
5498 
5499   // Returns true if the given instruction can be scalarized.
5500   auto canBeScalarized = [&](Instruction *I) -> bool {
5501     // We only attempt to scalarize instructions forming a single-use chain
5502     // from the original predicated block that would otherwise be vectorized.
5503     // Although not strictly necessary, we give up on instructions we know will
5504     // already be scalar to avoid traversing chains that are unlikely to be
5505     // beneficial.
5506     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
5507         isScalarAfterVectorization(I, VF))
5508       return false;
5509 
5510     // If the instruction is scalar with predication, it will be analyzed
5511     // separately. We ignore it within the context of PredInst.
5512     if (isScalarWithPredication(I))
5513       return false;
5514 
5515     // If any of the instruction's operands are uniform after vectorization,
5516     // the instruction cannot be scalarized. This prevents, for example, a
5517     // masked load from being scalarized.
5518     //
5519     // We assume we will only emit a value for lane zero of an instruction
5520     // marked uniform after vectorization, rather than VF identical values.
5521     // Thus, if we scalarize an instruction that uses a uniform, we would
5522     // create uses of values corresponding to the lanes we aren't emitting code
5523     // for. This behavior can be changed by allowing getScalarValue to clone
5524     // the lane zero values for uniforms rather than asserting.
5525     for (Use &U : I->operands())
5526       if (auto *J = dyn_cast<Instruction>(U.get()))
5527         if (isUniformAfterVectorization(J, VF))
5528           return false;
5529 
5530     // Otherwise, we can scalarize the instruction.
5531     return true;
5532   };
5533 
5534   // Returns true if an operand that cannot be scalarized must be extracted
5535   // from a vector. We will account for this scalarization overhead below. Note
5536   // that the non-void predicated instructions are placed in their own blocks,
5537   // and their return values are inserted into vectors. Thus, an extract would
5538   // still be required.
5539   auto needsExtract = [&](Instruction *I) -> bool {
5540     return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
5541   };
5542 
5543   // Compute the expected cost discount from scalarizing the entire expression
5544   // feeding the predicated instruction. We currently only consider expressions
5545   // that are single-use instruction chains.
5546   Worklist.push_back(PredInst);
5547   while (!Worklist.empty()) {
5548     Instruction *I = Worklist.pop_back_val();
5549 
5550     // If we've already analyzed the instruction, there's nothing to do.
5551     if (ScalarCosts.count(I))
5552       continue;
5553 
5554     // Compute the cost of the vector instruction. Note that this cost already
5555     // includes the scalarization overhead of the predicated instruction.
5556     unsigned VectorCost = getInstructionCost(I, VF).first;
5557 
5558     // Compute the cost of the scalarized instruction. This cost is the cost of
5559     // the instruction as if it wasn't if-converted and instead remained in the
5560     // predicated block. We will scale this cost by block probability after
5561     // computing the scalarization overhead.
5562     unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
5563 
5564     // Compute the scalarization overhead of needed insertelement instructions
5565     // and phi nodes.
5566     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
5567       ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
5568                                                  true, false);
5569       ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
5570     }
5571 
5572     // Compute the scalarization overhead of needed extractelement
5573     // instructions. For each of the instruction's operands, if the operand can
5574     // be scalarized, add it to the worklist; otherwise, account for the
5575     // overhead.
5576     for (Use &U : I->operands())
5577       if (auto *J = dyn_cast<Instruction>(U.get())) {
5578         assert(VectorType::isValidElementType(J->getType()) &&
5579                "Instruction has non-scalar type");
5580         if (canBeScalarized(J))
5581           Worklist.push_back(J);
5582         else if (needsExtract(J))
5583           ScalarCost += TTI.getScalarizationOverhead(
5584                               ToVectorTy(J->getType(),VF), false, true);
5585       }
5586 
5587     // Scale the total scalar cost by block probability.
5588     ScalarCost /= getReciprocalPredBlockProb();
5589 
5590     // Compute the discount. A non-negative discount means the vector version
5591     // of the instruction costs more, and scalarizing would be beneficial.
5592     Discount += VectorCost - ScalarCost;
5593     ScalarCosts[I] = ScalarCost;
5594   }
5595 
5596   return Discount;
5597 }
5598 
5599 LoopVectorizationCostModel::VectorizationCostTy
5600 LoopVectorizationCostModel::expectedCost(unsigned VF) {
5601   VectorizationCostTy Cost;
5602 
5603   // For each block.
5604   for (BasicBlock *BB : TheLoop->blocks()) {
5605     VectorizationCostTy BlockCost;
5606 
5607     // For each instruction in the old loop.
5608     for (Instruction &I : BB->instructionsWithoutDebug()) {
5609       // Skip ignored values.
5610       if (ValuesToIgnore.count(&I) ||
5611           (VF > 1 && VecValuesToIgnore.count(&I)))
5612         continue;
5613 
5614       VectorizationCostTy C = getInstructionCost(&I, VF);
5615 
5616       // Check if we should override the cost.
5617       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5618         C.first = ForceTargetInstructionCost;
5619 
5620       BlockCost.first += C.first;
5621       BlockCost.second |= C.second;
5622       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
5623                         << " for VF " << VF << " For instruction: " << I
5624                         << '\n');
5625     }
5626 
5627     // If we are vectorizing a predicated block, it will have been
5628     // if-converted. This means that the block's instructions (aside from
5629     // stores and instructions that may divide by zero) will now be
5630     // unconditionally executed. For the scalar case, we may not always execute
5631     // the predicated block. Thus, scale the block's cost by the probability of
5632     // executing it.
5633     if (VF == 1 && Legal->blockNeedsPredication(BB))
5634       BlockCost.first /= getReciprocalPredBlockProb();
5635 
5636     Cost.first += BlockCost.first;
5637     Cost.second |= BlockCost.second;
5638   }
5639 
5640   return Cost;
5641 }
5642 
5643 /// Gets Address Access SCEV after verifying that the access pattern
5644 /// is loop invariant except the induction variable dependence.
5645 ///
5646 /// This SCEV can be sent to the Target in order to estimate the address
5647 /// calculation cost.
5648 static const SCEV *getAddressAccessSCEV(
5649               Value *Ptr,
5650               LoopVectorizationLegality *Legal,
5651               PredicatedScalarEvolution &PSE,
5652               const Loop *TheLoop) {
5653 
5654   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5655   if (!Gep)
5656     return nullptr;
5657 
5658   // We are looking for a gep with all loop invariant indices except for one
5659   // which should be an induction variable.
5660   auto SE = PSE.getSE();
5661   unsigned NumOperands = Gep->getNumOperands();
5662   for (unsigned i = 1; i < NumOperands; ++i) {
5663     Value *Opd = Gep->getOperand(i);
5664     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5665         !Legal->isInductionVariable(Opd))
5666       return nullptr;
5667   }
5668 
5669   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
5670   return PSE.getSCEV(Ptr);
5671 }
5672 
5673 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5674   return Legal->hasStride(I->getOperand(0)) ||
5675          Legal->hasStride(I->getOperand(1));
5676 }
5677 
5678 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
5679                                                                  unsigned VF) {
5680   Type *ValTy = getMemInstValueType(I);
5681   auto SE = PSE.getSE();
5682 
5683   unsigned Alignment = getMemInstAlignment(I);
5684   unsigned AS = getMemInstAddressSpace(I);
5685   Value *Ptr = getLoadStorePointerOperand(I);
5686   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5687 
5688   // Figure out whether the access is strided and get the stride value
5689   // if it's known in compile time
5690   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
5691 
5692   // Get the cost of the scalar memory instruction and address computation.
5693   unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
5694 
5695   Cost += VF *
5696           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
5697                               AS, I);
5698 
5699   // Get the overhead of the extractelement and insertelement instructions
5700   // we might create due to scalarization.
5701   Cost += getScalarizationOverhead(I, VF, TTI);
5702 
5703   // If we have a predicated store, it may not be executed for each vector
5704   // lane. Scale the cost by the probability of executing the predicated
5705   // block.
5706   if (isScalarWithPredication(I)) {
5707     Cost /= getReciprocalPredBlockProb();
5708 
5709     if (useEmulatedMaskMemRefHack(I))
5710       // Artificially setting to a high enough value to practically disable
5711       // vectorization with such operations.
5712       Cost = 3000000;
5713   }
5714 
5715   return Cost;
5716 }
5717 
5718 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
5719                                                              unsigned VF) {
5720   Type *ValTy = getMemInstValueType(I);
5721   Type *VectorTy = ToVectorTy(ValTy, VF);
5722   unsigned Alignment = getMemInstAlignment(I);
5723   Value *Ptr = getLoadStorePointerOperand(I);
5724   unsigned AS = getMemInstAddressSpace(I);
5725   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5726 
5727   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5728          "Stride should be 1 or -1 for consecutive memory access");
5729   unsigned Cost = 0;
5730   if (Legal->isMaskRequired(I))
5731     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5732   else
5733     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
5734 
5735   bool Reverse = ConsecutiveStride < 0;
5736   if (Reverse)
5737     Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5738   return Cost;
5739 }
5740 
5741 unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
5742                                                          unsigned VF) {
5743   LoadInst *LI = cast<LoadInst>(I);
5744   Type *ValTy = LI->getType();
5745   Type *VectorTy = ToVectorTy(ValTy, VF);
5746   unsigned Alignment = LI->getAlignment();
5747   unsigned AS = LI->getPointerAddressSpace();
5748 
5749   return TTI.getAddressComputationCost(ValTy) +
5750          TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
5751          TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
5752 }
5753 
5754 unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
5755                                                           unsigned VF) {
5756   Type *ValTy = getMemInstValueType(I);
5757   Type *VectorTy = ToVectorTy(ValTy, VF);
5758   unsigned Alignment = getMemInstAlignment(I);
5759   Value *Ptr = getLoadStorePointerOperand(I);
5760 
5761   return TTI.getAddressComputationCost(VectorTy) +
5762          TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
5763                                     Legal->isMaskRequired(I), Alignment);
5764 }
5765 
5766 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
5767                                                             unsigned VF) {
5768   Type *ValTy = getMemInstValueType(I);
5769   Type *VectorTy = ToVectorTy(ValTy, VF);
5770   unsigned AS = getMemInstAddressSpace(I);
5771 
5772   auto Group = getInterleavedAccessGroup(I);
5773   assert(Group && "Fail to get an interleaved access group.");
5774 
5775   unsigned InterleaveFactor = Group->getFactor();
5776   Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5777 
5778   // Holds the indices of existing members in an interleaved load group.
5779   // An interleaved store group doesn't need this as it doesn't allow gaps.
5780   SmallVector<unsigned, 4> Indices;
5781   if (isa<LoadInst>(I)) {
5782     for (unsigned i = 0; i < InterleaveFactor; i++)
5783       if (Group->getMember(i))
5784         Indices.push_back(i);
5785   }
5786 
5787   // Calculate the cost of the whole interleaved group.
5788   unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy,
5789                                                  Group->getFactor(), Indices,
5790                                                  Group->getAlignment(), AS);
5791 
5792   if (Group->isReverse())
5793     Cost += Group->getNumMembers() *
5794             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5795   return Cost;
5796 }
5797 
5798 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
5799                                                               unsigned VF) {
5800   // Calculate scalar cost only. Vectorization cost should be ready at this
5801   // moment.
5802   if (VF == 1) {
5803     Type *ValTy = getMemInstValueType(I);
5804     unsigned Alignment = getMemInstAlignment(I);
5805     unsigned AS = getMemInstAddressSpace(I);
5806 
5807     return TTI.getAddressComputationCost(ValTy) +
5808            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
5809   }
5810   return getWideningCost(I, VF);
5811 }
5812 
5813 LoopVectorizationCostModel::VectorizationCostTy
5814 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5815   // If we know that this instruction will remain uniform, check the cost of
5816   // the scalar version.
5817   if (isUniformAfterVectorization(I, VF))
5818     VF = 1;
5819 
5820   if (VF > 1 && isProfitableToScalarize(I, VF))
5821     return VectorizationCostTy(InstsToScalarize[VF][I], false);
5822 
5823   // Forced scalars do not have any scalarization overhead.
5824   if (VF > 1 && ForcedScalars.count(VF) &&
5825       ForcedScalars.find(VF)->second.count(I))
5826     return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false);
5827 
5828   Type *VectorTy;
5829   unsigned C = getInstructionCost(I, VF, VectorTy);
5830 
5831   bool TypeNotScalarized =
5832       VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF;
5833   return VectorizationCostTy(C, TypeNotScalarized);
5834 }
5835 
5836 void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
5837   if (VF == 1)
5838     return;
5839   NumPredStores = 0;
5840   for (BasicBlock *BB : TheLoop->blocks()) {
5841     // For each instruction in the old loop.
5842     for (Instruction &I : *BB) {
5843       Value *Ptr =  getLoadStorePointerOperand(&I);
5844       if (!Ptr)
5845         continue;
5846 
5847       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
5848         NumPredStores++;
5849       if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
5850         // Scalar load + broadcast
5851         unsigned Cost = getUniformMemOpCost(&I, VF);
5852         setWideningDecision(&I, VF, CM_Scalarize, Cost);
5853         continue;
5854       }
5855 
5856       // We assume that widening is the best solution when possible.
5857       if (memoryInstructionCanBeWidened(&I, VF)) {
5858         unsigned Cost = getConsecutiveMemOpCost(&I, VF);
5859         int ConsecutiveStride =
5860                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
5861         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5862                "Expected consecutive stride.");
5863         InstWidening Decision =
5864             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
5865         setWideningDecision(&I, VF, Decision, Cost);
5866         continue;
5867       }
5868 
5869       // Choose between Interleaving, Gather/Scatter or Scalarization.
5870       unsigned InterleaveCost = std::numeric_limits<unsigned>::max();
5871       unsigned NumAccesses = 1;
5872       if (isAccessInterleaved(&I)) {
5873         auto Group = getInterleavedAccessGroup(&I);
5874         assert(Group && "Fail to get an interleaved access group.");
5875 
5876         // Make one decision for the whole group.
5877         if (getWideningDecision(&I, VF) != CM_Unknown)
5878           continue;
5879 
5880         NumAccesses = Group->getNumMembers();
5881         InterleaveCost = getInterleaveGroupCost(&I, VF);
5882       }
5883 
5884       unsigned GatherScatterCost =
5885           isLegalGatherOrScatter(&I)
5886               ? getGatherScatterCost(&I, VF) * NumAccesses
5887               : std::numeric_limits<unsigned>::max();
5888 
5889       unsigned ScalarizationCost =
5890           getMemInstScalarizationCost(&I, VF) * NumAccesses;
5891 
5892       // Choose better solution for the current VF,
5893       // write down this decision and use it during vectorization.
5894       unsigned Cost;
5895       InstWidening Decision;
5896       if (InterleaveCost <= GatherScatterCost &&
5897           InterleaveCost < ScalarizationCost) {
5898         Decision = CM_Interleave;
5899         Cost = InterleaveCost;
5900       } else if (GatherScatterCost < ScalarizationCost) {
5901         Decision = CM_GatherScatter;
5902         Cost = GatherScatterCost;
5903       } else {
5904         Decision = CM_Scalarize;
5905         Cost = ScalarizationCost;
5906       }
5907       // If the instructions belongs to an interleave group, the whole group
5908       // receives the same decision. The whole group receives the cost, but
5909       // the cost will actually be assigned to one instruction.
5910       if (auto Group = getInterleavedAccessGroup(&I))
5911         setWideningDecision(Group, VF, Decision, Cost);
5912       else
5913         setWideningDecision(&I, VF, Decision, Cost);
5914     }
5915   }
5916 
5917   // Make sure that any load of address and any other address computation
5918   // remains scalar unless there is gather/scatter support. This avoids
5919   // inevitable extracts into address registers, and also has the benefit of
5920   // activating LSR more, since that pass can't optimize vectorized
5921   // addresses.
5922   if (TTI.prefersVectorizedAddressing())
5923     return;
5924 
5925   // Start with all scalar pointer uses.
5926   SmallPtrSet<Instruction *, 8> AddrDefs;
5927   for (BasicBlock *BB : TheLoop->blocks())
5928     for (Instruction &I : *BB) {
5929       Instruction *PtrDef =
5930         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
5931       if (PtrDef && TheLoop->contains(PtrDef) &&
5932           getWideningDecision(&I, VF) != CM_GatherScatter)
5933         AddrDefs.insert(PtrDef);
5934     }
5935 
5936   // Add all instructions used to generate the addresses.
5937   SmallVector<Instruction *, 4> Worklist;
5938   for (auto *I : AddrDefs)
5939     Worklist.push_back(I);
5940   while (!Worklist.empty()) {
5941     Instruction *I = Worklist.pop_back_val();
5942     for (auto &Op : I->operands())
5943       if (auto *InstOp = dyn_cast<Instruction>(Op))
5944         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
5945             AddrDefs.insert(InstOp).second)
5946           Worklist.push_back(InstOp);
5947   }
5948 
5949   for (auto *I : AddrDefs) {
5950     if (isa<LoadInst>(I)) {
5951       // Setting the desired widening decision should ideally be handled in
5952       // by cost functions, but since this involves the task of finding out
5953       // if the loaded register is involved in an address computation, it is
5954       // instead changed here when we know this is the case.
5955       InstWidening Decision = getWideningDecision(I, VF);
5956       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
5957         // Scalarize a widened load of address.
5958         setWideningDecision(I, VF, CM_Scalarize,
5959                             (VF * getMemoryInstructionCost(I, 1)));
5960       else if (auto Group = getInterleavedAccessGroup(I)) {
5961         // Scalarize an interleave group of address loads.
5962         for (unsigned I = 0; I < Group->getFactor(); ++I) {
5963           if (Instruction *Member = Group->getMember(I))
5964             setWideningDecision(Member, VF, CM_Scalarize,
5965                                 (VF * getMemoryInstructionCost(Member, 1)));
5966         }
5967       }
5968     } else
5969       // Make sure I gets scalarized and a cost estimate without
5970       // scalarization overhead.
5971       ForcedScalars[VF].insert(I);
5972   }
5973 }
5974 
5975 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
5976                                                         unsigned VF,
5977                                                         Type *&VectorTy) {
5978   Type *RetTy = I->getType();
5979   if (canTruncateToMinimalBitwidth(I, VF))
5980     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
5981   VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
5982   auto SE = PSE.getSE();
5983 
5984   // TODO: We need to estimate the cost of intrinsic calls.
5985   switch (I->getOpcode()) {
5986   case Instruction::GetElementPtr:
5987     // We mark this instruction as zero-cost because the cost of GEPs in
5988     // vectorized code depends on whether the corresponding memory instruction
5989     // is scalarized or not. Therefore, we handle GEPs with the memory
5990     // instruction cost.
5991     return 0;
5992   case Instruction::Br: {
5993     // In cases of scalarized and predicated instructions, there will be VF
5994     // predicated blocks in the vectorized loop. Each branch around these
5995     // blocks requires also an extract of its vector compare i1 element.
5996     bool ScalarPredicatedBB = false;
5997     BranchInst *BI = cast<BranchInst>(I);
5998     if (VF > 1 && BI->isConditional() &&
5999         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
6000          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
6001       ScalarPredicatedBB = true;
6002 
6003     if (ScalarPredicatedBB) {
6004       // Return cost for branches around scalarized and predicated blocks.
6005       Type *Vec_i1Ty =
6006           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
6007       return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
6008               (TTI.getCFInstrCost(Instruction::Br) * VF));
6009     } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
6010       // The back-edge branch will remain, as will all scalar branches.
6011       return TTI.getCFInstrCost(Instruction::Br);
6012     else
6013       // This branch will be eliminated by if-conversion.
6014       return 0;
6015     // Note: We currently assume zero cost for an unconditional branch inside
6016     // a predicated block since it will become a fall-through, although we
6017     // may decide in the future to call TTI for all branches.
6018   }
6019   case Instruction::PHI: {
6020     auto *Phi = cast<PHINode>(I);
6021 
6022     // First-order recurrences are replaced by vector shuffles inside the loop.
6023     if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
6024       return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
6025                                 VectorTy, VF - 1, VectorTy);
6026 
6027     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
6028     // converted into select instructions. We require N - 1 selects per phi
6029     // node, where N is the number of incoming values.
6030     if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
6031       return (Phi->getNumIncomingValues() - 1) *
6032              TTI.getCmpSelInstrCost(
6033                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
6034                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF));
6035 
6036     return TTI.getCFInstrCost(Instruction::PHI);
6037   }
6038   case Instruction::UDiv:
6039   case Instruction::SDiv:
6040   case Instruction::URem:
6041   case Instruction::SRem:
6042     // If we have a predicated instruction, it may not be executed for each
6043     // vector lane. Get the scalarization cost and scale this amount by the
6044     // probability of executing the predicated block. If the instruction is not
6045     // predicated, we fall through to the next case.
6046     if (VF > 1 && isScalarWithPredication(I)) {
6047       unsigned Cost = 0;
6048 
6049       // These instructions have a non-void type, so account for the phi nodes
6050       // that we will create. This cost is likely to be zero. The phi node
6051       // cost, if any, should be scaled by the block probability because it
6052       // models a copy at the end of each predicated block.
6053       Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
6054 
6055       // The cost of the non-predicated instruction.
6056       Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
6057 
6058       // The cost of insertelement and extractelement instructions needed for
6059       // scalarization.
6060       Cost += getScalarizationOverhead(I, VF, TTI);
6061 
6062       // Scale the cost by the probability of executing the predicated blocks.
6063       // This assumes the predicated block for each vector lane is equally
6064       // likely.
6065       return Cost / getReciprocalPredBlockProb();
6066     }
6067     LLVM_FALLTHROUGH;
6068   case Instruction::Add:
6069   case Instruction::FAdd:
6070   case Instruction::Sub:
6071   case Instruction::FSub:
6072   case Instruction::Mul:
6073   case Instruction::FMul:
6074   case Instruction::FDiv:
6075   case Instruction::FRem:
6076   case Instruction::Shl:
6077   case Instruction::LShr:
6078   case Instruction::AShr:
6079   case Instruction::And:
6080   case Instruction::Or:
6081   case Instruction::Xor: {
6082     // Since we will replace the stride by 1 the multiplication should go away.
6083     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
6084       return 0;
6085     // Certain instructions can be cheaper to vectorize if they have a constant
6086     // second vector operand. One example of this are shifts on x86.
6087     TargetTransformInfo::OperandValueKind Op1VK =
6088         TargetTransformInfo::OK_AnyValue;
6089     TargetTransformInfo::OperandValueKind Op2VK =
6090         TargetTransformInfo::OK_AnyValue;
6091     TargetTransformInfo::OperandValueProperties Op1VP =
6092         TargetTransformInfo::OP_None;
6093     TargetTransformInfo::OperandValueProperties Op2VP =
6094         TargetTransformInfo::OP_None;
6095     Value *Op2 = I->getOperand(1);
6096 
6097     // Check for a splat or for a non uniform vector of constants.
6098     if (isa<ConstantInt>(Op2)) {
6099       ConstantInt *CInt = cast<ConstantInt>(Op2);
6100       if (CInt && CInt->getValue().isPowerOf2())
6101         Op2VP = TargetTransformInfo::OP_PowerOf2;
6102       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
6103     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
6104       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6105       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
6106       if (SplatValue) {
6107         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
6108         if (CInt && CInt->getValue().isPowerOf2())
6109           Op2VP = TargetTransformInfo::OP_PowerOf2;
6110         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
6111       }
6112     } else if (Legal->isUniform(Op2)) {
6113       Op2VK = TargetTransformInfo::OK_UniformValue;
6114     }
6115     SmallVector<const Value *, 4> Operands(I->operand_values());
6116     unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
6117     return N * TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK,
6118                                           Op2VK, Op1VP, Op2VP, Operands);
6119   }
6120   case Instruction::Select: {
6121     SelectInst *SI = cast<SelectInst>(I);
6122     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6123     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6124     Type *CondTy = SI->getCondition()->getType();
6125     if (!ScalarCond)
6126       CondTy = VectorType::get(CondTy, VF);
6127 
6128     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
6129   }
6130   case Instruction::ICmp:
6131   case Instruction::FCmp: {
6132     Type *ValTy = I->getOperand(0)->getType();
6133     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6134     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6135       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
6136     VectorTy = ToVectorTy(ValTy, VF);
6137     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
6138   }
6139   case Instruction::Store:
6140   case Instruction::Load: {
6141     unsigned Width = VF;
6142     if (Width > 1) {
6143       InstWidening Decision = getWideningDecision(I, Width);
6144       assert(Decision != CM_Unknown &&
6145              "CM decision should be taken at this point");
6146       if (Decision == CM_Scalarize)
6147         Width = 1;
6148     }
6149     VectorTy = ToVectorTy(getMemInstValueType(I), Width);
6150     return getMemoryInstructionCost(I, VF);
6151   }
6152   case Instruction::ZExt:
6153   case Instruction::SExt:
6154   case Instruction::FPToUI:
6155   case Instruction::FPToSI:
6156   case Instruction::FPExt:
6157   case Instruction::PtrToInt:
6158   case Instruction::IntToPtr:
6159   case Instruction::SIToFP:
6160   case Instruction::UIToFP:
6161   case Instruction::Trunc:
6162   case Instruction::FPTrunc:
6163   case Instruction::BitCast: {
6164     // We optimize the truncation of induction variables having constant
6165     // integer steps. The cost of these truncations is the same as the scalar
6166     // operation.
6167     if (isOptimizableIVTruncate(I, VF)) {
6168       auto *Trunc = cast<TruncInst>(I);
6169       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
6170                                   Trunc->getSrcTy(), Trunc);
6171     }
6172 
6173     Type *SrcScalarTy = I->getOperand(0)->getType();
6174     Type *SrcVecTy =
6175         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
6176     if (canTruncateToMinimalBitwidth(I, VF)) {
6177       // This cast is going to be shrunk. This may remove the cast or it might
6178       // turn it into slightly different cast. For example, if MinBW == 16,
6179       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
6180       //
6181       // Calculate the modified src and dest types.
6182       Type *MinVecTy = VectorTy;
6183       if (I->getOpcode() == Instruction::Trunc) {
6184         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
6185         VectorTy =
6186             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6187       } else if (I->getOpcode() == Instruction::ZExt ||
6188                  I->getOpcode() == Instruction::SExt) {
6189         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
6190         VectorTy =
6191             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6192       }
6193     }
6194 
6195     unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
6196     return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
6197   }
6198   case Instruction::Call: {
6199     bool NeedToScalarize;
6200     CallInst *CI = cast<CallInst>(I);
6201     unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
6202     if (getVectorIntrinsicIDForCall(CI, TLI))
6203       return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
6204     return CallCost;
6205   }
6206   default:
6207     // The cost of executing VF copies of the scalar instruction. This opcode
6208     // is unknown. Assume that it is the same as 'mul'.
6209     return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
6210            getScalarizationOverhead(I, VF, TTI);
6211   } // end of switch.
6212 }
6213 
6214 char LoopVectorize::ID = 0;
6215 
6216 static const char lv_name[] = "Loop Vectorization";
6217 
6218 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
6219 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6220 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
6221 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6222 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
6223 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6224 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
6225 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6226 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6227 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
6228 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
6229 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
6230 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
6231 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
6232 
6233 namespace llvm {
6234 
6235 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
6236   return new LoopVectorize(NoUnrolling, AlwaysVectorize);
6237 }
6238 
6239 } // end namespace llvm
6240 
6241 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
6242   // Check if the pointer operand of a load or store instruction is
6243   // consecutive.
6244   if (auto *Ptr = getLoadStorePointerOperand(Inst))
6245     return Legal->isConsecutivePtr(Ptr);
6246   return false;
6247 }
6248 
6249 void LoopVectorizationCostModel::collectValuesToIgnore() {
6250   // Ignore ephemeral values.
6251   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
6252 
6253   // Ignore type-promoting instructions we identified during reduction
6254   // detection.
6255   for (auto &Reduction : *Legal->getReductionVars()) {
6256     RecurrenceDescriptor &RedDes = Reduction.second;
6257     SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6258     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
6259   }
6260   // Ignore type-casting instructions we identified during induction
6261   // detection.
6262   for (auto &Induction : *Legal->getInductionVars()) {
6263     InductionDescriptor &IndDes = Induction.second;
6264     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
6265     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
6266   }
6267 }
6268 
6269 VectorizationFactor
6270 LoopVectorizationPlanner::planInVPlanNativePath(bool OptForSize,
6271                                                 unsigned UserVF) {
6272   // Width 1 means no vectorization, cost 0 means uncomputed cost.
6273   const VectorizationFactor NoVectorization = {1U, 0U};
6274 
6275   // Outer loop handling: They may require CFG and instruction level
6276   // transformations before even evaluating whether vectorization is profitable.
6277   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
6278   // the vectorization pipeline.
6279   if (!OrigLoop->empty()) {
6280     // TODO: If UserVF is not provided, we set UserVF to 4 for stress testing.
6281     // This won't be necessary when UserVF is not required in the VPlan-native
6282     // path.
6283     if (VPlanBuildStressTest && !UserVF)
6284       UserVF = 4;
6285 
6286     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
6287     assert(UserVF && "Expected UserVF for outer loop vectorization.");
6288     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
6289     LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
6290     buildVPlans(UserVF, UserVF);
6291 
6292     // For VPlan build stress testing, we bail out after VPlan construction.
6293     if (VPlanBuildStressTest)
6294       return NoVectorization;
6295 
6296     return {UserVF, 0};
6297   }
6298 
6299   LLVM_DEBUG(
6300       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
6301                 "VPlan-native path.\n");
6302   return NoVectorization;
6303 }
6304 
6305 VectorizationFactor
6306 LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) {
6307   assert(OrigLoop->empty() && "Inner loop expected.");
6308   // Width 1 means no vectorization, cost 0 means uncomputed cost.
6309   const VectorizationFactor NoVectorization = {1U, 0U};
6310   Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
6311   if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize.
6312     return NoVectorization;
6313 
6314   if (UserVF) {
6315     LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
6316     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
6317     // Collect the instructions (and their associated costs) that will be more
6318     // profitable to scalarize.
6319     CM.selectUserVectorizationFactor(UserVF);
6320     buildVPlansWithVPRecipes(UserVF, UserVF);
6321     LLVM_DEBUG(printPlans(dbgs()));
6322     return {UserVF, 0};
6323   }
6324 
6325   unsigned MaxVF = MaybeMaxVF.getValue();
6326   assert(MaxVF != 0 && "MaxVF is zero.");
6327 
6328   for (unsigned VF = 1; VF <= MaxVF; VF *= 2) {
6329     // Collect Uniform and Scalar instructions after vectorization with VF.
6330     CM.collectUniformsAndScalars(VF);
6331 
6332     // Collect the instructions (and their associated costs) that will be more
6333     // profitable to scalarize.
6334     if (VF > 1)
6335       CM.collectInstsToScalarize(VF);
6336   }
6337 
6338   buildVPlansWithVPRecipes(1, MaxVF);
6339   LLVM_DEBUG(printPlans(dbgs()));
6340   if (MaxVF == 1)
6341     return NoVectorization;
6342 
6343   // Select the optimal vectorization factor.
6344   return CM.selectVectorizationFactor(MaxVF);
6345 }
6346 
6347 void LoopVectorizationPlanner::setBestPlan(unsigned VF, unsigned UF) {
6348   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
6349                     << '\n');
6350   BestVF = VF;
6351   BestUF = UF;
6352 
6353   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
6354     return !Plan->hasVF(VF);
6355   });
6356   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
6357 }
6358 
6359 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
6360                                            DominatorTree *DT) {
6361   // Perform the actual loop transformation.
6362 
6363   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
6364   VPCallbackILV CallbackILV(ILV);
6365 
6366   VPTransformState State{BestVF, BestUF,      LI,
6367                          DT,     ILV.Builder, ILV.VectorLoopValueMap,
6368                          &ILV,   CallbackILV};
6369   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
6370 
6371   //===------------------------------------------------===//
6372   //
6373   // Notice: any optimization or new instruction that go
6374   // into the code below should also be implemented in
6375   // the cost-model.
6376   //
6377   //===------------------------------------------------===//
6378 
6379   // 2. Copy and widen instructions from the old loop into the new loop.
6380   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
6381   VPlans.front()->execute(&State);
6382 
6383   // 3. Fix the vectorized code: take care of header phi's, live-outs,
6384   //    predication, updating analyses.
6385   ILV.fixVectorizedLoop();
6386 }
6387 
6388 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
6389     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
6390   BasicBlock *Latch = OrigLoop->getLoopLatch();
6391 
6392   // We create new control-flow for the vectorized loop, so the original
6393   // condition will be dead after vectorization if it's only used by the
6394   // branch.
6395   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
6396   if (Cmp && Cmp->hasOneUse())
6397     DeadInstructions.insert(Cmp);
6398 
6399   // We create new "steps" for induction variable updates to which the original
6400   // induction variables map. An original update instruction will be dead if
6401   // all its users except the induction variable are dead.
6402   for (auto &Induction : *Legal->getInductionVars()) {
6403     PHINode *Ind = Induction.first;
6404     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
6405     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
6406           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
6407         }))
6408       DeadInstructions.insert(IndUpdate);
6409 
6410     // We record as "Dead" also the type-casting instructions we had identified
6411     // during induction analysis. We don't need any handling for them in the
6412     // vectorized loop because we have proven that, under a proper runtime
6413     // test guarding the vectorized loop, the value of the phi, and the casted
6414     // value of the phi, are the same. The last instruction in this casting chain
6415     // will get its scalar/vector/widened def from the scalar/vector/widened def
6416     // of the respective phi node. Any other casts in the induction def-use chain
6417     // have no other uses outside the phi update chain, and will be ignored.
6418     InductionDescriptor &IndDes = Induction.second;
6419     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
6420     DeadInstructions.insert(Casts.begin(), Casts.end());
6421   }
6422 }
6423 
6424 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
6425 
6426 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
6427 
6428 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
6429                                         Instruction::BinaryOps BinOp) {
6430   // When unrolling and the VF is 1, we only need to add a simple scalar.
6431   Type *Ty = Val->getType();
6432   assert(!Ty->isVectorTy() && "Val must be a scalar");
6433 
6434   if (Ty->isFloatingPointTy()) {
6435     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
6436 
6437     // Floating point operations had to be 'fast' to enable the unrolling.
6438     Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
6439     return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
6440   }
6441   Constant *C = ConstantInt::get(Ty, StartIdx);
6442   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
6443 }
6444 
6445 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
6446   SmallVector<Metadata *, 4> MDs;
6447   // Reserve first location for self reference to the LoopID metadata node.
6448   MDs.push_back(nullptr);
6449   bool IsUnrollMetadata = false;
6450   MDNode *LoopID = L->getLoopID();
6451   if (LoopID) {
6452     // First find existing loop unrolling disable metadata.
6453     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
6454       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
6455       if (MD) {
6456         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
6457         IsUnrollMetadata =
6458             S && S->getString().startswith("llvm.loop.unroll.disable");
6459       }
6460       MDs.push_back(LoopID->getOperand(i));
6461     }
6462   }
6463 
6464   if (!IsUnrollMetadata) {
6465     // Add runtime unroll disable metadata.
6466     LLVMContext &Context = L->getHeader()->getContext();
6467     SmallVector<Metadata *, 1> DisableOperands;
6468     DisableOperands.push_back(
6469         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
6470     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
6471     MDs.push_back(DisableNode);
6472     MDNode *NewLoopID = MDNode::get(Context, MDs);
6473     // Set operand 0 to refer to the loop id itself.
6474     NewLoopID->replaceOperandWith(0, NewLoopID);
6475     L->setLoopID(NewLoopID);
6476   }
6477 }
6478 
6479 bool LoopVectorizationPlanner::getDecisionAndClampRange(
6480     const std::function<bool(unsigned)> &Predicate, VFRange &Range) {
6481   assert(Range.End > Range.Start && "Trying to test an empty VF range.");
6482   bool PredicateAtRangeStart = Predicate(Range.Start);
6483 
6484   for (unsigned TmpVF = Range.Start * 2; TmpVF < Range.End; TmpVF *= 2)
6485     if (Predicate(TmpVF) != PredicateAtRangeStart) {
6486       Range.End = TmpVF;
6487       break;
6488     }
6489 
6490   return PredicateAtRangeStart;
6491 }
6492 
6493 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
6494 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
6495 /// of VF's starting at a given VF and extending it as much as possible. Each
6496 /// vectorization decision can potentially shorten this sub-range during
6497 /// buildVPlan().
6498 void LoopVectorizationPlanner::buildVPlans(unsigned MinVF, unsigned MaxVF) {
6499   for (unsigned VF = MinVF; VF < MaxVF + 1;) {
6500     VFRange SubRange = {VF, MaxVF + 1};
6501     VPlans.push_back(buildVPlan(SubRange));
6502     VF = SubRange.End;
6503   }
6504 }
6505 
6506 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
6507                                          VPlanPtr &Plan) {
6508   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
6509 
6510   // Look for cached value.
6511   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
6512   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
6513   if (ECEntryIt != EdgeMaskCache.end())
6514     return ECEntryIt->second;
6515 
6516   VPValue *SrcMask = createBlockInMask(Src, Plan);
6517 
6518   // The terminator has to be a branch inst!
6519   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
6520   assert(BI && "Unexpected terminator found");
6521 
6522   if (!BI->isConditional())
6523     return EdgeMaskCache[Edge] = SrcMask;
6524 
6525   VPValue *EdgeMask = Plan->getVPValue(BI->getCondition());
6526   assert(EdgeMask && "No Edge Mask found for condition");
6527 
6528   if (BI->getSuccessor(0) != Dst)
6529     EdgeMask = Builder.createNot(EdgeMask);
6530 
6531   if (SrcMask) // Otherwise block in-mask is all-one, no need to AND.
6532     EdgeMask = Builder.createAnd(EdgeMask, SrcMask);
6533 
6534   return EdgeMaskCache[Edge] = EdgeMask;
6535 }
6536 
6537 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
6538   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
6539 
6540   // Look for cached value.
6541   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
6542   if (BCEntryIt != BlockMaskCache.end())
6543     return BCEntryIt->second;
6544 
6545   // All-one mask is modelled as no-mask following the convention for masked
6546   // load/store/gather/scatter. Initialize BlockMask to no-mask.
6547   VPValue *BlockMask = nullptr;
6548 
6549   // Loop incoming mask is all-one.
6550   if (OrigLoop->getHeader() == BB)
6551     return BlockMaskCache[BB] = BlockMask;
6552 
6553   // This is the block mask. We OR all incoming edges.
6554   for (auto *Predecessor : predecessors(BB)) {
6555     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
6556     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
6557       return BlockMaskCache[BB] = EdgeMask;
6558 
6559     if (!BlockMask) { // BlockMask has its initialized nullptr value.
6560       BlockMask = EdgeMask;
6561       continue;
6562     }
6563 
6564     BlockMask = Builder.createOr(BlockMask, EdgeMask);
6565   }
6566 
6567   return BlockMaskCache[BB] = BlockMask;
6568 }
6569 
6570 VPInterleaveRecipe *VPRecipeBuilder::tryToInterleaveMemory(Instruction *I,
6571                                                            VFRange &Range) {
6572   const InterleaveGroup *IG = CM.getInterleavedAccessGroup(I);
6573   if (!IG)
6574     return nullptr;
6575 
6576   // Now check if IG is relevant for VF's in the given range.
6577   auto isIGMember = [&](Instruction *I) -> std::function<bool(unsigned)> {
6578     return [=](unsigned VF) -> bool {
6579       return (VF >= 2 && // Query is illegal for VF == 1
6580               CM.getWideningDecision(I, VF) ==
6581                   LoopVectorizationCostModel::CM_Interleave);
6582     };
6583   };
6584   if (!LoopVectorizationPlanner::getDecisionAndClampRange(isIGMember(I), Range))
6585     return nullptr;
6586 
6587   // I is a member of an InterleaveGroup for VF's in the (possibly trimmed)
6588   // range. If it's the primary member of the IG construct a VPInterleaveRecipe.
6589   // Otherwise, it's an adjunct member of the IG, do not construct any Recipe.
6590   assert(I == IG->getInsertPos() &&
6591          "Generating a recipe for an adjunct member of an interleave group");
6592 
6593   return new VPInterleaveRecipe(IG);
6594 }
6595 
6596 VPWidenMemoryInstructionRecipe *
6597 VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range,
6598                                   VPlanPtr &Plan) {
6599   if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
6600     return nullptr;
6601 
6602   auto willWiden = [&](unsigned VF) -> bool {
6603     if (VF == 1)
6604       return false;
6605     if (CM.isScalarAfterVectorization(I, VF) ||
6606         CM.isProfitableToScalarize(I, VF))
6607       return false;
6608     LoopVectorizationCostModel::InstWidening Decision =
6609         CM.getWideningDecision(I, VF);
6610     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
6611            "CM decision should be taken at this point.");
6612     assert(Decision != LoopVectorizationCostModel::CM_Interleave &&
6613            "Interleave memory opportunity should be caught earlier.");
6614     return Decision != LoopVectorizationCostModel::CM_Scalarize;
6615   };
6616 
6617   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
6618     return nullptr;
6619 
6620   VPValue *Mask = nullptr;
6621   if (Legal->isMaskRequired(I))
6622     Mask = createBlockInMask(I->getParent(), Plan);
6623 
6624   return new VPWidenMemoryInstructionRecipe(*I, Mask);
6625 }
6626 
6627 VPWidenIntOrFpInductionRecipe *
6628 VPRecipeBuilder::tryToOptimizeInduction(Instruction *I, VFRange &Range) {
6629   if (PHINode *Phi = dyn_cast<PHINode>(I)) {
6630     // Check if this is an integer or fp induction. If so, build the recipe that
6631     // produces its scalar and vector values.
6632     InductionDescriptor II = Legal->getInductionVars()->lookup(Phi);
6633     if (II.getKind() == InductionDescriptor::IK_IntInduction ||
6634         II.getKind() == InductionDescriptor::IK_FpInduction)
6635       return new VPWidenIntOrFpInductionRecipe(Phi);
6636 
6637     return nullptr;
6638   }
6639 
6640   // Optimize the special case where the source is a constant integer
6641   // induction variable. Notice that we can only optimize the 'trunc' case
6642   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
6643   // (c) other casts depend on pointer size.
6644 
6645   // Determine whether \p K is a truncation based on an induction variable that
6646   // can be optimized.
6647   auto isOptimizableIVTruncate =
6648       [&](Instruction *K) -> std::function<bool(unsigned)> {
6649     return
6650         [=](unsigned VF) -> bool { return CM.isOptimizableIVTruncate(K, VF); };
6651   };
6652 
6653   if (isa<TruncInst>(I) && LoopVectorizationPlanner::getDecisionAndClampRange(
6654                                isOptimizableIVTruncate(I), Range))
6655     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
6656                                              cast<TruncInst>(I));
6657   return nullptr;
6658 }
6659 
6660 VPBlendRecipe *VPRecipeBuilder::tryToBlend(Instruction *I, VPlanPtr &Plan) {
6661   PHINode *Phi = dyn_cast<PHINode>(I);
6662   if (!Phi || Phi->getParent() == OrigLoop->getHeader())
6663     return nullptr;
6664 
6665   // We know that all PHIs in non-header blocks are converted into selects, so
6666   // we don't have to worry about the insertion order and we can just use the
6667   // builder. At this point we generate the predication tree. There may be
6668   // duplications since this is a simple recursive scan, but future
6669   // optimizations will clean it up.
6670 
6671   SmallVector<VPValue *, 2> Masks;
6672   unsigned NumIncoming = Phi->getNumIncomingValues();
6673   for (unsigned In = 0; In < NumIncoming; In++) {
6674     VPValue *EdgeMask =
6675       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
6676     assert((EdgeMask || NumIncoming == 1) &&
6677            "Multiple predecessors with one having a full mask");
6678     if (EdgeMask)
6679       Masks.push_back(EdgeMask);
6680   }
6681   return new VPBlendRecipe(Phi, Masks);
6682 }
6683 
6684 bool VPRecipeBuilder::tryToWiden(Instruction *I, VPBasicBlock *VPBB,
6685                                  VFRange &Range) {
6686   if (CM.isScalarWithPredication(I))
6687     return false;
6688 
6689   auto IsVectorizableOpcode = [](unsigned Opcode) {
6690     switch (Opcode) {
6691     case Instruction::Add:
6692     case Instruction::And:
6693     case Instruction::AShr:
6694     case Instruction::BitCast:
6695     case Instruction::Br:
6696     case Instruction::Call:
6697     case Instruction::FAdd:
6698     case Instruction::FCmp:
6699     case Instruction::FDiv:
6700     case Instruction::FMul:
6701     case Instruction::FPExt:
6702     case Instruction::FPToSI:
6703     case Instruction::FPToUI:
6704     case Instruction::FPTrunc:
6705     case Instruction::FRem:
6706     case Instruction::FSub:
6707     case Instruction::GetElementPtr:
6708     case Instruction::ICmp:
6709     case Instruction::IntToPtr:
6710     case Instruction::Load:
6711     case Instruction::LShr:
6712     case Instruction::Mul:
6713     case Instruction::Or:
6714     case Instruction::PHI:
6715     case Instruction::PtrToInt:
6716     case Instruction::SDiv:
6717     case Instruction::Select:
6718     case Instruction::SExt:
6719     case Instruction::Shl:
6720     case Instruction::SIToFP:
6721     case Instruction::SRem:
6722     case Instruction::Store:
6723     case Instruction::Sub:
6724     case Instruction::Trunc:
6725     case Instruction::UDiv:
6726     case Instruction::UIToFP:
6727     case Instruction::URem:
6728     case Instruction::Xor:
6729     case Instruction::ZExt:
6730       return true;
6731     }
6732     return false;
6733   };
6734 
6735   if (!IsVectorizableOpcode(I->getOpcode()))
6736     return false;
6737 
6738   if (CallInst *CI = dyn_cast<CallInst>(I)) {
6739     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6740     if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
6741                ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
6742       return false;
6743   }
6744 
6745   auto willWiden = [&](unsigned VF) -> bool {
6746     if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
6747                              CM.isProfitableToScalarize(I, VF)))
6748       return false;
6749     if (CallInst *CI = dyn_cast<CallInst>(I)) {
6750       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6751       // The following case may be scalarized depending on the VF.
6752       // The flag shows whether we use Intrinsic or a usual Call for vectorized
6753       // version of the instruction.
6754       // Is it beneficial to perform intrinsic call compared to lib call?
6755       bool NeedToScalarize;
6756       unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
6757       bool UseVectorIntrinsic =
6758           ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
6759       return UseVectorIntrinsic || !NeedToScalarize;
6760     }
6761     if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
6762       assert(CM.getWideningDecision(I, VF) ==
6763                  LoopVectorizationCostModel::CM_Scalarize &&
6764              "Memory widening decisions should have been taken care by now");
6765       return false;
6766     }
6767     return true;
6768   };
6769 
6770   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
6771     return false;
6772 
6773   // Success: widen this instruction. We optimize the common case where
6774   // consecutive instructions can be represented by a single recipe.
6775   if (!VPBB->empty()) {
6776     VPWidenRecipe *LastWidenRecipe = dyn_cast<VPWidenRecipe>(&VPBB->back());
6777     if (LastWidenRecipe && LastWidenRecipe->appendInstruction(I))
6778       return true;
6779   }
6780 
6781   VPBB->appendRecipe(new VPWidenRecipe(I));
6782   return true;
6783 }
6784 
6785 VPBasicBlock *VPRecipeBuilder::handleReplication(
6786     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
6787     DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
6788     VPlanPtr &Plan) {
6789   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
6790       [&](unsigned VF) { return CM.isUniformAfterVectorization(I, VF); },
6791       Range);
6792 
6793   bool IsPredicated = CM.isScalarWithPredication(I);
6794   auto *Recipe = new VPReplicateRecipe(I, IsUniform, IsPredicated);
6795 
6796   // Find if I uses a predicated instruction. If so, it will use its scalar
6797   // value. Avoid hoisting the insert-element which packs the scalar value into
6798   // a vector value, as that happens iff all users use the vector value.
6799   for (auto &Op : I->operands())
6800     if (auto *PredInst = dyn_cast<Instruction>(Op))
6801       if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
6802         PredInst2Recipe[PredInst]->setAlsoPack(false);
6803 
6804   // Finalize the recipe for Instr, first if it is not predicated.
6805   if (!IsPredicated) {
6806     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
6807     VPBB->appendRecipe(Recipe);
6808     return VPBB;
6809   }
6810   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
6811   assert(VPBB->getSuccessors().empty() &&
6812          "VPBB has successors when handling predicated replication.");
6813   // Record predicated instructions for above packing optimizations.
6814   PredInst2Recipe[I] = Recipe;
6815   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
6816   VPBlockUtils::insertBlockAfter(Region, VPBB);
6817   auto *RegSucc = new VPBasicBlock();
6818   VPBlockUtils::insertBlockAfter(RegSucc, Region);
6819   return RegSucc;
6820 }
6821 
6822 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
6823                                                       VPRecipeBase *PredRecipe,
6824                                                       VPlanPtr &Plan) {
6825   // Instructions marked for predication are replicated and placed under an
6826   // if-then construct to prevent side-effects.
6827 
6828   // Generate recipes to compute the block mask for this region.
6829   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
6830 
6831   // Build the triangular if-then region.
6832   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
6833   assert(Instr->getParent() && "Predicated instruction not in any basic block");
6834   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
6835   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
6836   auto *PHIRecipe =
6837       Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr);
6838   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
6839   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
6840   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
6841 
6842   // Note: first set Entry as region entry and then connect successors starting
6843   // from it in order, to propagate the "parent" of each VPBasicBlock.
6844   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, Entry);
6845   VPBlockUtils::connectBlocks(Pred, Exit);
6846 
6847   return Region;
6848 }
6849 
6850 bool VPRecipeBuilder::tryToCreateRecipe(Instruction *Instr, VFRange &Range,
6851                                         VPlanPtr &Plan, VPBasicBlock *VPBB) {
6852   VPRecipeBase *Recipe = nullptr;
6853   // Check if Instr should belong to an interleave memory recipe, or already
6854   // does. In the latter case Instr is irrelevant.
6855   if ((Recipe = tryToInterleaveMemory(Instr, Range))) {
6856     VPBB->appendRecipe(Recipe);
6857     return true;
6858   }
6859 
6860   // Check if Instr is a memory operation that should be widened.
6861   if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) {
6862     VPBB->appendRecipe(Recipe);
6863     return true;
6864   }
6865 
6866   // Check if Instr should form some PHI recipe.
6867   if ((Recipe = tryToOptimizeInduction(Instr, Range))) {
6868     VPBB->appendRecipe(Recipe);
6869     return true;
6870   }
6871   if ((Recipe = tryToBlend(Instr, Plan))) {
6872     VPBB->appendRecipe(Recipe);
6873     return true;
6874   }
6875   if (PHINode *Phi = dyn_cast<PHINode>(Instr)) {
6876     VPBB->appendRecipe(new VPWidenPHIRecipe(Phi));
6877     return true;
6878   }
6879 
6880   // Check if Instr is to be widened by a general VPWidenRecipe, after
6881   // having first checked for specific widening recipes that deal with
6882   // Interleave Groups, Inductions and Phi nodes.
6883   if (tryToWiden(Instr, VPBB, Range))
6884     return true;
6885 
6886   return false;
6887 }
6888 
6889 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(unsigned MinVF,
6890                                                         unsigned MaxVF) {
6891   assert(OrigLoop->empty() && "Inner loop expected.");
6892 
6893   // Collect conditions feeding internal conditional branches; they need to be
6894   // represented in VPlan for it to model masking.
6895   SmallPtrSet<Value *, 1> NeedDef;
6896 
6897   auto *Latch = OrigLoop->getLoopLatch();
6898   for (BasicBlock *BB : OrigLoop->blocks()) {
6899     if (BB == Latch)
6900       continue;
6901     BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
6902     if (Branch && Branch->isConditional())
6903       NeedDef.insert(Branch->getCondition());
6904   }
6905 
6906   // Collect instructions from the original loop that will become trivially dead
6907   // in the vectorized loop. We don't need to vectorize these instructions. For
6908   // example, original induction update instructions can become dead because we
6909   // separately emit induction "steps" when generating code for the new loop.
6910   // Similarly, we create a new latch condition when setting up the structure
6911   // of the new loop, so the old one can become dead.
6912   SmallPtrSet<Instruction *, 4> DeadInstructions;
6913   collectTriviallyDeadInstructions(DeadInstructions);
6914 
6915   for (unsigned VF = MinVF; VF < MaxVF + 1;) {
6916     VFRange SubRange = {VF, MaxVF + 1};
6917     VPlans.push_back(
6918         buildVPlanWithVPRecipes(SubRange, NeedDef, DeadInstructions));
6919     VF = SubRange.End;
6920   }
6921 }
6922 
6923 LoopVectorizationPlanner::VPlanPtr
6924 LoopVectorizationPlanner::buildVPlanWithVPRecipes(
6925     VFRange &Range, SmallPtrSetImpl<Value *> &NeedDef,
6926     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
6927   // Hold a mapping from predicated instructions to their recipes, in order to
6928   // fix their AlsoPack behavior if a user is determined to replicate and use a
6929   // scalar instead of vector value.
6930   DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
6931 
6932   DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
6933   DenseMap<Instruction *, Instruction *> SinkAfterInverse;
6934 
6935   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
6936   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
6937   auto Plan = llvm::make_unique<VPlan>(VPBB);
6938 
6939   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, TTI, Legal, CM, Builder);
6940   // Represent values that will have defs inside VPlan.
6941   for (Value *V : NeedDef)
6942     Plan->addVPValue(V);
6943 
6944   // Scan the body of the loop in a topological order to visit each basic block
6945   // after having visited its predecessor basic blocks.
6946   LoopBlocksDFS DFS(OrigLoop);
6947   DFS.perform(LI);
6948 
6949   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6950     // Relevant instructions from basic block BB will be grouped into VPRecipe
6951     // ingredients and fill a new VPBasicBlock.
6952     unsigned VPBBsForBB = 0;
6953     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
6954     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
6955     VPBB = FirstVPBBForBB;
6956     Builder.setInsertPoint(VPBB);
6957 
6958     std::vector<Instruction *> Ingredients;
6959 
6960     // Organize the ingredients to vectorize from current basic block in the
6961     // right order.
6962     for (Instruction &I : BB->instructionsWithoutDebug()) {
6963       Instruction *Instr = &I;
6964 
6965       // First filter out irrelevant instructions, to ensure no recipes are
6966       // built for them.
6967       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
6968         continue;
6969 
6970       // I is a member of an InterleaveGroup for Range.Start. If it's an adjunct
6971       // member of the IG, do not construct any Recipe for it.
6972       const InterleaveGroup *IG = CM.getInterleavedAccessGroup(Instr);
6973       if (IG && Instr != IG->getInsertPos() &&
6974           Range.Start >= 2 && // Query is illegal for VF == 1
6975           CM.getWideningDecision(Instr, Range.Start) ==
6976               LoopVectorizationCostModel::CM_Interleave) {
6977         if (SinkAfterInverse.count(Instr))
6978           Ingredients.push_back(SinkAfterInverse.find(Instr)->second);
6979         continue;
6980       }
6981 
6982       // Move instructions to handle first-order recurrences, step 1: avoid
6983       // handling this instruction until after we've handled the instruction it
6984       // should follow.
6985       auto SAIt = SinkAfter.find(Instr);
6986       if (SAIt != SinkAfter.end()) {
6987         LLVM_DEBUG(dbgs() << "Sinking" << *SAIt->first << " after"
6988                           << *SAIt->second
6989                           << " to vectorize a 1st order recurrence.\n");
6990         SinkAfterInverse[SAIt->second] = Instr;
6991         continue;
6992       }
6993 
6994       Ingredients.push_back(Instr);
6995 
6996       // Move instructions to handle first-order recurrences, step 2: push the
6997       // instruction to be sunk at its insertion point.
6998       auto SAInvIt = SinkAfterInverse.find(Instr);
6999       if (SAInvIt != SinkAfterInverse.end())
7000         Ingredients.push_back(SAInvIt->second);
7001     }
7002 
7003     // Introduce each ingredient into VPlan.
7004     for (Instruction *Instr : Ingredients) {
7005       if (RecipeBuilder.tryToCreateRecipe(Instr, Range, Plan, VPBB))
7006         continue;
7007 
7008       // Otherwise, if all widening options failed, Instruction is to be
7009       // replicated. This may create a successor for VPBB.
7010       VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
7011           Instr, Range, VPBB, PredInst2Recipe, Plan);
7012       if (NextVPBB != VPBB) {
7013         VPBB = NextVPBB;
7014         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
7015                                     : "");
7016       }
7017     }
7018   }
7019 
7020   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
7021   // may also be empty, such as the last one VPBB, reflecting original
7022   // basic-blocks with no recipes.
7023   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
7024   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
7025   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
7026   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
7027   delete PreEntry;
7028 
7029   std::string PlanName;
7030   raw_string_ostream RSO(PlanName);
7031   unsigned VF = Range.Start;
7032   Plan->addVF(VF);
7033   RSO << "Initial VPlan for VF={" << VF;
7034   for (VF *= 2; VF < Range.End; VF *= 2) {
7035     Plan->addVF(VF);
7036     RSO << "," << VF;
7037   }
7038   RSO << "},UF>=1";
7039   RSO.flush();
7040   Plan->setName(PlanName);
7041 
7042   return Plan;
7043 }
7044 
7045 LoopVectorizationPlanner::VPlanPtr
7046 LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
7047   // Outer loop handling: They may require CFG and instruction level
7048   // transformations before even evaluating whether vectorization is profitable.
7049   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7050   // the vectorization pipeline.
7051   assert(!OrigLoop->empty());
7052   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7053 
7054   // Create new empty VPlan
7055   auto Plan = llvm::make_unique<VPlan>();
7056 
7057   // Build hierarchical CFG
7058   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI);
7059   HCFGBuilder.buildHierarchicalCFG(*Plan.get());
7060 
7061   return Plan;
7062 }
7063 
7064 Value* LoopVectorizationPlanner::VPCallbackILV::
7065 getOrCreateVectorValues(Value *V, unsigned Part) {
7066       return ILV.getOrCreateVectorValue(V, Part);
7067 }
7068 
7069 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent) const {
7070   O << " +\n"
7071     << Indent << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
7072   IG->getInsertPos()->printAsOperand(O, false);
7073   O << "\\l\"";
7074   for (unsigned i = 0; i < IG->getFactor(); ++i)
7075     if (Instruction *I = IG->getMember(i))
7076       O << " +\n"
7077         << Indent << "\"  " << VPlanIngredient(I) << " " << i << "\\l\"";
7078 }
7079 
7080 void VPWidenRecipe::execute(VPTransformState &State) {
7081   for (auto &Instr : make_range(Begin, End))
7082     State.ILV->widenInstruction(Instr);
7083 }
7084 
7085 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
7086   assert(!State.Instance && "Int or FP induction being replicated.");
7087   State.ILV->widenIntOrFpInduction(IV, Trunc);
7088 }
7089 
7090 void VPWidenPHIRecipe::execute(VPTransformState &State) {
7091   State.ILV->widenPHIInstruction(Phi, State.UF, State.VF);
7092 }
7093 
7094 void VPBlendRecipe::execute(VPTransformState &State) {
7095   State.ILV->setDebugLocFromInst(State.Builder, Phi);
7096   // We know that all PHIs in non-header blocks are converted into
7097   // selects, so we don't have to worry about the insertion order and we
7098   // can just use the builder.
7099   // At this point we generate the predication tree. There may be
7100   // duplications since this is a simple recursive scan, but future
7101   // optimizations will clean it up.
7102 
7103   unsigned NumIncoming = Phi->getNumIncomingValues();
7104 
7105   assert((User || NumIncoming == 1) &&
7106          "Multiple predecessors with predecessors having a full mask");
7107   // Generate a sequence of selects of the form:
7108   // SELECT(Mask3, In3,
7109   //      SELECT(Mask2, In2,
7110   //                   ( ...)))
7111   InnerLoopVectorizer::VectorParts Entry(State.UF);
7112   for (unsigned In = 0; In < NumIncoming; ++In) {
7113     for (unsigned Part = 0; Part < State.UF; ++Part) {
7114       // We might have single edge PHIs (blocks) - use an identity
7115       // 'select' for the first PHI operand.
7116       Value *In0 =
7117           State.ILV->getOrCreateVectorValue(Phi->getIncomingValue(In), Part);
7118       if (In == 0)
7119         Entry[Part] = In0; // Initialize with the first incoming value.
7120       else {
7121         // Select between the current value and the previous incoming edge
7122         // based on the incoming mask.
7123         Value *Cond = State.get(User->getOperand(In), Part);
7124         Entry[Part] =
7125             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
7126       }
7127     }
7128   }
7129   for (unsigned Part = 0; Part < State.UF; ++Part)
7130     State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
7131 }
7132 
7133 void VPInterleaveRecipe::execute(VPTransformState &State) {
7134   assert(!State.Instance && "Interleave group being replicated.");
7135   State.ILV->vectorizeInterleaveGroup(IG->getInsertPos());
7136 }
7137 
7138 void VPReplicateRecipe::execute(VPTransformState &State) {
7139   if (State.Instance) { // Generate a single instance.
7140     State.ILV->scalarizeInstruction(Ingredient, *State.Instance, IsPredicated);
7141     // Insert scalar instance packing it into a vector.
7142     if (AlsoPack && State.VF > 1) {
7143       // If we're constructing lane 0, initialize to start from undef.
7144       if (State.Instance->Lane == 0) {
7145         Value *Undef =
7146             UndefValue::get(VectorType::get(Ingredient->getType(), State.VF));
7147         State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef);
7148       }
7149       State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance);
7150     }
7151     return;
7152   }
7153 
7154   // Generate scalar instances for all VF lanes of all UF parts, unless the
7155   // instruction is uniform inwhich case generate only the first lane for each
7156   // of the UF parts.
7157   unsigned EndLane = IsUniform ? 1 : State.VF;
7158   for (unsigned Part = 0; Part < State.UF; ++Part)
7159     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
7160       State.ILV->scalarizeInstruction(Ingredient, {Part, Lane}, IsPredicated);
7161 }
7162 
7163 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
7164   assert(State.Instance && "Branch on Mask works only on single instance.");
7165 
7166   unsigned Part = State.Instance->Part;
7167   unsigned Lane = State.Instance->Lane;
7168 
7169   Value *ConditionBit = nullptr;
7170   if (!User) // Block in mask is all-one.
7171     ConditionBit = State.Builder.getTrue();
7172   else {
7173     VPValue *BlockInMask = User->getOperand(0);
7174     ConditionBit = State.get(BlockInMask, Part);
7175     if (ConditionBit->getType()->isVectorTy())
7176       ConditionBit = State.Builder.CreateExtractElement(
7177           ConditionBit, State.Builder.getInt32(Lane));
7178   }
7179 
7180   // Replace the temporary unreachable terminator with a new conditional branch,
7181   // whose two destinations will be set later when they are created.
7182   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
7183   assert(isa<UnreachableInst>(CurrentTerminator) &&
7184          "Expected to replace unreachable terminator with conditional branch.");
7185   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
7186   CondBr->setSuccessor(0, nullptr);
7187   ReplaceInstWithInst(CurrentTerminator, CondBr);
7188 }
7189 
7190 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
7191   assert(State.Instance && "Predicated instruction PHI works per instance.");
7192   Instruction *ScalarPredInst = cast<Instruction>(
7193       State.ValueMap.getScalarValue(PredInst, *State.Instance));
7194   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
7195   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
7196   assert(PredicatingBB && "Predicated block has no single predecessor.");
7197 
7198   // By current pack/unpack logic we need to generate only a single phi node: if
7199   // a vector value for the predicated instruction exists at this point it means
7200   // the instruction has vector users only, and a phi for the vector value is
7201   // needed. In this case the recipe of the predicated instruction is marked to
7202   // also do that packing, thereby "hoisting" the insert-element sequence.
7203   // Otherwise, a phi node for the scalar value is needed.
7204   unsigned Part = State.Instance->Part;
7205   if (State.ValueMap.hasVectorValue(PredInst, Part)) {
7206     Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
7207     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
7208     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
7209     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
7210     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
7211     State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
7212   } else {
7213     Type *PredInstType = PredInst->getType();
7214     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
7215     Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB);
7216     Phi->addIncoming(ScalarPredInst, PredicatedBB);
7217     State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
7218   }
7219 }
7220 
7221 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
7222   if (!User)
7223     return State.ILV->vectorizeMemoryInstruction(&Instr);
7224 
7225   // Last (and currently only) operand is a mask.
7226   InnerLoopVectorizer::VectorParts MaskValues(State.UF);
7227   VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
7228   for (unsigned Part = 0; Part < State.UF; ++Part)
7229     MaskValues[Part] = State.get(Mask, Part);
7230   State.ILV->vectorizeMemoryInstruction(&Instr, &MaskValues);
7231 }
7232 
7233 // Process the loop in the VPlan-native vectorization path. This path builds
7234 // VPlan upfront in the vectorization pipeline, which allows to apply
7235 // VPlan-to-VPlan transformations from the very beginning without modifying the
7236 // input LLVM IR.
7237 static bool processLoopInVPlanNativePath(
7238     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
7239     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
7240     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
7241     OptimizationRemarkEmitter *ORE, LoopVectorizeHints &Hints) {
7242 
7243   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
7244   Function *F = L->getHeader()->getParent();
7245   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
7246   LoopVectorizationCostModel CM(L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
7247                                 &Hints, IAI);
7248   // Use the planner for outer loop vectorization.
7249   // TODO: CM is not used at this point inside the planner. Turn CM into an
7250   // optional argument if we don't need it in the future.
7251   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM);
7252 
7253   // Get user vectorization factor.
7254   unsigned UserVF = Hints.getWidth();
7255 
7256   // Check the function attributes to find out if this function should be
7257   // optimized for size.
7258   bool OptForSize =
7259       Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
7260 
7261   // Plan how to best vectorize, return the best VF and its cost.
7262   LVP.planInVPlanNativePath(OptForSize, UserVF);
7263 
7264   // Returning false. We are currently not generating vector code in the VPlan
7265   // native path.
7266   return false;
7267 }
7268 
7269 bool LoopVectorizePass::processLoop(Loop *L) {
7270   assert((EnableVPlanNativePath || L->empty()) &&
7271          "VPlan-native path is not enabled. Only process inner loops.");
7272 
7273 #ifndef NDEBUG
7274   const std::string DebugLocStr = getDebugLocString(L);
7275 #endif /* NDEBUG */
7276 
7277   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
7278                     << L->getHeader()->getParent()->getName() << "\" from "
7279                     << DebugLocStr << "\n");
7280 
7281   LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
7282 
7283   LLVM_DEBUG(
7284       dbgs() << "LV: Loop hints:"
7285              << " force="
7286              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
7287                      ? "disabled"
7288                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
7289                             ? "enabled"
7290                             : "?"))
7291              << " width=" << Hints.getWidth()
7292              << " unroll=" << Hints.getInterleave() << "\n");
7293 
7294   // Function containing loop
7295   Function *F = L->getHeader()->getParent();
7296 
7297   // Looking at the diagnostic output is the only way to determine if a loop
7298   // was vectorized (other than looking at the IR or machine code), so it
7299   // is important to generate an optimization remark for each loop. Most of
7300   // these messages are generated as OptimizationRemarkAnalysis. Remarks
7301   // generated as OptimizationRemark and OptimizationRemarkMissed are
7302   // less verbose reporting vectorized loops and unvectorized loops that may
7303   // benefit from vectorization, respectively.
7304 
7305   if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
7306     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
7307     return false;
7308   }
7309 
7310   PredicatedScalarEvolution PSE(*SE, *L);
7311 
7312   // Check if it is legal to vectorize the loop.
7313   LoopVectorizationRequirements Requirements(*ORE);
7314   LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, GetLAA, LI, ORE,
7315                                 &Requirements, &Hints, DB, AC);
7316   if (!LVL.canVectorize(EnableVPlanNativePath)) {
7317     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
7318     emitMissedWarning(F, L, Hints, ORE);
7319     return false;
7320   }
7321 
7322   // Check the function attributes to find out if this function should be
7323   // optimized for size.
7324   bool OptForSize =
7325       Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
7326 
7327   // Entrance to the VPlan-native vectorization path. Outer loops are processed
7328   // here. They may require CFG and instruction level transformations before
7329   // even evaluating whether vectorization is profitable. Since we cannot modify
7330   // the incoming IR, we need to build VPlan upfront in the vectorization
7331   // pipeline.
7332   if (!L->empty())
7333     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
7334                                         ORE, Hints);
7335 
7336   assert(L->empty() && "Inner loop expected.");
7337   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
7338   // count by optimizing for size, to minimize overheads.
7339   // Prefer constant trip counts over profile data, over upper bound estimate.
7340   unsigned ExpectedTC = 0;
7341   bool HasExpectedTC = false;
7342   if (const SCEVConstant *ConstExits =
7343       dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) {
7344     const APInt &ExitsCount = ConstExits->getAPInt();
7345     // We are interested in small values for ExpectedTC. Skip over those that
7346     // can't fit an unsigned.
7347     if (ExitsCount.ult(std::numeric_limits<unsigned>::max())) {
7348       ExpectedTC = static_cast<unsigned>(ExitsCount.getZExtValue()) + 1;
7349       HasExpectedTC = true;
7350     }
7351   }
7352   // ExpectedTC may be large because it's bound by a variable. Check
7353   // profiling information to validate we should vectorize.
7354   if (!HasExpectedTC && LoopVectorizeWithBlockFrequency) {
7355     auto EstimatedTC = getLoopEstimatedTripCount(L);
7356     if (EstimatedTC) {
7357       ExpectedTC = *EstimatedTC;
7358       HasExpectedTC = true;
7359     }
7360   }
7361   if (!HasExpectedTC) {
7362     ExpectedTC = SE->getSmallConstantMaxTripCount(L);
7363     HasExpectedTC = (ExpectedTC > 0);
7364   }
7365 
7366   if (HasExpectedTC && ExpectedTC < TinyTripCountVectorThreshold) {
7367     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
7368                       << "This loop is worth vectorizing only if no scalar "
7369                       << "iteration overheads are incurred.");
7370     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
7371       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
7372     else {
7373       LLVM_DEBUG(dbgs() << "\n");
7374       // Loops with a very small trip count are considered for vectorization
7375       // under OptForSize, thereby making sure the cost of their loop body is
7376       // dominant, free of runtime guards and scalar iteration overheads.
7377       OptForSize = true;
7378     }
7379   }
7380 
7381   // Check the function attributes to see if implicit floats are allowed.
7382   // FIXME: This check doesn't seem possibly correct -- what if the loop is
7383   // an integer loop and the vector instructions selected are purely integer
7384   // vector instructions?
7385   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7386     LLVM_DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
7387                          "attribute is used.\n");
7388     ORE->emit(createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(),
7389                                      "NoImplicitFloat", L)
7390               << "loop not vectorized due to NoImplicitFloat attribute");
7391     emitMissedWarning(F, L, Hints, ORE);
7392     return false;
7393   }
7394 
7395   // Check if the target supports potentially unsafe FP vectorization.
7396   // FIXME: Add a check for the type of safety issue (denormal, signaling)
7397   // for the target we're vectorizing for, to make sure none of the
7398   // additional fp-math flags can help.
7399   if (Hints.isPotentiallyUnsafe() &&
7400       TTI->isFPVectorizationPotentiallyUnsafe()) {
7401     LLVM_DEBUG(
7402         dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
7403     ORE->emit(
7404         createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
7405         << "loop not vectorized due to unsafe FP support.");
7406     emitMissedWarning(F, L, Hints, ORE);
7407     return false;
7408   }
7409 
7410   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
7411   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
7412 
7413   // If an override option has been passed in for interleaved accesses, use it.
7414   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
7415     UseInterleaved = EnableInterleavedMemAccesses;
7416 
7417   // Analyze interleaved memory accesses.
7418   if (UseInterleaved) {
7419     IAI.analyzeInterleaving();
7420   }
7421 
7422   // Use the cost model.
7423   LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
7424                                 &Hints, IAI);
7425   CM.collectValuesToIgnore();
7426 
7427   // Use the planner for vectorization.
7428   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM);
7429 
7430   // Get user vectorization factor.
7431   unsigned UserVF = Hints.getWidth();
7432 
7433   // Plan how to best vectorize, return the best VF and its cost.
7434   VectorizationFactor VF = LVP.plan(OptForSize, UserVF);
7435 
7436   // Select the interleave count.
7437   unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
7438 
7439   // Get user interleave count.
7440   unsigned UserIC = Hints.getInterleave();
7441 
7442   // Identify the diagnostic messages that should be produced.
7443   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7444   bool VectorizeLoop = true, InterleaveLoop = true;
7445   if (Requirements.doesNotMeet(F, L, Hints)) {
7446     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
7447                          "requirements.\n");
7448     emitMissedWarning(F, L, Hints, ORE);
7449     return false;
7450   }
7451 
7452   if (VF.Width == 1) {
7453     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
7454     VecDiagMsg = std::make_pair(
7455         "VectorizationNotBeneficial",
7456         "the cost-model indicates that vectorization is not beneficial");
7457     VectorizeLoop = false;
7458   }
7459 
7460   if (IC == 1 && UserIC <= 1) {
7461     // Tell the user interleaving is not beneficial.
7462     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
7463     IntDiagMsg = std::make_pair(
7464         "InterleavingNotBeneficial",
7465         "the cost-model indicates that interleaving is not beneficial");
7466     InterleaveLoop = false;
7467     if (UserIC == 1) {
7468       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
7469       IntDiagMsg.second +=
7470           " and is explicitly disabled or interleave count is set to 1";
7471     }
7472   } else if (IC > 1 && UserIC == 1) {
7473     // Tell the user interleaving is beneficial, but it explicitly disabled.
7474     LLVM_DEBUG(
7475         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
7476     IntDiagMsg = std::make_pair(
7477         "InterleavingBeneficialButDisabled",
7478         "the cost-model indicates that interleaving is beneficial "
7479         "but is explicitly disabled or interleave count is set to 1");
7480     InterleaveLoop = false;
7481   }
7482 
7483   // Override IC if user provided an interleave count.
7484   IC = UserIC > 0 ? UserIC : IC;
7485 
7486   // Emit diagnostic messages, if any.
7487   const char *VAPassName = Hints.vectorizeAnalysisPassName();
7488   if (!VectorizeLoop && !InterleaveLoop) {
7489     // Do not vectorize or interleaving the loop.
7490     ORE->emit([&]() {
7491       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
7492                                       L->getStartLoc(), L->getHeader())
7493              << VecDiagMsg.second;
7494     });
7495     ORE->emit([&]() {
7496       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
7497                                       L->getStartLoc(), L->getHeader())
7498              << IntDiagMsg.second;
7499     });
7500     return false;
7501   } else if (!VectorizeLoop && InterleaveLoop) {
7502     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7503     ORE->emit([&]() {
7504       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
7505                                         L->getStartLoc(), L->getHeader())
7506              << VecDiagMsg.second;
7507     });
7508   } else if (VectorizeLoop && !InterleaveLoop) {
7509     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
7510                       << ") in " << DebugLocStr << '\n');
7511     ORE->emit([&]() {
7512       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
7513                                         L->getStartLoc(), L->getHeader())
7514              << IntDiagMsg.second;
7515     });
7516   } else if (VectorizeLoop && InterleaveLoop) {
7517     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
7518                       << ") in " << DebugLocStr << '\n');
7519     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7520   }
7521 
7522   LVP.setBestPlan(VF.Width, IC);
7523 
7524   using namespace ore;
7525 
7526   if (!VectorizeLoop) {
7527     assert(IC > 1 && "interleave count should not be 1 or 0");
7528     // If we decided that it is not legal to vectorize the loop, then
7529     // interleave it.
7530     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
7531                                &CM);
7532     LVP.executePlan(Unroller, DT);
7533 
7534     ORE->emit([&]() {
7535       return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
7536                                 L->getHeader())
7537              << "interleaved loop (interleaved count: "
7538              << NV("InterleaveCount", IC) << ")";
7539     });
7540   } else {
7541     // If we decided that it is *legal* to vectorize the loop, then do it.
7542     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
7543                            &LVL, &CM);
7544     LVP.executePlan(LB, DT);
7545     ++LoopsVectorized;
7546 
7547     // Add metadata to disable runtime unrolling a scalar loop when there are
7548     // no runtime checks about strides and memory. A scalar loop that is
7549     // rarely used is not worth unrolling.
7550     if (!LB.areSafetyChecksAdded())
7551       AddRuntimeUnrollDisableMetaData(L);
7552 
7553     // Report the vectorization decision.
7554     ORE->emit([&]() {
7555       return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
7556                                 L->getHeader())
7557              << "vectorized loop (vectorization width: "
7558              << NV("VectorizationFactor", VF.Width)
7559              << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
7560     });
7561   }
7562 
7563   // Mark the loop as already vectorized to avoid vectorizing again.
7564   Hints.setAlreadyVectorized();
7565 
7566   LLVM_DEBUG(verifyFunction(*L->getHeader()->getParent()));
7567   return true;
7568 }
7569 
7570 bool LoopVectorizePass::runImpl(
7571     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
7572     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
7573     DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
7574     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
7575     OptimizationRemarkEmitter &ORE_) {
7576   SE = &SE_;
7577   LI = &LI_;
7578   TTI = &TTI_;
7579   DT = &DT_;
7580   BFI = &BFI_;
7581   TLI = TLI_;
7582   AA = &AA_;
7583   AC = &AC_;
7584   GetLAA = &GetLAA_;
7585   DB = &DB_;
7586   ORE = &ORE_;
7587 
7588   // Don't attempt if
7589   // 1. the target claims to have no vector registers, and
7590   // 2. interleaving won't help ILP.
7591   //
7592   // The second condition is necessary because, even if the target has no
7593   // vector registers, loop vectorization may still enable scalar
7594   // interleaving.
7595   if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
7596     return false;
7597 
7598   bool Changed = false;
7599 
7600   // The vectorizer requires loops to be in simplified form.
7601   // Since simplification may add new inner loops, it has to run before the
7602   // legality and profitability checks. This means running the loop vectorizer
7603   // will simplify all loops, regardless of whether anything end up being
7604   // vectorized.
7605   for (auto &L : *LI)
7606     Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
7607 
7608   // Build up a worklist of inner-loops to vectorize. This is necessary as
7609   // the act of vectorizing or partially unrolling a loop creates new loops
7610   // and can invalidate iterators across the loops.
7611   SmallVector<Loop *, 8> Worklist;
7612 
7613   for (Loop *L : *LI)
7614     collectSupportedLoops(*L, LI, ORE, Worklist);
7615 
7616   LoopsAnalyzed += Worklist.size();
7617 
7618   // Now walk the identified inner loops.
7619   while (!Worklist.empty()) {
7620     Loop *L = Worklist.pop_back_val();
7621 
7622     // For the inner loops we actually process, form LCSSA to simplify the
7623     // transform.
7624     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
7625 
7626     Changed |= processLoop(L);
7627   }
7628 
7629   // Process each loop nest in the function.
7630   return Changed;
7631 }
7632 
7633 PreservedAnalyses LoopVectorizePass::run(Function &F,
7634                                          FunctionAnalysisManager &AM) {
7635     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
7636     auto &LI = AM.getResult<LoopAnalysis>(F);
7637     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
7638     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
7639     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
7640     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
7641     auto &AA = AM.getResult<AAManager>(F);
7642     auto &AC = AM.getResult<AssumptionAnalysis>(F);
7643     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
7644     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
7645 
7646     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
7647     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
7648         [&](Loop &L) -> const LoopAccessInfo & {
7649       LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, nullptr};
7650       return LAM.getResult<LoopAccessAnalysis>(L, AR);
7651     };
7652     bool Changed =
7653         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
7654     if (!Changed)
7655       return PreservedAnalyses::all();
7656     PreservedAnalyses PA;
7657     PA.preserve<LoopAnalysis>();
7658     PA.preserve<DominatorTreeAnalysis>();
7659     PA.preserve<BasicAA>();
7660     PA.preserve<GlobalsAA>();
7661     return PA;
7662 }
7663