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