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