1 //===- LoopVectorize.h --- A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
44 #ifndef LLVM_TRANSFORM_VECTORIZE_LOOP_VECTORIZE_H
45 #define LLVM_TRANSFORM_VECTORIZE_LOOP_VECTORIZE_H
47 #define LV_NAME "loop-vectorize"
48 #define DEBUG_TYPE LV_NAME
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/MapVector.h"
52 #include "llvm/ADT/SmallPtrSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/Analysis/ScalarEvolution.h"
55 #include "llvm/IR/IRBuilder.h"
59 /// We don't vectorize loops with a known constant trip count below this number.
60 const unsigned TinyTripCountThreshold = 16;
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;
66 /// This is the highest vector width that we try to generate.
67 const unsigned MaxVectorSize = 8;
71 // Forward declarations.
72 class LoopVectorizationLegality;
73 class LoopVectorizationCostModel;
74 class VectorTargetTransformInfo;
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
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 {
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) { }
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.
110 /// A small list of PHINodes.
111 typedef SmallVector<PHINode*, 4> PhiVector;
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,
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);
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
128 Value *createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
130 /// A helper function to vectorize a single BB within the innermost loop.
131 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
134 /// Insert the new loop to the loop hierarchy and pass manager
135 /// and update the analysis passes.
136 void updateAnalysis();
138 /// This instruction is un-vectorizable. Implement it as a sequence
140 void scalarizeInstruction(Instruction *Instr);
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
147 Value *getBroadcastInstrs(Value *V);
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);
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);
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);
164 /// Generate a shuffle sequence that will reverse the vector Vec.
165 Value *reverseVector(Value *Vec);
167 typedef DenseMap<Value*, Value*> ValueMap;
169 /// The original loop.
171 // Scev analysis to use.
179 // The vectorization factor to use.
182 // The builder that we use
185 // --- Vectorization state ---
187 /// The vector-loop preheader.
188 BasicBlock *LoopVectorPreHeader;
189 /// The scalar-loop preheader.
190 BasicBlock *LoopScalarPreHeader;
191 /// Middle Block between the vector and the scalar.
192 BasicBlock *LoopMiddleBlock;
193 ///The ExitBlock of the scalar loop.
194 BasicBlock *LoopExitBlock;
195 ///The vector loop body.
196 BasicBlock *LoopVectorBody;
197 ///The scalar loop body.
198 BasicBlock *LoopScalarBody;
199 ///The first bypass block.
200 BasicBlock *LoopBypassBlock;
202 /// The new Induction variable which was added to the new block.
204 /// The induction variable of the old basic block.
205 PHINode *OldInduction;
206 // Maps scalars to widened vectors.
210 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
211 /// to what vectorization factor.
212 /// This class does not look at the profitability of vectorization, only the
213 /// legality. This class has two main kinds of checks:
214 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
215 /// will change the order of memory accesses in a way that will change the
216 /// correctness of the program.
217 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
218 /// checks for a number of different conditions, such as the availability of a
219 /// single induction variable, that all types are supported and vectorize-able,
220 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
221 /// This class is also used by InnerLoopVectorizer for identifying
222 /// induction variable and the different reduction variables.
223 class LoopVectorizationLegality {
225 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl,
227 TheLoop(Lp), SE(Se), DL(Dl), DT(Dt), Induction(0) { }
229 /// This enum represents the kinds of reductions that we support.
231 NoReduction, /// Not a reduction.
232 IntegerAdd, /// Sum of numbers.
233 IntegerMult, /// Product of numbers.
234 IntegerOr, /// Bitwise or logical OR of numbers.
235 IntegerAnd, /// Bitwise or logical AND of numbers.
236 IntegerXor /// Bitwise or logical XOR of numbers.
239 /// This enum represents the kinds of inductions that we support.
241 NoInduction, /// Not an induction variable.
242 IntInduction, /// Integer induction variable. Step = 1.
243 ReverseIntInduction, /// Reverse int induction variable. Step = -1.
244 PtrInduction /// Pointer induction variable. Step = sizeof(elem).
247 /// This POD struct holds information about reduction variables.
248 struct ReductionDescriptor {
250 ReductionDescriptor():
251 StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
254 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
255 StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
257 // The starting value of the reduction.
258 // It does not have to be zero!
260 // The instruction who's value is used outside the loop.
261 Instruction *LoopExitInstr;
262 // The kind of the reduction.
266 // This POD struct holds information about the memory runtime legality
267 // check that a group of pointers do not overlap.
268 struct RuntimePointerCheck {
269 RuntimePointerCheck(): Need(false) {}
271 /// Reset the state of the pointer runtime information.
279 /// Insert a pointer and calculate the start and end SCEVs.
280 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
282 /// This flag indicates if we need to add the runtime check.
284 /// Holds the pointers that we need to check.
285 SmallVector<Value*, 2> Pointers;
286 /// Holds the pointer value at the beginning of the loop.
287 SmallVector<const SCEV*, 2> Starts;
288 /// Holds the pointer value at the end of the loop.
289 SmallVector<const SCEV*, 2> Ends;
292 /// A POD for saving information about induction variables.
293 struct InductionInfo {
295 InductionInfo(Value *Start, InductionKind K):
296 StartValue(Start), IK(K) {};
297 InductionInfo(): StartValue(0), IK(NoInduction) {};
304 /// ReductionList contains the reduction descriptors for all
305 /// of the reductions that were found in the loop.
306 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
308 /// InductionList saves induction variables and maps them to the
309 /// induction descriptor.
310 typedef MapVector<PHINode*, InductionInfo> InductionList;
312 /// Returns true if it is legal to vectorize this loop.
313 /// This does not mean that it is profitable to vectorize this
314 /// loop, only that it is legal to do so.
317 /// Returns the Induction variable.
318 PHINode *getInduction() {return Induction;}
320 /// Returns the reduction variables found in the loop.
321 ReductionList *getReductionVars() { return &Reductions; }
323 /// Returns the induction variables found in the loop.
324 InductionList *getInductionVars() { return &Inductions; }
326 /// Returns True if V is an induction variable in this loop.
327 bool isInductionVariable(const Value *V);
329 /// Return true if the block BB needs to be predicated in order for the loop
330 /// to be vectorized.
331 bool blockNeedsPredication(BasicBlock *BB);
333 /// Check if this pointer is consecutive when vectorizing. This happens
334 /// when the last index of the GEP is the induction variable, or that the
335 /// pointer itself is an induction variable.
336 /// This check allows us to vectorize A[idx] into a wide load/store.
338 /// 0 - Stride is unknown or non consecutive.
339 /// 1 - Address is consecutive.
340 /// -1 - Address is consecutive, and decreasing.
341 int isConsecutivePtr(Value *Ptr);
343 /// Returns true if the value V is uniform within the loop.
344 bool isUniform(Value *V);
346 /// Returns true if this instruction will remain scalar after vectorization.
347 bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
349 /// Returns the information that we collected about runtime memory check.
350 RuntimePointerCheck *getRuntimePointerCheck() {return &PtrRtCheck; }
352 /// Check if a single basic block loop is vectorizable.
353 /// At this point we know that this is a loop with a constant trip count
354 /// and we only need to check individual instructions.
355 bool canVectorizeInstrs();
357 /// When we vectorize loops we may change the order in which
358 /// we read and write from memory. This method checks if it is
359 /// legal to vectorize the code, considering only memory constrains.
360 /// Returns true if the loop is vectorizable
361 bool canVectorizeMemory();
363 /// Return true if we can vectorize this loop using the IF-conversion
365 bool canVectorizeWithIfConvert();
367 /// Collect the variables that need to stay uniform after vectorization.
368 void collectLoopUniforms();
370 /// Return true if all of the instructions in the block can be speculatively
372 bool blockCanBePredicated(BasicBlock *BB);
374 /// Returns True, if 'Phi' is the kind of reduction variable for type
375 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
376 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
377 /// Returns true if the instruction I can be a reduction variable of type
379 bool isReductionInstr(Instruction *I, ReductionKind Kind);
380 /// Returns the induction kind of Phi. This function may return NoInduction
381 /// if the PHI is not an induction variable.
382 InductionKind isInductionVariable(PHINode *Phi);
383 /// Return true if can compute the address bounds of Ptr within the loop.
384 bool hasComputableBounds(Value *Ptr);
386 /// The loop that we evaluate.
390 /// DataLayout analysis.
395 // --- vectorization state --- //
397 /// Holds the integer induction variable. This is the counter of the
400 /// Holds the reduction variables.
401 ReductionList Reductions;
402 /// Holds all of the induction variables that we found in the loop.
403 /// Notice that inductions don't need to start at zero and that induction
404 /// variables can be pointers.
405 InductionList Inductions;
407 /// Allowed outside users. This holds the reduction
408 /// vars which can be accessed from outside the loop.
409 SmallPtrSet<Value*, 4> AllowedExit;
410 /// This set holds the variables which are known to be uniform after
412 SmallPtrSet<Instruction*, 4> Uniforms;
413 /// We need to check that all of the pointers in this list are disjoint
415 RuntimePointerCheck PtrRtCheck;
418 /// LoopVectorizationCostModel - estimates the expected speedups due to
420 /// In many cases vectorization is not profitable. This can happen because
421 /// of a number of reasons. In this class we mainly attempt to predict
422 /// the expected speedup/slowdowns due to the supported instruction set.
423 /// We use the VectorTargetTransformInfo to query the different backends
424 /// for the cost of different operations.
425 class LoopVectorizationCostModel {
428 LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
429 LoopVectorizationLegality *Leg,
430 const VectorTargetTransformInfo *Vtti):
431 TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
433 /// Returns the most profitable vectorization factor in powers of two.
434 /// This method checks every power of two up to VF. If UserVF is not ZERO
435 /// then this vectorization factor will be selected if vectorization is
437 unsigned selectVectorizationFactor(bool OptForSize, unsigned UserVF);
440 /// Returns the expected execution cost. The unit of the cost does
441 /// not matter because we use the 'cost' units to compare different
442 /// vector widths. The cost that is returned is *not* normalized by
443 /// the factor width.
444 unsigned expectedCost(unsigned VF);
446 /// Returns the execution time cost of an instruction for a given vector
447 /// width. Vector width of one means scalar.
448 unsigned getInstructionCost(Instruction *I, unsigned VF);
450 /// A helper function for converting Scalar types to vector types.
451 /// If the incoming type is void, we return void. If the VF is 1, we return
453 static Type* ToVectorTy(Type *Scalar, unsigned VF);
455 /// The loop that we evaluate.
460 /// Vectorization legality.
461 LoopVectorizationLegality *Legal;
462 /// Vector target information.
463 const VectorTargetTransformInfo *VTTI;
468 #endif //LLVM_TRANSFORM_VECTORIZE_LOOP_VECTORIZE_H