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