fix a naming typo
[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 isIdentifiedSafeObject(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   BasicBlock *ScalarPH =
431           MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
432                                        "scalar.preheader");
433
434   // Find the induction variable.
435   BasicBlock *OldBasicBlock = Orig->getHeader();
436   OldInduction = dyn_cast<PHINode>(OldBasicBlock->begin());
437   assert(OldInduction && "We must have a single phi node.");
438   Type *IdxTy = OldInduction->getType();
439
440   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
441   // inside the loop.
442   Builder = new IRBuilder<>(VecBody);
443   Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
444
445   // Generate the induction variable.
446   Induction = Builder->CreatePHI(IdxTy, 2, "index");
447   Constant *Zero = ConstantInt::get(IdxTy, 0);
448   Constant *Step = ConstantInt::get(IdxTy, VF);
449
450   // Find the loop boundaries.
451   const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
452   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
453
454   // Get the total trip count from the count by adding 1.
455   ExitCount = SE->getAddExpr(ExitCount,
456                              SE->getConstant(ExitCount->getType(), 1));
457
458   // Expand the trip count and place the new instructions in the preheader.
459   // Notice that the pre-header does not change, only the loop body.
460   SCEVExpander Exp(*SE, "induction");
461   Instruction *Loc = BypassBlock->getTerminator();
462
463   // We may need to extend the index in case there is a type mismatch.
464   // We know that the count starts at zero and does not overflow.
465   // We are using Zext because it should be less expensive.
466   if (ExitCount->getType() != Induction->getType())
467     ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
468
469   // Count holds the overall loop count (N).
470   Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
471   // Now we need to generate the expression for N - (N % VF), which is
472   // the part that the vectorized body will execute.
473   Constant *CIVF = ConstantInt::get(IdxTy, VF);
474   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
475   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
476
477   // Now, compare the new count to zero. If it is zero, jump to the scalar part.
478   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
479                                CountRoundDown, ConstantInt::getNullValue(IdxTy),
480                                "cmp.zero", Loc);
481   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
482   // Remove the old terminator.
483   Loc->eraseFromParent();
484
485   // Add a check in the middle block to see if we have completed
486   // all of the iterations in the first vector loop.
487   // If (N - N%VF) == N, then we *don't* need to run the remainder.
488   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
489                                 CountRoundDown, "cmp.n",
490                                 MiddleBlock->getTerminator());
491
492   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
493   // Remove the old terminator.
494   MiddleBlock->getTerminator()->eraseFromParent();
495
496   // Create i+1 and fill the PHINode.
497   Value *NextIdx = Builder->CreateAdd(Induction, Step, "index.next");
498   Induction->addIncoming(Zero, VectorPH);
499   Induction->addIncoming(NextIdx, VecBody);
500   // Create the compare.
501   Value *ICmp = Builder->CreateICmpEQ(NextIdx, CountRoundDown);
502   Builder->CreateCondBr(ICmp, MiddleBlock, VecBody);
503
504   // Now we have two terminators. Remove the old one from the block.
505   VecBody->getTerminator()->eraseFromParent();
506
507   // Fix the scalar body iteration count.
508   unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
509   OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
510
511   // Get ready to start creating new instructions into the vectorized body.
512   Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
513
514   // Register the new loop.
515   Loop* Lp = new Loop();
516   LPM->insertLoop(Lp, Orig->getParentLoop());
517
518   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
519
520   Loop *ParentLoop = Orig->getParentLoop();
521   if (ParentLoop) {
522     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
523     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
524     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
525   }
526 }
527
528 void SingleBlockLoopVectorizer::vectorizeLoop() {
529   BasicBlock &BB = *Orig->getHeader();
530
531   // For each instruction in the old loop.
532   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
533     Instruction *Inst = it;
534
535     switch (Inst->getOpcode()) {
536       case Instruction::PHI:
537       case Instruction::Br:
538         // Nothing to do for PHIs and BR, since we already took care of the
539         // loop control flow instructions.
540         continue;
541
542       case Instruction::Add:
543       case Instruction::FAdd:
544       case Instruction::Sub:
545       case Instruction::FSub:
546       case Instruction::Mul:
547       case Instruction::FMul:
548       case Instruction::UDiv:
549       case Instruction::SDiv:
550       case Instruction::FDiv:
551       case Instruction::URem:
552       case Instruction::SRem:
553       case Instruction::FRem:
554       case Instruction::Shl:
555       case Instruction::LShr:
556       case Instruction::AShr:
557       case Instruction::And:
558       case Instruction::Or:
559       case Instruction::Xor: {
560         // Just widen binops.
561         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
562         Value *A = getVectorValue(Inst->getOperand(0));
563         Value *B = getVectorValue(Inst->getOperand(1));
564         // Use this vector value for all users of the original instruction.
565         WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
566         break;
567       }
568       case Instruction::Select: {
569         // Widen selects.
570         Value *A = getVectorValue(Inst->getOperand(0));
571         Value *B = getVectorValue(Inst->getOperand(1));
572         Value *C = getVectorValue(Inst->getOperand(2));
573         WidenMap[Inst] = Builder->CreateSelect(A, B, C);
574         break;
575       }
576
577       case Instruction::ICmp:
578       case Instruction::FCmp: {
579         // Widen compares. Generate vector compares.
580         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
581         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
582         Value *A = getVectorValue(Inst->getOperand(0));
583         Value *B = getVectorValue(Inst->getOperand(1));
584         if (FCmp)
585           WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
586         else
587           WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
588         break;
589       }
590
591       case Instruction::Store: {
592         // Attempt to issue a wide store.
593         StoreInst *SI = dyn_cast<StoreInst>(Inst);
594         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
595         Value *Ptr = SI->getPointerOperand();
596         unsigned Alignment = SI->getAlignment();
597         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
598         // This store does not use GEPs.
599         if (!isConsecutiveGep(Gep)) {
600           scalarizeInstruction(Inst);
601           break;
602         }
603
604         // Create the new GEP with the new induction variable.
605         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
606         unsigned NumOperands = Gep->getNumOperands();
607         Gep2->setOperand(NumOperands - 1, Induction);
608         Ptr = Builder->Insert(Gep2);
609         Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
610         Value *Val = getVectorValue(SI->getValueOperand());
611         Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
612         break;
613       }
614       case Instruction::Load: {
615         // Attempt to issue a wide load.
616         LoadInst *LI = dyn_cast<LoadInst>(Inst);
617         Type *RetTy = VectorType::get(LI->getType(), VF);
618         Value *Ptr = LI->getPointerOperand();
619         unsigned Alignment = LI->getAlignment();
620         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
621
622         // We don't have a gep. Scalarize the load.
623         if (!isConsecutiveGep(Gep)) {
624           scalarizeInstruction(Inst);
625           break;
626         }
627
628         // Create the new GEP with the new induction variable.
629         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
630         unsigned NumOperands = Gep->getNumOperands();
631         Gep2->setOperand(NumOperands - 1, Induction);
632         Ptr = Builder->Insert(Gep2);
633         Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
634         LI = Builder->CreateLoad(Ptr);
635         LI->setAlignment(Alignment);
636         // Use this vector value for all users of the load.
637         WidenMap[Inst] = LI;
638         break;
639       }
640       case Instruction::ZExt:
641       case Instruction::SExt:
642       case Instruction::FPToUI:
643       case Instruction::FPToSI:
644       case Instruction::FPExt:
645       case Instruction::PtrToInt:
646       case Instruction::IntToPtr:
647       case Instruction::SIToFP:
648       case Instruction::UIToFP:
649       case Instruction::Trunc:
650       case Instruction::FPTrunc:
651       case Instruction::BitCast: {
652         /// Vectorize bitcasts.
653         CastInst *CI = dyn_cast<CastInst>(Inst);
654         Value *A = getVectorValue(Inst->getOperand(0));
655         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
656         WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
657         break;
658       }
659
660       default:
661         /// All other instructions are unsupported. Scalarize them.
662         scalarizeInstruction(Inst);
663         break;
664     }// end of switch.
665   }// end of for_each instr.
666 }
667
668 void SingleBlockLoopVectorizer::cleanup() {
669   // The original basic block.
670   SE->forgetLoop(Orig);
671 }
672
673 unsigned LoopVectorizationLegality::getLoopMaxVF() {
674   if (!TheLoop->getLoopPreheader()) {
675     assert(false && "No preheader!!");
676     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
677     return  1;
678   }
679
680   // We can only vectorize single basic block loops.
681   unsigned NumBlocks = TheLoop->getNumBlocks();
682   if (NumBlocks != 1) {
683     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
684     return 1;
685   }
686
687   // We need to have a loop header.
688   BasicBlock *BB = TheLoop->getHeader();
689   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
690
691   // Go over each instruction and look at memory deps.
692   if (!canVectorizeBlock(*BB)) {
693     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
694     return 1;
695   }
696
697   // ScalarEvolution needs to be able to find the exit count.
698   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
699   if (ExitCount == SE->getCouldNotCompute()) {
700     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
701     return 1;
702   }
703
704   DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
705
706   // Okay! We can vectorize. At this point we don't have any other mem analysis
707   // which may limit our maximum vectorization factor, so just return the
708   // maximum SIMD size.
709   return DefaultVectorizationFactor;
710 }
711
712 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
713   // Holds the read and write pointers that we find.
714   typedef SmallVector<Value*, 10> ValueVector;
715   ValueVector Reads;
716   ValueVector Writes;
717
718   unsigned NumPhis = 0;
719   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
720     Instruction *I = it;
721
722     PHINode *Phi = dyn_cast<PHINode>(I);
723     if (Phi) {
724       NumPhis++;
725       // We only look at integer phi nodes.
726       if (!Phi->getType()->isIntegerTy()) {
727         DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
728         return false;
729       }
730
731       // If we found an induction variable.
732       if (NumPhis > 1) {
733         DEBUG(dbgs() << "LV: Found more than one PHI.\n");
734         return false;
735       }
736
737       // This should not happen because the loop should be normalized.
738       if (Phi->getNumIncomingValues() != 2) {
739         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
740         return false;
741       }
742
743       // Check that the PHI is consecutive and starts at zero.
744       const SCEV *PhiScev = SE->getSCEV(Phi);
745       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
746       if (!AR) {
747         DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
748         return false;
749       }
750
751       const SCEV *Step = AR->getStepRecurrence(*SE);
752       const SCEV *Start = AR->getStart();
753
754       if (!Step->isOne() || !Start->isZero()) {
755         DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
756         return false;
757       }
758     }
759
760     // If this is a load, record its pointer. If it is not a load, abort.
761     // Notice that we don't handle function calls that read or write.
762     if (I->mayReadFromMemory()) {
763       LoadInst *Ld = dyn_cast<LoadInst>(I);
764       if (!Ld) return false;
765       if (!Ld->isSimple()) {
766         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
767         return false;
768       }
769       GetUnderlyingObjects(Ld->getPointerOperand(), Reads, DL);
770     }
771
772     // Record store pointers. Abort on all other instructions that write to
773     // memory.
774     if (I->mayWriteToMemory()) {
775       StoreInst *St = dyn_cast<StoreInst>(I);
776       if (!St) return false;
777       if (!St->isSimple()) {
778         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
779         return false;
780       }
781       GetUnderlyingObjects(St->getPointerOperand(), Writes, DL);
782     }
783
784     // We still don't handle functions.
785     CallInst *CI = dyn_cast<CallInst>(I);
786     if (CI) {
787       DEBUG(dbgs() << "LV: Found a call site:"<<
788             CI->getCalledFunction()->getName() << "\n");
789       return false;
790     }
791
792     // We do not re-vectorize vectors.
793     if (!VectorType::isValidElementType(I->getType()) &&
794         !I->getType()->isVoidTy()) {
795       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
796       return false;
797     }
798     //Check that all of the users of the loop are inside the BB.
799     for (Value::use_iterator it = I->use_begin(), e = I->use_end();
800          it != e; ++it) {
801       Instruction *U = cast<Instruction>(*it);
802       BasicBlock *Parent = U->getParent();
803       if (Parent != &BB) {
804         DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
805         return false;
806       }
807     }
808   } // next instr.
809
810   if (NumPhis != 1) {
811       DEBUG(dbgs() << "LV: Did not find a Phi node.\n");
812       return false;
813   }
814
815   // Check that the underlying objects of the reads and writes are either
816   // disjoint memory locations, or that they are no-alias arguments.
817   ValueVector::iterator r, re, w, we;
818   for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
819     if (!isIdentifiedSafeObject(*r)) {
820       DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
821       return false;
822     }
823   }
824
825   for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
826     if (!isIdentifiedSafeObject(*w)) {
827       DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
828       return false;
829     }
830   }
831
832   // Check that there are no multiple write locations to the same pointer.
833   SmallPtrSet<Value*, 8> WritePointerSet;
834   for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
835     if (!WritePointerSet.insert(*w)) {
836       DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
837       return false;
838     }
839   }
840
841   // Check that the reads and the writes are disjoint.
842   for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
843     if (WritePointerSet.count(*r)) {
844       DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
845       return false;
846     }
847   }
848
849   // All is okay.
850   return true;
851 }
852
853 /// Checks if the value is a Global variable or if it is an Arguments
854 /// marked with the NoAlias attribute.
855 bool LoopVectorizationLegality::isIdentifiedSafeObject(Value* Val) {
856   assert(Val && "Invalid value");
857   if (dyn_cast<GlobalValue>(Val))
858     return true;
859   if (dyn_cast<AllocaInst>(Val))
860     return true;
861   Argument *A = dyn_cast<Argument>(Val);
862   if (!A)
863     return false;
864   return A->hasNoAliasAttr();
865 }
866
867 } // namespace
868
869 char LoopVectorize::ID = 0;
870 static const char lv_name[] = "Loop Vectorization";
871 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
872 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
873 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
874 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
875 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
876
877 namespace llvm {
878   Pass *createLoopVectorizePass() {
879     return new LoopVectorize();
880   }
881
882 }
883