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