Stylistic tweak.
[oota-llvm.git] / lib / Transforms / Vectorize / LoopVectorize.h
1 //===- LoopVectorize.h --- 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. InnerLoopVectorizer - 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 //
31 // The reduction-variable vectorization is based on the paper:
32 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33 //
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
36 //
37 // Other ideas/concepts are from:
38 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39 //
40 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
41 //  Vectorizing Compilers.
42 //
43 //===----------------------------------------------------------------------===//
44 #ifndef LLVM_TRANSFORM_VECTORIZE_LOOP_VECTORIZE_H
45 #define LLVM_TRANSFORM_VECTORIZE_LOOP_VECTORIZE_H
46
47 #define LV_NAME "loop-vectorize"
48 #define DEBUG_TYPE LV_NAME
49
50 #include "llvm/Analysis/ScalarEvolution.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/DenseMap.h"
53 #include "llvm/ADT/SmallPtrSet.h"
54 #include "llvm/IRBuilder.h" 
55
56 #include <algorithm>
57 using namespace llvm;
58
59 /// We don't vectorize loops with a known constant trip count below this number.
60 const unsigned TinyTripCountThreshold = 16;
61
62 /// When performing a runtime memory check, do not check more than this
63 /// number of pointers. Notice that the check is quadratic!
64 const unsigned RuntimeMemoryCheckThreshold = 4;
65
66 /// This is the highest vector width that we try to generate.
67 const unsigned MaxVectorSize = 8;
68
69 namespace llvm {
70
71 // Forward declarations.
72 class LoopVectorizationLegality;
73 class LoopVectorizationCostModel;
74 class VectorTargetTransformInfo;
75
76 /// InnerLoopVectorizer vectorizes loops which contain only one basic
77 /// block to a specified vectorization factor (VF).
78 /// This class performs the widening of scalars into vectors, or multiple
79 /// scalars. This class also implements the following features:
80 /// * It inserts an epilogue loop for handling loops that don't have iteration
81 ///   counts that are known to be a multiple of the vectorization factor.
82 /// * It handles the code generation for reduction variables.
83 /// * Scalarization (implementation using scalars) of un-vectorizable
84 ///   instructions.
85 /// InnerLoopVectorizer does not perform any vectorization-legality
86 /// checks, and relies on the caller to check for the different legality
87 /// aspects. The InnerLoopVectorizer relies on the
88 /// LoopVectorizationLegality class to provide information about the induction
89 /// and reduction variables that were found to a given vectorization factor.
90 class InnerLoopVectorizer {
91 public:
92   /// Ctor.
93   InnerLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
94                       DominatorTree *Dt, DataLayout *Dl, unsigned VecWidth):
95   OrigLoop(Orig), SE(Se), LI(Li), DT(Dt), DL(Dl), VF(VecWidth),
96   Builder(Se->getContext()), Induction(0), OldInduction(0) { }
97
98   // Perform the actual loop widening (vectorization).
99   void vectorize(LoopVectorizationLegality *Legal) {
100     // Create a new empty loop. Unlink the old loop and connect the new one.
101     createEmptyLoop(Legal);
102     // Widen each instruction in the old loop to a new one in the new loop.
103     // Use the Legality module to find the induction and reduction variables.
104     vectorizeLoop(Legal);
105     // Register the new loop and update the analysis passes.
106     updateAnalysis();
107   }
108
109 private:
110   /// A small list of PHINodes.
111   typedef SmallVector<PHINode*, 4> PhiVector;
112
113   /// Add code that checks at runtime if the accessed arrays overlap.
114   /// Returns the comparator value or NULL if no check is needed.
115   Value *addRuntimeCheck(LoopVectorizationLegality *Legal,
116                          Instruction *Loc);
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
122   /// A helper function that computes the predicate of the block BB, assuming
123   /// that the header block of the loop is set to True. It returns the *entry*
124   /// mask for the block BB.
125   Value *createBlockInMask(BasicBlock *BB);
126   /// A helper function that computes the predicate of the edge between SRC
127   /// and DST.
128   Value *createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
129
130   /// A helper function to vectorize a single BB within the innermost loop.
131   void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
132                             PhiVector *PV);
133
134   /// Insert the new loop to the loop hierarchy and pass manager
135   /// and update the analysis passes.
136   void updateAnalysis();
137
138   /// This instruction is un-vectorizable. Implement it as a sequence
139   /// of scalars.
140   void scalarizeInstruction(Instruction *Instr);
141
142   /// Create a broadcast instruction. This method generates a broadcast
143   /// instruction (shuffle) for loop invariant values and for the induction
144   /// value. If this is the induction variable then we extend it to N, N+1, ...
145   /// this is needed because each iteration in the loop corresponds to a SIMD
146   /// element.
147   Value *getBroadcastInstrs(Value *V);
148
149   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
150   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
151   Value *getConsecutiveVector(Value* Val, bool Negate = false);
152
153   /// When we go over instructions in the basic block we rely on previous
154   /// values within the current basic block or on loop invariant values.
155   /// When we widen (vectorize) values we place them in the map. If the values
156   /// are not within the map, they have to be loop invariant, so we simply
157   /// broadcast them into a vector.
158   Value *getVectorValue(Value *V);
159
160   /// Get a uniform vector of constant integers. We use this to get
161   /// vectors of ones and zeros for the reduction code.
162   Constant* getUniformVector(unsigned Val, Type* ScalarTy);
163
164   typedef DenseMap<Value*, Value*> ValueMap;
165
166   /// The original loop.
167   Loop *OrigLoop;
168   // Scev analysis to use.
169   ScalarEvolution *SE;
170   // Loop Info.
171   LoopInfo *LI;
172   // Dominator Tree.
173   DominatorTree *DT;
174   // Data Layout.
175   DataLayout *DL;
176   // The vectorization factor to use.
177   unsigned VF;
178
179   // The builder that we use
180   IRBuilder<> Builder;
181
182   // --- Vectorization state ---
183
184   /// The vector-loop preheader.
185   BasicBlock *LoopVectorPreHeader;
186   /// The scalar-loop preheader.
187   BasicBlock *LoopScalarPreHeader;
188   /// Middle Block between the vector and the scalar.
189   BasicBlock *LoopMiddleBlock;
190   ///The ExitBlock of the scalar loop.
191   BasicBlock *LoopExitBlock;
192   ///The vector loop body.
193   BasicBlock *LoopVectorBody;
194   ///The scalar loop body.
195   BasicBlock *LoopScalarBody;
196   ///The first bypass block.
197   BasicBlock *LoopBypassBlock;
198
199   /// The new Induction variable which was added to the new block.
200   PHINode *Induction;
201   /// The induction variable of the old basic block.
202   PHINode *OldInduction;
203   // Maps scalars to widened vectors.
204   ValueMap WidenMap;
205 };
206
207 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
208 /// to what vectorization factor.
209 /// This class does not look at the profitability of vectorization, only the
210 /// legality. This class has two main kinds of checks:
211 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
212 ///   will change the order of memory accesses in a way that will change the
213 ///   correctness of the program.
214 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
215 /// checks for a number of different conditions, such as the availability of a
216 /// single induction variable, that all types are supported and vectorize-able,
217 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
218 /// This class is also used by InnerLoopVectorizer for identifying
219 /// induction variable and the different reduction variables.
220 class LoopVectorizationLegality {
221 public:
222   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl,
223                             DominatorTree *Dt):
224   TheLoop(Lp), SE(Se), DL(Dl), DT(Dt), Induction(0) { }
225
226   /// This enum represents the kinds of reductions that we support.
227   enum ReductionKind {
228     NoReduction, /// Not a reduction.
229     IntegerAdd,  /// Sum of numbers.
230     IntegerMult, /// Product of numbers.
231     IntegerOr,   /// Bitwise or logical OR of numbers.
232     IntegerAnd,  /// Bitwise or logical AND of numbers.
233     IntegerXor   /// Bitwise or logical XOR of numbers.
234   };
235
236   /// This enum represents the kinds of inductions that we support.
237   enum InductionKind {
238     NoInduction,         /// Not an induction variable.
239     IntInduction,        /// Integer induction variable. Step = 1.
240     ReverseIntInduction, /// Reverse int induction variable. Step = -1.
241     PtrInduction         /// Pointer induction variable. Step = sizeof(elem).
242   };
243
244   /// This POD struct holds information about reduction variables.
245   struct ReductionDescriptor {
246     // Default C'tor
247     ReductionDescriptor():
248     StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
249
250     // C'tor.
251     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
252     StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
253
254     // The starting value of the reduction.
255     // It does not have to be zero!
256     Value *StartValue;
257     // The instruction who's value is used outside the loop.
258     Instruction *LoopExitInstr;
259     // The kind of the reduction.
260     ReductionKind Kind;
261   };
262
263   // This POD struct holds information about the memory runtime legality
264   // check that a group of pointers do not overlap.
265   struct RuntimePointerCheck {
266     RuntimePointerCheck(): Need(false) {}
267
268     /// Reset the state of the pointer runtime information.
269     void reset() {
270       Need = false;
271       Pointers.clear();
272       Starts.clear();
273       Ends.clear();
274     }
275
276     /// Insert a pointer and calculate the start and end SCEVs.
277     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
278
279     /// This flag indicates if we need to add the runtime check.
280     bool Need;
281     /// Holds the pointers that we need to check.
282     SmallVector<Value*, 2> Pointers;
283     /// Holds the pointer value at the beginning of the loop.
284     SmallVector<const SCEV*, 2> Starts;
285     /// Holds the pointer value at the end of the loop.
286     SmallVector<const SCEV*, 2> Ends;
287   };
288
289   /// A POD for saving information about induction variables.
290   struct InductionInfo {
291     /// Ctors.
292     InductionInfo(Value *Start, InductionKind K):
293     StartValue(Start), IK(K) {};
294     InductionInfo(): StartValue(0), IK(NoInduction) {};
295     /// Start value.
296     Value *StartValue;
297     /// Induction kind.
298     InductionKind IK;
299   };
300
301   /// ReductionList contains the reduction descriptors for all
302   /// of the reductions that were found in the loop.
303   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
304
305   /// InductionList saves induction variables and maps them to the
306   /// induction descriptor.
307   typedef DenseMap<PHINode*, InductionInfo> InductionList;
308
309   /// Returns true if it is legal to vectorize this loop.
310   /// This does not mean that it is profitable to vectorize this
311   /// loop, only that it is legal to do so.
312   bool canVectorize();
313
314   /// Returns the Induction variable.
315   PHINode *getInduction() {return Induction;}
316
317   /// Returns the reduction variables found in the loop.
318   ReductionList *getReductionVars() { return &Reductions; }
319
320   /// Returns the induction variables found in the loop.
321   InductionList *getInductionVars() { return &Inductions; }
322
323   /// Return true if the block BB needs to be predicated in order for the loop
324   /// to be vectorized.
325   bool blockNeedsPredication(BasicBlock *BB);
326
327   /// Check if this  pointer is consecutive when vectorizing. This happens
328   /// when the last index of the GEP is the induction variable, or that the
329   /// pointer itself is an induction variable.
330   /// This check allows us to vectorize A[idx] into a wide load/store.
331   bool isConsecutivePtr(Value *Ptr);
332
333   /// Returns true if the value V is uniform within the loop.
334   bool isUniform(Value *V);
335
336   /// Returns true if this instruction will remain scalar after vectorization.
337   bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
338
339   /// Returns the information that we collected about runtime memory check.
340   RuntimePointerCheck *getRuntimePointerCheck() {return &PtrRtCheck; }
341 private:
342   /// Check if a single basic block loop is vectorizable.
343   /// At this point we know that this is a loop with a constant trip count
344   /// and we only need to check individual instructions.
345   bool canVectorizeInstrs();
346
347   /// When we vectorize loops we may change the order in which
348   /// we read and write from memory. This method checks if it is
349   /// legal to vectorize the code, considering only memory constrains.
350   /// Returns true if the loop is vectorizable
351   bool canVectorizeMemory();
352
353   /// Return true if we can vectorize this loop using the IF-conversion
354   /// transformation.
355   bool canVectorizeWithIfConvert();
356
357   /// Collect the variables that need to stay uniform after vectorization.
358   void collectLoopUniforms();
359
360   /// Return true if all of the instructions in the block can be speculatively
361   /// executed.
362   bool blockCanBePredicated(BasicBlock *BB);
363
364   /// Returns True, if 'Phi' is the kind of reduction variable for type
365   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
366   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
367   /// Returns true if the instruction I can be a reduction variable of type
368   /// 'Kind'.
369   bool isReductionInstr(Instruction *I, ReductionKind Kind);
370   /// Returns the induction kind of Phi. This function may return NoInduction
371   /// if the PHI is not an induction variable.
372   InductionKind isInductionVariable(PHINode *Phi);
373   /// Return true if can compute the address bounds of Ptr within the loop.
374   bool hasComputableBounds(Value *Ptr);
375
376   /// The loop that we evaluate.
377   Loop *TheLoop;
378   /// Scev analysis.
379   ScalarEvolution *SE;
380   /// DataLayout analysis.
381   DataLayout *DL;
382   // Dominators.
383   DominatorTree *DT;
384
385   //  ---  vectorization state --- //
386
387   /// Holds the integer induction variable. This is the counter of the
388   /// loop.
389   PHINode *Induction;
390   /// Holds the reduction variables.
391   ReductionList Reductions;
392   /// Holds all of the induction variables that we found in the loop.
393   /// Notice that inductions don't need to start at zero and that induction
394   /// variables can be pointers.
395   InductionList Inductions;
396
397   /// Allowed outside users. This holds the reduction
398   /// vars which can be accessed from outside the loop.
399   SmallPtrSet<Value*, 4> AllowedExit;
400   /// This set holds the variables which are known to be uniform after
401   /// vectorization.
402   SmallPtrSet<Instruction*, 4> Uniforms;
403   /// We need to check that all of the pointers in this list are disjoint
404   /// at runtime.
405   RuntimePointerCheck PtrRtCheck;
406 };
407
408 /// LoopVectorizationCostModel - estimates the expected speedups due to
409 /// vectorization.
410 /// In many cases vectorization is not profitable. This can happen because
411 /// of a number of reasons. In this class we mainly attempt to predict
412 /// the expected speedup/slowdowns due to the supported instruction set.
413 /// We use the VectorTargetTransformInfo to query the different backends
414 /// for the cost of different operations.
415 class LoopVectorizationCostModel {
416 public:
417   /// C'tor.
418   LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
419                              LoopVectorizationLegality *Leg,
420                              const VectorTargetTransformInfo *Vtti):
421   TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
422
423   /// Returns the most profitable vectorization factor for the loop that is
424   /// smaller or equal to the VF argument. This method checks every power
425   /// of two up to VF.
426   unsigned findBestVectorizationFactor(unsigned VF = MaxVectorSize);
427
428 private:
429   /// Returns the expected execution cost. The unit of the cost does
430   /// not matter because we use the 'cost' units to compare different
431   /// vector widths. The cost that is returned is *not* normalized by
432   /// the factor width.
433   unsigned expectedCost(unsigned VF);
434
435   /// Returns the execution time cost of an instruction for a given vector
436   /// width. Vector width of one means scalar.
437   unsigned getInstructionCost(Instruction *I, unsigned VF);
438
439   /// A helper function for converting Scalar types to vector types.
440   /// If the incoming type is void, we return void. If the VF is 1, we return
441   /// the scalar type.
442   static Type* ToVectorTy(Type *Scalar, unsigned VF);
443
444   /// The loop that we evaluate.
445   Loop *TheLoop;
446   /// Scev analysis.
447   ScalarEvolution *SE;
448
449   /// Vectorization legality.
450   LoopVectorizationLegality *Legal;
451   /// Vector target information.
452   const VectorTargetTransformInfo *VTTI;
453 };
454
455 }// namespace llvm
456
457 #endif //LLVM_TRANSFORM_VECTORIZE_LOOP_VECTORIZE_H
458