Allow GlobalValues to vectorize with AliasAnalysis
[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. Legalization of the IR is done
12 // in the codegen. However, the vectorizer uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
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/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
85 #include <algorithm>
86 #include <map>
87
88 using namespace llvm;
89
90 static cl::opt<unsigned>
91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92                     cl::desc("Sets the SIMD width. Zero is autoselect."));
93
94 static cl::opt<unsigned>
95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96                     cl::desc("Sets the vectorization unroll count. "
97                              "Zero is autoselect."));
98
99 static cl::opt<bool>
100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101                    cl::desc("Enable if-conversion during vectorization."));
102
103 /// We don't vectorize loops with a known constant trip count below this number.
104 static cl::opt<unsigned>
105 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
106                              cl::Hidden,
107                              cl::desc("Don't vectorize loops with a constant "
108                                       "trip count that is smaller than this "
109                                       "value."));
110
111 /// We don't unroll loops with a known constant trip count below this number.
112 static const unsigned TinyTripCountUnrollThreshold = 128;
113
114 /// When performing a runtime memory check, do not check more than this
115 /// number of pointers. Notice that the check is quadratic!
116 static const unsigned RuntimeMemoryCheckThreshold = 4;
117
118 namespace {
119
120 // Forward declarations.
121 class LoopVectorizationLegality;
122 class LoopVectorizationCostModel;
123
124 /// InnerLoopVectorizer vectorizes loops which contain only one basic
125 /// block to a specified vectorization factor (VF).
126 /// This class performs the widening of scalars into vectors, or multiple
127 /// scalars. This class also implements the following features:
128 /// * It inserts an epilogue loop for handling loops that don't have iteration
129 ///   counts that are known to be a multiple of the vectorization factor.
130 /// * It handles the code generation for reduction variables.
131 /// * Scalarization (implementation using scalars) of un-vectorizable
132 ///   instructions.
133 /// InnerLoopVectorizer does not perform any vectorization-legality
134 /// checks, and relies on the caller to check for the different legality
135 /// aspects. The InnerLoopVectorizer relies on the
136 /// LoopVectorizationLegality class to provide information about the induction
137 /// and reduction variables that were found to a given vectorization factor.
138 class InnerLoopVectorizer {
139 public:
140   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
141                       DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
142                       unsigned UnrollFactor)
143       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
144         UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
145         OldInduction(0), WidenMap(UnrollFactor) {}
146
147   // Perform the actual loop widening (vectorization).
148   void vectorize(LoopVectorizationLegality *Legal) {
149     // Create a new empty loop. Unlink the old loop and connect the new one.
150     createEmptyLoop(Legal);
151     // Widen each instruction in the old loop to a new one in the new loop.
152     // Use the Legality module to find the induction and reduction variables.
153     vectorizeLoop(Legal);
154     // Register the new loop and update the analysis passes.
155     updateAnalysis();
156   }
157
158 private:
159   /// A small list of PHINodes.
160   typedef SmallVector<PHINode*, 4> PhiVector;
161   /// When we unroll loops we have multiple vector values for each scalar.
162   /// This data structure holds the unrolled and vectorized values that
163   /// originated from one scalar instruction.
164   typedef SmallVector<Value*, 2> VectorParts;
165
166   /// Add code that checks at runtime if the accessed arrays overlap.
167   /// Returns the comparator value or NULL if no check is needed.
168   Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
169                                Instruction *Loc);
170   /// Create an empty loop, based on the loop ranges of the old loop.
171   void createEmptyLoop(LoopVectorizationLegality *Legal);
172   /// Copy and widen the instructions from the old loop.
173   void vectorizeLoop(LoopVectorizationLegality *Legal);
174
175   /// A helper function that computes the predicate of the block BB, assuming
176   /// that the header block of the loop is set to True. It returns the *entry*
177   /// mask for the block BB.
178   VectorParts createBlockInMask(BasicBlock *BB);
179   /// A helper function that computes the predicate of the edge between SRC
180   /// and DST.
181   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
182
183   /// A helper function to vectorize a single BB within the innermost loop.
184   void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
185                             PhiVector *PV);
186
187   /// Insert the new loop to the loop hierarchy and pass manager
188   /// and update the analysis passes.
189   void updateAnalysis();
190
191   /// This instruction is un-vectorizable. Implement it as a sequence
192   /// of scalars.
193   void scalarizeInstruction(Instruction *Instr);
194
195   /// Vectorize Load and Store instructions,
196   void vectorizeMemoryInstruction(Instruction *Instr,
197                                   LoopVectorizationLegality *Legal);
198
199   /// Create a broadcast instruction. This method generates a broadcast
200   /// instruction (shuffle) for loop invariant values and for the induction
201   /// value. If this is the induction variable then we extend it to N, N+1, ...
202   /// this is needed because each iteration in the loop corresponds to a SIMD
203   /// element.
204   Value *getBroadcastInstrs(Value *V);
205
206   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
207   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
208   /// The sequence starts at StartIndex.
209   Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
210
211   /// When we go over instructions in the basic block we rely on previous
212   /// values within the current basic block or on loop invariant values.
213   /// When we widen (vectorize) values we place them in the map. If the values
214   /// are not within the map, they have to be loop invariant, so we simply
215   /// broadcast them into a vector.
216   VectorParts &getVectorValue(Value *V);
217
218   /// Generate a shuffle sequence that will reverse the vector Vec.
219   Value *reverseVector(Value *Vec);
220
221   /// This is a helper class that holds the vectorizer state. It maps scalar
222   /// instructions to vector instructions. When the code is 'unrolled' then
223   /// then a single scalar value is mapped to multiple vector parts. The parts
224   /// are stored in the VectorPart type.
225   struct ValueMap {
226     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
227     /// are mapped.
228     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
229
230     /// \return True if 'Key' is saved in the Value Map.
231     bool has(Value *Key) const { return MapStorage.count(Key); }
232
233     /// Initializes a new entry in the map. Sets all of the vector parts to the
234     /// save value in 'Val'.
235     /// \return A reference to a vector with splat values.
236     VectorParts &splat(Value *Key, Value *Val) {
237       VectorParts &Entry = MapStorage[Key];
238       Entry.assign(UF, Val);
239       return Entry;
240     }
241
242     ///\return A reference to the value that is stored at 'Key'.
243     VectorParts &get(Value *Key) {
244       VectorParts &Entry = MapStorage[Key];
245       if (Entry.empty())
246         Entry.resize(UF);
247       assert(Entry.size() == UF);
248       return Entry;
249     }
250
251   private:
252     /// The unroll factor. Each entry in the map stores this number of vector
253     /// elements.
254     unsigned UF;
255
256     /// Map storage. We use std::map and not DenseMap because insertions to a
257     /// dense map invalidates its iterators.
258     std::map<Value *, VectorParts> MapStorage;
259   };
260
261   /// The original loop.
262   Loop *OrigLoop;
263   /// Scev analysis to use.
264   ScalarEvolution *SE;
265   /// Loop Info.
266   LoopInfo *LI;
267   /// Dominator Tree.
268   DominatorTree *DT;
269   /// Data Layout.
270   DataLayout *DL;
271   /// The vectorization SIMD factor to use. Each vector will have this many
272   /// vector elements.
273   unsigned VF;
274   /// The vectorization unroll factor to use. Each scalar is vectorized to this
275   /// many different vector instructions.
276   unsigned UF;
277
278   /// The builder that we use
279   IRBuilder<> Builder;
280
281   // --- Vectorization state ---
282
283   /// The vector-loop preheader.
284   BasicBlock *LoopVectorPreHeader;
285   /// The scalar-loop preheader.
286   BasicBlock *LoopScalarPreHeader;
287   /// Middle Block between the vector and the scalar.
288   BasicBlock *LoopMiddleBlock;
289   ///The ExitBlock of the scalar loop.
290   BasicBlock *LoopExitBlock;
291   ///The vector loop body.
292   BasicBlock *LoopVectorBody;
293   ///The scalar loop body.
294   BasicBlock *LoopScalarBody;
295   /// A list of all bypass blocks. The first block is the entry of the loop.
296   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
297
298   /// The new Induction variable which was added to the new block.
299   PHINode *Induction;
300   /// The induction variable of the old basic block.
301   PHINode *OldInduction;
302   /// Maps scalars to widened vectors.
303   ValueMap WidenMap;
304 };
305
306 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
307 /// to what vectorization factor.
308 /// This class does not look at the profitability of vectorization, only the
309 /// legality. This class has two main kinds of checks:
310 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
311 ///   will change the order of memory accesses in a way that will change the
312 ///   correctness of the program.
313 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
314 /// checks for a number of different conditions, such as the availability of a
315 /// single induction variable, that all types are supported and vectorize-able,
316 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
317 /// This class is also used by InnerLoopVectorizer for identifying
318 /// induction variable and the different reduction variables.
319 class LoopVectorizationLegality {
320 public:
321   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
322                             DominatorTree *DT, TargetTransformInfo* TTI,
323                             AliasAnalysis* AA)
324       : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), Induction(0) {}
325
326   /// This enum represents the kinds of reductions that we support.
327   enum ReductionKind {
328     RK_NoReduction, ///< Not a reduction.
329     RK_IntegerAdd,  ///< Sum of integers.
330     RK_IntegerMult, ///< Product of integers.
331     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
332     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
333     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
334     RK_FloatAdd,    ///< Sum of floats.
335     RK_FloatMult    ///< Product of floats.
336   };
337
338   /// This enum represents the kinds of inductions that we support.
339   enum InductionKind {
340     IK_NoInduction,         ///< Not an induction variable.
341     IK_IntInduction,        ///< Integer induction variable. Step = 1.
342     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
343     IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
344     IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
345   };
346
347   /// This POD struct holds information about reduction variables.
348   struct ReductionDescriptor {
349     ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
350       Kind(RK_NoReduction) {}
351
352     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
353         : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
354
355     // The starting value of the reduction.
356     // It does not have to be zero!
357     Value *StartValue;
358     // The instruction who's value is used outside the loop.
359     Instruction *LoopExitInstr;
360     // The kind of the reduction.
361     ReductionKind Kind;
362   };
363
364   // This POD struct holds information about the memory runtime legality
365   // check that a group of pointers do not overlap.
366   struct RuntimePointerCheck {
367     RuntimePointerCheck() : Need(false) {}
368
369     /// Reset the state of the pointer runtime information.
370     void reset() {
371       Need = false;
372       Pointers.clear();
373       Starts.clear();
374       Ends.clear();
375     }
376
377     /// Insert a pointer and calculate the start and end SCEVs.
378     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
379
380     /// This flag indicates if we need to add the runtime check.
381     bool Need;
382     /// Holds the pointers that we need to check.
383     SmallVector<Value*, 2> Pointers;
384     /// Holds the pointer value at the beginning of the loop.
385     SmallVector<const SCEV*, 2> Starts;
386     /// Holds the pointer value at the end of the loop.
387     SmallVector<const SCEV*, 2> Ends;
388   };
389
390   /// A POD for saving information about induction variables.
391   struct InductionInfo {
392     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
393     InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
394     /// Start value.
395     Value *StartValue;
396     /// Induction kind.
397     InductionKind IK;
398   };
399
400   /// ReductionList contains the reduction descriptors for all
401   /// of the reductions that were found in the loop.
402   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
403
404   /// InductionList saves induction variables and maps them to the
405   /// induction descriptor.
406   typedef MapVector<PHINode*, InductionInfo> InductionList;
407
408   /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
409   /// respective Store/Load instruction(s) to calculate aliasing.
410   typedef DenseMap<Value*, Instruction* > AliasMap;
411   typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
412
413   /// Returns true if it is legal to vectorize this loop.
414   /// This does not mean that it is profitable to vectorize this
415   /// loop, only that it is legal to do so.
416   bool canVectorize();
417
418   /// Returns the Induction variable.
419   PHINode *getInduction() { return Induction; }
420
421   /// Returns the reduction variables found in the loop.
422   ReductionList *getReductionVars() { return &Reductions; }
423
424   /// Returns the induction variables found in the loop.
425   InductionList *getInductionVars() { return &Inductions; }
426
427   /// Returns True if V is an induction variable in this loop.
428   bool isInductionVariable(const Value *V);
429
430   /// Return true if the block BB needs to be predicated in order for the loop
431   /// to be vectorized.
432   bool blockNeedsPredication(BasicBlock *BB);
433
434   /// Check if this  pointer is consecutive when vectorizing. This happens
435   /// when the last index of the GEP is the induction variable, or that the
436   /// pointer itself is an induction variable.
437   /// This check allows us to vectorize A[idx] into a wide load/store.
438   /// Returns:
439   /// 0 - Stride is unknown or non consecutive.
440   /// 1 - Address is consecutive.
441   /// -1 - Address is consecutive, and decreasing.
442   int isConsecutivePtr(Value *Ptr);
443
444   /// Returns true if the value V is uniform within the loop.
445   bool isUniform(Value *V);
446
447   /// Returns true if this instruction will remain scalar after vectorization.
448   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
449
450   /// Returns the information that we collected about runtime memory check.
451   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
452 private:
453   /// Check if a single basic block loop is vectorizable.
454   /// At this point we know that this is a loop with a constant trip count
455   /// and we only need to check individual instructions.
456   bool canVectorizeInstrs();
457
458   /// When we vectorize loops we may change the order in which
459   /// we read and write from memory. This method checks if it is
460   /// legal to vectorize the code, considering only memory constrains.
461   /// Returns true if the loop is vectorizable
462   bool canVectorizeMemory();
463
464   /// Return true if we can vectorize this loop using the IF-conversion
465   /// transformation.
466   bool canVectorizeWithIfConvert();
467
468   /// Collect the variables that need to stay uniform after vectorization.
469   void collectLoopUniforms();
470
471   /// Return true if all of the instructions in the block can be speculatively
472   /// executed.
473   bool blockCanBePredicated(BasicBlock *BB);
474
475   /// Returns True, if 'Phi' is the kind of reduction variable for type
476   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
477   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
478   /// Returns true if the instruction I can be a reduction variable of type
479   /// 'Kind'.
480   bool isReductionInstr(Instruction *I, ReductionKind Kind);
481   /// Returns the induction kind of Phi. This function may return NoInduction
482   /// if the PHI is not an induction variable.
483   InductionKind isInductionVariable(PHINode *Phi);
484   /// Return true if can compute the address bounds of Ptr within the loop.
485   bool hasComputableBounds(Value *Ptr);
486   /// Return true if there is the chance of write reorder.
487   bool hasPossibleGlobalWriteReorder(Value *Object,
488                                      Instruction *Inst,
489                                      AliasMultiMap &WriteObjects,
490                                      unsigned MaxByteWidth);
491   /// Return the AA location for a load or a store.
492   AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
493
494
495   /// The loop that we evaluate.
496   Loop *TheLoop;
497   /// Scev analysis.
498   ScalarEvolution *SE;
499   /// DataLayout analysis.
500   DataLayout *DL;
501   /// Dominators.
502   DominatorTree *DT;
503   /// Target Info.
504   TargetTransformInfo *TTI;
505   /// Alias Analysis.
506   AliasAnalysis *AA;
507
508   //  ---  vectorization state --- //
509
510   /// Holds the integer induction variable. This is the counter of the
511   /// loop.
512   PHINode *Induction;
513   /// Holds the reduction variables.
514   ReductionList Reductions;
515   /// Holds all of the induction variables that we found in the loop.
516   /// Notice that inductions don't need to start at zero and that induction
517   /// variables can be pointers.
518   InductionList Inductions;
519
520   /// Allowed outside users. This holds the reduction
521   /// vars which can be accessed from outside the loop.
522   SmallPtrSet<Value*, 4> AllowedExit;
523   /// This set holds the variables which are known to be uniform after
524   /// vectorization.
525   SmallPtrSet<Instruction*, 4> Uniforms;
526   /// We need to check that all of the pointers in this list are disjoint
527   /// at runtime.
528   RuntimePointerCheck PtrRtCheck;
529 };
530
531 /// LoopVectorizationCostModel - estimates the expected speedups due to
532 /// vectorization.
533 /// In many cases vectorization is not profitable. This can happen because of
534 /// a number of reasons. In this class we mainly attempt to predict the
535 /// expected speedup/slowdowns due to the supported instruction set. We use the
536 /// TargetTransformInfo to query the different backends for the cost of
537 /// different operations.
538 class LoopVectorizationCostModel {
539 public:
540   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
541                              LoopVectorizationLegality *Legal,
542                              const TargetTransformInfo &TTI,
543                              DataLayout *DL)
544       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL) {}
545
546   /// Information about vectorization costs
547   struct VectorizationFactor {
548     unsigned Width; // Vector width with best cost
549     unsigned Cost; // Cost of the loop with that width
550   };
551   /// \return The most profitable vectorization factor and the cost of that VF.
552   /// This method checks every power of two up to VF. If UserVF is not ZERO
553   /// then this vectorization factor will be selected if vectorization is
554   /// possible.
555   VectorizationFactor selectVectorizationFactor(bool OptForSize,
556                                                 unsigned UserVF);
557
558   /// \return The size (in bits) of the widest type in the code that
559   /// needs to be vectorized. We ignore values that remain scalar such as
560   /// 64 bit loop indices.
561   unsigned getWidestType();
562
563   /// \return The most profitable unroll factor.
564   /// If UserUF is non-zero then this method finds the best unroll-factor
565   /// based on register pressure and other parameters.
566   /// VF and LoopCost are the selected vectorization factor and the cost of the
567   /// selected VF.
568   unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
569                               unsigned LoopCost);
570
571   /// \brief A struct that represents some properties of the register usage
572   /// of a loop.
573   struct RegisterUsage {
574     /// Holds the number of loop invariant values that are used in the loop.
575     unsigned LoopInvariantRegs;
576     /// Holds the maximum number of concurrent live intervals in the loop.
577     unsigned MaxLocalUsers;
578     /// Holds the number of instructions in the loop.
579     unsigned NumInstructions;
580   };
581
582   /// \return  information about the register usage of the loop.
583   RegisterUsage calculateRegisterUsage();
584
585 private:
586   /// Returns the expected execution cost. The unit of the cost does
587   /// not matter because we use the 'cost' units to compare different
588   /// vector widths. The cost that is returned is *not* normalized by
589   /// the factor width.
590   unsigned expectedCost(unsigned VF);
591
592   /// Returns the execution time cost of an instruction for a given vector
593   /// width. Vector width of one means scalar.
594   unsigned getInstructionCost(Instruction *I, unsigned VF);
595
596   /// A helper function for converting Scalar types to vector types.
597   /// If the incoming type is void, we return void. If the VF is 1, we return
598   /// the scalar type.
599   static Type* ToVectorTy(Type *Scalar, unsigned VF);
600
601   /// Returns whether the instruction is a load or store and will be a emitted
602   /// as a vector operation.
603   bool isConsecutiveLoadOrStore(Instruction *I);
604
605   /// The loop that we evaluate.
606   Loop *TheLoop;
607   /// Scev analysis.
608   ScalarEvolution *SE;
609   /// Loop Info analysis.
610   LoopInfo *LI;
611   /// Vectorization legality.
612   LoopVectorizationLegality *Legal;
613   /// Vector target information.
614   const TargetTransformInfo &TTI;
615   /// Target data layout information.
616   DataLayout *DL;
617 };
618
619 /// The LoopVectorize Pass.
620 struct LoopVectorize : public LoopPass {
621   /// Pass identification, replacement for typeid
622   static char ID;
623
624   explicit LoopVectorize() : LoopPass(ID) {
625     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
626   }
627
628   ScalarEvolution *SE;
629   DataLayout *DL;
630   LoopInfo *LI;
631   TargetTransformInfo *TTI;
632   DominatorTree *DT;
633   AliasAnalysis *AA;
634
635   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
636     // We only vectorize innermost loops.
637     if (!L->empty())
638       return false;
639
640     SE = &getAnalysis<ScalarEvolution>();
641     DL = getAnalysisIfAvailable<DataLayout>();
642     LI = &getAnalysis<LoopInfo>();
643     TTI = &getAnalysis<TargetTransformInfo>();
644     DT = &getAnalysis<DominatorTree>();
645     AA = getAnalysisIfAvailable<AliasAnalysis>();
646
647     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
648           L->getHeader()->getParent()->getName() << "\"\n");
649
650     // Check if it is legal to vectorize the loop.
651     LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA);
652     if (!LVL.canVectorize()) {
653       DEBUG(dbgs() << "LV: Not vectorizing.\n");
654       return false;
655     }
656
657     // Use the cost model.
658     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL);
659
660     // Check the function attributes to find out if this function should be
661     // optimized for size.
662     Function *F = L->getHeader()->getParent();
663     Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
664     Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
665     unsigned FnIndex = AttributeSet::FunctionIndex;
666     bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
667     bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
668
669     if (NoFloat) {
670       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
671             "attribute is used.\n");
672       return false;
673     }
674
675     // Select the optimal vectorization factor.
676     LoopVectorizationCostModel::VectorizationFactor VF;
677     VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
678     // Select the unroll factor.
679     unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
680                                         VF.Width, VF.Cost);
681
682     if (VF.Width == 1) {
683       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
684       return false;
685     }
686
687     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
688           F->getParent()->getModuleIdentifier()<<"\n");
689     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
690
691     // If we decided that it is *legal* to vectorize the loop then do it.
692     InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF.Width, UF);
693     LB.vectorize(&LVL);
694
695     DEBUG(verifyFunction(*L->getHeader()->getParent()));
696     return true;
697   }
698
699   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
700     LoopPass::getAnalysisUsage(AU);
701     AU.addRequiredID(LoopSimplifyID);
702     AU.addRequiredID(LCSSAID);
703     AU.addRequired<DominatorTree>();
704     AU.addRequired<LoopInfo>();
705     AU.addRequired<ScalarEvolution>();
706     AU.addRequired<TargetTransformInfo>();
707     AU.addPreserved<LoopInfo>();
708     AU.addPreserved<DominatorTree>();
709   }
710
711 };
712
713 } // end anonymous namespace
714
715 //===----------------------------------------------------------------------===//
716 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
717 // LoopVectorizationCostModel.
718 //===----------------------------------------------------------------------===//
719
720 void
721 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
722                                                        Loop *Lp, Value *Ptr) {
723   const SCEV *Sc = SE->getSCEV(Ptr);
724   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
725   assert(AR && "Invalid addrec expression");
726   const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
727   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
728   Pointers.push_back(Ptr);
729   Starts.push_back(AR->getStart());
730   Ends.push_back(ScEnd);
731 }
732
733 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
734   // Save the current insertion location.
735   Instruction *Loc = Builder.GetInsertPoint();
736
737   // We need to place the broadcast of invariant variables outside the loop.
738   Instruction *Instr = dyn_cast<Instruction>(V);
739   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
740   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
741
742   // Place the code for broadcasting invariant variables in the new preheader.
743   if (Invariant)
744     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
745
746   // Broadcast the scalar into all locations in the vector.
747   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
748
749   // Restore the builder insertion point.
750   if (Invariant)
751     Builder.SetInsertPoint(Loc);
752
753   return Shuf;
754 }
755
756 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
757                                                  bool Negate) {
758   assert(Val->getType()->isVectorTy() && "Must be a vector");
759   assert(Val->getType()->getScalarType()->isIntegerTy() &&
760          "Elem must be an integer");
761   // Create the types.
762   Type *ITy = Val->getType()->getScalarType();
763   VectorType *Ty = cast<VectorType>(Val->getType());
764   int VLen = Ty->getNumElements();
765   SmallVector<Constant*, 8> Indices;
766
767   // Create a vector of consecutive numbers from zero to VF.
768   for (int i = 0; i < VLen; ++i) {
769     int Idx = Negate ? (-i): i;
770     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
771   }
772
773   // Add the consecutive indices to the vector value.
774   Constant *Cv = ConstantVector::get(Indices);
775   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
776   return Builder.CreateAdd(Val, Cv, "induction");
777 }
778
779 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
780   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
781   // Make sure that the pointer does not point to structs.
782   if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
783     return 0;
784
785   // If this value is a pointer induction variable we know it is consecutive.
786   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
787   if (Phi && Inductions.count(Phi)) {
788     InductionInfo II = Inductions[Phi];
789     if (IK_PtrInduction == II.IK)
790       return 1;
791     else if (IK_ReversePtrInduction == II.IK)
792       return -1;
793   }
794
795   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
796   if (!Gep)
797     return 0;
798
799   unsigned NumOperands = Gep->getNumOperands();
800   Value *LastIndex = Gep->getOperand(NumOperands - 1);
801
802   Value *GpPtr = Gep->getPointerOperand();
803   // If this GEP value is a consecutive pointer induction variable and all of
804   // the indices are constant then we know it is consecutive. We can
805   Phi = dyn_cast<PHINode>(GpPtr);
806   if (Phi && Inductions.count(Phi)) {
807
808     // Make sure that the pointer does not point to structs.
809     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
810     if (GepPtrType->getElementType()->isAggregateType())
811       return 0;
812
813     // Make sure that all of the index operands are loop invariant.
814     for (unsigned i = 1; i < NumOperands; ++i)
815       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
816         return 0;
817
818     InductionInfo II = Inductions[Phi];
819     if (IK_PtrInduction == II.IK)
820       return 1;
821     else if (IK_ReversePtrInduction == II.IK)
822       return -1;
823   }
824
825   // Check that all of the gep indices are uniform except for the last.
826   for (unsigned i = 0; i < NumOperands - 1; ++i)
827     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
828       return 0;
829
830   // We can emit wide load/stores only if the last index is the induction
831   // variable.
832   const SCEV *Last = SE->getSCEV(LastIndex);
833   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
834     const SCEV *Step = AR->getStepRecurrence(*SE);
835
836     // The memory is consecutive because the last index is consecutive
837     // and all other indices are loop invariant.
838     if (Step->isOne())
839       return 1;
840     if (Step->isAllOnesValue())
841       return -1;
842   }
843
844   return 0;
845 }
846
847 bool LoopVectorizationLegality::isUniform(Value *V) {
848   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
849 }
850
851 InnerLoopVectorizer::VectorParts&
852 InnerLoopVectorizer::getVectorValue(Value *V) {
853   assert(V != Induction && "The new induction variable should not be used.");
854   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
855
856   // If we have this scalar in the map, return it.
857   if (WidenMap.has(V))
858     return WidenMap.get(V);
859
860   // If this scalar is unknown, assume that it is a constant or that it is
861   // loop invariant. Broadcast V and save the value for future uses.
862   Value *B = getBroadcastInstrs(V);
863   return WidenMap.splat(V, B);
864 }
865
866 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
867   assert(Vec->getType()->isVectorTy() && "Invalid type");
868   SmallVector<Constant*, 8> ShuffleMask;
869   for (unsigned i = 0; i < VF; ++i)
870     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
871
872   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
873                                      ConstantVector::get(ShuffleMask),
874                                      "reverse");
875 }
876
877
878 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
879                                              LoopVectorizationLegality *Legal) {
880   // Attempt to issue a wide load.
881   LoadInst *LI = dyn_cast<LoadInst>(Instr);
882   StoreInst *SI = dyn_cast<StoreInst>(Instr);
883
884   assert((LI || SI) && "Invalid Load/Store instruction");
885
886   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
887   Type *DataTy = VectorType::get(ScalarDataTy, VF);
888   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
889   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
890
891   // If the pointer is loop invariant or if it is non consecutive,
892   // scalarize the load.
893   int Stride = Legal->isConsecutivePtr(Ptr);
894   bool Reverse = Stride < 0;
895   bool UniformLoad = LI && Legal->isUniform(Ptr);
896   if (Stride == 0 || UniformLoad)
897     return scalarizeInstruction(Instr);
898
899   Constant *Zero = Builder.getInt32(0);
900   VectorParts &Entry = WidenMap.get(Instr);
901
902   // Handle consecutive loads/stores.
903   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
904   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
905     Value *PtrOperand = Gep->getPointerOperand();
906     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
907     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
908
909     // Create the new GEP with the new induction variable.
910     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
911     Gep2->setOperand(0, FirstBasePtr);
912     Gep2->setName("gep.indvar.base");
913     Ptr = Builder.Insert(Gep2);
914   } else if (Gep) {
915     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
916                                OrigLoop) && "Base ptr must be invariant");
917
918     // The last index does not have to be the induction. It can be
919     // consecutive and be a function of the index. For example A[I+1];
920     unsigned NumOperands = Gep->getNumOperands();
921
922     Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
923     VectorParts &GEPParts = getVectorValue(LastGepOperand);
924     Value *LastIndex = GEPParts[0];
925     LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
926
927     // Create the new GEP with the new induction variable.
928     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
929     Gep2->setOperand(NumOperands - 1, LastIndex);
930     Gep2->setName("gep.indvar.idx");
931     Ptr = Builder.Insert(Gep2);
932   } else {
933     // Use the induction element ptr.
934     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
935     VectorParts &PtrVal = getVectorValue(Ptr);
936     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
937   }
938
939   // Handle Stores:
940   if (SI) {
941     assert(!Legal->isUniform(SI->getPointerOperand()) &&
942            "We do not allow storing to uniform addresses");
943
944     VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
945     for (unsigned Part = 0; Part < UF; ++Part) {
946       // Calculate the pointer for the specific unroll-part.
947       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
948
949       if (Reverse) {
950         // If we store to reverse consecutive memory locations then we need
951         // to reverse the order of elements in the stored value.
952         StoredVal[Part] = reverseVector(StoredVal[Part]);
953         // If the address is consecutive but reversed, then the
954         // wide store needs to start at the last vector element.
955         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
956         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
957       }
958
959       Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
960       Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
961     }
962   }
963
964   for (unsigned Part = 0; Part < UF; ++Part) {
965     // Calculate the pointer for the specific unroll-part.
966     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
967
968     if (Reverse) {
969       // If the address is consecutive but reversed, then the
970       // wide store needs to start at the last vector element.
971       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
972       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
973     }
974
975     Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
976     Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
977     cast<LoadInst>(LI)->setAlignment(Alignment);
978     Entry[Part] = Reverse ? reverseVector(LI) :  LI;
979   }
980 }
981
982 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
983   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
984   // Holds vector parameters or scalars, in case of uniform vals.
985   SmallVector<VectorParts, 4> Params;
986
987   // Find all of the vectorized parameters.
988   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
989     Value *SrcOp = Instr->getOperand(op);
990
991     // If we are accessing the old induction variable, use the new one.
992     if (SrcOp == OldInduction) {
993       Params.push_back(getVectorValue(SrcOp));
994       continue;
995     }
996
997     // Try using previously calculated values.
998     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
999
1000     // If the src is an instruction that appeared earlier in the basic block
1001     // then it should already be vectorized.
1002     if (SrcInst && OrigLoop->contains(SrcInst)) {
1003       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1004       // The parameter is a vector value from earlier.
1005       Params.push_back(WidenMap.get(SrcInst));
1006     } else {
1007       // The parameter is a scalar from outside the loop. Maybe even a constant.
1008       VectorParts Scalars;
1009       Scalars.append(UF, SrcOp);
1010       Params.push_back(Scalars);
1011     }
1012   }
1013
1014   assert(Params.size() == Instr->getNumOperands() &&
1015          "Invalid number of operands");
1016
1017   // Does this instruction return a value ?
1018   bool IsVoidRetTy = Instr->getType()->isVoidTy();
1019
1020   Value *UndefVec = IsVoidRetTy ? 0 :
1021     UndefValue::get(VectorType::get(Instr->getType(), VF));
1022   // Create a new entry in the WidenMap and initialize it to Undef or Null.
1023   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1024
1025   // For each scalar that we create:
1026   for (unsigned Width = 0; Width < VF; ++Width) {
1027     // For each vector unroll 'part':
1028     for (unsigned Part = 0; Part < UF; ++Part) {
1029       Instruction *Cloned = Instr->clone();
1030       if (!IsVoidRetTy)
1031         Cloned->setName(Instr->getName() + ".cloned");
1032       // Replace the operands of the cloned instrucions with extracted scalars.
1033       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1034         Value *Op = Params[op][Part];
1035         // Param is a vector. Need to extract the right lane.
1036         if (Op->getType()->isVectorTy())
1037           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1038         Cloned->setOperand(op, Op);
1039       }
1040
1041       // Place the cloned scalar in the new loop.
1042       Builder.Insert(Cloned);
1043
1044       // If the original scalar returns a value we need to place it in a vector
1045       // so that future users will be able to use it.
1046       if (!IsVoidRetTy)
1047         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1048                                                        Builder.getInt32(Width));
1049     }
1050   }
1051 }
1052
1053 Instruction *
1054 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1055                                      Instruction *Loc) {
1056   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1057   Legal->getRuntimePointerCheck();
1058
1059   if (!PtrRtCheck->Need)
1060     return NULL;
1061
1062   Instruction *MemoryRuntimeCheck = 0;
1063   unsigned NumPointers = PtrRtCheck->Pointers.size();
1064   SmallVector<Value* , 2> Starts;
1065   SmallVector<Value* , 2> Ends;
1066
1067   SCEVExpander Exp(*SE, "induction");
1068
1069   // Use this type for pointer arithmetic.
1070   Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1071
1072   for (unsigned i = 0; i < NumPointers; ++i) {
1073     Value *Ptr = PtrRtCheck->Pointers[i];
1074     const SCEV *Sc = SE->getSCEV(Ptr);
1075
1076     if (SE->isLoopInvariant(Sc, OrigLoop)) {
1077       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1078             *Ptr <<"\n");
1079       Starts.push_back(Ptr);
1080       Ends.push_back(Ptr);
1081     } else {
1082       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1083
1084       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1085       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1086       Starts.push_back(Start);
1087       Ends.push_back(End);
1088     }
1089   }
1090
1091   IRBuilder<> ChkBuilder(Loc);
1092
1093   for (unsigned i = 0; i < NumPointers; ++i) {
1094     for (unsigned j = i+1; j < NumPointers; ++j) {
1095       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1096       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1097       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy, "bc");
1098       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy, "bc");
1099
1100       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1101       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1102       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1103       if (MemoryRuntimeCheck)
1104         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1105                                          "conflict.rdx");
1106
1107       MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1108     }
1109   }
1110
1111   return MemoryRuntimeCheck;
1112 }
1113
1114 void
1115 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1116   /*
1117    In this function we generate a new loop. The new loop will contain
1118    the vectorized instructions while the old loop will continue to run the
1119    scalar remainder.
1120
1121        [ ] <-- vector loop bypass (may consist of multiple blocks).
1122      /  |
1123     /   v
1124    |   [ ]     <-- vector pre header.
1125    |    |
1126    |    v
1127    |   [  ] \
1128    |   [  ]_|   <-- vector loop.
1129    |    |
1130     \   v
1131       >[ ]   <--- middle-block.
1132      /  |
1133     /   v
1134    |   [ ]     <--- new preheader.
1135    |    |
1136    |    v
1137    |   [ ] \
1138    |   [ ]_|   <-- old scalar loop to handle remainder.
1139     \   |
1140      \  v
1141       >[ ]     <-- exit block.
1142    ...
1143    */
1144
1145   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1146   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1147   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1148   assert(ExitBlock && "Must have an exit block");
1149
1150   // Some loops have a single integer induction variable, while other loops
1151   // don't. One example is c++ iterators that often have multiple pointer
1152   // induction variables. In the code below we also support a case where we
1153   // don't have a single induction variable.
1154   OldInduction = Legal->getInduction();
1155   Type *IdxTy = OldInduction ? OldInduction->getType() :
1156   DL->getIntPtrType(SE->getContext());
1157
1158   // Find the loop boundaries.
1159   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1160   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1161
1162   // Get the total trip count from the count by adding 1.
1163   ExitCount = SE->getAddExpr(ExitCount,
1164                              SE->getConstant(ExitCount->getType(), 1));
1165
1166   // Expand the trip count and place the new instructions in the preheader.
1167   // Notice that the pre-header does not change, only the loop body.
1168   SCEVExpander Exp(*SE, "induction");
1169
1170   // Count holds the overall loop count (N).
1171   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1172                                    BypassBlock->getTerminator());
1173
1174   // The loop index does not have to start at Zero. Find the original start
1175   // value from the induction PHI node. If we don't have an induction variable
1176   // then we know that it starts at zero.
1177   Value *StartIdx = OldInduction ?
1178   OldInduction->getIncomingValueForBlock(BypassBlock):
1179   ConstantInt::get(IdxTy, 0);
1180
1181   assert(BypassBlock && "Invalid loop structure");
1182   LoopBypassBlocks.push_back(BypassBlock);
1183
1184   // Split the single block loop into the two loop structure described above.
1185   BasicBlock *VectorPH =
1186   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1187   BasicBlock *VecBody =
1188   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1189   BasicBlock *MiddleBlock =
1190   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1191   BasicBlock *ScalarPH =
1192   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1193
1194   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1195   // inside the loop.
1196   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1197
1198   // Generate the induction variable.
1199   Induction = Builder.CreatePHI(IdxTy, 2, "index");
1200   // The loop step is equal to the vectorization factor (num of SIMD elements)
1201   // times the unroll factor (num of SIMD instructions).
1202   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1203
1204   // This is the IR builder that we use to add all of the logic for bypassing
1205   // the new vector loop.
1206   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1207
1208   // We may need to extend the index in case there is a type mismatch.
1209   // We know that the count starts at zero and does not overflow.
1210   if (Count->getType() != IdxTy) {
1211     // The exit count can be of pointer type. Convert it to the correct
1212     // integer type.
1213     if (ExitCount->getType()->isPointerTy())
1214       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1215     else
1216       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1217   }
1218
1219   // Add the start index to the loop count to get the new end index.
1220   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1221
1222   // Now we need to generate the expression for N - (N % VF), which is
1223   // the part that the vectorized body will execute.
1224   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1225   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1226   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1227                                                      "end.idx.rnd.down");
1228
1229   // Now, compare the new count to zero. If it is zero skip the vector loop and
1230   // jump to the scalar loop.
1231   Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1232                                           "cmp.zero");
1233
1234   BasicBlock *LastBypassBlock = BypassBlock;
1235
1236   // Generate the code that checks in runtime if arrays overlap. We put the
1237   // checks into a separate block to make the more common case of few elements
1238   // faster.
1239   Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1240                                                  BypassBlock->getTerminator());
1241   if (MemRuntimeCheck) {
1242     // Create a new block containing the memory check.
1243     BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1244                                                           "vector.memcheck");
1245     LoopBypassBlocks.push_back(CheckBlock);
1246
1247     // Replace the branch into the memory check block with a conditional branch
1248     // for the "few elements case".
1249     Instruction *OldTerm = BypassBlock->getTerminator();
1250     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1251     OldTerm->eraseFromParent();
1252
1253     Cmp = MemRuntimeCheck;
1254     LastBypassBlock = CheckBlock;
1255   }
1256
1257   LastBypassBlock->getTerminator()->eraseFromParent();
1258   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1259                      LastBypassBlock);
1260
1261   // We are going to resume the execution of the scalar loop.
1262   // Go over all of the induction variables that we found and fix the
1263   // PHIs that are left in the scalar version of the loop.
1264   // The starting values of PHI nodes depend on the counter of the last
1265   // iteration in the vectorized loop.
1266   // If we come from a bypass edge then we need to start from the original
1267   // start value.
1268
1269   // This variable saves the new starting index for the scalar loop.
1270   PHINode *ResumeIndex = 0;
1271   LoopVectorizationLegality::InductionList::iterator I, E;
1272   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1273   for (I = List->begin(), E = List->end(); I != E; ++I) {
1274     PHINode *OrigPhi = I->first;
1275     LoopVectorizationLegality::InductionInfo II = I->second;
1276     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1277                                          MiddleBlock->getTerminator());
1278     Value *EndValue = 0;
1279     switch (II.IK) {
1280     case LoopVectorizationLegality::IK_NoInduction:
1281       llvm_unreachable("Unknown induction");
1282     case LoopVectorizationLegality::IK_IntInduction: {
1283       // Handle the integer induction counter:
1284       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1285       assert(OrigPhi == OldInduction && "Unknown integer PHI");
1286       // We know what the end value is.
1287       EndValue = IdxEndRoundDown;
1288       // We also know which PHI node holds it.
1289       ResumeIndex = ResumeVal;
1290       break;
1291     }
1292     case LoopVectorizationLegality::IK_ReverseIntInduction: {
1293       // Convert the CountRoundDown variable to the PHI size.
1294       unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1295       unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1296       Value *CRD = CountRoundDown;
1297       if (CRDSize > IISize)
1298         CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1299                                II.StartValue->getType(), "tr.crd",
1300                                LoopBypassBlocks.back()->getTerminator());
1301       else if (CRDSize < IISize)
1302         CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1303                                II.StartValue->getType(),
1304                                "sext.crd",
1305                                LoopBypassBlocks.back()->getTerminator());
1306       // Handle reverse integer induction counter:
1307       EndValue =
1308         BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1309                                   LoopBypassBlocks.back()->getTerminator());
1310       break;
1311     }
1312     case LoopVectorizationLegality::IK_PtrInduction: {
1313       // For pointer induction variables, calculate the offset using
1314       // the end index.
1315       EndValue =
1316         GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1317                                   LoopBypassBlocks.back()->getTerminator());
1318       break;
1319     }
1320     case LoopVectorizationLegality::IK_ReversePtrInduction: {
1321       // The value at the end of the loop for the reverse pointer is calculated
1322       // by creating a GEP with a negative index starting from the start value.
1323       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1324       Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1325                                   "rev.ind.end",
1326                                   LoopBypassBlocks.back()->getTerminator());
1327       EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1328                                   "rev.ptr.ind.end",
1329                                   LoopBypassBlocks.back()->getTerminator());
1330       break;
1331     }
1332     }// end of case
1333
1334     // The new PHI merges the original incoming value, in case of a bypass,
1335     // or the value at the end of the vectorized loop.
1336     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1337       ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1338     ResumeVal->addIncoming(EndValue, VecBody);
1339
1340     // Fix the scalar body counter (PHI node).
1341     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1342     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1343   }
1344
1345   // If we are generating a new induction variable then we also need to
1346   // generate the code that calculates the exit value. This value is not
1347   // simply the end of the counter because we may skip the vectorized body
1348   // in case of a runtime check.
1349   if (!OldInduction){
1350     assert(!ResumeIndex && "Unexpected resume value found");
1351     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1352                                   MiddleBlock->getTerminator());
1353     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1354       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1355     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1356   }
1357
1358   // Make sure that we found the index where scalar loop needs to continue.
1359   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1360          "Invalid resume Index");
1361
1362   // Add a check in the middle block to see if we have completed
1363   // all of the iterations in the first vector loop.
1364   // If (N - N%VF) == N, then we *don't* need to run the remainder.
1365   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1366                                 ResumeIndex, "cmp.n",
1367                                 MiddleBlock->getTerminator());
1368
1369   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1370   // Remove the old terminator.
1371   MiddleBlock->getTerminator()->eraseFromParent();
1372
1373   // Create i+1 and fill the PHINode.
1374   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1375   Induction->addIncoming(StartIdx, VectorPH);
1376   Induction->addIncoming(NextIdx, VecBody);
1377   // Create the compare.
1378   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1379   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1380
1381   // Now we have two terminators. Remove the old one from the block.
1382   VecBody->getTerminator()->eraseFromParent();
1383
1384   // Get ready to start creating new instructions into the vectorized body.
1385   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1386
1387   // Create and register the new vector loop.
1388   Loop* Lp = new Loop();
1389   Loop *ParentLoop = OrigLoop->getParentLoop();
1390
1391   // Insert the new loop into the loop nest and register the new basic blocks.
1392   if (ParentLoop) {
1393     ParentLoop->addChildLoop(Lp);
1394     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1395       ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1396     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1397     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1398     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1399   } else {
1400     LI->addTopLevelLoop(Lp);
1401   }
1402
1403   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1404
1405   // Save the state.
1406   LoopVectorPreHeader = VectorPH;
1407   LoopScalarPreHeader = ScalarPH;
1408   LoopMiddleBlock = MiddleBlock;
1409   LoopExitBlock = ExitBlock;
1410   LoopVectorBody = VecBody;
1411   LoopScalarBody = OldBasicBlock;
1412 }
1413
1414 /// This function returns the identity element (or neutral element) for
1415 /// the operation K.
1416 static Constant*
1417 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1418   switch (K) {
1419   case LoopVectorizationLegality:: RK_IntegerXor:
1420   case LoopVectorizationLegality:: RK_IntegerAdd:
1421   case LoopVectorizationLegality:: RK_IntegerOr:
1422     // Adding, Xoring, Oring zero to a number does not change it.
1423     return ConstantInt::get(Tp, 0);
1424   case LoopVectorizationLegality:: RK_IntegerMult:
1425     // Multiplying a number by 1 does not change it.
1426     return ConstantInt::get(Tp, 1);
1427   case LoopVectorizationLegality:: RK_IntegerAnd:
1428     // AND-ing a number with an all-1 value does not change it.
1429     return ConstantInt::get(Tp, -1, true);
1430   case LoopVectorizationLegality:: RK_FloatMult:
1431     // Multiplying a number by 1 does not change it.
1432     return ConstantFP::get(Tp, 1.0L);
1433   case LoopVectorizationLegality:: RK_FloatAdd:
1434     // Adding zero to a number does not change it.
1435     return ConstantFP::get(Tp, 0.0L);
1436   default:
1437     llvm_unreachable("Unknown reduction kind");
1438   }
1439 }
1440
1441 static bool
1442 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1443   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1444   if (!II)
1445     return false;
1446   switch (II->getIntrinsicID()) {
1447   case Intrinsic::sqrt:
1448   case Intrinsic::sin:
1449   case Intrinsic::cos:
1450   case Intrinsic::exp:
1451   case Intrinsic::exp2:
1452   case Intrinsic::log:
1453   case Intrinsic::log10:
1454   case Intrinsic::log2:
1455   case Intrinsic::fabs:
1456   case Intrinsic::floor:
1457   case Intrinsic::ceil:
1458   case Intrinsic::trunc:
1459   case Intrinsic::rint:
1460   case Intrinsic::nearbyint:
1461   case Intrinsic::pow:
1462   case Intrinsic::fma:
1463   case Intrinsic::fmuladd:
1464     return true;
1465   default:
1466     return false;
1467   }
1468   return false;
1469 }
1470
1471 /// This function translates the reduction kind to an LLVM binary operator.
1472 static Instruction::BinaryOps
1473 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1474   switch (Kind) {
1475     case LoopVectorizationLegality::RK_IntegerAdd:
1476       return Instruction::Add;
1477     case LoopVectorizationLegality::RK_IntegerMult:
1478       return Instruction::Mul;
1479     case LoopVectorizationLegality::RK_IntegerOr:
1480       return Instruction::Or;
1481     case LoopVectorizationLegality::RK_IntegerAnd:
1482       return Instruction::And;
1483     case LoopVectorizationLegality::RK_IntegerXor:
1484       return Instruction::Xor;
1485     case LoopVectorizationLegality::RK_FloatMult:
1486       return Instruction::FMul;
1487     case LoopVectorizationLegality::RK_FloatAdd:
1488       return Instruction::FAdd;
1489     default:
1490       llvm_unreachable("Unknown reduction operation");
1491   }
1492 }
1493
1494 void
1495 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1496   //===------------------------------------------------===//
1497   //
1498   // Notice: any optimization or new instruction that go
1499   // into the code below should be also be implemented in
1500   // the cost-model.
1501   //
1502   //===------------------------------------------------===//
1503   Constant *Zero = Builder.getInt32(0);
1504
1505   // In order to support reduction variables we need to be able to vectorize
1506   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1507   // stages. First, we create a new vector PHI node with no incoming edges.
1508   // We use this value when we vectorize all of the instructions that use the
1509   // PHI. Next, after all of the instructions in the block are complete we
1510   // add the new incoming edges to the PHI. At this point all of the
1511   // instructions in the basic block are vectorized, so we can use them to
1512   // construct the PHI.
1513   PhiVector RdxPHIsToFix;
1514
1515   // Scan the loop in a topological order to ensure that defs are vectorized
1516   // before users.
1517   LoopBlocksDFS DFS(OrigLoop);
1518   DFS.perform(LI);
1519
1520   // Vectorize all of the blocks in the original loop.
1521   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1522        be = DFS.endRPO(); bb != be; ++bb)
1523     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1524
1525   // At this point every instruction in the original loop is widened to
1526   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1527   // that we vectorized. The PHI nodes are currently empty because we did
1528   // not want to introduce cycles. Notice that the remaining PHI nodes
1529   // that we need to fix are reduction variables.
1530
1531   // Create the 'reduced' values for each of the induction vars.
1532   // The reduced values are the vector values that we scalarize and combine
1533   // after the loop is finished.
1534   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1535        it != e; ++it) {
1536     PHINode *RdxPhi = *it;
1537     assert(RdxPhi && "Unable to recover vectorized PHI");
1538
1539     // Find the reduction variable descriptor.
1540     assert(Legal->getReductionVars()->count(RdxPhi) &&
1541            "Unable to find the reduction variable");
1542     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1543     (*Legal->getReductionVars())[RdxPhi];
1544
1545     // We need to generate a reduction vector from the incoming scalar.
1546     // To do so, we need to generate the 'identity' vector and overide
1547     // one of the elements with the incoming scalar reduction. We need
1548     // to do it in the vector-loop preheader.
1549     Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1550
1551     // This is the vector-clone of the value that leaves the loop.
1552     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1553     Type *VecTy = VectorExit[0]->getType();
1554
1555     // Find the reduction identity variable. Zero for addition, or, xor,
1556     // one for multiplication, -1 for And.
1557     Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1558     Constant *Identity = ConstantVector::getSplat(VF, Iden);
1559
1560     // This vector is the Identity vector where the first element is the
1561     // incoming scalar reduction.
1562     Value *VectorStart = Builder.CreateInsertElement(Identity,
1563                                                      RdxDesc.StartValue, Zero);
1564
1565     // Fix the vector-loop phi.
1566     // We created the induction variable so we know that the
1567     // preheader is the first entry.
1568     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1569
1570     // Reductions do not have to start at zero. They can start with
1571     // any loop invariant values.
1572     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1573     BasicBlock *Latch = OrigLoop->getLoopLatch();
1574     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1575     VectorParts &Val = getVectorValue(LoopVal);
1576     for (unsigned part = 0; part < UF; ++part) {
1577       // Make sure to add the reduction stat value only to the 
1578       // first unroll part.
1579       Value *StartVal = (part == 0) ? VectorStart : Identity;
1580       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1581       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1582     }
1583
1584     // Before each round, move the insertion point right between
1585     // the PHIs and the values we are going to write.
1586     // This allows us to write both PHINodes and the extractelement
1587     // instructions.
1588     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1589
1590     VectorParts RdxParts;
1591     for (unsigned part = 0; part < UF; ++part) {
1592       // This PHINode contains the vectorized reduction variable, or
1593       // the initial value vector, if we bypass the vector loop.
1594       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1595       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1596       Value *StartVal = (part == 0) ? VectorStart : Identity;
1597       for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1598         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1599       NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1600       RdxParts.push_back(NewPhi);
1601     }
1602
1603     // Reduce all of the unrolled parts into a single vector.
1604     Value *ReducedPartRdx = RdxParts[0];
1605     for (unsigned part = 1; part < UF; ++part) {
1606       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1607       ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1608                                            "bin.rdx");
1609     }
1610
1611     // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1612     // and vector ops, reducing the set of values being computed by half each
1613     // round.
1614     assert(isPowerOf2_32(VF) &&
1615            "Reduction emission only supported for pow2 vectors!");
1616     Value *TmpVec = ReducedPartRdx;
1617     SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1618     for (unsigned i = VF; i != 1; i >>= 1) {
1619       // Move the upper half of the vector to the lower half.
1620       for (unsigned j = 0; j != i/2; ++j)
1621         ShuffleMask[j] = Builder.getInt32(i/2 + j);
1622
1623       // Fill the rest of the mask with undef.
1624       std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1625                 UndefValue::get(Builder.getInt32Ty()));
1626
1627       Value *Shuf =
1628         Builder.CreateShuffleVector(TmpVec,
1629                                     UndefValue::get(TmpVec->getType()),
1630                                     ConstantVector::get(ShuffleMask),
1631                                     "rdx.shuf");
1632
1633       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1634       TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1635     }
1636
1637     // The result is in the first element of the vector.
1638     Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1639
1640     // Now, we need to fix the users of the reduction variable
1641     // inside and outside of the scalar remainder loop.
1642     // We know that the loop is in LCSSA form. We need to update the
1643     // PHI nodes in the exit blocks.
1644     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1645          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1646       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1647       if (!LCSSAPhi) continue;
1648
1649       // All PHINodes need to have a single entry edge, or two if
1650       // we already fixed them.
1651       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1652
1653       // We found our reduction value exit-PHI. Update it with the
1654       // incoming bypass edge.
1655       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1656         // Add an edge coming from the bypass.
1657         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1658         break;
1659       }
1660     }// end of the LCSSA phi scan.
1661
1662     // Fix the scalar loop reduction variable with the incoming reduction sum
1663     // from the vector body and from the backedge value.
1664     int IncomingEdgeBlockIdx =
1665     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1666     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1667     // Pick the other block.
1668     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1669     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1670     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1671   }// end of for each redux variable.
1672
1673   // The Loop exit block may have single value PHI nodes where the incoming
1674   // value is 'undef'. While vectorizing we only handled real values that
1675   // were defined inside the loop. Here we handle the 'undef case'.
1676   // See PR14725.
1677   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1678        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1679     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1680     if (!LCSSAPhi) continue;
1681     if (LCSSAPhi->getNumIncomingValues() == 1)
1682       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1683                             LoopMiddleBlock);
1684   }
1685 }
1686
1687 InnerLoopVectorizer::VectorParts
1688 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1689   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1690          "Invalid edge");
1691
1692   VectorParts SrcMask = createBlockInMask(Src);
1693
1694   // The terminator has to be a branch inst!
1695   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1696   assert(BI && "Unexpected terminator found");
1697
1698   if (BI->isConditional()) {
1699     VectorParts EdgeMask = getVectorValue(BI->getCondition());
1700
1701     if (BI->getSuccessor(0) != Dst)
1702       for (unsigned part = 0; part < UF; ++part)
1703         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1704
1705     for (unsigned part = 0; part < UF; ++part)
1706       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1707     return EdgeMask;
1708   }
1709
1710   return SrcMask;
1711 }
1712
1713 InnerLoopVectorizer::VectorParts
1714 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1715   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1716
1717   // Loop incoming mask is all-one.
1718   if (OrigLoop->getHeader() == BB) {
1719     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1720     return getVectorValue(C);
1721   }
1722
1723   // This is the block mask. We OR all incoming edges, and with zero.
1724   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1725   VectorParts BlockMask = getVectorValue(Zero);
1726
1727   // For each pred:
1728   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1729     VectorParts EM = createEdgeMask(*it, BB);
1730     for (unsigned part = 0; part < UF; ++part)
1731       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1732   }
1733
1734   return BlockMask;
1735 }
1736
1737 void
1738 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1739                                           BasicBlock *BB, PhiVector *PV) {
1740   // For each instruction in the old loop.
1741   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1742     VectorParts &Entry = WidenMap.get(it);
1743     switch (it->getOpcode()) {
1744     case Instruction::Br:
1745       // Nothing to do for PHIs and BR, since we already took care of the
1746       // loop control flow instructions.
1747       continue;
1748     case Instruction::PHI:{
1749       PHINode* P = cast<PHINode>(it);
1750       // Handle reduction variables:
1751       if (Legal->getReductionVars()->count(P)) {
1752         for (unsigned part = 0; part < UF; ++part) {
1753           // This is phase one of vectorizing PHIs.
1754           Type *VecTy = VectorType::get(it->getType(), VF);
1755           Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1756                                         LoopVectorBody-> getFirstInsertionPt());
1757         }
1758         PV->push_back(P);
1759         continue;
1760       }
1761
1762       // Check for PHI nodes that are lowered to vector selects.
1763       if (P->getParent() != OrigLoop->getHeader()) {
1764         // We know that all PHIs in non header blocks are converted into
1765         // selects, so we don't have to worry about the insertion order and we
1766         // can just use the builder.
1767
1768         // At this point we generate the predication tree. There may be
1769         // duplications since this is a simple recursive scan, but future
1770         // optimizations will clean it up.
1771         VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1772                                                P->getParent());
1773
1774         for (unsigned part = 0; part < UF; ++part) {
1775         VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1776         VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1777           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1778                                              "predphi");
1779         }
1780         continue;
1781       }
1782
1783       // This PHINode must be an induction variable.
1784       // Make sure that we know about it.
1785       assert(Legal->getInductionVars()->count(P) &&
1786              "Not an induction variable");
1787
1788       LoopVectorizationLegality::InductionInfo II =
1789         Legal->getInductionVars()->lookup(P);
1790
1791       switch (II.IK) {
1792       case LoopVectorizationLegality::IK_NoInduction:
1793         llvm_unreachable("Unknown induction");
1794       case LoopVectorizationLegality::IK_IntInduction: {
1795         assert(P == OldInduction && "Unexpected PHI");
1796         Value *Broadcasted = getBroadcastInstrs(Induction);
1797         // After broadcasting the induction variable we need to make the
1798         // vector consecutive by adding 0, 1, 2 ...
1799         for (unsigned part = 0; part < UF; ++part)
1800           Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1801         continue;
1802       }
1803       case LoopVectorizationLegality::IK_ReverseIntInduction:
1804       case LoopVectorizationLegality::IK_PtrInduction:
1805       case LoopVectorizationLegality::IK_ReversePtrInduction:
1806         // Handle reverse integer and pointer inductions.
1807         Value *StartIdx = 0;
1808         // If we have a single integer induction variable then use it.
1809         // Otherwise, start counting at zero.
1810         if (OldInduction) {
1811           LoopVectorizationLegality::InductionInfo OldII =
1812             Legal->getInductionVars()->lookup(OldInduction);
1813           StartIdx = OldII.StartValue;
1814         } else {
1815           StartIdx = ConstantInt::get(Induction->getType(), 0);
1816         }
1817         // This is the normalized GEP that starts counting at zero.
1818         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1819                                                  "normalized.idx");
1820
1821         // Handle the reverse integer induction variable case.
1822         if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1823           IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1824           Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1825                                                  "resize.norm.idx");
1826           Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1827                                                  "reverse.idx");
1828
1829           // This is a new value so do not hoist it out.
1830           Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1831           // After broadcasting the induction variable we need to make the
1832           // vector consecutive by adding  ... -3, -2, -1, 0.
1833           for (unsigned part = 0; part < UF; ++part)
1834             Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1835           continue;
1836         }
1837
1838         // Handle the pointer induction variable case.
1839         assert(P->getType()->isPointerTy() && "Unexpected type.");
1840
1841         // Is this a reverse induction ptr or a consecutive induction ptr.
1842         bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
1843                         II.IK);
1844
1845         // This is the vector of results. Notice that we don't generate
1846         // vector geps because scalar geps result in better code.
1847         for (unsigned part = 0; part < UF; ++part) {
1848           Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1849           for (unsigned int i = 0; i < VF; ++i) {
1850             int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
1851             Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
1852             Value *GlobalIdx;
1853             if (!Reverse)
1854               GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1855             else
1856               GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
1857
1858             Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1859                                                "next.gep");
1860             VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1861                                                  Builder.getInt32(i),
1862                                                  "insert.gep");
1863           }
1864           Entry[part] = VecVal;
1865         }
1866         continue;
1867       }
1868
1869     }// End of PHI.
1870
1871     case Instruction::Add:
1872     case Instruction::FAdd:
1873     case Instruction::Sub:
1874     case Instruction::FSub:
1875     case Instruction::Mul:
1876     case Instruction::FMul:
1877     case Instruction::UDiv:
1878     case Instruction::SDiv:
1879     case Instruction::FDiv:
1880     case Instruction::URem:
1881     case Instruction::SRem:
1882     case Instruction::FRem:
1883     case Instruction::Shl:
1884     case Instruction::LShr:
1885     case Instruction::AShr:
1886     case Instruction::And:
1887     case Instruction::Or:
1888     case Instruction::Xor: {
1889       // Just widen binops.
1890       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1891       VectorParts &A = getVectorValue(it->getOperand(0));
1892       VectorParts &B = getVectorValue(it->getOperand(1));
1893
1894       // Use this vector value for all users of the original instruction.
1895       for (unsigned Part = 0; Part < UF; ++Part) {
1896         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1897
1898         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1899         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1900         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1901           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1902           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1903         }
1904         if (VecOp && isa<PossiblyExactOperator>(VecOp))
1905           VecOp->setIsExact(BinOp->isExact());
1906
1907         Entry[Part] = V;
1908       }
1909       break;
1910     }
1911     case Instruction::Select: {
1912       // Widen selects.
1913       // If the selector is loop invariant we can create a select
1914       // instruction with a scalar condition. Otherwise, use vector-select.
1915       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1916                                                OrigLoop);
1917
1918       // The condition can be loop invariant  but still defined inside the
1919       // loop. This means that we can't just use the original 'cond' value.
1920       // We have to take the 'vectorized' value and pick the first lane.
1921       // Instcombine will make this a no-op.
1922       VectorParts &Cond = getVectorValue(it->getOperand(0));
1923       VectorParts &Op0  = getVectorValue(it->getOperand(1));
1924       VectorParts &Op1  = getVectorValue(it->getOperand(2));
1925       Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1926                                                        Builder.getInt32(0));
1927       for (unsigned Part = 0; Part < UF; ++Part) {
1928         Entry[Part] = Builder.CreateSelect(
1929           InvariantCond ? ScalarCond : Cond[Part],
1930           Op0[Part],
1931           Op1[Part]);
1932       }
1933       break;
1934     }
1935
1936     case Instruction::ICmp:
1937     case Instruction::FCmp: {
1938       // Widen compares. Generate vector compares.
1939       bool FCmp = (it->getOpcode() == Instruction::FCmp);
1940       CmpInst *Cmp = dyn_cast<CmpInst>(it);
1941       VectorParts &A = getVectorValue(it->getOperand(0));
1942       VectorParts &B = getVectorValue(it->getOperand(1));
1943       for (unsigned Part = 0; Part < UF; ++Part) {
1944         Value *C = 0;
1945         if (FCmp)
1946           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1947         else
1948           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1949         Entry[Part] = C;
1950       }
1951       break;
1952     }
1953
1954     case Instruction::Store:
1955     case Instruction::Load:
1956         vectorizeMemoryInstruction(it, Legal);
1957         break;
1958     case Instruction::ZExt:
1959     case Instruction::SExt:
1960     case Instruction::FPToUI:
1961     case Instruction::FPToSI:
1962     case Instruction::FPExt:
1963     case Instruction::PtrToInt:
1964     case Instruction::IntToPtr:
1965     case Instruction::SIToFP:
1966     case Instruction::UIToFP:
1967     case Instruction::Trunc:
1968     case Instruction::FPTrunc:
1969     case Instruction::BitCast: {
1970       CastInst *CI = dyn_cast<CastInst>(it);
1971       /// Optimize the special case where the source is the induction
1972       /// variable. Notice that we can only optimize the 'trunc' case
1973       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1974       /// c. other casts depend on pointer size.
1975       if (CI->getOperand(0) == OldInduction &&
1976           it->getOpcode() == Instruction::Trunc) {
1977         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1978                                                CI->getType());
1979         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1980         for (unsigned Part = 0; Part < UF; ++Part)
1981           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1982         break;
1983       }
1984       /// Vectorize casts.
1985       Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1986
1987       VectorParts &A = getVectorValue(it->getOperand(0));
1988       for (unsigned Part = 0; Part < UF; ++Part)
1989         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1990       break;
1991     }
1992
1993     case Instruction::Call: {
1994       assert(isTriviallyVectorizableIntrinsic(it));
1995       Module *M = BB->getParent()->getParent();
1996       IntrinsicInst *II = cast<IntrinsicInst>(it);
1997       Intrinsic::ID ID = II->getIntrinsicID();
1998       for (unsigned Part = 0; Part < UF; ++Part) {
1999         SmallVector<Value*, 4> Args;
2000         for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
2001           VectorParts &Arg = getVectorValue(II->getArgOperand(i));
2002           Args.push_back(Arg[Part]);
2003         }
2004         Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
2005         Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2006         Entry[Part] = Builder.CreateCall(F, Args);
2007       }
2008       break;
2009     }
2010
2011     default:
2012       // All other instructions are unsupported. Scalarize them.
2013       scalarizeInstruction(it);
2014       break;
2015     }// end of switch.
2016   }// end of for_each instr.
2017 }
2018
2019 void InnerLoopVectorizer::updateAnalysis() {
2020   // Forget the original basic block.
2021   SE->forgetLoop(OrigLoop);
2022
2023   // Update the dominator tree information.
2024   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2025          "Entry does not dominate exit.");
2026
2027   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2028     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2029   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2030   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2031   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2032   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2033   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2034   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2035
2036   DEBUG(DT->verifyAnalysis());
2037 }
2038
2039 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2040   if (!EnableIfConversion)
2041     return false;
2042
2043   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2044   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2045
2046   // Collect the blocks that need predication.
2047   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2048     BasicBlock *BB = LoopBlocks[i];
2049
2050     // We don't support switch statements inside loops.
2051     if (!isa<BranchInst>(BB->getTerminator()))
2052       return false;
2053
2054     // We must have at most two predecessors because we need to convert
2055     // all PHIs to selects.
2056     unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2057     if (Preds > 2)
2058       return false;
2059
2060     // We must be able to predicate all blocks that need to be predicated.
2061     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2062       return false;
2063   }
2064
2065   // We can if-convert this loop.
2066   return true;
2067 }
2068
2069 bool LoopVectorizationLegality::canVectorize() {
2070   assert(TheLoop->getLoopPreheader() && "No preheader!!");
2071
2072   // We can only vectorize innermost loops.
2073   if (TheLoop->getSubLoopsVector().size())
2074     return false;
2075
2076   // We must have a single backedge.
2077   if (TheLoop->getNumBackEdges() != 1)
2078     return false;
2079
2080   // We must have a single exiting block.
2081   if (!TheLoop->getExitingBlock())
2082     return false;
2083
2084   unsigned NumBlocks = TheLoop->getNumBlocks();
2085
2086   // Check if we can if-convert non single-bb loops.
2087   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2088     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2089     return false;
2090   }
2091
2092   // We need to have a loop header.
2093   BasicBlock *Latch = TheLoop->getLoopLatch();
2094   DEBUG(dbgs() << "LV: Found a loop: " <<
2095         TheLoop->getHeader()->getName() << "\n");
2096
2097   // ScalarEvolution needs to be able to find the exit count.
2098   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2099   if (ExitCount == SE->getCouldNotCompute()) {
2100     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2101     return false;
2102   }
2103
2104   // Do not loop-vectorize loops with a tiny trip count.
2105   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2106   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2107     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2108           "This loop is not worth vectorizing.\n");
2109     return false;
2110   }
2111
2112   // Check if we can vectorize the instructions and CFG in this loop.
2113   if (!canVectorizeInstrs()) {
2114     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2115     return false;
2116   }
2117
2118   // Go over each instruction and look at memory deps.
2119   if (!canVectorizeMemory()) {
2120     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2121     return false;
2122   }
2123
2124   // Collect all of the variables that remain uniform after vectorization.
2125   collectLoopUniforms();
2126
2127   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2128         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2129         <<"!\n");
2130
2131   // Okay! We can vectorize. At this point we don't have any other mem analysis
2132   // which may limit our maximum vectorization factor, so just return true with
2133   // no restrictions.
2134   return true;
2135 }
2136
2137 bool LoopVectorizationLegality::canVectorizeInstrs() {
2138   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2139   BasicBlock *Header = TheLoop->getHeader();
2140
2141   // For each block in the loop.
2142   for (Loop::block_iterator bb = TheLoop->block_begin(),
2143        be = TheLoop->block_end(); bb != be; ++bb) {
2144
2145     // Scan the instructions in the block and look for hazards.
2146     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2147          ++it) {
2148
2149       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2150         // This should not happen because the loop should be normalized.
2151         if (Phi->getNumIncomingValues() != 2) {
2152           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2153           return false;
2154         }
2155
2156         // Check that this PHI type is allowed.
2157         if (!Phi->getType()->isIntegerTy() &&
2158             !Phi->getType()->isFloatingPointTy() &&
2159             !Phi->getType()->isPointerTy()) {
2160           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2161           return false;
2162         }
2163
2164         // If this PHINode is not in the header block, then we know that we
2165         // can convert it to select during if-conversion. No need to check if
2166         // the PHIs in this block are induction or reduction variables.
2167         if (*bb != Header)
2168           continue;
2169
2170         // This is the value coming from the preheader.
2171         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2172         // Check if this is an induction variable.
2173         InductionKind IK = isInductionVariable(Phi);
2174
2175         if (IK_NoInduction != IK) {
2176           // Int inductions are special because we only allow one IV.
2177           if (IK == IK_IntInduction) {
2178             if (Induction) {
2179               DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2180               return false;
2181             }
2182             Induction = Phi;
2183           }
2184
2185           DEBUG(dbgs() << "LV: Found an induction variable.\n");
2186           Inductions[Phi] = InductionInfo(StartValue, IK);
2187           continue;
2188         }
2189
2190         if (AddReductionVar(Phi, RK_IntegerAdd)) {
2191           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2192           continue;
2193         }
2194         if (AddReductionVar(Phi, RK_IntegerMult)) {
2195           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2196           continue;
2197         }
2198         if (AddReductionVar(Phi, RK_IntegerOr)) {
2199           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2200           continue;
2201         }
2202         if (AddReductionVar(Phi, RK_IntegerAnd)) {
2203           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2204           continue;
2205         }
2206         if (AddReductionVar(Phi, RK_IntegerXor)) {
2207           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2208           continue;
2209         }
2210         if (AddReductionVar(Phi, RK_FloatMult)) {
2211           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2212           continue;
2213         }
2214         if (AddReductionVar(Phi, RK_FloatAdd)) {
2215           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2216           continue;
2217         }
2218
2219         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2220         return false;
2221       }// end of PHI handling
2222
2223       // We still don't handle functions.
2224       CallInst *CI = dyn_cast<CallInst>(it);
2225       if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2226         DEBUG(dbgs() << "LV: Found a call site.\n");
2227         return false;
2228       }
2229
2230       // Check that the instruction return type is vectorizable.
2231       if (!VectorType::isValidElementType(it->getType()) &&
2232           !it->getType()->isVoidTy()) {
2233         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2234         return false;
2235       }
2236
2237       // Check that the stored type is vectorizable.
2238       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2239         Type *T = ST->getValueOperand()->getType();
2240         if (!VectorType::isValidElementType(T))
2241           return false;
2242       }
2243
2244       // Reduction instructions are allowed to have exit users.
2245       // All other instructions must not have external users.
2246       if (!AllowedExit.count(it))
2247         //Check that all of the users of the loop are inside the BB.
2248         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2249              I != E; ++I) {
2250           Instruction *U = cast<Instruction>(*I);
2251           // This user may be a reduction exit value.
2252           if (!TheLoop->contains(U)) {
2253             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2254             return false;
2255           }
2256         }
2257     } // next instr.
2258
2259   }
2260
2261   if (!Induction) {
2262     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2263     assert(getInductionVars()->size() && "No induction variables");
2264   }
2265
2266   return true;
2267 }
2268
2269 void LoopVectorizationLegality::collectLoopUniforms() {
2270   // We now know that the loop is vectorizable!
2271   // Collect variables that will remain uniform after vectorization.
2272   std::vector<Value*> Worklist;
2273   BasicBlock *Latch = TheLoop->getLoopLatch();
2274
2275   // Start with the conditional branch and walk up the block.
2276   Worklist.push_back(Latch->getTerminator()->getOperand(0));
2277
2278   while (Worklist.size()) {
2279     Instruction *I = dyn_cast<Instruction>(Worklist.back());
2280     Worklist.pop_back();
2281
2282     // Look at instructions inside this loop.
2283     // Stop when reaching PHI nodes.
2284     // TODO: we need to follow values all over the loop, not only in this block.
2285     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2286       continue;
2287
2288     // This is a known uniform.
2289     Uniforms.insert(I);
2290
2291     // Insert all operands.
2292     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2293       Worklist.push_back(I->getOperand(i));
2294     }
2295   }
2296 }
2297
2298 AliasAnalysis::Location
2299 LoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
2300   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
2301     return AA->getLocation(Store);
2302   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
2303     return AA->getLocation(Load);
2304
2305   llvm_unreachable("Should be either load or store instruction");
2306 }
2307
2308 bool
2309 LoopVectorizationLegality::hasPossibleGlobalWriteReorder(
2310                                                 Value *Object,
2311                                                 Instruction *Inst,
2312                                                 AliasMultiMap& WriteObjects,
2313                                                 unsigned MaxByteWidth) {
2314
2315   AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
2316
2317   std::vector<Instruction*>::iterator
2318               it = WriteObjects[Object].begin(),
2319               end = WriteObjects[Object].end();
2320
2321   for (; it != end; ++it) {
2322     Instruction* I = *it;
2323     if (I == Inst)
2324       continue;
2325
2326     AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
2327     if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
2328                   ThatLoc.getWithNewSize(MaxByteWidth)))
2329       return true;
2330   }
2331   return false;
2332 }
2333
2334 bool LoopVectorizationLegality::canVectorizeMemory() {
2335
2336   if (TheLoop->isAnnotatedParallel()) {
2337     DEBUG(dbgs()
2338           << "LV: A loop annotated parallel, ignore memory dependency "
2339           << "checks.\n");
2340     return true;
2341   }
2342
2343   typedef SmallVector<Value*, 16> ValueVector;
2344   typedef SmallPtrSet<Value*, 16> ValueSet;
2345   // Holds the Load and Store *instructions*.
2346   ValueVector Loads;
2347   ValueVector Stores;
2348   PtrRtCheck.Pointers.clear();
2349   PtrRtCheck.Need = false;
2350
2351   // For each block.
2352   for (Loop::block_iterator bb = TheLoop->block_begin(),
2353        be = TheLoop->block_end(); bb != be; ++bb) {
2354
2355     // Scan the BB and collect legal loads and stores.
2356     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2357          ++it) {
2358
2359       // If this is a load, save it. If this instruction can read from memory
2360       // but is not a load, then we quit. Notice that we don't handle function
2361       // calls that read or write.
2362       if (it->mayReadFromMemory()) {
2363         LoadInst *Ld = dyn_cast<LoadInst>(it);
2364         if (!Ld) return false;
2365         if (!Ld->isSimple()) {
2366           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2367           return false;
2368         }
2369         Loads.push_back(Ld);
2370         continue;
2371       }
2372
2373       // Save 'store' instructions. Abort if other instructions write to memory.
2374       if (it->mayWriteToMemory()) {
2375         StoreInst *St = dyn_cast<StoreInst>(it);
2376         if (!St) return false;
2377         if (!St->isSimple()) {
2378           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2379           return false;
2380         }
2381         Stores.push_back(St);
2382       }
2383     } // next instr.
2384   } // next block.
2385
2386   // Now we have two lists that hold the loads and the stores.
2387   // Next, we find the pointers that they use.
2388
2389   // Check if we see any stores. If there are no stores, then we don't
2390   // care if the pointers are *restrict*.
2391   if (!Stores.size()) {
2392     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2393     return true;
2394   }
2395
2396   // Holds the read and read-write *pointers* that we find. These maps hold
2397   // unique values for pointers (so no need for multi-map).
2398   AliasMap Reads;
2399   AliasMap ReadWrites;
2400
2401   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2402   // multiple times on the same object. If the ptr is accessed twice, once
2403   // for read and once for write, it will only appear once (on the write
2404   // list). This is okay, since we are going to check for conflicts between
2405   // writes and between reads and writes, but not between reads and reads.
2406   ValueSet Seen;
2407
2408   ValueVector::iterator I, IE;
2409   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2410     StoreInst *ST = cast<StoreInst>(*I);
2411     Value* Ptr = ST->getPointerOperand();
2412
2413     if (isUniform(Ptr)) {
2414       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2415       return false;
2416     }
2417
2418     // If we did *not* see this pointer before, insert it to
2419     // the read-write list. At this phase it is only a 'write' list.
2420     if (Seen.insert(Ptr))
2421       ReadWrites.insert(std::make_pair(Ptr, ST));
2422   }
2423
2424   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2425     LoadInst *LD = cast<LoadInst>(*I);
2426     Value* Ptr = LD->getPointerOperand();
2427     // If we did *not* see this pointer before, insert it to the
2428     // read list. If we *did* see it before, then it is already in
2429     // the read-write list. This allows us to vectorize expressions
2430     // such as A[i] += x;  Because the address of A[i] is a read-write
2431     // pointer. This only works if the index of A[i] is consecutive.
2432     // If the address of i is unknown (for example A[B[i]]) then we may
2433     // read a few words, modify, and write a few words, and some of the
2434     // words may be written to the same address.
2435     if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2436       Reads.insert(std::make_pair(Ptr, LD));
2437   }
2438
2439   // If we write (or read-write) to a single destination and there are no
2440   // other reads in this loop then is it safe to vectorize.
2441   if (ReadWrites.size() == 1 && Reads.size() == 0) {
2442     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2443     return true;
2444   }
2445
2446   // Find pointers with computable bounds. We are going to use this information
2447   // to place a runtime bound check.
2448   bool CanDoRT = true;
2449   AliasMap::iterator MI, ME;
2450   for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2451     Value *V = (*MI).first;
2452     if (hasComputableBounds(V)) {
2453       PtrRtCheck.insert(SE, TheLoop, V);
2454       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2455     } else {
2456       CanDoRT = false;
2457       break;
2458     }
2459   }
2460   for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2461     Value *V = (*MI).first;
2462     if (hasComputableBounds(V)) {
2463       PtrRtCheck.insert(SE, TheLoop, V);
2464       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2465     } else {
2466       CanDoRT = false;
2467       break;
2468     }
2469   }
2470
2471   // Check that we did not collect too many pointers or found a
2472   // unsizeable pointer.
2473   if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2474     PtrRtCheck.reset();
2475     CanDoRT = false;
2476   }
2477
2478   if (CanDoRT) {
2479     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2480   }
2481
2482   bool NeedRTCheck = false;
2483
2484   // Biggest vectorized access possible, vector width * unroll factor.
2485   // TODO: We're being very pessimistic here, find a way to know the
2486   // real access width before getting here.
2487   unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
2488                            TTI->getMaximumUnrollFactor();
2489   // Now that the pointers are in two lists (Reads and ReadWrites), we
2490   // can check that there are no conflicts between each of the writes and
2491   // between the writes to the reads.
2492   // Note that WriteObjects duplicates the stores (indexed now by underlying
2493   // objects) to avoid pointing to elements inside ReadWrites.
2494   // TODO: Maybe create a new type where they can interact without duplication.
2495   AliasMultiMap WriteObjects;
2496   ValueVector TempObjects;
2497
2498   // Check that the read-writes do not conflict with other read-write
2499   // pointers.
2500   bool AllWritesIdentified = true;
2501   for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2502     Value *Val = (*MI).first;
2503     Instruction *Inst = (*MI).second;
2504
2505     GetUnderlyingObjects(Val, TempObjects, DL);
2506     for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2507          UI != UE; ++UI) {
2508       if (!isIdentifiedObject(*UI)) {
2509         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
2510         NeedRTCheck = true;
2511         AllWritesIdentified = false;
2512       }
2513
2514       // Never seen it before, can't alias.
2515       if (WriteObjects[*UI].empty()) {
2516         DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
2517         WriteObjects[*UI].push_back(Inst);
2518         continue;
2519       }
2520       // Direct alias found.
2521       if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2522         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2523               << **UI <<"\n");
2524         return false;
2525       }
2526       DEBUG(dbgs() << "LV: Found a conflicting global value:"
2527             << **UI <<"\n");
2528       DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
2529       DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2530
2531       // If global alias, make sure they do alias.
2532       if (hasPossibleGlobalWriteReorder(*UI,
2533                                         Inst,
2534                                         WriteObjects,
2535                                         MaxByteWidth)) {
2536         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2537               << *UI <<"\n");
2538         return false;
2539       }
2540
2541       // Didn't alias, insert into map for further reference.
2542       WriteObjects[*UI].push_back(Inst);
2543     }
2544     TempObjects.clear();
2545   }
2546
2547   /// Check that the reads don't conflict with the read-writes.
2548   for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2549     Value *Val = (*MI).first;
2550     GetUnderlyingObjects(Val, TempObjects, DL);
2551     for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2552          UI != UE; ++UI) {
2553       // If all of the writes are identified then we don't care if the read
2554       // pointer is identified or not.
2555       if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
2556         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
2557         NeedRTCheck = true;
2558       }
2559
2560       // Never seen it before, can't alias.
2561       if (WriteObjects[*UI].empty())
2562         continue;
2563       // Direct alias found.
2564       if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2565         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2566               << **UI <<"\n");
2567         return false;
2568       }
2569       DEBUG(dbgs() << "LV: Found a global value:  "
2570             << **UI <<"\n");
2571       Instruction *Inst = (*MI).second;
2572       DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
2573       DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2574
2575       // If global alias, make sure they do alias.
2576       if (hasPossibleGlobalWriteReorder(*UI,
2577                                         Inst,
2578                                         WriteObjects,
2579                                         MaxByteWidth)) {
2580         DEBUG(dbgs() << "LV: Found a possible read-write reorder:"
2581               << *UI <<"\n");
2582         return false;
2583       }
2584     }
2585     TempObjects.clear();
2586   }
2587
2588   PtrRtCheck.Need = NeedRTCheck;
2589   if (NeedRTCheck && !CanDoRT) {
2590     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2591           "the array bounds.\n");
2592     PtrRtCheck.reset();
2593     return false;
2594   }
2595
2596   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2597         " need a runtime memory check.\n");
2598   return true;
2599 }
2600
2601 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2602                                                 ReductionKind Kind) {
2603   if (Phi->getNumIncomingValues() != 2)
2604     return false;
2605
2606   // Reduction variables are only found in the loop header block.
2607   if (Phi->getParent() != TheLoop->getHeader())
2608     return false;
2609
2610   // Obtain the reduction start value from the value that comes from the loop
2611   // preheader.
2612   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2613
2614   // ExitInstruction is the single value which is used outside the loop.
2615   // We only allow for a single reduction value to be used outside the loop.
2616   // This includes users of the reduction, variables (which form a cycle
2617   // which ends in the phi node).
2618   Instruction *ExitInstruction = 0;
2619   // Indicates that we found a binary operation in our scan.
2620   bool FoundBinOp = false;
2621
2622   // Iter is our iterator. We start with the PHI node and scan for all of the
2623   // users of this instruction. All users must be instructions that can be
2624   // used as reduction variables (such as ADD). We may have a single
2625   // out-of-block user. The cycle must end with the original PHI.
2626   Instruction *Iter = Phi;
2627   while (true) {
2628     // If the instruction has no users then this is a broken
2629     // chain and can't be a reduction variable.
2630     if (Iter->use_empty())
2631       return false;
2632
2633     // Did we find a user inside this loop already ?
2634     bool FoundInBlockUser = false;
2635     // Did we reach the initial PHI node already ?
2636     bool FoundStartPHI = false;
2637
2638     // Is this a bin op ?
2639     FoundBinOp |= !isa<PHINode>(Iter);
2640
2641     // For each of the *users* of iter.
2642     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2643          it != e; ++it) {
2644       Instruction *U = cast<Instruction>(*it);
2645       // We already know that the PHI is a user.
2646       if (U == Phi) {
2647         FoundStartPHI = true;
2648         continue;
2649       }
2650
2651       // Check if we found the exit user.
2652       BasicBlock *Parent = U->getParent();
2653       if (!TheLoop->contains(Parent)) {
2654         // Exit if you find multiple outside users.
2655         if (ExitInstruction != 0)
2656           return false;
2657         ExitInstruction = Iter;
2658       }
2659
2660       // We allow in-loop PHINodes which are not the original reduction PHI
2661       // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2662       // structure) then don't skip this PHI.
2663       if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2664           U->getParent() != TheLoop->getHeader() &&
2665           TheLoop->contains(U) &&
2666           Iter->getNumUses() > 1)
2667         continue;
2668
2669       // We can't have multiple inside users.
2670       if (FoundInBlockUser)
2671         return false;
2672       FoundInBlockUser = true;
2673
2674       // Any reduction instr must be of one of the allowed kinds.
2675       if (!isReductionInstr(U, Kind))
2676         return false;
2677
2678       // Reductions of instructions such as Div, and Sub is only
2679       // possible if the LHS is the reduction variable.
2680       if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2681         return false;
2682
2683       Iter = U;
2684     }
2685
2686     // We found a reduction var if we have reached the original
2687     // phi node and we only have a single instruction with out-of-loop
2688     // users.
2689     if (FoundStartPHI) {
2690       // This instruction is allowed to have out-of-loop users.
2691       AllowedExit.insert(ExitInstruction);
2692
2693       // Save the description of this reduction variable.
2694       ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2695       Reductions[Phi] = RD;
2696       // We've ended the cycle. This is a reduction variable if we have an
2697       // outside user and it has a binary op.
2698       return FoundBinOp && ExitInstruction;
2699     }
2700   }
2701 }
2702
2703 bool
2704 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2705                                             ReductionKind Kind) {
2706   bool FP = I->getType()->isFloatingPointTy();
2707   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2708
2709   switch (I->getOpcode()) {
2710   default:
2711     return false;
2712   case Instruction::PHI:
2713       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2714         return false;
2715     // possibly.
2716     return true;
2717   case Instruction::Sub:
2718   case Instruction::Add:
2719     return Kind == RK_IntegerAdd;
2720   case Instruction::SDiv:
2721   case Instruction::UDiv:
2722   case Instruction::Mul:
2723     return Kind == RK_IntegerMult;
2724   case Instruction::And:
2725     return Kind == RK_IntegerAnd;
2726   case Instruction::Or:
2727     return Kind == RK_IntegerOr;
2728   case Instruction::Xor:
2729     return Kind == RK_IntegerXor;
2730   case Instruction::FMul:
2731     return Kind == RK_FloatMult && FastMath;
2732   case Instruction::FAdd:
2733     return Kind == RK_FloatAdd && FastMath;
2734    }
2735 }
2736
2737 LoopVectorizationLegality::InductionKind
2738 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2739   Type *PhiTy = Phi->getType();
2740   // We only handle integer and pointer inductions variables.
2741   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2742     return IK_NoInduction;
2743
2744   // Check that the PHI is consecutive.
2745   const SCEV *PhiScev = SE->getSCEV(Phi);
2746   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2747   if (!AR) {
2748     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2749     return IK_NoInduction;
2750   }
2751   const SCEV *Step = AR->getStepRecurrence(*SE);
2752
2753   // Integer inductions need to have a stride of one.
2754   if (PhiTy->isIntegerTy()) {
2755     if (Step->isOne())
2756       return IK_IntInduction;
2757     if (Step->isAllOnesValue())
2758       return IK_ReverseIntInduction;
2759     return IK_NoInduction;
2760   }
2761
2762   // Calculate the pointer stride and check if it is consecutive.
2763   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2764   if (!C)
2765     return IK_NoInduction;
2766
2767   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2768   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2769   if (C->getValue()->equalsInt(Size))
2770     return IK_PtrInduction;
2771   else if (C->getValue()->equalsInt(0 - Size))
2772     return IK_ReversePtrInduction;
2773
2774   return IK_NoInduction;
2775 }
2776
2777 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2778   Value *In0 = const_cast<Value*>(V);
2779   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2780   if (!PN)
2781     return false;
2782
2783   return Inductions.count(PN);
2784 }
2785
2786 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
2787   assert(TheLoop->contains(BB) && "Unknown block used");
2788
2789   // Blocks that do not dominate the latch need predication.
2790   BasicBlock* Latch = TheLoop->getLoopLatch();
2791   return !DT->dominates(BB, Latch);
2792 }
2793
2794 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2795   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2796     // We don't predicate loads/stores at the moment.
2797     if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2798       return false;
2799
2800     // The instructions below can trap.
2801     switch (it->getOpcode()) {
2802     default: continue;
2803     case Instruction::UDiv:
2804     case Instruction::SDiv:
2805     case Instruction::URem:
2806     case Instruction::SRem:
2807              return false;
2808     }
2809   }
2810
2811   return true;
2812 }
2813
2814 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2815   const SCEV *PhiScev = SE->getSCEV(Ptr);
2816   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2817   if (!AR)
2818     return false;
2819
2820   return AR->isAffine();
2821 }
2822
2823 LoopVectorizationCostModel::VectorizationFactor
2824 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2825                                                       unsigned UserVF) {
2826   // Width 1 means no vectorize
2827   VectorizationFactor Factor = { 1U, 0U };
2828   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2829     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2830     return Factor;
2831   }
2832
2833   // Find the trip count.
2834   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2835   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2836
2837   unsigned WidestType = getWidestType();
2838   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2839   unsigned MaxVectorSize = WidestRegister / WidestType;
2840   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2841   DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2842
2843   if (MaxVectorSize == 0) {
2844     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2845     MaxVectorSize = 1;
2846   }
2847
2848   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2849          " into one vector!");
2850
2851   unsigned VF = MaxVectorSize;
2852
2853   // If we optimize the program for size, avoid creating the tail loop.
2854   if (OptForSize) {
2855     // If we are unable to calculate the trip count then don't try to vectorize.
2856     if (TC < 2) {
2857       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2858       return Factor;
2859     }
2860
2861     // Find the maximum SIMD width that can fit within the trip count.
2862     VF = TC % MaxVectorSize;
2863
2864     if (VF == 0)
2865       VF = MaxVectorSize;
2866
2867     // If the trip count that we found modulo the vectorization factor is not
2868     // zero then we require a tail.
2869     if (VF < 2) {
2870       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2871       return Factor;
2872     }
2873   }
2874
2875   if (UserVF != 0) {
2876     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2877     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2878
2879     Factor.Width = UserVF;
2880     return Factor;
2881   }
2882
2883   float Cost = expectedCost(1);
2884   unsigned Width = 1;
2885   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2886   for (unsigned i=2; i <= VF; i*=2) {
2887     // Notice that the vector loop needs to be executed less times, so
2888     // we need to divide the cost of the vector loops by the width of
2889     // the vector elements.
2890     float VectorCost = expectedCost(i) / (float)i;
2891     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2892           (int)VectorCost << ".\n");
2893     if (VectorCost < Cost) {
2894       Cost = VectorCost;
2895       Width = i;
2896     }
2897   }
2898
2899   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2900   Factor.Width = Width;
2901   Factor.Cost = Width * Cost;
2902   return Factor;
2903 }
2904
2905 unsigned LoopVectorizationCostModel::getWidestType() {
2906   unsigned MaxWidth = 8;
2907
2908   // For each block.
2909   for (Loop::block_iterator bb = TheLoop->block_begin(),
2910        be = TheLoop->block_end(); bb != be; ++bb) {
2911     BasicBlock *BB = *bb;
2912
2913     // For each instruction in the loop.
2914     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2915       Type *T = it->getType();
2916
2917       // Only examine Loads, Stores and PHINodes.
2918       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2919         continue;
2920
2921       // Examine PHI nodes that are reduction variables.
2922       if (PHINode *PN = dyn_cast<PHINode>(it))
2923         if (!Legal->getReductionVars()->count(PN))
2924           continue;
2925
2926       // Examine the stored values.
2927       if (StoreInst *ST = dyn_cast<StoreInst>(it))
2928         T = ST->getValueOperand()->getType();
2929
2930       // Ignore loaded pointer types and stored pointer types that are not
2931       // consecutive. However, we do want to take consecutive stores/loads of
2932       // pointer vectors into account.
2933       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
2934         continue;
2935
2936       MaxWidth = std::max(MaxWidth,
2937                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
2938     }
2939   }
2940
2941   return MaxWidth;
2942 }
2943
2944 unsigned
2945 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2946                                                unsigned UserUF,
2947                                                unsigned VF,
2948                                                unsigned LoopCost) {
2949
2950   // -- The unroll heuristics --
2951   // We unroll the loop in order to expose ILP and reduce the loop overhead.
2952   // There are many micro-architectural considerations that we can't predict
2953   // at this level. For example frontend pressure (on decode or fetch) due to
2954   // code size, or the number and capabilities of the execution ports.
2955   //
2956   // We use the following heuristics to select the unroll factor:
2957   // 1. If the code has reductions the we unroll in order to break the cross
2958   // iteration dependency.
2959   // 2. If the loop is really small then we unroll in order to reduce the loop
2960   // overhead.
2961   // 3. We don't unroll if we think that we will spill registers to memory due
2962   // to the increased register pressure.
2963
2964   // Use the user preference, unless 'auto' is selected.
2965   if (UserUF != 0)
2966     return UserUF;
2967
2968   // When we optimize for size we don't unroll.
2969   if (OptForSize)
2970     return 1;
2971
2972   // Do not unroll loops with a relatively small trip count.
2973   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2974                                               TheLoop->getLoopLatch());
2975   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2976     return 1;
2977
2978   unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2979   DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2980         " vector registers\n");
2981
2982   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2983   // We divide by these constants so assume that we have at least one
2984   // instruction that uses at least one register.
2985   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2986   R.NumInstructions = std::max(R.NumInstructions, 1U);
2987
2988   // We calculate the unroll factor using the following formula.
2989   // Subtract the number of loop invariants from the number of available
2990   // registers. These registers are used by all of the unrolled instances.
2991   // Next, divide the remaining registers by the number of registers that is
2992   // required by the loop, in order to estimate how many parallel instances
2993   // fit without causing spills.
2994   unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2995
2996   // Clamp the unroll factor ranges to reasonable factors.
2997   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2998
2999   // If we did not calculate the cost for VF (because the user selected the VF)
3000   // then we calculate the cost of VF here.
3001   if (LoopCost == 0)
3002     LoopCost = expectedCost(VF);
3003
3004   // Clamp the calculated UF to be between the 1 and the max unroll factor
3005   // that the target allows.
3006   if (UF > MaxUnrollSize)
3007     UF = MaxUnrollSize;
3008   else if (UF < 1)
3009     UF = 1;
3010
3011   if (Legal->getReductionVars()->size()) {
3012     DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3013     return UF;
3014   }
3015
3016   // We want to unroll tiny loops in order to reduce the loop overhead.
3017   // We assume that the cost overhead is 1 and we use the cost model
3018   // to estimate the cost of the loop and unroll until the cost of the
3019   // loop overhead is about 5% of the cost of the loop.
3020   DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3021   if (LoopCost < 20) {
3022     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3023     unsigned NewUF = 20/LoopCost + 1;
3024     return std::min(NewUF, UF);
3025   }
3026
3027   DEBUG(dbgs() << "LV: Not Unrolling. \n");
3028   return 1;
3029 }
3030
3031 LoopVectorizationCostModel::RegisterUsage
3032 LoopVectorizationCostModel::calculateRegisterUsage() {
3033   // This function calculates the register usage by measuring the highest number
3034   // of values that are alive at a single location. Obviously, this is a very
3035   // rough estimation. We scan the loop in a topological order in order and
3036   // assign a number to each instruction. We use RPO to ensure that defs are
3037   // met before their users. We assume that each instruction that has in-loop
3038   // users starts an interval. We record every time that an in-loop value is
3039   // used, so we have a list of the first and last occurrences of each
3040   // instruction. Next, we transpose this data structure into a multi map that
3041   // holds the list of intervals that *end* at a specific location. This multi
3042   // map allows us to perform a linear search. We scan the instructions linearly
3043   // and record each time that a new interval starts, by placing it in a set.
3044   // If we find this value in the multi-map then we remove it from the set.
3045   // The max register usage is the maximum size of the set.
3046   // We also search for instructions that are defined outside the loop, but are
3047   // used inside the loop. We need this number separately from the max-interval
3048   // usage number because when we unroll, loop-invariant values do not take
3049   // more register.
3050   LoopBlocksDFS DFS(TheLoop);
3051   DFS.perform(LI);
3052
3053   RegisterUsage R;
3054   R.NumInstructions = 0;
3055
3056   // Each 'key' in the map opens a new interval. The values
3057   // of the map are the index of the 'last seen' usage of the
3058   // instruction that is the key.
3059   typedef DenseMap<Instruction*, unsigned> IntervalMap;
3060   // Maps instruction to its index.
3061   DenseMap<unsigned, Instruction*> IdxToInstr;
3062   // Marks the end of each interval.
3063   IntervalMap EndPoint;
3064   // Saves the list of instruction indices that are used in the loop.
3065   SmallSet<Instruction*, 8> Ends;
3066   // Saves the list of values that are used in the loop but are
3067   // defined outside the loop, such as arguments and constants.
3068   SmallPtrSet<Value*, 8> LoopInvariants;
3069
3070   unsigned Index = 0;
3071   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3072        be = DFS.endRPO(); bb != be; ++bb) {
3073     R.NumInstructions += (*bb)->size();
3074     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3075          ++it) {
3076       Instruction *I = it;
3077       IdxToInstr[Index++] = I;
3078
3079       // Save the end location of each USE.
3080       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3081         Value *U = I->getOperand(i);
3082         Instruction *Instr = dyn_cast<Instruction>(U);
3083
3084         // Ignore non-instruction values such as arguments, constants, etc.
3085         if (!Instr) continue;
3086
3087         // If this instruction is outside the loop then record it and continue.
3088         if (!TheLoop->contains(Instr)) {
3089           LoopInvariants.insert(Instr);
3090           continue;
3091         }
3092
3093         // Overwrite previous end points.
3094         EndPoint[Instr] = Index;
3095         Ends.insert(Instr);
3096       }
3097     }
3098   }
3099
3100   // Saves the list of intervals that end with the index in 'key'.
3101   typedef SmallVector<Instruction*, 2> InstrList;
3102   DenseMap<unsigned, InstrList> TransposeEnds;
3103
3104   // Transpose the EndPoints to a list of values that end at each index.
3105   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3106        it != e; ++it)
3107     TransposeEnds[it->second].push_back(it->first);
3108
3109   SmallSet<Instruction*, 8> OpenIntervals;
3110   unsigned MaxUsage = 0;
3111
3112
3113   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3114   for (unsigned int i = 0; i < Index; ++i) {
3115     Instruction *I = IdxToInstr[i];
3116     // Ignore instructions that are never used within the loop.
3117     if (!Ends.count(I)) continue;
3118
3119     // Remove all of the instructions that end at this location.
3120     InstrList &List = TransposeEnds[i];
3121     for (unsigned int j=0, e = List.size(); j < e; ++j)
3122       OpenIntervals.erase(List[j]);
3123
3124     // Count the number of live interals.
3125     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3126
3127     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3128           OpenIntervals.size() <<"\n");
3129
3130     // Add the current instruction to the list of open intervals.
3131     OpenIntervals.insert(I);
3132   }
3133
3134   unsigned Invariant = LoopInvariants.size();
3135   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3136   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3137   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3138
3139   R.LoopInvariantRegs = Invariant;
3140   R.MaxLocalUsers = MaxUsage;
3141   return R;
3142 }
3143
3144 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3145   unsigned Cost = 0;
3146
3147   // For each block.
3148   for (Loop::block_iterator bb = TheLoop->block_begin(),
3149        be = TheLoop->block_end(); bb != be; ++bb) {
3150     unsigned BlockCost = 0;
3151     BasicBlock *BB = *bb;
3152
3153     // For each instruction in the old loop.
3154     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3155       unsigned C = getInstructionCost(it, VF);
3156       Cost += C;
3157       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3158             VF << " For instruction: "<< *it << "\n");
3159     }
3160
3161     // We assume that if-converted blocks have a 50% chance of being executed.
3162     // When the code is scalar then some of the blocks are avoided due to CF.
3163     // When the code is vectorized we execute all code paths.
3164     if (Legal->blockNeedsPredication(*bb) && VF == 1)
3165       BlockCost /= 2;
3166
3167     Cost += BlockCost;
3168   }
3169
3170   return Cost;
3171 }
3172
3173 unsigned
3174 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3175   // If we know that this instruction will remain uniform, check the cost of
3176   // the scalar version.
3177   if (Legal->isUniformAfterVectorization(I))
3178     VF = 1;
3179
3180   Type *RetTy = I->getType();
3181   Type *VectorTy = ToVectorTy(RetTy, VF);
3182
3183   // TODO: We need to estimate the cost of intrinsic calls.
3184   switch (I->getOpcode()) {
3185   case Instruction::GetElementPtr:
3186     // We mark this instruction as zero-cost because the cost of GEPs in
3187     // vectorized code depends on whether the corresponding memory instruction
3188     // is scalarized or not. Therefore, we handle GEPs with the memory
3189     // instruction cost.
3190     return 0;
3191   case Instruction::Br: {
3192     return TTI.getCFInstrCost(I->getOpcode());
3193   }
3194   case Instruction::PHI:
3195     //TODO: IF-converted IFs become selects.
3196     return 0;
3197   case Instruction::Add:
3198   case Instruction::FAdd:
3199   case Instruction::Sub:
3200   case Instruction::FSub:
3201   case Instruction::Mul:
3202   case Instruction::FMul:
3203   case Instruction::UDiv:
3204   case Instruction::SDiv:
3205   case Instruction::FDiv:
3206   case Instruction::URem:
3207   case Instruction::SRem:
3208   case Instruction::FRem:
3209   case Instruction::Shl:
3210   case Instruction::LShr:
3211   case Instruction::AShr:
3212   case Instruction::And:
3213   case Instruction::Or:
3214   case Instruction::Xor:
3215     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
3216   case Instruction::Select: {
3217     SelectInst *SI = cast<SelectInst>(I);
3218     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3219     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3220     Type *CondTy = SI->getCondition()->getType();
3221     if (ScalarCond)
3222       CondTy = VectorType::get(CondTy, VF);
3223
3224     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3225   }
3226   case Instruction::ICmp:
3227   case Instruction::FCmp: {
3228     Type *ValTy = I->getOperand(0)->getType();
3229     VectorTy = ToVectorTy(ValTy, VF);
3230     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3231   }
3232   case Instruction::Store:
3233   case Instruction::Load: {
3234     StoreInst *SI = dyn_cast<StoreInst>(I);
3235     LoadInst *LI = dyn_cast<LoadInst>(I);
3236     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3237                    LI->getType());
3238     VectorTy = ToVectorTy(ValTy, VF);
3239
3240     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3241     unsigned AS = SI ? SI->getPointerAddressSpace() :
3242       LI->getPointerAddressSpace();
3243     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3244     // We add the cost of address computation here instead of with the gep
3245     // instruction because only here we know whether the operation is
3246     // scalarized.
3247     if (VF == 1)
3248       return TTI.getAddressComputationCost(VectorTy) +
3249         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3250
3251     // Scalarized loads/stores.
3252     int Stride = Legal->isConsecutivePtr(Ptr);
3253     bool Reverse = Stride < 0;
3254     if (0 == Stride) {
3255       unsigned Cost = 0;
3256       // The cost of extracting from the value vector and pointer vector.
3257       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3258       for (unsigned i = 0; i < VF; ++i) {
3259         //  The cost of extracting the pointer operand.
3260         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3261         // In case of STORE, the cost of ExtractElement from the vector.
3262         // In case of LOAD, the cost of InsertElement into the returned
3263         // vector.
3264         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3265                                             Instruction::InsertElement,
3266                                             VectorTy, i);
3267       }
3268
3269       // The cost of the scalar loads/stores.
3270       Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3271       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3272                                        Alignment, AS);
3273       return Cost;
3274     }
3275
3276     // Wide load/stores.
3277     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3278     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3279
3280     if (Reverse)
3281       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3282                                   VectorTy, 0);
3283     return Cost;
3284   }
3285   case Instruction::ZExt:
3286   case Instruction::SExt:
3287   case Instruction::FPToUI:
3288   case Instruction::FPToSI:
3289   case Instruction::FPExt:
3290   case Instruction::PtrToInt:
3291   case Instruction::IntToPtr:
3292   case Instruction::SIToFP:
3293   case Instruction::UIToFP:
3294   case Instruction::Trunc:
3295   case Instruction::FPTrunc:
3296   case Instruction::BitCast: {
3297     // We optimize the truncation of induction variable.
3298     // The cost of these is the same as the scalar operation.
3299     if (I->getOpcode() == Instruction::Trunc &&
3300         Legal->isInductionVariable(I->getOperand(0)))
3301       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3302                                   I->getOperand(0)->getType());
3303
3304     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3305     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3306   }
3307   case Instruction::Call: {
3308     assert(isTriviallyVectorizableIntrinsic(I));
3309     IntrinsicInst *II = cast<IntrinsicInst>(I);
3310     Type *RetTy = ToVectorTy(II->getType(), VF);
3311     SmallVector<Type*, 4> Tys;
3312     for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3313       Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3314     return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3315   }
3316   default: {
3317     // We are scalarizing the instruction. Return the cost of the scalar
3318     // instruction, plus the cost of insert and extract into vector
3319     // elements, times the vector width.
3320     unsigned Cost = 0;
3321
3322     if (!RetTy->isVoidTy() && VF != 1) {
3323       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3324                                                 VectorTy);
3325       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3326                                                 VectorTy);
3327
3328       // The cost of inserting the results plus extracting each one of the
3329       // operands.
3330       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3331     }
3332
3333     // The cost of executing VF copies of the scalar instruction. This opcode
3334     // is unknown. Assume that it is the same as 'mul'.
3335     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3336     return Cost;
3337   }
3338   }// end of switch.
3339 }
3340
3341 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3342   if (Scalar->isVoidTy() || VF == 1)
3343     return Scalar;
3344   return VectorType::get(Scalar, VF);
3345 }
3346
3347 char LoopVectorize::ID = 0;
3348 static const char lv_name[] = "Loop Vectorization";
3349 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3350 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3351 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3352 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3353 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3354 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3355
3356 namespace llvm {
3357   Pass *createLoopVectorizePass() {
3358     return new LoopVectorize();
3359   }
3360 }
3361
3362 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3363   // Check for a store.
3364   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
3365     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3366
3367   // Check for a load.
3368   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
3369     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
3370
3371   return false;
3372 }