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