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