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