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"
61 /// We don't vectorize loops with a known constant trip count below this number.
62 const unsigned TinyTripCountThreshold = 16;
64 /// When performing a runtime memory check, do not check more than this
65 /// number of pointers. Notice that the check is quadratic!
66 const unsigned RuntimeMemoryCheckThreshold = 4;
68 /// This is the highest vector width that we try to generate.
69 const unsigned MaxVectorSize = 8;
73 // Forward declarations.
74 class LoopVectorizationLegality;
75 class LoopVectorizationCostModel;
76 class VectorTargetTransformInfo;
78 /// InnerLoopVectorizer vectorizes loops which contain only one basic
79 /// block to a specified vectorization factor (VF).
80 /// This class performs the widening of scalars into vectors, or multiple
81 /// scalars. This class also implements the following features:
82 /// * It inserts an epilogue loop for handling loops that don't have iteration
83 /// counts that are known to be a multiple of the vectorization factor.
84 /// * It handles the code generation for reduction variables.
85 /// * Scalarization (implementation using scalars) of un-vectorizable
87 /// InnerLoopVectorizer does not perform any vectorization-legality
88 /// checks, and relies on the caller to check for the different legality
89 /// aspects. The InnerLoopVectorizer relies on the
90 /// LoopVectorizationLegality class to provide information about the induction
91 /// and reduction variables that were found to a given vectorization factor.
92 class InnerLoopVectorizer {
95 InnerLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
96 DominatorTree *Dt, DataLayout *Dl,
97 unsigned VecWidth, unsigned UnrollFactor):
98 OrigLoop(Orig), SE(Se), LI(Li), DT(Dt), DL(Dl), VF(VecWidth),
99 UF(UnrollFactor), Builder(Se->getContext()), Induction(0), OldInduction(0),
100 WidenMap(UnrollFactor) { }
102 // Perform the actual loop widening (vectorization).
103 void vectorize(LoopVectorizationLegality *Legal) {
104 // Create a new empty loop. Unlink the old loop and connect the new one.
105 createEmptyLoop(Legal);
106 // Widen each instruction in the old loop to a new one in the new loop.
107 // Use the Legality module to find the induction and reduction variables.
108 vectorizeLoop(Legal);
109 // Register the new loop and update the analysis passes.
114 /// A small list of PHINodes.
115 typedef SmallVector<PHINode*, 4> PhiVector;
116 /// When we unroll loops we have multiple vector values for each scalar.
117 /// This data structure holds the unrolled and vectorized values that
118 /// originated from one scalar instruction.
119 typedef SmallVector<Value*, 2> VectorParts;
121 /// Add code that checks at runtime if the accessed arrays overlap.
122 /// Returns the comparator value or NULL if no check is needed.
123 Value *addRuntimeCheck(LoopVectorizationLegality *Legal,
125 /// Create an empty loop, based on the loop ranges of the old loop.
126 void createEmptyLoop(LoopVectorizationLegality *Legal);
127 /// Copy and widen the instructions from the old loop.
128 void vectorizeLoop(LoopVectorizationLegality *Legal);
130 /// A helper function that computes the predicate of the block BB, assuming
131 /// that the header block of the loop is set to True. It returns the *entry*
132 /// mask for the block BB.
133 VectorParts createBlockInMask(BasicBlock *BB);
134 /// A helper function that computes the predicate of the edge between SRC
136 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
138 /// A helper function to vectorize a single BB within the innermost loop.
139 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
142 /// Insert the new loop to the loop hierarchy and pass manager
143 /// and update the analysis passes.
144 void updateAnalysis();
146 /// This instruction is un-vectorizable. Implement it as a sequence
148 void scalarizeInstruction(Instruction *Instr);
150 /// Create a broadcast instruction. This method generates a broadcast
151 /// instruction (shuffle) for loop invariant values and for the induction
152 /// value. If this is the induction variable then we extend it to N, N+1, ...
153 /// this is needed because each iteration in the loop corresponds to a SIMD
155 Value *getBroadcastInstrs(Value *V);
157 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
158 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
159 /// The sequence starts at StartIndex.
160 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
162 /// When we go over instructions in the basic block we rely on previous
163 /// values within the current basic block or on loop invariant values.
164 /// When we widen (vectorize) values we place them in the map. If the values
165 /// are not within the map, they have to be loop invariant, so we simply
166 /// broadcast them into a vector.
167 VectorParts &getVectorValue(Value *V);
169 /// Get a uniform vector of constant integers. We use this to get
170 /// vectors of ones and zeros for the reduction code.
171 Constant* getUniformVector(unsigned Val, Type* ScalarTy);
173 /// Generate a shuffle sequence that will reverse the vector Vec.
174 Value *reverseVector(Value *Vec);
176 /// This is a helper class that holds the vectorizer state. It maps scalar
177 /// instructions to vector instructions. When the code is 'unrolled' then
178 /// then a single scalar value is mapped to multiple vector parts. The parts
179 /// are stored in the VectorPart type.
181 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
183 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
185 /// \return True if 'Key' is saved in the Value Map.
186 bool has(Value *Key) { return MapStoreage.count(Key); }
188 /// Initializes a new entry in the map. Sets all of the vector parts to the
189 /// save value in 'Val'.
190 /// \return A reference to a vector with splat values.
191 VectorParts &splat(Value *Key, Value *Val) {
192 MapStoreage[Key].clear();
193 MapStoreage[Key].append(UF, Val);
194 return MapStoreage[Key];
197 ///\return A reference to the value that is stored at 'Key'.
198 VectorParts &get(Value *Key) {
200 MapStoreage[Key].resize(UF);
201 return MapStoreage[Key];
204 /// The unroll factor. Each entry in the map stores this number of vector
208 /// Map storage. We use std::map and not DenseMap because insertions to a
209 /// dense map invalidates its iterators.
210 std::map<Value*, VectorParts> MapStoreage;
213 /// The original loop.
215 /// Scev analysis to use.
223 /// The vectorization SIMD factor to use. Each vector will have this many
226 /// The vectorization unroll factor to use. Each scalar is vectorized to this
227 /// many different vector instructions.
230 /// The builder that we use
233 // --- Vectorization state ---
235 /// The vector-loop preheader.
236 BasicBlock *LoopVectorPreHeader;
237 /// The scalar-loop preheader.
238 BasicBlock *LoopScalarPreHeader;
239 /// Middle Block between the vector and the scalar.
240 BasicBlock *LoopMiddleBlock;
241 ///The ExitBlock of the scalar loop.
242 BasicBlock *LoopExitBlock;
243 ///The vector loop body.
244 BasicBlock *LoopVectorBody;
245 ///The scalar loop body.
246 BasicBlock *LoopScalarBody;
247 ///The first bypass block.
248 BasicBlock *LoopBypassBlock;
250 /// The new Induction variable which was added to the new block.
252 /// The induction variable of the old basic block.
253 PHINode *OldInduction;
254 /// Maps scalars to widened vectors.
258 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
259 /// to what vectorization factor.
260 /// This class does not look at the profitability of vectorization, only the
261 /// legality. This class has two main kinds of checks:
262 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
263 /// will change the order of memory accesses in a way that will change the
264 /// correctness of the program.
265 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
266 /// checks for a number of different conditions, such as the availability of a
267 /// single induction variable, that all types are supported and vectorize-able,
268 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
269 /// This class is also used by InnerLoopVectorizer for identifying
270 /// induction variable and the different reduction variables.
271 class LoopVectorizationLegality {
273 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl,
275 TheLoop(Lp), SE(Se), DL(Dl), DT(Dt), Induction(0) { }
277 /// This enum represents the kinds of reductions that we support.
279 NoReduction, /// Not a reduction.
280 IntegerAdd, /// Sum of numbers.
281 IntegerMult, /// Product of numbers.
282 IntegerOr, /// Bitwise or logical OR of numbers.
283 IntegerAnd, /// Bitwise or logical AND of numbers.
284 IntegerXor /// Bitwise or logical XOR of numbers.
287 /// This enum represents the kinds of inductions that we support.
289 NoInduction, /// Not an induction variable.
290 IntInduction, /// Integer induction variable. Step = 1.
291 ReverseIntInduction, /// Reverse int induction variable. Step = -1.
292 PtrInduction /// Pointer induction variable. Step = sizeof(elem).
295 /// This POD struct holds information about reduction variables.
296 struct ReductionDescriptor {
298 ReductionDescriptor():
299 StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
302 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
303 StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
305 // The starting value of the reduction.
306 // It does not have to be zero!
308 // The instruction who's value is used outside the loop.
309 Instruction *LoopExitInstr;
310 // The kind of the reduction.
314 // This POD struct holds information about the memory runtime legality
315 // check that a group of pointers do not overlap.
316 struct RuntimePointerCheck {
317 RuntimePointerCheck(): Need(false) {}
319 /// Reset the state of the pointer runtime information.
327 /// Insert a pointer and calculate the start and end SCEVs.
328 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
330 /// This flag indicates if we need to add the runtime check.
332 /// Holds the pointers that we need to check.
333 SmallVector<Value*, 2> Pointers;
334 /// Holds the pointer value at the beginning of the loop.
335 SmallVector<const SCEV*, 2> Starts;
336 /// Holds the pointer value at the end of the loop.
337 SmallVector<const SCEV*, 2> Ends;
340 /// A POD for saving information about induction variables.
341 struct InductionInfo {
343 InductionInfo(Value *Start, InductionKind K):
344 StartValue(Start), IK(K) {};
345 InductionInfo(): StartValue(0), IK(NoInduction) {};
352 /// ReductionList contains the reduction descriptors for all
353 /// of the reductions that were found in the loop.
354 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
356 /// InductionList saves induction variables and maps them to the
357 /// induction descriptor.
358 typedef MapVector<PHINode*, InductionInfo> InductionList;
360 /// Returns true if it is legal to vectorize this loop.
361 /// This does not mean that it is profitable to vectorize this
362 /// loop, only that it is legal to do so.
365 /// Returns the Induction variable.
366 PHINode *getInduction() {return Induction;}
368 /// Returns the reduction variables found in the loop.
369 ReductionList *getReductionVars() { return &Reductions; }
371 /// Returns the induction variables found in the loop.
372 InductionList *getInductionVars() { return &Inductions; }
374 /// Returns True if V is an induction variable in this loop.
375 bool isInductionVariable(const Value *V);
377 /// Return true if the block BB needs to be predicated in order for the loop
378 /// to be vectorized.
379 bool blockNeedsPredication(BasicBlock *BB);
381 /// Check if this pointer is consecutive when vectorizing. This happens
382 /// when the last index of the GEP is the induction variable, or that the
383 /// pointer itself is an induction variable.
384 /// This check allows us to vectorize A[idx] into a wide load/store.
386 /// 0 - Stride is unknown or non consecutive.
387 /// 1 - Address is consecutive.
388 /// -1 - Address is consecutive, and decreasing.
389 int isConsecutivePtr(Value *Ptr);
391 /// Returns true if the value V is uniform within the loop.
392 bool isUniform(Value *V);
394 /// Returns true if this instruction will remain scalar after vectorization.
395 bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
397 /// Returns the information that we collected about runtime memory check.
398 RuntimePointerCheck *getRuntimePointerCheck() {return &PtrRtCheck; }
400 /// Check if a single basic block loop is vectorizable.
401 /// At this point we know that this is a loop with a constant trip count
402 /// and we only need to check individual instructions.
403 bool canVectorizeInstrs();
405 /// When we vectorize loops we may change the order in which
406 /// we read and write from memory. This method checks if it is
407 /// legal to vectorize the code, considering only memory constrains.
408 /// Returns true if the loop is vectorizable
409 bool canVectorizeMemory();
411 /// Return true if we can vectorize this loop using the IF-conversion
413 bool canVectorizeWithIfConvert();
415 /// Collect the variables that need to stay uniform after vectorization.
416 void collectLoopUniforms();
418 /// Return true if all of the instructions in the block can be speculatively
420 bool blockCanBePredicated(BasicBlock *BB);
422 /// Returns True, if 'Phi' is the kind of reduction variable for type
423 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
424 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
425 /// Returns true if the instruction I can be a reduction variable of type
427 bool isReductionInstr(Instruction *I, ReductionKind Kind);
428 /// Returns the induction kind of Phi. This function may return NoInduction
429 /// if the PHI is not an induction variable.
430 InductionKind isInductionVariable(PHINode *Phi);
431 /// Return true if can compute the address bounds of Ptr within the loop.
432 bool hasComputableBounds(Value *Ptr);
434 /// The loop that we evaluate.
438 /// DataLayout analysis.
443 // --- vectorization state --- //
445 /// Holds the integer induction variable. This is the counter of the
448 /// Holds the reduction variables.
449 ReductionList Reductions;
450 /// Holds all of the induction variables that we found in the loop.
451 /// Notice that inductions don't need to start at zero and that induction
452 /// variables can be pointers.
453 InductionList Inductions;
455 /// Allowed outside users. This holds the reduction
456 /// vars which can be accessed from outside the loop.
457 SmallPtrSet<Value*, 4> AllowedExit;
458 /// This set holds the variables which are known to be uniform after
460 SmallPtrSet<Instruction*, 4> Uniforms;
461 /// We need to check that all of the pointers in this list are disjoint
463 RuntimePointerCheck PtrRtCheck;
466 /// LoopVectorizationCostModel - estimates the expected speedups due to
468 /// In many cases vectorization is not profitable. This can happen because
469 /// of a number of reasons. In this class we mainly attempt to predict
470 /// the expected speedup/slowdowns due to the supported instruction set.
471 /// We use the VectorTargetTransformInfo to query the different backends
472 /// for the cost of different operations.
473 class LoopVectorizationCostModel {
476 LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
477 LoopVectorizationLegality *Leg,
478 const VectorTargetTransformInfo *Vtti):
479 TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
481 /// Returns the most profitable vectorization factor in powers of two.
482 /// This method checks every power of two up to VF. If UserVF is not ZERO
483 /// then this vectorization factor will be selected if vectorization is
485 unsigned selectVectorizationFactor(bool OptForSize, unsigned UserVF);
488 /// Returns the expected execution cost. The unit of the cost does
489 /// not matter because we use the 'cost' units to compare different
490 /// vector widths. The cost that is returned is *not* normalized by
491 /// the factor width.
492 unsigned expectedCost(unsigned VF);
494 /// Returns the execution time cost of an instruction for a given vector
495 /// width. Vector width of one means scalar.
496 unsigned getInstructionCost(Instruction *I, unsigned VF);
498 /// A helper function for converting Scalar types to vector types.
499 /// If the incoming type is void, we return void. If the VF is 1, we return
501 static Type* ToVectorTy(Type *Scalar, unsigned VF);
503 /// The loop that we evaluate.
508 /// Vectorization legality.
509 LoopVectorizationLegality *Legal;
510 /// Vector target information.
511 const VectorTargetTransformInfo *VTTI;
516 #endif //LLVM_TRANSFORM_VECTORIZE_LOOP_VECTORIZE_H