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