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