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