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