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