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