1 //===- LoopVectorize.cpp - 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.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
15 // The loop vectorizer combines consecutive loop iterations 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 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/EquivalenceClasses.h"
51 #include "llvm/ADT/Hashing.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/Analysis/AliasAnalysis.h"
59 #include "llvm/Analysis/LoopInfo.h"
60 #include "llvm/Analysis/LoopIterator.h"
61 #include "llvm/Analysis/LoopPass.h"
62 #include "llvm/Analysis/ScalarEvolution.h"
63 #include "llvm/Analysis/ScalarEvolutionExpander.h"
64 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
65 #include "llvm/Analysis/TargetTransformInfo.h"
66 #include "llvm/Analysis/ValueTracking.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Dominators.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/LLVMContext.h"
76 #include "llvm/IR/Module.h"
77 #include "llvm/IR/Type.h"
78 #include "llvm/IR/Value.h"
79 #include "llvm/IR/Verifier.h"
80 #include "llvm/Pass.h"
81 #include "llvm/Support/CommandLine.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/PatternMatch.h"
84 #include "llvm/Support/ValueHandle.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Target/TargetLibraryInfo.h"
87 #include "llvm/Transforms/Scalar.h"
88 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
89 #include "llvm/Transforms/Utils/Local.h"
94 using namespace llvm::PatternMatch;
96 static cl::opt<unsigned>
97 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
98 cl::desc("Sets the SIMD width. Zero is autoselect."));
100 static cl::opt<unsigned>
101 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
102 cl::desc("Sets the vectorization unroll count. "
103 "Zero is autoselect."));
106 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
107 cl::desc("Enable if-conversion during vectorization."));
109 /// We don't vectorize loops with a known constant trip count below this number.
110 static cl::opt<unsigned>
111 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
113 cl::desc("Don't vectorize loops with a constant "
114 "trip count that is smaller than this "
117 /// This enables versioning on the strides of symbolically striding memory
118 /// accesses in code like the following.
119 /// for (i = 0; i < N; ++i)
120 /// A[i * Stride1] += B[i * Stride2] ...
122 /// Will be roughly translated to
123 /// if (Stride1 == 1 && Stride2 == 1) {
124 /// for (i = 0; i < N; i+=4)
128 static cl::opt<bool> EnableMemAccessVersioning(
129 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
130 cl::desc("Enable symblic stride memory access versioning"));
132 /// We don't unroll loops with a known constant trip count below this number.
133 static const unsigned TinyTripCountUnrollThreshold = 128;
135 /// When performing memory disambiguation checks at runtime do not make more
136 /// than this number of comparisons.
137 static const unsigned RuntimeMemoryCheckThreshold = 8;
139 /// Maximum simd width.
140 static const unsigned MaxVectorWidth = 64;
142 static cl::opt<unsigned> ForceTargetNumScalarRegs(
143 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
144 cl::desc("A flag that overrides the target's number of scalar registers."));
146 static cl::opt<unsigned> ForceTargetNumVectorRegs(
147 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
148 cl::desc("A flag that overrides the target's number of vector registers."));
150 /// Maximum vectorization unroll count.
151 static const unsigned MaxUnrollFactor = 16;
153 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
154 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
155 cl::desc("A flag that overrides the target's max unroll factor for scalar "
158 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
159 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
160 cl::desc("A flag that overrides the target's max unroll factor for "
161 "vectorized loops."));
163 static cl::opt<unsigned> SmallLoopCost(
164 "small-loop-cost", cl::init(20), cl::Hidden,
165 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
169 // Forward declarations.
170 class LoopVectorizationLegality;
171 class LoopVectorizationCostModel;
173 /// InnerLoopVectorizer vectorizes loops which contain only one basic
174 /// block to a specified vectorization factor (VF).
175 /// This class performs the widening of scalars into vectors, or multiple
176 /// scalars. This class also implements the following features:
177 /// * It inserts an epilogue loop for handling loops that don't have iteration
178 /// counts that are known to be a multiple of the vectorization factor.
179 /// * It handles the code generation for reduction variables.
180 /// * Scalarization (implementation using scalars) of un-vectorizable
182 /// InnerLoopVectorizer does not perform any vectorization-legality
183 /// checks, and relies on the caller to check for the different legality
184 /// aspects. The InnerLoopVectorizer relies on the
185 /// LoopVectorizationLegality class to provide information about the induction
186 /// and reduction variables that were found to a given vectorization factor.
187 class InnerLoopVectorizer {
189 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
190 DominatorTree *DT, DataLayout *DL,
191 const TargetLibraryInfo *TLI, unsigned VecWidth,
192 unsigned UnrollFactor)
193 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
194 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
195 OldInduction(0), WidenMap(UnrollFactor), Legal(0) {}
197 // Perform the actual loop widening (vectorization).
198 void vectorize(LoopVectorizationLegality *L) {
200 // Create a new empty loop. Unlink the old loop and connect the new one.
202 // Widen each instruction in the old loop to a new one in the new loop.
203 // Use the Legality module to find the induction and reduction variables.
205 // Register the new loop and update the analysis passes.
209 virtual ~InnerLoopVectorizer() {}
212 /// A small list of PHINodes.
213 typedef SmallVector<PHINode*, 4> PhiVector;
214 /// When we unroll loops we have multiple vector values for each scalar.
215 /// This data structure holds the unrolled and vectorized values that
216 /// originated from one scalar instruction.
217 typedef SmallVector<Value*, 2> VectorParts;
219 // When we if-convert we need create edge masks. We have to cache values so
220 // that we don't end up with exponential recursion/IR.
221 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
222 VectorParts> EdgeMaskCache;
224 /// \brief Add code that checks at runtime if the accessed arrays overlap.
226 /// Returns a pair of instructions where the first element is the first
227 /// instruction generated in possibly a sequence of instructions and the
228 /// second value is the final comparator value or NULL if no check is needed.
229 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
231 /// \brief Add checks for strides that where assumed to be 1.
233 /// Returns the last check instruction and the first check instruction in the
234 /// pair as (first, last).
235 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
237 /// Create an empty loop, based on the loop ranges of the old loop.
238 void createEmptyLoop();
239 /// Copy and widen the instructions from the old loop.
240 virtual void vectorizeLoop();
242 /// \brief The Loop exit block may have single value PHI nodes where the
243 /// incoming value is 'Undef'. While vectorizing we only handled real values
244 /// that were defined inside the loop. Here we fix the 'undef case'.
248 /// A helper function that computes the predicate of the block BB, assuming
249 /// that the header block of the loop is set to True. It returns the *entry*
250 /// mask for the block BB.
251 VectorParts createBlockInMask(BasicBlock *BB);
252 /// A helper function that computes the predicate of the edge between SRC
254 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
256 /// A helper function to vectorize a single BB within the innermost loop.
257 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
259 /// Vectorize a single PHINode in a block. This method handles the induction
260 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
261 /// arbitrary length vectors.
262 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
263 unsigned UF, unsigned VF, PhiVector *PV);
265 /// Insert the new loop to the loop hierarchy and pass manager
266 /// and update the analysis passes.
267 void updateAnalysis();
269 /// This instruction is un-vectorizable. Implement it as a sequence
271 virtual void scalarizeInstruction(Instruction *Instr);
273 /// Vectorize Load and Store instructions,
274 virtual void vectorizeMemoryInstruction(Instruction *Instr);
276 /// Create a broadcast instruction. This method generates a broadcast
277 /// instruction (shuffle) for loop invariant values and for the induction
278 /// value. If this is the induction variable then we extend it to N, N+1, ...
279 /// this is needed because each iteration in the loop corresponds to a SIMD
281 virtual Value *getBroadcastInstrs(Value *V);
283 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
284 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
285 /// The sequence starts at StartIndex.
286 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
288 /// When we go over instructions in the basic block we rely on previous
289 /// values within the current basic block or on loop invariant values.
290 /// When we widen (vectorize) values we place them in the map. If the values
291 /// are not within the map, they have to be loop invariant, so we simply
292 /// broadcast them into a vector.
293 VectorParts &getVectorValue(Value *V);
295 /// Generate a shuffle sequence that will reverse the vector Vec.
296 virtual Value *reverseVector(Value *Vec);
298 /// This is a helper class that holds the vectorizer state. It maps scalar
299 /// instructions to vector instructions. When the code is 'unrolled' then
300 /// then a single scalar value is mapped to multiple vector parts. The parts
301 /// are stored in the VectorPart type.
303 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
305 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
307 /// \return True if 'Key' is saved in the Value Map.
308 bool has(Value *Key) const { return MapStorage.count(Key); }
310 /// Initializes a new entry in the map. Sets all of the vector parts to the
311 /// save value in 'Val'.
312 /// \return A reference to a vector with splat values.
313 VectorParts &splat(Value *Key, Value *Val) {
314 VectorParts &Entry = MapStorage[Key];
315 Entry.assign(UF, Val);
319 ///\return A reference to the value that is stored at 'Key'.
320 VectorParts &get(Value *Key) {
321 VectorParts &Entry = MapStorage[Key];
324 assert(Entry.size() == UF);
329 /// The unroll factor. Each entry in the map stores this number of vector
333 /// Map storage. We use std::map and not DenseMap because insertions to a
334 /// dense map invalidates its iterators.
335 std::map<Value *, VectorParts> MapStorage;
338 /// The original loop.
340 /// Scev analysis to use.
348 /// Target Library Info.
349 const TargetLibraryInfo *TLI;
351 /// The vectorization SIMD factor to use. Each vector will have this many
356 /// The vectorization unroll factor to use. Each scalar is vectorized to this
357 /// many different vector instructions.
360 /// The builder that we use
363 // --- Vectorization state ---
365 /// The vector-loop preheader.
366 BasicBlock *LoopVectorPreHeader;
367 /// The scalar-loop preheader.
368 BasicBlock *LoopScalarPreHeader;
369 /// Middle Block between the vector and the scalar.
370 BasicBlock *LoopMiddleBlock;
371 ///The ExitBlock of the scalar loop.
372 BasicBlock *LoopExitBlock;
373 ///The vector loop body.
374 BasicBlock *LoopVectorBody;
375 ///The scalar loop body.
376 BasicBlock *LoopScalarBody;
377 /// A list of all bypass blocks. The first block is the entry of the loop.
378 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
380 /// The new Induction variable which was added to the new block.
382 /// The induction variable of the old basic block.
383 PHINode *OldInduction;
384 /// Holds the extended (to the widest induction type) start index.
386 /// Maps scalars to widened vectors.
388 EdgeMaskCache MaskCache;
390 LoopVectorizationLegality *Legal;
393 class InnerLoopUnroller : public InnerLoopVectorizer {
395 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
396 DominatorTree *DT, DataLayout *DL,
397 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
398 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
401 virtual void scalarizeInstruction(Instruction *Instr);
402 virtual void vectorizeMemoryInstruction(Instruction *Instr);
403 virtual Value *getBroadcastInstrs(Value *V);
404 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
405 virtual Value *reverseVector(Value *Vec);
408 /// \brief Look for a meaningful debug location on the instruction or it's
410 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
415 if (I->getDebugLoc() != Empty)
418 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
419 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
420 if (OpInst->getDebugLoc() != Empty)
427 /// \brief Set the debug location in the builder using the debug location in the
429 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
430 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
431 B.SetCurrentDebugLocation(Inst->getDebugLoc());
433 B.SetCurrentDebugLocation(DebugLoc());
436 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
437 /// to what vectorization factor.
438 /// This class does not look at the profitability of vectorization, only the
439 /// legality. This class has two main kinds of checks:
440 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
441 /// will change the order of memory accesses in a way that will change the
442 /// correctness of the program.
443 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
444 /// checks for a number of different conditions, such as the availability of a
445 /// single induction variable, that all types are supported and vectorize-able,
446 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
447 /// This class is also used by InnerLoopVectorizer for identifying
448 /// induction variable and the different reduction variables.
449 class LoopVectorizationLegality {
451 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
452 DominatorTree *DT, TargetLibraryInfo *TLI)
453 : TheLoop(L), SE(SE), DL(DL), DT(DT), TLI(TLI),
454 Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
455 MaxSafeDepDistBytes(-1U) {}
457 /// This enum represents the kinds of reductions that we support.
459 RK_NoReduction, ///< Not a reduction.
460 RK_IntegerAdd, ///< Sum of integers.
461 RK_IntegerMult, ///< Product of integers.
462 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
463 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
464 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
465 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
466 RK_FloatAdd, ///< Sum of floats.
467 RK_FloatMult, ///< Product of floats.
468 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
471 /// This enum represents the kinds of inductions that we support.
473 IK_NoInduction, ///< Not an induction variable.
474 IK_IntInduction, ///< Integer induction variable. Step = 1.
475 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
476 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
477 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
480 // This enum represents the kind of minmax reduction.
481 enum MinMaxReductionKind {
491 /// This struct holds information about reduction variables.
492 struct ReductionDescriptor {
493 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
494 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
496 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
497 MinMaxReductionKind MK)
498 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
500 // The starting value of the reduction.
501 // It does not have to be zero!
502 TrackingVH<Value> StartValue;
503 // The instruction who's value is used outside the loop.
504 Instruction *LoopExitInstr;
505 // The kind of the reduction.
507 // If this a min/max reduction the kind of reduction.
508 MinMaxReductionKind MinMaxKind;
511 /// This POD struct holds information about a potential reduction operation.
512 struct ReductionInstDesc {
513 ReductionInstDesc(bool IsRedux, Instruction *I) :
514 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
516 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
517 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
519 // Is this instruction a reduction candidate.
521 // The last instruction in a min/max pattern (select of the select(icmp())
522 // pattern), or the current reduction instruction otherwise.
523 Instruction *PatternLastInst;
524 // If this is a min/max pattern the comparison predicate.
525 MinMaxReductionKind MinMaxKind;
528 /// This struct holds information about the memory runtime legality
529 /// check that a group of pointers do not overlap.
530 struct RuntimePointerCheck {
531 RuntimePointerCheck() : Need(false) {}
533 /// Reset the state of the pointer runtime information.
540 DependencySetId.clear();
543 /// Insert a pointer and calculate the start and end SCEVs.
544 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
545 unsigned DepSetId, ValueToValueMap &Strides);
547 /// This flag indicates if we need to add the runtime check.
549 /// Holds the pointers that we need to check.
550 SmallVector<TrackingVH<Value>, 2> Pointers;
551 /// Holds the pointer value at the beginning of the loop.
552 SmallVector<const SCEV*, 2> Starts;
553 /// Holds the pointer value at the end of the loop.
554 SmallVector<const SCEV*, 2> Ends;
555 /// Holds the information if this pointer is used for writing to memory.
556 SmallVector<bool, 2> IsWritePtr;
557 /// Holds the id of the set of pointers that could be dependent because of a
558 /// shared underlying object.
559 SmallVector<unsigned, 2> DependencySetId;
562 /// A struct for saving information about induction variables.
563 struct InductionInfo {
564 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
565 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
567 TrackingVH<Value> StartValue;
572 /// ReductionList contains the reduction descriptors for all
573 /// of the reductions that were found in the loop.
574 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
576 /// InductionList saves induction variables and maps them to the
577 /// induction descriptor.
578 typedef MapVector<PHINode*, InductionInfo> InductionList;
580 /// Returns true if it is legal to vectorize this loop.
581 /// This does not mean that it is profitable to vectorize this
582 /// loop, only that it is legal to do so.
585 /// Returns the Induction variable.
586 PHINode *getInduction() { return Induction; }
588 /// Returns the reduction variables found in the loop.
589 ReductionList *getReductionVars() { return &Reductions; }
591 /// Returns the induction variables found in the loop.
592 InductionList *getInductionVars() { return &Inductions; }
594 /// Returns the widest induction type.
595 Type *getWidestInductionType() { return WidestIndTy; }
597 /// Returns True if V is an induction variable in this loop.
598 bool isInductionVariable(const Value *V);
600 /// Return true if the block BB needs to be predicated in order for the loop
601 /// to be vectorized.
602 bool blockNeedsPredication(BasicBlock *BB);
604 /// Check if this pointer is consecutive when vectorizing. This happens
605 /// when the last index of the GEP is the induction variable, or that the
606 /// pointer itself is an induction variable.
607 /// This check allows us to vectorize A[idx] into a wide load/store.
609 /// 0 - Stride is unknown or non-consecutive.
610 /// 1 - Address is consecutive.
611 /// -1 - Address is consecutive, and decreasing.
612 int isConsecutivePtr(Value *Ptr);
614 /// Returns true if the value V is uniform within the loop.
615 bool isUniform(Value *V);
617 /// Returns true if this instruction will remain scalar after vectorization.
618 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
620 /// Returns the information that we collected about runtime memory check.
621 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
623 /// This function returns the identity element (or neutral element) for
625 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
627 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
629 bool hasStride(Value *V) { return StrideSet.count(V); }
630 bool mustCheckStrides() { return !StrideSet.empty(); }
631 SmallPtrSet<Value *, 8>::iterator strides_begin() {
632 return StrideSet.begin();
634 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
637 /// Check if a single basic block loop is vectorizable.
638 /// At this point we know that this is a loop with a constant trip count
639 /// and we only need to check individual instructions.
640 bool canVectorizeInstrs();
642 /// When we vectorize loops we may change the order in which
643 /// we read and write from memory. This method checks if it is
644 /// legal to vectorize the code, considering only memory constrains.
645 /// Returns true if the loop is vectorizable
646 bool canVectorizeMemory();
648 /// Return true if we can vectorize this loop using the IF-conversion
650 bool canVectorizeWithIfConvert();
652 /// Collect the variables that need to stay uniform after vectorization.
653 void collectLoopUniforms();
655 /// Return true if all of the instructions in the block can be speculatively
656 /// executed. \p SafePtrs is a list of addresses that are known to be legal
657 /// and we know that we can read from them without segfault.
658 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
660 /// Returns True, if 'Phi' is the kind of reduction variable for type
661 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
662 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
663 /// Returns a struct describing if the instruction 'I' can be a reduction
664 /// variable of type 'Kind'. If the reduction is a min/max pattern of
665 /// select(icmp()) this function advances the instruction pointer 'I' from the
666 /// compare instruction to the select instruction and stores this pointer in
667 /// 'PatternLastInst' member of the returned struct.
668 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
669 ReductionInstDesc &Desc);
670 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
671 /// pattern corresponding to a min(X, Y) or max(X, Y).
672 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
673 ReductionInstDesc &Prev);
674 /// Returns the induction kind of Phi. This function may return NoInduction
675 /// if the PHI is not an induction variable.
676 InductionKind isInductionVariable(PHINode *Phi);
678 /// \brief Collect memory access with loop invariant strides.
680 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
682 void collectStridedAcccess(Value *LoadOrStoreInst);
684 /// The loop that we evaluate.
688 /// DataLayout analysis.
692 /// Target Library Info.
693 TargetLibraryInfo *TLI;
695 // --- vectorization state --- //
697 /// Holds the integer induction variable. This is the counter of the
700 /// Holds the reduction variables.
701 ReductionList Reductions;
702 /// Holds all of the induction variables that we found in the loop.
703 /// Notice that inductions don't need to start at zero and that induction
704 /// variables can be pointers.
705 InductionList Inductions;
706 /// Holds the widest induction type encountered.
709 /// Allowed outside users. This holds the reduction
710 /// vars which can be accessed from outside the loop.
711 SmallPtrSet<Value*, 4> AllowedExit;
712 /// This set holds the variables which are known to be uniform after
714 SmallPtrSet<Instruction*, 4> Uniforms;
715 /// We need to check that all of the pointers in this list are disjoint
717 RuntimePointerCheck PtrRtCheck;
718 /// Can we assume the absence of NaNs.
719 bool HasFunNoNaNAttr;
721 unsigned MaxSafeDepDistBytes;
723 ValueToValueMap Strides;
724 SmallPtrSet<Value *, 8> StrideSet;
727 /// LoopVectorizationCostModel - estimates the expected speedups due to
729 /// In many cases vectorization is not profitable. This can happen because of
730 /// a number of reasons. In this class we mainly attempt to predict the
731 /// expected speedup/slowdowns due to the supported instruction set. We use the
732 /// TargetTransformInfo to query the different backends for the cost of
733 /// different operations.
734 class LoopVectorizationCostModel {
736 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
737 LoopVectorizationLegality *Legal,
738 const TargetTransformInfo &TTI,
739 DataLayout *DL, const TargetLibraryInfo *TLI)
740 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
742 /// Information about vectorization costs
743 struct VectorizationFactor {
744 unsigned Width; // Vector width with best cost
745 unsigned Cost; // Cost of the loop with that width
747 /// \return The most profitable vectorization factor and the cost of that VF.
748 /// This method checks every power of two up to VF. If UserVF is not ZERO
749 /// then this vectorization factor will be selected if vectorization is
751 VectorizationFactor selectVectorizationFactor(bool OptForSize,
754 /// \return The size (in bits) of the widest type in the code that
755 /// needs to be vectorized. We ignore values that remain scalar such as
756 /// 64 bit loop indices.
757 unsigned getWidestType();
759 /// \return The most profitable unroll factor.
760 /// If UserUF is non-zero then this method finds the best unroll-factor
761 /// based on register pressure and other parameters.
762 /// VF and LoopCost are the selected vectorization factor and the cost of the
764 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
767 /// \brief A struct that represents some properties of the register usage
769 struct RegisterUsage {
770 /// Holds the number of loop invariant values that are used in the loop.
771 unsigned LoopInvariantRegs;
772 /// Holds the maximum number of concurrent live intervals in the loop.
773 unsigned MaxLocalUsers;
774 /// Holds the number of instructions in the loop.
775 unsigned NumInstructions;
778 /// \return information about the register usage of the loop.
779 RegisterUsage calculateRegisterUsage();
782 /// Returns the expected execution cost. The unit of the cost does
783 /// not matter because we use the 'cost' units to compare different
784 /// vector widths. The cost that is returned is *not* normalized by
785 /// the factor width.
786 unsigned expectedCost(unsigned VF);
788 /// Returns the execution time cost of an instruction for a given vector
789 /// width. Vector width of one means scalar.
790 unsigned getInstructionCost(Instruction *I, unsigned VF);
792 /// A helper function for converting Scalar types to vector types.
793 /// If the incoming type is void, we return void. If the VF is 1, we return
795 static Type* ToVectorTy(Type *Scalar, unsigned VF);
797 /// Returns whether the instruction is a load or store and will be a emitted
798 /// as a vector operation.
799 bool isConsecutiveLoadOrStore(Instruction *I);
801 /// The loop that we evaluate.
805 /// Loop Info analysis.
807 /// Vectorization legality.
808 LoopVectorizationLegality *Legal;
809 /// Vector target information.
810 const TargetTransformInfo &TTI;
811 /// Target data layout information.
813 /// Target Library Info.
814 const TargetLibraryInfo *TLI;
817 /// Utility class for getting and setting loop vectorizer hints in the form
818 /// of loop metadata.
819 struct LoopVectorizeHints {
820 /// Vectorization width.
822 /// Vectorization unroll factor.
824 /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled)
827 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
828 : Width(VectorizationFactor)
829 , Unroll(DisableUnrolling ? 1 : VectorizationUnroll)
831 , LoopID(L->getLoopID()) {
833 // The command line options override any loop metadata except for when
834 // width == 1 which is used to indicate the loop is already vectorized.
835 if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
836 Width = VectorizationFactor;
837 if (VectorizationUnroll.getNumOccurrences() > 0)
838 Unroll = VectorizationUnroll;
840 DEBUG(if (DisableUnrolling && Unroll == 1)
841 dbgs() << "LV: Unrolling disabled by the pass manager\n");
844 /// Return the loop vectorizer metadata prefix.
845 static StringRef Prefix() { return "llvm.vectorizer."; }
847 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
848 SmallVector<Value*, 2> Vals;
849 Vals.push_back(MDString::get(Context, Name));
850 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
851 return MDNode::get(Context, Vals);
854 /// Mark the loop L as already vectorized by setting the width to 1.
855 void setAlreadyVectorized(Loop *L) {
856 LLVMContext &Context = L->getHeader()->getContext();
860 // Create a new loop id with one more operand for the already_vectorized
861 // hint. If the loop already has a loop id then copy the existing operands.
862 SmallVector<Value*, 4> Vals(1);
864 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
865 Vals.push_back(LoopID->getOperand(i));
867 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
868 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
870 MDNode *NewLoopID = MDNode::get(Context, Vals);
871 // Set operand 0 to refer to the loop id itself.
872 NewLoopID->replaceOperandWith(0, NewLoopID);
874 L->setLoopID(NewLoopID);
876 LoopID->replaceAllUsesWith(NewLoopID);
884 /// Find hints specified in the loop metadata.
885 void getHints(const Loop *L) {
889 // First operand should refer to the loop id itself.
890 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
891 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
893 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
894 const MDString *S = 0;
895 SmallVector<Value*, 4> Args;
897 // The expected hint is either a MDString or a MDNode with the first
898 // operand a MDString.
899 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
900 if (!MD || MD->getNumOperands() == 0)
902 S = dyn_cast<MDString>(MD->getOperand(0));
903 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
904 Args.push_back(MD->getOperand(i));
906 S = dyn_cast<MDString>(LoopID->getOperand(i));
907 assert(Args.size() == 0 && "too many arguments for MDString");
913 // Check if the hint starts with the vectorizer prefix.
914 StringRef Hint = S->getString();
915 if (!Hint.startswith(Prefix()))
917 // Remove the prefix.
918 Hint = Hint.substr(Prefix().size(), StringRef::npos);
920 if (Args.size() == 1)
921 getHint(Hint, Args[0]);
925 // Check string hint with one operand.
926 void getHint(StringRef Hint, Value *Arg) {
927 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
929 unsigned Val = C->getZExtValue();
931 if (Hint == "width") {
932 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
935 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
936 } else if (Hint == "unroll") {
937 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
940 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
941 } else if (Hint == "enable") {
942 if (C->getBitWidth() == 1)
945 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
947 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
952 static void addInnerLoop(Loop *L, SmallVectorImpl<Loop *> &V) {
954 return V.push_back(L);
956 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
960 /// The LoopVectorize Pass.
961 struct LoopVectorize : public FunctionPass {
962 /// Pass identification, replacement for typeid
965 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
967 DisableUnrolling(NoUnrolling),
968 AlwaysVectorize(AlwaysVectorize) {
969 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
975 TargetTransformInfo *TTI;
977 TargetLibraryInfo *TLI;
978 bool DisableUnrolling;
979 bool AlwaysVectorize;
981 virtual bool runOnFunction(Function &F) {
982 SE = &getAnalysis<ScalarEvolution>();
983 DL = getAnalysisIfAvailable<DataLayout>();
984 LI = &getAnalysis<LoopInfo>();
985 TTI = &getAnalysis<TargetTransformInfo>();
986 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
987 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
989 // If the target claims to have no vector registers don't attempt
991 if (!TTI->getNumberOfRegisters(true))
995 DEBUG(dbgs() << "LV: Not vectorizing: Missing data layout\n");
999 // Build up a worklist of inner-loops to vectorize. This is necessary as
1000 // the act of vectorizing or partially unrolling a loop creates new loops
1001 // and can invalidate iterators across the loops.
1002 SmallVector<Loop *, 8> Worklist;
1004 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
1005 addInnerLoop(*I, Worklist);
1007 // Now walk the identified inner loops.
1008 bool Changed = false;
1009 while (!Worklist.empty())
1010 Changed |= processLoop(Worklist.pop_back_val());
1012 // Process each loop nest in the function.
1016 bool processLoop(Loop *L) {
1017 // We only handle inner loops, so if there are children just recurse.
1019 bool Changed = false;
1020 for (Loop::iterator I = L->begin(), E = L->begin(); I != E; ++I)
1021 Changed |= processLoop(*I);
1025 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
1026 L->getHeader()->getParent()->getName() << "\"\n");
1028 LoopVectorizeHints Hints(L, DisableUnrolling);
1030 if (Hints.Force == 0) {
1031 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1035 if (!AlwaysVectorize && Hints.Force != 1) {
1036 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1040 if (Hints.Width == 1 && Hints.Unroll == 1) {
1041 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1045 // Check if it is legal to vectorize the loop.
1046 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1047 if (!LVL.canVectorize()) {
1048 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1052 // Use the cost model.
1053 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1055 // Check the function attributes to find out if this function should be
1056 // optimized for size.
1057 Function *F = L->getHeader()->getParent();
1059 Hints.Force != 1 && F->hasFnAttribute(Attribute::OptimizeForSize);
1061 // Check the function attributes to see if implicit floats are allowed.a
1062 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1063 // an integer loop and the vector instructions selected are purely integer
1064 // vector instructions?
1065 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1066 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1067 "attribute is used.\n");
1071 // Select the optimal vectorization factor.
1072 LoopVectorizationCostModel::VectorizationFactor VF;
1073 VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
1074 // Select the unroll factor.
1075 unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
1078 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
1079 F->getParent()->getModuleIdentifier() << '\n');
1080 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1082 if (VF.Width == 1) {
1083 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1086 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1087 // We decided not to vectorize, but we may want to unroll.
1088 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1089 Unroller.vectorize(&LVL);
1091 // If we decided that it is *legal* to vectorize the loop then do it.
1092 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1096 // Mark the loop as already vectorized to avoid vectorizing again.
1097 Hints.setAlreadyVectorized(L);
1099 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1103 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1104 AU.addRequiredID(LoopSimplifyID);
1105 AU.addRequiredID(LCSSAID);
1106 AU.addRequired<DominatorTreeWrapperPass>();
1107 AU.addRequired<LoopInfo>();
1108 AU.addRequired<ScalarEvolution>();
1109 AU.addRequired<TargetTransformInfo>();
1110 AU.addPreserved<LoopInfo>();
1111 AU.addPreserved<DominatorTreeWrapperPass>();
1116 } // end anonymous namespace
1118 //===----------------------------------------------------------------------===//
1119 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1120 // LoopVectorizationCostModel.
1121 //===----------------------------------------------------------------------===//
1123 static Value *stripIntegerCast(Value *V) {
1124 if (CastInst *CI = dyn_cast<CastInst>(V))
1125 if (CI->getOperand(0)->getType()->isIntegerTy())
1126 return CI->getOperand(0);
1130 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1132 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1134 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1135 ValueToValueMap &PtrToStride,
1136 Value *Ptr, Value *OrigPtr = 0) {
1138 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1140 // If there is an entry in the map return the SCEV of the pointer with the
1141 // symbolic stride replaced by one.
1142 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1143 if (SI != PtrToStride.end()) {
1144 Value *StrideVal = SI->second;
1147 StrideVal = stripIntegerCast(StrideVal);
1149 // Replace symbolic stride by one.
1150 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1151 ValueToValueMap RewriteMap;
1152 RewriteMap[StrideVal] = One;
1155 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1156 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1161 // Otherwise, just return the SCEV of the original pointer.
1162 return SE->getSCEV(Ptr);
1165 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1166 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1167 ValueToValueMap &Strides) {
1168 // Get the stride replaced scev.
1169 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1170 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1171 assert(AR && "Invalid addrec expression");
1172 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1173 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1174 Pointers.push_back(Ptr);
1175 Starts.push_back(AR->getStart());
1176 Ends.push_back(ScEnd);
1177 IsWritePtr.push_back(WritePtr);
1178 DependencySetId.push_back(DepSetId);
1181 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1182 // We need to place the broadcast of invariant variables outside the loop.
1183 Instruction *Instr = dyn_cast<Instruction>(V);
1184 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
1185 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1187 // Place the code for broadcasting invariant variables in the new preheader.
1188 IRBuilder<>::InsertPointGuard Guard(Builder);
1190 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1192 // Broadcast the scalar into all locations in the vector.
1193 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1198 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1200 assert(Val->getType()->isVectorTy() && "Must be a vector");
1201 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1202 "Elem must be an integer");
1203 // Create the types.
1204 Type *ITy = Val->getType()->getScalarType();
1205 VectorType *Ty = cast<VectorType>(Val->getType());
1206 int VLen = Ty->getNumElements();
1207 SmallVector<Constant*, 8> Indices;
1209 // Create a vector of consecutive numbers from zero to VF.
1210 for (int i = 0; i < VLen; ++i) {
1211 int64_t Idx = Negate ? (-i) : i;
1212 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1215 // Add the consecutive indices to the vector value.
1216 Constant *Cv = ConstantVector::get(Indices);
1217 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1218 return Builder.CreateAdd(Val, Cv, "induction");
1221 /// \brief Find the operand of the GEP that should be checked for consecutive
1222 /// stores. This ignores trailing indices that have no effect on the final
1224 static unsigned getGEPInductionOperand(DataLayout *DL,
1225 const GetElementPtrInst *Gep) {
1226 unsigned LastOperand = Gep->getNumOperands() - 1;
1227 unsigned GEPAllocSize = DL->getTypeAllocSize(
1228 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1230 // Walk backwards and try to peel off zeros.
1231 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1232 // Find the type we're currently indexing into.
1233 gep_type_iterator GEPTI = gep_type_begin(Gep);
1234 std::advance(GEPTI, LastOperand - 1);
1236 // If it's a type with the same allocation size as the result of the GEP we
1237 // can peel off the zero index.
1238 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1246 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1247 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1248 // Make sure that the pointer does not point to structs.
1249 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1252 // If this value is a pointer induction variable we know it is consecutive.
1253 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1254 if (Phi && Inductions.count(Phi)) {
1255 InductionInfo II = Inductions[Phi];
1256 if (IK_PtrInduction == II.IK)
1258 else if (IK_ReversePtrInduction == II.IK)
1262 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1266 unsigned NumOperands = Gep->getNumOperands();
1267 Value *GpPtr = Gep->getPointerOperand();
1268 // If this GEP value is a consecutive pointer induction variable and all of
1269 // the indices are constant then we know it is consecutive. We can
1270 Phi = dyn_cast<PHINode>(GpPtr);
1271 if (Phi && Inductions.count(Phi)) {
1273 // Make sure that the pointer does not point to structs.
1274 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1275 if (GepPtrType->getElementType()->isAggregateType())
1278 // Make sure that all of the index operands are loop invariant.
1279 for (unsigned i = 1; i < NumOperands; ++i)
1280 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1283 InductionInfo II = Inductions[Phi];
1284 if (IK_PtrInduction == II.IK)
1286 else if (IK_ReversePtrInduction == II.IK)
1290 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1292 // Check that all of the gep indices are uniform except for our induction
1294 for (unsigned i = 0; i != NumOperands; ++i)
1295 if (i != InductionOperand &&
1296 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1299 // We can emit wide load/stores only if the last non-zero index is the
1300 // induction variable.
1301 const SCEV *Last = 0;
1302 if (!Strides.count(Gep))
1303 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1305 // Because of the multiplication by a stride we can have a s/zext cast.
1306 // We are going to replace this stride by 1 so the cast is safe to ignore.
1308 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1309 // %0 = trunc i64 %indvars.iv to i32
1310 // %mul = mul i32 %0, %Stride1
1311 // %idxprom = zext i32 %mul to i64 << Safe cast.
1312 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1314 Last = replaceSymbolicStrideSCEV(SE, Strides,
1315 Gep->getOperand(InductionOperand), Gep);
1316 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1318 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1322 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1323 const SCEV *Step = AR->getStepRecurrence(*SE);
1325 // The memory is consecutive because the last index is consecutive
1326 // and all other indices are loop invariant.
1329 if (Step->isAllOnesValue())
1336 bool LoopVectorizationLegality::isUniform(Value *V) {
1337 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1340 InnerLoopVectorizer::VectorParts&
1341 InnerLoopVectorizer::getVectorValue(Value *V) {
1342 assert(V != Induction && "The new induction variable should not be used.");
1343 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1345 // If we have a stride that is replaced by one, do it here.
1346 if (Legal->hasStride(V))
1347 V = ConstantInt::get(V->getType(), 1);
1349 // If we have this scalar in the map, return it.
1350 if (WidenMap.has(V))
1351 return WidenMap.get(V);
1353 // If this scalar is unknown, assume that it is a constant or that it is
1354 // loop invariant. Broadcast V and save the value for future uses.
1355 Value *B = getBroadcastInstrs(V);
1356 return WidenMap.splat(V, B);
1359 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1360 assert(Vec->getType()->isVectorTy() && "Invalid type");
1361 SmallVector<Constant*, 8> ShuffleMask;
1362 for (unsigned i = 0; i < VF; ++i)
1363 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1365 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1366 ConstantVector::get(ShuffleMask),
1370 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1371 // Attempt to issue a wide load.
1372 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1373 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1375 assert((LI || SI) && "Invalid Load/Store instruction");
1377 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1378 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1379 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1380 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1381 // An alignment of 0 means target abi alignment. We need to use the scalar's
1382 // target abi alignment in such a case.
1384 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1385 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1386 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1387 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1389 if (ScalarAllocatedSize != VectorElementSize)
1390 return scalarizeInstruction(Instr);
1392 // If the pointer is loop invariant or if it is non-consecutive,
1393 // scalarize the load.
1394 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1395 bool Reverse = ConsecutiveStride < 0;
1396 bool UniformLoad = LI && Legal->isUniform(Ptr);
1397 if (!ConsecutiveStride || UniformLoad)
1398 return scalarizeInstruction(Instr);
1400 Constant *Zero = Builder.getInt32(0);
1401 VectorParts &Entry = WidenMap.get(Instr);
1403 // Handle consecutive loads/stores.
1404 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1405 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1406 setDebugLocFromInst(Builder, Gep);
1407 Value *PtrOperand = Gep->getPointerOperand();
1408 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1409 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1411 // Create the new GEP with the new induction variable.
1412 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1413 Gep2->setOperand(0, FirstBasePtr);
1414 Gep2->setName("gep.indvar.base");
1415 Ptr = Builder.Insert(Gep2);
1417 setDebugLocFromInst(Builder, Gep);
1418 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1419 OrigLoop) && "Base ptr must be invariant");
1421 // The last index does not have to be the induction. It can be
1422 // consecutive and be a function of the index. For example A[I+1];
1423 unsigned NumOperands = Gep->getNumOperands();
1424 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1425 // Create the new GEP with the new induction variable.
1426 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1428 for (unsigned i = 0; i < NumOperands; ++i) {
1429 Value *GepOperand = Gep->getOperand(i);
1430 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1432 // Update last index or loop invariant instruction anchored in loop.
1433 if (i == InductionOperand ||
1434 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1435 assert((i == InductionOperand ||
1436 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1437 "Must be last index or loop invariant");
1439 VectorParts &GEPParts = getVectorValue(GepOperand);
1440 Value *Index = GEPParts[0];
1441 Index = Builder.CreateExtractElement(Index, Zero);
1442 Gep2->setOperand(i, Index);
1443 Gep2->setName("gep.indvar.idx");
1446 Ptr = Builder.Insert(Gep2);
1448 // Use the induction element ptr.
1449 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1450 setDebugLocFromInst(Builder, Ptr);
1451 VectorParts &PtrVal = getVectorValue(Ptr);
1452 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1457 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1458 "We do not allow storing to uniform addresses");
1459 setDebugLocFromInst(Builder, SI);
1460 // We don't want to update the value in the map as it might be used in
1461 // another expression. So don't use a reference type for "StoredVal".
1462 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1464 for (unsigned Part = 0; Part < UF; ++Part) {
1465 // Calculate the pointer for the specific unroll-part.
1466 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1469 // If we store to reverse consecutive memory locations then we need
1470 // to reverse the order of elements in the stored value.
1471 StoredVal[Part] = reverseVector(StoredVal[Part]);
1472 // If the address is consecutive but reversed, then the
1473 // wide store needs to start at the last vector element.
1474 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1475 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1478 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1479 DataTy->getPointerTo(AddressSpace));
1480 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1486 assert(LI && "Must have a load instruction");
1487 setDebugLocFromInst(Builder, LI);
1488 for (unsigned Part = 0; Part < UF; ++Part) {
1489 // Calculate the pointer for the specific unroll-part.
1490 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1493 // If the address is consecutive but reversed, then the
1494 // wide store needs to start at the last vector element.
1495 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1496 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1499 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1500 DataTy->getPointerTo(AddressSpace));
1501 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1502 cast<LoadInst>(LI)->setAlignment(Alignment);
1503 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1507 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1508 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1509 // Holds vector parameters or scalars, in case of uniform vals.
1510 SmallVector<VectorParts, 4> Params;
1512 setDebugLocFromInst(Builder, Instr);
1514 // Find all of the vectorized parameters.
1515 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1516 Value *SrcOp = Instr->getOperand(op);
1518 // If we are accessing the old induction variable, use the new one.
1519 if (SrcOp == OldInduction) {
1520 Params.push_back(getVectorValue(SrcOp));
1524 // Try using previously calculated values.
1525 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1527 // If the src is an instruction that appeared earlier in the basic block
1528 // then it should already be vectorized.
1529 if (SrcInst && OrigLoop->contains(SrcInst)) {
1530 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1531 // The parameter is a vector value from earlier.
1532 Params.push_back(WidenMap.get(SrcInst));
1534 // The parameter is a scalar from outside the loop. Maybe even a constant.
1535 VectorParts Scalars;
1536 Scalars.append(UF, SrcOp);
1537 Params.push_back(Scalars);
1541 assert(Params.size() == Instr->getNumOperands() &&
1542 "Invalid number of operands");
1544 // Does this instruction return a value ?
1545 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1547 Value *UndefVec = IsVoidRetTy ? 0 :
1548 UndefValue::get(VectorType::get(Instr->getType(), VF));
1549 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1550 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1552 // For each vector unroll 'part':
1553 for (unsigned Part = 0; Part < UF; ++Part) {
1554 // For each scalar that we create:
1555 for (unsigned Width = 0; Width < VF; ++Width) {
1556 Instruction *Cloned = Instr->clone();
1558 Cloned->setName(Instr->getName() + ".cloned");
1559 // Replace the operands of the cloned instructions with extracted scalars.
1560 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1561 Value *Op = Params[op][Part];
1562 // Param is a vector. Need to extract the right lane.
1563 if (Op->getType()->isVectorTy())
1564 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1565 Cloned->setOperand(op, Op);
1568 // Place the cloned scalar in the new loop.
1569 Builder.Insert(Cloned);
1571 // If the original scalar returns a value we need to place it in a vector
1572 // so that future users will be able to use it.
1574 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1575 Builder.getInt32(Width));
1580 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1584 if (Instruction *I = dyn_cast<Instruction>(V))
1585 return I->getParent() == Loc->getParent() ? I : 0;
1589 std::pair<Instruction *, Instruction *>
1590 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1591 Instruction *tnullptr = 0;
1592 if (!Legal->mustCheckStrides())
1593 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1595 IRBuilder<> ChkBuilder(Loc);
1599 Instruction *FirstInst = 0;
1600 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1601 SE = Legal->strides_end();
1603 Value *Ptr = stripIntegerCast(*SI);
1604 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1606 // Store the first instruction we create.
1607 FirstInst = getFirstInst(FirstInst, C, Loc);
1609 Check = ChkBuilder.CreateOr(Check, C);
1614 // We have to do this trickery because the IRBuilder might fold the check to a
1615 // constant expression in which case there is no Instruction anchored in a
1617 LLVMContext &Ctx = Loc->getContext();
1618 Instruction *TheCheck =
1619 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1620 ChkBuilder.Insert(TheCheck, "stride.not.one");
1621 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1623 return std::make_pair(FirstInst, TheCheck);
1626 std::pair<Instruction *, Instruction *>
1627 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1628 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1629 Legal->getRuntimePointerCheck();
1631 Instruction *tnullptr = 0;
1632 if (!PtrRtCheck->Need)
1633 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1635 unsigned NumPointers = PtrRtCheck->Pointers.size();
1636 SmallVector<TrackingVH<Value> , 2> Starts;
1637 SmallVector<TrackingVH<Value> , 2> Ends;
1639 LLVMContext &Ctx = Loc->getContext();
1640 SCEVExpander Exp(*SE, "induction");
1641 Instruction *FirstInst = 0;
1643 for (unsigned i = 0; i < NumPointers; ++i) {
1644 Value *Ptr = PtrRtCheck->Pointers[i];
1645 const SCEV *Sc = SE->getSCEV(Ptr);
1647 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1648 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1650 Starts.push_back(Ptr);
1651 Ends.push_back(Ptr);
1653 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1654 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1656 // Use this type for pointer arithmetic.
1657 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1659 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1660 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1661 Starts.push_back(Start);
1662 Ends.push_back(End);
1666 IRBuilder<> ChkBuilder(Loc);
1667 // Our instructions might fold to a constant.
1668 Value *MemoryRuntimeCheck = 0;
1669 for (unsigned i = 0; i < NumPointers; ++i) {
1670 for (unsigned j = i+1; j < NumPointers; ++j) {
1671 // No need to check if two readonly pointers intersect.
1672 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1675 // Only need to check pointers between two different dependency sets.
1676 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1679 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1680 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1682 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1683 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1684 "Trying to bounds check pointers with different address spaces");
1686 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1687 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1689 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1690 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1691 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1692 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1694 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1695 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1696 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1697 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1698 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1699 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1700 if (MemoryRuntimeCheck) {
1701 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1703 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1705 MemoryRuntimeCheck = IsConflict;
1709 // We have to do this trickery because the IRBuilder might fold the check to a
1710 // constant expression in which case there is no Instruction anchored in a
1712 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1713 ConstantInt::getTrue(Ctx));
1714 ChkBuilder.Insert(Check, "memcheck.conflict");
1715 FirstInst = getFirstInst(FirstInst, Check, Loc);
1716 return std::make_pair(FirstInst, Check);
1719 void InnerLoopVectorizer::createEmptyLoop() {
1721 In this function we generate a new loop. The new loop will contain
1722 the vectorized instructions while the old loop will continue to run the
1725 [ ] <-- vector loop bypass (may consist of multiple blocks).
1728 | [ ] <-- vector pre header.
1732 | [ ]_| <-- vector loop.
1735 >[ ] <--- middle-block.
1738 | [ ] <--- new preheader.
1742 | [ ]_| <-- old scalar loop to handle remainder.
1745 >[ ] <-- exit block.
1749 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1750 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1751 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1752 assert(ExitBlock && "Must have an exit block");
1754 // Some loops have a single integer induction variable, while other loops
1755 // don't. One example is c++ iterators that often have multiple pointer
1756 // induction variables. In the code below we also support a case where we
1757 // don't have a single induction variable.
1758 OldInduction = Legal->getInduction();
1759 Type *IdxTy = Legal->getWidestInductionType();
1761 // Find the loop boundaries.
1762 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1763 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1765 // The exit count might have the type of i64 while the phi is i32. This can
1766 // happen if we have an induction variable that is sign extended before the
1767 // compare. The only way that we get a backedge taken count is that the
1768 // induction variable was signed and as such will not overflow. In such a case
1769 // truncation is legal.
1770 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1771 IdxTy->getPrimitiveSizeInBits())
1772 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1774 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1775 // Get the total trip count from the count by adding 1.
1776 ExitCount = SE->getAddExpr(ExitCount,
1777 SE->getConstant(ExitCount->getType(), 1));
1779 // Expand the trip count and place the new instructions in the preheader.
1780 // Notice that the pre-header does not change, only the loop body.
1781 SCEVExpander Exp(*SE, "induction");
1783 // Count holds the overall loop count (N).
1784 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1785 BypassBlock->getTerminator());
1787 // The loop index does not have to start at Zero. Find the original start
1788 // value from the induction PHI node. If we don't have an induction variable
1789 // then we know that it starts at zero.
1790 Builder.SetInsertPoint(BypassBlock->getTerminator());
1791 Value *StartIdx = ExtendedIdx = OldInduction ?
1792 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1794 ConstantInt::get(IdxTy, 0);
1796 assert(BypassBlock && "Invalid loop structure");
1797 LoopBypassBlocks.push_back(BypassBlock);
1799 // Split the single block loop into the two loop structure described above.
1800 BasicBlock *VectorPH =
1801 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1802 BasicBlock *VecBody =
1803 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1804 BasicBlock *MiddleBlock =
1805 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1806 BasicBlock *ScalarPH =
1807 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1809 // Create and register the new vector loop.
1810 Loop* Lp = new Loop();
1811 Loop *ParentLoop = OrigLoop->getParentLoop();
1813 // Insert the new loop into the loop nest and register the new basic blocks
1814 // before calling any utilities such as SCEV that require valid LoopInfo.
1816 ParentLoop->addChildLoop(Lp);
1817 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1818 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1819 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1821 LI->addTopLevelLoop(Lp);
1823 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1825 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1827 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
1829 // Generate the induction variable.
1830 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1831 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1832 // The loop step is equal to the vectorization factor (num of SIMD elements)
1833 // times the unroll factor (num of SIMD instructions).
1834 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1836 // This is the IR builder that we use to add all of the logic for bypassing
1837 // the new vector loop.
1838 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1839 setDebugLocFromInst(BypassBuilder,
1840 getDebugLocFromInstOrOperands(OldInduction));
1842 // We may need to extend the index in case there is a type mismatch.
1843 // We know that the count starts at zero and does not overflow.
1844 if (Count->getType() != IdxTy) {
1845 // The exit count can be of pointer type. Convert it to the correct
1847 if (ExitCount->getType()->isPointerTy())
1848 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1850 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1853 // Add the start index to the loop count to get the new end index.
1854 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1856 // Now we need to generate the expression for N - (N % VF), which is
1857 // the part that the vectorized body will execute.
1858 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1859 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1860 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1861 "end.idx.rnd.down");
1863 // Now, compare the new count to zero. If it is zero skip the vector loop and
1864 // jump to the scalar loop.
1865 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1868 BasicBlock *LastBypassBlock = BypassBlock;
1870 // Generate the code to check that the strides we assumed to be one are really
1871 // one. We want the new basic block to start at the first instruction in a
1872 // sequence of instructions that form a check.
1873 Instruction *StrideCheck;
1874 Instruction *FirstCheckInst;
1875 tie(FirstCheckInst, StrideCheck) =
1876 addStrideCheck(BypassBlock->getTerminator());
1878 // Create a new block containing the stride check.
1879 BasicBlock *CheckBlock =
1880 BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
1882 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1883 LoopBypassBlocks.push_back(CheckBlock);
1885 // Replace the branch into the memory check block with a conditional branch
1886 // for the "few elements case".
1887 Instruction *OldTerm = BypassBlock->getTerminator();
1888 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1889 OldTerm->eraseFromParent();
1892 LastBypassBlock = CheckBlock;
1895 // Generate the code that checks in runtime if arrays overlap. We put the
1896 // checks into a separate block to make the more common case of few elements
1898 Instruction *MemRuntimeCheck;
1899 tie(FirstCheckInst, MemRuntimeCheck) =
1900 addRuntimeCheck(LastBypassBlock->getTerminator());
1901 if (MemRuntimeCheck) {
1902 // Create a new block containing the memory check.
1903 BasicBlock *CheckBlock =
1904 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
1906 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1907 LoopBypassBlocks.push_back(CheckBlock);
1909 // Replace the branch into the memory check block with a conditional branch
1910 // for the "few elements case".
1911 Instruction *OldTerm = LastBypassBlock->getTerminator();
1912 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1913 OldTerm->eraseFromParent();
1915 Cmp = MemRuntimeCheck;
1916 LastBypassBlock = CheckBlock;
1919 LastBypassBlock->getTerminator()->eraseFromParent();
1920 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1923 // We are going to resume the execution of the scalar loop.
1924 // Go over all of the induction variables that we found and fix the
1925 // PHIs that are left in the scalar version of the loop.
1926 // The starting values of PHI nodes depend on the counter of the last
1927 // iteration in the vectorized loop.
1928 // If we come from a bypass edge then we need to start from the original
1931 // This variable saves the new starting index for the scalar loop.
1932 PHINode *ResumeIndex = 0;
1933 LoopVectorizationLegality::InductionList::iterator I, E;
1934 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1935 // Set builder to point to last bypass block.
1936 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1937 for (I = List->begin(), E = List->end(); I != E; ++I) {
1938 PHINode *OrigPhi = I->first;
1939 LoopVectorizationLegality::InductionInfo II = I->second;
1941 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1942 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1943 MiddleBlock->getTerminator());
1944 // We might have extended the type of the induction variable but we need a
1945 // truncated version for the scalar loop.
1946 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1947 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1948 MiddleBlock->getTerminator()) : 0;
1950 Value *EndValue = 0;
1952 case LoopVectorizationLegality::IK_NoInduction:
1953 llvm_unreachable("Unknown induction");
1954 case LoopVectorizationLegality::IK_IntInduction: {
1955 // Handle the integer induction counter.
1956 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1958 // We have the canonical induction variable.
1959 if (OrigPhi == OldInduction) {
1960 // Create a truncated version of the resume value for the scalar loop,
1961 // we might have promoted the type to a larger width.
1963 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1964 // The new PHI merges the original incoming value, in case of a bypass,
1965 // or the value at the end of the vectorized loop.
1966 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1967 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1968 TruncResumeVal->addIncoming(EndValue, VecBody);
1970 // We know what the end value is.
1971 EndValue = IdxEndRoundDown;
1972 // We also know which PHI node holds it.
1973 ResumeIndex = ResumeVal;
1977 // Not the canonical induction variable - add the vector loop count to the
1979 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1980 II.StartValue->getType(),
1982 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1985 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1986 // Convert the CountRoundDown variable to the PHI size.
1987 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1988 II.StartValue->getType(),
1990 // Handle reverse integer induction counter.
1991 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1994 case LoopVectorizationLegality::IK_PtrInduction: {
1995 // For pointer induction variables, calculate the offset using
1997 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2001 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2002 // The value at the end of the loop for the reverse pointer is calculated
2003 // by creating a GEP with a negative index starting from the start value.
2004 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2005 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2007 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2013 // The new PHI merges the original incoming value, in case of a bypass,
2014 // or the value at the end of the vectorized loop.
2015 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
2016 if (OrigPhi == OldInduction)
2017 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2019 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2021 ResumeVal->addIncoming(EndValue, VecBody);
2023 // Fix the scalar body counter (PHI node).
2024 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2025 // The old inductions phi node in the scalar body needs the truncated value.
2026 if (OrigPhi == OldInduction)
2027 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
2029 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
2032 // If we are generating a new induction variable then we also need to
2033 // generate the code that calculates the exit value. This value is not
2034 // simply the end of the counter because we may skip the vectorized body
2035 // in case of a runtime check.
2037 assert(!ResumeIndex && "Unexpected resume value found");
2038 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2039 MiddleBlock->getTerminator());
2040 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2041 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2042 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2045 // Make sure that we found the index where scalar loop needs to continue.
2046 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2047 "Invalid resume Index");
2049 // Add a check in the middle block to see if we have completed
2050 // all of the iterations in the first vector loop.
2051 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2052 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2053 ResumeIndex, "cmp.n",
2054 MiddleBlock->getTerminator());
2056 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2057 // Remove the old terminator.
2058 MiddleBlock->getTerminator()->eraseFromParent();
2060 // Create i+1 and fill the PHINode.
2061 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2062 Induction->addIncoming(StartIdx, VectorPH);
2063 Induction->addIncoming(NextIdx, VecBody);
2064 // Create the compare.
2065 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2066 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2068 // Now we have two terminators. Remove the old one from the block.
2069 VecBody->getTerminator()->eraseFromParent();
2071 // Get ready to start creating new instructions into the vectorized body.
2072 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2075 LoopVectorPreHeader = VectorPH;
2076 LoopScalarPreHeader = ScalarPH;
2077 LoopMiddleBlock = MiddleBlock;
2078 LoopExitBlock = ExitBlock;
2079 LoopVectorBody = VecBody;
2080 LoopScalarBody = OldBasicBlock;
2082 LoopVectorizeHints Hints(Lp, true);
2083 Hints.setAlreadyVectorized(Lp);
2086 /// This function returns the identity element (or neutral element) for
2087 /// the operation K.
2089 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2094 // Adding, Xoring, Oring zero to a number does not change it.
2095 return ConstantInt::get(Tp, 0);
2096 case RK_IntegerMult:
2097 // Multiplying a number by 1 does not change it.
2098 return ConstantInt::get(Tp, 1);
2100 // AND-ing a number with an all-1 value does not change it.
2101 return ConstantInt::get(Tp, -1, true);
2103 // Multiplying a number by 1 does not change it.
2104 return ConstantFP::get(Tp, 1.0L);
2106 // Adding zero to a number does not change it.
2107 return ConstantFP::get(Tp, 0.0L);
2109 llvm_unreachable("Unknown reduction kind");
2113 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
2114 Intrinsic::ID ValidIntrinsicID) {
2115 if (I.getNumArgOperands() != 1 ||
2116 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2117 I.getType() != I.getArgOperand(0)->getType() ||
2118 !I.onlyReadsMemory())
2119 return Intrinsic::not_intrinsic;
2121 return ValidIntrinsicID;
2124 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
2125 Intrinsic::ID ValidIntrinsicID) {
2126 if (I.getNumArgOperands() != 2 ||
2127 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2128 !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
2129 I.getType() != I.getArgOperand(0)->getType() ||
2130 I.getType() != I.getArgOperand(1)->getType() ||
2131 !I.onlyReadsMemory())
2132 return Intrinsic::not_intrinsic;
2134 return ValidIntrinsicID;
2138 static Intrinsic::ID
2139 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
2140 // If we have an intrinsic call, check if it is trivially vectorizable.
2141 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2142 switch (II->getIntrinsicID()) {
2143 case Intrinsic::sqrt:
2144 case Intrinsic::sin:
2145 case Intrinsic::cos:
2146 case Intrinsic::exp:
2147 case Intrinsic::exp2:
2148 case Intrinsic::log:
2149 case Intrinsic::log10:
2150 case Intrinsic::log2:
2151 case Intrinsic::fabs:
2152 case Intrinsic::copysign:
2153 case Intrinsic::floor:
2154 case Intrinsic::ceil:
2155 case Intrinsic::trunc:
2156 case Intrinsic::rint:
2157 case Intrinsic::nearbyint:
2158 case Intrinsic::round:
2159 case Intrinsic::pow:
2160 case Intrinsic::fma:
2161 case Intrinsic::fmuladd:
2162 case Intrinsic::lifetime_start:
2163 case Intrinsic::lifetime_end:
2164 return II->getIntrinsicID();
2166 return Intrinsic::not_intrinsic;
2171 return Intrinsic::not_intrinsic;
2174 Function *F = CI->getCalledFunction();
2175 // We're going to make assumptions on the semantics of the functions, check
2176 // that the target knows that it's available in this environment and it does
2177 // not have local linkage.
2178 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
2179 return Intrinsic::not_intrinsic;
2181 // Otherwise check if we have a call to a function that can be turned into a
2182 // vector intrinsic.
2189 return checkUnaryFloatSignature(*CI, Intrinsic::sin);
2193 return checkUnaryFloatSignature(*CI, Intrinsic::cos);
2197 return checkUnaryFloatSignature(*CI, Intrinsic::exp);
2199 case LibFunc::exp2f:
2200 case LibFunc::exp2l:
2201 return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
2205 return checkUnaryFloatSignature(*CI, Intrinsic::log);
2206 case LibFunc::log10:
2207 case LibFunc::log10f:
2208 case LibFunc::log10l:
2209 return checkUnaryFloatSignature(*CI, Intrinsic::log10);
2211 case LibFunc::log2f:
2212 case LibFunc::log2l:
2213 return checkUnaryFloatSignature(*CI, Intrinsic::log2);
2215 case LibFunc::fabsf:
2216 case LibFunc::fabsl:
2217 return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
2218 case LibFunc::copysign:
2219 case LibFunc::copysignf:
2220 case LibFunc::copysignl:
2221 return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
2222 case LibFunc::floor:
2223 case LibFunc::floorf:
2224 case LibFunc::floorl:
2225 return checkUnaryFloatSignature(*CI, Intrinsic::floor);
2227 case LibFunc::ceilf:
2228 case LibFunc::ceill:
2229 return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
2230 case LibFunc::trunc:
2231 case LibFunc::truncf:
2232 case LibFunc::truncl:
2233 return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
2235 case LibFunc::rintf:
2236 case LibFunc::rintl:
2237 return checkUnaryFloatSignature(*CI, Intrinsic::rint);
2238 case LibFunc::nearbyint:
2239 case LibFunc::nearbyintf:
2240 case LibFunc::nearbyintl:
2241 return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
2242 case LibFunc::round:
2243 case LibFunc::roundf:
2244 case LibFunc::roundl:
2245 return checkUnaryFloatSignature(*CI, Intrinsic::round);
2249 return checkBinaryFloatSignature(*CI, Intrinsic::pow);
2252 return Intrinsic::not_intrinsic;
2255 /// This function translates the reduction kind to an LLVM binary operator.
2257 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2259 case LoopVectorizationLegality::RK_IntegerAdd:
2260 return Instruction::Add;
2261 case LoopVectorizationLegality::RK_IntegerMult:
2262 return Instruction::Mul;
2263 case LoopVectorizationLegality::RK_IntegerOr:
2264 return Instruction::Or;
2265 case LoopVectorizationLegality::RK_IntegerAnd:
2266 return Instruction::And;
2267 case LoopVectorizationLegality::RK_IntegerXor:
2268 return Instruction::Xor;
2269 case LoopVectorizationLegality::RK_FloatMult:
2270 return Instruction::FMul;
2271 case LoopVectorizationLegality::RK_FloatAdd:
2272 return Instruction::FAdd;
2273 case LoopVectorizationLegality::RK_IntegerMinMax:
2274 return Instruction::ICmp;
2275 case LoopVectorizationLegality::RK_FloatMinMax:
2276 return Instruction::FCmp;
2278 llvm_unreachable("Unknown reduction operation");
2282 Value *createMinMaxOp(IRBuilder<> &Builder,
2283 LoopVectorizationLegality::MinMaxReductionKind RK,
2286 CmpInst::Predicate P = CmpInst::ICMP_NE;
2289 llvm_unreachable("Unknown min/max reduction kind");
2290 case LoopVectorizationLegality::MRK_UIntMin:
2291 P = CmpInst::ICMP_ULT;
2293 case LoopVectorizationLegality::MRK_UIntMax:
2294 P = CmpInst::ICMP_UGT;
2296 case LoopVectorizationLegality::MRK_SIntMin:
2297 P = CmpInst::ICMP_SLT;
2299 case LoopVectorizationLegality::MRK_SIntMax:
2300 P = CmpInst::ICMP_SGT;
2302 case LoopVectorizationLegality::MRK_FloatMin:
2303 P = CmpInst::FCMP_OLT;
2305 case LoopVectorizationLegality::MRK_FloatMax:
2306 P = CmpInst::FCMP_OGT;
2311 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2312 RK == LoopVectorizationLegality::MRK_FloatMax)
2313 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2315 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2317 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2322 struct CSEDenseMapInfo {
2323 static bool canHandle(Instruction *I) {
2324 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2325 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2327 static inline Instruction *getEmptyKey() {
2328 return DenseMapInfo<Instruction *>::getEmptyKey();
2330 static inline Instruction *getTombstoneKey() {
2331 return DenseMapInfo<Instruction *>::getTombstoneKey();
2333 static unsigned getHashValue(Instruction *I) {
2334 assert(canHandle(I) && "Unknown instruction!");
2335 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2336 I->value_op_end()));
2338 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2339 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2340 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2342 return LHS->isIdenticalTo(RHS);
2347 ///\brief Perform cse of induction variable instructions.
2348 static void cse(BasicBlock *BB) {
2349 // Perform simple cse.
2350 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2351 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2352 Instruction *In = I++;
2354 if (!CSEDenseMapInfo::canHandle(In))
2357 // Check if we can replace this instruction with any of the
2358 // visited instructions.
2359 if (Instruction *V = CSEMap.lookup(In)) {
2360 In->replaceAllUsesWith(V);
2361 In->eraseFromParent();
2369 void InnerLoopVectorizer::vectorizeLoop() {
2370 //===------------------------------------------------===//
2372 // Notice: any optimization or new instruction that go
2373 // into the code below should be also be implemented in
2376 //===------------------------------------------------===//
2377 Constant *Zero = Builder.getInt32(0);
2379 // In order to support reduction variables we need to be able to vectorize
2380 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2381 // stages. First, we create a new vector PHI node with no incoming edges.
2382 // We use this value when we vectorize all of the instructions that use the
2383 // PHI. Next, after all of the instructions in the block are complete we
2384 // add the new incoming edges to the PHI. At this point all of the
2385 // instructions in the basic block are vectorized, so we can use them to
2386 // construct the PHI.
2387 PhiVector RdxPHIsToFix;
2389 // Scan the loop in a topological order to ensure that defs are vectorized
2391 LoopBlocksDFS DFS(OrigLoop);
2394 // Vectorize all of the blocks in the original loop.
2395 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2396 be = DFS.endRPO(); bb != be; ++bb)
2397 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2399 // At this point every instruction in the original loop is widened to
2400 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2401 // that we vectorized. The PHI nodes are currently empty because we did
2402 // not want to introduce cycles. Notice that the remaining PHI nodes
2403 // that we need to fix are reduction variables.
2405 // Create the 'reduced' values for each of the induction vars.
2406 // The reduced values are the vector values that we scalarize and combine
2407 // after the loop is finished.
2408 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2410 PHINode *RdxPhi = *it;
2411 assert(RdxPhi && "Unable to recover vectorized PHI");
2413 // Find the reduction variable descriptor.
2414 assert(Legal->getReductionVars()->count(RdxPhi) &&
2415 "Unable to find the reduction variable");
2416 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2417 (*Legal->getReductionVars())[RdxPhi];
2419 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2421 // We need to generate a reduction vector from the incoming scalar.
2422 // To do so, we need to generate the 'identity' vector and override
2423 // one of the elements with the incoming scalar reduction. We need
2424 // to do it in the vector-loop preheader.
2425 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2427 // This is the vector-clone of the value that leaves the loop.
2428 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2429 Type *VecTy = VectorExit[0]->getType();
2431 // Find the reduction identity variable. Zero for addition, or, xor,
2432 // one for multiplication, -1 for And.
2435 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2436 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2437 // MinMax reduction have the start value as their identify.
2439 VectorStart = Identity = RdxDesc.StartValue;
2441 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2446 // Handle other reduction kinds:
2448 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2449 VecTy->getScalarType());
2452 // This vector is the Identity vector where the first element is the
2453 // incoming scalar reduction.
2454 VectorStart = RdxDesc.StartValue;
2456 Identity = ConstantVector::getSplat(VF, Iden);
2458 // This vector is the Identity vector where the first element is the
2459 // incoming scalar reduction.
2460 VectorStart = Builder.CreateInsertElement(Identity,
2461 RdxDesc.StartValue, Zero);
2465 // Fix the vector-loop phi.
2466 // We created the induction variable so we know that the
2467 // preheader is the first entry.
2468 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2470 // Reductions do not have to start at zero. They can start with
2471 // any loop invariant values.
2472 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2473 BasicBlock *Latch = OrigLoop->getLoopLatch();
2474 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2475 VectorParts &Val = getVectorValue(LoopVal);
2476 for (unsigned part = 0; part < UF; ++part) {
2477 // Make sure to add the reduction stat value only to the
2478 // first unroll part.
2479 Value *StartVal = (part == 0) ? VectorStart : Identity;
2480 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2481 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
2484 // Before each round, move the insertion point right between
2485 // the PHIs and the values we are going to write.
2486 // This allows us to write both PHINodes and the extractelement
2488 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2490 VectorParts RdxParts;
2491 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2492 for (unsigned part = 0; part < UF; ++part) {
2493 // This PHINode contains the vectorized reduction variable, or
2494 // the initial value vector, if we bypass the vector loop.
2495 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2496 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2497 Value *StartVal = (part == 0) ? VectorStart : Identity;
2498 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2499 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2500 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
2501 RdxParts.push_back(NewPhi);
2504 // Reduce all of the unrolled parts into a single vector.
2505 Value *ReducedPartRdx = RdxParts[0];
2506 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2507 setDebugLocFromInst(Builder, ReducedPartRdx);
2508 for (unsigned part = 1; part < UF; ++part) {
2509 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2510 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2511 RdxParts[part], ReducedPartRdx,
2514 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2515 ReducedPartRdx, RdxParts[part]);
2519 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2520 // and vector ops, reducing the set of values being computed by half each
2522 assert(isPowerOf2_32(VF) &&
2523 "Reduction emission only supported for pow2 vectors!");
2524 Value *TmpVec = ReducedPartRdx;
2525 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2526 for (unsigned i = VF; i != 1; i >>= 1) {
2527 // Move the upper half of the vector to the lower half.
2528 for (unsigned j = 0; j != i/2; ++j)
2529 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2531 // Fill the rest of the mask with undef.
2532 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2533 UndefValue::get(Builder.getInt32Ty()));
2536 Builder.CreateShuffleVector(TmpVec,
2537 UndefValue::get(TmpVec->getType()),
2538 ConstantVector::get(ShuffleMask),
2541 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2542 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2545 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2548 // The result is in the first element of the vector.
2549 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2550 Builder.getInt32(0));
2553 // Now, we need to fix the users of the reduction variable
2554 // inside and outside of the scalar remainder loop.
2555 // We know that the loop is in LCSSA form. We need to update the
2556 // PHI nodes in the exit blocks.
2557 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2558 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2559 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2560 if (!LCSSAPhi) break;
2562 // All PHINodes need to have a single entry edge, or two if
2563 // we already fixed them.
2564 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2566 // We found our reduction value exit-PHI. Update it with the
2567 // incoming bypass edge.
2568 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2569 // Add an edge coming from the bypass.
2570 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2573 }// end of the LCSSA phi scan.
2575 // Fix the scalar loop reduction variable with the incoming reduction sum
2576 // from the vector body and from the backedge value.
2577 int IncomingEdgeBlockIdx =
2578 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2579 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2580 // Pick the other block.
2581 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2582 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2583 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2584 }// end of for each redux variable.
2588 // Remove redundant induction instructions.
2589 cse(LoopVectorBody);
2592 void InnerLoopVectorizer::fixLCSSAPHIs() {
2593 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2594 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2595 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2596 if (!LCSSAPhi) break;
2597 if (LCSSAPhi->getNumIncomingValues() == 1)
2598 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2603 InnerLoopVectorizer::VectorParts
2604 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2605 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2608 // Look for cached value.
2609 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2610 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2611 if (ECEntryIt != MaskCache.end())
2612 return ECEntryIt->second;
2614 VectorParts SrcMask = createBlockInMask(Src);
2616 // The terminator has to be a branch inst!
2617 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2618 assert(BI && "Unexpected terminator found");
2620 if (BI->isConditional()) {
2621 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2623 if (BI->getSuccessor(0) != Dst)
2624 for (unsigned part = 0; part < UF; ++part)
2625 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2627 for (unsigned part = 0; part < UF; ++part)
2628 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2630 MaskCache[Edge] = EdgeMask;
2634 MaskCache[Edge] = SrcMask;
2638 InnerLoopVectorizer::VectorParts
2639 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2640 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2642 // Loop incoming mask is all-one.
2643 if (OrigLoop->getHeader() == BB) {
2644 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2645 return getVectorValue(C);
2648 // This is the block mask. We OR all incoming edges, and with zero.
2649 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2650 VectorParts BlockMask = getVectorValue(Zero);
2653 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2654 VectorParts EM = createEdgeMask(*it, BB);
2655 for (unsigned part = 0; part < UF; ++part)
2656 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2662 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2663 InnerLoopVectorizer::VectorParts &Entry,
2664 unsigned UF, unsigned VF, PhiVector *PV) {
2665 PHINode* P = cast<PHINode>(PN);
2666 // Handle reduction variables:
2667 if (Legal->getReductionVars()->count(P)) {
2668 for (unsigned part = 0; part < UF; ++part) {
2669 // This is phase one of vectorizing PHIs.
2670 Type *VecTy = (VF == 1) ? PN->getType() :
2671 VectorType::get(PN->getType(), VF);
2672 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2673 LoopVectorBody-> getFirstInsertionPt());
2679 setDebugLocFromInst(Builder, P);
2680 // Check for PHI nodes that are lowered to vector selects.
2681 if (P->getParent() != OrigLoop->getHeader()) {
2682 // We know that all PHIs in non-header blocks are converted into
2683 // selects, so we don't have to worry about the insertion order and we
2684 // can just use the builder.
2685 // At this point we generate the predication tree. There may be
2686 // duplications since this is a simple recursive scan, but future
2687 // optimizations will clean it up.
2689 unsigned NumIncoming = P->getNumIncomingValues();
2691 // Generate a sequence of selects of the form:
2692 // SELECT(Mask3, In3,
2693 // SELECT(Mask2, In2,
2695 for (unsigned In = 0; In < NumIncoming; In++) {
2696 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2698 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2700 for (unsigned part = 0; part < UF; ++part) {
2701 // We might have single edge PHIs (blocks) - use an identity
2702 // 'select' for the first PHI operand.
2704 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2707 // Select between the current value and the previous incoming edge
2708 // based on the incoming mask.
2709 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2710 Entry[part], "predphi");
2716 // This PHINode must be an induction variable.
2717 // Make sure that we know about it.
2718 assert(Legal->getInductionVars()->count(P) &&
2719 "Not an induction variable");
2721 LoopVectorizationLegality::InductionInfo II =
2722 Legal->getInductionVars()->lookup(P);
2725 case LoopVectorizationLegality::IK_NoInduction:
2726 llvm_unreachable("Unknown induction");
2727 case LoopVectorizationLegality::IK_IntInduction: {
2728 assert(P->getType() == II.StartValue->getType() && "Types must match");
2729 Type *PhiTy = P->getType();
2731 if (P == OldInduction) {
2732 // Handle the canonical induction variable. We might have had to
2734 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2736 // Handle other induction variables that are now based on the
2738 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2740 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2741 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2744 Broadcasted = getBroadcastInstrs(Broadcasted);
2745 // After broadcasting the induction variable we need to make the vector
2746 // consecutive by adding 0, 1, 2, etc.
2747 for (unsigned part = 0; part < UF; ++part)
2748 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2751 case LoopVectorizationLegality::IK_ReverseIntInduction:
2752 case LoopVectorizationLegality::IK_PtrInduction:
2753 case LoopVectorizationLegality::IK_ReversePtrInduction:
2754 // Handle reverse integer and pointer inductions.
2755 Value *StartIdx = ExtendedIdx;
2756 // This is the normalized GEP that starts counting at zero.
2757 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2760 // Handle the reverse integer induction variable case.
2761 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2762 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2763 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2765 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2768 // This is a new value so do not hoist it out.
2769 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2770 // After broadcasting the induction variable we need to make the
2771 // vector consecutive by adding ... -3, -2, -1, 0.
2772 for (unsigned part = 0; part < UF; ++part)
2773 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2778 // Handle the pointer induction variable case.
2779 assert(P->getType()->isPointerTy() && "Unexpected type.");
2781 // Is this a reverse induction ptr or a consecutive induction ptr.
2782 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2785 // This is the vector of results. Notice that we don't generate
2786 // vector geps because scalar geps result in better code.
2787 for (unsigned part = 0; part < UF; ++part) {
2789 int EltIndex = (part) * (Reverse ? -1 : 1);
2790 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2793 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2795 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2797 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2799 Entry[part] = SclrGep;
2803 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2804 for (unsigned int i = 0; i < VF; ++i) {
2805 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2806 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2809 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2811 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2813 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2815 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2816 Builder.getInt32(i),
2819 Entry[part] = VecVal;
2825 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2826 // For each instruction in the old loop.
2827 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2828 VectorParts &Entry = WidenMap.get(it);
2829 switch (it->getOpcode()) {
2830 case Instruction::Br:
2831 // Nothing to do for PHIs and BR, since we already took care of the
2832 // loop control flow instructions.
2834 case Instruction::PHI:{
2835 // Vectorize PHINodes.
2836 widenPHIInstruction(it, Entry, UF, VF, PV);
2840 case Instruction::Add:
2841 case Instruction::FAdd:
2842 case Instruction::Sub:
2843 case Instruction::FSub:
2844 case Instruction::Mul:
2845 case Instruction::FMul:
2846 case Instruction::UDiv:
2847 case Instruction::SDiv:
2848 case Instruction::FDiv:
2849 case Instruction::URem:
2850 case Instruction::SRem:
2851 case Instruction::FRem:
2852 case Instruction::Shl:
2853 case Instruction::LShr:
2854 case Instruction::AShr:
2855 case Instruction::And:
2856 case Instruction::Or:
2857 case Instruction::Xor: {
2858 // Just widen binops.
2859 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2860 setDebugLocFromInst(Builder, BinOp);
2861 VectorParts &A = getVectorValue(it->getOperand(0));
2862 VectorParts &B = getVectorValue(it->getOperand(1));
2864 // Use this vector value for all users of the original instruction.
2865 for (unsigned Part = 0; Part < UF; ++Part) {
2866 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2868 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2869 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2870 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2871 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2872 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2874 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2875 VecOp->setIsExact(BinOp->isExact());
2881 case Instruction::Select: {
2883 // If the selector is loop invariant we can create a select
2884 // instruction with a scalar condition. Otherwise, use vector-select.
2885 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2887 setDebugLocFromInst(Builder, it);
2889 // The condition can be loop invariant but still defined inside the
2890 // loop. This means that we can't just use the original 'cond' value.
2891 // We have to take the 'vectorized' value and pick the first lane.
2892 // Instcombine will make this a no-op.
2893 VectorParts &Cond = getVectorValue(it->getOperand(0));
2894 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2895 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2897 Value *ScalarCond = (VF == 1) ? Cond[0] :
2898 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
2900 for (unsigned Part = 0; Part < UF; ++Part) {
2901 Entry[Part] = Builder.CreateSelect(
2902 InvariantCond ? ScalarCond : Cond[Part],
2909 case Instruction::ICmp:
2910 case Instruction::FCmp: {
2911 // Widen compares. Generate vector compares.
2912 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2913 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2914 setDebugLocFromInst(Builder, it);
2915 VectorParts &A = getVectorValue(it->getOperand(0));
2916 VectorParts &B = getVectorValue(it->getOperand(1));
2917 for (unsigned Part = 0; Part < UF; ++Part) {
2920 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2922 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2928 case Instruction::Store:
2929 case Instruction::Load:
2930 vectorizeMemoryInstruction(it);
2932 case Instruction::ZExt:
2933 case Instruction::SExt:
2934 case Instruction::FPToUI:
2935 case Instruction::FPToSI:
2936 case Instruction::FPExt:
2937 case Instruction::PtrToInt:
2938 case Instruction::IntToPtr:
2939 case Instruction::SIToFP:
2940 case Instruction::UIToFP:
2941 case Instruction::Trunc:
2942 case Instruction::FPTrunc:
2943 case Instruction::BitCast: {
2944 CastInst *CI = dyn_cast<CastInst>(it);
2945 setDebugLocFromInst(Builder, it);
2946 /// Optimize the special case where the source is the induction
2947 /// variable. Notice that we can only optimize the 'trunc' case
2948 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2949 /// c. other casts depend on pointer size.
2950 if (CI->getOperand(0) == OldInduction &&
2951 it->getOpcode() == Instruction::Trunc) {
2952 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2954 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2955 for (unsigned Part = 0; Part < UF; ++Part)
2956 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2959 /// Vectorize casts.
2960 Type *DestTy = (VF == 1) ? CI->getType() :
2961 VectorType::get(CI->getType(), VF);
2963 VectorParts &A = getVectorValue(it->getOperand(0));
2964 for (unsigned Part = 0; Part < UF; ++Part)
2965 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2969 case Instruction::Call: {
2970 // Ignore dbg intrinsics.
2971 if (isa<DbgInfoIntrinsic>(it))
2973 setDebugLocFromInst(Builder, it);
2975 Module *M = BB->getParent()->getParent();
2976 CallInst *CI = cast<CallInst>(it);
2977 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2978 assert(ID && "Not an intrinsic call!");
2980 case Intrinsic::lifetime_end:
2981 case Intrinsic::lifetime_start:
2982 scalarizeInstruction(it);
2985 for (unsigned Part = 0; Part < UF; ++Part) {
2986 SmallVector<Value *, 4> Args;
2987 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2988 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2989 Args.push_back(Arg[Part]);
2991 Type *Tys[] = {CI->getType()};
2993 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
2995 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2996 Entry[Part] = Builder.CreateCall(F, Args);
3004 // All other instructions are unsupported. Scalarize them.
3005 scalarizeInstruction(it);
3008 }// end of for_each instr.
3011 void InnerLoopVectorizer::updateAnalysis() {
3012 // Forget the original basic block.
3013 SE->forgetLoop(OrigLoop);
3015 // Update the dominator tree information.
3016 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3017 "Entry does not dominate exit.");
3019 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3020 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3021 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3022 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
3023 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
3024 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
3025 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3026 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3028 DEBUG(DT->verifyDomTree());
3031 /// \brief Check whether it is safe to if-convert this phi node.
3033 /// Phi nodes with constant expressions that can trap are not safe to if
3035 static bool canIfConvertPHINodes(BasicBlock *BB) {
3036 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3037 PHINode *Phi = dyn_cast<PHINode>(I);
3040 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3041 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3048 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3049 if (!EnableIfConversion)
3052 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3054 // A list of pointers that we can safely read and write to.
3055 SmallPtrSet<Value *, 8> SafePointes;
3057 // Collect safe addresses.
3058 for (Loop::block_iterator BI = TheLoop->block_begin(),
3059 BE = TheLoop->block_end(); BI != BE; ++BI) {
3060 BasicBlock *BB = *BI;
3062 if (blockNeedsPredication(BB))
3065 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3066 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3067 SafePointes.insert(LI->getPointerOperand());
3068 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3069 SafePointes.insert(SI->getPointerOperand());
3073 // Collect the blocks that need predication.
3074 BasicBlock *Header = TheLoop->getHeader();
3075 for (Loop::block_iterator BI = TheLoop->block_begin(),
3076 BE = TheLoop->block_end(); BI != BE; ++BI) {
3077 BasicBlock *BB = *BI;
3079 // We don't support switch statements inside loops.
3080 if (!isa<BranchInst>(BB->getTerminator()))
3083 // We must be able to predicate all blocks that need to be predicated.
3084 if (blockNeedsPredication(BB)) {
3085 if (!blockCanBePredicated(BB, SafePointes))
3087 } else if (BB != Header && !canIfConvertPHINodes(BB))
3092 // We can if-convert this loop.
3096 bool LoopVectorizationLegality::canVectorize() {
3097 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3098 // be canonicalized.
3099 if (!TheLoop->getLoopPreheader())
3102 // We can only vectorize innermost loops.
3103 if (TheLoop->getSubLoopsVector().size())
3106 // We must have a single backedge.
3107 if (TheLoop->getNumBackEdges() != 1)
3110 // We must have a single exiting block.
3111 if (!TheLoop->getExitingBlock())
3114 // We need to have a loop header.
3115 DEBUG(dbgs() << "LV: Found a loop: " <<
3116 TheLoop->getHeader()->getName() << '\n');
3118 // Check if we can if-convert non-single-bb loops.
3119 unsigned NumBlocks = TheLoop->getNumBlocks();
3120 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3121 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3125 // ScalarEvolution needs to be able to find the exit count.
3126 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3127 if (ExitCount == SE->getCouldNotCompute()) {
3128 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3132 // Do not loop-vectorize loops with a tiny trip count.
3133 BasicBlock *Latch = TheLoop->getLoopLatch();
3134 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
3135 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
3136 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
3137 "This loop is not worth vectorizing.\n");
3141 // Check if we can vectorize the instructions and CFG in this loop.
3142 if (!canVectorizeInstrs()) {
3143 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3147 // Go over each instruction and look at memory deps.
3148 if (!canVectorizeMemory()) {
3149 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3153 // Collect all of the variables that remain uniform after vectorization.
3154 collectLoopUniforms();
3156 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3157 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3160 // Okay! We can vectorize. At this point we don't have any other mem analysis
3161 // which may limit our maximum vectorization factor, so just return true with
3166 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
3167 if (Ty->isPointerTy())
3168 return DL.getIntPtrType(Ty);
3170 // It is possible that char's or short's overflow when we ask for the loop's
3171 // trip count, work around this by changing the type size.
3172 if (Ty->getScalarSizeInBits() < 32)
3173 return Type::getInt32Ty(Ty->getContext());
3178 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
3179 Ty0 = convertPointerToIntegerType(DL, Ty0);
3180 Ty1 = convertPointerToIntegerType(DL, Ty1);
3181 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3186 /// \brief Check that the instruction has outside loop users and is not an
3187 /// identified reduction variable.
3188 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3189 SmallPtrSet<Value *, 4> &Reductions) {
3190 // Reduction instructions are allowed to have exit users. All other
3191 // instructions must not have external users.
3192 if (!Reductions.count(Inst))
3193 //Check that all of the users of the loop are inside the BB.
3194 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
3196 Instruction *U = cast<Instruction>(*I);
3197 // This user may be a reduction exit value.
3198 if (!TheLoop->contains(U)) {
3199 DEBUG(dbgs() << "LV: Found an outside user for : " << *U << '\n');
3206 bool LoopVectorizationLegality::canVectorizeInstrs() {
3207 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3208 BasicBlock *Header = TheLoop->getHeader();
3210 // Look for the attribute signaling the absence of NaNs.
3211 Function &F = *Header->getParent();
3212 if (F.hasFnAttribute("no-nans-fp-math"))
3213 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3214 AttributeSet::FunctionIndex,
3215 "no-nans-fp-math").getValueAsString() == "true";
3217 // For each block in the loop.
3218 for (Loop::block_iterator bb = TheLoop->block_begin(),
3219 be = TheLoop->block_end(); bb != be; ++bb) {
3221 // Scan the instructions in the block and look for hazards.
3222 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3225 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3226 Type *PhiTy = Phi->getType();
3227 // Check that this PHI type is allowed.
3228 if (!PhiTy->isIntegerTy() &&
3229 !PhiTy->isFloatingPointTy() &&
3230 !PhiTy->isPointerTy()) {
3231 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3235 // If this PHINode is not in the header block, then we know that we
3236 // can convert it to select during if-conversion. No need to check if
3237 // the PHIs in this block are induction or reduction variables.
3238 if (*bb != Header) {
3239 // Check that this instruction has no outside users or is an
3240 // identified reduction value with an outside user.
3241 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3246 // We only allow if-converted PHIs with more than two incoming values.
3247 if (Phi->getNumIncomingValues() != 2) {
3248 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3252 // This is the value coming from the preheader.
3253 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3254 // Check if this is an induction variable.
3255 InductionKind IK = isInductionVariable(Phi);
3257 if (IK_NoInduction != IK) {
3258 // Get the widest type.
3260 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3262 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3264 // Int inductions are special because we only allow one IV.
3265 if (IK == IK_IntInduction) {
3266 // Use the phi node with the widest type as induction. Use the last
3267 // one if there are multiple (no good reason for doing this other
3268 // than it is expedient).
3269 if (!Induction || PhiTy == WidestIndTy)
3273 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3274 Inductions[Phi] = InductionInfo(StartValue, IK);
3276 // Until we explicitly handle the case of an induction variable with
3277 // an outside loop user we have to give up vectorizing this loop.
3278 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3284 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3285 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3288 if (AddReductionVar(Phi, RK_IntegerMult)) {
3289 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3292 if (AddReductionVar(Phi, RK_IntegerOr)) {
3293 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3296 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3297 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3300 if (AddReductionVar(Phi, RK_IntegerXor)) {
3301 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3304 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3305 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3308 if (AddReductionVar(Phi, RK_FloatMult)) {
3309 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3312 if (AddReductionVar(Phi, RK_FloatAdd)) {
3313 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3316 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3317 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3322 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3324 }// end of PHI handling
3326 // We still don't handle functions. However, we can ignore dbg intrinsic
3327 // calls and we do handle certain intrinsic and libm functions.
3328 CallInst *CI = dyn_cast<CallInst>(it);
3329 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3330 DEBUG(dbgs() << "LV: Found a call site.\n");
3334 // Check that the instruction return type is vectorizable.
3335 // Also, we can't vectorize extractelement instructions.
3336 if ((!VectorType::isValidElementType(it->getType()) &&
3337 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3338 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3342 // Check that the stored type is vectorizable.
3343 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3344 Type *T = ST->getValueOperand()->getType();
3345 if (!VectorType::isValidElementType(T))
3347 if (EnableMemAccessVersioning)
3348 collectStridedAcccess(ST);
3351 if (EnableMemAccessVersioning)
3352 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3353 collectStridedAcccess(LI);
3355 // Reduction instructions are allowed to have exit users.
3356 // All other instructions must not have external users.
3357 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3365 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3366 if (Inductions.empty())
3373 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3374 /// return the induction operand of the gep pointer.
3375 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3376 DataLayout *DL, Loop *Lp) {
3377 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3381 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3383 // Check that all of the gep indices are uniform except for our induction
3385 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3386 if (i != InductionOperand &&
3387 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3389 return GEP->getOperand(InductionOperand);
3392 ///\brief Look for a cast use of the passed value.
3393 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3394 Value *UniqueCast = 0;
3395 for (Value::use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); UI != UE;
3397 CastInst *CI = dyn_cast<CastInst>(*UI);
3398 if (CI && CI->getType() == Ty) {
3408 ///\brief Get the stride of a pointer access in a loop.
3409 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3410 /// pointer to the Value, or null otherwise.
3411 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3412 DataLayout *DL, Loop *Lp) {
3413 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3414 if (!PtrTy || PtrTy->isAggregateType())
3417 // Try to remove a gep instruction to make the pointer (actually index at this
3418 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3419 // pointer, otherwise, we are analyzing the index.
3420 Value *OrigPtr = Ptr;
3422 // The size of the pointer access.
3423 int64_t PtrAccessSize = 1;
3425 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3426 const SCEV *V = SE->getSCEV(Ptr);
3430 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3431 V = C->getOperand();
3433 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3437 V = S->getStepRecurrence(*SE);
3441 // Strip off the size of access multiplication if we are still analyzing the
3443 if (OrigPtr == Ptr) {
3444 DL->getTypeAllocSize(PtrTy->getElementType());
3445 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3446 if (M->getOperand(0)->getSCEVType() != scConstant)
3449 const APInt &APStepVal =
3450 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3452 // Huge step value - give up.
3453 if (APStepVal.getBitWidth() > 64)
3456 int64_t StepVal = APStepVal.getSExtValue();
3457 if (PtrAccessSize != StepVal)
3459 V = M->getOperand(1);
3464 Type *StripedOffRecurrenceCast = 0;
3465 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3466 StripedOffRecurrenceCast = C->getType();
3467 V = C->getOperand();
3470 // Look for the loop invariant symbolic value.
3471 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3475 Value *Stride = U->getValue();
3476 if (!Lp->isLoopInvariant(Stride))
3479 // If we have stripped off the recurrence cast we have to make sure that we
3480 // return the value that is used in this loop so that we can replace it later.
3481 if (StripedOffRecurrenceCast)
3482 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3487 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3489 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3490 Ptr = LI->getPointerOperand();
3491 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3492 Ptr = SI->getPointerOperand();
3496 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3500 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3501 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3502 Strides[Ptr] = Stride;
3503 StrideSet.insert(Stride);
3506 void LoopVectorizationLegality::collectLoopUniforms() {
3507 // We now know that the loop is vectorizable!
3508 // Collect variables that will remain uniform after vectorization.
3509 std::vector<Value*> Worklist;
3510 BasicBlock *Latch = TheLoop->getLoopLatch();
3512 // Start with the conditional branch and walk up the block.
3513 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3515 while (Worklist.size()) {
3516 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3517 Worklist.pop_back();
3519 // Look at instructions inside this loop.
3520 // Stop when reaching PHI nodes.
3521 // TODO: we need to follow values all over the loop, not only in this block.
3522 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3525 // This is a known uniform.
3528 // Insert all operands.
3529 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3534 /// \brief Analyses memory accesses in a loop.
3536 /// Checks whether run time pointer checks are needed and builds sets for data
3537 /// dependence checking.
3538 class AccessAnalysis {
3540 /// \brief Read or write access location.
3541 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3542 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3544 /// \brief Set of potential dependent memory accesses.
3545 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3547 AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
3548 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3549 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3551 /// \brief Register a load and whether it is only read from.
3552 void addLoad(Value *Ptr, bool IsReadOnly) {
3553 Accesses.insert(MemAccessInfo(Ptr, false));
3555 ReadOnlyPtr.insert(Ptr);
3558 /// \brief Register a store.
3559 void addStore(Value *Ptr) {
3560 Accesses.insert(MemAccessInfo(Ptr, true));
3563 /// \brief Check whether we can check the pointers at runtime for
3564 /// non-intersection.
3565 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3566 unsigned &NumComparisons, ScalarEvolution *SE,
3567 Loop *TheLoop, ValueToValueMap &Strides,
3568 bool ShouldCheckStride = false);
3570 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3571 /// and builds sets of dependent accesses.
3572 void buildDependenceSets() {
3573 // Process read-write pointers first.
3574 processMemAccesses(false);
3575 // Next, process read pointers.
3576 processMemAccesses(true);
3579 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3581 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3582 void resetDepChecks() { CheckDeps.clear(); }
3584 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3587 typedef SetVector<MemAccessInfo> PtrAccessSet;
3588 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3590 /// \brief Go over all memory access or only the deferred ones if
3591 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3592 /// and build sets of dependency check candidates.
3593 void processMemAccesses(bool UseDeferred);
3595 /// Set of all accesses.
3596 PtrAccessSet Accesses;
3598 /// Set of access to check after all writes have been processed.
3599 PtrAccessSet DeferredAccesses;
3601 /// Map of pointers to last access encountered.
3602 UnderlyingObjToAccessMap ObjToLastAccess;
3604 /// Set of accesses that need a further dependence check.
3605 MemAccessInfoSet CheckDeps;
3607 /// Set of pointers that are read only.
3608 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3610 /// Set of underlying objects already written to.
3611 SmallPtrSet<Value*, 16> WriteObjects;
3615 /// Sets of potentially dependent accesses - members of one set share an
3616 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3617 /// dependence check.
3618 DepCandidates &DepCands;
3620 bool AreAllWritesIdentified;
3621 bool AreAllReadsIdentified;
3622 bool IsRTCheckNeeded;
3625 } // end anonymous namespace
3627 /// \brief Check whether a pointer can participate in a runtime bounds check.
3628 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3630 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3631 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3635 return AR->isAffine();
3638 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3639 /// the address space.
3640 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3641 const Loop *Lp, ValueToValueMap &StridesMap);
3643 bool AccessAnalysis::canCheckPtrAtRT(
3644 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3645 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3646 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3647 // Find pointers with computable bounds. We are going to use this information
3648 // to place a runtime bound check.
3649 unsigned NumReadPtrChecks = 0;
3650 unsigned NumWritePtrChecks = 0;
3651 bool CanDoRT = true;
3653 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3654 // We assign consecutive id to access from different dependence sets.
3655 // Accesses within the same set don't need a runtime check.
3656 unsigned RunningDepId = 1;
3657 DenseMap<Value *, unsigned> DepSetId;
3659 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3661 const MemAccessInfo &Access = *AI;
3662 Value *Ptr = Access.getPointer();
3663 bool IsWrite = Access.getInt();
3665 // Just add write checks if we have both.
3666 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3670 ++NumWritePtrChecks;
3674 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3675 // When we run after a failing dependency check we have to make sure we
3676 // don't have wrapping pointers.
3677 (!ShouldCheckStride ||
3678 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3679 // The id of the dependence set.
3682 if (IsDepCheckNeeded) {
3683 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3684 unsigned &LeaderId = DepSetId[Leader];
3686 LeaderId = RunningDepId++;
3689 // Each access has its own dependence set.
3690 DepId = RunningDepId++;
3692 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3694 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3700 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3701 NumComparisons = 0; // Only one dependence set.
3703 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3704 NumWritePtrChecks - 1));
3707 // If the pointers that we would use for the bounds comparison have different
3708 // address spaces, assume the values aren't directly comparable, so we can't
3709 // use them for the runtime check. We also have to assume they could
3710 // overlap. In the future there should be metadata for whether address spaces
3712 unsigned NumPointers = RtCheck.Pointers.size();
3713 for (unsigned i = 0; i < NumPointers; ++i) {
3714 for (unsigned j = i + 1; j < NumPointers; ++j) {
3715 // Only need to check pointers between two different dependency sets.
3716 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3719 Value *PtrI = RtCheck.Pointers[i];
3720 Value *PtrJ = RtCheck.Pointers[j];
3722 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3723 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3725 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3726 " different address spaces\n");
3735 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3736 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3739 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3740 // We process the set twice: first we process read-write pointers, last we
3741 // process read-only pointers. This allows us to skip dependence tests for
3742 // read-only pointers.
3744 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3745 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3746 const MemAccessInfo &Access = *AI;
3747 Value *Ptr = Access.getPointer();
3748 bool IsWrite = Access.getInt();
3750 DepCands.insert(Access);
3752 // Memorize read-only pointers for later processing and skip them in the
3753 // first round (they need to be checked after we have seen all write
3754 // pointers). Note: we also mark pointer that are not consecutive as
3755 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3756 // second check for "!IsWrite".
3757 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3758 if (!UseDeferred && IsReadOnlyPtr) {
3759 DeferredAccesses.insert(Access);
3763 bool NeedDepCheck = false;
3764 // Check whether there is the possibility of dependency because of
3765 // underlying objects being the same.
3766 typedef SmallVector<Value*, 16> ValueVector;
3767 ValueVector TempObjects;
3768 GetUnderlyingObjects(Ptr, TempObjects, DL);
3769 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3771 Value *UnderlyingObj = *UI;
3773 // If this is a write then it needs to be an identified object. If this a
3774 // read and all writes (so far) are identified function scope objects we
3775 // don't need an identified underlying object but only an Argument (the
3776 // next write is going to invalidate this assumption if it is
3778 // This is a micro-optimization for the case where all writes are
3779 // identified and we have one argument pointer.
3780 // Otherwise, we do need a runtime check.
3781 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3782 (!IsWrite && (!AreAllWritesIdentified ||
3783 !isa<Argument>(UnderlyingObj)) &&
3784 !isIdentifiedObject(UnderlyingObj))) {
3785 DEBUG(dbgs() << "LV: Found an unidentified " <<
3786 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3788 IsRTCheckNeeded = (IsRTCheckNeeded ||
3789 !isIdentifiedObject(UnderlyingObj) ||
3790 !AreAllReadsIdentified);
3793 AreAllWritesIdentified = false;
3795 AreAllReadsIdentified = false;
3798 // If this is a write - check other reads and writes for conflicts. If
3799 // this is a read only check other writes for conflicts (but only if there
3800 // is no other write to the ptr - this is an optimization to catch "a[i] =
3801 // a[i] + " without having to do a dependence check).
3802 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3803 NeedDepCheck = true;
3806 WriteObjects.insert(UnderlyingObj);
3808 // Create sets of pointers connected by shared underlying objects.
3809 UnderlyingObjToAccessMap::iterator Prev =
3810 ObjToLastAccess.find(UnderlyingObj);
3811 if (Prev != ObjToLastAccess.end())
3812 DepCands.unionSets(Access, Prev->second);
3814 ObjToLastAccess[UnderlyingObj] = Access;
3818 CheckDeps.insert(Access);
3823 /// \brief Checks memory dependences among accesses to the same underlying
3824 /// object to determine whether there vectorization is legal or not (and at
3825 /// which vectorization factor).
3827 /// This class works under the assumption that we already checked that memory
3828 /// locations with different underlying pointers are "must-not alias".
3829 /// We use the ScalarEvolution framework to symbolically evalutate access
3830 /// functions pairs. Since we currently don't restructure the loop we can rely
3831 /// on the program order of memory accesses to determine their safety.
3832 /// At the moment we will only deem accesses as safe for:
3833 /// * A negative constant distance assuming program order.
3835 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
3836 /// a[i] = tmp; y = a[i];
3838 /// The latter case is safe because later checks guarantuee that there can't
3839 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
3840 /// the same variable: a header phi can only be an induction or a reduction, a
3841 /// reduction can't have a memory sink, an induction can't have a memory
3842 /// source). This is important and must not be violated (or we have to
3843 /// resort to checking for cycles through memory).
3845 /// * A positive constant distance assuming program order that is bigger
3846 /// than the biggest memory access.
3848 /// tmp = a[i] OR b[i] = x
3849 /// a[i+2] = tmp y = b[i+2];
3851 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3853 /// * Zero distances and all accesses have the same size.
3855 class MemoryDepChecker {
3857 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3858 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3860 MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L)
3861 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
3862 ShouldRetryWithRuntimeCheck(false) {}
3864 /// \brief Register the location (instructions are given increasing numbers)
3865 /// of a write access.
3866 void addAccess(StoreInst *SI) {
3867 Value *Ptr = SI->getPointerOperand();
3868 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3869 InstMap.push_back(SI);
3873 /// \brief Register the location (instructions are given increasing numbers)
3874 /// of a write access.
3875 void addAccess(LoadInst *LI) {
3876 Value *Ptr = LI->getPointerOperand();
3877 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
3878 InstMap.push_back(LI);
3882 /// \brief Check whether the dependencies between the accesses are safe.
3884 /// Only checks sets with elements in \p CheckDeps.
3885 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3886 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
3888 /// \brief The maximum number of bytes of a vector register we can vectorize
3889 /// the accesses safely with.
3890 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
3892 /// \brief In same cases when the dependency check fails we can still
3893 /// vectorize the loop with a dynamic array access check.
3894 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
3897 ScalarEvolution *SE;
3899 const Loop *InnermostLoop;
3901 /// \brief Maps access locations (ptr, read/write) to program order.
3902 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
3904 /// \brief Memory access instructions in program order.
3905 SmallVector<Instruction *, 16> InstMap;
3907 /// \brief The program order index to be used for the next instruction.
3910 // We can access this many bytes in parallel safely.
3911 unsigned MaxSafeDepDistBytes;
3913 /// \brief If we see a non-constant dependence distance we can still try to
3914 /// vectorize this loop with runtime checks.
3915 bool ShouldRetryWithRuntimeCheck;
3917 /// \brief Check whether there is a plausible dependence between the two
3920 /// Access \p A must happen before \p B in program order. The two indices
3921 /// identify the index into the program order map.
3923 /// This function checks whether there is a plausible dependence (or the
3924 /// absence of such can't be proved) between the two accesses. If there is a
3925 /// plausible dependence but the dependence distance is bigger than one
3926 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
3927 /// distance is smaller than any other distance encountered so far).
3928 /// Otherwise, this function returns true signaling a possible dependence.
3929 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
3930 const MemAccessInfo &B, unsigned BIdx,
3931 ValueToValueMap &Strides);
3933 /// \brief Check whether the data dependence could prevent store-load
3935 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
3938 } // end anonymous namespace
3940 static bool isInBoundsGep(Value *Ptr) {
3941 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
3942 return GEP->isInBounds();
3946 /// \brief Check whether the access through \p Ptr has a constant stride.
3947 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3948 const Loop *Lp, ValueToValueMap &StridesMap) {
3949 const Type *Ty = Ptr->getType();
3950 assert(Ty->isPointerTy() && "Unexpected non-ptr");
3952 // Make sure that the pointer does not point to aggregate types.
3953 const PointerType *PtrTy = cast<PointerType>(Ty);
3954 if (PtrTy->getElementType()->isAggregateType()) {
3955 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
3960 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
3962 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3964 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
3965 << *Ptr << " SCEV: " << *PtrScev << "\n");
3969 // The accesss function must stride over the innermost loop.
3970 if (Lp != AR->getLoop()) {
3971 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
3972 *Ptr << " SCEV: " << *PtrScev << "\n");
3975 // The address calculation must not wrap. Otherwise, a dependence could be
3977 // An inbounds getelementptr that is a AddRec with a unit stride
3978 // cannot wrap per definition. The unit stride requirement is checked later.
3979 // An getelementptr without an inbounds attribute and unit stride would have
3980 // to access the pointer value "0" which is undefined behavior in address
3981 // space 0, therefore we can also vectorize this case.
3982 bool IsInBoundsGEP = isInBoundsGep(Ptr);
3983 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
3984 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
3985 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
3986 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
3987 << *Ptr << " SCEV: " << *PtrScev << "\n");
3991 // Check the step is constant.
3992 const SCEV *Step = AR->getStepRecurrence(*SE);
3994 // Calculate the pointer stride and check if it is consecutive.
3995 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3997 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
3998 " SCEV: " << *PtrScev << "\n");
4002 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4003 const APInt &APStepVal = C->getValue()->getValue();
4005 // Huge step value - give up.
4006 if (APStepVal.getBitWidth() > 64)
4009 int64_t StepVal = APStepVal.getSExtValue();
4012 int64_t Stride = StepVal / Size;
4013 int64_t Rem = StepVal % Size;
4017 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4018 // know we can't "wrap around the address space". In case of address space
4019 // zero we know that this won't happen without triggering undefined behavior.
4020 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4021 Stride != 1 && Stride != -1)
4027 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4028 unsigned TypeByteSize) {
4029 // If loads occur at a distance that is not a multiple of a feasible vector
4030 // factor store-load forwarding does not take place.
4031 // Positive dependences might cause troubles because vectorizing them might
4032 // prevent store-load forwarding making vectorized code run a lot slower.
4033 // a[i] = a[i-3] ^ a[i-8];
4034 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4035 // hence on your typical architecture store-load forwarding does not take
4036 // place. Vectorizing in such cases does not make sense.
4037 // Store-load forwarding distance.
4038 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4039 // Maximum vector factor.
4040 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4041 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4042 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4044 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4046 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4047 MaxVFWithoutSLForwardIssues = (vf >>=1);
4052 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4053 DEBUG(dbgs() << "LV: Distance " << Distance <<
4054 " that could cause a store-load forwarding conflict\n");
4058 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4059 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4060 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4064 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4065 const MemAccessInfo &B, unsigned BIdx,
4066 ValueToValueMap &Strides) {
4067 assert (AIdx < BIdx && "Must pass arguments in program order");
4069 Value *APtr = A.getPointer();
4070 Value *BPtr = B.getPointer();
4071 bool AIsWrite = A.getInt();
4072 bool BIsWrite = B.getInt();
4074 // Two reads are independent.
4075 if (!AIsWrite && !BIsWrite)
4078 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4079 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4081 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4082 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4084 const SCEV *Src = AScev;
4085 const SCEV *Sink = BScev;
4087 // If the induction step is negative we have to invert source and sink of the
4089 if (StrideAPtr < 0) {
4092 std::swap(APtr, BPtr);
4093 std::swap(Src, Sink);
4094 std::swap(AIsWrite, BIsWrite);
4095 std::swap(AIdx, BIdx);
4096 std::swap(StrideAPtr, StrideBPtr);
4099 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4101 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4102 << "(Induction step: " << StrideAPtr << ")\n");
4103 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4104 << *InstMap[BIdx] << ": " << *Dist << "\n");
4106 // Need consecutive accesses. We don't want to vectorize
4107 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4108 // the address space.
4109 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4110 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4114 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4116 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4117 ShouldRetryWithRuntimeCheck = true;
4121 Type *ATy = APtr->getType()->getPointerElementType();
4122 Type *BTy = BPtr->getType()->getPointerElementType();
4123 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4125 // Negative distances are not plausible dependencies.
4126 const APInt &Val = C->getValue()->getValue();
4127 if (Val.isNegative()) {
4128 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4129 if (IsTrueDataDependence &&
4130 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4134 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4138 // Write to the same location with the same size.
4139 // Could be improved to assert type sizes are the same (i32 == float, etc).
4143 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4147 assert(Val.isStrictlyPositive() && "Expect a positive value");
4149 // Positive distance bigger than max vectorization factor.
4152 "LV: ReadWrite-Write positive dependency with different types\n");
4156 unsigned Distance = (unsigned) Val.getZExtValue();
4158 // Bail out early if passed-in parameters make vectorization not feasible.
4159 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4160 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4162 // The distance must be bigger than the size needed for a vectorized version
4163 // of the operation and the size of the vectorized operation must not be
4164 // bigger than the currrent maximum size.
4165 if (Distance < 2*TypeByteSize ||
4166 2*TypeByteSize > MaxSafeDepDistBytes ||
4167 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4168 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4169 << Val.getSExtValue() << '\n');
4173 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4174 Distance : MaxSafeDepDistBytes;
4176 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4177 if (IsTrueDataDependence &&
4178 couldPreventStoreLoadForward(Distance, TypeByteSize))
4181 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4182 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4187 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4188 MemAccessInfoSet &CheckDeps,
4189 ValueToValueMap &Strides) {
4191 MaxSafeDepDistBytes = -1U;
4192 while (!CheckDeps.empty()) {
4193 MemAccessInfo CurAccess = *CheckDeps.begin();
4195 // Get the relevant memory access set.
4196 EquivalenceClasses<MemAccessInfo>::iterator I =
4197 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4199 // Check accesses within this set.
4200 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4201 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4203 // Check every access pair.
4205 CheckDeps.erase(*AI);
4206 EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
4208 // Check every accessing instruction pair in program order.
4209 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4210 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4211 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4212 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4213 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4215 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4226 bool LoopVectorizationLegality::canVectorizeMemory() {
4228 typedef SmallVector<Value*, 16> ValueVector;
4229 typedef SmallPtrSet<Value*, 16> ValueSet;
4231 // Holds the Load and Store *instructions*.
4235 // Holds all the different accesses in the loop.
4236 unsigned NumReads = 0;
4237 unsigned NumReadWrites = 0;
4239 PtrRtCheck.Pointers.clear();
4240 PtrRtCheck.Need = false;
4242 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4243 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4246 for (Loop::block_iterator bb = TheLoop->block_begin(),
4247 be = TheLoop->block_end(); bb != be; ++bb) {
4249 // Scan the BB and collect legal loads and stores.
4250 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4253 // If this is a load, save it. If this instruction can read from memory
4254 // but is not a load, then we quit. Notice that we don't handle function
4255 // calls that read or write.
4256 if (it->mayReadFromMemory()) {
4257 // Many math library functions read the rounding mode. We will only
4258 // vectorize a loop if it contains known function calls that don't set
4259 // the flag. Therefore, it is safe to ignore this read from memory.
4260 CallInst *Call = dyn_cast<CallInst>(it);
4261 if (Call && getIntrinsicIDForCall(Call, TLI))
4264 LoadInst *Ld = dyn_cast<LoadInst>(it);
4265 if (!Ld) return false;
4266 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4267 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4270 Loads.push_back(Ld);
4271 DepChecker.addAccess(Ld);
4275 // Save 'store' instructions. Abort if other instructions write to memory.
4276 if (it->mayWriteToMemory()) {
4277 StoreInst *St = dyn_cast<StoreInst>(it);
4278 if (!St) return false;
4279 if (!St->isSimple() && !IsAnnotatedParallel) {
4280 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4283 Stores.push_back(St);
4284 DepChecker.addAccess(St);
4289 // Now we have two lists that hold the loads and the stores.
4290 // Next, we find the pointers that they use.
4292 // Check if we see any stores. If there are no stores, then we don't
4293 // care if the pointers are *restrict*.
4294 if (!Stores.size()) {
4295 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4299 AccessAnalysis::DepCandidates DependentAccesses;
4300 AccessAnalysis Accesses(DL, DependentAccesses);
4302 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4303 // multiple times on the same object. If the ptr is accessed twice, once
4304 // for read and once for write, it will only appear once (on the write
4305 // list). This is okay, since we are going to check for conflicts between
4306 // writes and between reads and writes, but not between reads and reads.
4309 ValueVector::iterator I, IE;
4310 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4311 StoreInst *ST = cast<StoreInst>(*I);
4312 Value* Ptr = ST->getPointerOperand();
4314 if (isUniform(Ptr)) {
4315 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4319 // If we did *not* see this pointer before, insert it to the read-write
4320 // list. At this phase it is only a 'write' list.
4321 if (Seen.insert(Ptr)) {
4323 Accesses.addStore(Ptr);
4327 if (IsAnnotatedParallel) {
4329 << "LV: A loop annotated parallel, ignore memory dependency "
4334 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4335 LoadInst *LD = cast<LoadInst>(*I);
4336 Value* Ptr = LD->getPointerOperand();
4337 // If we did *not* see this pointer before, insert it to the
4338 // read list. If we *did* see it before, then it is already in
4339 // the read-write list. This allows us to vectorize expressions
4340 // such as A[i] += x; Because the address of A[i] is a read-write
4341 // pointer. This only works if the index of A[i] is consecutive.
4342 // If the address of i is unknown (for example A[B[i]]) then we may
4343 // read a few words, modify, and write a few words, and some of the
4344 // words may be written to the same address.
4345 bool IsReadOnlyPtr = false;
4346 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4348 IsReadOnlyPtr = true;
4350 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4353 // If we write (or read-write) to a single destination and there are no
4354 // other reads in this loop then is it safe to vectorize.
4355 if (NumReadWrites == 1 && NumReads == 0) {
4356 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4360 // Build dependence sets and check whether we need a runtime pointer bounds
4362 Accesses.buildDependenceSets();
4363 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4365 // Find pointers with computable bounds. We are going to use this information
4366 // to place a runtime bound check.
4367 unsigned NumComparisons = 0;
4368 bool CanDoRT = false;
4370 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4373 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4374 " pointer comparisons.\n");
4376 // If we only have one set of dependences to check pointers among we don't
4377 // need a runtime check.
4378 if (NumComparisons == 0 && NeedRTCheck)
4379 NeedRTCheck = false;
4381 // Check that we did not collect too many pointers or found an unsizeable
4383 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4389 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4392 if (NeedRTCheck && !CanDoRT) {
4393 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4394 "the array bounds.\n");
4399 PtrRtCheck.Need = NeedRTCheck;
4401 bool CanVecMem = true;
4402 if (Accesses.isDependencyCheckNeeded()) {
4403 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4404 CanVecMem = DepChecker.areDepsSafe(
4405 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4406 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4408 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4409 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4412 // Clear the dependency checks. We assume they are not needed.
4413 Accesses.resetDepChecks();
4416 PtrRtCheck.Need = true;
4418 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4419 TheLoop, Strides, true);
4420 // Check that we did not collect too many pointers or found an unsizeable
4422 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4423 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4432 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4433 " need a runtime memory check.\n");
4438 static bool hasMultipleUsesOf(Instruction *I,
4439 SmallPtrSet<Instruction *, 8> &Insts) {
4440 unsigned NumUses = 0;
4441 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4442 if (Insts.count(dyn_cast<Instruction>(*Use)))
4451 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4452 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4453 if (!Set.count(dyn_cast<Instruction>(*Use)))
4458 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4459 ReductionKind Kind) {
4460 if (Phi->getNumIncomingValues() != 2)
4463 // Reduction variables are only found in the loop header block.
4464 if (Phi->getParent() != TheLoop->getHeader())
4467 // Obtain the reduction start value from the value that comes from the loop
4469 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4471 // ExitInstruction is the single value which is used outside the loop.
4472 // We only allow for a single reduction value to be used outside the loop.
4473 // This includes users of the reduction, variables (which form a cycle
4474 // which ends in the phi node).
4475 Instruction *ExitInstruction = 0;
4476 // Indicates that we found a reduction operation in our scan.
4477 bool FoundReduxOp = false;
4479 // We start with the PHI node and scan for all of the users of this
4480 // instruction. All users must be instructions that can be used as reduction
4481 // variables (such as ADD). We must have a single out-of-block user. The cycle
4482 // must include the original PHI.
4483 bool FoundStartPHI = false;
4485 // To recognize min/max patterns formed by a icmp select sequence, we store
4486 // the number of instruction we saw from the recognized min/max pattern,
4487 // to make sure we only see exactly the two instructions.
4488 unsigned NumCmpSelectPatternInst = 0;
4489 ReductionInstDesc ReduxDesc(false, 0);
4491 SmallPtrSet<Instruction *, 8> VisitedInsts;
4492 SmallVector<Instruction *, 8> Worklist;
4493 Worklist.push_back(Phi);
4494 VisitedInsts.insert(Phi);
4496 // A value in the reduction can be used:
4497 // - By the reduction:
4498 // - Reduction operation:
4499 // - One use of reduction value (safe).
4500 // - Multiple use of reduction value (not safe).
4502 // - All uses of the PHI must be the reduction (safe).
4503 // - Otherwise, not safe.
4504 // - By one instruction outside of the loop (safe).
4505 // - By further instructions outside of the loop (not safe).
4506 // - By an instruction that is not part of the reduction (not safe).
4508 // * An instruction type other than PHI or the reduction operation.
4509 // * A PHI in the header other than the initial PHI.
4510 while (!Worklist.empty()) {
4511 Instruction *Cur = Worklist.back();
4512 Worklist.pop_back();
4515 // If the instruction has no users then this is a broken chain and can't be
4516 // a reduction variable.
4517 if (Cur->use_empty())
4520 bool IsAPhi = isa<PHINode>(Cur);
4522 // A header PHI use other than the original PHI.
4523 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4526 // Reductions of instructions such as Div, and Sub is only possible if the
4527 // LHS is the reduction variable.
4528 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4529 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4530 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4533 // Any reduction instruction must be of one of the allowed kinds.
4534 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4535 if (!ReduxDesc.IsReduction)
4538 // A reduction operation must only have one use of the reduction value.
4539 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4540 hasMultipleUsesOf(Cur, VisitedInsts))
4543 // All inputs to a PHI node must be a reduction value.
4544 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4547 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4548 isa<SelectInst>(Cur)))
4549 ++NumCmpSelectPatternInst;
4550 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4551 isa<SelectInst>(Cur)))
4552 ++NumCmpSelectPatternInst;
4554 // Check whether we found a reduction operator.
4555 FoundReduxOp |= !IsAPhi;
4557 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4558 // onto the stack. This way we are going to have seen all inputs to PHI
4559 // nodes once we get to them.
4560 SmallVector<Instruction *, 8> NonPHIs;
4561 SmallVector<Instruction *, 8> PHIs;
4562 for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
4564 Instruction *Usr = cast<Instruction>(*UI);
4566 // Check if we found the exit user.
4567 BasicBlock *Parent = Usr->getParent();
4568 if (!TheLoop->contains(Parent)) {
4569 // Exit if you find multiple outside users or if the header phi node is
4570 // being used. In this case the user uses the value of the previous
4571 // iteration, in which case we would loose "VF-1" iterations of the
4572 // reduction operation if we vectorize.
4573 if (ExitInstruction != 0 || Cur == Phi)
4576 // The instruction used by an outside user must be the last instruction
4577 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4578 // operations on the value.
4579 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4582 ExitInstruction = Cur;
4586 // Process instructions only once (termination). Each reduction cycle
4587 // value must only be used once, except by phi nodes and min/max
4588 // reductions which are represented as a cmp followed by a select.
4589 ReductionInstDesc IgnoredVal(false, 0);
4590 if (VisitedInsts.insert(Usr)) {
4591 if (isa<PHINode>(Usr))
4592 PHIs.push_back(Usr);
4594 NonPHIs.push_back(Usr);
4595 } else if (!isa<PHINode>(Usr) &&
4596 ((!isa<FCmpInst>(Usr) &&
4597 !isa<ICmpInst>(Usr) &&
4598 !isa<SelectInst>(Usr)) ||
4599 !isMinMaxSelectCmpPattern(Usr, IgnoredVal).IsReduction))
4602 // Remember that we completed the cycle.
4604 FoundStartPHI = true;
4606 Worklist.append(PHIs.begin(), PHIs.end());
4607 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4610 // This means we have seen one but not the other instruction of the
4611 // pattern or more than just a select and cmp.
4612 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4613 NumCmpSelectPatternInst != 2)
4616 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4619 // We found a reduction var if we have reached the original phi node and we
4620 // only have a single instruction with out-of-loop users.
4622 // This instruction is allowed to have out-of-loop users.
4623 AllowedExit.insert(ExitInstruction);
4625 // Save the description of this reduction variable.
4626 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4627 ReduxDesc.MinMaxKind);
4628 Reductions[Phi] = RD;
4629 // We've ended the cycle. This is a reduction variable if we have an
4630 // outside user and it has a binary op.
4635 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4636 /// pattern corresponding to a min(X, Y) or max(X, Y).
4637 LoopVectorizationLegality::ReductionInstDesc
4638 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4639 ReductionInstDesc &Prev) {
4641 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4642 "Expect a select instruction");
4643 Instruction *Cmp = 0;
4644 SelectInst *Select = 0;
4646 // We must handle the select(cmp()) as a single instruction. Advance to the
4648 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4649 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
4650 return ReductionInstDesc(false, I);
4651 return ReductionInstDesc(Select, Prev.MinMaxKind);
4654 // Only handle single use cases for now.
4655 if (!(Select = dyn_cast<SelectInst>(I)))
4656 return ReductionInstDesc(false, I);
4657 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4658 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4659 return ReductionInstDesc(false, I);
4660 if (!Cmp->hasOneUse())
4661 return ReductionInstDesc(false, I);
4666 // Look for a min/max pattern.
4667 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4668 return ReductionInstDesc(Select, MRK_UIntMin);
4669 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4670 return ReductionInstDesc(Select, MRK_UIntMax);
4671 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4672 return ReductionInstDesc(Select, MRK_SIntMax);
4673 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4674 return ReductionInstDesc(Select, MRK_SIntMin);
4675 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4676 return ReductionInstDesc(Select, MRK_FloatMin);
4677 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4678 return ReductionInstDesc(Select, MRK_FloatMax);
4679 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4680 return ReductionInstDesc(Select, MRK_FloatMin);
4681 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4682 return ReductionInstDesc(Select, MRK_FloatMax);
4684 return ReductionInstDesc(false, I);
4687 LoopVectorizationLegality::ReductionInstDesc
4688 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4690 ReductionInstDesc &Prev) {
4691 bool FP = I->getType()->isFloatingPointTy();
4692 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4693 switch (I->getOpcode()) {
4695 return ReductionInstDesc(false, I);
4696 case Instruction::PHI:
4697 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4698 Kind != RK_FloatMinMax))
4699 return ReductionInstDesc(false, I);
4700 return ReductionInstDesc(I, Prev.MinMaxKind);
4701 case Instruction::Sub:
4702 case Instruction::Add:
4703 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4704 case Instruction::Mul:
4705 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4706 case Instruction::And:
4707 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4708 case Instruction::Or:
4709 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4710 case Instruction::Xor:
4711 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4712 case Instruction::FMul:
4713 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4714 case Instruction::FAdd:
4715 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4716 case Instruction::FCmp:
4717 case Instruction::ICmp:
4718 case Instruction::Select:
4719 if (Kind != RK_IntegerMinMax &&
4720 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4721 return ReductionInstDesc(false, I);
4722 return isMinMaxSelectCmpPattern(I, Prev);
4726 LoopVectorizationLegality::InductionKind
4727 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4728 Type *PhiTy = Phi->getType();
4729 // We only handle integer and pointer inductions variables.
4730 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4731 return IK_NoInduction;
4733 // Check that the PHI is consecutive.
4734 const SCEV *PhiScev = SE->getSCEV(Phi);
4735 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4737 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4738 return IK_NoInduction;
4740 const SCEV *Step = AR->getStepRecurrence(*SE);
4742 // Integer inductions need to have a stride of one.
4743 if (PhiTy->isIntegerTy()) {
4745 return IK_IntInduction;
4746 if (Step->isAllOnesValue())
4747 return IK_ReverseIntInduction;
4748 return IK_NoInduction;
4751 // Calculate the pointer stride and check if it is consecutive.
4752 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4754 return IK_NoInduction;
4756 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4757 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4758 if (C->getValue()->equalsInt(Size))
4759 return IK_PtrInduction;
4760 else if (C->getValue()->equalsInt(0 - Size))
4761 return IK_ReversePtrInduction;
4763 return IK_NoInduction;
4766 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4767 Value *In0 = const_cast<Value*>(V);
4768 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4772 return Inductions.count(PN);
4775 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4776 assert(TheLoop->contains(BB) && "Unknown block used");
4778 // Blocks that do not dominate the latch need predication.
4779 BasicBlock* Latch = TheLoop->getLoopLatch();
4780 return !DT->dominates(BB, Latch);
4783 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4784 SmallPtrSet<Value *, 8>& SafePtrs) {
4785 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4786 // We might be able to hoist the load.
4787 if (it->mayReadFromMemory()) {
4788 LoadInst *LI = dyn_cast<LoadInst>(it);
4789 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4793 // We don't predicate stores at the moment.
4794 if (it->mayWriteToMemory() || it->mayThrow())
4797 // Check that we don't have a constant expression that can trap as operand.
4798 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4800 if (Constant *C = dyn_cast<Constant>(*OI))
4805 // The instructions below can trap.
4806 switch (it->getOpcode()) {
4808 case Instruction::UDiv:
4809 case Instruction::SDiv:
4810 case Instruction::URem:
4811 case Instruction::SRem:
4819 LoopVectorizationCostModel::VectorizationFactor
4820 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4822 // Width 1 means no vectorize
4823 VectorizationFactor Factor = { 1U, 0U };
4824 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4825 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4829 // Find the trip count.
4830 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4831 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4833 unsigned WidestType = getWidestType();
4834 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4835 unsigned MaxSafeDepDist = -1U;
4836 if (Legal->getMaxSafeDepDistBytes() != -1U)
4837 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4838 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4839 WidestRegister : MaxSafeDepDist);
4840 unsigned MaxVectorSize = WidestRegister / WidestType;
4841 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4842 DEBUG(dbgs() << "LV: The Widest register is: "
4843 << WidestRegister << " bits.\n");
4845 if (MaxVectorSize == 0) {
4846 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4850 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4851 " into one vector!");
4853 unsigned VF = MaxVectorSize;
4855 // If we optimize the program for size, avoid creating the tail loop.
4857 // If we are unable to calculate the trip count then don't try to vectorize.
4859 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4863 // Find the maximum SIMD width that can fit within the trip count.
4864 VF = TC % MaxVectorSize;
4869 // If the trip count that we found modulo the vectorization factor is not
4870 // zero then we require a tail.
4872 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4878 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4879 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4881 Factor.Width = UserVF;
4885 float Cost = expectedCost(1);
4887 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
4888 for (unsigned i=2; i <= VF; i*=2) {
4889 // Notice that the vector loop needs to be executed less times, so
4890 // we need to divide the cost of the vector loops by the width of
4891 // the vector elements.
4892 float VectorCost = expectedCost(i) / (float)i;
4893 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4894 (int)VectorCost << ".\n");
4895 if (VectorCost < Cost) {
4901 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
4902 Factor.Width = Width;
4903 Factor.Cost = Width * Cost;
4907 unsigned LoopVectorizationCostModel::getWidestType() {
4908 unsigned MaxWidth = 8;
4911 for (Loop::block_iterator bb = TheLoop->block_begin(),
4912 be = TheLoop->block_end(); bb != be; ++bb) {
4913 BasicBlock *BB = *bb;
4915 // For each instruction in the loop.
4916 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4917 Type *T = it->getType();
4919 // Only examine Loads, Stores and PHINodes.
4920 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4923 // Examine PHI nodes that are reduction variables.
4924 if (PHINode *PN = dyn_cast<PHINode>(it))
4925 if (!Legal->getReductionVars()->count(PN))
4928 // Examine the stored values.
4929 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4930 T = ST->getValueOperand()->getType();
4932 // Ignore loaded pointer types and stored pointer types that are not
4933 // consecutive. However, we do want to take consecutive stores/loads of
4934 // pointer vectors into account.
4935 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4938 MaxWidth = std::max(MaxWidth,
4939 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4947 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4950 unsigned LoopCost) {
4952 // -- The unroll heuristics --
4953 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4954 // There are many micro-architectural considerations that we can't predict
4955 // at this level. For example frontend pressure (on decode or fetch) due to
4956 // code size, or the number and capabilities of the execution ports.
4958 // We use the following heuristics to select the unroll factor:
4959 // 1. If the code has reductions the we unroll in order to break the cross
4960 // iteration dependency.
4961 // 2. If the loop is really small then we unroll in order to reduce the loop
4963 // 3. We don't unroll if we think that we will spill registers to memory due
4964 // to the increased register pressure.
4966 // Use the user preference, unless 'auto' is selected.
4970 // When we optimize for size we don't unroll.
4974 // We used the distance for the unroll factor.
4975 if (Legal->getMaxSafeDepDistBytes() != -1U)
4978 // Do not unroll loops with a relatively small trip count.
4979 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
4980 TheLoop->getLoopLatch());
4981 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4984 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4985 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4989 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4990 TargetNumRegisters = ForceTargetNumScalarRegs;
4992 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4993 TargetNumRegisters = ForceTargetNumVectorRegs;
4996 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4997 // We divide by these constants so assume that we have at least one
4998 // instruction that uses at least one register.
4999 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5000 R.NumInstructions = std::max(R.NumInstructions, 1U);
5002 // We calculate the unroll factor using the following formula.
5003 // Subtract the number of loop invariants from the number of available
5004 // registers. These registers are used by all of the unrolled instances.
5005 // Next, divide the remaining registers by the number of registers that is
5006 // required by the loop, in order to estimate how many parallel instances
5007 // fit without causing spills. All of this is rounded down if necessary to be
5008 // a power of two. We want power of two unroll factors to simplify any
5009 // addressing operations or alignment considerations.
5010 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5013 // Clamp the unroll factor ranges to reasonable factors.
5014 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5016 // Check if the user has overridden the unroll max.
5018 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5019 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5021 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5022 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5025 // If we did not calculate the cost for VF (because the user selected the VF)
5026 // then we calculate the cost of VF here.
5028 LoopCost = expectedCost(VF);
5030 // Clamp the calculated UF to be between the 1 and the max unroll factor
5031 // that the target allows.
5032 if (UF > MaxUnrollSize)
5037 // Unroll if we vectorized this loop and there is a reduction that could
5038 // benefit from unrolling.
5039 if (VF > 1 && Legal->getReductionVars()->size()) {
5040 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5044 // We want to unroll tiny loops in order to reduce the loop overhead.
5045 // We assume that the cost overhead is 1 and we use the cost model
5046 // to estimate the cost of the loop and unroll until the cost of the
5047 // loop overhead is about 5% of the cost of the loop.
5048 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5049 if (LoopCost < SmallLoopCost) {
5050 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5051 unsigned NewUF = PowerOf2Floor(SmallLoopCost / LoopCost);
5052 return std::min(NewUF, UF);
5055 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5059 LoopVectorizationCostModel::RegisterUsage
5060 LoopVectorizationCostModel::calculateRegisterUsage() {
5061 // This function calculates the register usage by measuring the highest number
5062 // of values that are alive at a single location. Obviously, this is a very
5063 // rough estimation. We scan the loop in a topological order in order and
5064 // assign a number to each instruction. We use RPO to ensure that defs are
5065 // met before their users. We assume that each instruction that has in-loop
5066 // users starts an interval. We record every time that an in-loop value is
5067 // used, so we have a list of the first and last occurrences of each
5068 // instruction. Next, we transpose this data structure into a multi map that
5069 // holds the list of intervals that *end* at a specific location. This multi
5070 // map allows us to perform a linear search. We scan the instructions linearly
5071 // and record each time that a new interval starts, by placing it in a set.
5072 // If we find this value in the multi-map then we remove it from the set.
5073 // The max register usage is the maximum size of the set.
5074 // We also search for instructions that are defined outside the loop, but are
5075 // used inside the loop. We need this number separately from the max-interval
5076 // usage number because when we unroll, loop-invariant values do not take
5078 LoopBlocksDFS DFS(TheLoop);
5082 R.NumInstructions = 0;
5084 // Each 'key' in the map opens a new interval. The values
5085 // of the map are the index of the 'last seen' usage of the
5086 // instruction that is the key.
5087 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5088 // Maps instruction to its index.
5089 DenseMap<unsigned, Instruction*> IdxToInstr;
5090 // Marks the end of each interval.
5091 IntervalMap EndPoint;
5092 // Saves the list of instruction indices that are used in the loop.
5093 SmallSet<Instruction*, 8> Ends;
5094 // Saves the list of values that are used in the loop but are
5095 // defined outside the loop, such as arguments and constants.
5096 SmallPtrSet<Value*, 8> LoopInvariants;
5099 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5100 be = DFS.endRPO(); bb != be; ++bb) {
5101 R.NumInstructions += (*bb)->size();
5102 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5104 Instruction *I = it;
5105 IdxToInstr[Index++] = I;
5107 // Save the end location of each USE.
5108 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5109 Value *U = I->getOperand(i);
5110 Instruction *Instr = dyn_cast<Instruction>(U);
5112 // Ignore non-instruction values such as arguments, constants, etc.
5113 if (!Instr) continue;
5115 // If this instruction is outside the loop then record it and continue.
5116 if (!TheLoop->contains(Instr)) {
5117 LoopInvariants.insert(Instr);
5121 // Overwrite previous end points.
5122 EndPoint[Instr] = Index;
5128 // Saves the list of intervals that end with the index in 'key'.
5129 typedef SmallVector<Instruction*, 2> InstrList;
5130 DenseMap<unsigned, InstrList> TransposeEnds;
5132 // Transpose the EndPoints to a list of values that end at each index.
5133 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5135 TransposeEnds[it->second].push_back(it->first);
5137 SmallSet<Instruction*, 8> OpenIntervals;
5138 unsigned MaxUsage = 0;
5141 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5142 for (unsigned int i = 0; i < Index; ++i) {
5143 Instruction *I = IdxToInstr[i];
5144 // Ignore instructions that are never used within the loop.
5145 if (!Ends.count(I)) continue;
5147 // Remove all of the instructions that end at this location.
5148 InstrList &List = TransposeEnds[i];
5149 for (unsigned int j=0, e = List.size(); j < e; ++j)
5150 OpenIntervals.erase(List[j]);
5152 // Count the number of live interals.
5153 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5155 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5156 OpenIntervals.size() << '\n');
5158 // Add the current instruction to the list of open intervals.
5159 OpenIntervals.insert(I);
5162 unsigned Invariant = LoopInvariants.size();
5163 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5164 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5165 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5167 R.LoopInvariantRegs = Invariant;
5168 R.MaxLocalUsers = MaxUsage;
5172 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5176 for (Loop::block_iterator bb = TheLoop->block_begin(),
5177 be = TheLoop->block_end(); bb != be; ++bb) {
5178 unsigned BlockCost = 0;
5179 BasicBlock *BB = *bb;
5181 // For each instruction in the old loop.
5182 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5183 // Skip dbg intrinsics.
5184 if (isa<DbgInfoIntrinsic>(it))
5187 unsigned C = getInstructionCost(it, VF);
5189 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5190 VF << " For instruction: " << *it << '\n');
5193 // We assume that if-converted blocks have a 50% chance of being executed.
5194 // When the code is scalar then some of the blocks are avoided due to CF.
5195 // When the code is vectorized we execute all code paths.
5196 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5205 /// \brief Check whether the address computation for a non-consecutive memory
5206 /// access looks like an unlikely candidate for being merged into the indexing
5209 /// We look for a GEP which has one index that is an induction variable and all
5210 /// other indices are loop invariant. If the stride of this access is also
5211 /// within a small bound we decide that this address computation can likely be
5212 /// merged into the addressing mode.
5213 /// In all other cases, we identify the address computation as complex.
5214 static bool isLikelyComplexAddressComputation(Value *Ptr,
5215 LoopVectorizationLegality *Legal,
5216 ScalarEvolution *SE,
5217 const Loop *TheLoop) {
5218 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5222 // We are looking for a gep with all loop invariant indices except for one
5223 // which should be an induction variable.
5224 unsigned NumOperands = Gep->getNumOperands();
5225 for (unsigned i = 1; i < NumOperands; ++i) {
5226 Value *Opd = Gep->getOperand(i);
5227 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5228 !Legal->isInductionVariable(Opd))
5232 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5233 // can likely be merged into the address computation.
5234 unsigned MaxMergeDistance = 64;
5236 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5240 // Check the step is constant.
5241 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5242 // Calculate the pointer stride and check if it is consecutive.
5243 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5247 const APInt &APStepVal = C->getValue()->getValue();
5249 // Huge step value - give up.
5250 if (APStepVal.getBitWidth() > 64)
5253 int64_t StepVal = APStepVal.getSExtValue();
5255 return StepVal > MaxMergeDistance;
5258 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5259 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5265 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5266 // If we know that this instruction will remain uniform, check the cost of
5267 // the scalar version.
5268 if (Legal->isUniformAfterVectorization(I))
5271 Type *RetTy = I->getType();
5272 Type *VectorTy = ToVectorTy(RetTy, VF);
5274 // TODO: We need to estimate the cost of intrinsic calls.
5275 switch (I->getOpcode()) {
5276 case Instruction::GetElementPtr:
5277 // We mark this instruction as zero-cost because the cost of GEPs in
5278 // vectorized code depends on whether the corresponding memory instruction
5279 // is scalarized or not. Therefore, we handle GEPs with the memory
5280 // instruction cost.
5282 case Instruction::Br: {
5283 return TTI.getCFInstrCost(I->getOpcode());
5285 case Instruction::PHI:
5286 //TODO: IF-converted IFs become selects.
5288 case Instruction::Add:
5289 case Instruction::FAdd:
5290 case Instruction::Sub:
5291 case Instruction::FSub:
5292 case Instruction::Mul:
5293 case Instruction::FMul:
5294 case Instruction::UDiv:
5295 case Instruction::SDiv:
5296 case Instruction::FDiv:
5297 case Instruction::URem:
5298 case Instruction::SRem:
5299 case Instruction::FRem:
5300 case Instruction::Shl:
5301 case Instruction::LShr:
5302 case Instruction::AShr:
5303 case Instruction::And:
5304 case Instruction::Or:
5305 case Instruction::Xor: {
5306 // Since we will replace the stride by 1 the multiplication should go away.
5307 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5309 // Certain instructions can be cheaper to vectorize if they have a constant
5310 // second vector operand. One example of this are shifts on x86.
5311 TargetTransformInfo::OperandValueKind Op1VK =
5312 TargetTransformInfo::OK_AnyValue;
5313 TargetTransformInfo::OperandValueKind Op2VK =
5314 TargetTransformInfo::OK_AnyValue;
5316 if (isa<ConstantInt>(I->getOperand(1)))
5317 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5319 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5321 case Instruction::Select: {
5322 SelectInst *SI = cast<SelectInst>(I);
5323 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5324 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5325 Type *CondTy = SI->getCondition()->getType();
5327 CondTy = VectorType::get(CondTy, VF);
5329 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5331 case Instruction::ICmp:
5332 case Instruction::FCmp: {
5333 Type *ValTy = I->getOperand(0)->getType();
5334 VectorTy = ToVectorTy(ValTy, VF);
5335 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5337 case Instruction::Store:
5338 case Instruction::Load: {
5339 StoreInst *SI = dyn_cast<StoreInst>(I);
5340 LoadInst *LI = dyn_cast<LoadInst>(I);
5341 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5343 VectorTy = ToVectorTy(ValTy, VF);
5345 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5346 unsigned AS = SI ? SI->getPointerAddressSpace() :
5347 LI->getPointerAddressSpace();
5348 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5349 // We add the cost of address computation here instead of with the gep
5350 // instruction because only here we know whether the operation is
5353 return TTI.getAddressComputationCost(VectorTy) +
5354 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5356 // Scalarized loads/stores.
5357 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5358 bool Reverse = ConsecutiveStride < 0;
5359 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5360 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5361 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5362 bool IsComplexComputation =
5363 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5365 // The cost of extracting from the value vector and pointer vector.
5366 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5367 for (unsigned i = 0; i < VF; ++i) {
5368 // The cost of extracting the pointer operand.
5369 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5370 // In case of STORE, the cost of ExtractElement from the vector.
5371 // In case of LOAD, the cost of InsertElement into the returned
5373 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5374 Instruction::InsertElement,
5378 // The cost of the scalar loads/stores.
5379 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5380 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5385 // Wide load/stores.
5386 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5387 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5390 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5394 case Instruction::ZExt:
5395 case Instruction::SExt:
5396 case Instruction::FPToUI:
5397 case Instruction::FPToSI:
5398 case Instruction::FPExt:
5399 case Instruction::PtrToInt:
5400 case Instruction::IntToPtr:
5401 case Instruction::SIToFP:
5402 case Instruction::UIToFP:
5403 case Instruction::Trunc:
5404 case Instruction::FPTrunc:
5405 case Instruction::BitCast: {
5406 // We optimize the truncation of induction variable.
5407 // The cost of these is the same as the scalar operation.
5408 if (I->getOpcode() == Instruction::Trunc &&
5409 Legal->isInductionVariable(I->getOperand(0)))
5410 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5411 I->getOperand(0)->getType());
5413 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5414 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5416 case Instruction::Call: {
5417 CallInst *CI = cast<CallInst>(I);
5418 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5419 assert(ID && "Not an intrinsic call!");
5420 Type *RetTy = ToVectorTy(CI->getType(), VF);
5421 SmallVector<Type*, 4> Tys;
5422 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5423 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5424 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5427 // We are scalarizing the instruction. Return the cost of the scalar
5428 // instruction, plus the cost of insert and extract into vector
5429 // elements, times the vector width.
5432 if (!RetTy->isVoidTy() && VF != 1) {
5433 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5435 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5438 // The cost of inserting the results plus extracting each one of the
5440 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5443 // The cost of executing VF copies of the scalar instruction. This opcode
5444 // is unknown. Assume that it is the same as 'mul'.
5445 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5451 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5452 if (Scalar->isVoidTy() || VF == 1)
5454 return VectorType::get(Scalar, VF);
5457 char LoopVectorize::ID = 0;
5458 static const char lv_name[] = "Loop Vectorization";
5459 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5460 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5461 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5462 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5463 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5464 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5465 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5466 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5469 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5470 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5474 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5475 // Check for a store.
5476 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5477 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5479 // Check for a load.
5480 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5481 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5487 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr) {
5488 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5489 // Holds vector parameters or scalars, in case of uniform vals.
5490 SmallVector<VectorParts, 4> Params;
5492 setDebugLocFromInst(Builder, Instr);
5494 // Find all of the vectorized parameters.
5495 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5496 Value *SrcOp = Instr->getOperand(op);
5498 // If we are accessing the old induction variable, use the new one.
5499 if (SrcOp == OldInduction) {
5500 Params.push_back(getVectorValue(SrcOp));
5504 // Try using previously calculated values.
5505 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5507 // If the src is an instruction that appeared earlier in the basic block
5508 // then it should already be vectorized.
5509 if (SrcInst && OrigLoop->contains(SrcInst)) {
5510 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5511 // The parameter is a vector value from earlier.
5512 Params.push_back(WidenMap.get(SrcInst));
5514 // The parameter is a scalar from outside the loop. Maybe even a constant.
5515 VectorParts Scalars;
5516 Scalars.append(UF, SrcOp);
5517 Params.push_back(Scalars);
5521 assert(Params.size() == Instr->getNumOperands() &&
5522 "Invalid number of operands");
5524 // Does this instruction return a value ?
5525 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5527 Value *UndefVec = IsVoidRetTy ? 0 :
5528 UndefValue::get(Instr->getType());
5529 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5530 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5532 // For each vector unroll 'part':
5533 for (unsigned Part = 0; Part < UF; ++Part) {
5534 // For each scalar that we create:
5536 Instruction *Cloned = Instr->clone();
5538 Cloned->setName(Instr->getName() + ".cloned");
5539 // Replace the operands of the cloned instructions with extracted scalars.
5540 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5541 Value *Op = Params[op][Part];
5542 Cloned->setOperand(op, Op);
5545 // Place the cloned scalar in the new loop.
5546 Builder.Insert(Cloned);
5548 // If the original scalar returns a value we need to place it in a vector
5549 // so that future users will be able to use it.
5551 VecResults[Part] = Cloned;
5555 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5556 return scalarizeInstruction(Instr);
5559 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5563 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5567 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5569 // When unrolling and the VF is 1, we only need to add a simple scalar.
5570 Type *ITy = Val->getType();
5571 assert(!ITy->isVectorTy() && "Val must be a scalar");
5572 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5573 return Builder.CreateAdd(Val, C, "induction");