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