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