Update the loop vectorizer docs.
[oota-llvm.git] / lib / Transforms / Vectorize / LoopVectorize.cpp
1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR. Legalization of the IR is done
12 // in the codegen. However, the vectorizes uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
14 //
15 // The loop vectorizer combines consecutive loop iteration into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
18 //
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A helper class that checks for the legality
22 //    of the vectorization.
23 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
24 //    widening of instructions.
25 //===----------------------------------------------------------------------===//
26 //
27 // The reduction-variable vectorization is based on the paper:
28 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
29 //
30 // Variable uniformity checks are inspired by:
31 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
32 //
33 // Other ideas/concepts are from:
34 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
35 //
36 //===----------------------------------------------------------------------===//
37 #define LV_NAME "loop-vectorize"
38 #define DEBUG_TYPE LV_NAME
39 #include "llvm/Constants.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/Instructions.h"
42 #include "llvm/LLVMContext.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Value.h"
46 #include "llvm/Function.h"
47 #include "llvm/Analysis/Verifier.h"
48 #include "llvm/Module.h"
49 #include "llvm/Type.h"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Analysis/AliasAnalysis.h"
53 #include "llvm/Analysis/AliasSetTracker.h"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Analysis/ScalarEvolution.h"
56 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
57 #include "llvm/Analysis/ScalarEvolutionExpander.h"
58 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
59 #include "llvm/Analysis/ValueTracking.h"
60 #include "llvm/Analysis/LoopInfo.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/DataLayout.h"
65 #include "llvm/Transforms/Utils/Local.h"
66 #include <algorithm>
67 using namespace llvm;
68
69 static cl::opt<unsigned>
70 DefaultVectorizationFactor("default-loop-vectorize-width",
71                           cl::init(4), cl::Hidden,
72                           cl::desc("Set the default loop vectorization width"));
73 namespace {
74
75 // Forward declaration.
76 class LoopVectorizationLegality;
77
78 /// SingleBlockLoopVectorizer vectorizes loops which contain only one basic
79 /// block to a specified vectorization factor (VF).
80 /// This class performs the widening of scalars into vectors, or multiple
81 /// scalars. This class also implements the following features:
82 /// * It inserts an epilogue loop for handling loops that don't have iteration
83 ///   counts that are known to be a multiple of the vectorization factor.
84 /// * It handles the code generation for reduction variables.
85 /// * Scalarization (implementation using scalars) of un-vectorizable
86 ///   instructions.
87 /// SingleBlockLoopVectorizer does not perform any vectorization-legality
88 /// checks, and relies on the caller to check for the different legality
89 /// aspects. The SingleBlockLoopVectorizer relies on the
90 /// LoopVectorizationLegality class to provide information about the induction
91 /// and reduction variables that were found to a given vectorization factor.
92 class SingleBlockLoopVectorizer {
93 public:
94   /// Ctor.
95   SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
96                             LPPassManager *Lpm, unsigned VecWidth):
97   Orig(OrigLoop), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
98   Builder(Se->getContext()), Induction(0), OldInduction(0) { }
99
100   // Perform the actual loop widening (vectorization).
101   void vectorize(LoopVectorizationLegality *Legal) {
102     ///Create a new empty loop. Unlink the old loop and connect the new one.
103     createEmptyLoop(Legal);
104     /// Widen each instruction in the old loop to a new one in the new loop.
105     /// Use the Legality module to find the induction and reduction variables.
106    vectorizeLoop(Legal);
107     // register the new loop.
108     cleanup();
109  }
110
111 private:
112   /// Create an empty loop, based on the loop ranges of the old loop.
113   void createEmptyLoop(LoopVectorizationLegality *Legal);
114   /// Copy and widen the instructions from the old loop.
115   void vectorizeLoop(LoopVectorizationLegality *Legal);
116   /// Insert the new loop to the loop hierarchy and pass manager.
117   void cleanup();
118
119   /// This instruction is un-vectorizable. Implement it as a sequence
120   /// of scalars.
121   void scalarizeInstruction(Instruction *Instr);
122
123   /// Create a broadcast instruction. This method generates a broadcast
124   /// instruction (shuffle) for loop invariant values and for the induction
125   /// value. If this is the induction variable then we extend it to N, N+1, ...
126   /// this is needed because each iteration in the loop corresponds to a SIMD
127   /// element.
128   Value *getBroadcastInstrs(Value *V);
129
130   /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
131   /// for each element in the vector. Starting from zero.
132   Value *getConsecutiveVector(Value* Val);
133
134   /// When we go over instructions in the basic block we rely on previous
135   /// values within the current basic block or on loop invariant values.
136   /// When we widen (vectorize) values we place them in the map. If the values
137   /// are not within the map, they have to be loop invariant, so we simply
138   /// broadcast them into a vector.
139   Value *getVectorValue(Value *V);
140
141   /// Get a uniform vector of constant integers. We use this to get
142   /// vectors of ones and zeros for the reduction code.
143   Constant* getUniformVector(unsigned Val, Type* ScalarTy);
144
145   typedef DenseMap<Value*, Value*> ValueMap;
146
147   /// The original loop.
148   Loop *Orig;
149   // Scev analysis to use.
150   ScalarEvolution *SE;
151   // Loop Info.
152   LoopInfo *LI;
153   // Loop Pass Manager;
154   LPPassManager *LPM;
155   // The vectorization factor to use.
156   unsigned VF;
157
158   // The builder that we use
159   IRBuilder<> Builder;
160
161   // --- Vectorization state ---
162
163   /// Middle Block between the vector and the scalar.
164   BasicBlock *LoopMiddleBlock;
165   ///The ExitBlock of the scalar loop.
166   BasicBlock *LoopExitBlock;
167   ///The vector loop body.
168   BasicBlock *LoopVectorBody;
169   ///The scalar loop body.
170   BasicBlock *LoopScalarBody;
171   ///The first bypass block.
172   BasicBlock *LoopBypassBlock;
173
174   /// The new Induction variable which was added to the new block.
175   PHINode *Induction;
176   /// The induction variable of the old basic block.
177   PHINode *OldInduction;
178   // Maps scalars to widened vectors.
179   ValueMap WidenMap;
180 };
181
182 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
183 /// to what vectorization factor.
184 /// This class does not look at the profitability of vectorization, only the
185 /// legality. This class has two main kinds of checks:
186 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
187 ///   will change the order of memory accesses in a way that will change the
188 ///   correctness of the program.
189 /// * Scalars checks - The code in canVectorizeBlock checks for a number
190 ///   of different conditions, such as the availability of a single induction
191 ///   variable, that all types are supported and vectorize-able, etc.
192 /// This code reflects the capabilities of SingleBlockLoopVectorizer.
193 /// This class is also used by SingleBlockLoopVectorizer for identifying
194 /// induction variable and the different reduction variables.
195 class LoopVectorizationLegality {
196 public:
197   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
198   TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
199
200   /// This represents the kinds of reductions that we support.
201   /// We use the enum values to hold the 'identity' value for
202   /// each operand. This value does not change the result if applied.
203   enum ReductionKind {
204     NoReduction = -1, /// Not a reduction.
205     IntegerAdd  = 0,  /// Sum of numbers.
206     IntegerMult = 1  /// Product of numbers.
207   };
208
209   /// This POD struct holds information about reduction variables.
210   struct ReductionDescriptor {
211     // Default C'tor
212     ReductionDescriptor():
213     StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
214
215     // C'tor.
216     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
217     StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
218
219     // The starting value of the reduction.
220     // It does not have to be zero!
221     Value *StartValue;
222     // The instruction who's value is used outside the loop.
223     Instruction *LoopExitInstr;
224     // The kind of the reduction.
225     ReductionKind Kind;
226   };
227
228   /// ReductionList contains the reduction descriptors for all
229   /// of the reductions that were found in the loop.
230   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
231
232   /// Returns the maximum vectorization factor that we *can* use to vectorize
233   /// this loop. This does not mean that it is profitable to vectorize this
234   /// loop, only that it is legal to do so. This may be a large number. We
235   /// can vectorize to any SIMD width below this number.
236   unsigned getLoopMaxVF();
237
238   /// Returns the Induction variable.
239   PHINode *getInduction() {return Induction;}
240
241   /// Returns the reduction variables found in the loop.
242   ReductionList *getReductionVars() { return &Reductions; }
243
244   /// Check if the pointer returned by this GEP is consecutive
245   /// when the index is vectorized. This happens when the last
246   /// index of the GEP is consecutive, like the induction variable.
247   /// This check allows us to vectorize A[idx] into a wide load/store.
248   bool isConsecutiveGep(Value *Ptr);
249
250 private:
251   /// Check if a single basic block loop is vectorizable.
252   /// At this point we know that this is a loop with a constant trip count
253   /// and we only need to check individual instructions.
254   bool canVectorizeBlock(BasicBlock &BB);
255
256   /// When we vectorize loops we may change the order in which
257   /// we read and write from memory. This method checks if it is
258   /// legal to vectorize the code, considering only memory constrains.
259   /// Returns true if BB is vectorizable
260   bool canVectorizeMemory(BasicBlock &BB);
261
262   // Check if a pointer value is known to be disjoint.
263   // Example: Alloca, Global, NoAlias.
264   bool isIdentifiedSafeObject(Value* Val);
265
266   /// Returns True, if 'Phi' is the kind of reduction variable for type
267   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
268   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
269   /// Returns true if the instruction I can be a reduction variable of type
270   /// 'Kind'.
271   bool isReductionInstr(Instruction *I, ReductionKind Kind);
272   /// Returns True, if 'Phi' is an induction variable.
273   bool isInductionVariable(PHINode *Phi);
274
275   /// The loop that we evaluate.
276   Loop *TheLoop;
277   /// Scev analysis.
278   ScalarEvolution *SE;
279   /// DataLayout analysis.
280   DataLayout *DL;
281
282   //  ---  vectorization state --- //
283
284   /// Holds the induction variable.
285   PHINode *Induction;
286   /// Holds the reduction variables.
287   ReductionList Reductions;
288   /// Allowed outside users. This holds the reduction
289   /// vars which can be accessed from outside the loop.
290   SmallPtrSet<Value*, 4> AllowedExit;
291 };
292
293 struct LoopVectorize : public LoopPass {
294   static char ID; // Pass identification, replacement for typeid
295
296   LoopVectorize() : LoopPass(ID) {
297     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
298   }
299
300   ScalarEvolution *SE;
301   DataLayout *DL;
302   LoopInfo *LI;
303
304   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
305     // We only vectorize innermost loops.
306     if (!L->empty())
307       return false;
308
309     SE = &getAnalysis<ScalarEvolution>();
310     DL = getAnalysisIfAvailable<DataLayout>();
311     LI = &getAnalysis<LoopInfo>();
312
313     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
314           L->getHeader()->getParent()->getName() << "\"\n");
315
316     // Check if it is legal to vectorize the loop.
317     LoopVectorizationLegality LVL(L, SE, DL);
318     unsigned MaxVF = LVL.getLoopMaxVF();
319
320     // Check that we can vectorize this loop using the chosen vectorization
321     // width.
322     if (MaxVF < DefaultVectorizationFactor) {
323       DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
324       return false;
325     }
326
327     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
328
329     // If we decided that it is *legal* to vectorizer the loop then do it.
330     SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, DefaultVectorizationFactor);
331     LB.vectorize(&LVL);
332
333     DEBUG(verifyFunction(*L->getHeader()->getParent()));
334     return true;
335   }
336
337   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
338     LoopPass::getAnalysisUsage(AU);
339     AU.addRequiredID(LoopSimplifyID);
340     AU.addRequiredID(LCSSAID);
341     AU.addRequired<LoopInfo>();
342     AU.addRequired<ScalarEvolution>();
343   }
344
345 };
346
347 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
348   // Instructions that access the old induction variable
349   // actually want to get the new one.
350   if (V == OldInduction)
351     V = Induction;
352   // Create the types.
353   LLVMContext &C = V->getContext();
354   Type *VTy = VectorType::get(V->getType(), VF);
355   Type *I32 = IntegerType::getInt32Ty(C);
356   Constant *Zero = ConstantInt::get(I32, 0);
357   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
358   Value *UndefVal = UndefValue::get(VTy);
359   // Insert the value into a new vector.
360   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
361   // Broadcast the scalar into all locations in the vector.
362   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
363                                              "broadcast");
364   // We are accessing the induction variable. Make sure to promote the
365   // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
366   if (V == Induction)
367     return getConsecutiveVector(Shuf);
368   return Shuf;
369 }
370
371 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
372   assert(Val->getType()->isVectorTy() && "Must be a vector");
373   assert(Val->getType()->getScalarType()->isIntegerTy() &&
374          "Elem must be an integer");
375   // Create the types.
376   Type *ITy = Val->getType()->getScalarType();
377   VectorType *Ty = cast<VectorType>(Val->getType());
378   unsigned VLen = Ty->getNumElements();
379   SmallVector<Constant*, 8> Indices;
380
381   // Create a vector of consecutive numbers from zero to VF.
382   for (unsigned i = 0; i < VLen; ++i)
383     Indices.push_back(ConstantInt::get(ITy, i));
384
385   // Add the consecutive indices to the vector value.
386   Constant *Cv = ConstantVector::get(Indices);
387   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
388   return Builder.CreateAdd(Val, Cv, "induction");
389 }
390
391 bool LoopVectorizationLegality::isConsecutiveGep(Value *Ptr) {
392   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
393   if (!Gep)
394     return false;
395
396   unsigned NumOperands = Gep->getNumOperands();
397   Value *LastIndex = Gep->getOperand(NumOperands - 1);
398
399   // Check that all of the gep indices are uniform except for the last.
400   for (unsigned i = 0; i < NumOperands - 1; ++i)
401     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
402       return false;
403
404   // We can emit wide load/stores only of the last index is the induction
405   // variable.
406   const SCEV *Last = SE->getSCEV(LastIndex);
407   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
408     const SCEV *Step = AR->getStepRecurrence(*SE);
409
410     // The memory is consecutive because the last index is consecutive
411     // and all other indices are loop invariant.
412     if (Step->isOne())
413       return true;
414   }
415
416   return false;
417 }
418
419 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
420   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
421   // If we saved a vectorized copy of V, use it.
422   Value *&MapEntry = WidenMap[V];
423   if (MapEntry)
424     return MapEntry;
425
426   // Broadcast V and save the value for future uses.
427   Value *B = getBroadcastInstrs(V);
428   MapEntry = B;
429   return B;
430 }
431
432 Constant*
433 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
434   SmallVector<Constant*, 8> Indices;
435   // Create a vector of consecutive numbers from zero to VF.
436   for (unsigned i = 0; i < VF; ++i)
437     Indices.push_back(ConstantInt::get(ScalarTy, Val));
438
439   // Add the consecutive indices to the vector value.
440   return ConstantVector::get(Indices);
441 }
442
443 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
444   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
445   // Holds vector parameters or scalars, in case of uniform vals.
446   SmallVector<Value*, 8> Params;
447
448   // Find all of the vectorized parameters.
449   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
450     Value *SrcOp = Instr->getOperand(op);
451
452     // If we are accessing the old induction variable, use the new one.
453     if (SrcOp == OldInduction) {
454       Params.push_back(getBroadcastInstrs(Induction));
455       continue;
456     }
457
458     // Try using previously calculated values.
459     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
460
461     // If the src is an instruction that appeared earlier in the basic block
462     // then it should already be vectorized.
463     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
464       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
465       // The parameter is a vector value from earlier.
466       Params.push_back(WidenMap[SrcInst]);
467     } else {
468       // The parameter is a scalar from outside the loop. Maybe even a constant.
469       Params.push_back(SrcOp);
470     }
471   }
472
473   assert(Params.size() == Instr->getNumOperands() &&
474          "Invalid number of operands");
475
476   // Does this instruction return a value ?
477   bool IsVoidRetTy = Instr->getType()->isVoidTy();
478   Value *VecResults = 0;
479
480   // If we have a return value, create an empty vector. We place the scalarized
481   // instructions in this vector.
482   if (!IsVoidRetTy)
483     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
484
485   // For each scalar that we create:
486   for (unsigned i = 0; i < VF; ++i) {
487     Instruction *Cloned = Instr->clone();
488     if (!IsVoidRetTy)
489       Cloned->setName(Instr->getName() + ".cloned");
490     // Replace the operands of the cloned instrucions with extracted scalars.
491     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
492       Value *Op = Params[op];
493       // Param is a vector. Need to extract the right lane.
494       if (Op->getType()->isVectorTy())
495         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
496       Cloned->setOperand(op, Op);
497     }
498
499     // Place the cloned scalar in the new loop.
500     Builder.Insert(Cloned);
501
502     // If the original scalar returns a value we need to place it in a vector
503     // so that future users will be able to use it.
504     if (!IsVoidRetTy)
505       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
506                                                Builder.getInt32(i));
507   }
508
509   if (!IsVoidRetTy)
510     WidenMap[Instr] = VecResults;
511 }
512
513 void SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
514   /*
515    In this function we generate a new loop. The new loop will contain
516    the vectorized instructions while the old loop will continue to run the
517    scalar remainder.
518
519     [ ] <-- vector loop bypass.
520   /  |
521  /   v
522 |   [ ]     <-- vector pre header.
523 |    |
524 |    v
525 |   [  ] \
526 |   [  ]_|   <-- vector loop.
527 |    |
528  \   v
529    >[ ]   <--- middle-block.
530   /  |
531  /   v
532 |   [ ]     <--- new preheader.
533 |    |
534 |    v
535 |   [ ] \
536 |   [ ]_|   <-- old scalar loop to handle remainder.
537  \   |
538   \  v
539    >[ ]     <-- exit block.
540    ...
541    */
542
543   // This is the original scalar-loop preheader.
544   BasicBlock *BypassBlock = Orig->getLoopPreheader();
545   BasicBlock *ExitBlock = Orig->getExitBlock();
546   assert(ExitBlock && "Must have an exit block");
547
548   assert(Orig->getNumBlocks() == 1 && "Invalid loop");
549   assert(BypassBlock && "Invalid loop structure");
550
551   BasicBlock *VectorPH =
552       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
553   BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
554                                                  "vector.body");
555
556   BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
557                                                   "middle.block");
558   BasicBlock *ScalarPH =
559     MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
560                                  "scalar.preheader");
561   // Find the induction variable.
562   BasicBlock *OldBasicBlock = Orig->getHeader();
563   OldInduction = Legal->getInduction();
564   assert(OldInduction && "We must have a single phi node.");
565   Type *IdxTy = OldInduction->getType();
566
567   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
568   // inside the loop.
569   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
570
571   // Generate the induction variable.
572   Induction = Builder.CreatePHI(IdxTy, 2, "index");
573   Constant *Zero = ConstantInt::get(IdxTy, 0);
574   Constant *Step = ConstantInt::get(IdxTy, VF);
575
576   // Find the loop boundaries.
577   const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
578   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
579
580   // Get the total trip count from the count by adding 1.
581   ExitCount = SE->getAddExpr(ExitCount,
582                              SE->getConstant(ExitCount->getType(), 1));
583
584   // Expand the trip count and place the new instructions in the preheader.
585   // Notice that the pre-header does not change, only the loop body.
586   SCEVExpander Exp(*SE, "induction");
587   Instruction *Loc = BypassBlock->getTerminator();
588
589   // We may need to extend the index in case there is a type mismatch.
590   // We know that the count starts at zero and does not overflow.
591   // We are using Zext because it should be less expensive.
592   if (ExitCount->getType() != Induction->getType())
593     ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
594
595   // Count holds the overall loop count (N).
596   Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
597   // Now we need to generate the expression for N - (N % VF), which is
598   // the part that the vectorized body will execute.
599   Constant *CIVF = ConstantInt::get(IdxTy, VF);
600   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
601   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
602
603   // Now, compare the new count to zero. If it is zero, jump to the scalar part.
604   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
605                                CountRoundDown, ConstantInt::getNullValue(IdxTy),
606                                "cmp.zero", Loc);
607   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
608   // Remove the old terminator.
609   Loc->eraseFromParent();
610
611   // Add a check in the middle block to see if we have completed
612   // all of the iterations in the first vector loop.
613   // If (N - N%VF) == N, then we *don't* need to run the remainder.
614   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
615                                 CountRoundDown, "cmp.n",
616                                 MiddleBlock->getTerminator());
617
618   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
619   // Remove the old terminator.
620   MiddleBlock->getTerminator()->eraseFromParent();
621
622   // Create i+1 and fill the PHINode.
623   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
624   Induction->addIncoming(Zero, VectorPH);
625   Induction->addIncoming(NextIdx, VecBody);
626   // Create the compare.
627   Value *ICmp = Builder.CreateICmpEQ(NextIdx, CountRoundDown);
628   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
629
630   // Now we have two terminators. Remove the old one from the block.
631   VecBody->getTerminator()->eraseFromParent();
632
633   // Fix the scalar body iteration count.
634   unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
635   OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
636
637   // Get ready to start creating new instructions into the vectorized body.
638   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
639
640   // Register the new loop.
641   Loop* Lp = new Loop();
642   LPM->insertLoop(Lp, Orig->getParentLoop());
643
644   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
645
646   Loop *ParentLoop = Orig->getParentLoop();
647   if (ParentLoop) {
648     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
649     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
650     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
651   }
652
653   // Save the state.
654   LoopMiddleBlock = MiddleBlock;
655   LoopExitBlock = ExitBlock;
656   LoopVectorBody = VecBody;
657   LoopScalarBody = OldBasicBlock;
658   LoopBypassBlock = BypassBlock;
659 }
660
661 void
662 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
663   typedef SmallVector<PHINode*, 4> PhiVector;
664   BasicBlock &BB = *Orig->getHeader();
665   Constant *Zero = ConstantInt::get(
666     IntegerType::getInt32Ty(BB.getContext()), 0);
667
668   // In order to support reduction variables we need to be able to vectorize
669   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
670   // steages. First, we create a new vector PHI node with no incoming edges.
671   // We use this value when we vectorize all of the instructions that use the
672   // PHI. Next, after all of the instructions in the block are complete we
673   // add the new incoming edges to the PHI. At this point all of the
674   // instructions in the basic block are vectorized, so we can use them to
675   // construct the PHI.
676   PhiVector PHIsToFix;
677
678   // For each instruction in the old loop.
679   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
680     Instruction *Inst = it;
681
682     switch (Inst->getOpcode()) {
683       case Instruction::Br:
684         // Nothing to do for PHIs and BR, since we already took care of the
685         // loop control flow instructions.
686         continue;
687       case Instruction::PHI:{
688         PHINode* P = cast<PHINode>(Inst);
689         // Special handling for the induction var.
690         if (OldInduction == Inst)
691           continue;
692         // This is phase one of vectorizing PHIs.
693         // This has to be a reduction variable.
694         assert(Legal->getReductionVars()->count(P) && "Not a Reduction");
695         Type *VecTy = VectorType::get(Inst->getType(), VF);
696         WidenMap[Inst] = Builder.CreatePHI(VecTy, 2, "vec.phi");
697         PHIsToFix.push_back(P);
698         continue;
699       }
700       case Instruction::Add:
701       case Instruction::FAdd:
702       case Instruction::Sub:
703       case Instruction::FSub:
704       case Instruction::Mul:
705       case Instruction::FMul:
706       case Instruction::UDiv:
707       case Instruction::SDiv:
708       case Instruction::FDiv:
709       case Instruction::URem:
710       case Instruction::SRem:
711       case Instruction::FRem:
712       case Instruction::Shl:
713       case Instruction::LShr:
714       case Instruction::AShr:
715       case Instruction::And:
716       case Instruction::Or:
717       case Instruction::Xor: {
718         // Just widen binops.
719         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
720         Value *A = getVectorValue(Inst->getOperand(0));
721         Value *B = getVectorValue(Inst->getOperand(1));
722         // Use this vector value for all users of the original instruction.
723         WidenMap[Inst] = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
724         break;
725       }
726       case Instruction::Select: {
727         // Widen selects.
728         // TODO: If the selector is loop invariant we can issue a select
729         // instruction with a scalar condition.
730         Value *A = getVectorValue(Inst->getOperand(0));
731         Value *B = getVectorValue(Inst->getOperand(1));
732         Value *C = getVectorValue(Inst->getOperand(2));
733         WidenMap[Inst] = Builder.CreateSelect(A, B, C);
734         break;
735       }
736
737       case Instruction::ICmp:
738       case Instruction::FCmp: {
739         // Widen compares. Generate vector compares.
740         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
741         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
742         Value *A = getVectorValue(Inst->getOperand(0));
743         Value *B = getVectorValue(Inst->getOperand(1));
744         if (FCmp)
745           WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
746         else
747           WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
748         break;
749       }
750
751       case Instruction::Store: {
752         // Attempt to issue a wide store.
753         StoreInst *SI = dyn_cast<StoreInst>(Inst);
754         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
755         Value *Ptr = SI->getPointerOperand();
756         unsigned Alignment = SI->getAlignment();
757         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
758         // This store does not use GEPs.
759         if (!Legal->isConsecutiveGep(Gep)) {
760           scalarizeInstruction(Inst);
761           break;
762         }
763
764         // The last index does not have to be the induction. It can be
765         // consecutive and be a function of the index. For example A[I+1];
766         unsigned NumOperands = Gep->getNumOperands();
767         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
768         LastIndex = Builder.CreateExtractElement(LastIndex, Builder.getInt32(0));
769
770         // Create the new GEP with the new induction variable.
771         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
772         Gep2->setOperand(NumOperands - 1, LastIndex);
773         Ptr = Builder.Insert(Gep2);
774         Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
775         Value *Val = getVectorValue(SI->getValueOperand());
776         Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
777         break;
778       }
779       case Instruction::Load: {
780         // Attempt to issue a wide load.
781         LoadInst *LI = dyn_cast<LoadInst>(Inst);
782         Type *RetTy = VectorType::get(LI->getType(), VF);
783         Value *Ptr = LI->getPointerOperand();
784         unsigned Alignment = LI->getAlignment();
785         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
786
787         // We don't have a gep. Scalarize the load.
788         if (!Legal->isConsecutiveGep(Gep)) {
789           scalarizeInstruction(Inst);
790           break;
791         }
792
793         // The last index does not have to be the induction. It can be
794         // consecutive and be a function of the index. For example A[I+1];
795         unsigned NumOperands = Gep->getNumOperands();
796         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
797         LastIndex = Builder.CreateExtractElement(LastIndex, Builder.getInt32(0));
798
799         // Create the new GEP with the new induction variable.
800         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
801         Gep2->setOperand(NumOperands - 1, LastIndex);
802         Ptr = Builder.Insert(Gep2);
803         Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
804         LI = Builder.CreateLoad(Ptr);
805         LI->setAlignment(Alignment);
806         // Use this vector value for all users of the load.
807         WidenMap[Inst] = LI;
808         break;
809       }
810       case Instruction::ZExt:
811       case Instruction::SExt:
812       case Instruction::FPToUI:
813       case Instruction::FPToSI:
814       case Instruction::FPExt:
815       case Instruction::PtrToInt:
816       case Instruction::IntToPtr:
817       case Instruction::SIToFP:
818       case Instruction::UIToFP:
819       case Instruction::Trunc:
820       case Instruction::FPTrunc:
821       case Instruction::BitCast: {
822         /// Vectorize bitcasts.
823         CastInst *CI = dyn_cast<CastInst>(Inst);
824         Value *A = getVectorValue(Inst->getOperand(0));
825         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
826         WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
827         break;
828       }
829
830       default:
831         /// All other instructions are unsupported. Scalarize them.
832         scalarizeInstruction(Inst);
833         break;
834     }// end of switch.
835   }// end of for_each instr.
836
837   // At this point every instruction in the original loop is widended to
838   // a vector form. We are almost done. Now, we need to fix the PHI nodes
839   // that we vectorized. The PHI nodes are currently empty because we did
840   // not want to introduce cycles. Notice that the remaining PHI nodes
841   // that we need to fix are reduction variables.
842
843   // Create the 'reduced' values for each of the induction vars.
844   // The reduced values are the vector values that we scalarize and combine
845   // after the loop is finished.
846   for (PhiVector::iterator it = PHIsToFix.begin(), e = PHIsToFix.end();
847        it != e; ++it) {
848     PHINode *RdxPhi = *it;
849     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
850     assert(RdxPhi && "Unable to recover vectorized PHI");
851
852     // Find the reduction variable descriptor.
853     assert(Legal->getReductionVars()->count(RdxPhi) &&
854            "Unable to find the reduction variable");
855     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
856       (*Legal->getReductionVars())[RdxPhi];
857
858     // We need to generate a reduction vector from the incoming scalar.
859     // To do so, we need to generate the 'identity' vector and overide
860     // one of the elements with the incoming scalar reduction. We need
861     // to do it in the vector-loop preheader.
862     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
863
864     // This is the vector-clone of the value that leaves the loop.
865     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
866     Type *VecTy = VectorExit->getType();
867
868     // Find the reduction identity variable. The value of the enum is the
869     // identity. Zero for addition. One for Multiplication.
870     unsigned IdentitySclr =  RdxDesc.Kind;
871     Constant *Identity = getUniformVector(IdentitySclr,
872                                           VecTy->getScalarType());
873
874     // This vector is the Identity vector where the first element is the
875     // incoming scalar reduction.
876     Value *VectorStart = Builder.CreateInsertElement(Identity,
877                                                     RdxDesc.StartValue, Zero);
878
879
880     // Fix the vector-loop phi.
881     // We created the induction variable so we know that the
882     // preheader is the first entry.
883     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
884
885     // Reductions do not have to start at zero. They can start with
886     // any loop invariant values.
887     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
888     unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
889     Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
890     VecRdxPhi->addIncoming(Val, LoopVectorBody);
891
892     // Before each round, move the insertion point right between
893     // the PHIs and the values we are going to write.
894     // This allows us to write both PHINodes and the extractelement
895     // instructions.
896     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
897
898     // This PHINode contains the vectorized reduction variable, or
899     // the initial value vector, if we bypass the vector loop.
900     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
901     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
902     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
903
904     // Extract the first scalar.
905     Value *Scalar0 =
906       Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
907     // Extract and sum the remaining vector elements.
908     for (unsigned i=1; i < VF; ++i) {
909       Value *Scalar1 =
910         Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
911       if (RdxDesc.Kind == LoopVectorizationLegality::IntegerAdd) {
912         Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
913       } else {
914         Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
915       }
916     }
917
918     // Now, we need to fix the users of the reduction variable
919     // inside and outside of the scalar remainder loop.
920     // We know that the loop is in LCSSA form. We need to update the
921     // PHI nodes in the exit blocks.
922     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
923          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
924       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
925       if (!LCSSAPhi) continue;
926
927       // All PHINodes need to have a single entry edge, or two if
928       // we already fixed them.
929       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
930
931       // We found our reduction value exit-PHI. Update it with the
932       // incoming bypass edge.
933       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
934         // Add an edge coming from the bypass.
935         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
936         break;
937       }
938     }// end of the LCSSA phi scan.
939
940     // Fix the scalar loop reduction variable with the incoming reduction sum
941     // from the vector body and from the backedge value.
942     int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
943     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
944     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
945     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
946   }// end of for each redux variable.
947 }
948
949 void SingleBlockLoopVectorizer::cleanup() {
950   // The original basic block.
951   SE->forgetLoop(Orig);
952 }
953
954 unsigned LoopVectorizationLegality::getLoopMaxVF() {
955   if (!TheLoop->getLoopPreheader()) {
956     assert(false && "No preheader!!");
957     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
958     return  1;
959   }
960
961   // We can only vectorize single basic block loops.
962   unsigned NumBlocks = TheLoop->getNumBlocks();
963   if (NumBlocks != 1) {
964     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
965     return 1;
966   }
967
968   // We need to have a loop header.
969   BasicBlock *BB = TheLoop->getHeader();
970   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
971
972   // Go over each instruction and look at memory deps.
973   if (!canVectorizeBlock(*BB)) {
974     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
975     return 1;
976   }
977
978   // ScalarEvolution needs to be able to find the exit count.
979   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
980   if (ExitCount == SE->getCouldNotCompute()) {
981     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
982     return 1;
983   }
984
985   DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
986
987   // Okay! We can vectorize. At this point we don't have any other mem analysis
988   // which may limit our maximum vectorization factor, so just return the
989   // maximum SIMD size.
990   return DefaultVectorizationFactor;
991 }
992
993 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
994   // Scan the instructions in the block and look for hazards.
995   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
996     Instruction *I = it;
997
998     PHINode *Phi = dyn_cast<PHINode>(I);
999     if (Phi) {
1000       // This should not happen because the loop should be normalized.
1001       if (Phi->getNumIncomingValues() != 2) {
1002         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1003         return false;
1004       }
1005       // We only look at integer phi nodes.
1006       if (!Phi->getType()->isIntegerTy()) {
1007         DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
1008         return false;
1009       }
1010
1011       if (isInductionVariable(Phi)) {
1012         if (Induction) {
1013           DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1014           return false;
1015         }
1016         DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1017         Induction = Phi;
1018         continue;
1019       }
1020       if (AddReductionVar(Phi, IntegerAdd)) {
1021         DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1022         continue;
1023       }
1024       if (AddReductionVar(Phi, IntegerMult)) {
1025         DEBUG(dbgs() << "LV: Found an Mult reduction PHI."<< *Phi <<"\n");
1026         continue;
1027       }
1028
1029       DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1030       return false;
1031     }// end of PHI handling
1032
1033     // We still don't handle functions.
1034     CallInst *CI = dyn_cast<CallInst>(I);
1035     if (CI) {
1036       DEBUG(dbgs() << "LV: Found a call site:"<<
1037             CI->getCalledFunction()->getName() << "\n");
1038       return false;
1039     }
1040
1041     // We do not re-vectorize vectors.
1042     if (!VectorType::isValidElementType(I->getType()) &&
1043         !I->getType()->isVoidTy()) {
1044       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1045       return false;
1046     }
1047
1048     // Reduction instructions are allowed to have exit users.
1049     // All other instructions must not have external users.
1050     if (!AllowedExit.count(I))
1051       //Check that all of the users of the loop are inside the BB.
1052       for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1053            it != e; ++it) {
1054         Instruction *U = cast<Instruction>(*it);
1055         // This user may be a reduction exit value.
1056         BasicBlock *Parent = U->getParent();
1057         if (Parent != &BB) {
1058           DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1059           return false;
1060         }
1061     }
1062   } // next instr.
1063
1064   if (!Induction) {
1065       DEBUG(dbgs() << "LV: Did not find an induction var.\n");
1066       return false;
1067   }
1068
1069   // If the memory dependencies do not prevent us from
1070   // vectorizing, then vectorize.
1071   return canVectorizeMemory(BB);
1072 }
1073
1074 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1075   typedef SmallVector<Value*, 16> ValueVector;
1076   typedef SmallPtrSet<Value*, 16> ValueSet;
1077   // Holds the Load and Store *instructions*.
1078   ValueVector Loads;
1079   ValueVector Stores;
1080
1081   // Scan the BB and collect legal loads and stores.
1082   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1083     Instruction *I = it;
1084
1085     // If this is a load, save it. If this instruction can read from memory
1086     // but is not a load, then we quit. Notice that we don't handle function
1087     // calls that read or write.
1088     if (I->mayReadFromMemory()) {
1089       LoadInst *Ld = dyn_cast<LoadInst>(I);
1090       if (!Ld) return false;
1091       if (!Ld->isSimple()) {
1092         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1093         return false;
1094       }
1095       Loads.push_back(Ld);
1096       continue;
1097     }
1098
1099     // Save store instructions. Abort if other instructions write to memory.
1100     if (I->mayWriteToMemory()) {
1101       StoreInst *St = dyn_cast<StoreInst>(I);
1102       if (!St) return false;
1103       if (!St->isSimple()) {
1104         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1105         return false;
1106       }
1107       Stores.push_back(St);
1108     }
1109   } // next instr.
1110
1111   // Now we have two lists that hold the loads and the stores.
1112   // Next, we find the pointers that they use.
1113
1114   // Check if we see any stores. If there are no stores, then we don't
1115   // care if the pointers are *restrict*.
1116   if (!Stores.size()) {
1117         DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1118         return true;
1119   }
1120
1121   // Holds the read and read-write *pointers* that we find.
1122   ValueVector Reads;
1123   ValueVector ReadWrites;
1124
1125   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1126   // multiple times on the same object. If the ptr is accessed twice, once
1127   // for read and once for write, it will only appear once (on the write
1128   // list). This is okay, since we are going to check for conflicts between
1129   // writes and between reads and writes, but not between reads and reads.
1130   ValueSet Seen;
1131
1132   ValueVector::iterator I, IE;
1133   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1134     StoreInst *ST = dyn_cast<StoreInst>(*I);
1135     assert(ST && "Bad StoreInst");
1136     Value* Ptr = ST->getPointerOperand();
1137     // If we did *not* see this pointer before, insert it to
1138     // the read-write list. At this phase it is only a 'write' list.
1139     if (Seen.insert(Ptr))
1140       ReadWrites.push_back(Ptr);
1141   }
1142
1143   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1144     LoadInst *LD = dyn_cast<LoadInst>(*I);
1145     assert(LD && "Bad LoadInst");
1146     Value* Ptr = LD->getPointerOperand();
1147     // If we did *not* see this pointer before, insert it to the
1148     // read list. If we *did* see it before, then it is already in
1149     // the read-write list. This allows us to vectorize expressions
1150     // such as A[i] += x;  Because the address of A[i] is a read-write
1151     // pointer. This only works if the index of A[i] is consecutive.
1152     // If the address of i is unknown (for example A[B[i]]) then we may
1153     // read a few words, modify, and write a few words, and some of the
1154     // words may be written to the same address.
1155     if (Seen.insert(Ptr) || !isConsecutiveGep(Ptr))
1156       Reads.push_back(Ptr);
1157   }
1158
1159   // Now that the pointers are in two lists (Reads and ReadWrites), we
1160   // can check that there are no conflicts between each of the writes and
1161   // between the writes to the reads.
1162   ValueSet WriteObjects;
1163   ValueVector TempObjects;
1164
1165   // Check that the read-writes do not conflict with other read-write
1166   // pointers.
1167   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1168     GetUnderlyingObjects(*I, TempObjects, DL);
1169     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1170          it != e; ++it) {
1171       if (!isIdentifiedSafeObject(*it)) {
1172         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1173         return false;
1174       }
1175       if (!WriteObjects.insert(*it)) {
1176         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1177               << **it <<"\n");
1178         return false;
1179       }
1180     }
1181     TempObjects.clear();
1182   }
1183
1184   /// Check that the reads don't conflict with the read-writes.
1185   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1186     GetUnderlyingObjects(*I, TempObjects, DL);
1187     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1188          it != e; ++it) {
1189       if (!isIdentifiedSafeObject(*it)) {
1190         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1191         return false;
1192       }
1193       if (WriteObjects.count(*it)) {
1194         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1195               << **it <<"\n");
1196         return false;
1197       }
1198     }
1199     TempObjects.clear();
1200   }
1201
1202   // All is okay.
1203   return true;
1204 }
1205
1206 /// Checks if the value is a Global variable or if it is an Arguments
1207 /// marked with the NoAlias attribute.
1208 bool LoopVectorizationLegality::isIdentifiedSafeObject(Value* Val) {
1209   assert(Val && "Invalid value");
1210   if (isa<GlobalValue>(Val))
1211     return true;
1212   if (isa<AllocaInst>(Val))
1213     return true;
1214   if (Argument *A = dyn_cast<Argument>(Val))
1215     return A->hasNoAliasAttr();
1216   return false;
1217 }
1218
1219 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1220                                                 ReductionKind Kind) {
1221   if (Phi->getNumIncomingValues() != 2)
1222     return false;
1223
1224   // Find the possible incoming reduction variable.
1225   BasicBlock *BB = Phi->getParent();
1226   int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1227   int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1228   Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1229
1230   // ExitInstruction is the single value which is used outside the loop.
1231   // We only allow for a single reduction value to be used outside the loop.
1232   // This includes users of the reduction, variables (which form a cycle
1233   // which ends in the phi node).
1234   Instruction *ExitInstruction = 0;
1235
1236   // Iter is our iterator. We start with the PHI node and scan for all of the
1237   // users of this instruction. All users must be instructions which can be
1238   // used as reduction variables (such as ADD). We may have a single
1239   // out-of-block user. They cycle must end with the original PHI.
1240   // Also, we can't have multiple block-local users.
1241   Instruction *Iter = Phi;
1242   while (true) {
1243     // Any reduction instr must be of one of the allowed kinds.
1244     if (!isReductionInstr(Iter, Kind))
1245       return false;
1246
1247     // Did we found a user inside this block ?
1248     bool FoundInBlockUser = false;
1249     // Did we reach the initial PHI node ?
1250     bool FoundStartPHI = false;
1251
1252     // If the instruction has no users then this is a broken
1253     // chain and can't be a reduction variable.
1254     if (Iter->use_empty())
1255       return false;
1256
1257     // For each of the *users* of iter.
1258     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1259          it != e; ++it) {
1260       Instruction *U = cast<Instruction>(*it);
1261       // We already know that the PHI is a user.
1262       if (U == Phi) {
1263         FoundStartPHI = true;
1264         continue;
1265       }
1266       // Check if we found the exit user.
1267       BasicBlock *Parent = U->getParent();
1268       if (Parent != BB) {
1269         // We must have a single exit instruction.
1270         if (ExitInstruction != 0)
1271           return false;
1272         ExitInstruction = Iter;
1273       }
1274       // We can't have multiple inside users.
1275       if (FoundInBlockUser)
1276         return false;
1277       FoundInBlockUser = true;
1278       Iter = U;
1279     }
1280
1281     // We found a reduction var if we have reached the original
1282     // phi node and we only have a single instruction with out-of-loop
1283     // users.
1284    if (FoundStartPHI && ExitInstruction) {
1285      // This instruction is allowed to have out-of-loop users.
1286      AllowedExit.insert(ExitInstruction);
1287
1288      // Save the description of this reduction variable.
1289      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1290      Reductions[Phi] = RD;
1291      return true;
1292    }
1293   }
1294 }
1295
1296 bool
1297 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1298                                             ReductionKind Kind) {
1299     switch (I->getOpcode()) {
1300     default:
1301       return false;
1302     case Instruction::PHI:
1303       // possibly.
1304       return true;
1305     case Instruction::Add:
1306     case Instruction::Sub:
1307       return Kind == IntegerAdd;
1308     case Instruction::Mul:
1309     case Instruction::UDiv:
1310     case Instruction::SDiv:
1311       return Kind == IntegerMult;
1312     }
1313 }
1314
1315 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1316   // Check that the PHI is consecutive and starts at zero.
1317   const SCEV *PhiScev = SE->getSCEV(Phi);
1318   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1319   if (!AR) {
1320     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1321     return false;
1322   }
1323   const SCEV *Step = AR->getStepRecurrence(*SE);
1324   const SCEV *Start = AR->getStart();
1325
1326   if (!Step->isOne() || !Start->isZero()) {
1327     DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
1328     return false;
1329   }
1330   return true;
1331 }
1332
1333 } // namespace
1334
1335 char LoopVectorize::ID = 0;
1336 static const char lv_name[] = "Loop Vectorization";
1337 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
1338 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1339 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1340 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1341 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
1342
1343 namespace llvm {
1344   Pass *createLoopVectorizePass() {
1345     return new LoopVectorize();
1346   }
1347 }
1348