Add support for reduction variables that do not start at zero.
[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 helper class that checks for the legality
22 //    of the vectorization.
23 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
24 //    widening of instructions.
25 //===----------------------------------------------------------------------===//
26 //
27 // The reduction-variable vectorization is based on the paper:
28 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
29 //
30 // Variable uniformity checks are inspired by:
31 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
32 //
33 // Other ideas/concepts are from:
34 //  A. Zaks and D. Nuzman. Autovectorization in GCC—two years later.
35 //
36 //===----------------------------------------------------------------------===//
37 #define LV_NAME "loop-vectorize"
38 #define DEBUG_TYPE LV_NAME
39 #include "llvm/Constants.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/Instructions.h"
42 #include "llvm/LLVMContext.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Value.h"
46 #include "llvm/Function.h"
47 #include "llvm/Analysis/Verifier.h"
48 #include "llvm/Module.h"
49 #include "llvm/Type.h"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Analysis/AliasAnalysis.h"
53 #include "llvm/Analysis/AliasSetTracker.h"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Analysis/ScalarEvolution.h"
56 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
57 #include "llvm/Analysis/ScalarEvolutionExpander.h"
58 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
59 #include "llvm/Analysis/ValueTracking.h"
60 #include "llvm/Analysis/LoopInfo.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/DataLayout.h"
65 #include "llvm/Transforms/Utils/Local.h"
66 #include <algorithm>
67 using namespace llvm;
68
69 static cl::opt<unsigned>
70 DefaultVectorizationFactor("default-loop-vectorize-width",
71                           cl::init(4), cl::Hidden,
72                           cl::desc("Set the default loop vectorization width"));
73 namespace {
74
75 // Forward declaration.
76 class LoopVectorizationLegality;
77
78 /// Vectorize a simple loop. This class performs the widening of simple single
79 /// basic block loops into vectors. It does not perform any
80 /// vectorization-legality checks, and just does it.  It widens the vectors
81 /// to a given vectorization factor (VF).
82 class SingleBlockLoopVectorizer {
83 public:
84   /// Ctor.
85   SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
86                             LPPassManager *Lpm, unsigned VecWidth):
87   Orig(OrigLoop), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
88   Builder(Se->getContext()), Induction(0), OldInduction(0) { }
89
90   // Perform the actual loop widening (vectorization).
91   void vectorize(LoopVectorizationLegality *Legal) {
92     ///Create a new empty loop. Unlink the old loop and connect the new one.
93     createEmptyLoop(Legal);
94     /// Widen each instruction in the old loop to a new one in the new loop.
95     /// Use the Legality module to find the induction and reduction variables.
96    vectorizeLoop(Legal);
97     // register the new loop.
98     cleanup();
99  }
100
101 private:
102   /// Create an empty loop, based on the loop ranges of the old loop.
103   void createEmptyLoop(LoopVectorizationLegality *Legal);
104   /// Copy and widen the instructions from the old loop.
105   void vectorizeLoop(LoopVectorizationLegality *Legal);
106   /// Insert the new loop to the loop hierarchy and pass manager.
107   void cleanup();
108
109   /// This instruction is un-vectorizable. Implement it as a sequence
110   /// of scalars.
111   void scalarizeInstruction(Instruction *Instr);
112
113   /// Create a broadcast instruction. This method generates a broadcast
114   /// instruction (shuffle) for loop invariant values and for the induction
115   /// value. If this is the induction variable then we extend it to N, N+1, ...
116   /// this is needed because each iteration in the loop corresponds to a SIMD
117   /// element.
118   Value *getBroadcastInstrs(Value *V);
119
120   /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
121   /// for each element in the vector. Starting from zero.
122   Value *getConsecutiveVector(Value* Val);
123
124   /// When we go over instructions in the basic block we rely on previous
125   /// values within the current basic block or on loop invariant values.
126   /// When we widen (vectorize) values we place them in the map. If the values
127   /// are not within the map, they have to be loop invariant, so we simply
128   /// broadcast them into a vector.
129   Value *getVectorValue(Value *V);
130
131   /// Get a uniform vector of constant integers. We use this to get
132   /// vectors of ones and zeros for the reduction code.
133   Constant* getUniformVector(unsigned Val, Type* ScalarTy);
134
135   typedef DenseMap<Value*, Value*> ValueMap;
136
137   /// The original loop.
138   Loop *Orig;
139   // Scev analysis to use.
140   ScalarEvolution *SE;
141   // Loop Info.
142   LoopInfo *LI;
143   // Loop Pass Manager;
144   LPPassManager *LPM;
145   // The vectorization factor to use.
146   unsigned VF;
147
148   // The builder that we use
149   IRBuilder<> Builder;
150
151   // --- Vectorization state ---
152
153   /// Middle Block between the vector and the scalar.
154   BasicBlock *LoopMiddleBlock;
155   ///The ExitBlock of the scalar loop.
156   BasicBlock *LoopExitBlock;
157   ///The vector loop body.
158   BasicBlock *LoopVectorBody;
159   ///The scalar loop body.
160   BasicBlock *LoopScalarBody;
161   ///The first bypass block.
162   BasicBlock *LoopBypassBlock;
163
164   /// The new Induction variable which was added to the new block.
165   PHINode *Induction;
166   /// The induction variable of the old basic block.
167   PHINode *OldInduction;
168   // Maps scalars to widened vectors.
169   ValueMap WidenMap;
170 };
171
172 /// Perform the vectorization legality check. This class does not look at the
173 /// profitability of vectorization, only the legality. At the moment the checks
174 /// are very simple and focus on single basic block loops with a constant
175 /// iteration count and no reductions.
176 class LoopVectorizationLegality {
177 public:
178   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
179   TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
180
181   /// This represents the kinds of reductions that we support.
182   /// We use the enum values to hold the 'identity' value for
183   /// each operand. This value does not change the result if applied.
184   enum ReductionKind {
185     NoReduction = -1, /// Not a reduction.
186     IntegerAdd  = 0,  /// Sum of numbers.
187     IntegerMult = 1  /// Product of numbers.
188   };
189
190   /// This POD struct holds information about reduction variables.
191   struct ReductionDescriptor {
192     // Default C'tor
193     ReductionDescriptor():
194     StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
195
196     // C'tor.
197     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
198     StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
199
200     // The starting value of the reduction.
201     // It does not have to be zero!
202     Value *StartValue;
203     // The instruction who's value is used outside the loop.
204     Instruction *LoopExitInstr;
205     // The kind of the reduction.
206     ReductionKind Kind;
207   };
208
209   /// ReductionList contains the reduction descriptors for all
210   /// of the reductions that were found in the loop.
211   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
212
213   /// Returns the maximum vectorization factor that we *can* use to vectorize
214   /// this loop. This does not mean that it is profitable to vectorize this
215   /// loop, only that it is legal to do so. This may be a large number. We
216   /// can vectorize to any SIMD width below this number.
217   unsigned getLoopMaxVF();
218
219   /// Returns the Induction variable.
220   PHINode *getInduction() {return Induction;}
221
222   /// Returns the reduction variables found in the loop.
223   ReductionList *getReductionVars() { return &Reductions; }
224
225   /// Check that the GEP operands are all uniform except for the last index
226   /// which has to be the induction variable.
227   bool isConsecutiveGep(Value *Ptr);
228
229 private:
230   /// Check if a single basic block loop is vectorizable.
231   /// At this point we know that this is a loop with a constant trip count
232   /// and we only need to check individual instructions.
233   bool canVectorizeBlock(BasicBlock &BB);
234
235   /// When we vectorize loops we may change the order in which
236   /// we read and write from memory. This method checks if it is
237   /// legal to vectorize the code, considering only memory constrains.
238   /// Returns true if BB is vectorizable
239   bool canVectorizeMemory(BasicBlock &BB);
240
241   // Check if a pointer value is known to be disjoint.
242   // Example: Alloca, Global, NoAlias.
243   bool isIdentifiedSafeObject(Value* Val);
244
245   /// Returns True, if 'Phi' is the kind of reduction variable for type
246   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
247   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
248   /// Returns true if the instruction I can be a reduction variable of type
249   /// 'Kind'.
250   bool isReductionInstr(Instruction *I, ReductionKind Kind);
251   /// Returns True, if 'Phi' is an induction variable.
252   bool isInductionVariable(PHINode *Phi);
253
254   /// The loop that we evaluate.
255   Loop *TheLoop;
256   /// Scev analysis.
257   ScalarEvolution *SE;
258   /// DataLayout analysis.
259   DataLayout *DL;
260
261   //  ---  vectorization state --- //
262
263   /// Holds the induction variable.
264   PHINode *Induction;
265   /// Holds the reduction variables.
266   ReductionList Reductions;
267   /// Allowed outside users. This holds the reduction
268   /// vars which can be accessed from outside the loop.
269   SmallPtrSet<Value*, 4> AllowedExit;
270 };
271
272 struct LoopVectorize : public LoopPass {
273   static char ID; // Pass identification, replacement for typeid
274
275   LoopVectorize() : LoopPass(ID) {
276     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
277   }
278
279   ScalarEvolution *SE;
280   DataLayout *DL;
281   LoopInfo *LI;
282
283   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
284
285     // Only vectorize innermost loops.
286     if (!L->empty())
287       return false;
288
289     SE = &getAnalysis<ScalarEvolution>();
290     DL = getAnalysisIfAvailable<DataLayout>();
291     LI = &getAnalysis<LoopInfo>();
292
293     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
294           L->getHeader()->getParent()->getName() << "\"\n");
295
296     // Check if it is legal to vectorize the loop.
297     LoopVectorizationLegality LVL(L, SE, DL);
298     unsigned MaxVF = LVL.getLoopMaxVF();
299
300     // Check that we can vectorize using the chosen vectorization width.
301     if (MaxVF < DefaultVectorizationFactor) {
302       DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
303       return false;
304     }
305
306     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
307
308     // If we decided that is is *legal* to vectorizer the loop. Do it.
309     SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, DefaultVectorizationFactor);
310     LB.vectorize(&LVL);
311
312     DEBUG(verifyFunction(*L->getHeader()->getParent()));
313     return true;
314   }
315
316   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
317     LoopPass::getAnalysisUsage(AU);
318     AU.addRequiredID(LoopSimplifyID);
319     AU.addRequiredID(LCSSAID);
320     AU.addRequired<LoopInfo>();
321     AU.addRequired<ScalarEvolution>();
322   }
323
324 };
325
326 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
327   // Instructions that access the old induction variable
328   // actually want to get the new one.
329   if (V == OldInduction)
330     V = Induction;
331   // Create the types.
332   LLVMContext &C = V->getContext();
333   Type *VTy = VectorType::get(V->getType(), VF);
334   Type *I32 = IntegerType::getInt32Ty(C);
335   Constant *Zero = ConstantInt::get(I32, 0);
336   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
337   Value *UndefVal = UndefValue::get(VTy);
338   // Insert the value into a new vector.
339   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
340   // Broadcast the scalar into all locations in the vector.
341   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
342                                              "broadcast");
343   // We are accessing the induction variable. Make sure to promote the
344   // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
345   if (V == Induction)
346     return getConsecutiveVector(Shuf);
347   return Shuf;
348 }
349
350 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
351   assert(Val->getType()->isVectorTy() && "Must be a vector");
352   assert(Val->getType()->getScalarType()->isIntegerTy() &&
353          "Elem must be an integer");
354   // Create the types.
355   Type *ITy = Val->getType()->getScalarType();
356   VectorType *Ty = cast<VectorType>(Val->getType());
357   unsigned VLen = Ty->getNumElements();
358   SmallVector<Constant*, 8> Indices;
359
360   // Create a vector of consecutive numbers from zero to VF.
361   for (unsigned i = 0; i < VLen; ++i)
362     Indices.push_back(ConstantInt::get(ITy, i));
363
364   // Add the consecutive indices to the vector value.
365   Constant *Cv = ConstantVector::get(Indices);
366   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
367   return Builder.CreateAdd(Val, Cv, "induction");
368 }
369
370 bool LoopVectorizationLegality::isConsecutiveGep(Value *Ptr) {
371   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
372   if (!Gep)
373     return false;
374
375   unsigned NumOperands = Gep->getNumOperands();
376   Value *LastIndex = Gep->getOperand(NumOperands - 1);
377
378   // Check that all of the gep indices are uniform except for the last.
379   for (unsigned i = 0; i < NumOperands - 1; ++i)
380     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
381       return false;
382
383   // We can emit wide load/stores only of the last index is the induction
384   // variable.
385   const SCEV *Last = SE->getSCEV(LastIndex);
386   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
387     const SCEV *Step = AR->getStepRecurrence(*SE);
388
389     // The memory is consecutive because the last index is consecutive
390     // and all other indices are loop invariant.
391     if (Step->isOne())
392       return true;
393   }
394
395   return false;
396 }
397
398 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
399   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
400   // If we saved a vectorized copy of V, use it.
401   ValueMap::iterator it = WidenMap.find(V);
402   if (it != WidenMap.end())
403      return it->second;
404
405   // Broadcast V and save the value for future uses.
406   Value *B = getBroadcastInstrs(V);
407   WidenMap[V] = B;
408   return B;
409 }
410
411 Constant*
412 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
413   SmallVector<Constant*, 8> Indices;
414   // Create a vector of consecutive numbers from zero to VF.
415   for (unsigned i = 0; i < VF; ++i)
416     Indices.push_back(ConstantInt::get(ScalarTy, Val));
417
418   // Add the consecutive indices to the vector value.
419   return ConstantVector::get(Indices);
420 }
421
422 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
423   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
424   // Holds vector parameters or scalars, in case of uniform vals.
425   SmallVector<Value*, 8> Params;
426
427   // Find all of the vectorized parameters.
428   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
429     Value *SrcOp = Instr->getOperand(op);
430
431     // If we are accessing the old induction variable, use the new one.
432     if (SrcOp == OldInduction) {
433       Params.push_back(getBroadcastInstrs(Induction));
434       continue;
435     }
436
437     // Try using previously calculated values.
438     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
439
440     // If the src is an instruction that appeared earlier in the basic block
441     // then it should already be vectorized.
442     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
443       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
444       // The parameter is a vector value from earlier.
445       Params.push_back(WidenMap[SrcInst]);
446     } else {
447       // The parameter is a scalar from outside the loop. Maybe even a constant.
448       Params.push_back(SrcOp);
449     }
450   }
451
452   assert(Params.size() == Instr->getNumOperands() &&
453          "Invalid number of operands");
454
455   // Does this instruction return a value ?
456   bool IsVoidRetTy = Instr->getType()->isVoidTy();
457   Value *VecResults = 0;
458
459   // If we have a return value, create an empty vector. We place the scalarized
460   // instructions in this vector.
461   if (!IsVoidRetTy)
462     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
463
464   // For each scalar that we create.
465   for (unsigned i = 0; i < VF; ++i) {
466     Instruction *Cloned = Instr->clone();
467     if (!IsVoidRetTy)
468       Cloned->setName(Instr->getName() + ".cloned");
469     // Replace the operands of the cloned instrucions with extracted scalars.
470     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
471       Value *Op = Params[op];
472       // Param is a vector. Need to extract the right lane.
473       if (Op->getType()->isVectorTy())
474         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
475       Cloned->setOperand(op, Op);
476     }
477
478     // Place the cloned scalar in the new loop.
479     Builder.Insert(Cloned);
480
481     // If the original scalar returns a value we need to place it in a vector
482     // so that future users will be able to use it.
483     if (!IsVoidRetTy)
484       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
485                                                Builder.getInt32(i));
486   }
487
488   if (!IsVoidRetTy)
489     WidenMap[Instr] = VecResults;
490 }
491
492 void SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
493   /*
494    In this function we generate a new loop. The new loop will contain
495    the vectorized instructions while the old loop will continue to run the
496    scalar remainder.
497
498    [  ] <-- vector loop bypass.
499   /  |
500  /   v
501 |   [ ]     <-- vector pre header.
502 |    |
503 |    v
504 |   [  ] \
505 |   [  ]_|   <-- vector loop.
506 |    |
507  \   v
508    >[ ]   <--- middle-block.
509   /  |
510  /   v
511 |   [ ]     <--- new preheader.
512 |    |
513 |    v
514 |   [ ] \
515 |   [ ]_|   <-- old scalar loop to handle remainder.
516  \   |
517   \  v
518    >[ ]     <-- exit block.
519    ...
520    */
521
522   // This is the original scalar-loop preheader.
523   BasicBlock *BypassBlock = Orig->getLoopPreheader();
524   BasicBlock *ExitBlock = Orig->getExitBlock();
525   assert(ExitBlock && "Must have an exit block");
526
527   assert(Orig->getNumBlocks() == 1 && "Invalid loop");
528   assert(BypassBlock && "Invalid loop structure");
529
530   BasicBlock *VectorPH =
531       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
532   BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
533                                                  "vector.body");
534
535   BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
536                                                   "middle.block");
537   BasicBlock *ScalarPH =
538     MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
539                                  "scalar.preheader");
540   // Find the induction variable.
541   BasicBlock *OldBasicBlock = Orig->getHeader();
542   OldInduction = Legal->getInduction();
543   assert(OldInduction && "We must have a single phi node.");
544   Type *IdxTy = OldInduction->getType();
545
546   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
547   // inside the loop.
548   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
549
550   // Generate the induction variable.
551   Induction = Builder.CreatePHI(IdxTy, 2, "index");
552   Constant *Zero = ConstantInt::get(IdxTy, 0);
553   Constant *Step = ConstantInt::get(IdxTy, VF);
554
555   // Find the loop boundaries.
556   const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
557   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
558
559   // Get the total trip count from the count by adding 1.
560   ExitCount = SE->getAddExpr(ExitCount,
561                              SE->getConstant(ExitCount->getType(), 1));
562
563   // Expand the trip count and place the new instructions in the preheader.
564   // Notice that the pre-header does not change, only the loop body.
565   SCEVExpander Exp(*SE, "induction");
566   Instruction *Loc = BypassBlock->getTerminator();
567
568   // We may need to extend the index in case there is a type mismatch.
569   // We know that the count starts at zero and does not overflow.
570   // We are using Zext because it should be less expensive.
571   if (ExitCount->getType() != Induction->getType())
572     ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
573
574   // Count holds the overall loop count (N).
575   Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
576   // Now we need to generate the expression for N - (N % VF), which is
577   // the part that the vectorized body will execute.
578   Constant *CIVF = ConstantInt::get(IdxTy, VF);
579   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
580   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
581
582   // Now, compare the new count to zero. If it is zero, jump to the scalar part.
583   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
584                                CountRoundDown, ConstantInt::getNullValue(IdxTy),
585                                "cmp.zero", Loc);
586   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
587   // Remove the old terminator.
588   Loc->eraseFromParent();
589
590   // Add a check in the middle block to see if we have completed
591   // all of the iterations in the first vector loop.
592   // If (N - N%VF) == N, then we *don't* need to run the remainder.
593   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
594                                 CountRoundDown, "cmp.n",
595                                 MiddleBlock->getTerminator());
596
597   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
598   // Remove the old terminator.
599   MiddleBlock->getTerminator()->eraseFromParent();
600
601   // Create i+1 and fill the PHINode.
602   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
603   Induction->addIncoming(Zero, VectorPH);
604   Induction->addIncoming(NextIdx, VecBody);
605   // Create the compare.
606   Value *ICmp = Builder.CreateICmpEQ(NextIdx, CountRoundDown);
607   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
608
609   // Now we have two terminators. Remove the old one from the block.
610   VecBody->getTerminator()->eraseFromParent();
611
612   // Fix the scalar body iteration count.
613   unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
614   OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
615
616   // Get ready to start creating new instructions into the vectorized body.
617   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
618
619   // Register the new loop.
620   Loop* Lp = new Loop();
621   LPM->insertLoop(Lp, Orig->getParentLoop());
622
623   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
624
625   Loop *ParentLoop = Orig->getParentLoop();
626   if (ParentLoop) {
627     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
628     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
629     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
630   }
631
632   // Save the state.
633   LoopMiddleBlock = MiddleBlock;
634   LoopExitBlock = ExitBlock;
635   LoopVectorBody = VecBody;
636   LoopScalarBody = OldBasicBlock;
637   LoopBypassBlock = BypassBlock;
638 }
639
640 void
641 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
642   typedef SmallVector<PHINode*, 4> PhiVector;
643   BasicBlock &BB = *Orig->getHeader();
644   Constant *Zero = ConstantInt::get(
645     IntegerType::getInt32Ty(BB.getContext()), 0);
646
647   // In order to support reduction variables we need to be able to vectorize
648   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
649   // steages. First, we create a new vector PHI node with no incoming edges.
650   // We use this value when we vectorize all of the instructions that use the
651   // PHI. Next, after all of the instructions in the block are complete we
652   // add the new incoming edges to the PHI. At this point all of the
653   // instructions in the basic block are vectorized, so we can use them to
654   // construct the PHI.
655   PhiVector PHIsToFix;
656
657   // For each instruction in the old loop.
658   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
659     Instruction *Inst = it;
660
661     switch (Inst->getOpcode()) {
662       case Instruction::Br:
663         // Nothing to do for PHIs and BR, since we already took care of the
664         // loop control flow instructions.
665         continue;
666       case Instruction::PHI:{
667         PHINode* P = cast<PHINode>(Inst);
668         // Special handling for the induction var.
669         if (OldInduction == Inst)
670           continue;
671         // This is phase one of vectorizing PHIs.
672         // This has to be a reduction variable.
673         assert(Legal->getReductionVars()->count(P) && "Not a Reduction");
674         Type *VecTy = VectorType::get(Inst->getType(), VF);
675         WidenMap[Inst] = Builder.CreatePHI(VecTy, 2, "vec.phi");
676         PHIsToFix.push_back(P);
677         continue;
678       }
679       case Instruction::Add:
680       case Instruction::FAdd:
681       case Instruction::Sub:
682       case Instruction::FSub:
683       case Instruction::Mul:
684       case Instruction::FMul:
685       case Instruction::UDiv:
686       case Instruction::SDiv:
687       case Instruction::FDiv:
688       case Instruction::URem:
689       case Instruction::SRem:
690       case Instruction::FRem:
691       case Instruction::Shl:
692       case Instruction::LShr:
693       case Instruction::AShr:
694       case Instruction::And:
695       case Instruction::Or:
696       case Instruction::Xor: {
697         // Just widen binops.
698         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
699         Value *A = getVectorValue(Inst->getOperand(0));
700         Value *B = getVectorValue(Inst->getOperand(1));
701         // Use this vector value for all users of the original instruction.
702         WidenMap[Inst] = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
703         break;
704       }
705       case Instruction::Select: {
706         // Widen selects.
707         // TODO: If the selector is loop invariant we can issue a select
708         // instruction with a scalar condition.
709         Value *A = getVectorValue(Inst->getOperand(0));
710         Value *B = getVectorValue(Inst->getOperand(1));
711         Value *C = getVectorValue(Inst->getOperand(2));
712         WidenMap[Inst] = Builder.CreateSelect(A, B, C);
713         break;
714       }
715
716       case Instruction::ICmp:
717       case Instruction::FCmp: {
718         // Widen compares. Generate vector compares.
719         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
720         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
721         Value *A = getVectorValue(Inst->getOperand(0));
722         Value *B = getVectorValue(Inst->getOperand(1));
723         if (FCmp)
724           WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
725         else
726           WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
727         break;
728       }
729
730       case Instruction::Store: {
731         // Attempt to issue a wide store.
732         StoreInst *SI = dyn_cast<StoreInst>(Inst);
733         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
734         Value *Ptr = SI->getPointerOperand();
735         unsigned Alignment = SI->getAlignment();
736         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
737         // This store does not use GEPs.
738         if (!Legal->isConsecutiveGep(Gep)) {
739           scalarizeInstruction(Inst);
740           break;
741         }
742
743         // Create the new GEP with the new induction variable.
744         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
745         unsigned NumOperands = Gep->getNumOperands();
746         Gep2->setOperand(NumOperands - 1, Induction);
747         Ptr = Builder.Insert(Gep2);
748         Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
749         Value *Val = getVectorValue(SI->getValueOperand());
750         Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
751         break;
752       }
753       case Instruction::Load: {
754         // Attempt to issue a wide load.
755         LoadInst *LI = dyn_cast<LoadInst>(Inst);
756         Type *RetTy = VectorType::get(LI->getType(), VF);
757         Value *Ptr = LI->getPointerOperand();
758         unsigned Alignment = LI->getAlignment();
759         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
760
761         // We don't have a gep. Scalarize the load.
762         if (!Legal->isConsecutiveGep(Gep)) {
763           scalarizeInstruction(Inst);
764           break;
765         }
766
767         // Create the new GEP with the new induction variable.
768         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
769         unsigned NumOperands = Gep->getNumOperands();
770         Gep2->setOperand(NumOperands - 1, Induction);
771         Ptr = Builder.Insert(Gep2);
772         Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
773         LI = Builder.CreateLoad(Ptr);
774         LI->setAlignment(Alignment);
775         // Use this vector value for all users of the load.
776         WidenMap[Inst] = LI;
777         break;
778       }
779       case Instruction::ZExt:
780       case Instruction::SExt:
781       case Instruction::FPToUI:
782       case Instruction::FPToSI:
783       case Instruction::FPExt:
784       case Instruction::PtrToInt:
785       case Instruction::IntToPtr:
786       case Instruction::SIToFP:
787       case Instruction::UIToFP:
788       case Instruction::Trunc:
789       case Instruction::FPTrunc:
790       case Instruction::BitCast: {
791         /// Vectorize bitcasts.
792         CastInst *CI = dyn_cast<CastInst>(Inst);
793         Value *A = getVectorValue(Inst->getOperand(0));
794         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
795         WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
796         break;
797       }
798
799       default:
800         /// All other instructions are unsupported. Scalarize them.
801         scalarizeInstruction(Inst);
802         break;
803     }// end of switch.
804   }// end of for_each instr.
805
806   // At this point every instruction in the original loop is widended to
807   // a vector form. We are almost done. Now, we need to fix the PHI nodes
808   // that we vectorized. The PHI nodes are currently empty because we did
809   // not want to introduce cycles. Notice that the remaining PHI nodes
810   // that we need to fix are reduction variables.
811
812   // Create the 'reduced' values for each of the induction vars.
813   // The reduced values are the vector values that we scalarize and combine
814   // after the loop is finished.
815   for (PhiVector::iterator it = PHIsToFix.begin(), e = PHIsToFix.end();
816        it != e; ++it) {
817     PHINode *RdxPhi = *it;
818     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
819     assert(RdxPhi && "Unable to recover vectorized PHI");
820
821     // Find the reduction variable descriptor.
822     assert(Legal->getReductionVars()->count(RdxPhi) &&
823            "Unable to find the reduction variable");
824     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
825       (*Legal->getReductionVars())[RdxPhi];
826
827     // We need to generate a reduction vector from the incoming scalar.
828     // To do so, we need to generate the 'identity' vector and overide
829     // one of the elements with the incoming scalar reduction. We need
830     // to do it in the vector-loop preheader.
831     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
832
833     // This is the vector-clone of the value that leaves the loop.
834     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
835     Type *VecTy = VectorExit->getType();
836
837     // Find the reduction identity variable. The value of the enum is the
838     // identity. Zero for addition. One for Multiplication.
839     unsigned IdentitySclr =  RdxDesc.Kind;
840     Constant *Identity = getUniformVector(IdentitySclr,
841                                           VecTy->getScalarType());
842
843     // This vector is the Identity vector where the first element is the
844     // incoming scalar reduction.
845     Value *VectorStart = Builder.CreateInsertElement(Identity,
846                                                     RdxDesc.StartValue, Zero);
847
848
849     // Fix the vector-loop phi.
850     // We created the induction variable so we know that the
851     // preheader is the first entry.
852     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
853
854     // Reductions do not have to start at zero. They can start with
855     // any loop invariant values.
856     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
857     unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
858     Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
859     VecRdxPhi->addIncoming(Val, LoopVectorBody);
860
861     // Before each round, move the insertion point right between
862     // the PHIs and the values we are going to write.
863     // This allows us to write both PHINodes and the extractelement
864     // instructions.
865     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
866
867     // This PHINode contains the vectorized reduction variable, or
868     // the initial value vector, if we bypass the vector loop.
869     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
870     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
871     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
872
873     // Extract the first scalar.
874     Value *Scalar0 =
875       Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
876     // Extract and sum the remaining vector elements.
877     for (unsigned i=1; i < VF; ++i) {
878       Value *Scalar1 =
879         Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
880       if (RdxDesc.Kind == LoopVectorizationLegality::IntegerAdd) {
881         Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
882       } else {
883         Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
884       }
885     }
886
887     // Now, we need to fix the users of the reduction variable
888     // inside and outside of the scalar remainder loop.
889     // We know that the loop is in LCSSA form. We need to update the
890     // PHI nodes in the exit blocks.
891     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
892          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
893       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
894       if (!LCSSAPhi) continue;
895
896       // All PHINodes need to have a single entry edge, or two if
897       // we already fixed them.
898       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
899
900       // We found our reduction value exit-PHI. Update it with the
901       // incoming bypass edge.
902       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
903         // Add an edge coming from the bypass.
904         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
905         break;
906       }
907     }// end of the LCSSA phi scan.
908
909     // Fix the scalar loop reduction variable with the incoming reduction sum
910     // from the vector body and from the backedge value.
911     int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
912     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
913     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
914     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
915   }// end of for each redux variable.
916 }
917
918 void SingleBlockLoopVectorizer::cleanup() {
919   // The original basic block.
920   SE->forgetLoop(Orig);
921 }
922
923 unsigned LoopVectorizationLegality::getLoopMaxVF() {
924   if (!TheLoop->getLoopPreheader()) {
925     assert(false && "No preheader!!");
926     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
927     return  1;
928   }
929
930   // We can only vectorize single basic block loops.
931   unsigned NumBlocks = TheLoop->getNumBlocks();
932   if (NumBlocks != 1) {
933     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
934     return 1;
935   }
936
937   // We need to have a loop header.
938   BasicBlock *BB = TheLoop->getHeader();
939   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
940
941   // Go over each instruction and look at memory deps.
942   if (!canVectorizeBlock(*BB)) {
943     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
944     return 1;
945   }
946
947   // ScalarEvolution needs to be able to find the exit count.
948   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
949   if (ExitCount == SE->getCouldNotCompute()) {
950     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
951     return 1;
952   }
953
954   DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
955
956   // Okay! We can vectorize. At this point we don't have any other mem analysis
957   // which may limit our maximum vectorization factor, so just return the
958   // maximum SIMD size.
959   return DefaultVectorizationFactor;
960 }
961
962 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
963   // Scan the instructions in the block and look for hazards.
964   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
965     Instruction *I = it;
966
967     PHINode *Phi = dyn_cast<PHINode>(I);
968     if (Phi) {
969       // This should not happen because the loop should be normalized.
970       if (Phi->getNumIncomingValues() != 2) {
971         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
972         return false;
973       }
974       // We only look at integer phi nodes.
975       if (!Phi->getType()->isIntegerTy()) {
976         DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
977         return false;
978       }
979
980       if (isInductionVariable(Phi)) {
981         if (Induction) {
982           DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
983           return false;
984         }
985         DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
986         Induction = Phi;
987         continue;
988       }
989       if (AddReductionVar(Phi, IntegerAdd)) {
990         DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
991         continue;
992       }
993       if (AddReductionVar(Phi, IntegerMult)) {
994         DEBUG(dbgs() << "LV: Found an Mult reduction PHI."<< *Phi <<"\n");
995         continue;
996       }
997
998       DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
999       return false;
1000     }// end of PHI handling
1001
1002     // We still don't handle functions.
1003     CallInst *CI = dyn_cast<CallInst>(I);
1004     if (CI) {
1005       DEBUG(dbgs() << "LV: Found a call site:"<<
1006             CI->getCalledFunction()->getName() << "\n");
1007       return false;
1008     }
1009
1010     // We do not re-vectorize vectors.
1011     if (!VectorType::isValidElementType(I->getType()) &&
1012         !I->getType()->isVoidTy()) {
1013       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1014       return false;
1015     }
1016
1017     // Reduction instructions are allowed to have exit users.
1018     // All other instructions must not have external users.
1019     if (!AllowedExit.count(I))
1020       //Check that all of the users of the loop are inside the BB.
1021       for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1022            it != e; ++it) {
1023         Instruction *U = cast<Instruction>(*it);
1024         // This user may be a reduction exit value.
1025         BasicBlock *Parent = U->getParent();
1026         if (Parent != &BB) {
1027           DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1028           return false;
1029         }
1030     }
1031   } // next instr.
1032
1033   if (!Induction) {
1034       DEBUG(dbgs() << "LV: Did not find an induction var.\n");
1035       return false;
1036   }
1037
1038   // If the memory dependencies do not prevent us from
1039   // vectorizing, then vectorize.
1040   return canVectorizeMemory(BB);
1041 }
1042
1043 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1044   typedef SmallVector<Value*, 16> ValueVector;
1045   typedef SmallPtrSet<Value*, 16> ValueSet;
1046   // Holds the Load and Store *instructions*.
1047   ValueVector Loads;
1048   ValueVector Stores;
1049
1050   // Scan the BB and collect legal loads and stores.
1051   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1052     Instruction *I = it;
1053
1054     // If this is a load, save it. If this instruction can read from memory
1055     // but is not a load, then we quit. Notice that we don't handle function
1056     // calls that read or write.
1057     if (I->mayReadFromMemory()) {
1058       LoadInst *Ld = dyn_cast<LoadInst>(I);
1059       if (!Ld) return false;
1060       if (!Ld->isSimple()) {
1061         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1062         return false;
1063       }
1064       Loads.push_back(Ld);
1065       continue;
1066     }
1067
1068     // Save store instructions. Abort if other instructions write to memory.
1069     if (I->mayWriteToMemory()) {
1070       StoreInst *St = dyn_cast<StoreInst>(I);
1071       if (!St) return false;
1072       if (!St->isSimple()) {
1073         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1074         return false;
1075       }
1076       Stores.push_back(St);
1077     }
1078   } // next instr.
1079
1080   // Now we have two lists that hold the loads and the stores.
1081   // Next, we find the pointers that they use.
1082
1083   // Check if we see any stores. If there are no stores, then we don't
1084   // care if the pointers are *restrict*.
1085   if (!Stores.size()) {
1086         DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1087         return true;
1088   }
1089
1090   // Holds the read and read-write *pointers* that we find.
1091   ValueVector Reads;
1092   ValueVector ReadWrites;
1093
1094   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1095   // multiple times on the same object. If the ptr is accessed twice, once
1096   // for read and once for write, it will only appear once (on the write
1097   // list). This is okay, since we are going to check for conflicts between
1098   // writes and between reads and writes, but not between reads and reads.
1099   ValueSet Seen;
1100
1101   ValueVector::iterator I, IE;
1102   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1103     StoreInst *ST = dyn_cast<StoreInst>(*I);
1104     assert(ST && "Bad StoreInst");
1105     Value* Ptr = ST->getPointerOperand();
1106     // If we did *not* see this pointer before, insert it to
1107     // the read-write list. At this phase it is only a 'write' list.
1108     if (Seen.insert(Ptr))
1109       ReadWrites.push_back(Ptr);
1110   }
1111
1112   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1113     LoadInst *LD = dyn_cast<LoadInst>(*I);
1114     assert(LD && "Bad LoadInst");
1115     Value* Ptr = LD->getPointerOperand();
1116     // If we did *not* see this pointer before, insert it to the
1117     // read list. If we *did* see it before, then it is already in
1118     // the read-write list. This allows us to vectorize expressions
1119     // such as A[i] += x;  Because the address of A[i] is a read-write
1120     // pointer. This only works if the index of A[i] is consecutive.
1121     // If the address of i is unknown (for example A[B[i]]) then we may
1122     // read a few words, modify, and write a few words, and some of the
1123     // words may be written to the same address.
1124     if (Seen.insert(Ptr) || !isConsecutiveGep(Ptr))
1125       Reads.push_back(Ptr);
1126   }
1127
1128   // Now that the pointers are in two lists (Reads and ReadWrites), we
1129   // can check that there are no conflicts between each of the writes and
1130   // between the writes to the reads.
1131   ValueSet WriteObjects;
1132   ValueVector TempObjects;
1133
1134   // Check that the read-writes do not conflict with other read-write
1135   // pointers.
1136   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1137     GetUnderlyingObjects(*I, TempObjects, DL);
1138     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1139          it != e; ++it) {
1140       if (!isIdentifiedSafeObject(*it)) {
1141         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1142         return false;
1143       }
1144       if (!WriteObjects.insert(*it)) {
1145         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1146               << **it <<"\n");
1147         return false;
1148       }
1149     }
1150     TempObjects.clear();
1151   }
1152
1153   /// Check that the reads don't conflict with the read-writes.
1154   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1155     GetUnderlyingObjects(*I, TempObjects, DL);
1156     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1157          it != e; ++it) {
1158       if (!isIdentifiedSafeObject(*it)) {
1159         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1160         return false;
1161       }
1162       if (WriteObjects.count(*it)) {
1163         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1164               << **it <<"\n");
1165         return false;
1166       }
1167     }
1168     TempObjects.clear();
1169   }
1170
1171   // All is okay.
1172   return true;
1173 }
1174
1175 /// Checks if the value is a Global variable or if it is an Arguments
1176 /// marked with the NoAlias attribute.
1177 bool LoopVectorizationLegality::isIdentifiedSafeObject(Value* Val) {
1178   assert(Val && "Invalid value");
1179   if (dyn_cast<GlobalValue>(Val))
1180     return true;
1181   if (dyn_cast<AllocaInst>(Val))
1182     return true;
1183   Argument *A = dyn_cast<Argument>(Val);
1184   if (!A)
1185     return false;
1186   return A->hasNoAliasAttr();
1187 }
1188
1189 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1190                                                 ReductionKind Kind) {
1191   if (Phi->getNumIncomingValues() != 2)
1192     return false;
1193
1194   // Find the possible incoming reduction variable.
1195   BasicBlock *BB = Phi->getParent();
1196   int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1197   int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1198   Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1199
1200   // ExitInstruction is the single value which is used outside the loop.
1201   // We only allow for a single reduction value to be used outside the loop.
1202   // This includes users of the reduction, variables (which form a cycle
1203   // which ends in the phi node).
1204   Instruction *ExitInstruction = 0;
1205
1206   // Iter is our iterator. We start with the PHI node and scan for all of the
1207   // users of this instruction. All users must be instructions which can be
1208   // used as reduction variables (such as ADD). We may have a single
1209   // out-of-block user. They cycle must end with the original PHI.
1210   // Also, we can't have multiple block-local users.
1211   Instruction *Iter = Phi;
1212   while (true) {
1213     // Any reduction instr must be of one of the allowed kinds.
1214     if (!isReductionInstr(Iter, Kind))
1215       return false;
1216
1217     // Did we found a user inside this block ?
1218     bool FoundInBlockUser = false;
1219     // Did we reach the initial PHI node ?
1220     bool FoundStartPHI = false;
1221
1222     // If the instruction has no users then this is a broken
1223     // chain and can't be a reduction variable.
1224     if (Iter->use_begin() == Iter->use_end())
1225       return false;
1226
1227     // For each of the *users* of iter.
1228     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1229          it != e; ++it) {
1230       Instruction *U = cast<Instruction>(*it);
1231       // We already know that the PHI is a user.
1232       if (U == Phi) {
1233         FoundStartPHI = true;
1234         continue;
1235       }
1236       // Check if we found the exit user.
1237       BasicBlock *Parent = U->getParent();
1238       if (Parent != BB) {
1239         // We must have a single exit instruction.
1240         if (ExitInstruction != 0)
1241           return false;
1242         ExitInstruction = Iter;
1243       }
1244       // We can't have multiple inside users.
1245       if (FoundInBlockUser)
1246         return false;
1247       FoundInBlockUser = true;
1248       Iter = U;
1249     }
1250
1251     // We found a reduction var if we have reached the original
1252     // phi node and we only have a single instruction with out-of-loop
1253     // users.
1254    if (FoundStartPHI && ExitInstruction) {
1255      // This instruction is allowed to have out-of-loop users.
1256      AllowedExit.insert(ExitInstruction);
1257
1258      // Save the description of this reduction variable.
1259      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1260      Reductions[Phi] = RD;
1261      return true;
1262    }
1263   }
1264 }
1265
1266 bool
1267 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1268                                             ReductionKind Kind) {
1269     switch (I->getOpcode()) {
1270     default:
1271       return false;
1272     case Instruction::PHI:
1273       // possibly.
1274       return true;
1275     case Instruction::Add:
1276     case Instruction::Sub:
1277       return Kind == IntegerAdd;
1278     case Instruction::Mul:
1279     case Instruction::UDiv:
1280     case Instruction::SDiv:
1281       return Kind == IntegerMult;
1282     }
1283 }
1284
1285 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1286   // Check that the PHI is consecutive and starts at zero.
1287   const SCEV *PhiScev = SE->getSCEV(Phi);
1288   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1289   if (!AR) {
1290     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1291     return false;
1292   }
1293   const SCEV *Step = AR->getStepRecurrence(*SE);
1294   const SCEV *Start = AR->getStart();
1295
1296   if (!Step->isOne() || !Start->isZero()) {
1297     DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
1298     return false;
1299   }
1300   return true;
1301 }
1302
1303 } // namespace
1304
1305 char LoopVectorize::ID = 0;
1306 static const char lv_name[] = "Loop Vectorization";
1307 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
1308 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1309 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1310 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1311 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
1312
1313 namespace llvm {
1314   Pass *createLoopVectorizePass() {
1315     return new LoopVectorize();
1316   }
1317 }
1318