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