When looking for a vector representation of a scalar, do a single lookup. Also, cache...
[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 a simple loop vectorizer. We currently only support single block
11 // loops. We have a very simple and restrictive legality check: we need to read
12 // and write from disjoint memory locations. We still don't have a cost model.
13 // This pass has three parts:
14 // 1. The main loop pass that drives the different parts.
15 // 2. LoopVectorizationLegality - A helper class that checks for the legality
16 //    of the vectorization.
17 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
18 //    widening of instructions.
19 //
20 //===----------------------------------------------------------------------===//
21 #define LV_NAME "loop-vectorize"
22 #define DEBUG_TYPE LV_NAME
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Value.h"
30 #include "llvm/Function.h"
31 #include "llvm/Analysis/Verifier.h"
32 #include "llvm/Module.h"
33 #include "llvm/Type.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/AliasSetTracker.h"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Analysis/ScalarEvolution.h"
40 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
41 #include "llvm/Analysis/ScalarEvolutionExpander.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Analysis/LoopInfo.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/DataLayout.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include <algorithm>
51 using namespace llvm;
52
53 static cl::opt<unsigned>
54 DefaultVectorizationFactor("default-loop-vectorize-width",
55                           cl::init(4), cl::Hidden,
56                           cl::desc("Set the default loop vectorization width"));
57
58 namespace {
59
60 /// Vectorize a simple loop. This class performs the widening of simple single
61 /// basic block loops into vectors. It does not perform any
62 /// vectorization-legality checks, and just does it.  It widens the vectors
63 /// to a given vectorization factor (VF).
64 class SingleBlockLoopVectorizer {
65 public:
66   /// Ctor.
67   SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
68                             LPPassManager *Lpm, unsigned VecWidth):
69   Orig(OrigLoop), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
70    Builder(0), Induction(0), OldInduction(0) { }
71
72   ~SingleBlockLoopVectorizer() {
73     delete Builder;
74   }
75
76   // Perform the actual loop widening (vectorization).
77   void vectorize() {
78     ///Create a new empty loop. Unlink the old loop and connect the new one.
79     createEmptyLoop();
80     /// Widen each instruction in the old loop to a new one in the new loop.
81     vectorizeLoop();
82     // register the new loop.
83     cleanup();
84  }
85
86 private:
87   /// Create an empty loop, based on the loop ranges of the old loop.
88   void createEmptyLoop();
89   /// Copy and widen the instructions from the old loop.
90   void vectorizeLoop();
91   /// Insert the new loop to the loop hierarchy and pass manager.
92   void cleanup();
93
94   /// This instruction is un-vectorizable. Implement it as a sequence
95   /// of scalars.
96   void scalarizeInstruction(Instruction *Instr);
97
98   /// Create a broadcast instruction. This method generates a broadcast
99   /// instruction (shuffle) for loop invariant values and for the induction
100   /// value. If this is the induction variable then we extend it to N, N+1, ...
101   /// this is needed because each iteration in the loop corresponds to a SIMD
102   /// element.
103   Value *getBroadcastInstrs(Value *V);
104
105   /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
106   /// for each element in the vector. Starting from zero.
107   Value *getConsecutiveVector(Value* Val);
108
109   /// Check that the GEP operands are all uniform except for the last index
110   /// which has to be the induction variable.
111   bool isConsecutiveGep(GetElementPtrInst *Gep);
112
113   /// When we go over instructions in the basic block we rely on previous
114   /// values within the current basic block or on loop invariant values.
115   /// When we widen (vectorize) values we place them in the map. If the values
116   /// are not within the map, they have to be loop invariant, so we simply
117   /// broadcast them into a vector.
118   Value *getVectorValue(Value *V);
119
120   typedef DenseMap<Value*, Value*> ValueMap;
121
122   /// The original loop.
123   Loop *Orig;
124   // Scev analysis to use.
125   ScalarEvolution *SE;
126   // Loop Info.
127   LoopInfo *LI;
128   // Loop Pass Manager;
129   LPPassManager *LPM;
130   // The vectorization factor to use.
131   unsigned VF;
132
133   // The builder that we use
134   IRBuilder<> *Builder;
135
136   // --- Vectorization state ---
137
138   /// The new Induction variable which was added to the new block.
139   PHINode *Induction;
140   /// The induction variable of the old basic block.
141   PHINode *OldInduction;
142   // Maps scalars to widened vectors.
143   ValueMap WidenMap;
144 };
145
146 /// Perform the vectorization legality check. This class does not look at the
147 /// profitability of vectorization, only the legality. At the moment the checks
148 /// are very simple and focus on single basic block loops with a constant
149 /// iteration count and no reductions.
150 class LoopVectorizationLegality {
151 public:
152   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
153   TheLoop(Lp), SE(Se), DL(Dl) { }
154
155   /// Returns the maximum vectorization factor that we *can* use to vectorize
156   /// this loop. This does not mean that it is profitable to vectorize this
157   /// loop, only that it is legal to do so. This may be a large number. We
158   /// can vectorize to any SIMD width below this number.
159   unsigned getLoopMaxVF();
160
161 private:
162   /// Check if a single basic block loop is vectorizable.
163   /// At this point we know that this is a loop with a constant trip count
164   /// and we only need to check individual instructions.
165   bool canVectorizeBlock(BasicBlock &BB);
166
167   // Check if a pointer value is known to be disjoint.
168   // Example: Alloca, Global, NoAlias.
169   bool isKnownDisjoint(Value* Val);
170
171   /// The loop that we evaluate.
172   Loop *TheLoop;
173   /// Scev analysis.
174   ScalarEvolution *SE;
175   /// DataLayout analysis.
176   DataLayout *DL;
177 };
178
179 struct LoopVectorize : public LoopPass {
180   static char ID; // Pass identification, replacement for typeid
181
182   LoopVectorize() : LoopPass(ID) {
183     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
184   }
185
186   ScalarEvolution *SE;
187   DataLayout *DL;
188   LoopInfo *LI;
189
190   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
191     // Only vectorize innermost loops.
192     if (!L->empty())
193       return false;
194
195     SE = &getAnalysis<ScalarEvolution>();
196     DL = getAnalysisIfAvailable<DataLayout>();
197     LI = &getAnalysis<LoopInfo>();
198
199     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
200           L->getHeader()->getParent()->getName() << "\"\n");
201
202     // Check if it is legal to vectorize the loop.
203     LoopVectorizationLegality LVL(L, SE, DL);
204     unsigned MaxVF = LVL.getLoopMaxVF();
205
206     // Check that we can vectorize using the chosen vectorization width.
207     if (MaxVF < DefaultVectorizationFactor) {
208       DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
209       return false;
210     }
211
212     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
213
214     // If we decided that is is *legal* to vectorizer the loop. Do it.
215     SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, DefaultVectorizationFactor);
216     LB.vectorize();
217
218     DEBUG(verifyFunction(*L->getHeader()->getParent()));
219     return true;
220   }
221
222   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
223     LoopPass::getAnalysisUsage(AU);
224     AU.addRequiredID(LoopSimplifyID);
225     AU.addRequired<LoopInfo>();
226     AU.addRequired<ScalarEvolution>();
227   }
228
229 };
230
231 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
232   // Instructions that access the old induction variable
233   // actually want to get the new one.
234   if (V == OldInduction)
235     V = Induction;
236   // Create the types.
237   LLVMContext &C = V->getContext();
238   Type *VTy = VectorType::get(V->getType(), VF);
239   Type *I32 = IntegerType::getInt32Ty(C);
240   Constant *Zero = ConstantInt::get(I32, 0);
241   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
242   Value *UndefVal = UndefValue::get(VTy);
243   // Insert the value into a new vector.
244   Value *SingleElem = Builder->CreateInsertElement(UndefVal, V, Zero);
245   // Broadcast the scalar into all locations in the vector.
246   Value *Shuf = Builder->CreateShuffleVector(SingleElem, UndefVal, Zeros,
247                                              "broadcast");
248   // We are accessing the induction variable. Make sure to promote the
249   // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
250   if (V == Induction)
251     return getConsecutiveVector(Shuf);
252   return Shuf;
253 }
254
255 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
256   assert(Val->getType()->isVectorTy() && "Must be a vector");
257   assert(Val->getType()->getScalarType()->isIntegerTy() &&
258          "Elem must be an integer");
259   // Create the types.
260   Type *ITy = Val->getType()->getScalarType();
261   VectorType *Ty = cast<VectorType>(Val->getType());
262   unsigned VLen = Ty->getNumElements();
263   SmallVector<Constant*, 8> Indices;
264
265   // Create a vector of consecutive numbers from zero to VF.
266   for (unsigned i = 0; i < VLen; ++i)
267     Indices.push_back(ConstantInt::get(ITy, i));
268
269   // Add the consecutive indices to the vector value.
270   Constant *Cv = ConstantVector::get(Indices);
271   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
272   return Builder->CreateAdd(Val, Cv, "induction");
273 }
274
275
276 bool SingleBlockLoopVectorizer::isConsecutiveGep(GetElementPtrInst *Gep) {
277   if (!Gep)
278     return false;
279
280   unsigned NumOperands = Gep->getNumOperands();
281   Value *LastIndex = Gep->getOperand(NumOperands - 1);
282
283   // Check that all of the gep indices are uniform except for the last.
284   for (unsigned i = 0; i < NumOperands - 1; ++i)
285     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), Orig))
286       return false;
287
288   // We can emit wide load/stores only of the last index is the induction
289   // variable.
290   const SCEV *Last = SE->getSCEV(LastIndex);
291   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
292     const SCEV *Step = AR->getStepRecurrence(*SE);
293
294     // The memory is consecutive because the last index is consecutive
295     // and all other indices are loop invariant.
296     if (Step->isOne())
297       return true;
298   }
299
300   return false;
301 }
302
303 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
304   // If we saved a vectorized copy of V, use it.
305   ValueMap::iterator it = WidenMap.find(V);
306   if (it != WidenMap.end())
307      return it->second;
308
309   // Broadcast V and save the value for future uses.
310   Value *B = getBroadcastInstrs(V);
311   WidenMap[V] = B;
312   return B;
313 }
314
315 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
316   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
317   // Holds vector parameters or scalars, in case of uniform vals.
318   SmallVector<Value*, 8> Params;
319
320   // Find all of the vectorized parameters.
321   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
322     Value *SrcOp = Instr->getOperand(op);
323
324     // If we are accessing the old induction variable, use the new one.
325     if (SrcOp == OldInduction) {
326       Params.push_back(getBroadcastInstrs(Induction));
327       continue;
328     }
329
330     // Try using previously calculated values.
331     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
332
333     // If the src is an instruction that appeared earlier in the basic block
334     // then it should already be vectorized.
335     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
336       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
337       // The parameter is a vector value from earlier.
338       Params.push_back(WidenMap[SrcInst]);
339     } else {
340       // The parameter is a scalar from outside the loop. Maybe even a constant.
341       Params.push_back(SrcOp);
342     }
343   }
344
345   assert(Params.size() == Instr->getNumOperands() &&
346          "Invalid number of operands");
347
348   // Does this instruction return a value ?
349   bool IsVoidRetTy = Instr->getType()->isVoidTy();
350   Value *VecResults = 0;
351
352   // If we have a return value, create an empty vector. We place the scalarized
353   // instructions in this vector.
354   if (!IsVoidRetTy)
355     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
356
357   // For each scalar that we create.
358   for (unsigned i = 0; i < VF; ++i) {
359     Instruction *Cloned = Instr->clone();
360     if (!IsVoidRetTy)
361       Cloned->setName(Instr->getName() + ".cloned");
362     // Replace the operands of the cloned instrucions with extracted scalars.
363     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
364       Value *Op = Params[op];
365       // Param is a vector. Need to extract the right lane.
366       if (Op->getType()->isVectorTy())
367         Op = Builder->CreateExtractElement(Op, Builder->getInt32(i));
368       Cloned->setOperand(op, Op);
369     }
370
371     // Place the cloned scalar in the new loop.
372     Builder->Insert(Cloned);
373
374     // If the original scalar returns a value we need to place it in a vector
375     // so that future users will be able to use it.
376     if (!IsVoidRetTy)
377       VecResults = Builder->CreateInsertElement(VecResults, Cloned,
378                                                Builder->getInt32(i));
379   }
380
381   if (!IsVoidRetTy)
382     WidenMap[Instr] = VecResults;
383 }
384
385 void SingleBlockLoopVectorizer::createEmptyLoop() {
386   /*
387    In this function we generate a new loop. The new loop will contain
388    the vectorized instructions while the old loop will continue to run the
389    scalar remainder.
390
391    [  ] <-- vector loop bypass.
392   /  |
393  /   v
394 |   [ ]     <-- vector pre header.
395 |    |
396 |    v
397 |   [  ] \
398 |   [  ]_|   <-- vector loop.
399 |    |
400  \   v
401    >[ ]   <--- middle-block.
402   /  |
403  /   v
404 |   [ ]     <--- new preheader.
405 |    |
406 |    v
407 |   [ ] \
408 |   [ ]_|   <-- old scalar loop to handle remainder. ()
409  \   |
410   \  v
411    >[ ]     <-- exit block.
412    ...
413    */
414
415   // This is the original scalar-loop preheader.
416   BasicBlock *BypassBlock = Orig->getLoopPreheader();
417   BasicBlock *ExitBlock = Orig->getExitBlock();
418   assert(ExitBlock && "Must have an exit block");
419
420   assert(Orig->getNumBlocks() == 1 && "Invalid loop");
421   assert(BypassBlock && "Invalid loop structure");
422
423   BasicBlock *VectorPH =
424       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
425   BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
426                                                  "vector.body");
427
428   BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
429                                                   "middle.block");
430
431
432   BasicBlock *ScalarPH =
433           MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
434                                        "scalar.preheader");
435
436   // Find the induction variable.
437   BasicBlock *OldBasicBlock = Orig->getHeader();
438   OldInduction = dyn_cast<PHINode>(OldBasicBlock->begin());
439   assert(OldInduction && "We must have a single phi node.");
440   Type *IdxTy = OldInduction->getType();
441
442   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
443   // inside the loop.
444   Builder = new IRBuilder<>(VecBody);
445   Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
446
447   // Generate the induction variable.
448   Induction = Builder->CreatePHI(IdxTy, 2, "index");
449   Constant *Zero = ConstantInt::get(IdxTy, 0);
450   Constant *Step = ConstantInt::get(IdxTy, VF);
451
452   // Find the loop boundaries.
453   const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
454   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
455
456   // Get the total trip count from the count by adding 1.
457   ExitCount = SE->getAddExpr(ExitCount,
458                              SE->getConstant(ExitCount->getType(), 1));
459
460   // Expand the trip count and place the new instructions in the preheader.
461   // Notice that the pre-header does not change, only the loop body.
462   SCEVExpander Exp(*SE, "induction");
463   Instruction *Loc = BypassBlock->getTerminator();
464
465   // We may need to extend the index in case there is a type mismatch.
466   // We know that the count starts at zero and does not overflow.
467   // We are using Zext because it should be less expensive.
468   if (ExitCount->getType() != Induction->getType())
469     ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
470
471   // Count holds the overall loop count (N).
472   Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
473   // Now we need to generate the expression for N - (N % VF), which is
474   // the part that the vectorized body will execute.
475   Constant *CIVF = ConstantInt::get(IdxTy, VF);
476   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
477   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
478
479   // Now, compare the new count to zero. If it is zero, jump to the scalar part.
480   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
481                                CountRoundDown, ConstantInt::getNullValue(IdxTy),
482                                "cmp.zero", Loc);
483   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
484   // Remove the old terminator.
485   Loc->eraseFromParent();
486
487   // Add a check in the middle block to see if we have completed
488   // all of the iterations in the first vector loop.
489   // If (N - N%VF) == N, then we *don't* need to run the remainder.
490   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
491                                 CountRoundDown, "cmp.n",
492                                 MiddleBlock->getTerminator());
493
494   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
495   // Remove the old terminator.
496   MiddleBlock->getTerminator()->eraseFromParent();
497
498   // Create i+1 and fill the PHINode.
499   Value *NextIdx = Builder->CreateAdd(Induction, Step, "index.next");
500   Induction->addIncoming(Zero, VectorPH);
501   Induction->addIncoming(NextIdx, VecBody);
502   // Create the compare.
503   Value *ICmp = Builder->CreateICmpEQ(NextIdx, CountRoundDown);
504   Builder->CreateCondBr(ICmp, MiddleBlock, VecBody);
505
506   // Now we have two terminators. Remove the old one from the block.
507   VecBody->getTerminator()->eraseFromParent();
508
509   // Fix the scalar body iteration count.
510   unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
511   OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
512
513   // Get ready to start creating new instructions into the vectorized body.
514   Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
515
516   // Register the new loop.
517   Loop* Lp = new Loop();
518   LPM->insertLoop(Lp, Orig->getParentLoop());
519
520   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
521
522   Loop *ParentLoop = Orig->getParentLoop();
523   if (ParentLoop) {
524     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
525     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
526     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
527   }
528 }
529
530 void SingleBlockLoopVectorizer::vectorizeLoop() {
531   BasicBlock &BB = *Orig->getHeader();
532
533   // For each instruction in the old loop.
534   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
535     Instruction *Inst = it;
536
537     switch (Inst->getOpcode()) {
538       case Instruction::PHI:
539       case Instruction::Br:
540         // Nothing to do for PHIs and BR, since we already took care of the
541         // loop control flow instructions.
542         continue;
543
544       case Instruction::Add:
545       case Instruction::FAdd:
546       case Instruction::Sub:
547       case Instruction::FSub:
548       case Instruction::Mul:
549       case Instruction::FMul:
550       case Instruction::UDiv:
551       case Instruction::SDiv:
552       case Instruction::FDiv:
553       case Instruction::URem:
554       case Instruction::SRem:
555       case Instruction::FRem:
556       case Instruction::Shl:
557       case Instruction::LShr:
558       case Instruction::AShr:
559       case Instruction::And:
560       case Instruction::Or:
561       case Instruction::Xor: {
562         // Just widen binops.
563         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
564         Value *A = getVectorValue(Inst->getOperand(0));
565         Value *B = getVectorValue(Inst->getOperand(1));
566         // Use this vector value for all users of the original instruction.
567         WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
568         break;
569       }
570       case Instruction::Select: {
571         // Widen selects.
572         Value *A = getVectorValue(Inst->getOperand(0));
573         Value *B = getVectorValue(Inst->getOperand(1));
574         Value *C = getVectorValue(Inst->getOperand(2));
575         WidenMap[Inst] = Builder->CreateSelect(A, B, C);
576         break;
577       }
578
579       case Instruction::ICmp:
580       case Instruction::FCmp: {
581         // Widen compares. Generate vector compares.
582         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
583         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
584         Value *A = getVectorValue(Inst->getOperand(0));
585         Value *B = getVectorValue(Inst->getOperand(1));
586         if (FCmp)
587           WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
588         else
589           WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
590         break;
591       }
592
593       case Instruction::Store: {
594         // Attempt to issue a wide store.
595         StoreInst *SI = dyn_cast<StoreInst>(Inst);
596         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
597         Value *Ptr = SI->getPointerOperand();
598         unsigned Alignment = SI->getAlignment();
599         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
600         // This store does not use GEPs.
601         if (!isConsecutiveGep(Gep)) {
602           scalarizeInstruction(Inst);
603           break;
604         }
605
606         // Create the new GEP with the new induction variable.
607         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
608         unsigned NumOperands = Gep->getNumOperands();
609         Gep2->setOperand(NumOperands - 1, Induction);
610         Ptr = Builder->Insert(Gep2);
611         Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
612         Value *Val = getVectorValue(SI->getValueOperand());
613         Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
614         break;
615       }
616       case Instruction::Load: {
617         // Attempt to issue a wide load.
618         LoadInst *LI = dyn_cast<LoadInst>(Inst);
619         Type *RetTy = VectorType::get(LI->getType(), VF);
620         Value *Ptr = LI->getPointerOperand();
621         unsigned Alignment = LI->getAlignment();
622         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
623
624         // We don't have a gep. Scalarize the load.
625         if (!isConsecutiveGep(Gep)) {
626           scalarizeInstruction(Inst);
627           break;
628         }
629
630         // Create the new GEP with the new induction variable.
631         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
632         unsigned NumOperands = Gep->getNumOperands();
633         Gep2->setOperand(NumOperands - 1, Induction);
634         Ptr = Builder->Insert(Gep2);
635         Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
636         LI = Builder->CreateLoad(Ptr);
637         LI->setAlignment(Alignment);
638         // Use this vector value for all users of the load.
639         WidenMap[Inst] = LI;
640         break;
641       }
642       case Instruction::ZExt:
643       case Instruction::SExt:
644       case Instruction::FPToUI:
645       case Instruction::FPToSI:
646       case Instruction::FPExt:
647       case Instruction::PtrToInt:
648       case Instruction::IntToPtr:
649       case Instruction::SIToFP:
650       case Instruction::UIToFP:
651       case Instruction::Trunc:
652       case Instruction::FPTrunc:
653       case Instruction::BitCast: {
654         /// Vectorize bitcasts.
655         CastInst *CI = dyn_cast<CastInst>(Inst);
656         Value *A = getVectorValue(Inst->getOperand(0));
657         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
658         WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
659         break;
660       }
661
662       default:
663         /// All other instructions are unsupported. Scalarize them.
664         scalarizeInstruction(Inst);
665         break;
666     }// end of switch.
667   }// end of for_each instr.
668 }
669
670 void SingleBlockLoopVectorizer::cleanup() {
671   // The original basic block.
672   SE->forgetLoop(Orig);
673 }
674
675 unsigned LoopVectorizationLegality::getLoopMaxVF() {
676   if (!TheLoop->getLoopPreheader()) {
677     assert(false && "No preheader!!");
678     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
679     return  1;
680   }
681
682   // We can only vectorize single basic block loops.
683   unsigned NumBlocks = TheLoop->getNumBlocks();
684   if (NumBlocks != 1) {
685     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
686     return 1;
687   }
688
689   // We need to have a loop header.
690   BasicBlock *BB = TheLoop->getHeader();
691   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
692
693   // Go over each instruction and look at memory deps.
694   if (!canVectorizeBlock(*BB)) {
695     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
696     return 1;
697   }
698
699   // ScalarEvolution needs to be able to find the exit count.
700   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
701   if (ExitCount == SE->getCouldNotCompute()) {
702     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
703     return 1;
704   }
705
706   DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
707
708   // Okay! We can vectorize. At this point we don't have any other mem analysis
709   // which may limit our maximum vectorization factor, so just return the
710   // maximum SIMD size.
711   return DefaultVectorizationFactor;
712 }
713
714 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
715   // Holds the read and write pointers that we find.
716   typedef SmallVector<Value*, 10> ValueVector;
717   ValueVector Reads;
718   ValueVector Writes;
719
720   unsigned NumPhis = 0;
721   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
722     Instruction *I = it;
723
724     PHINode *Phi = dyn_cast<PHINode>(I);
725     if (Phi) {
726       NumPhis++;
727       // We only look at integer phi nodes.
728       if (!Phi->getType()->isIntegerTy()) {
729         DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
730         return false;
731       }
732
733       // If we found an induction variable.
734       if (NumPhis > 1) {
735         DEBUG(dbgs() << "LV: Found more than one PHI.\n");
736         return false;
737       }
738
739       // This should not happen because the loop should be normalized.
740       if (Phi->getNumIncomingValues() != 2) {
741         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
742         return false;
743       }
744
745       // Check that the PHI is consecutive and starts at zero.
746       const SCEV *PhiScev = SE->getSCEV(Phi);
747       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
748       if (!AR) {
749         DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
750         return false;
751       }
752
753       const SCEV *Step = AR->getStepRecurrence(*SE);
754       const SCEV *Start = AR->getStart();
755
756       if (!Step->isOne() || !Start->isZero()) {
757         DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
758         return false;
759       }
760     }
761
762     // If this is a load, record its pointer. If it is not a load, abort.
763     // Notice that we don't handle function calls that read or write.
764     if (I->mayReadFromMemory()) {
765       LoadInst *Ld = dyn_cast<LoadInst>(I);
766       if (!Ld) return false;
767       if (!Ld->isSimple()) {
768         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
769         return false;
770       }
771       GetUnderlyingObjects(Ld->getPointerOperand(), Reads, DL);
772     }
773
774     // Record store pointers. Abort on all other instructions that write to
775     // memory.
776     if (I->mayWriteToMemory()) {
777       StoreInst *St = dyn_cast<StoreInst>(I);
778       if (!St) return false;
779       if (!St->isSimple()) {
780         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
781         return false;
782       }
783       GetUnderlyingObjects(St->getPointerOperand(), Writes, DL);
784     }
785
786     // We still don't handle functions.
787     CallInst *CI = dyn_cast<CallInst>(I);
788     if (CI) {
789       DEBUG(dbgs() << "LV: Found a call site:"<<
790             CI->getCalledFunction()->getName() << "\n");
791       return false;
792     }
793
794     // We do not re-vectorize vectors.
795     if (!VectorType::isValidElementType(I->getType()) &&
796         !I->getType()->isVoidTy()) {
797       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
798       return false;
799     }
800     //Check that all of the users of the loop are inside the BB.
801     for (Value::use_iterator it = I->use_begin(), e = I->use_end();
802          it != e; ++it) {
803       Instruction *U = cast<Instruction>(*it);
804       BasicBlock *Parent = U->getParent();
805       if (Parent != &BB) {
806         DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
807         return false;
808       }
809     }
810   } // next instr.
811
812   if (NumPhis != 1) {
813       DEBUG(dbgs() << "LV: Did not find a Phi node.\n");
814       return false;
815   }
816
817   // Check that the underlying objects of the reads and writes are either
818   // disjoint memory locations, or that they are no-alias arguments.
819   ValueVector::iterator r, re, w, we;
820   for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
821     if (!isKnownDisjoint(*r)) {
822       DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
823       return false;
824     }
825   }
826
827   for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
828     if (!isKnownDisjoint(*w)) {
829       DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
830       return false;
831     }
832   }
833
834   // Check that there are no multiple write locations to the same pointer.
835   SmallPtrSet<Value*, 8> BasePointers;
836   for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
837     if (BasePointers.count(*w)) {
838       DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
839       return false;
840     }
841     BasePointers.insert(*w);
842   }
843
844   // Sort the writes vector so that we can use a binary search.
845   std::sort(Writes.begin(), Writes.end());
846   // Check that the reads and the writes are disjoint.
847   for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
848     if (std::binary_search(Writes.begin(), Writes.end(), *r)) {
849       DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
850       return false;
851     }
852   }
853
854   // All is okay.
855   return true;
856 }
857
858 /// Checks if the value is a Global variable or if it is an Arguments
859 /// marked with the NoAlias attribute.
860 bool LoopVectorizationLegality::isKnownDisjoint(Value* Val) {
861   assert(Val && "Invalid value");
862   if (dyn_cast<GlobalValue>(Val))
863     return true;
864   if (dyn_cast<AllocaInst>(Val))
865     return true;
866   Argument *A = dyn_cast<Argument>(Val);
867   if (!A)
868     return false;
869   return A->hasNoAliasAttr();
870 }
871
872 } // namespace
873
874 char LoopVectorize::ID = 0;
875 static const char lv_name[] = "Loop Vectorization";
876 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
877 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
878 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
879 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
880 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
881
882 namespace llvm {
883   Pass *createLoopVectorizePass() {
884     return new LoopVectorize();
885   }
886
887 }
888