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