minor renaming, documentation and cleanups.
[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 #define LV_NAME "loop-vectorize"
45 #define DEBUG_TYPE LV_NAME
46 #include "llvm/Transforms/Vectorize.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/Analysis/AliasAnalysis.h"
50 #include "llvm/Analysis/AliasSetTracker.h"
51 #include "llvm/Analysis/Dominators.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Analysis/ScalarEvolution.h"
55 #include "llvm/Analysis/ScalarEvolutionExpander.h"
56 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
57 #include "llvm/Analysis/ValueTracking.h"
58 #include "llvm/Analysis/Verifier.h"
59 #include "llvm/Constants.h"
60 #include "llvm/DataLayout.h"
61 #include "llvm/DerivedTypes.h"
62 #include "llvm/Function.h"
63 #include "llvm/Instructions.h"
64 #include "llvm/LLVMContext.h"
65 #include "llvm/Module.h"
66 #include "llvm/Pass.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/TargetTransformInfo.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
73 #include "llvm/Transforms/Utils/Local.h"
74 #include "llvm/Type.h"
75 #include "llvm/Value.h"
76 #include <algorithm>
77 using namespace llvm;
78
79 static cl::opt<unsigned>
80 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
81           cl::desc("Set the default vectorization width. Zero is autoselect."));
82
83 static cl::opt<bool>
84 EnableIfConversion("enable-if-conversion", cl::init(false), cl::Hidden,
85                    cl::desc("Enable if-conversion during vectorization."));
86
87 /// We don't vectorize loops with a known constant trip count below this number.
88 const unsigned TinyTripCountThreshold = 16;
89
90 /// When performing a runtime memory check, do not check more than this
91 /// number of pointers. Notice that the check is quadratic!
92 const unsigned RuntimeMemoryCheckThreshold = 2;
93
94 /// This is the highest vector width that we try to generate.
95 const unsigned MaxVectorSize = 8;
96
97 namespace {
98
99 // Forward declarations.
100 class LoopVectorizationLegality;
101 class LoopVectorizationCostModel;
102
103 /// InnerLoopVectorizer vectorizes loops which contain only one basic
104 /// block to a specified vectorization factor (VF).
105 /// This class performs the widening of scalars into vectors, or multiple
106 /// scalars. This class also implements the following features:
107 /// * It inserts an epilogue loop for handling loops that don't have iteration
108 ///   counts that are known to be a multiple of the vectorization factor.
109 /// * It handles the code generation for reduction variables.
110 /// * Scalarization (implementation using scalars) of un-vectorizable
111 ///   instructions.
112 /// InnerLoopVectorizer does not perform any vectorization-legality
113 /// checks, and relies on the caller to check for the different legality
114 /// aspects. The InnerLoopVectorizer relies on the
115 /// LoopVectorizationLegality class to provide information about the induction
116 /// and reduction variables that were found to a given vectorization factor.
117 class InnerLoopVectorizer {
118 public:
119   /// Ctor.
120   InnerLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
121                       DominatorTree *Dt, DataLayout *Dl, unsigned VecWidth):
122   OrigLoop(Orig), SE(Se), LI(Li), DT(Dt), DL(Dl), VF(VecWidth),
123   Builder(Se->getContext()), Induction(0), OldInduction(0) { }
124
125   // Perform the actual loop widening (vectorization).
126   void vectorize(LoopVectorizationLegality *Legal) {
127     // Create a new empty loop. Unlink the old loop and connect the new one.
128     createEmptyLoop(Legal);
129     // Widen each instruction in the old loop to a new one in the new loop.
130     // Use the Legality module to find the induction and reduction variables.
131     vectorizeLoop(Legal);
132     // Register the new loop and update the analysis passes.
133     updateAnalysis();
134  }
135
136 private:
137   /// Add code that checks at runtime if the accessed arrays overlap.
138   /// Returns the comperator value or NULL if no check is needed.
139   Value *addRuntimeCheck(LoopVectorizationLegality *Legal,
140                          Instruction *Loc);
141   /// Create an empty loop, based on the loop ranges of the old loop.
142   void createEmptyLoop(LoopVectorizationLegality *Legal);
143   /// Copy and widen the instructions from the old loop.
144   void vectorizeLoop(LoopVectorizationLegality *Legal);
145   /// Insert the new loop to the loop hierarchy and pass manager
146   /// and update the analysis passes.
147   void updateAnalysis();
148
149   /// This instruction is un-vectorizable. Implement it as a sequence
150   /// of scalars.
151   void scalarizeInstruction(Instruction *Instr);
152
153   /// Create a broadcast instruction. This method generates a broadcast
154   /// instruction (shuffle) for loop invariant values and for the induction
155   /// value. If this is the induction variable then we extend it to N, N+1, ...
156   /// this is needed because each iteration in the loop corresponds to a SIMD
157   /// element.
158   Value *getBroadcastInstrs(Value *V);
159
160   /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
161   /// for each element in the vector. Starting from zero.
162   Value *getConsecutiveVector(Value* Val);
163
164   /// When we go over instructions in the basic block we rely on previous
165   /// values within the current basic block or on loop invariant values.
166   /// When we widen (vectorize) values we place them in the map. If the values
167   /// are not within the map, they have to be loop invariant, so we simply
168   /// broadcast them into a vector.
169   Value *getVectorValue(Value *V);
170
171   /// Get a uniform vector of constant integers. We use this to get
172   /// vectors of ones and zeros for the reduction code.
173   Constant* getUniformVector(unsigned Val, Type* ScalarTy);
174
175   typedef DenseMap<Value*, Value*> ValueMap;
176
177   /// The original loop.
178   Loop *OrigLoop;
179   // Scev analysis to use.
180   ScalarEvolution *SE;
181   // Loop Info.
182   LoopInfo *LI;
183   // Dominator Tree.
184   DominatorTree *DT;
185   // Data Layout.
186   DataLayout *DL;
187   // The vectorization factor to use.
188   unsigned VF;
189
190   // The builder that we use
191   IRBuilder<> Builder;
192
193   // --- Vectorization state ---
194
195   /// The vector-loop preheader.
196   BasicBlock *LoopVectorPreHeader;
197   /// The scalar-loop preheader.
198   BasicBlock *LoopScalarPreHeader;
199   /// Middle Block between the vector and the scalar.
200   BasicBlock *LoopMiddleBlock;
201   ///The ExitBlock of the scalar loop.
202   BasicBlock *LoopExitBlock;
203   ///The vector loop body.
204   BasicBlock *LoopVectorBody;
205   ///The scalar loop body.
206   BasicBlock *LoopScalarBody;
207   ///The first bypass block.
208   BasicBlock *LoopBypassBlock;
209
210   /// The new Induction variable which was added to the new block.
211   PHINode *Induction;
212   /// The induction variable of the old basic block.
213   PHINode *OldInduction;
214   // Maps scalars to widened vectors.
215   ValueMap WidenMap;
216 };
217
218 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
219 /// to what vectorization factor.
220 /// This class does not look at the profitability of vectorization, only the
221 /// legality. This class has two main kinds of checks:
222 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
223 ///   will change the order of memory accesses in a way that will change the
224 ///   correctness of the program.
225 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
226 /// checks for a number of different conditions, such as the availability of a
227 /// single induction variable, that all types are supported and vectorize-able,
228 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
229 /// This class is also used by InnerLoopVectorizer for identifying
230 /// induction variable and the different reduction variables.
231 class LoopVectorizationLegality {
232 public:
233   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl,
234                               DominatorTree *Dt):
235   TheLoop(Lp), SE(Se), DL(Dl), DT(Dt), Induction(0) { }
236
237   /// This represents the kinds of reductions that we support.
238   enum ReductionKind {
239     NoReduction, /// Not a reduction.
240     IntegerAdd,  /// Sum of numbers.
241     IntegerMult, /// Product of numbers.
242     IntegerOr,   /// Bitwise or logical OR of numbers.
243     IntegerAnd,  /// Bitwise or logical AND of numbers.
244     IntegerXor   /// Bitwise or logical XOR of numbers.
245   };
246
247   /// This POD struct holds information about reduction variables.
248   struct ReductionDescriptor {
249     // Default C'tor
250     ReductionDescriptor():
251     StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
252
253     // C'tor.
254     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
255     StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
256
257     // The starting value of the reduction.
258     // It does not have to be zero!
259     Value *StartValue;
260     // The instruction who's value is used outside the loop.
261     Instruction *LoopExitInstr;
262     // The kind of the reduction.
263     ReductionKind Kind;
264   };
265
266   // This POD struct holds information about the memory runtime legality
267   // check that a group of pointers do not overlap.
268   struct RuntimePointerCheck {
269     RuntimePointerCheck(): Need(false) {}
270
271     /// Reset the state of the pointer runtime information.
272     void reset() {
273       Need = false;
274       Pointers.clear();
275       Starts.clear();
276       Ends.clear();
277     }
278
279     /// Insert a pointer and calculate the start and end SCEVs.
280     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr) {
281       const SCEV *Sc = SE->getSCEV(Ptr);
282       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
283       assert(AR && "Invalid addrec expression");
284       const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
285       const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
286       Pointers.push_back(Ptr);
287       Starts.push_back(AR->getStart());
288       Ends.push_back(ScEnd);
289     }
290
291     /// This flag indicates if we need to add the runtime check.
292     bool Need;
293     /// Holds the pointers that we need to check.
294     SmallVector<Value*, 2> Pointers;
295     /// Holds the pointer value at the beginning of the loop.
296     SmallVector<const SCEV*, 2> Starts;
297     /// Holds the pointer value at the end of the loop.
298     SmallVector<const SCEV*, 2> Ends;
299   };
300
301   /// ReductionList contains the reduction descriptors for all
302   /// of the reductions that were found in the loop.
303   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
304
305   /// InductionList saves induction variables and maps them to the initial
306   /// value entring the loop.
307   typedef DenseMap<PHINode*, Value*> InductionList;
308
309   /// Returns true if it is legal to vectorize this loop.
310   /// This does not mean that it is profitable to vectorize this
311   /// loop, only that it is legal to do so.
312   bool canVectorize();
313
314   /// Returns the Induction variable.
315   PHINode *getInduction() {return Induction;}
316
317   /// Returns the reduction variables found in the loop.
318   ReductionList *getReductionVars() { return &Reductions; }
319
320   /// Returns the induction variables found in the loop.
321   InductionList *getInductionVars() { return &Inductions; }
322
323   /// Return true if the block BB needs to be predicated in order for the loop
324   /// to be vectorized.
325   bool blockNeedsPredication(BasicBlock *BB);
326
327   /// Check if this  pointer is consecutive when vectorizing. This happens
328   /// when the last index of the GEP is the induction variable, or that the
329   /// pointer itself is an induction variable.
330   /// This check allows us to vectorize A[idx] into a wide load/store.
331   bool isConsecutivePtr(Value *Ptr);
332
333   /// Returns true if the value V is uniform within the loop.
334   bool isUniform(Value *V);
335
336   /// Returns true if this instruction will remain scalar after vectorization.
337   bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
338
339   /// Returns the information that we collected about runtime memory check.
340   RuntimePointerCheck *getRuntimePointerCheck() {return &PtrRtCheck; }
341 private:
342   /// Check if a single basic block loop is vectorizable.
343   /// At this point we know that this is a loop with a constant trip count
344   /// and we only need to check individual instructions.
345   bool canVectorizeInstrs();
346
347   /// When we vectorize loops we may change the order in which
348   /// we read and write from memory. This method checks if it is
349   /// legal to vectorize the code, considering only memory constrains.
350   /// Returns true if the loop is vectorizable
351   bool canVectorizeMemory();
352
353   /// Return true if we can vectorize this loop using the IF-conversion
354   /// transformation.
355   bool canVectorizeWithIfConvert();
356
357   /// Collect the variables that need to stay uniform after vectorization.
358   void collectLoopUniforms();
359
360   /// Return true if all of the instructions in the block can be speculatively
361   /// executed.
362   bool blockCanBePredicated(BasicBlock *BB);
363
364   /// Returns True, if 'Phi' is the kind of reduction variable for type
365   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
366   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
367   /// Returns true if the instruction I can be a reduction variable of type
368   /// 'Kind'.
369   bool isReductionInstr(Instruction *I, ReductionKind Kind);
370   /// Returns True, if 'Phi' is an induction variable.
371   bool isInductionVariable(PHINode *Phi);
372   /// Return true if can compute the address bounds of Ptr within the loop.
373   bool hasComputableBounds(Value *Ptr);
374
375   /// The loop that we evaluate.
376   Loop *TheLoop;
377   /// Scev analysis.
378   ScalarEvolution *SE;
379   /// DataLayout analysis.
380   DataLayout *DL;
381   // Dominators.
382   DominatorTree *DT;
383
384   //  ---  vectorization state --- //
385
386   /// Holds the integer induction variable. This is the counter of the
387   /// loop.
388   PHINode *Induction;
389   /// Holds the reduction variables.
390   ReductionList Reductions;
391   /// Holds all of the induction variables that we found in the loop.
392   /// Notice that inductions don't need to start at zero and that induction
393   /// variables can be pointers.
394   InductionList Inductions;
395
396   /// Allowed outside users. This holds the reduction
397   /// vars which can be accessed from outside the loop.
398   SmallPtrSet<Value*, 4> AllowedExit;
399   /// This set holds the variables which are known to be uniform after
400   /// vectorization.
401   SmallPtrSet<Instruction*, 4> Uniforms;
402   /// We need to check that all of the pointers in this list are disjoint
403   /// at runtime.
404   RuntimePointerCheck PtrRtCheck;
405 };
406
407 /// LoopVectorizationCostModel - estimates the expected speedups due to
408 /// vectorization.
409 /// In many cases vectorization is not profitable. This can happen because
410 /// of a number of reasons. In this class we mainly attempt to predict
411 /// the expected speedup/slowdowns due to the supported instruction set.
412 /// We use the VectorTargetTransformInfo to query the different backends
413 /// for the cost of different operations.
414 class LoopVectorizationCostModel {
415 public:
416   /// C'tor.
417   LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
418                              LoopVectorizationLegality *Leg,
419                              const VectorTargetTransformInfo *Vtti):
420   TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
421
422   /// Returns the most profitable vectorization factor for the loop that is
423   /// smaller or equal to the VF argument. This method checks every power
424   /// of two up to VF.
425   unsigned findBestVectorizationFactor(unsigned VF = MaxVectorSize);
426
427 private:
428   /// Returns the expected execution cost. The unit of the cost does
429   /// not matter because we use the 'cost' units to compare different
430   /// vector widths. The cost that is returned is *not* normalized by
431   /// the factor width.
432   unsigned expectedCost(unsigned VF);
433
434   /// Returns the execution time cost of an instruction for a given vector
435   /// width. Vector width of one means scalar.
436   unsigned getInstructionCost(Instruction *I, unsigned VF);
437
438   /// A helper function for converting Scalar types to vector types.
439   /// If the incoming type is void, we return void. If the VF is 1, we return
440   /// the scalar type.
441   static Type* ToVectorTy(Type *Scalar, unsigned VF);
442
443   /// The loop that we evaluate.
444   Loop *TheLoop;
445   /// Scev analysis.
446   ScalarEvolution *SE;
447
448   /// Vectorization legality.
449   LoopVectorizationLegality *Legal;
450   /// Vector target information.
451   const VectorTargetTransformInfo *VTTI;
452 };
453
454 struct LoopVectorize : public LoopPass {
455   static char ID; // Pass identification, replacement for typeid
456
457   LoopVectorize() : LoopPass(ID) {
458     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
459   }
460
461   ScalarEvolution *SE;
462   DataLayout *DL;
463   LoopInfo *LI;
464   TargetTransformInfo *TTI;
465   DominatorTree *DT;
466
467   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
468     // We only vectorize innermost loops.
469     if (!L->empty())
470       return false;
471
472     SE = &getAnalysis<ScalarEvolution>();
473     DL = getAnalysisIfAvailable<DataLayout>();
474     LI = &getAnalysis<LoopInfo>();
475     TTI = getAnalysisIfAvailable<TargetTransformInfo>();
476     DT = &getAnalysis<DominatorTree>();
477
478     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
479           L->getHeader()->getParent()->getName() << "\"\n");
480
481     // Check if it is legal to vectorize the loop.
482     LoopVectorizationLegality LVL(L, SE, DL, DT);
483     if (!LVL.canVectorize()) {
484       DEBUG(dbgs() << "LV: Not vectorizing.\n");
485       return false;
486     }
487
488     // Select the preffered vectorization factor.
489     unsigned VF = 1;
490     if (VectorizationFactor == 0) {
491       const VectorTargetTransformInfo *VTTI = 0;
492       if (TTI)
493         VTTI = TTI->getVectorTargetTransformInfo();
494       // Use the cost model.
495       LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
496       VF = CM.findBestVectorizationFactor();
497
498       if (VF == 1) {
499         DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
500         return false;
501       }
502
503     } else {
504       // Use the user command flag.
505       VF = VectorizationFactor;
506     }
507
508     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
509           L->getHeader()->getParent()->getParent()->getModuleIdentifier()<<
510           "\n");
511
512     // If we decided that it is *legal* to vectorizer the loop then do it.
513     InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
514     LB.vectorize(&LVL);
515
516     DEBUG(verifyFunction(*L->getHeader()->getParent()));
517     return true;
518   }
519
520   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
521     LoopPass::getAnalysisUsage(AU);
522     AU.addRequiredID(LoopSimplifyID);
523     AU.addRequiredID(LCSSAID);
524     AU.addRequired<LoopInfo>();
525     AU.addRequired<ScalarEvolution>();
526     AU.addRequired<DominatorTree>();
527     AU.addPreserved<LoopInfo>();
528     AU.addPreserved<DominatorTree>();
529   }
530
531 };
532
533 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
534   // Create the types.
535   LLVMContext &C = V->getContext();
536   Type *VTy = VectorType::get(V->getType(), VF);
537   Type *I32 = IntegerType::getInt32Ty(C);
538
539   // Save the current insertion location.
540   Instruction *Loc = Builder.GetInsertPoint();
541
542   // We need to place the broadcast of invariant variables outside the loop.
543   bool Invariant = (OrigLoop->isLoopInvariant(V) && V != Induction);
544
545   // Place the code for broadcasting invariant variables in the new preheader.
546   if (Invariant)
547     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
548
549   Constant *Zero = ConstantInt::get(I32, 0);
550   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
551   Value *UndefVal = UndefValue::get(VTy);
552   // Insert the value into a new vector.
553   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
554   // Broadcast the scalar into all locations in the vector.
555   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
556                                              "broadcast");
557
558   // Restore the builder insertion point.
559   if (Invariant)
560     Builder.SetInsertPoint(Loc);
561
562   return Shuf;
563 }
564
565 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val) {
566   assert(Val->getType()->isVectorTy() && "Must be a vector");
567   assert(Val->getType()->getScalarType()->isIntegerTy() &&
568          "Elem must be an integer");
569   // Create the types.
570   Type *ITy = Val->getType()->getScalarType();
571   VectorType *Ty = cast<VectorType>(Val->getType());
572   unsigned VLen = Ty->getNumElements();
573   SmallVector<Constant*, 8> Indices;
574
575   // Create a vector of consecutive numbers from zero to VF.
576   for (unsigned i = 0; i < VLen; ++i)
577     Indices.push_back(ConstantInt::get(ITy, i));
578
579   // Add the consecutive indices to the vector value.
580   Constant *Cv = ConstantVector::get(Indices);
581   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
582   return Builder.CreateAdd(Val, Cv, "induction");
583 }
584
585 bool LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
586   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
587
588   // If this pointer is an induction variable, return it.
589   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
590   if (Phi && getInductionVars()->count(Phi))
591     return true;
592
593   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
594   if (!Gep)
595     return false;
596
597   unsigned NumOperands = Gep->getNumOperands();
598   Value *LastIndex = Gep->getOperand(NumOperands - 1);
599
600   // Check that all of the gep indices are uniform except for the last.
601   for (unsigned i = 0; i < NumOperands - 1; ++i)
602     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
603       return false;
604
605   // We can emit wide load/stores only if the last index is the induction
606   // variable.
607   const SCEV *Last = SE->getSCEV(LastIndex);
608   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
609     const SCEV *Step = AR->getStepRecurrence(*SE);
610
611     // The memory is consecutive because the last index is consecutive
612     // and all other indices are loop invariant.
613     if (Step->isOne())
614       return true;
615   }
616
617   return false;
618 }
619
620 bool LoopVectorizationLegality::isUniform(Value *V) {
621   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
622 }
623
624 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
625   assert(V != Induction && "The new induction variable should not be used.");
626   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
627   // If we saved a vectorized copy of V, use it.
628   Value *&MapEntry = WidenMap[V];
629   if (MapEntry)
630     return MapEntry;
631
632   // Broadcast V and save the value for future uses.
633   Value *B = getBroadcastInstrs(V);
634   MapEntry = B;
635   return B;
636 }
637
638 Constant*
639 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
640   return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
641 }
642
643 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
644   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
645   // Holds vector parameters or scalars, in case of uniform vals.
646   SmallVector<Value*, 8> Params;
647
648   // Find all of the vectorized parameters.
649   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
650     Value *SrcOp = Instr->getOperand(op);
651
652     // If we are accessing the old induction variable, use the new one.
653     if (SrcOp == OldInduction) {
654       Params.push_back(getVectorValue(SrcOp));
655       continue;
656     }
657
658     // Try using previously calculated values.
659     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
660
661     // If the src is an instruction that appeared earlier in the basic block
662     // then it should already be vectorized.
663     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
664       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
665       // The parameter is a vector value from earlier.
666       Params.push_back(WidenMap[SrcInst]);
667     } else {
668       // The parameter is a scalar from outside the loop. Maybe even a constant.
669       Params.push_back(SrcOp);
670     }
671   }
672
673   assert(Params.size() == Instr->getNumOperands() &&
674          "Invalid number of operands");
675
676   // Does this instruction return a value ?
677   bool IsVoidRetTy = Instr->getType()->isVoidTy();
678   Value *VecResults = 0;
679
680   // If we have a return value, create an empty vector. We place the scalarized
681   // instructions in this vector.
682   if (!IsVoidRetTy)
683     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
684
685   // For each scalar that we create:
686   for (unsigned i = 0; i < VF; ++i) {
687     Instruction *Cloned = Instr->clone();
688     if (!IsVoidRetTy)
689       Cloned->setName(Instr->getName() + ".cloned");
690     // Replace the operands of the cloned instrucions with extracted scalars.
691     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
692       Value *Op = Params[op];
693       // Param is a vector. Need to extract the right lane.
694       if (Op->getType()->isVectorTy())
695         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
696       Cloned->setOperand(op, Op);
697     }
698
699     // Place the cloned scalar in the new loop.
700     Builder.Insert(Cloned);
701
702     // If the original scalar returns a value we need to place it in a vector
703     // so that future users will be able to use it.
704     if (!IsVoidRetTy)
705       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
706                                                Builder.getInt32(i));
707   }
708
709   if (!IsVoidRetTy)
710     WidenMap[Instr] = VecResults;
711 }
712
713 Value*
714 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
715                                            Instruction *Loc) {
716   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
717     Legal->getRuntimePointerCheck();
718
719   if (!PtrRtCheck->Need)
720     return NULL;
721
722   Value *MemoryRuntimeCheck = 0;
723   unsigned NumPointers = PtrRtCheck->Pointers.size();
724   SmallVector<Value* , 2> Starts;
725   SmallVector<Value* , 2> Ends;
726
727   SCEVExpander Exp(*SE, "induction");
728
729   // Use this type for pointer arithmetic.
730   Type* PtrArithTy = PtrRtCheck->Pointers[0]->getType();
731
732   for (unsigned i = 0; i < NumPointers; ++i) {
733     Value *Ptr = PtrRtCheck->Pointers[i];
734     const SCEV *Sc = SE->getSCEV(Ptr);
735
736     if (SE->isLoopInvariant(Sc, OrigLoop)) {
737       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
738             *Ptr <<"\n");
739       Starts.push_back(Ptr);
740       Ends.push_back(Ptr);
741     } else {
742       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
743
744       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i],
745                                        PtrArithTy, Loc);
746       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
747       Starts.push_back(Start);
748       Ends.push_back(End);
749     }
750   }
751
752   for (unsigned i = 0; i < NumPointers; ++i) {
753     for (unsigned j = i+1; j < NumPointers; ++j) {
754       Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
755                                     Starts[i], Ends[j], "bound0", Loc);
756       Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
757                                     Starts[j], Ends[i], "bound1", Loc);
758       Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
759                                                  "found.conflict", Loc);
760       if (MemoryRuntimeCheck)
761         MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
762                                                     MemoryRuntimeCheck,
763                                                     IsConflict,
764                                                     "conflict.rdx", Loc);
765       else
766         MemoryRuntimeCheck = IsConflict;
767
768     }
769   }
770
771   return MemoryRuntimeCheck;
772 }
773
774 void
775 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
776   /*
777    In this function we generate a new loop. The new loop will contain
778    the vectorized instructions while the old loop will continue to run the
779    scalar remainder.
780
781     [ ] <-- vector loop bypass.
782   /  |
783  /   v
784 |   [ ]     <-- vector pre header.
785 |    |
786 |    v
787 |   [  ] \
788 |   [  ]_|   <-- vector loop.
789 |    |
790  \   v
791    >[ ]   <--- middle-block.
792   /  |
793  /   v
794 |   [ ]     <--- new preheader.
795 |    |
796 |    v
797 |   [ ] \
798 |   [ ]_|   <-- old scalar loop to handle remainder.
799  \   |
800   \  v
801    >[ ]     <-- exit block.
802    ...
803    */
804
805   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
806   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
807   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
808   assert(ExitBlock && "Must have an exit block");
809
810   // Some loops have a single integer induction variable, while other loops
811   // don't. One example is c++ iterators that often have multiple pointer
812   // induction variables. In the code below we also support a case where we
813   // don't have a single induction variable.
814   OldInduction = Legal->getInduction();
815   Type *IdxTy = OldInduction ? OldInduction->getType() :
816     DL->getIntPtrType(SE->getContext());
817
818   // Find the loop boundaries.
819   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getHeader());
820   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
821
822   // Get the total trip count from the count by adding 1.
823   ExitCount = SE->getAddExpr(ExitCount,
824                              SE->getConstant(ExitCount->getType(), 1));
825
826   // Expand the trip count and place the new instructions in the preheader.
827   // Notice that the pre-header does not change, only the loop body.
828   SCEVExpander Exp(*SE, "induction");
829
830   // Count holds the overall loop count (N).
831   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
832                                    BypassBlock->getTerminator());
833
834   // The loop index does not have to start at Zero. Find the original start
835   // value from the induction PHI node. If we don't have an induction variable
836   // then we know that it starts at zero.
837   Value *StartIdx = OldInduction ?
838     OldInduction->getIncomingValueForBlock(BypassBlock):
839     ConstantInt::get(IdxTy, 0);
840
841   assert(OrigLoop->getNumBlocks() == 1 && "Invalid loop");
842   assert(BypassBlock && "Invalid loop structure");
843
844   // Generate the code that checks in runtime if arrays overlap.
845   Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
846                                               BypassBlock->getTerminator());
847
848   // Split the single block loop into the two loop structure described above.
849   BasicBlock *VectorPH =
850       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
851   BasicBlock *VecBody =
852     VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
853   BasicBlock *MiddleBlock =
854     VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
855   BasicBlock *ScalarPH =
856     MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
857
858   // This is the location in which we add all of the logic for bypassing
859   // the new vector loop.
860   Instruction *Loc = BypassBlock->getTerminator();
861
862   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
863   // inside the loop.
864   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
865
866   // Generate the induction variable.
867   Induction = Builder.CreatePHI(IdxTy, 2, "index");
868   Constant *Step = ConstantInt::get(IdxTy, VF);
869
870   // We may need to extend the index in case there is a type mismatch.
871   // We know that the count starts at zero and does not overflow.
872   if (Count->getType() != IdxTy) {
873     // The exit count can be of pointer type. Convert it to the correct
874     // integer type.
875     if (ExitCount->getType()->isPointerTy())
876       Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
877     else
878       Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
879   }
880
881   // Add the start index to the loop count to get the new end index.
882   Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
883
884   // Now we need to generate the expression for N - (N % VF), which is
885   // the part that the vectorized body will execute.
886   Constant *CIVF = ConstantInt::get(IdxTy, VF);
887   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
888   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
889   Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
890                                                      "end.idx.rnd.down", Loc);
891
892   // Now, compare the new count to zero. If it is zero skip the vector loop and
893   // jump to the scalar loop.
894   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
895                                IdxEndRoundDown,
896                                StartIdx,
897                                "cmp.zero", Loc);
898
899   // If we are using memory runtime checks, include them in.
900   if (MemoryRuntimeCheck)
901     Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
902                                  "CntOrMem", Loc);
903
904   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
905   // Remove the old terminator.
906   Loc->eraseFromParent();
907
908   // We are going to resume the execution of the scalar loop.
909   // Go over all of the induction variables that we found and fix the
910   // PHIs that are left in the scalar version of the loop.
911   // The starting values of PHI nodes depend on the counter of the last
912   // iteration in the vectorized loop.
913   // If we come from a bypass edge then we need to start from the original start
914   // value.
915
916   // This variable saves the new starting index for the scalar loop.
917   PHINode *ResumeIndex = 0;
918   LoopVectorizationLegality::InductionList::iterator I, E;
919   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
920   for (I = List->begin(), E = List->end(); I != E; ++I) {
921     PHINode *OrigPhi = I->first;
922     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
923                                            MiddleBlock->getTerminator());
924     Value *EndValue = 0;
925     if (OrigPhi->getType()->isIntegerTy()) {
926       // Handle the integer induction counter:
927       assert(OrigPhi == OldInduction && "Unknown integer PHI");
928       // We know what the end value is.
929       EndValue = IdxEndRoundDown;
930       // We also know which PHI node holds it.
931       ResumeIndex = ResumeVal;
932     } else {
933       // For pointer induction variables, calculate the offset using
934       // the end index.
935       EndValue = GetElementPtrInst::Create(I->second, CountRoundDown,
936                                            "ptr.ind.end",
937                                            BypassBlock->getTerminator());
938     }
939
940     // The new PHI merges the original incoming value, in case of a bypass,
941     // or the value at the end of the vectorized loop.
942     ResumeVal->addIncoming(I->second, BypassBlock);
943     ResumeVal->addIncoming(EndValue, VecBody);
944
945     // Fix the scalar body counter (PHI node).
946     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
947     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
948   }
949
950   // If we are generating a new induction variable then we also need to
951   // generate the code that calculates the exit value. This value is not
952   // simply the end of the counter because we may skip the vectorized body
953   // in case of a runtime check.
954   if (!OldInduction){
955     assert(!ResumeIndex && "Unexpected resume value found");
956     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
957                                   MiddleBlock->getTerminator());
958     ResumeIndex->addIncoming(StartIdx, BypassBlock);
959     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
960   }
961
962   // Make sure that we found the index where scalar loop needs to continue.
963   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
964          "Invalid resume Index");
965
966   // Add a check in the middle block to see if we have completed
967   // all of the iterations in the first vector loop.
968   // If (N - N%VF) == N, then we *don't* need to run the remainder.
969   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
970                                 ResumeIndex, "cmp.n",
971                                 MiddleBlock->getTerminator());
972
973   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
974   // Remove the old terminator.
975   MiddleBlock->getTerminator()->eraseFromParent();
976
977   // Create i+1 and fill the PHINode.
978   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
979   Induction->addIncoming(StartIdx, VectorPH);
980   Induction->addIncoming(NextIdx, VecBody);
981   // Create the compare.
982   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
983   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
984
985   // Now we have two terminators. Remove the old one from the block.
986   VecBody->getTerminator()->eraseFromParent();
987
988   // Get ready to start creating new instructions into the vectorized body.
989   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
990
991   // Create and register the new vector loop.
992   Loop* Lp = new Loop();
993   Loop *ParentLoop = OrigLoop->getParentLoop();
994
995   // Insert the new loop into the loop nest and register the new basic blocks.
996   if (ParentLoop) {
997     ParentLoop->addChildLoop(Lp);
998     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
999     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1000     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1001   } else {
1002     LI->addTopLevelLoop(Lp);
1003   }
1004
1005   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1006
1007   // Save the state.
1008   LoopVectorPreHeader = VectorPH;
1009   LoopScalarPreHeader = ScalarPH;
1010   LoopMiddleBlock = MiddleBlock;
1011   LoopExitBlock = ExitBlock;
1012   LoopVectorBody = VecBody;
1013   LoopScalarBody = OldBasicBlock;
1014   LoopBypassBlock = BypassBlock;
1015 }
1016
1017 /// This function returns the identity element (or neutral element) for
1018 /// the operation K.
1019 static unsigned
1020 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
1021   switch (K) {
1022   case LoopVectorizationLegality::IntegerXor:
1023   case LoopVectorizationLegality::IntegerAdd:
1024   case LoopVectorizationLegality::IntegerOr:
1025     // Adding, Xoring, Oring zero to a number does not change it.
1026     return 0;
1027   case LoopVectorizationLegality::IntegerMult:
1028     // Multiplying a number by 1 does not change it.
1029     return 1;
1030   case LoopVectorizationLegality::IntegerAnd:
1031     // AND-ing a number with an all-1 value does not change it.
1032     return -1;
1033   default:
1034     llvm_unreachable("Unknown reduction kind");
1035   }
1036 }
1037
1038 void
1039 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1040   //===------------------------------------------------===//
1041   //
1042   // Notice: any optimization or new instruction that go
1043   // into the code below should be also be implemented in
1044   // the cost-model.
1045   //
1046   //===------------------------------------------------===//
1047   typedef SmallVector<PHINode*, 4> PhiVector;
1048   BasicBlock &BB = *OrigLoop->getHeader();
1049   Constant *Zero = ConstantInt::get(
1050     IntegerType::getInt32Ty(BB.getContext()), 0);
1051
1052   // In order to support reduction variables we need to be able to vectorize
1053   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1054   // stages. First, we create a new vector PHI node with no incoming edges.
1055   // We use this value when we vectorize all of the instructions that use the
1056   // PHI. Next, after all of the instructions in the block are complete we
1057   // add the new incoming edges to the PHI. At this point all of the
1058   // instructions in the basic block are vectorized, so we can use them to
1059   // construct the PHI.
1060   PhiVector RdxPHIsToFix;
1061
1062   // For each instruction in the old loop.
1063   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1064     Instruction *Inst = it;
1065
1066     switch (Inst->getOpcode()) {
1067       case Instruction::Br:
1068         // Nothing to do for PHIs and BR, since we already took care of the
1069         // loop control flow instructions.
1070         continue;
1071       case Instruction::PHI:{
1072         PHINode* P = cast<PHINode>(Inst);
1073         // Handle reduction variables:
1074         if (Legal->getReductionVars()->count(P)) {
1075           // This is phase one of vectorizing PHIs.
1076           Type *VecTy = VectorType::get(Inst->getType(), VF);
1077           WidenMap[Inst] = PHINode::Create(VecTy, 2, "vec.phi",
1078                                   LoopVectorBody->getFirstInsertionPt());
1079           RdxPHIsToFix.push_back(P);
1080           continue;
1081         }
1082
1083         // This PHINode must be an induction variable.
1084         // Make sure that we know about it.
1085         assert(Legal->getInductionVars()->count(P) &&
1086                "Not an induction variable");
1087
1088         if (P->getType()->isIntegerTy()) {
1089           assert(P == OldInduction && "Unexpected PHI");
1090           Value *Broadcasted = getBroadcastInstrs(Induction);
1091           // After broadcasting the induction variable we need to make the
1092           // vector consecutive by adding 0, 1, 2 ...
1093           Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1094            
1095           WidenMap[OldInduction] = ConsecutiveInduction;
1096           continue;
1097         }
1098
1099         // Handle pointer inductions.
1100         assert(P->getType()->isPointerTy() && "Unexpected type.");
1101         Value *StartIdx = OldInduction ?
1102           Legal->getInductionVars()->lookup(OldInduction) :
1103           ConstantInt::get(Induction->getType(), 0);
1104
1105         // This is the pointer value coming into the loop.
1106         Value *StartPtr = Legal->getInductionVars()->lookup(P);
1107
1108         // This is the normalized GEP that starts counting at zero.
1109         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1110                                                  "normalized.idx");
1111
1112         // This is the vector of results. Notice that we don't generate vector
1113         // geps because scalar geps result in better code.
1114         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1115         for (unsigned int i = 0; i < VF; ++i) {
1116           Constant *Idx = ConstantInt::get(Induction->getType(), i);
1117           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1118           Value *SclrGep = Builder.CreateGEP(StartPtr, GlobalIdx, "next.gep");
1119           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1120                                                Builder.getInt32(i),
1121                                                "insert.gep");
1122         }
1123
1124         WidenMap[Inst] = VecVal;
1125         continue;
1126       }
1127       case Instruction::Add:
1128       case Instruction::FAdd:
1129       case Instruction::Sub:
1130       case Instruction::FSub:
1131       case Instruction::Mul:
1132       case Instruction::FMul:
1133       case Instruction::UDiv:
1134       case Instruction::SDiv:
1135       case Instruction::FDiv:
1136       case Instruction::URem:
1137       case Instruction::SRem:
1138       case Instruction::FRem:
1139       case Instruction::Shl:
1140       case Instruction::LShr:
1141       case Instruction::AShr:
1142       case Instruction::And:
1143       case Instruction::Or:
1144       case Instruction::Xor: {
1145         // Just widen binops.
1146         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1147         Value *A = getVectorValue(Inst->getOperand(0));
1148         Value *B = getVectorValue(Inst->getOperand(1));
1149
1150         // Use this vector value for all users of the original instruction.
1151         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1152         WidenMap[Inst] = V;
1153
1154         // Update the NSW, NUW and Exact flags.
1155         BinaryOperator *VecOp = cast<BinaryOperator>(V);
1156         if (isa<OverflowingBinaryOperator>(BinOp)) {
1157           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1158           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1159         }
1160         if (isa<PossiblyExactOperator>(VecOp))
1161           VecOp->setIsExact(BinOp->isExact());
1162         break;
1163       }
1164       case Instruction::Select: {
1165         // Widen selects.
1166         // If the selector is loop invariant we can create a select
1167         // instruction with a scalar condition. Otherwise, use vector-select.
1168         Value *Cond = Inst->getOperand(0);
1169         bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1170
1171         // The condition can be loop invariant  but still defined inside the
1172         // loop. This means that we can't just use the original 'cond' value.
1173         // We have to take the 'vectorized' value and pick the first lane.
1174         // Instcombine will make this a no-op.
1175         Cond = getVectorValue(Cond);
1176         if (InvariantCond)
1177           Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1178
1179         Value *Op0 = getVectorValue(Inst->getOperand(1));
1180         Value *Op1 = getVectorValue(Inst->getOperand(2));
1181         WidenMap[Inst] = Builder.CreateSelect(Cond, Op0, Op1);
1182         break;
1183       }
1184
1185       case Instruction::ICmp:
1186       case Instruction::FCmp: {
1187         // Widen compares. Generate vector compares.
1188         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
1189         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
1190         Value *A = getVectorValue(Inst->getOperand(0));
1191         Value *B = getVectorValue(Inst->getOperand(1));
1192         if (FCmp)
1193           WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1194         else
1195           WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1196         break;
1197       }
1198
1199       case Instruction::Store: {
1200         // Attempt to issue a wide store.
1201         StoreInst *SI = dyn_cast<StoreInst>(Inst);
1202         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1203         Value *Ptr = SI->getPointerOperand();
1204         unsigned Alignment = SI->getAlignment();
1205
1206         assert(!Legal->isUniform(Ptr) &&
1207                "We do not allow storing to uniform addresses");
1208
1209         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1210
1211         // This store does not use GEPs.
1212         if (!Legal->isConsecutivePtr(Ptr)) {
1213           scalarizeInstruction(Inst);
1214           break;
1215         }
1216
1217         if (Gep) {
1218           // The last index does not have to be the induction. It can be
1219           // consecutive and be a function of the index. For example A[I+1];
1220           unsigned NumOperands = Gep->getNumOperands();
1221           Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1222           LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1223
1224           // Create the new GEP with the new induction variable.
1225           GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1226           Gep2->setOperand(NumOperands - 1, LastIndex);
1227           Ptr = Builder.Insert(Gep2);
1228         } else {
1229           // Use the induction element ptr.
1230           assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1231           Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1232         }
1233         Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1234         Value *Val = getVectorValue(SI->getValueOperand());
1235         Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1236         break;
1237       }
1238       case Instruction::Load: {
1239         // Attempt to issue a wide load.
1240         LoadInst *LI = dyn_cast<LoadInst>(Inst);
1241         Type *RetTy = VectorType::get(LI->getType(), VF);
1242         Value *Ptr = LI->getPointerOperand();
1243         unsigned Alignment = LI->getAlignment();
1244         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1245
1246         // If the pointer is loop invariant or if it is non consecutive,
1247         // scalarize the load.
1248         bool Con = Legal->isConsecutivePtr(Ptr);
1249         if (Legal->isUniform(Ptr) || !Con) {
1250           scalarizeInstruction(Inst);
1251           break;
1252         }
1253
1254         if (Gep) {
1255           // The last index does not have to be the induction. It can be
1256           // consecutive and be a function of the index. For example A[I+1];
1257           unsigned NumOperands = Gep->getNumOperands();
1258           Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1259           LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1260
1261           // Create the new GEP with the new induction variable.
1262           GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1263           Gep2->setOperand(NumOperands - 1, LastIndex);
1264           Ptr = Builder.Insert(Gep2);
1265         } else {
1266           // Use the induction element ptr.
1267           assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1268           Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1269         }
1270
1271         Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1272         LI = Builder.CreateLoad(Ptr);
1273         LI->setAlignment(Alignment);
1274         // Use this vector value for all users of the load.
1275         WidenMap[Inst] = LI;
1276         break;
1277       }
1278       case Instruction::ZExt:
1279       case Instruction::SExt:
1280       case Instruction::FPToUI:
1281       case Instruction::FPToSI:
1282       case Instruction::FPExt:
1283       case Instruction::PtrToInt:
1284       case Instruction::IntToPtr:
1285       case Instruction::SIToFP:
1286       case Instruction::UIToFP:
1287       case Instruction::Trunc:
1288       case Instruction::FPTrunc:
1289       case Instruction::BitCast: {
1290         /// Vectorize bitcasts.
1291         CastInst *CI = dyn_cast<CastInst>(Inst);
1292         Value *A = getVectorValue(Inst->getOperand(0));
1293         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1294         WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1295         break;
1296       }
1297
1298       default:
1299         /// All other instructions are unsupported. Scalarize them.
1300         scalarizeInstruction(Inst);
1301         break;
1302     }// end of switch.
1303   }// end of for_each instr.
1304
1305   // At this point every instruction in the original loop is widended to
1306   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1307   // that we vectorized. The PHI nodes are currently empty because we did
1308   // not want to introduce cycles. Notice that the remaining PHI nodes
1309   // that we need to fix are reduction variables.
1310
1311   // Create the 'reduced' values for each of the induction vars.
1312   // The reduced values are the vector values that we scalarize and combine
1313   // after the loop is finished.
1314   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1315        it != e; ++it) {
1316     PHINode *RdxPhi = *it;
1317     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
1318     assert(RdxPhi && "Unable to recover vectorized PHI");
1319
1320     // Find the reduction variable descriptor.
1321     assert(Legal->getReductionVars()->count(RdxPhi) &&
1322            "Unable to find the reduction variable");
1323     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1324       (*Legal->getReductionVars())[RdxPhi];
1325
1326     // We need to generate a reduction vector from the incoming scalar.
1327     // To do so, we need to generate the 'identity' vector and overide
1328     // one of the elements with the incoming scalar reduction. We need
1329     // to do it in the vector-loop preheader.
1330     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1331
1332     // This is the vector-clone of the value that leaves the loop.
1333     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1334     Type *VecTy = VectorExit->getType();
1335
1336     // Find the reduction identity variable. Zero for addition, or, xor,
1337     // one for multiplication, -1 for And.
1338     Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
1339                                           VecTy->getScalarType());
1340
1341     // This vector is the Identity vector where the first element is the
1342     // incoming scalar reduction.
1343     Value *VectorStart = Builder.CreateInsertElement(Identity,
1344                                                     RdxDesc.StartValue, Zero);
1345
1346     // Fix the vector-loop phi.
1347     // We created the induction variable so we know that the
1348     // preheader is the first entry.
1349     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1350
1351     // Reductions do not have to start at zero. They can start with
1352     // any loop invariant values.
1353     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
1354     unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1355     Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
1356     VecRdxPhi->addIncoming(Val, LoopVectorBody);
1357
1358     // Before each round, move the insertion point right between
1359     // the PHIs and the values we are going to write.
1360     // This allows us to write both PHINodes and the extractelement
1361     // instructions.
1362     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1363
1364     // This PHINode contains the vectorized reduction variable, or
1365     // the initial value vector, if we bypass the vector loop.
1366     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1367     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
1368     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
1369
1370     // Extract the first scalar.
1371     Value *Scalar0 =
1372       Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
1373     // Extract and reduce the remaining vector elements.
1374     for (unsigned i=1; i < VF; ++i) {
1375       Value *Scalar1 =
1376         Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
1377       switch (RdxDesc.Kind) {
1378         case LoopVectorizationLegality::IntegerAdd:
1379           Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
1380           break;
1381         case LoopVectorizationLegality::IntegerMult:
1382           Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
1383           break;
1384         case LoopVectorizationLegality::IntegerOr:
1385           Scalar0 = Builder.CreateOr(Scalar0, Scalar1);
1386           break;
1387         case LoopVectorizationLegality::IntegerAnd:
1388           Scalar0 = Builder.CreateAnd(Scalar0, Scalar1);
1389           break;
1390         case LoopVectorizationLegality::IntegerXor:
1391           Scalar0 = Builder.CreateXor(Scalar0, Scalar1);
1392           break;
1393         default:
1394           llvm_unreachable("Unknown reduction operation");
1395       }
1396     }
1397
1398     // Now, we need to fix the users of the reduction variable
1399     // inside and outside of the scalar remainder loop.
1400     // We know that the loop is in LCSSA form. We need to update the
1401     // PHI nodes in the exit blocks.
1402     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1403          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1404       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1405       if (!LCSSAPhi) continue;
1406
1407       // All PHINodes need to have a single entry edge, or two if
1408       // we already fixed them.
1409       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1410
1411       // We found our reduction value exit-PHI. Update it with the
1412       // incoming bypass edge.
1413       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1414         // Add an edge coming from the bypass.
1415         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1416         break;
1417       }
1418     }// end of the LCSSA phi scan.
1419
1420     // Fix the scalar loop reduction variable with the incoming reduction sum
1421     // from the vector body and from the backedge value.
1422     int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1423     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
1424     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1425     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1426   }// end of for each redux variable.
1427 }
1428
1429 void InnerLoopVectorizer::updateAnalysis() {
1430   // Forget the original basic block.
1431   SE->forgetLoop(OrigLoop);
1432
1433   // Update the dominator tree information.
1434   assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1435          "Entry does not dominate exit.");
1436
1437   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1438   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1439   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1440   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1441   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1442   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1443
1444   DEBUG(DT->verifyAnalysis());
1445 }
1446
1447
1448 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1449   if (!EnableIfConversion)
1450     return false;
1451
1452   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1453   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1454
1455   // Collect the blocks that need predication.
1456   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1457     BasicBlock *BB = LoopBlocks[i];
1458
1459     // We must have at most two predecessors because we need to convert
1460     // all PHIs to selects.
1461     unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1462     if (Preds > 2)
1463       return false;
1464
1465     // We must be able to predicate all blocks that need to be predicated.
1466     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1467       return false;
1468   }
1469
1470   // We can if-convert this loop.
1471   return true;
1472 }
1473
1474 bool LoopVectorizationLegality::canVectorize() {
1475   assert(TheLoop->getLoopPreheader() && "No preheader!!");
1476
1477   // We can only vectorize innermost loops.
1478   if (TheLoop->getSubLoopsVector().size())
1479     return false;
1480
1481   // We must have a single backedge.
1482   if (TheLoop->getNumBackEdges() != 1)
1483     return false;
1484
1485   // We must have a single exiting block.
1486   if (!TheLoop->getExitingBlock())
1487     return false;
1488
1489   unsigned NumBlocks = TheLoop->getNumBlocks();
1490
1491   // Check if we can if-convert non single-bb loops.
1492   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1493     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1494     return false;
1495   }
1496
1497   // We need to have a loop header.
1498   BasicBlock *Header = TheLoop->getHeader();
1499   BasicBlock *Latch = TheLoop->getLoopLatch();
1500   DEBUG(dbgs() << "LV: Found a loop: " << Header->getName() << "\n");
1501
1502   // ScalarEvolution needs to be able to find the exit count.
1503   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1504   if (ExitCount == SE->getCouldNotCompute()) {
1505     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1506     return false;
1507   }
1508
1509   // Do not loop-vectorize loops with a tiny trip count.
1510   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1511   if (TC > 0u && TC < TinyTripCountThreshold) {
1512     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1513           "This loop is not worth vectorizing.\n");
1514     return false;
1515   }
1516
1517   // Check if we can vectorize the instructions and CFG in this loop.
1518   if (!canVectorizeInstrs()) {
1519     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1520     return false;
1521   }
1522
1523   // Go over each instruction and look at memory deps.
1524   if (!canVectorizeMemory()) {
1525     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1526     return false;
1527   }
1528
1529   // Collect all of the variables that remain uniform after vectorization.
1530   collectLoopUniforms();
1531
1532   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1533         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1534         <<"!\n");
1535
1536   // Okay! We can vectorize. At this point we don't have any other mem analysis
1537   // which may limit our maximum vectorization factor, so just return true with
1538   // no restrictions.
1539   return true;
1540 }
1541
1542 bool LoopVectorizationLegality::canVectorizeInstrs() {
1543   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1544   BasicBlock *Header = TheLoop->getHeader();
1545
1546   // For each block in the loop.
1547   for (Loop::block_iterator bb = TheLoop->block_begin(),
1548        be = TheLoop->block_end(); bb != be; ++bb) {
1549
1550     // Scan the instructions in the block and look for hazards.
1551     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1552          ++it) {
1553
1554       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1555         // This should not happen because the loop should be normalized.
1556         if (Phi->getNumIncomingValues() != 2) {
1557           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1558           return false;
1559         }
1560
1561         // If this PHINode is not in the header block, then we know that we
1562         // can convert it to select during if-conversion.
1563         if (*bb != Header)
1564           continue;
1565
1566         // This is the value coming from the preheader.
1567         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1568
1569         // We only look at integer and pointer phi nodes.
1570         if (Phi->getType()->isPointerTy() && isInductionVariable(Phi)) {
1571           DEBUG(dbgs() << "LV: Found a pointer induction variable.\n");
1572           Inductions[Phi] = StartValue;
1573           continue;
1574         } else if (!Phi->getType()->isIntegerTy()) {
1575           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1576           return false;
1577         }
1578
1579         // Handle integer PHIs:
1580         if (isInductionVariable(Phi)) {
1581           if (Induction) {
1582             DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1583             return false;
1584           }
1585           DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1586           Induction = Phi;
1587           Inductions[Phi] = StartValue;
1588           continue;
1589         }
1590         if (AddReductionVar(Phi, IntegerAdd)) {
1591           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1592           continue;
1593         }
1594         if (AddReductionVar(Phi, IntegerMult)) {
1595           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1596           continue;
1597         }
1598         if (AddReductionVar(Phi, IntegerOr)) {
1599           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1600           continue;
1601         }
1602         if (AddReductionVar(Phi, IntegerAnd)) {
1603           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1604           continue;
1605         }
1606         if (AddReductionVar(Phi, IntegerXor)) {
1607           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1608           continue;
1609         }
1610
1611         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1612         return false;
1613       }// end of PHI handling
1614
1615       // We still don't handle functions.
1616       CallInst *CI = dyn_cast<CallInst>(it);
1617       if (CI) {
1618         DEBUG(dbgs() << "LV: Found a call site.\n");
1619         return false;
1620       }
1621
1622       // We do not re-vectorize vectors.
1623       if (!VectorType::isValidElementType(it->getType()) &&
1624           !it->getType()->isVoidTy()) {
1625         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1626         return false;
1627       }
1628
1629       // Reduction instructions are allowed to have exit users.
1630       // All other instructions must not have external users.
1631       if (!AllowedExit.count(it))
1632         //Check that all of the users of the loop are inside the BB.
1633         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1634              I != E; ++I) {
1635           Instruction *U = cast<Instruction>(*I);
1636           // This user may be a reduction exit value.
1637           if (!TheLoop->contains(U)) {
1638             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1639             return false;
1640           }
1641         }
1642     } // next instr.
1643
1644   }
1645
1646   if (!Induction) {
1647     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1648     assert(getInductionVars()->size() && "No induction variables");
1649   }
1650
1651   return true;
1652 }
1653
1654 void LoopVectorizationLegality::collectLoopUniforms() {
1655   // We now know that the loop is vectorizable!
1656   // Collect variables that will remain uniform after vectorization.
1657   std::vector<Value*> Worklist;
1658   BasicBlock *Latch = TheLoop->getLoopLatch();
1659
1660   // Start with the conditional branch and walk up the block.
1661   Worklist.push_back(Latch->getTerminator()->getOperand(0));
1662
1663   while (Worklist.size()) {
1664     Instruction *I = dyn_cast<Instruction>(Worklist.back());
1665     Worklist.pop_back();
1666
1667     // Look at instructions inside this loop.
1668     // Stop when reaching PHI nodes.
1669     // TODO: we need to follow values all over the loop, not only in this block.
1670     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1671       continue;
1672
1673     // This is a known uniform.
1674     Uniforms.insert(I);
1675
1676     // Insert all operands.
1677     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1678       Worklist.push_back(I->getOperand(i));
1679     }
1680   }
1681 }
1682
1683 bool LoopVectorizationLegality::canVectorizeMemory() {
1684   typedef SmallVector<Value*, 16> ValueVector;
1685   typedef SmallPtrSet<Value*, 16> ValueSet;
1686   // Holds the Load and Store *instructions*.
1687   ValueVector Loads;
1688   ValueVector Stores;
1689   PtrRtCheck.Pointers.clear();
1690   PtrRtCheck.Need = false;
1691
1692   // For each block.
1693   for (Loop::block_iterator bb = TheLoop->block_begin(),
1694        be = TheLoop->block_end(); bb != be; ++bb) {
1695
1696     // Scan the BB and collect legal loads and stores.
1697     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1698          ++it) {
1699
1700       // If this is a load, save it. If this instruction can read from memory
1701       // but is not a load, then we quit. Notice that we don't handle function
1702       // calls that read or write.
1703       if (it->mayReadFromMemory()) {
1704         LoadInst *Ld = dyn_cast<LoadInst>(it);
1705         if (!Ld) return false;
1706         if (!Ld->isSimple()) {
1707           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1708           return false;
1709         }
1710         Loads.push_back(Ld);
1711         continue;
1712       }
1713
1714       // Save 'store' instructions. Abort if other instructions write to memory.
1715       if (it->mayWriteToMemory()) {
1716         StoreInst *St = dyn_cast<StoreInst>(it);
1717         if (!St) return false;
1718         if (!St->isSimple()) {
1719           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1720           return false;
1721         }
1722         Stores.push_back(St);
1723       }
1724     } // next instr.
1725   } // next block.
1726
1727   // Now we have two lists that hold the loads and the stores.
1728   // Next, we find the pointers that they use.
1729
1730   // Check if we see any stores. If there are no stores, then we don't
1731   // care if the pointers are *restrict*.
1732   if (!Stores.size()) {
1733         DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1734         return true;
1735   }
1736
1737   // Holds the read and read-write *pointers* that we find.
1738   ValueVector Reads;
1739   ValueVector ReadWrites;
1740
1741   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1742   // multiple times on the same object. If the ptr is accessed twice, once
1743   // for read and once for write, it will only appear once (on the write
1744   // list). This is okay, since we are going to check for conflicts between
1745   // writes and between reads and writes, but not between reads and reads.
1746   ValueSet Seen;
1747
1748   ValueVector::iterator I, IE;
1749   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1750     StoreInst *ST = dyn_cast<StoreInst>(*I);
1751     assert(ST && "Bad StoreInst");
1752     Value* Ptr = ST->getPointerOperand();
1753
1754     if (isUniform(Ptr)) {
1755       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1756       return false;
1757     }
1758
1759     // If we did *not* see this pointer before, insert it to
1760     // the read-write list. At this phase it is only a 'write' list.
1761     if (Seen.insert(Ptr))
1762       ReadWrites.push_back(Ptr);
1763   }
1764
1765   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1766     LoadInst *LD = dyn_cast<LoadInst>(*I);
1767     assert(LD && "Bad LoadInst");
1768     Value* Ptr = LD->getPointerOperand();
1769     // If we did *not* see this pointer before, insert it to the
1770     // read list. If we *did* see it before, then it is already in
1771     // the read-write list. This allows us to vectorize expressions
1772     // such as A[i] += x;  Because the address of A[i] is a read-write
1773     // pointer. This only works if the index of A[i] is consecutive.
1774     // If the address of i is unknown (for example A[B[i]]) then we may
1775     // read a few words, modify, and write a few words, and some of the
1776     // words may be written to the same address.
1777     if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1778       Reads.push_back(Ptr);
1779   }
1780
1781   // If we write (or read-write) to a single destination and there are no
1782   // other reads in this loop then is it safe to vectorize.
1783   if (ReadWrites.size() == 1 && Reads.size() == 0) {
1784     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1785     return true;
1786   }
1787
1788   // Find pointers with computable bounds. We are going to use this information
1789   // to place a runtime bound check.
1790   bool RT = true;
1791   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1792     if (hasComputableBounds(*I)) {
1793       PtrRtCheck.insert(SE, TheLoop, *I);
1794       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1795     } else {
1796       RT = false;
1797       break;
1798     }
1799   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1800     if (hasComputableBounds(*I)) {
1801       PtrRtCheck.insert(SE, TheLoop, *I);
1802       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1803     } else {
1804       RT = false;
1805       break;
1806     }
1807
1808   // Check that we did not collect too many pointers or found a
1809   // unsizeable pointer.
1810   if (!RT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1811     PtrRtCheck.reset();
1812     RT = false;
1813   }
1814
1815   PtrRtCheck.Need = RT;
1816
1817   if (RT) {
1818     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1819   }
1820
1821   // Now that the pointers are in two lists (Reads and ReadWrites), we
1822   // can check that there are no conflicts between each of the writes and
1823   // between the writes to the reads.
1824   ValueSet WriteObjects;
1825   ValueVector TempObjects;
1826
1827   // Check that the read-writes do not conflict with other read-write
1828   // pointers.
1829   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1830     GetUnderlyingObjects(*I, TempObjects, DL);
1831     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1832          it != e; ++it) {
1833       if (!isIdentifiedObject(*it)) {
1834         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1835         return RT;
1836       }
1837       if (!WriteObjects.insert(*it)) {
1838         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1839               << **it <<"\n");
1840         return RT;
1841       }
1842     }
1843     TempObjects.clear();
1844   }
1845
1846   /// Check that the reads don't conflict with the read-writes.
1847   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1848     GetUnderlyingObjects(*I, TempObjects, DL);
1849     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1850          it != e; ++it) {
1851       if (!isIdentifiedObject(*it)) {
1852         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1853         return RT;
1854       }
1855       if (WriteObjects.count(*it)) {
1856         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1857               << **it <<"\n");
1858         return RT;
1859       }
1860     }
1861     TempObjects.clear();
1862   }
1863
1864   // It is safe to vectorize and we don't need any runtime checks.
1865   DEBUG(dbgs() << "LV: We don't need a runtime memory check.\n");
1866   PtrRtCheck.reset();
1867   return true;
1868 }
1869
1870 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1871                                                 ReductionKind Kind) {
1872   if (Phi->getNumIncomingValues() != 2)
1873     return false;
1874
1875   // Find the possible incoming reduction variable.
1876   BasicBlock *BB = Phi->getParent();
1877   int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1878   int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1879   Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1880
1881   // ExitInstruction is the single value which is used outside the loop.
1882   // We only allow for a single reduction value to be used outside the loop.
1883   // This includes users of the reduction, variables (which form a cycle
1884   // which ends in the phi node).
1885   Instruction *ExitInstruction = 0;
1886
1887   // Iter is our iterator. We start with the PHI node and scan for all of the
1888   // users of this instruction. All users must be instructions which can be
1889   // used as reduction variables (such as ADD). We may have a single
1890   // out-of-block user. They cycle must end with the original PHI.
1891   // Also, we can't have multiple block-local users.
1892   Instruction *Iter = Phi;
1893   while (true) {
1894     // Any reduction instr must be of one of the allowed kinds.
1895     if (!isReductionInstr(Iter, Kind))
1896       return false;
1897
1898     // Did we found a user inside this block ?
1899     bool FoundInBlockUser = false;
1900     // Did we reach the initial PHI node ?
1901     bool FoundStartPHI = false;
1902
1903     // If the instruction has no users then this is a broken
1904     // chain and can't be a reduction variable.
1905     if (Iter->use_empty())
1906       return false;
1907
1908     // For each of the *users* of iter.
1909     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1910          it != e; ++it) {
1911       Instruction *U = cast<Instruction>(*it);
1912       // We already know that the PHI is a user.
1913       if (U == Phi) {
1914         FoundStartPHI = true;
1915         continue;
1916       }
1917       // Check if we found the exit user.
1918       BasicBlock *Parent = U->getParent();
1919       if (Parent != BB) {
1920         // We must have a single exit instruction.
1921         if (ExitInstruction != 0)
1922           return false;
1923         ExitInstruction = Iter;
1924       }
1925       // We can't have multiple inside users.
1926       if (FoundInBlockUser)
1927         return false;
1928       FoundInBlockUser = true;
1929       Iter = U;
1930     }
1931
1932     // We found a reduction var if we have reached the original
1933     // phi node and we only have a single instruction with out-of-loop
1934     // users.
1935    if (FoundStartPHI && ExitInstruction) {
1936      // This instruction is allowed to have out-of-loop users.
1937      AllowedExit.insert(ExitInstruction);
1938
1939      // Save the description of this reduction variable.
1940      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1941      Reductions[Phi] = RD;
1942      return true;
1943    }
1944   }
1945 }
1946
1947 bool
1948 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1949                                             ReductionKind Kind) {
1950     switch (I->getOpcode()) {
1951     default:
1952       return false;
1953     case Instruction::PHI:
1954       // possibly.
1955       return true;
1956     case Instruction::Add:
1957     case Instruction::Sub:
1958       return Kind == IntegerAdd;
1959     case Instruction::Mul:
1960       return Kind == IntegerMult;
1961     case Instruction::And:
1962       return Kind == IntegerAnd;
1963     case Instruction::Or:
1964       return Kind == IntegerOr;
1965     case Instruction::Xor:
1966       return Kind == IntegerXor;
1967     }
1968 }
1969
1970 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1971   Type *PhiTy = Phi->getType();
1972   // We only handle integer and pointer inductions variables.
1973   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1974     return false;
1975
1976   // Check that the PHI is consecutive and starts at zero.
1977   const SCEV *PhiScev = SE->getSCEV(Phi);
1978   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1979   if (!AR) {
1980     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1981     return false;
1982   }
1983   const SCEV *Step = AR->getStepRecurrence(*SE);
1984
1985   // Integer inductions need to have a stride of one.
1986   if (PhiTy->isIntegerTy())
1987     return Step->isOne();
1988
1989   // Calculate the pointer stride and check if it is consecutive.
1990   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1991   if (!C) return false;
1992
1993   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1994   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1995   return (C->getValue()->equalsInt(Size));
1996 }
1997
1998 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
1999   assert(TheLoop->contains(BB) && "Unknown block used");
2000
2001   // Blocks that do not dominate the latch need predication.
2002   BasicBlock* Latch = TheLoop->getLoopLatch();
2003   return !DT->dominates(BB, Latch);
2004 }
2005
2006 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2007   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2008     // We don't predicate loads/stores at the moment.
2009     if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2010       return false;
2011
2012     // The isntructions below can trap.
2013     switch (it->getOpcode()) {
2014       default: continue;
2015       case Instruction::UDiv:
2016       case Instruction::SDiv:
2017       case Instruction::URem:
2018       case Instruction::SRem:
2019         return false;
2020     }
2021   }
2022
2023   return true;
2024 }
2025
2026 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2027   const SCEV *PhiScev = SE->getSCEV(Ptr);
2028   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2029   if (!AR)
2030     return false;
2031
2032   return AR->isAffine();
2033 }
2034
2035 unsigned
2036 LoopVectorizationCostModel::findBestVectorizationFactor(unsigned VF) {
2037   if (!VTTI) {
2038     DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2039     return 1;
2040   }
2041
2042   float Cost = expectedCost(1);
2043   unsigned Width = 1;
2044   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2045   for (unsigned i=2; i <= VF; i*=2) {
2046     // Notice that the vector loop needs to be executed less times, so
2047     // we need to divide the cost of the vector loops by the width of
2048     // the vector elements.
2049     float VectorCost = expectedCost(i) / (float)i;
2050     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2051           (int)VectorCost << ".\n");
2052     if (VectorCost < Cost) {
2053       Cost = VectorCost;
2054       Width = i;
2055     }
2056   }
2057
2058   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2059   return Width;
2060 }
2061
2062 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2063   unsigned Cost = 0;
2064
2065   // For each block.
2066   for (Loop::block_iterator bb = TheLoop->block_begin(),
2067        be = TheLoop->block_end(); bb != be; ++bb) {
2068     unsigned BlockCost = 0;
2069     BasicBlock *BB = *bb;
2070     
2071     // For each instruction in the old loop.
2072     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2073
2074       unsigned C = getInstructionCost(it, VF);
2075       Cost += C;
2076       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2077             VF << " For instruction: "<< *it << "\n");
2078     }
2079
2080     // TODO: if-converted blocks can have a high-nest level. We need to
2081     // calculate the loop nest level and multiply the cost accordingly.
2082     if (Legal->blockNeedsPredication(*bb))
2083       BlockCost *= 2;
2084     
2085     Cost += BlockCost;
2086   }
2087
2088   return Cost;
2089 }
2090
2091 unsigned
2092 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2093   assert(VTTI && "Invalid vector target transformation info");
2094
2095   // If we know that this instruction will remain uniform, check the cost of
2096   // the scalar version.
2097   if (Legal->isUniformAfterVectorization(I))
2098     VF = 1;
2099
2100   Type *RetTy = I->getType();
2101   Type *VectorTy = ToVectorTy(RetTy, VF);
2102
2103
2104   // TODO: We need to estimate the cost of intrinsic calls.
2105   switch (I->getOpcode()) {
2106     case Instruction::GetElementPtr:
2107       // We mark this instruction as zero-cost because scalar GEPs are usually
2108       // lowered to the intruction addressing mode. At the moment we don't
2109       // generate vector geps.
2110       return 0;
2111     case Instruction::Br: {
2112       return VTTI->getCFInstrCost(I->getOpcode());
2113     }
2114     case Instruction::PHI:
2115       //TODO: IF-converted IFs become selects.
2116       return 0;
2117     case Instruction::Add:
2118     case Instruction::FAdd:
2119     case Instruction::Sub:
2120     case Instruction::FSub:
2121     case Instruction::Mul:
2122     case Instruction::FMul:
2123     case Instruction::UDiv:
2124     case Instruction::SDiv:
2125     case Instruction::FDiv:
2126     case Instruction::URem:
2127     case Instruction::SRem:
2128     case Instruction::FRem:
2129     case Instruction::Shl:
2130     case Instruction::LShr:
2131     case Instruction::AShr:
2132     case Instruction::And:
2133     case Instruction::Or:
2134     case Instruction::Xor:
2135       return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2136     case Instruction::Select: {
2137       SelectInst *SI = cast<SelectInst>(I);
2138       const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2139       bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2140       Type *CondTy = SI->getCondition()->getType();
2141       if (ScalarCond)
2142         CondTy = VectorType::get(CondTy, VF);
2143
2144       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2145     }
2146     case Instruction::ICmp:
2147     case Instruction::FCmp: {
2148       Type *ValTy = I->getOperand(0)->getType();
2149       VectorTy = ToVectorTy(ValTy, VF);
2150       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2151     }
2152     case Instruction::Store: {
2153       StoreInst *SI = cast<StoreInst>(I);
2154       Type *ValTy = SI->getValueOperand()->getType();
2155       VectorTy = ToVectorTy(ValTy, VF);
2156
2157       if (VF == 1)
2158         return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
2159                               SI->getAlignment(), SI->getPointerAddressSpace());
2160
2161       // Scalarized stores.
2162       if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2163         unsigned Cost = 0;
2164         unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2165                                               ValTy);
2166         // The cost of extracting from the value vector.
2167         Cost += VF * (ExtCost);
2168         // The cost of the scalar stores.
2169         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2170                                            ValTy->getScalarType(),
2171                                            SI->getAlignment(),
2172                                            SI->getPointerAddressSpace());
2173         return Cost;
2174       }
2175
2176       // Wide stores.
2177       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2178                                    SI->getPointerAddressSpace());
2179     }
2180     case Instruction::Load: {
2181       LoadInst *LI = cast<LoadInst>(I);
2182
2183       if (VF == 1)
2184         return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
2185                                      LI->getAlignment(),
2186                                      LI->getPointerAddressSpace());
2187
2188       // Scalarized loads.
2189       if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2190         unsigned Cost = 0;
2191         unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
2192         // The cost of inserting the loaded value into the result vector.
2193         Cost += VF * (InCost);
2194         // The cost of the scalar stores.
2195         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2196                                            RetTy->getScalarType(),
2197                                            LI->getAlignment(),
2198                                            LI->getPointerAddressSpace());
2199         return Cost;
2200       }
2201
2202       // Wide loads.
2203       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2204                                    LI->getPointerAddressSpace());
2205     }
2206     case Instruction::ZExt:
2207     case Instruction::SExt:
2208     case Instruction::FPToUI:
2209     case Instruction::FPToSI:
2210     case Instruction::FPExt:
2211     case Instruction::PtrToInt:
2212     case Instruction::IntToPtr:
2213     case Instruction::SIToFP:
2214     case Instruction::UIToFP:
2215     case Instruction::Trunc:
2216     case Instruction::FPTrunc:
2217     case Instruction::BitCast: {
2218       Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2219       return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2220     }
2221     default: {
2222       // We are scalarizing the instruction. Return the cost of the scalar
2223       // instruction, plus the cost of insert and extract into vector
2224       // elements, times the vector width.
2225       unsigned Cost = 0;
2226
2227       bool IsVoid = RetTy->isVoidTy();
2228
2229       unsigned InsCost = (IsVoid ? 0 :
2230                           VTTI->getInstrCost(Instruction::InsertElement,
2231                                              VectorTy));
2232
2233       unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2234                                             VectorTy);
2235
2236       // The cost of inserting the results plus extracting each one of the
2237       // operands.
2238       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2239
2240       // The cost of executing VF copies of the scalar instruction.
2241       Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
2242       return Cost;
2243     }
2244   }// end of switch.
2245 }
2246
2247 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2248   if (Scalar->isVoidTy() || VF == 1)
2249     return Scalar;
2250   return VectorType::get(Scalar, VF);
2251 }
2252
2253 } // namespace
2254
2255 char LoopVectorize::ID = 0;
2256 static const char lv_name[] = "Loop Vectorization";
2257 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2258 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2259 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2260 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2261 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2262
2263 namespace llvm {
2264   Pass *createLoopVectorizePass() {
2265     return new LoopVectorize();
2266   }
2267 }
2268