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