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/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/LoopInfo.h"
61 #include "llvm/Analysis/LoopIterator.h"
62 #include "llvm/Analysis/LoopPass.h"
63 #include "llvm/Analysis/ScalarEvolution.h"
64 #include "llvm/Analysis/ScalarEvolutionExpander.h"
65 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
66 #include "llvm/Analysis/TargetTransformInfo.h"
67 #include "llvm/Analysis/ValueTracking.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/IRBuilder.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/LLVMContext.h"
77 #include "llvm/IR/Module.h"
78 #include "llvm/IR/Type.h"
79 #include "llvm/IR/Value.h"
80 #include "llvm/IR/Verifier.h"
81 #include "llvm/Pass.h"
82 #include "llvm/Support/BranchProbability.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/PatternMatch.h"
86 #include "llvm/Support/ValueHandle.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetLibraryInfo.h"
89 #include "llvm/Transforms/Scalar.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 #include "llvm/Transforms/Utils/Local.h"
96 using namespace llvm::PatternMatch;
98 static cl::opt<unsigned>
99 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
100 cl::desc("Sets the SIMD width. Zero is autoselect."));
102 static cl::opt<unsigned>
103 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
104 cl::desc("Sets the vectorization unroll count. "
105 "Zero is autoselect."));
108 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
109 cl::desc("Enable if-conversion during vectorization."));
111 /// We don't vectorize loops with a known constant trip count below this number.
112 static cl::opt<unsigned>
113 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
115 cl::desc("Don't vectorize loops with a constant "
116 "trip count that is smaller than this "
119 /// This enables versioning on the strides of symbolically striding memory
120 /// accesses in code like the following.
121 /// for (i = 0; i < N; ++i)
122 /// A[i * Stride1] += B[i * Stride2] ...
124 /// Will be roughly translated to
125 /// if (Stride1 == 1 && Stride2 == 1) {
126 /// for (i = 0; i < N; i+=4)
130 static cl::opt<bool> EnableMemAccessVersioning(
131 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
132 cl::desc("Enable symblic stride memory access versioning"));
134 /// We don't unroll loops with a known constant trip count below this number.
135 static const unsigned TinyTripCountUnrollThreshold = 128;
137 /// When performing memory disambiguation checks at runtime do not make more
138 /// than this number of comparisons.
139 static const unsigned RuntimeMemoryCheckThreshold = 8;
141 /// Maximum simd width.
142 static const unsigned MaxVectorWidth = 64;
144 static cl::opt<unsigned> ForceTargetNumScalarRegs(
145 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
146 cl::desc("A flag that overrides the target's number of scalar registers."));
148 static cl::opt<unsigned> ForceTargetNumVectorRegs(
149 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
150 cl::desc("A flag that overrides the target's number of vector registers."));
152 /// Maximum vectorization unroll count.
153 static const unsigned MaxUnrollFactor = 16;
155 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
156 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's max unroll factor for scalar "
160 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
161 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
162 cl::desc("A flag that overrides the target's max unroll factor for "
163 "vectorized loops."));
165 static cl::opt<unsigned> ForceTargetInstructionCost(
166 "force-target-instruction-cost", cl::init(0), cl::Hidden,
167 cl::desc("A flag that overrides the target's expected cost for "
168 "an instruction to a single constant value. Mostly "
169 "useful for getting consistent testing."));
171 static cl::opt<unsigned> SmallLoopCost(
172 "small-loop-cost", cl::init(20), cl::Hidden,
173 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
175 // Runtime unroll loops for load/store throughput.
176 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
177 "enable-loadstore-runtime-unroll", cl::init(false), cl::Hidden,
178 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
180 /// The number of stores in a loop that are allowed to need predication.
181 static cl::opt<unsigned> NumberOfStoresToPredicate(
182 "vectorize-num-stores-pred", cl::init(0), cl::Hidden,
183 cl::desc("Max number of stores to be predicated behind an if."));
185 static cl::opt<bool> EnableCondStoresVectorization(
186 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
187 cl::desc("Enable if predication of stores during vectorization."));
191 // Forward declarations.
192 class LoopVectorizationLegality;
193 class LoopVectorizationCostModel;
195 /// InnerLoopVectorizer vectorizes loops which contain only one basic
196 /// block to a specified vectorization factor (VF).
197 /// This class performs the widening of scalars into vectors, or multiple
198 /// scalars. This class also implements the following features:
199 /// * It inserts an epilogue loop for handling loops that don't have iteration
200 /// counts that are known to be a multiple of the vectorization factor.
201 /// * It handles the code generation for reduction variables.
202 /// * Scalarization (implementation using scalars) of un-vectorizable
204 /// InnerLoopVectorizer does not perform any vectorization-legality
205 /// checks, and relies on the caller to check for the different legality
206 /// aspects. The InnerLoopVectorizer relies on the
207 /// LoopVectorizationLegality class to provide information about the induction
208 /// and reduction variables that were found to a given vectorization factor.
209 class InnerLoopVectorizer {
211 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
212 DominatorTree *DT, DataLayout *DL,
213 const TargetLibraryInfo *TLI, unsigned VecWidth,
214 unsigned UnrollFactor)
215 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
216 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
217 OldInduction(0), WidenMap(UnrollFactor), Legal(0) {}
219 // Perform the actual loop widening (vectorization).
220 void vectorize(LoopVectorizationLegality *L) {
222 // Create a new empty loop. Unlink the old loop and connect the new one.
224 // Widen each instruction in the old loop to a new one in the new loop.
225 // Use the Legality module to find the induction and reduction variables.
227 // Register the new loop and update the analysis passes.
231 virtual ~InnerLoopVectorizer() {}
234 /// A small list of PHINodes.
235 typedef SmallVector<PHINode*, 4> PhiVector;
236 /// When we unroll loops we have multiple vector values for each scalar.
237 /// This data structure holds the unrolled and vectorized values that
238 /// originated from one scalar instruction.
239 typedef SmallVector<Value*, 2> VectorParts;
241 // When we if-convert we need create edge masks. We have to cache values so
242 // that we don't end up with exponential recursion/IR.
243 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
244 VectorParts> EdgeMaskCache;
246 /// \brief Add code that checks at runtime if the accessed arrays overlap.
248 /// Returns a pair of instructions where the first element is the first
249 /// instruction generated in possibly a sequence of instructions and the
250 /// second value is the final comparator value or NULL if no check is needed.
251 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
253 /// \brief Add checks for strides that where assumed to be 1.
255 /// Returns the last check instruction and the first check instruction in the
256 /// pair as (first, last).
257 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
259 /// Create an empty loop, based on the loop ranges of the old loop.
260 void createEmptyLoop();
261 /// Copy and widen the instructions from the old loop.
262 virtual void vectorizeLoop();
264 /// \brief The Loop exit block may have single value PHI nodes where the
265 /// incoming value is 'Undef'. While vectorizing we only handled real values
266 /// that were defined inside the loop. Here we fix the 'undef case'.
270 /// A helper function that computes the predicate of the block BB, assuming
271 /// that the header block of the loop is set to True. It returns the *entry*
272 /// mask for the block BB.
273 VectorParts createBlockInMask(BasicBlock *BB);
274 /// A helper function that computes the predicate of the edge between SRC
276 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
278 /// A helper function to vectorize a single BB within the innermost loop.
279 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
281 /// Vectorize a single PHINode in a block. This method handles the induction
282 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
283 /// arbitrary length vectors.
284 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
285 unsigned UF, unsigned VF, PhiVector *PV);
287 /// Insert the new loop to the loop hierarchy and pass manager
288 /// and update the analysis passes.
289 void updateAnalysis();
291 /// This instruction is un-vectorizable. Implement it as a sequence
292 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
293 /// scalarized instruction behind an if block predicated on the control
294 /// dependence of the instruction.
295 virtual void scalarizeInstruction(Instruction *Instr,
296 bool IfPredicateStore=false);
298 /// Vectorize Load and Store instructions,
299 virtual void vectorizeMemoryInstruction(Instruction *Instr);
301 /// Create a broadcast instruction. This method generates a broadcast
302 /// instruction (shuffle) for loop invariant values and for the induction
303 /// value. If this is the induction variable then we extend it to N, N+1, ...
304 /// this is needed because each iteration in the loop corresponds to a SIMD
306 virtual Value *getBroadcastInstrs(Value *V);
308 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
309 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
310 /// The sequence starts at StartIndex.
311 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
313 /// When we go over instructions in the basic block we rely on previous
314 /// values within the current basic block or on loop invariant values.
315 /// When we widen (vectorize) values we place them in the map. If the values
316 /// are not within the map, they have to be loop invariant, so we simply
317 /// broadcast them into a vector.
318 VectorParts &getVectorValue(Value *V);
320 /// Generate a shuffle sequence that will reverse the vector Vec.
321 virtual Value *reverseVector(Value *Vec);
323 /// This is a helper class that holds the vectorizer state. It maps scalar
324 /// instructions to vector instructions. When the code is 'unrolled' then
325 /// then a single scalar value is mapped to multiple vector parts. The parts
326 /// are stored in the VectorPart type.
328 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
330 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
332 /// \return True if 'Key' is saved in the Value Map.
333 bool has(Value *Key) const { return MapStorage.count(Key); }
335 /// Initializes a new entry in the map. Sets all of the vector parts to the
336 /// save value in 'Val'.
337 /// \return A reference to a vector with splat values.
338 VectorParts &splat(Value *Key, Value *Val) {
339 VectorParts &Entry = MapStorage[Key];
340 Entry.assign(UF, Val);
344 ///\return A reference to the value that is stored at 'Key'.
345 VectorParts &get(Value *Key) {
346 VectorParts &Entry = MapStorage[Key];
349 assert(Entry.size() == UF);
354 /// The unroll factor. Each entry in the map stores this number of vector
358 /// Map storage. We use std::map and not DenseMap because insertions to a
359 /// dense map invalidates its iterators.
360 std::map<Value *, VectorParts> MapStorage;
363 /// The original loop.
365 /// Scev analysis to use.
373 /// Target Library Info.
374 const TargetLibraryInfo *TLI;
376 /// The vectorization SIMD factor to use. Each vector will have this many
381 /// The vectorization unroll factor to use. Each scalar is vectorized to this
382 /// many different vector instructions.
385 /// The builder that we use
388 // --- Vectorization state ---
390 /// The vector-loop preheader.
391 BasicBlock *LoopVectorPreHeader;
392 /// The scalar-loop preheader.
393 BasicBlock *LoopScalarPreHeader;
394 /// Middle Block between the vector and the scalar.
395 BasicBlock *LoopMiddleBlock;
396 ///The ExitBlock of the scalar loop.
397 BasicBlock *LoopExitBlock;
398 ///The vector loop body.
399 SmallVector<BasicBlock *, 4> LoopVectorBody;
400 ///The scalar loop body.
401 BasicBlock *LoopScalarBody;
402 /// A list of all bypass blocks. The first block is the entry of the loop.
403 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
405 /// The new Induction variable which was added to the new block.
407 /// The induction variable of the old basic block.
408 PHINode *OldInduction;
409 /// Holds the extended (to the widest induction type) start index.
411 /// Maps scalars to widened vectors.
413 EdgeMaskCache MaskCache;
415 LoopVectorizationLegality *Legal;
418 class InnerLoopUnroller : public InnerLoopVectorizer {
420 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
421 DominatorTree *DT, DataLayout *DL,
422 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
423 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
426 virtual void scalarizeInstruction(Instruction *Instr, bool IfPredicateStore = false);
427 virtual void vectorizeMemoryInstruction(Instruction *Instr);
428 virtual Value *getBroadcastInstrs(Value *V);
429 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
430 virtual Value *reverseVector(Value *Vec);
433 /// \brief Look for a meaningful debug location on the instruction or it's
435 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
440 if (I->getDebugLoc() != Empty)
443 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
444 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
445 if (OpInst->getDebugLoc() != Empty)
452 /// \brief Set the debug location in the builder using the debug location in the
454 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
455 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
456 B.SetCurrentDebugLocation(Inst->getDebugLoc());
458 B.SetCurrentDebugLocation(DebugLoc());
461 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
462 /// to what vectorization factor.
463 /// This class does not look at the profitability of vectorization, only the
464 /// legality. This class has two main kinds of checks:
465 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
466 /// will change the order of memory accesses in a way that will change the
467 /// correctness of the program.
468 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
469 /// checks for a number of different conditions, such as the availability of a
470 /// single induction variable, that all types are supported and vectorize-able,
471 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
472 /// This class is also used by InnerLoopVectorizer for identifying
473 /// induction variable and the different reduction variables.
474 class LoopVectorizationLegality {
478 unsigned NumPredStores;
480 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
481 DominatorTree *DT, TargetLibraryInfo *TLI)
482 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
483 DT(DT), TLI(TLI), Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
484 MaxSafeDepDistBytes(-1U) {}
486 /// This enum represents the kinds of reductions that we support.
488 RK_NoReduction, ///< Not a reduction.
489 RK_IntegerAdd, ///< Sum of integers.
490 RK_IntegerMult, ///< Product of integers.
491 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
492 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
493 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
494 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
495 RK_FloatAdd, ///< Sum of floats.
496 RK_FloatMult, ///< Product of floats.
497 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
500 /// This enum represents the kinds of inductions that we support.
502 IK_NoInduction, ///< Not an induction variable.
503 IK_IntInduction, ///< Integer induction variable. Step = 1.
504 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
505 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
506 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
509 // This enum represents the kind of minmax reduction.
510 enum MinMaxReductionKind {
520 /// This struct holds information about reduction variables.
521 struct ReductionDescriptor {
522 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
523 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
525 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
526 MinMaxReductionKind MK)
527 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
529 // The starting value of the reduction.
530 // It does not have to be zero!
531 TrackingVH<Value> StartValue;
532 // The instruction who's value is used outside the loop.
533 Instruction *LoopExitInstr;
534 // The kind of the reduction.
536 // If this a min/max reduction the kind of reduction.
537 MinMaxReductionKind MinMaxKind;
540 /// This POD struct holds information about a potential reduction operation.
541 struct ReductionInstDesc {
542 ReductionInstDesc(bool IsRedux, Instruction *I) :
543 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
545 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
546 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
548 // Is this instruction a reduction candidate.
550 // The last instruction in a min/max pattern (select of the select(icmp())
551 // pattern), or the current reduction instruction otherwise.
552 Instruction *PatternLastInst;
553 // If this is a min/max pattern the comparison predicate.
554 MinMaxReductionKind MinMaxKind;
557 /// This struct holds information about the memory runtime legality
558 /// check that a group of pointers do not overlap.
559 struct RuntimePointerCheck {
560 RuntimePointerCheck() : Need(false) {}
562 /// Reset the state of the pointer runtime information.
569 DependencySetId.clear();
572 /// Insert a pointer and calculate the start and end SCEVs.
573 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
574 unsigned DepSetId, ValueToValueMap &Strides);
576 /// This flag indicates if we need to add the runtime check.
578 /// Holds the pointers that we need to check.
579 SmallVector<TrackingVH<Value>, 2> Pointers;
580 /// Holds the pointer value at the beginning of the loop.
581 SmallVector<const SCEV*, 2> Starts;
582 /// Holds the pointer value at the end of the loop.
583 SmallVector<const SCEV*, 2> Ends;
584 /// Holds the information if this pointer is used for writing to memory.
585 SmallVector<bool, 2> IsWritePtr;
586 /// Holds the id of the set of pointers that could be dependent because of a
587 /// shared underlying object.
588 SmallVector<unsigned, 2> DependencySetId;
591 /// A struct for saving information about induction variables.
592 struct InductionInfo {
593 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
594 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
596 TrackingVH<Value> StartValue;
601 /// ReductionList contains the reduction descriptors for all
602 /// of the reductions that were found in the loop.
603 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
605 /// InductionList saves induction variables and maps them to the
606 /// induction descriptor.
607 typedef MapVector<PHINode*, InductionInfo> InductionList;
609 /// Returns true if it is legal to vectorize this loop.
610 /// This does not mean that it is profitable to vectorize this
611 /// loop, only that it is legal to do so.
614 /// Returns the Induction variable.
615 PHINode *getInduction() { return Induction; }
617 /// Returns the reduction variables found in the loop.
618 ReductionList *getReductionVars() { return &Reductions; }
620 /// Returns the induction variables found in the loop.
621 InductionList *getInductionVars() { return &Inductions; }
623 /// Returns the widest induction type.
624 Type *getWidestInductionType() { return WidestIndTy; }
626 /// Returns True if V is an induction variable in this loop.
627 bool isInductionVariable(const Value *V);
629 /// Return true if the block BB needs to be predicated in order for the loop
630 /// to be vectorized.
631 bool blockNeedsPredication(BasicBlock *BB);
633 /// Check if this pointer is consecutive when vectorizing. This happens
634 /// when the last index of the GEP is the induction variable, or that the
635 /// pointer itself is an induction variable.
636 /// This check allows us to vectorize A[idx] into a wide load/store.
638 /// 0 - Stride is unknown or non-consecutive.
639 /// 1 - Address is consecutive.
640 /// -1 - Address is consecutive, and decreasing.
641 int isConsecutivePtr(Value *Ptr);
643 /// Returns true if the value V is uniform within the loop.
644 bool isUniform(Value *V);
646 /// Returns true if this instruction will remain scalar after vectorization.
647 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
649 /// Returns the information that we collected about runtime memory check.
650 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
652 /// This function returns the identity element (or neutral element) for
654 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
656 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
658 bool hasStride(Value *V) { return StrideSet.count(V); }
659 bool mustCheckStrides() { return !StrideSet.empty(); }
660 SmallPtrSet<Value *, 8>::iterator strides_begin() {
661 return StrideSet.begin();
663 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
666 /// Check if a single basic block loop is vectorizable.
667 /// At this point we know that this is a loop with a constant trip count
668 /// and we only need to check individual instructions.
669 bool canVectorizeInstrs();
671 /// When we vectorize loops we may change the order in which
672 /// we read and write from memory. This method checks if it is
673 /// legal to vectorize the code, considering only memory constrains.
674 /// Returns true if the loop is vectorizable
675 bool canVectorizeMemory();
677 /// Return true if we can vectorize this loop using the IF-conversion
679 bool canVectorizeWithIfConvert();
681 /// Collect the variables that need to stay uniform after vectorization.
682 void collectLoopUniforms();
684 /// Return true if all of the instructions in the block can be speculatively
685 /// executed. \p SafePtrs is a list of addresses that are known to be legal
686 /// and we know that we can read from them without segfault.
687 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
689 /// Returns True, if 'Phi' is the kind of reduction variable for type
690 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
691 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
692 /// Returns a struct describing if the instruction 'I' can be a reduction
693 /// variable of type 'Kind'. If the reduction is a min/max pattern of
694 /// select(icmp()) this function advances the instruction pointer 'I' from the
695 /// compare instruction to the select instruction and stores this pointer in
696 /// 'PatternLastInst' member of the returned struct.
697 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
698 ReductionInstDesc &Desc);
699 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
700 /// pattern corresponding to a min(X, Y) or max(X, Y).
701 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
702 ReductionInstDesc &Prev);
703 /// Returns the induction kind of Phi. This function may return NoInduction
704 /// if the PHI is not an induction variable.
705 InductionKind isInductionVariable(PHINode *Phi);
707 /// \brief Collect memory access with loop invariant strides.
709 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
711 void collectStridedAcccess(Value *LoadOrStoreInst);
713 /// The loop that we evaluate.
717 /// DataLayout analysis.
721 /// Target Library Info.
722 TargetLibraryInfo *TLI;
724 // --- vectorization state --- //
726 /// Holds the integer induction variable. This is the counter of the
729 /// Holds the reduction variables.
730 ReductionList Reductions;
731 /// Holds all of the induction variables that we found in the loop.
732 /// Notice that inductions don't need to start at zero and that induction
733 /// variables can be pointers.
734 InductionList Inductions;
735 /// Holds the widest induction type encountered.
738 /// Allowed outside users. This holds the reduction
739 /// vars which can be accessed from outside the loop.
740 SmallPtrSet<Value*, 4> AllowedExit;
741 /// This set holds the variables which are known to be uniform after
743 SmallPtrSet<Instruction*, 4> Uniforms;
744 /// We need to check that all of the pointers in this list are disjoint
746 RuntimePointerCheck PtrRtCheck;
747 /// Can we assume the absence of NaNs.
748 bool HasFunNoNaNAttr;
750 unsigned MaxSafeDepDistBytes;
752 ValueToValueMap Strides;
753 SmallPtrSet<Value *, 8> StrideSet;
756 /// LoopVectorizationCostModel - estimates the expected speedups due to
758 /// In many cases vectorization is not profitable. This can happen because of
759 /// a number of reasons. In this class we mainly attempt to predict the
760 /// expected speedup/slowdowns due to the supported instruction set. We use the
761 /// TargetTransformInfo to query the different backends for the cost of
762 /// different operations.
763 class LoopVectorizationCostModel {
765 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
766 LoopVectorizationLegality *Legal,
767 const TargetTransformInfo &TTI,
768 DataLayout *DL, const TargetLibraryInfo *TLI)
769 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
771 /// Information about vectorization costs
772 struct VectorizationFactor {
773 unsigned Width; // Vector width with best cost
774 unsigned Cost; // Cost of the loop with that width
776 /// \return The most profitable vectorization factor and the cost of that VF.
777 /// This method checks every power of two up to VF. If UserVF is not ZERO
778 /// then this vectorization factor will be selected if vectorization is
780 VectorizationFactor selectVectorizationFactor(bool OptForSize,
783 /// \return The size (in bits) of the widest type in the code that
784 /// needs to be vectorized. We ignore values that remain scalar such as
785 /// 64 bit loop indices.
786 unsigned getWidestType();
788 /// \return The most profitable unroll factor.
789 /// If UserUF is non-zero then this method finds the best unroll-factor
790 /// based on register pressure and other parameters.
791 /// VF and LoopCost are the selected vectorization factor and the cost of the
793 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
796 /// \brief A struct that represents some properties of the register usage
798 struct RegisterUsage {
799 /// Holds the number of loop invariant values that are used in the loop.
800 unsigned LoopInvariantRegs;
801 /// Holds the maximum number of concurrent live intervals in the loop.
802 unsigned MaxLocalUsers;
803 /// Holds the number of instructions in the loop.
804 unsigned NumInstructions;
807 /// \return information about the register usage of the loop.
808 RegisterUsage calculateRegisterUsage();
811 /// Returns the expected execution cost. The unit of the cost does
812 /// not matter because we use the 'cost' units to compare different
813 /// vector widths. The cost that is returned is *not* normalized by
814 /// the factor width.
815 unsigned expectedCost(unsigned VF);
817 /// Returns the execution time cost of an instruction for a given vector
818 /// width. Vector width of one means scalar.
819 unsigned getInstructionCost(Instruction *I, unsigned VF);
821 /// A helper function for converting Scalar types to vector types.
822 /// If the incoming type is void, we return void. If the VF is 1, we return
824 static Type* ToVectorTy(Type *Scalar, unsigned VF);
826 /// Returns whether the instruction is a load or store and will be a emitted
827 /// as a vector operation.
828 bool isConsecutiveLoadOrStore(Instruction *I);
830 /// The loop that we evaluate.
834 /// Loop Info analysis.
836 /// Vectorization legality.
837 LoopVectorizationLegality *Legal;
838 /// Vector target information.
839 const TargetTransformInfo &TTI;
840 /// Target data layout information.
842 /// Target Library Info.
843 const TargetLibraryInfo *TLI;
846 /// Utility class for getting and setting loop vectorizer hints in the form
847 /// of loop metadata.
848 struct LoopVectorizeHints {
849 /// Vectorization width.
851 /// Vectorization unroll factor.
853 /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled)
856 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
857 : Width(VectorizationFactor)
858 , Unroll(DisableUnrolling ? 1 : VectorizationUnroll)
860 , LoopID(L->getLoopID()) {
862 // The command line options override any loop metadata except for when
863 // width == 1 which is used to indicate the loop is already vectorized.
864 if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
865 Width = VectorizationFactor;
866 if (VectorizationUnroll.getNumOccurrences() > 0)
867 Unroll = VectorizationUnroll;
869 DEBUG(if (DisableUnrolling && Unroll == 1)
870 dbgs() << "LV: Unrolling disabled by the pass manager\n");
873 /// Return the loop vectorizer metadata prefix.
874 static StringRef Prefix() { return "llvm.vectorizer."; }
876 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
877 SmallVector<Value*, 2> Vals;
878 Vals.push_back(MDString::get(Context, Name));
879 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
880 return MDNode::get(Context, Vals);
883 /// Mark the loop L as already vectorized by setting the width to 1.
884 void setAlreadyVectorized(Loop *L) {
885 LLVMContext &Context = L->getHeader()->getContext();
889 // Create a new loop id with one more operand for the already_vectorized
890 // hint. If the loop already has a loop id then copy the existing operands.
891 SmallVector<Value*, 4> Vals(1);
893 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
894 Vals.push_back(LoopID->getOperand(i));
896 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
897 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
899 MDNode *NewLoopID = MDNode::get(Context, Vals);
900 // Set operand 0 to refer to the loop id itself.
901 NewLoopID->replaceOperandWith(0, NewLoopID);
903 L->setLoopID(NewLoopID);
905 LoopID->replaceAllUsesWith(NewLoopID);
913 /// Find hints specified in the loop metadata.
914 void getHints(const Loop *L) {
918 // First operand should refer to the loop id itself.
919 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
920 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
922 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
923 const MDString *S = 0;
924 SmallVector<Value*, 4> Args;
926 // The expected hint is either a MDString or a MDNode with the first
927 // operand a MDString.
928 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
929 if (!MD || MD->getNumOperands() == 0)
931 S = dyn_cast<MDString>(MD->getOperand(0));
932 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
933 Args.push_back(MD->getOperand(i));
935 S = dyn_cast<MDString>(LoopID->getOperand(i));
936 assert(Args.size() == 0 && "too many arguments for MDString");
942 // Check if the hint starts with the vectorizer prefix.
943 StringRef Hint = S->getString();
944 if (!Hint.startswith(Prefix()))
946 // Remove the prefix.
947 Hint = Hint.substr(Prefix().size(), StringRef::npos);
949 if (Args.size() == 1)
950 getHint(Hint, Args[0]);
954 // Check string hint with one operand.
955 void getHint(StringRef Hint, Value *Arg) {
956 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
958 unsigned Val = C->getZExtValue();
960 if (Hint == "width") {
961 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
964 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
965 } else if (Hint == "unroll") {
966 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
969 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
970 } else if (Hint == "enable") {
971 if (C->getBitWidth() == 1)
974 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
976 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
981 static void addInnerLoop(Loop *L, SmallVectorImpl<Loop *> &V) {
983 return V.push_back(L);
985 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
989 /// The LoopVectorize Pass.
990 struct LoopVectorize : public FunctionPass {
991 /// Pass identification, replacement for typeid
994 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
996 DisableUnrolling(NoUnrolling),
997 AlwaysVectorize(AlwaysVectorize) {
998 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1001 ScalarEvolution *SE;
1004 TargetTransformInfo *TTI;
1006 BlockFrequencyInfo *BFI;
1007 TargetLibraryInfo *TLI;
1008 bool DisableUnrolling;
1009 bool AlwaysVectorize;
1011 BlockFrequency ColdEntryFreq;
1013 virtual bool runOnFunction(Function &F) {
1014 SE = &getAnalysis<ScalarEvolution>();
1015 DL = getAnalysisIfAvailable<DataLayout>();
1016 LI = &getAnalysis<LoopInfo>();
1017 TTI = &getAnalysis<TargetTransformInfo>();
1018 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1019 BFI = &getAnalysis<BlockFrequencyInfo>();
1020 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1022 // Compute some weights outside of the loop over the loops. Compute this
1023 // using a BranchProbability to re-use its scaling math.
1024 const BranchProbability ColdProb(1, 5); // 20%
1025 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1027 // If the target claims to have no vector registers don't attempt
1029 if (!TTI->getNumberOfRegisters(true))
1033 DEBUG(dbgs() << "LV: Not vectorizing: Missing data layout\n");
1037 // Build up a worklist of inner-loops to vectorize. This is necessary as
1038 // the act of vectorizing or partially unrolling a loop creates new loops
1039 // and can invalidate iterators across the loops.
1040 SmallVector<Loop *, 8> Worklist;
1042 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
1043 addInnerLoop(*I, Worklist);
1045 // Now walk the identified inner loops.
1046 bool Changed = false;
1047 while (!Worklist.empty())
1048 Changed |= processLoop(Worklist.pop_back_val());
1050 // Process each loop nest in the function.
1054 bool processLoop(Loop *L) {
1055 // We only handle inner loops, so if there are children just recurse.
1057 bool Changed = false;
1058 for (Loop::iterator I = L->begin(), E = L->begin(); I != E; ++I)
1059 Changed |= processLoop(*I);
1063 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
1064 L->getHeader()->getParent()->getName() << "\"\n");
1066 LoopVectorizeHints Hints(L, DisableUnrolling);
1068 if (Hints.Force == 0) {
1069 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1073 if (!AlwaysVectorize && Hints.Force != 1) {
1074 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1078 if (Hints.Width == 1 && Hints.Unroll == 1) {
1079 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1083 // Check if it is legal to vectorize the loop.
1084 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1085 if (!LVL.canVectorize()) {
1086 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1090 // Use the cost model.
1091 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1093 // Check the function attributes to find out if this function should be
1094 // optimized for size.
1095 Function *F = L->getHeader()->getParent();
1097 Hints.Force != 1 && F->hasFnAttribute(Attribute::OptimizeForSize);
1099 // Compute the weighted frequency of this loop being executed and see if it
1100 // is less than 20% of the function entry baseline frequency. Note that we
1101 // always have a canonical loop here because we think we *can* vectoriez.
1102 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1103 if (Hints.Force != 1 && LoopEntryFreq < ColdEntryFreq)
1106 // Check the function attributes to see if implicit floats are allowed.a
1107 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1108 // an integer loop and the vector instructions selected are purely integer
1109 // vector instructions?
1110 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1111 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1112 "attribute is used.\n");
1116 // Select the optimal vectorization factor.
1117 LoopVectorizationCostModel::VectorizationFactor VF;
1118 VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
1119 // Select the unroll factor.
1120 unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
1123 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
1124 F->getParent()->getModuleIdentifier() << '\n');
1125 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1127 if (VF.Width == 1) {
1128 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1131 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1132 // We decided not to vectorize, but we may want to unroll.
1133 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1134 Unroller.vectorize(&LVL);
1136 // If we decided that it is *legal* to vectorize the loop then do it.
1137 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1141 // Mark the loop as already vectorized to avoid vectorizing again.
1142 Hints.setAlreadyVectorized(L);
1144 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1149 AU.addRequiredID(LoopSimplifyID);
1150 AU.addRequiredID(LCSSAID);
1151 AU.addRequired<BlockFrequencyInfo>();
1152 AU.addRequired<DominatorTreeWrapperPass>();
1153 AU.addRequired<LoopInfo>();
1154 AU.addRequired<ScalarEvolution>();
1155 AU.addRequired<TargetTransformInfo>();
1156 AU.addPreserved<LoopInfo>();
1157 AU.addPreserved<DominatorTreeWrapperPass>();
1162 } // end anonymous namespace
1164 //===----------------------------------------------------------------------===//
1165 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1166 // LoopVectorizationCostModel.
1167 //===----------------------------------------------------------------------===//
1169 static Value *stripIntegerCast(Value *V) {
1170 if (CastInst *CI = dyn_cast<CastInst>(V))
1171 if (CI->getOperand(0)->getType()->isIntegerTy())
1172 return CI->getOperand(0);
1176 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1178 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1180 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1181 ValueToValueMap &PtrToStride,
1182 Value *Ptr, Value *OrigPtr = 0) {
1184 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1186 // If there is an entry in the map return the SCEV of the pointer with the
1187 // symbolic stride replaced by one.
1188 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1189 if (SI != PtrToStride.end()) {
1190 Value *StrideVal = SI->second;
1193 StrideVal = stripIntegerCast(StrideVal);
1195 // Replace symbolic stride by one.
1196 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1197 ValueToValueMap RewriteMap;
1198 RewriteMap[StrideVal] = One;
1201 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1202 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1207 // Otherwise, just return the SCEV of the original pointer.
1208 return SE->getSCEV(Ptr);
1211 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1212 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1213 ValueToValueMap &Strides) {
1214 // Get the stride replaced scev.
1215 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1216 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1217 assert(AR && "Invalid addrec expression");
1218 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1219 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1220 Pointers.push_back(Ptr);
1221 Starts.push_back(AR->getStart());
1222 Ends.push_back(ScEnd);
1223 IsWritePtr.push_back(WritePtr);
1224 DependencySetId.push_back(DepSetId);
1227 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1228 // We need to place the broadcast of invariant variables outside the loop.
1229 Instruction *Instr = dyn_cast<Instruction>(V);
1231 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1232 Instr->getParent()) != LoopVectorBody.end());
1233 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1235 // Place the code for broadcasting invariant variables in the new preheader.
1236 IRBuilder<>::InsertPointGuard Guard(Builder);
1238 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1240 // Broadcast the scalar into all locations in the vector.
1241 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1246 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1248 assert(Val->getType()->isVectorTy() && "Must be a vector");
1249 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1250 "Elem must be an integer");
1251 // Create the types.
1252 Type *ITy = Val->getType()->getScalarType();
1253 VectorType *Ty = cast<VectorType>(Val->getType());
1254 int VLen = Ty->getNumElements();
1255 SmallVector<Constant*, 8> Indices;
1257 // Create a vector of consecutive numbers from zero to VF.
1258 for (int i = 0; i < VLen; ++i) {
1259 int64_t Idx = Negate ? (-i) : i;
1260 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1263 // Add the consecutive indices to the vector value.
1264 Constant *Cv = ConstantVector::get(Indices);
1265 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1266 return Builder.CreateAdd(Val, Cv, "induction");
1269 /// \brief Find the operand of the GEP that should be checked for consecutive
1270 /// stores. This ignores trailing indices that have no effect on the final
1272 static unsigned getGEPInductionOperand(DataLayout *DL,
1273 const GetElementPtrInst *Gep) {
1274 unsigned LastOperand = Gep->getNumOperands() - 1;
1275 unsigned GEPAllocSize = DL->getTypeAllocSize(
1276 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1278 // Walk backwards and try to peel off zeros.
1279 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1280 // Find the type we're currently indexing into.
1281 gep_type_iterator GEPTI = gep_type_begin(Gep);
1282 std::advance(GEPTI, LastOperand - 1);
1284 // If it's a type with the same allocation size as the result of the GEP we
1285 // can peel off the zero index.
1286 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1294 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1295 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1296 // Make sure that the pointer does not point to structs.
1297 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1300 // If this value is a pointer induction variable we know it is consecutive.
1301 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1302 if (Phi && Inductions.count(Phi)) {
1303 InductionInfo II = Inductions[Phi];
1304 if (IK_PtrInduction == II.IK)
1306 else if (IK_ReversePtrInduction == II.IK)
1310 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1314 unsigned NumOperands = Gep->getNumOperands();
1315 Value *GpPtr = Gep->getPointerOperand();
1316 // If this GEP value is a consecutive pointer induction variable and all of
1317 // the indices are constant then we know it is consecutive. We can
1318 Phi = dyn_cast<PHINode>(GpPtr);
1319 if (Phi && Inductions.count(Phi)) {
1321 // Make sure that the pointer does not point to structs.
1322 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1323 if (GepPtrType->getElementType()->isAggregateType())
1326 // Make sure that all of the index operands are loop invariant.
1327 for (unsigned i = 1; i < NumOperands; ++i)
1328 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1331 InductionInfo II = Inductions[Phi];
1332 if (IK_PtrInduction == II.IK)
1334 else if (IK_ReversePtrInduction == II.IK)
1338 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1340 // Check that all of the gep indices are uniform except for our induction
1342 for (unsigned i = 0; i != NumOperands; ++i)
1343 if (i != InductionOperand &&
1344 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1347 // We can emit wide load/stores only if the last non-zero index is the
1348 // induction variable.
1349 const SCEV *Last = 0;
1350 if (!Strides.count(Gep))
1351 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1353 // Because of the multiplication by a stride we can have a s/zext cast.
1354 // We are going to replace this stride by 1 so the cast is safe to ignore.
1356 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1357 // %0 = trunc i64 %indvars.iv to i32
1358 // %mul = mul i32 %0, %Stride1
1359 // %idxprom = zext i32 %mul to i64 << Safe cast.
1360 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1362 Last = replaceSymbolicStrideSCEV(SE, Strides,
1363 Gep->getOperand(InductionOperand), Gep);
1364 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1366 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1370 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1371 const SCEV *Step = AR->getStepRecurrence(*SE);
1373 // The memory is consecutive because the last index is consecutive
1374 // and all other indices are loop invariant.
1377 if (Step->isAllOnesValue())
1384 bool LoopVectorizationLegality::isUniform(Value *V) {
1385 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1388 InnerLoopVectorizer::VectorParts&
1389 InnerLoopVectorizer::getVectorValue(Value *V) {
1390 assert(V != Induction && "The new induction variable should not be used.");
1391 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1393 // If we have a stride that is replaced by one, do it here.
1394 if (Legal->hasStride(V))
1395 V = ConstantInt::get(V->getType(), 1);
1397 // If we have this scalar in the map, return it.
1398 if (WidenMap.has(V))
1399 return WidenMap.get(V);
1401 // If this scalar is unknown, assume that it is a constant or that it is
1402 // loop invariant. Broadcast V and save the value for future uses.
1403 Value *B = getBroadcastInstrs(V);
1404 return WidenMap.splat(V, B);
1407 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1408 assert(Vec->getType()->isVectorTy() && "Invalid type");
1409 SmallVector<Constant*, 8> ShuffleMask;
1410 for (unsigned i = 0; i < VF; ++i)
1411 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1413 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1414 ConstantVector::get(ShuffleMask),
1418 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1419 // Attempt to issue a wide load.
1420 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1421 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1423 assert((LI || SI) && "Invalid Load/Store instruction");
1425 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1426 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1427 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1428 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1429 // An alignment of 0 means target abi alignment. We need to use the scalar's
1430 // target abi alignment in such a case.
1432 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1433 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1434 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1435 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1437 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1438 return scalarizeInstruction(Instr, true);
1440 if (ScalarAllocatedSize != VectorElementSize)
1441 return scalarizeInstruction(Instr);
1443 // If the pointer is loop invariant or if it is non-consecutive,
1444 // scalarize the load.
1445 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1446 bool Reverse = ConsecutiveStride < 0;
1447 bool UniformLoad = LI && Legal->isUniform(Ptr);
1448 if (!ConsecutiveStride || UniformLoad)
1449 return scalarizeInstruction(Instr);
1451 Constant *Zero = Builder.getInt32(0);
1452 VectorParts &Entry = WidenMap.get(Instr);
1454 // Handle consecutive loads/stores.
1455 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1456 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1457 setDebugLocFromInst(Builder, Gep);
1458 Value *PtrOperand = Gep->getPointerOperand();
1459 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1460 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1462 // Create the new GEP with the new induction variable.
1463 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1464 Gep2->setOperand(0, FirstBasePtr);
1465 Gep2->setName("gep.indvar.base");
1466 Ptr = Builder.Insert(Gep2);
1468 setDebugLocFromInst(Builder, Gep);
1469 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1470 OrigLoop) && "Base ptr must be invariant");
1472 // The last index does not have to be the induction. It can be
1473 // consecutive and be a function of the index. For example A[I+1];
1474 unsigned NumOperands = Gep->getNumOperands();
1475 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1476 // Create the new GEP with the new induction variable.
1477 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1479 for (unsigned i = 0; i < NumOperands; ++i) {
1480 Value *GepOperand = Gep->getOperand(i);
1481 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1483 // Update last index or loop invariant instruction anchored in loop.
1484 if (i == InductionOperand ||
1485 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1486 assert((i == InductionOperand ||
1487 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1488 "Must be last index or loop invariant");
1490 VectorParts &GEPParts = getVectorValue(GepOperand);
1491 Value *Index = GEPParts[0];
1492 Index = Builder.CreateExtractElement(Index, Zero);
1493 Gep2->setOperand(i, Index);
1494 Gep2->setName("gep.indvar.idx");
1497 Ptr = Builder.Insert(Gep2);
1499 // Use the induction element ptr.
1500 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1501 setDebugLocFromInst(Builder, Ptr);
1502 VectorParts &PtrVal = getVectorValue(Ptr);
1503 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1508 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1509 "We do not allow storing to uniform addresses");
1510 setDebugLocFromInst(Builder, SI);
1511 // We don't want to update the value in the map as it might be used in
1512 // another expression. So don't use a reference type for "StoredVal".
1513 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1515 for (unsigned Part = 0; Part < UF; ++Part) {
1516 // Calculate the pointer for the specific unroll-part.
1517 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1520 // If we store to reverse consecutive memory locations then we need
1521 // to reverse the order of elements in the stored value.
1522 StoredVal[Part] = reverseVector(StoredVal[Part]);
1523 // If the address is consecutive but reversed, then the
1524 // wide store needs to start at the last vector element.
1525 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1526 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1529 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1530 DataTy->getPointerTo(AddressSpace));
1531 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1537 assert(LI && "Must have a load instruction");
1538 setDebugLocFromInst(Builder, LI);
1539 for (unsigned Part = 0; Part < UF; ++Part) {
1540 // Calculate the pointer for the specific unroll-part.
1541 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1544 // If the address is consecutive but reversed, then the
1545 // wide store needs to start at the last vector element.
1546 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1547 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1550 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1551 DataTy->getPointerTo(AddressSpace));
1552 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1553 cast<LoadInst>(LI)->setAlignment(Alignment);
1554 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1558 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1559 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1560 // Holds vector parameters or scalars, in case of uniform vals.
1561 SmallVector<VectorParts, 4> Params;
1563 setDebugLocFromInst(Builder, Instr);
1565 // Find all of the vectorized parameters.
1566 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1567 Value *SrcOp = Instr->getOperand(op);
1569 // If we are accessing the old induction variable, use the new one.
1570 if (SrcOp == OldInduction) {
1571 Params.push_back(getVectorValue(SrcOp));
1575 // Try using previously calculated values.
1576 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1578 // If the src is an instruction that appeared earlier in the basic block
1579 // then it should already be vectorized.
1580 if (SrcInst && OrigLoop->contains(SrcInst)) {
1581 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1582 // The parameter is a vector value from earlier.
1583 Params.push_back(WidenMap.get(SrcInst));
1585 // The parameter is a scalar from outside the loop. Maybe even a constant.
1586 VectorParts Scalars;
1587 Scalars.append(UF, SrcOp);
1588 Params.push_back(Scalars);
1592 assert(Params.size() == Instr->getNumOperands() &&
1593 "Invalid number of operands");
1595 // Does this instruction return a value ?
1596 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1598 Value *UndefVec = IsVoidRetTy ? 0 :
1599 UndefValue::get(VectorType::get(Instr->getType(), VF));
1600 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1601 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1603 Instruction *InsertPt = Builder.GetInsertPoint();
1604 BasicBlock *IfBlock = Builder.GetInsertBlock();
1605 BasicBlock *CondBlock = 0;
1609 if (IfPredicateStore) {
1610 assert(Instr->getParent()->getSinglePredecessor() &&
1611 "Only support single predecessor blocks");
1612 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1613 Instr->getParent());
1614 VectorLp = LI->getLoopFor(IfBlock);
1615 assert(VectorLp && "Must have a loop for this block");
1618 // For each vector unroll 'part':
1619 for (unsigned Part = 0; Part < UF; ++Part) {
1620 // For each scalar that we create:
1621 for (unsigned Width = 0; Width < VF; ++Width) {
1625 if (IfPredicateStore) {
1626 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1627 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1628 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1629 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1630 // Update Builder with newly created basic block.
1631 Builder.SetInsertPoint(InsertPt);
1634 Instruction *Cloned = Instr->clone();
1636 Cloned->setName(Instr->getName() + ".cloned");
1637 // Replace the operands of the cloned instructions with extracted scalars.
1638 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1639 Value *Op = Params[op][Part];
1640 // Param is a vector. Need to extract the right lane.
1641 if (Op->getType()->isVectorTy())
1642 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1643 Cloned->setOperand(op, Op);
1646 // Place the cloned scalar in the new loop.
1647 Builder.Insert(Cloned);
1649 // If the original scalar returns a value we need to place it in a vector
1650 // so that future users will be able to use it.
1652 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1653 Builder.getInt32(Width));
1655 if (IfPredicateStore) {
1656 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1657 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1658 Builder.SetInsertPoint(InsertPt);
1659 Instruction *OldBr = IfBlock->getTerminator();
1660 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1661 OldBr->eraseFromParent();
1662 IfBlock = NewIfBlock;
1668 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1672 if (Instruction *I = dyn_cast<Instruction>(V))
1673 return I->getParent() == Loc->getParent() ? I : 0;
1677 std::pair<Instruction *, Instruction *>
1678 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1679 Instruction *tnullptr = 0;
1680 if (!Legal->mustCheckStrides())
1681 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1683 IRBuilder<> ChkBuilder(Loc);
1687 Instruction *FirstInst = 0;
1688 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1689 SE = Legal->strides_end();
1691 Value *Ptr = stripIntegerCast(*SI);
1692 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1694 // Store the first instruction we create.
1695 FirstInst = getFirstInst(FirstInst, C, Loc);
1697 Check = ChkBuilder.CreateOr(Check, C);
1702 // We have to do this trickery because the IRBuilder might fold the check to a
1703 // constant expression in which case there is no Instruction anchored in a
1705 LLVMContext &Ctx = Loc->getContext();
1706 Instruction *TheCheck =
1707 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1708 ChkBuilder.Insert(TheCheck, "stride.not.one");
1709 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1711 return std::make_pair(FirstInst, TheCheck);
1714 std::pair<Instruction *, Instruction *>
1715 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1716 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1717 Legal->getRuntimePointerCheck();
1719 Instruction *tnullptr = 0;
1720 if (!PtrRtCheck->Need)
1721 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1723 unsigned NumPointers = PtrRtCheck->Pointers.size();
1724 SmallVector<TrackingVH<Value> , 2> Starts;
1725 SmallVector<TrackingVH<Value> , 2> Ends;
1727 LLVMContext &Ctx = Loc->getContext();
1728 SCEVExpander Exp(*SE, "induction");
1729 Instruction *FirstInst = 0;
1731 for (unsigned i = 0; i < NumPointers; ++i) {
1732 Value *Ptr = PtrRtCheck->Pointers[i];
1733 const SCEV *Sc = SE->getSCEV(Ptr);
1735 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1736 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1738 Starts.push_back(Ptr);
1739 Ends.push_back(Ptr);
1741 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1742 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1744 // Use this type for pointer arithmetic.
1745 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1747 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1748 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1749 Starts.push_back(Start);
1750 Ends.push_back(End);
1754 IRBuilder<> ChkBuilder(Loc);
1755 // Our instructions might fold to a constant.
1756 Value *MemoryRuntimeCheck = 0;
1757 for (unsigned i = 0; i < NumPointers; ++i) {
1758 for (unsigned j = i+1; j < NumPointers; ++j) {
1759 // No need to check if two readonly pointers intersect.
1760 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1763 // Only need to check pointers between two different dependency sets.
1764 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1767 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1768 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1770 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1771 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1772 "Trying to bounds check pointers with different address spaces");
1774 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1775 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1777 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1778 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1779 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1780 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1782 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1783 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1784 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1785 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1786 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1787 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1788 if (MemoryRuntimeCheck) {
1789 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1791 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1793 MemoryRuntimeCheck = IsConflict;
1797 // We have to do this trickery because the IRBuilder might fold the check to a
1798 // constant expression in which case there is no Instruction anchored in a
1800 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1801 ConstantInt::getTrue(Ctx));
1802 ChkBuilder.Insert(Check, "memcheck.conflict");
1803 FirstInst = getFirstInst(FirstInst, Check, Loc);
1804 return std::make_pair(FirstInst, Check);
1807 void InnerLoopVectorizer::createEmptyLoop() {
1809 In this function we generate a new loop. The new loop will contain
1810 the vectorized instructions while the old loop will continue to run the
1813 [ ] <-- vector loop bypass (may consist of multiple blocks).
1816 | [ ] <-- vector pre header.
1820 | [ ]_| <-- vector loop.
1823 >[ ] <--- middle-block.
1826 | [ ] <--- new preheader.
1830 | [ ]_| <-- old scalar loop to handle remainder.
1833 >[ ] <-- exit block.
1837 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1838 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1839 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1840 assert(ExitBlock && "Must have an exit block");
1842 // Some loops have a single integer induction variable, while other loops
1843 // don't. One example is c++ iterators that often have multiple pointer
1844 // induction variables. In the code below we also support a case where we
1845 // don't have a single induction variable.
1846 OldInduction = Legal->getInduction();
1847 Type *IdxTy = Legal->getWidestInductionType();
1849 // Find the loop boundaries.
1850 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1851 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1853 // The exit count might have the type of i64 while the phi is i32. This can
1854 // happen if we have an induction variable that is sign extended before the
1855 // compare. The only way that we get a backedge taken count is that the
1856 // induction variable was signed and as such will not overflow. In such a case
1857 // truncation is legal.
1858 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1859 IdxTy->getPrimitiveSizeInBits())
1860 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1862 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1863 // Get the total trip count from the count by adding 1.
1864 ExitCount = SE->getAddExpr(ExitCount,
1865 SE->getConstant(ExitCount->getType(), 1));
1867 // Expand the trip count and place the new instructions in the preheader.
1868 // Notice that the pre-header does not change, only the loop body.
1869 SCEVExpander Exp(*SE, "induction");
1871 // Count holds the overall loop count (N).
1872 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1873 BypassBlock->getTerminator());
1875 // The loop index does not have to start at Zero. Find the original start
1876 // value from the induction PHI node. If we don't have an induction variable
1877 // then we know that it starts at zero.
1878 Builder.SetInsertPoint(BypassBlock->getTerminator());
1879 Value *StartIdx = ExtendedIdx = OldInduction ?
1880 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1882 ConstantInt::get(IdxTy, 0);
1884 assert(BypassBlock && "Invalid loop structure");
1885 LoopBypassBlocks.push_back(BypassBlock);
1887 // Split the single block loop into the two loop structure described above.
1888 BasicBlock *VectorPH =
1889 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1890 BasicBlock *VecBody =
1891 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1892 BasicBlock *MiddleBlock =
1893 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1894 BasicBlock *ScalarPH =
1895 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1897 // Create and register the new vector loop.
1898 Loop* Lp = new Loop();
1899 Loop *ParentLoop = OrigLoop->getParentLoop();
1901 // Insert the new loop into the loop nest and register the new basic blocks
1902 // before calling any utilities such as SCEV that require valid LoopInfo.
1904 ParentLoop->addChildLoop(Lp);
1905 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1906 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1907 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1909 LI->addTopLevelLoop(Lp);
1911 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1913 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1915 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
1917 // Generate the induction variable.
1918 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1919 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1920 // The loop step is equal to the vectorization factor (num of SIMD elements)
1921 // times the unroll factor (num of SIMD instructions).
1922 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1924 // This is the IR builder that we use to add all of the logic for bypassing
1925 // the new vector loop.
1926 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1927 setDebugLocFromInst(BypassBuilder,
1928 getDebugLocFromInstOrOperands(OldInduction));
1930 // We may need to extend the index in case there is a type mismatch.
1931 // We know that the count starts at zero and does not overflow.
1932 if (Count->getType() != IdxTy) {
1933 // The exit count can be of pointer type. Convert it to the correct
1935 if (ExitCount->getType()->isPointerTy())
1936 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1938 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1941 // Add the start index to the loop count to get the new end index.
1942 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1944 // Now we need to generate the expression for N - (N % VF), which is
1945 // the part that the vectorized body will execute.
1946 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1947 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1948 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1949 "end.idx.rnd.down");
1951 // Now, compare the new count to zero. If it is zero skip the vector loop and
1952 // jump to the scalar loop.
1953 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1956 BasicBlock *LastBypassBlock = BypassBlock;
1958 // Generate the code to check that the strides we assumed to be one are really
1959 // one. We want the new basic block to start at the first instruction in a
1960 // sequence of instructions that form a check.
1961 Instruction *StrideCheck;
1962 Instruction *FirstCheckInst;
1963 tie(FirstCheckInst, StrideCheck) =
1964 addStrideCheck(BypassBlock->getTerminator());
1966 // Create a new block containing the stride check.
1967 BasicBlock *CheckBlock =
1968 BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
1970 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1971 LoopBypassBlocks.push_back(CheckBlock);
1973 // Replace the branch into the memory check block with a conditional branch
1974 // for the "few elements case".
1975 Instruction *OldTerm = BypassBlock->getTerminator();
1976 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1977 OldTerm->eraseFromParent();
1980 LastBypassBlock = CheckBlock;
1983 // Generate the code that checks in runtime if arrays overlap. We put the
1984 // checks into a separate block to make the more common case of few elements
1986 Instruction *MemRuntimeCheck;
1987 tie(FirstCheckInst, MemRuntimeCheck) =
1988 addRuntimeCheck(LastBypassBlock->getTerminator());
1989 if (MemRuntimeCheck) {
1990 // Create a new block containing the memory check.
1991 BasicBlock *CheckBlock =
1992 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
1994 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1995 LoopBypassBlocks.push_back(CheckBlock);
1997 // Replace the branch into the memory check block with a conditional branch
1998 // for the "few elements case".
1999 Instruction *OldTerm = LastBypassBlock->getTerminator();
2000 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2001 OldTerm->eraseFromParent();
2003 Cmp = MemRuntimeCheck;
2004 LastBypassBlock = CheckBlock;
2007 LastBypassBlock->getTerminator()->eraseFromParent();
2008 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2011 // We are going to resume the execution of the scalar loop.
2012 // Go over all of the induction variables that we found and fix the
2013 // PHIs that are left in the scalar version of the loop.
2014 // The starting values of PHI nodes depend on the counter of the last
2015 // iteration in the vectorized loop.
2016 // If we come from a bypass edge then we need to start from the original
2019 // This variable saves the new starting index for the scalar loop.
2020 PHINode *ResumeIndex = 0;
2021 LoopVectorizationLegality::InductionList::iterator I, E;
2022 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2023 // Set builder to point to last bypass block.
2024 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2025 for (I = List->begin(), E = List->end(); I != E; ++I) {
2026 PHINode *OrigPhi = I->first;
2027 LoopVectorizationLegality::InductionInfo II = I->second;
2029 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2030 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2031 MiddleBlock->getTerminator());
2032 // We might have extended the type of the induction variable but we need a
2033 // truncated version for the scalar loop.
2034 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2035 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2036 MiddleBlock->getTerminator()) : 0;
2038 Value *EndValue = 0;
2040 case LoopVectorizationLegality::IK_NoInduction:
2041 llvm_unreachable("Unknown induction");
2042 case LoopVectorizationLegality::IK_IntInduction: {
2043 // Handle the integer induction counter.
2044 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2046 // We have the canonical induction variable.
2047 if (OrigPhi == OldInduction) {
2048 // Create a truncated version of the resume value for the scalar loop,
2049 // we might have promoted the type to a larger width.
2051 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2052 // The new PHI merges the original incoming value, in case of a bypass,
2053 // or the value at the end of the vectorized loop.
2054 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2055 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2056 TruncResumeVal->addIncoming(EndValue, VecBody);
2058 // We know what the end value is.
2059 EndValue = IdxEndRoundDown;
2060 // We also know which PHI node holds it.
2061 ResumeIndex = ResumeVal;
2065 // Not the canonical induction variable - add the vector loop count to the
2067 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2068 II.StartValue->getType(),
2070 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2073 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2074 // Convert the CountRoundDown variable to the PHI size.
2075 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2076 II.StartValue->getType(),
2078 // Handle reverse integer induction counter.
2079 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2082 case LoopVectorizationLegality::IK_PtrInduction: {
2083 // For pointer induction variables, calculate the offset using
2085 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2089 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2090 // The value at the end of the loop for the reverse pointer is calculated
2091 // by creating a GEP with a negative index starting from the start value.
2092 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2093 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2095 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2101 // The new PHI merges the original incoming value, in case of a bypass,
2102 // or the value at the end of the vectorized loop.
2103 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
2104 if (OrigPhi == OldInduction)
2105 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2107 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2109 ResumeVal->addIncoming(EndValue, VecBody);
2111 // Fix the scalar body counter (PHI node).
2112 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2113 // The old inductions phi node in the scalar body needs the truncated value.
2114 if (OrigPhi == OldInduction)
2115 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
2117 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
2120 // If we are generating a new induction variable then we also need to
2121 // generate the code that calculates the exit value. This value is not
2122 // simply the end of the counter because we may skip the vectorized body
2123 // in case of a runtime check.
2125 assert(!ResumeIndex && "Unexpected resume value found");
2126 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2127 MiddleBlock->getTerminator());
2128 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2129 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2130 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2133 // Make sure that we found the index where scalar loop needs to continue.
2134 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2135 "Invalid resume Index");
2137 // Add a check in the middle block to see if we have completed
2138 // all of the iterations in the first vector loop.
2139 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2140 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2141 ResumeIndex, "cmp.n",
2142 MiddleBlock->getTerminator());
2144 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2145 // Remove the old terminator.
2146 MiddleBlock->getTerminator()->eraseFromParent();
2148 // Create i+1 and fill the PHINode.
2149 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2150 Induction->addIncoming(StartIdx, VectorPH);
2151 Induction->addIncoming(NextIdx, VecBody);
2152 // Create the compare.
2153 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2154 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2156 // Now we have two terminators. Remove the old one from the block.
2157 VecBody->getTerminator()->eraseFromParent();
2159 // Get ready to start creating new instructions into the vectorized body.
2160 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2163 LoopVectorPreHeader = VectorPH;
2164 LoopScalarPreHeader = ScalarPH;
2165 LoopMiddleBlock = MiddleBlock;
2166 LoopExitBlock = ExitBlock;
2167 LoopVectorBody.push_back(VecBody);
2168 LoopScalarBody = OldBasicBlock;
2170 LoopVectorizeHints Hints(Lp, true);
2171 Hints.setAlreadyVectorized(Lp);
2174 /// This function returns the identity element (or neutral element) for
2175 /// the operation K.
2177 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2182 // Adding, Xoring, Oring zero to a number does not change it.
2183 return ConstantInt::get(Tp, 0);
2184 case RK_IntegerMult:
2185 // Multiplying a number by 1 does not change it.
2186 return ConstantInt::get(Tp, 1);
2188 // AND-ing a number with an all-1 value does not change it.
2189 return ConstantInt::get(Tp, -1, true);
2191 // Multiplying a number by 1 does not change it.
2192 return ConstantFP::get(Tp, 1.0L);
2194 // Adding zero to a number does not change it.
2195 return ConstantFP::get(Tp, 0.0L);
2197 llvm_unreachable("Unknown reduction kind");
2201 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
2202 Intrinsic::ID ValidIntrinsicID) {
2203 if (I.getNumArgOperands() != 1 ||
2204 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2205 I.getType() != I.getArgOperand(0)->getType() ||
2206 !I.onlyReadsMemory())
2207 return Intrinsic::not_intrinsic;
2209 return ValidIntrinsicID;
2212 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
2213 Intrinsic::ID ValidIntrinsicID) {
2214 if (I.getNumArgOperands() != 2 ||
2215 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2216 !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
2217 I.getType() != I.getArgOperand(0)->getType() ||
2218 I.getType() != I.getArgOperand(1)->getType() ||
2219 !I.onlyReadsMemory())
2220 return Intrinsic::not_intrinsic;
2222 return ValidIntrinsicID;
2226 static Intrinsic::ID
2227 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
2228 // If we have an intrinsic call, check if it is trivially vectorizable.
2229 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2230 switch (II->getIntrinsicID()) {
2231 case Intrinsic::sqrt:
2232 case Intrinsic::sin:
2233 case Intrinsic::cos:
2234 case Intrinsic::exp:
2235 case Intrinsic::exp2:
2236 case Intrinsic::log:
2237 case Intrinsic::log10:
2238 case Intrinsic::log2:
2239 case Intrinsic::fabs:
2240 case Intrinsic::copysign:
2241 case Intrinsic::floor:
2242 case Intrinsic::ceil:
2243 case Intrinsic::trunc:
2244 case Intrinsic::rint:
2245 case Intrinsic::nearbyint:
2246 case Intrinsic::round:
2247 case Intrinsic::pow:
2248 case Intrinsic::fma:
2249 case Intrinsic::fmuladd:
2250 case Intrinsic::lifetime_start:
2251 case Intrinsic::lifetime_end:
2252 return II->getIntrinsicID();
2254 return Intrinsic::not_intrinsic;
2259 return Intrinsic::not_intrinsic;
2262 Function *F = CI->getCalledFunction();
2263 // We're going to make assumptions on the semantics of the functions, check
2264 // that the target knows that it's available in this environment and it does
2265 // not have local linkage.
2266 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
2267 return Intrinsic::not_intrinsic;
2269 // Otherwise check if we have a call to a function that can be turned into a
2270 // vector intrinsic.
2277 return checkUnaryFloatSignature(*CI, Intrinsic::sin);
2281 return checkUnaryFloatSignature(*CI, Intrinsic::cos);
2285 return checkUnaryFloatSignature(*CI, Intrinsic::exp);
2287 case LibFunc::exp2f:
2288 case LibFunc::exp2l:
2289 return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
2293 return checkUnaryFloatSignature(*CI, Intrinsic::log);
2294 case LibFunc::log10:
2295 case LibFunc::log10f:
2296 case LibFunc::log10l:
2297 return checkUnaryFloatSignature(*CI, Intrinsic::log10);
2299 case LibFunc::log2f:
2300 case LibFunc::log2l:
2301 return checkUnaryFloatSignature(*CI, Intrinsic::log2);
2303 case LibFunc::fabsf:
2304 case LibFunc::fabsl:
2305 return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
2306 case LibFunc::copysign:
2307 case LibFunc::copysignf:
2308 case LibFunc::copysignl:
2309 return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
2310 case LibFunc::floor:
2311 case LibFunc::floorf:
2312 case LibFunc::floorl:
2313 return checkUnaryFloatSignature(*CI, Intrinsic::floor);
2315 case LibFunc::ceilf:
2316 case LibFunc::ceill:
2317 return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
2318 case LibFunc::trunc:
2319 case LibFunc::truncf:
2320 case LibFunc::truncl:
2321 return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
2323 case LibFunc::rintf:
2324 case LibFunc::rintl:
2325 return checkUnaryFloatSignature(*CI, Intrinsic::rint);
2326 case LibFunc::nearbyint:
2327 case LibFunc::nearbyintf:
2328 case LibFunc::nearbyintl:
2329 return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
2330 case LibFunc::round:
2331 case LibFunc::roundf:
2332 case LibFunc::roundl:
2333 return checkUnaryFloatSignature(*CI, Intrinsic::round);
2337 return checkBinaryFloatSignature(*CI, Intrinsic::pow);
2340 return Intrinsic::not_intrinsic;
2343 /// This function translates the reduction kind to an LLVM binary operator.
2345 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2347 case LoopVectorizationLegality::RK_IntegerAdd:
2348 return Instruction::Add;
2349 case LoopVectorizationLegality::RK_IntegerMult:
2350 return Instruction::Mul;
2351 case LoopVectorizationLegality::RK_IntegerOr:
2352 return Instruction::Or;
2353 case LoopVectorizationLegality::RK_IntegerAnd:
2354 return Instruction::And;
2355 case LoopVectorizationLegality::RK_IntegerXor:
2356 return Instruction::Xor;
2357 case LoopVectorizationLegality::RK_FloatMult:
2358 return Instruction::FMul;
2359 case LoopVectorizationLegality::RK_FloatAdd:
2360 return Instruction::FAdd;
2361 case LoopVectorizationLegality::RK_IntegerMinMax:
2362 return Instruction::ICmp;
2363 case LoopVectorizationLegality::RK_FloatMinMax:
2364 return Instruction::FCmp;
2366 llvm_unreachable("Unknown reduction operation");
2370 Value *createMinMaxOp(IRBuilder<> &Builder,
2371 LoopVectorizationLegality::MinMaxReductionKind RK,
2374 CmpInst::Predicate P = CmpInst::ICMP_NE;
2377 llvm_unreachable("Unknown min/max reduction kind");
2378 case LoopVectorizationLegality::MRK_UIntMin:
2379 P = CmpInst::ICMP_ULT;
2381 case LoopVectorizationLegality::MRK_UIntMax:
2382 P = CmpInst::ICMP_UGT;
2384 case LoopVectorizationLegality::MRK_SIntMin:
2385 P = CmpInst::ICMP_SLT;
2387 case LoopVectorizationLegality::MRK_SIntMax:
2388 P = CmpInst::ICMP_SGT;
2390 case LoopVectorizationLegality::MRK_FloatMin:
2391 P = CmpInst::FCMP_OLT;
2393 case LoopVectorizationLegality::MRK_FloatMax:
2394 P = CmpInst::FCMP_OGT;
2399 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2400 RK == LoopVectorizationLegality::MRK_FloatMax)
2401 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2403 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2405 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2410 struct CSEDenseMapInfo {
2411 static bool canHandle(Instruction *I) {
2412 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2413 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2415 static inline Instruction *getEmptyKey() {
2416 return DenseMapInfo<Instruction *>::getEmptyKey();
2418 static inline Instruction *getTombstoneKey() {
2419 return DenseMapInfo<Instruction *>::getTombstoneKey();
2421 static unsigned getHashValue(Instruction *I) {
2422 assert(canHandle(I) && "Unknown instruction!");
2423 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2424 I->value_op_end()));
2426 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2427 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2428 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2430 return LHS->isIdenticalTo(RHS);
2435 /// \brief Check whether this block is a predicated block.
2436 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2437 /// = ...; " blocks. We start with one vectorized basic block. For every
2438 /// conditional block we split this vectorized block. Therefore, every second
2439 /// block will be a predicated one.
2440 static bool isPredicatedBlock(unsigned BlockNum) {
2441 return BlockNum % 2;
2444 ///\brief Perform cse of induction variable instructions.
2445 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2446 // Perform simple cse.
2447 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2448 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2449 BasicBlock *BB = BBs[i];
2450 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2451 Instruction *In = I++;
2453 if (!CSEDenseMapInfo::canHandle(In))
2456 // Check if we can replace this instruction with any of the
2457 // visited instructions.
2458 if (Instruction *V = CSEMap.lookup(In)) {
2459 In->replaceAllUsesWith(V);
2460 In->eraseFromParent();
2463 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2464 // ...;" blocks for predicated stores. Every second block is a predicated
2466 if (isPredicatedBlock(i))
2474 void InnerLoopVectorizer::vectorizeLoop() {
2475 //===------------------------------------------------===//
2477 // Notice: any optimization or new instruction that go
2478 // into the code below should be also be implemented in
2481 //===------------------------------------------------===//
2482 Constant *Zero = Builder.getInt32(0);
2484 // In order to support reduction variables we need to be able to vectorize
2485 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2486 // stages. First, we create a new vector PHI node with no incoming edges.
2487 // We use this value when we vectorize all of the instructions that use the
2488 // PHI. Next, after all of the instructions in the block are complete we
2489 // add the new incoming edges to the PHI. At this point all of the
2490 // instructions in the basic block are vectorized, so we can use them to
2491 // construct the PHI.
2492 PhiVector RdxPHIsToFix;
2494 // Scan the loop in a topological order to ensure that defs are vectorized
2496 LoopBlocksDFS DFS(OrigLoop);
2499 // Vectorize all of the blocks in the original loop.
2500 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2501 be = DFS.endRPO(); bb != be; ++bb)
2502 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2504 // At this point every instruction in the original loop is widened to
2505 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2506 // that we vectorized. The PHI nodes are currently empty because we did
2507 // not want to introduce cycles. Notice that the remaining PHI nodes
2508 // that we need to fix are reduction variables.
2510 // Create the 'reduced' values for each of the induction vars.
2511 // The reduced values are the vector values that we scalarize and combine
2512 // after the loop is finished.
2513 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2515 PHINode *RdxPhi = *it;
2516 assert(RdxPhi && "Unable to recover vectorized PHI");
2518 // Find the reduction variable descriptor.
2519 assert(Legal->getReductionVars()->count(RdxPhi) &&
2520 "Unable to find the reduction variable");
2521 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2522 (*Legal->getReductionVars())[RdxPhi];
2524 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2526 // We need to generate a reduction vector from the incoming scalar.
2527 // To do so, we need to generate the 'identity' vector and override
2528 // one of the elements with the incoming scalar reduction. We need
2529 // to do it in the vector-loop preheader.
2530 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2532 // This is the vector-clone of the value that leaves the loop.
2533 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2534 Type *VecTy = VectorExit[0]->getType();
2536 // Find the reduction identity variable. Zero for addition, or, xor,
2537 // one for multiplication, -1 for And.
2540 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2541 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2542 // MinMax reduction have the start value as their identify.
2544 VectorStart = Identity = RdxDesc.StartValue;
2546 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2551 // Handle other reduction kinds:
2553 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2554 VecTy->getScalarType());
2557 // This vector is the Identity vector where the first element is the
2558 // incoming scalar reduction.
2559 VectorStart = RdxDesc.StartValue;
2561 Identity = ConstantVector::getSplat(VF, Iden);
2563 // This vector is the Identity vector where the first element is the
2564 // incoming scalar reduction.
2565 VectorStart = Builder.CreateInsertElement(Identity,
2566 RdxDesc.StartValue, Zero);
2570 // Fix the vector-loop phi.
2571 // We created the induction variable so we know that the
2572 // preheader is the first entry.
2573 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2575 // Reductions do not have to start at zero. They can start with
2576 // any loop invariant values.
2577 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2578 BasicBlock *Latch = OrigLoop->getLoopLatch();
2579 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2580 VectorParts &Val = getVectorValue(LoopVal);
2581 for (unsigned part = 0; part < UF; ++part) {
2582 // Make sure to add the reduction stat value only to the
2583 // first unroll part.
2584 Value *StartVal = (part == 0) ? VectorStart : Identity;
2585 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2586 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2587 LoopVectorBody.back());
2590 // Before each round, move the insertion point right between
2591 // the PHIs and the values we are going to write.
2592 // This allows us to write both PHINodes and the extractelement
2594 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2596 VectorParts RdxParts;
2597 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2598 for (unsigned part = 0; part < UF; ++part) {
2599 // This PHINode contains the vectorized reduction variable, or
2600 // the initial value vector, if we bypass the vector loop.
2601 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2602 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2603 Value *StartVal = (part == 0) ? VectorStart : Identity;
2604 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2605 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2606 NewPhi->addIncoming(RdxExitVal[part],
2607 LoopVectorBody.back());
2608 RdxParts.push_back(NewPhi);
2611 // Reduce all of the unrolled parts into a single vector.
2612 Value *ReducedPartRdx = RdxParts[0];
2613 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2614 setDebugLocFromInst(Builder, ReducedPartRdx);
2615 for (unsigned part = 1; part < UF; ++part) {
2616 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2617 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2618 RdxParts[part], ReducedPartRdx,
2621 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2622 ReducedPartRdx, RdxParts[part]);
2626 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2627 // and vector ops, reducing the set of values being computed by half each
2629 assert(isPowerOf2_32(VF) &&
2630 "Reduction emission only supported for pow2 vectors!");
2631 Value *TmpVec = ReducedPartRdx;
2632 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2633 for (unsigned i = VF; i != 1; i >>= 1) {
2634 // Move the upper half of the vector to the lower half.
2635 for (unsigned j = 0; j != i/2; ++j)
2636 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2638 // Fill the rest of the mask with undef.
2639 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2640 UndefValue::get(Builder.getInt32Ty()));
2643 Builder.CreateShuffleVector(TmpVec,
2644 UndefValue::get(TmpVec->getType()),
2645 ConstantVector::get(ShuffleMask),
2648 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2649 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2652 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2655 // The result is in the first element of the vector.
2656 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2657 Builder.getInt32(0));
2660 // Now, we need to fix the users of the reduction variable
2661 // inside and outside of the scalar remainder loop.
2662 // We know that the loop is in LCSSA form. We need to update the
2663 // PHI nodes in the exit blocks.
2664 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2665 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2666 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2667 if (!LCSSAPhi) break;
2669 // All PHINodes need to have a single entry edge, or two if
2670 // we already fixed them.
2671 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2673 // We found our reduction value exit-PHI. Update it with the
2674 // incoming bypass edge.
2675 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2676 // Add an edge coming from the bypass.
2677 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2680 }// end of the LCSSA phi scan.
2682 // Fix the scalar loop reduction variable with the incoming reduction sum
2683 // from the vector body and from the backedge value.
2684 int IncomingEdgeBlockIdx =
2685 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2686 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2687 // Pick the other block.
2688 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2689 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2690 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2691 }// end of for each redux variable.
2695 // Remove redundant induction instructions.
2696 cse(LoopVectorBody);
2699 void InnerLoopVectorizer::fixLCSSAPHIs() {
2700 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2701 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2702 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2703 if (!LCSSAPhi) break;
2704 if (LCSSAPhi->getNumIncomingValues() == 1)
2705 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2710 InnerLoopVectorizer::VectorParts
2711 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2712 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2715 // Look for cached value.
2716 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2717 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2718 if (ECEntryIt != MaskCache.end())
2719 return ECEntryIt->second;
2721 VectorParts SrcMask = createBlockInMask(Src);
2723 // The terminator has to be a branch inst!
2724 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2725 assert(BI && "Unexpected terminator found");
2727 if (BI->isConditional()) {
2728 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2730 if (BI->getSuccessor(0) != Dst)
2731 for (unsigned part = 0; part < UF; ++part)
2732 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2734 for (unsigned part = 0; part < UF; ++part)
2735 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2737 MaskCache[Edge] = EdgeMask;
2741 MaskCache[Edge] = SrcMask;
2745 InnerLoopVectorizer::VectorParts
2746 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2747 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2749 // Loop incoming mask is all-one.
2750 if (OrigLoop->getHeader() == BB) {
2751 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2752 return getVectorValue(C);
2755 // This is the block mask. We OR all incoming edges, and with zero.
2756 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2757 VectorParts BlockMask = getVectorValue(Zero);
2760 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2761 VectorParts EM = createEdgeMask(*it, BB);
2762 for (unsigned part = 0; part < UF; ++part)
2763 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2769 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2770 InnerLoopVectorizer::VectorParts &Entry,
2771 unsigned UF, unsigned VF, PhiVector *PV) {
2772 PHINode* P = cast<PHINode>(PN);
2773 // Handle reduction variables:
2774 if (Legal->getReductionVars()->count(P)) {
2775 for (unsigned part = 0; part < UF; ++part) {
2776 // This is phase one of vectorizing PHIs.
2777 Type *VecTy = (VF == 1) ? PN->getType() :
2778 VectorType::get(PN->getType(), VF);
2779 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2780 LoopVectorBody.back()-> getFirstInsertionPt());
2786 setDebugLocFromInst(Builder, P);
2787 // Check for PHI nodes that are lowered to vector selects.
2788 if (P->getParent() != OrigLoop->getHeader()) {
2789 // We know that all PHIs in non-header blocks are converted into
2790 // selects, so we don't have to worry about the insertion order and we
2791 // can just use the builder.
2792 // At this point we generate the predication tree. There may be
2793 // duplications since this is a simple recursive scan, but future
2794 // optimizations will clean it up.
2796 unsigned NumIncoming = P->getNumIncomingValues();
2798 // Generate a sequence of selects of the form:
2799 // SELECT(Mask3, In3,
2800 // SELECT(Mask2, In2,
2802 for (unsigned In = 0; In < NumIncoming; In++) {
2803 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2805 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2807 for (unsigned part = 0; part < UF; ++part) {
2808 // We might have single edge PHIs (blocks) - use an identity
2809 // 'select' for the first PHI operand.
2811 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2814 // Select between the current value and the previous incoming edge
2815 // based on the incoming mask.
2816 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2817 Entry[part], "predphi");
2823 // This PHINode must be an induction variable.
2824 // Make sure that we know about it.
2825 assert(Legal->getInductionVars()->count(P) &&
2826 "Not an induction variable");
2828 LoopVectorizationLegality::InductionInfo II =
2829 Legal->getInductionVars()->lookup(P);
2832 case LoopVectorizationLegality::IK_NoInduction:
2833 llvm_unreachable("Unknown induction");
2834 case LoopVectorizationLegality::IK_IntInduction: {
2835 assert(P->getType() == II.StartValue->getType() && "Types must match");
2836 Type *PhiTy = P->getType();
2838 if (P == OldInduction) {
2839 // Handle the canonical induction variable. We might have had to
2841 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2843 // Handle other induction variables that are now based on the
2845 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2847 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2848 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2851 Broadcasted = getBroadcastInstrs(Broadcasted);
2852 // After broadcasting the induction variable we need to make the vector
2853 // consecutive by adding 0, 1, 2, etc.
2854 for (unsigned part = 0; part < UF; ++part)
2855 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2858 case LoopVectorizationLegality::IK_ReverseIntInduction:
2859 case LoopVectorizationLegality::IK_PtrInduction:
2860 case LoopVectorizationLegality::IK_ReversePtrInduction:
2861 // Handle reverse integer and pointer inductions.
2862 Value *StartIdx = ExtendedIdx;
2863 // This is the normalized GEP that starts counting at zero.
2864 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2867 // Handle the reverse integer induction variable case.
2868 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2869 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2870 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2872 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2875 // This is a new value so do not hoist it out.
2876 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2877 // After broadcasting the induction variable we need to make the
2878 // vector consecutive by adding ... -3, -2, -1, 0.
2879 for (unsigned part = 0; part < UF; ++part)
2880 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2885 // Handle the pointer induction variable case.
2886 assert(P->getType()->isPointerTy() && "Unexpected type.");
2888 // Is this a reverse induction ptr or a consecutive induction ptr.
2889 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2892 // This is the vector of results. Notice that we don't generate
2893 // vector geps because scalar geps result in better code.
2894 for (unsigned part = 0; part < UF; ++part) {
2896 int EltIndex = (part) * (Reverse ? -1 : 1);
2897 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2900 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2902 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2904 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2906 Entry[part] = SclrGep;
2910 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2911 for (unsigned int i = 0; i < VF; ++i) {
2912 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2913 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2916 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2918 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2920 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2922 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2923 Builder.getInt32(i),
2926 Entry[part] = VecVal;
2932 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2933 // For each instruction in the old loop.
2934 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2935 VectorParts &Entry = WidenMap.get(it);
2936 switch (it->getOpcode()) {
2937 case Instruction::Br:
2938 // Nothing to do for PHIs and BR, since we already took care of the
2939 // loop control flow instructions.
2941 case Instruction::PHI:{
2942 // Vectorize PHINodes.
2943 widenPHIInstruction(it, Entry, UF, VF, PV);
2947 case Instruction::Add:
2948 case Instruction::FAdd:
2949 case Instruction::Sub:
2950 case Instruction::FSub:
2951 case Instruction::Mul:
2952 case Instruction::FMul:
2953 case Instruction::UDiv:
2954 case Instruction::SDiv:
2955 case Instruction::FDiv:
2956 case Instruction::URem:
2957 case Instruction::SRem:
2958 case Instruction::FRem:
2959 case Instruction::Shl:
2960 case Instruction::LShr:
2961 case Instruction::AShr:
2962 case Instruction::And:
2963 case Instruction::Or:
2964 case Instruction::Xor: {
2965 // Just widen binops.
2966 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2967 setDebugLocFromInst(Builder, BinOp);
2968 VectorParts &A = getVectorValue(it->getOperand(0));
2969 VectorParts &B = getVectorValue(it->getOperand(1));
2971 // Use this vector value for all users of the original instruction.
2972 for (unsigned Part = 0; Part < UF; ++Part) {
2973 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2975 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2976 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2977 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2978 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2979 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2981 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2982 VecOp->setIsExact(BinOp->isExact());
2988 case Instruction::Select: {
2990 // If the selector is loop invariant we can create a select
2991 // instruction with a scalar condition. Otherwise, use vector-select.
2992 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2994 setDebugLocFromInst(Builder, it);
2996 // The condition can be loop invariant but still defined inside the
2997 // loop. This means that we can't just use the original 'cond' value.
2998 // We have to take the 'vectorized' value and pick the first lane.
2999 // Instcombine will make this a no-op.
3000 VectorParts &Cond = getVectorValue(it->getOperand(0));
3001 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3002 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3004 Value *ScalarCond = (VF == 1) ? Cond[0] :
3005 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3007 for (unsigned Part = 0; Part < UF; ++Part) {
3008 Entry[Part] = Builder.CreateSelect(
3009 InvariantCond ? ScalarCond : Cond[Part],
3016 case Instruction::ICmp:
3017 case Instruction::FCmp: {
3018 // Widen compares. Generate vector compares.
3019 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3020 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3021 setDebugLocFromInst(Builder, it);
3022 VectorParts &A = getVectorValue(it->getOperand(0));
3023 VectorParts &B = getVectorValue(it->getOperand(1));
3024 for (unsigned Part = 0; Part < UF; ++Part) {
3027 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3029 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3035 case Instruction::Store:
3036 case Instruction::Load:
3037 vectorizeMemoryInstruction(it);
3039 case Instruction::ZExt:
3040 case Instruction::SExt:
3041 case Instruction::FPToUI:
3042 case Instruction::FPToSI:
3043 case Instruction::FPExt:
3044 case Instruction::PtrToInt:
3045 case Instruction::IntToPtr:
3046 case Instruction::SIToFP:
3047 case Instruction::UIToFP:
3048 case Instruction::Trunc:
3049 case Instruction::FPTrunc:
3050 case Instruction::BitCast: {
3051 CastInst *CI = dyn_cast<CastInst>(it);
3052 setDebugLocFromInst(Builder, it);
3053 /// Optimize the special case where the source is the induction
3054 /// variable. Notice that we can only optimize the 'trunc' case
3055 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3056 /// c. other casts depend on pointer size.
3057 if (CI->getOperand(0) == OldInduction &&
3058 it->getOpcode() == Instruction::Trunc) {
3059 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3061 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3062 for (unsigned Part = 0; Part < UF; ++Part)
3063 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3066 /// Vectorize casts.
3067 Type *DestTy = (VF == 1) ? CI->getType() :
3068 VectorType::get(CI->getType(), VF);
3070 VectorParts &A = getVectorValue(it->getOperand(0));
3071 for (unsigned Part = 0; Part < UF; ++Part)
3072 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3076 case Instruction::Call: {
3077 // Ignore dbg intrinsics.
3078 if (isa<DbgInfoIntrinsic>(it))
3080 setDebugLocFromInst(Builder, it);
3082 Module *M = BB->getParent()->getParent();
3083 CallInst *CI = cast<CallInst>(it);
3084 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3085 assert(ID && "Not an intrinsic call!");
3087 case Intrinsic::lifetime_end:
3088 case Intrinsic::lifetime_start:
3089 scalarizeInstruction(it);
3092 for (unsigned Part = 0; Part < UF; ++Part) {
3093 SmallVector<Value *, 4> Args;
3094 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3095 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3096 Args.push_back(Arg[Part]);
3098 Type *Tys[] = {CI->getType()};
3100 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3102 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3103 Entry[Part] = Builder.CreateCall(F, Args);
3111 // All other instructions are unsupported. Scalarize them.
3112 scalarizeInstruction(it);
3115 }// end of for_each instr.
3118 void InnerLoopVectorizer::updateAnalysis() {
3119 // Forget the original basic block.
3120 SE->forgetLoop(OrigLoop);
3122 // Update the dominator tree information.
3123 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3124 "Entry does not dominate exit.");
3126 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3127 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3128 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3130 // Due to if predication of stores we might create a sequence of "if(pred)
3131 // a[i] = ...; " blocks.
3132 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3134 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3135 else if (isPredicatedBlock(i)) {
3136 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3138 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3142 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
3143 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
3144 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3145 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3147 DEBUG(DT->verifyDomTree());
3150 /// \brief Check whether it is safe to if-convert this phi node.
3152 /// Phi nodes with constant expressions that can trap are not safe to if
3154 static bool canIfConvertPHINodes(BasicBlock *BB) {
3155 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3156 PHINode *Phi = dyn_cast<PHINode>(I);
3159 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3160 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3167 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3168 if (!EnableIfConversion)
3171 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3173 // A list of pointers that we can safely read and write to.
3174 SmallPtrSet<Value *, 8> SafePointes;
3176 // Collect safe addresses.
3177 for (Loop::block_iterator BI = TheLoop->block_begin(),
3178 BE = TheLoop->block_end(); BI != BE; ++BI) {
3179 BasicBlock *BB = *BI;
3181 if (blockNeedsPredication(BB))
3184 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3185 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3186 SafePointes.insert(LI->getPointerOperand());
3187 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3188 SafePointes.insert(SI->getPointerOperand());
3192 // Collect the blocks that need predication.
3193 BasicBlock *Header = TheLoop->getHeader();
3194 for (Loop::block_iterator BI = TheLoop->block_begin(),
3195 BE = TheLoop->block_end(); BI != BE; ++BI) {
3196 BasicBlock *BB = *BI;
3198 // We don't support switch statements inside loops.
3199 if (!isa<BranchInst>(BB->getTerminator()))
3202 // We must be able to predicate all blocks that need to be predicated.
3203 if (blockNeedsPredication(BB)) {
3204 if (!blockCanBePredicated(BB, SafePointes))
3206 } else if (BB != Header && !canIfConvertPHINodes(BB))
3211 // We can if-convert this loop.
3215 bool LoopVectorizationLegality::canVectorize() {
3216 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3217 // be canonicalized.
3218 if (!TheLoop->getLoopPreheader())
3221 // We can only vectorize innermost loops.
3222 if (TheLoop->getSubLoopsVector().size())
3225 // We must have a single backedge.
3226 if (TheLoop->getNumBackEdges() != 1)
3229 // We must have a single exiting block.
3230 if (!TheLoop->getExitingBlock())
3233 // We need to have a loop header.
3234 DEBUG(dbgs() << "LV: Found a loop: " <<
3235 TheLoop->getHeader()->getName() << '\n');
3237 // Check if we can if-convert non-single-bb loops.
3238 unsigned NumBlocks = TheLoop->getNumBlocks();
3239 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3240 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3244 // ScalarEvolution needs to be able to find the exit count.
3245 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3246 if (ExitCount == SE->getCouldNotCompute()) {
3247 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3251 // Do not loop-vectorize loops with a tiny trip count.
3252 BasicBlock *Latch = TheLoop->getLoopLatch();
3253 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
3254 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
3255 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
3256 "This loop is not worth vectorizing.\n");
3260 // Check if we can vectorize the instructions and CFG in this loop.
3261 if (!canVectorizeInstrs()) {
3262 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3266 // Go over each instruction and look at memory deps.
3267 if (!canVectorizeMemory()) {
3268 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3272 // Collect all of the variables that remain uniform after vectorization.
3273 collectLoopUniforms();
3275 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3276 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3279 // Okay! We can vectorize. At this point we don't have any other mem analysis
3280 // which may limit our maximum vectorization factor, so just return true with
3285 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
3286 if (Ty->isPointerTy())
3287 return DL.getIntPtrType(Ty);
3289 // It is possible that char's or short's overflow when we ask for the loop's
3290 // trip count, work around this by changing the type size.
3291 if (Ty->getScalarSizeInBits() < 32)
3292 return Type::getInt32Ty(Ty->getContext());
3297 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
3298 Ty0 = convertPointerToIntegerType(DL, Ty0);
3299 Ty1 = convertPointerToIntegerType(DL, Ty1);
3300 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3305 /// \brief Check that the instruction has outside loop users and is not an
3306 /// identified reduction variable.
3307 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3308 SmallPtrSet<Value *, 4> &Reductions) {
3309 // Reduction instructions are allowed to have exit users. All other
3310 // instructions must not have external users.
3311 if (!Reductions.count(Inst))
3312 //Check that all of the users of the loop are inside the BB.
3313 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
3315 Instruction *U = cast<Instruction>(*I);
3316 // This user may be a reduction exit value.
3317 if (!TheLoop->contains(U)) {
3318 DEBUG(dbgs() << "LV: Found an outside user for : " << *U << '\n');
3325 bool LoopVectorizationLegality::canVectorizeInstrs() {
3326 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3327 BasicBlock *Header = TheLoop->getHeader();
3329 // Look for the attribute signaling the absence of NaNs.
3330 Function &F = *Header->getParent();
3331 if (F.hasFnAttribute("no-nans-fp-math"))
3332 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3333 AttributeSet::FunctionIndex,
3334 "no-nans-fp-math").getValueAsString() == "true";
3336 // For each block in the loop.
3337 for (Loop::block_iterator bb = TheLoop->block_begin(),
3338 be = TheLoop->block_end(); bb != be; ++bb) {
3340 // Scan the instructions in the block and look for hazards.
3341 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3344 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3345 Type *PhiTy = Phi->getType();
3346 // Check that this PHI type is allowed.
3347 if (!PhiTy->isIntegerTy() &&
3348 !PhiTy->isFloatingPointTy() &&
3349 !PhiTy->isPointerTy()) {
3350 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3354 // If this PHINode is not in the header block, then we know that we
3355 // can convert it to select during if-conversion. No need to check if
3356 // the PHIs in this block are induction or reduction variables.
3357 if (*bb != Header) {
3358 // Check that this instruction has no outside users or is an
3359 // identified reduction value with an outside user.
3360 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3365 // We only allow if-converted PHIs with more than two incoming values.
3366 if (Phi->getNumIncomingValues() != 2) {
3367 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3371 // This is the value coming from the preheader.
3372 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3373 // Check if this is an induction variable.
3374 InductionKind IK = isInductionVariable(Phi);
3376 if (IK_NoInduction != IK) {
3377 // Get the widest type.
3379 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3381 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3383 // Int inductions are special because we only allow one IV.
3384 if (IK == IK_IntInduction) {
3385 // Use the phi node with the widest type as induction. Use the last
3386 // one if there are multiple (no good reason for doing this other
3387 // than it is expedient).
3388 if (!Induction || PhiTy == WidestIndTy)
3392 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3393 Inductions[Phi] = InductionInfo(StartValue, IK);
3395 // Until we explicitly handle the case of an induction variable with
3396 // an outside loop user we have to give up vectorizing this loop.
3397 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3403 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3404 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3407 if (AddReductionVar(Phi, RK_IntegerMult)) {
3408 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3411 if (AddReductionVar(Phi, RK_IntegerOr)) {
3412 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3415 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3416 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3419 if (AddReductionVar(Phi, RK_IntegerXor)) {
3420 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3423 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3424 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3427 if (AddReductionVar(Phi, RK_FloatMult)) {
3428 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3431 if (AddReductionVar(Phi, RK_FloatAdd)) {
3432 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3435 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3436 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3441 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3443 }// end of PHI handling
3445 // We still don't handle functions. However, we can ignore dbg intrinsic
3446 // calls and we do handle certain intrinsic and libm functions.
3447 CallInst *CI = dyn_cast<CallInst>(it);
3448 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3449 DEBUG(dbgs() << "LV: Found a call site.\n");
3453 // Check that the instruction return type is vectorizable.
3454 // Also, we can't vectorize extractelement instructions.
3455 if ((!VectorType::isValidElementType(it->getType()) &&
3456 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3457 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3461 // Check that the stored type is vectorizable.
3462 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3463 Type *T = ST->getValueOperand()->getType();
3464 if (!VectorType::isValidElementType(T))
3466 if (EnableMemAccessVersioning)
3467 collectStridedAcccess(ST);
3470 if (EnableMemAccessVersioning)
3471 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3472 collectStridedAcccess(LI);
3474 // Reduction instructions are allowed to have exit users.
3475 // All other instructions must not have external users.
3476 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3484 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3485 if (Inductions.empty())
3492 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3493 /// return the induction operand of the gep pointer.
3494 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3495 DataLayout *DL, Loop *Lp) {
3496 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3500 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3502 // Check that all of the gep indices are uniform except for our induction
3504 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3505 if (i != InductionOperand &&
3506 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3508 return GEP->getOperand(InductionOperand);
3511 ///\brief Look for a cast use of the passed value.
3512 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3513 Value *UniqueCast = 0;
3514 for (Value::use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); UI != UE;
3516 CastInst *CI = dyn_cast<CastInst>(*UI);
3517 if (CI && CI->getType() == Ty) {
3527 ///\brief Get the stride of a pointer access in a loop.
3528 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3529 /// pointer to the Value, or null otherwise.
3530 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3531 DataLayout *DL, Loop *Lp) {
3532 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3533 if (!PtrTy || PtrTy->isAggregateType())
3536 // Try to remove a gep instruction to make the pointer (actually index at this
3537 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3538 // pointer, otherwise, we are analyzing the index.
3539 Value *OrigPtr = Ptr;
3541 // The size of the pointer access.
3542 int64_t PtrAccessSize = 1;
3544 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3545 const SCEV *V = SE->getSCEV(Ptr);
3549 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3550 V = C->getOperand();
3552 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3556 V = S->getStepRecurrence(*SE);
3560 // Strip off the size of access multiplication if we are still analyzing the
3562 if (OrigPtr == Ptr) {
3563 DL->getTypeAllocSize(PtrTy->getElementType());
3564 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3565 if (M->getOperand(0)->getSCEVType() != scConstant)
3568 const APInt &APStepVal =
3569 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3571 // Huge step value - give up.
3572 if (APStepVal.getBitWidth() > 64)
3575 int64_t StepVal = APStepVal.getSExtValue();
3576 if (PtrAccessSize != StepVal)
3578 V = M->getOperand(1);
3583 Type *StripedOffRecurrenceCast = 0;
3584 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3585 StripedOffRecurrenceCast = C->getType();
3586 V = C->getOperand();
3589 // Look for the loop invariant symbolic value.
3590 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3594 Value *Stride = U->getValue();
3595 if (!Lp->isLoopInvariant(Stride))
3598 // If we have stripped off the recurrence cast we have to make sure that we
3599 // return the value that is used in this loop so that we can replace it later.
3600 if (StripedOffRecurrenceCast)
3601 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3606 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3608 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3609 Ptr = LI->getPointerOperand();
3610 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3611 Ptr = SI->getPointerOperand();
3615 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3619 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3620 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3621 Strides[Ptr] = Stride;
3622 StrideSet.insert(Stride);
3625 void LoopVectorizationLegality::collectLoopUniforms() {
3626 // We now know that the loop is vectorizable!
3627 // Collect variables that will remain uniform after vectorization.
3628 std::vector<Value*> Worklist;
3629 BasicBlock *Latch = TheLoop->getLoopLatch();
3631 // Start with the conditional branch and walk up the block.
3632 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3634 while (Worklist.size()) {
3635 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3636 Worklist.pop_back();
3638 // Look at instructions inside this loop.
3639 // Stop when reaching PHI nodes.
3640 // TODO: we need to follow values all over the loop, not only in this block.
3641 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3644 // This is a known uniform.
3647 // Insert all operands.
3648 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3653 /// \brief Analyses memory accesses in a loop.
3655 /// Checks whether run time pointer checks are needed and builds sets for data
3656 /// dependence checking.
3657 class AccessAnalysis {
3659 /// \brief Read or write access location.
3660 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3661 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3663 /// \brief Set of potential dependent memory accesses.
3664 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3666 AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
3667 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3668 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3670 /// \brief Register a load and whether it is only read from.
3671 void addLoad(Value *Ptr, bool IsReadOnly) {
3672 Accesses.insert(MemAccessInfo(Ptr, false));
3674 ReadOnlyPtr.insert(Ptr);
3677 /// \brief Register a store.
3678 void addStore(Value *Ptr) {
3679 Accesses.insert(MemAccessInfo(Ptr, true));
3682 /// \brief Check whether we can check the pointers at runtime for
3683 /// non-intersection.
3684 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3685 unsigned &NumComparisons, ScalarEvolution *SE,
3686 Loop *TheLoop, ValueToValueMap &Strides,
3687 bool ShouldCheckStride = false);
3689 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3690 /// and builds sets of dependent accesses.
3691 void buildDependenceSets() {
3692 // Process read-write pointers first.
3693 processMemAccesses(false);
3694 // Next, process read pointers.
3695 processMemAccesses(true);
3698 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3700 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3701 void resetDepChecks() { CheckDeps.clear(); }
3703 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3706 typedef SetVector<MemAccessInfo> PtrAccessSet;
3707 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3709 /// \brief Go over all memory access or only the deferred ones if
3710 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3711 /// and build sets of dependency check candidates.
3712 void processMemAccesses(bool UseDeferred);
3714 /// Set of all accesses.
3715 PtrAccessSet Accesses;
3717 /// Set of access to check after all writes have been processed.
3718 PtrAccessSet DeferredAccesses;
3720 /// Map of pointers to last access encountered.
3721 UnderlyingObjToAccessMap ObjToLastAccess;
3723 /// Set of accesses that need a further dependence check.
3724 MemAccessInfoSet CheckDeps;
3726 /// Set of pointers that are read only.
3727 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3729 /// Set of underlying objects already written to.
3730 SmallPtrSet<Value*, 16> WriteObjects;
3734 /// Sets of potentially dependent accesses - members of one set share an
3735 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3736 /// dependence check.
3737 DepCandidates &DepCands;
3739 bool AreAllWritesIdentified;
3740 bool AreAllReadsIdentified;
3741 bool IsRTCheckNeeded;
3744 } // end anonymous namespace
3746 /// \brief Check whether a pointer can participate in a runtime bounds check.
3747 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3749 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3750 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3754 return AR->isAffine();
3757 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3758 /// the address space.
3759 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3760 const Loop *Lp, ValueToValueMap &StridesMap);
3762 bool AccessAnalysis::canCheckPtrAtRT(
3763 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3764 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3765 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3766 // Find pointers with computable bounds. We are going to use this information
3767 // to place a runtime bound check.
3768 unsigned NumReadPtrChecks = 0;
3769 unsigned NumWritePtrChecks = 0;
3770 bool CanDoRT = true;
3772 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3773 // We assign consecutive id to access from different dependence sets.
3774 // Accesses within the same set don't need a runtime check.
3775 unsigned RunningDepId = 1;
3776 DenseMap<Value *, unsigned> DepSetId;
3778 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3780 const MemAccessInfo &Access = *AI;
3781 Value *Ptr = Access.getPointer();
3782 bool IsWrite = Access.getInt();
3784 // Just add write checks if we have both.
3785 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3789 ++NumWritePtrChecks;
3793 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3794 // When we run after a failing dependency check we have to make sure we
3795 // don't have wrapping pointers.
3796 (!ShouldCheckStride ||
3797 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3798 // The id of the dependence set.
3801 if (IsDepCheckNeeded) {
3802 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3803 unsigned &LeaderId = DepSetId[Leader];
3805 LeaderId = RunningDepId++;
3808 // Each access has its own dependence set.
3809 DepId = RunningDepId++;
3811 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3813 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3819 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3820 NumComparisons = 0; // Only one dependence set.
3822 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3823 NumWritePtrChecks - 1));
3826 // If the pointers that we would use for the bounds comparison have different
3827 // address spaces, assume the values aren't directly comparable, so we can't
3828 // use them for the runtime check. We also have to assume they could
3829 // overlap. In the future there should be metadata for whether address spaces
3831 unsigned NumPointers = RtCheck.Pointers.size();
3832 for (unsigned i = 0; i < NumPointers; ++i) {
3833 for (unsigned j = i + 1; j < NumPointers; ++j) {
3834 // Only need to check pointers between two different dependency sets.
3835 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3838 Value *PtrI = RtCheck.Pointers[i];
3839 Value *PtrJ = RtCheck.Pointers[j];
3841 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3842 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3844 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3845 " different address spaces\n");
3854 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3855 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3858 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3859 // We process the set twice: first we process read-write pointers, last we
3860 // process read-only pointers. This allows us to skip dependence tests for
3861 // read-only pointers.
3863 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3864 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3865 const MemAccessInfo &Access = *AI;
3866 Value *Ptr = Access.getPointer();
3867 bool IsWrite = Access.getInt();
3869 DepCands.insert(Access);
3871 // Memorize read-only pointers for later processing and skip them in the
3872 // first round (they need to be checked after we have seen all write
3873 // pointers). Note: we also mark pointer that are not consecutive as
3874 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3875 // second check for "!IsWrite".
3876 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3877 if (!UseDeferred && IsReadOnlyPtr) {
3878 DeferredAccesses.insert(Access);
3882 bool NeedDepCheck = false;
3883 // Check whether there is the possibility of dependency because of
3884 // underlying objects being the same.
3885 typedef SmallVector<Value*, 16> ValueVector;
3886 ValueVector TempObjects;
3887 GetUnderlyingObjects(Ptr, TempObjects, DL);
3888 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3890 Value *UnderlyingObj = *UI;
3892 // If this is a write then it needs to be an identified object. If this a
3893 // read and all writes (so far) are identified function scope objects we
3894 // don't need an identified underlying object but only an Argument (the
3895 // next write is going to invalidate this assumption if it is
3897 // This is a micro-optimization for the case where all writes are
3898 // identified and we have one argument pointer.
3899 // Otherwise, we do need a runtime check.
3900 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3901 (!IsWrite && (!AreAllWritesIdentified ||
3902 !isa<Argument>(UnderlyingObj)) &&
3903 !isIdentifiedObject(UnderlyingObj))) {
3904 DEBUG(dbgs() << "LV: Found an unidentified " <<
3905 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3907 IsRTCheckNeeded = (IsRTCheckNeeded ||
3908 !isIdentifiedObject(UnderlyingObj) ||
3909 !AreAllReadsIdentified);
3912 AreAllWritesIdentified = false;
3914 AreAllReadsIdentified = false;
3917 // If this is a write - check other reads and writes for conflicts. If
3918 // this is a read only check other writes for conflicts (but only if there
3919 // is no other write to the ptr - this is an optimization to catch "a[i] =
3920 // a[i] + " without having to do a dependence check).
3921 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3922 NeedDepCheck = true;
3925 WriteObjects.insert(UnderlyingObj);
3927 // Create sets of pointers connected by shared underlying objects.
3928 UnderlyingObjToAccessMap::iterator Prev =
3929 ObjToLastAccess.find(UnderlyingObj);
3930 if (Prev != ObjToLastAccess.end())
3931 DepCands.unionSets(Access, Prev->second);
3933 ObjToLastAccess[UnderlyingObj] = Access;
3937 CheckDeps.insert(Access);
3942 /// \brief Checks memory dependences among accesses to the same underlying
3943 /// object to determine whether there vectorization is legal or not (and at
3944 /// which vectorization factor).
3946 /// This class works under the assumption that we already checked that memory
3947 /// locations with different underlying pointers are "must-not alias".
3948 /// We use the ScalarEvolution framework to symbolically evalutate access
3949 /// functions pairs. Since we currently don't restructure the loop we can rely
3950 /// on the program order of memory accesses to determine their safety.
3951 /// At the moment we will only deem accesses as safe for:
3952 /// * A negative constant distance assuming program order.
3954 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
3955 /// a[i] = tmp; y = a[i];
3957 /// The latter case is safe because later checks guarantuee that there can't
3958 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
3959 /// the same variable: a header phi can only be an induction or a reduction, a
3960 /// reduction can't have a memory sink, an induction can't have a memory
3961 /// source). This is important and must not be violated (or we have to
3962 /// resort to checking for cycles through memory).
3964 /// * A positive constant distance assuming program order that is bigger
3965 /// than the biggest memory access.
3967 /// tmp = a[i] OR b[i] = x
3968 /// a[i+2] = tmp y = b[i+2];
3970 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3972 /// * Zero distances and all accesses have the same size.
3974 class MemoryDepChecker {
3976 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3977 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3979 MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L)
3980 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
3981 ShouldRetryWithRuntimeCheck(false) {}
3983 /// \brief Register the location (instructions are given increasing numbers)
3984 /// of a write access.
3985 void addAccess(StoreInst *SI) {
3986 Value *Ptr = SI->getPointerOperand();
3987 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3988 InstMap.push_back(SI);
3992 /// \brief Register the location (instructions are given increasing numbers)
3993 /// of a write access.
3994 void addAccess(LoadInst *LI) {
3995 Value *Ptr = LI->getPointerOperand();
3996 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
3997 InstMap.push_back(LI);
4001 /// \brief Check whether the dependencies between the accesses are safe.
4003 /// Only checks sets with elements in \p CheckDeps.
4004 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4005 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4007 /// \brief The maximum number of bytes of a vector register we can vectorize
4008 /// the accesses safely with.
4009 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4011 /// \brief In same cases when the dependency check fails we can still
4012 /// vectorize the loop with a dynamic array access check.
4013 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4016 ScalarEvolution *SE;
4018 const Loop *InnermostLoop;
4020 /// \brief Maps access locations (ptr, read/write) to program order.
4021 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4023 /// \brief Memory access instructions in program order.
4024 SmallVector<Instruction *, 16> InstMap;
4026 /// \brief The program order index to be used for the next instruction.
4029 // We can access this many bytes in parallel safely.
4030 unsigned MaxSafeDepDistBytes;
4032 /// \brief If we see a non-constant dependence distance we can still try to
4033 /// vectorize this loop with runtime checks.
4034 bool ShouldRetryWithRuntimeCheck;
4036 /// \brief Check whether there is a plausible dependence between the two
4039 /// Access \p A must happen before \p B in program order. The two indices
4040 /// identify the index into the program order map.
4042 /// This function checks whether there is a plausible dependence (or the
4043 /// absence of such can't be proved) between the two accesses. If there is a
4044 /// plausible dependence but the dependence distance is bigger than one
4045 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4046 /// distance is smaller than any other distance encountered so far).
4047 /// Otherwise, this function returns true signaling a possible dependence.
4048 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4049 const MemAccessInfo &B, unsigned BIdx,
4050 ValueToValueMap &Strides);
4052 /// \brief Check whether the data dependence could prevent store-load
4054 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4057 } // end anonymous namespace
4059 static bool isInBoundsGep(Value *Ptr) {
4060 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4061 return GEP->isInBounds();
4065 /// \brief Check whether the access through \p Ptr has a constant stride.
4066 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
4067 const Loop *Lp, ValueToValueMap &StridesMap) {
4068 const Type *Ty = Ptr->getType();
4069 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4071 // Make sure that the pointer does not point to aggregate types.
4072 const PointerType *PtrTy = cast<PointerType>(Ty);
4073 if (PtrTy->getElementType()->isAggregateType()) {
4074 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4079 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4081 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4083 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4084 << *Ptr << " SCEV: " << *PtrScev << "\n");
4088 // The accesss function must stride over the innermost loop.
4089 if (Lp != AR->getLoop()) {
4090 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4091 *Ptr << " SCEV: " << *PtrScev << "\n");
4094 // The address calculation must not wrap. Otherwise, a dependence could be
4096 // An inbounds getelementptr that is a AddRec with a unit stride
4097 // cannot wrap per definition. The unit stride requirement is checked later.
4098 // An getelementptr without an inbounds attribute and unit stride would have
4099 // to access the pointer value "0" which is undefined behavior in address
4100 // space 0, therefore we can also vectorize this case.
4101 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4102 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4103 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4104 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4105 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4106 << *Ptr << " SCEV: " << *PtrScev << "\n");
4110 // Check the step is constant.
4111 const SCEV *Step = AR->getStepRecurrence(*SE);
4113 // Calculate the pointer stride and check if it is consecutive.
4114 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4116 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4117 " SCEV: " << *PtrScev << "\n");
4121 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4122 const APInt &APStepVal = C->getValue()->getValue();
4124 // Huge step value - give up.
4125 if (APStepVal.getBitWidth() > 64)
4128 int64_t StepVal = APStepVal.getSExtValue();
4131 int64_t Stride = StepVal / Size;
4132 int64_t Rem = StepVal % Size;
4136 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4137 // know we can't "wrap around the address space". In case of address space
4138 // zero we know that this won't happen without triggering undefined behavior.
4139 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4140 Stride != 1 && Stride != -1)
4146 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4147 unsigned TypeByteSize) {
4148 // If loads occur at a distance that is not a multiple of a feasible vector
4149 // factor store-load forwarding does not take place.
4150 // Positive dependences might cause troubles because vectorizing them might
4151 // prevent store-load forwarding making vectorized code run a lot slower.
4152 // a[i] = a[i-3] ^ a[i-8];
4153 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4154 // hence on your typical architecture store-load forwarding does not take
4155 // place. Vectorizing in such cases does not make sense.
4156 // Store-load forwarding distance.
4157 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4158 // Maximum vector factor.
4159 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4160 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4161 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4163 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4165 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4166 MaxVFWithoutSLForwardIssues = (vf >>=1);
4171 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4172 DEBUG(dbgs() << "LV: Distance " << Distance <<
4173 " that could cause a store-load forwarding conflict\n");
4177 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4178 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4179 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4183 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4184 const MemAccessInfo &B, unsigned BIdx,
4185 ValueToValueMap &Strides) {
4186 assert (AIdx < BIdx && "Must pass arguments in program order");
4188 Value *APtr = A.getPointer();
4189 Value *BPtr = B.getPointer();
4190 bool AIsWrite = A.getInt();
4191 bool BIsWrite = B.getInt();
4193 // Two reads are independent.
4194 if (!AIsWrite && !BIsWrite)
4197 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4198 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4200 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4201 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4203 const SCEV *Src = AScev;
4204 const SCEV *Sink = BScev;
4206 // If the induction step is negative we have to invert source and sink of the
4208 if (StrideAPtr < 0) {
4211 std::swap(APtr, BPtr);
4212 std::swap(Src, Sink);
4213 std::swap(AIsWrite, BIsWrite);
4214 std::swap(AIdx, BIdx);
4215 std::swap(StrideAPtr, StrideBPtr);
4218 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4220 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4221 << "(Induction step: " << StrideAPtr << ")\n");
4222 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4223 << *InstMap[BIdx] << ": " << *Dist << "\n");
4225 // Need consecutive accesses. We don't want to vectorize
4226 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4227 // the address space.
4228 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4229 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4233 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4235 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4236 ShouldRetryWithRuntimeCheck = true;
4240 Type *ATy = APtr->getType()->getPointerElementType();
4241 Type *BTy = BPtr->getType()->getPointerElementType();
4242 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4244 // Negative distances are not plausible dependencies.
4245 const APInt &Val = C->getValue()->getValue();
4246 if (Val.isNegative()) {
4247 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4248 if (IsTrueDataDependence &&
4249 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4253 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4257 // Write to the same location with the same size.
4258 // Could be improved to assert type sizes are the same (i32 == float, etc).
4262 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4266 assert(Val.isStrictlyPositive() && "Expect a positive value");
4268 // Positive distance bigger than max vectorization factor.
4271 "LV: ReadWrite-Write positive dependency with different types\n");
4275 unsigned Distance = (unsigned) Val.getZExtValue();
4277 // Bail out early if passed-in parameters make vectorization not feasible.
4278 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4279 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4281 // The distance must be bigger than the size needed for a vectorized version
4282 // of the operation and the size of the vectorized operation must not be
4283 // bigger than the currrent maximum size.
4284 if (Distance < 2*TypeByteSize ||
4285 2*TypeByteSize > MaxSafeDepDistBytes ||
4286 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4287 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4288 << Val.getSExtValue() << '\n');
4292 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4293 Distance : MaxSafeDepDistBytes;
4295 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4296 if (IsTrueDataDependence &&
4297 couldPreventStoreLoadForward(Distance, TypeByteSize))
4300 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4301 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4306 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4307 MemAccessInfoSet &CheckDeps,
4308 ValueToValueMap &Strides) {
4310 MaxSafeDepDistBytes = -1U;
4311 while (!CheckDeps.empty()) {
4312 MemAccessInfo CurAccess = *CheckDeps.begin();
4314 // Get the relevant memory access set.
4315 EquivalenceClasses<MemAccessInfo>::iterator I =
4316 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4318 // Check accesses within this set.
4319 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4320 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4322 // Check every access pair.
4324 CheckDeps.erase(*AI);
4325 EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
4327 // Check every accessing instruction pair in program order.
4328 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4329 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4330 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4331 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4332 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4334 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4345 bool LoopVectorizationLegality::canVectorizeMemory() {
4347 typedef SmallVector<Value*, 16> ValueVector;
4348 typedef SmallPtrSet<Value*, 16> ValueSet;
4350 // Holds the Load and Store *instructions*.
4354 // Holds all the different accesses in the loop.
4355 unsigned NumReads = 0;
4356 unsigned NumReadWrites = 0;
4358 PtrRtCheck.Pointers.clear();
4359 PtrRtCheck.Need = false;
4361 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4362 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4365 for (Loop::block_iterator bb = TheLoop->block_begin(),
4366 be = TheLoop->block_end(); bb != be; ++bb) {
4368 // Scan the BB and collect legal loads and stores.
4369 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4372 // If this is a load, save it. If this instruction can read from memory
4373 // but is not a load, then we quit. Notice that we don't handle function
4374 // calls that read or write.
4375 if (it->mayReadFromMemory()) {
4376 // Many math library functions read the rounding mode. We will only
4377 // vectorize a loop if it contains known function calls that don't set
4378 // the flag. Therefore, it is safe to ignore this read from memory.
4379 CallInst *Call = dyn_cast<CallInst>(it);
4380 if (Call && getIntrinsicIDForCall(Call, TLI))
4383 LoadInst *Ld = dyn_cast<LoadInst>(it);
4384 if (!Ld) return false;
4385 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4386 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4390 Loads.push_back(Ld);
4391 DepChecker.addAccess(Ld);
4395 // Save 'store' instructions. Abort if other instructions write to memory.
4396 if (it->mayWriteToMemory()) {
4397 StoreInst *St = dyn_cast<StoreInst>(it);
4398 if (!St) return false;
4399 if (!St->isSimple() && !IsAnnotatedParallel) {
4400 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4404 Stores.push_back(St);
4405 DepChecker.addAccess(St);
4410 // Now we have two lists that hold the loads and the stores.
4411 // Next, we find the pointers that they use.
4413 // Check if we see any stores. If there are no stores, then we don't
4414 // care if the pointers are *restrict*.
4415 if (!Stores.size()) {
4416 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4420 AccessAnalysis::DepCandidates DependentAccesses;
4421 AccessAnalysis Accesses(DL, DependentAccesses);
4423 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4424 // multiple times on the same object. If the ptr is accessed twice, once
4425 // for read and once for write, it will only appear once (on the write
4426 // list). This is okay, since we are going to check for conflicts between
4427 // writes and between reads and writes, but not between reads and reads.
4430 ValueVector::iterator I, IE;
4431 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4432 StoreInst *ST = cast<StoreInst>(*I);
4433 Value* Ptr = ST->getPointerOperand();
4435 if (isUniform(Ptr)) {
4436 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4440 // If we did *not* see this pointer before, insert it to the read-write
4441 // list. At this phase it is only a 'write' list.
4442 if (Seen.insert(Ptr)) {
4444 Accesses.addStore(Ptr);
4448 if (IsAnnotatedParallel) {
4450 << "LV: A loop annotated parallel, ignore memory dependency "
4455 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4456 LoadInst *LD = cast<LoadInst>(*I);
4457 Value* Ptr = LD->getPointerOperand();
4458 // If we did *not* see this pointer before, insert it to the
4459 // read list. If we *did* see it before, then it is already in
4460 // the read-write list. This allows us to vectorize expressions
4461 // such as A[i] += x; Because the address of A[i] is a read-write
4462 // pointer. This only works if the index of A[i] is consecutive.
4463 // If the address of i is unknown (for example A[B[i]]) then we may
4464 // read a few words, modify, and write a few words, and some of the
4465 // words may be written to the same address.
4466 bool IsReadOnlyPtr = false;
4467 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4469 IsReadOnlyPtr = true;
4471 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4474 // If we write (or read-write) to a single destination and there are no
4475 // other reads in this loop then is it safe to vectorize.
4476 if (NumReadWrites == 1 && NumReads == 0) {
4477 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4481 // Build dependence sets and check whether we need a runtime pointer bounds
4483 Accesses.buildDependenceSets();
4484 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4486 // Find pointers with computable bounds. We are going to use this information
4487 // to place a runtime bound check.
4488 unsigned NumComparisons = 0;
4489 bool CanDoRT = false;
4491 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4494 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4495 " pointer comparisons.\n");
4497 // If we only have one set of dependences to check pointers among we don't
4498 // need a runtime check.
4499 if (NumComparisons == 0 && NeedRTCheck)
4500 NeedRTCheck = false;
4502 // Check that we did not collect too many pointers or found an unsizeable
4504 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4510 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4513 if (NeedRTCheck && !CanDoRT) {
4514 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4515 "the array bounds.\n");
4520 PtrRtCheck.Need = NeedRTCheck;
4522 bool CanVecMem = true;
4523 if (Accesses.isDependencyCheckNeeded()) {
4524 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4525 CanVecMem = DepChecker.areDepsSafe(
4526 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4527 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4529 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4530 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4533 // Clear the dependency checks. We assume they are not needed.
4534 Accesses.resetDepChecks();
4537 PtrRtCheck.Need = true;
4539 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4540 TheLoop, Strides, true);
4541 // Check that we did not collect too many pointers or found an unsizeable
4543 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4544 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4553 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4554 " need a runtime memory check.\n");
4559 static bool hasMultipleUsesOf(Instruction *I,
4560 SmallPtrSet<Instruction *, 8> &Insts) {
4561 unsigned NumUses = 0;
4562 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4563 if (Insts.count(dyn_cast<Instruction>(*Use)))
4572 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4573 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4574 if (!Set.count(dyn_cast<Instruction>(*Use)))
4579 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4580 ReductionKind Kind) {
4581 if (Phi->getNumIncomingValues() != 2)
4584 // Reduction variables are only found in the loop header block.
4585 if (Phi->getParent() != TheLoop->getHeader())
4588 // Obtain the reduction start value from the value that comes from the loop
4590 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4592 // ExitInstruction is the single value which is used outside the loop.
4593 // We only allow for a single reduction value to be used outside the loop.
4594 // This includes users of the reduction, variables (which form a cycle
4595 // which ends in the phi node).
4596 Instruction *ExitInstruction = 0;
4597 // Indicates that we found a reduction operation in our scan.
4598 bool FoundReduxOp = false;
4600 // We start with the PHI node and scan for all of the users of this
4601 // instruction. All users must be instructions that can be used as reduction
4602 // variables (such as ADD). We must have a single out-of-block user. The cycle
4603 // must include the original PHI.
4604 bool FoundStartPHI = false;
4606 // To recognize min/max patterns formed by a icmp select sequence, we store
4607 // the number of instruction we saw from the recognized min/max pattern,
4608 // to make sure we only see exactly the two instructions.
4609 unsigned NumCmpSelectPatternInst = 0;
4610 ReductionInstDesc ReduxDesc(false, 0);
4612 SmallPtrSet<Instruction *, 8> VisitedInsts;
4613 SmallVector<Instruction *, 8> Worklist;
4614 Worklist.push_back(Phi);
4615 VisitedInsts.insert(Phi);
4617 // A value in the reduction can be used:
4618 // - By the reduction:
4619 // - Reduction operation:
4620 // - One use of reduction value (safe).
4621 // - Multiple use of reduction value (not safe).
4623 // - All uses of the PHI must be the reduction (safe).
4624 // - Otherwise, not safe.
4625 // - By one instruction outside of the loop (safe).
4626 // - By further instructions outside of the loop (not safe).
4627 // - By an instruction that is not part of the reduction (not safe).
4629 // * An instruction type other than PHI or the reduction operation.
4630 // * A PHI in the header other than the initial PHI.
4631 while (!Worklist.empty()) {
4632 Instruction *Cur = Worklist.back();
4633 Worklist.pop_back();
4636 // If the instruction has no users then this is a broken chain and can't be
4637 // a reduction variable.
4638 if (Cur->use_empty())
4641 bool IsAPhi = isa<PHINode>(Cur);
4643 // A header PHI use other than the original PHI.
4644 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4647 // Reductions of instructions such as Div, and Sub is only possible if the
4648 // LHS is the reduction variable.
4649 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4650 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4651 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4654 // Any reduction instruction must be of one of the allowed kinds.
4655 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4656 if (!ReduxDesc.IsReduction)
4659 // A reduction operation must only have one use of the reduction value.
4660 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4661 hasMultipleUsesOf(Cur, VisitedInsts))
4664 // All inputs to a PHI node must be a reduction value.
4665 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4668 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4669 isa<SelectInst>(Cur)))
4670 ++NumCmpSelectPatternInst;
4671 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4672 isa<SelectInst>(Cur)))
4673 ++NumCmpSelectPatternInst;
4675 // Check whether we found a reduction operator.
4676 FoundReduxOp |= !IsAPhi;
4678 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4679 // onto the stack. This way we are going to have seen all inputs to PHI
4680 // nodes once we get to them.
4681 SmallVector<Instruction *, 8> NonPHIs;
4682 SmallVector<Instruction *, 8> PHIs;
4683 for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
4685 Instruction *Usr = cast<Instruction>(*UI);
4687 // Check if we found the exit user.
4688 BasicBlock *Parent = Usr->getParent();
4689 if (!TheLoop->contains(Parent)) {
4690 // Exit if you find multiple outside users or if the header phi node is
4691 // being used. In this case the user uses the value of the previous
4692 // iteration, in which case we would loose "VF-1" iterations of the
4693 // reduction operation if we vectorize.
4694 if (ExitInstruction != 0 || Cur == Phi)
4697 // The instruction used by an outside user must be the last instruction
4698 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4699 // operations on the value.
4700 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4703 ExitInstruction = Cur;
4707 // Process instructions only once (termination). Each reduction cycle
4708 // value must only be used once, except by phi nodes and min/max
4709 // reductions which are represented as a cmp followed by a select.
4710 ReductionInstDesc IgnoredVal(false, 0);
4711 if (VisitedInsts.insert(Usr)) {
4712 if (isa<PHINode>(Usr))
4713 PHIs.push_back(Usr);
4715 NonPHIs.push_back(Usr);
4716 } else if (!isa<PHINode>(Usr) &&
4717 ((!isa<FCmpInst>(Usr) &&
4718 !isa<ICmpInst>(Usr) &&
4719 !isa<SelectInst>(Usr)) ||
4720 !isMinMaxSelectCmpPattern(Usr, IgnoredVal).IsReduction))
4723 // Remember that we completed the cycle.
4725 FoundStartPHI = true;
4727 Worklist.append(PHIs.begin(), PHIs.end());
4728 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4731 // This means we have seen one but not the other instruction of the
4732 // pattern or more than just a select and cmp.
4733 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4734 NumCmpSelectPatternInst != 2)
4737 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4740 // We found a reduction var if we have reached the original phi node and we
4741 // only have a single instruction with out-of-loop users.
4743 // This instruction is allowed to have out-of-loop users.
4744 AllowedExit.insert(ExitInstruction);
4746 // Save the description of this reduction variable.
4747 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4748 ReduxDesc.MinMaxKind);
4749 Reductions[Phi] = RD;
4750 // We've ended the cycle. This is a reduction variable if we have an
4751 // outside user and it has a binary op.
4756 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4757 /// pattern corresponding to a min(X, Y) or max(X, Y).
4758 LoopVectorizationLegality::ReductionInstDesc
4759 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4760 ReductionInstDesc &Prev) {
4762 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4763 "Expect a select instruction");
4764 Instruction *Cmp = 0;
4765 SelectInst *Select = 0;
4767 // We must handle the select(cmp()) as a single instruction. Advance to the
4769 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4770 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
4771 return ReductionInstDesc(false, I);
4772 return ReductionInstDesc(Select, Prev.MinMaxKind);
4775 // Only handle single use cases for now.
4776 if (!(Select = dyn_cast<SelectInst>(I)))
4777 return ReductionInstDesc(false, I);
4778 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4779 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4780 return ReductionInstDesc(false, I);
4781 if (!Cmp->hasOneUse())
4782 return ReductionInstDesc(false, I);
4787 // Look for a min/max pattern.
4788 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4789 return ReductionInstDesc(Select, MRK_UIntMin);
4790 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4791 return ReductionInstDesc(Select, MRK_UIntMax);
4792 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4793 return ReductionInstDesc(Select, MRK_SIntMax);
4794 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4795 return ReductionInstDesc(Select, MRK_SIntMin);
4796 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4797 return ReductionInstDesc(Select, MRK_FloatMin);
4798 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4799 return ReductionInstDesc(Select, MRK_FloatMax);
4800 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4801 return ReductionInstDesc(Select, MRK_FloatMin);
4802 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4803 return ReductionInstDesc(Select, MRK_FloatMax);
4805 return ReductionInstDesc(false, I);
4808 LoopVectorizationLegality::ReductionInstDesc
4809 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4811 ReductionInstDesc &Prev) {
4812 bool FP = I->getType()->isFloatingPointTy();
4813 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4814 switch (I->getOpcode()) {
4816 return ReductionInstDesc(false, I);
4817 case Instruction::PHI:
4818 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4819 Kind != RK_FloatMinMax))
4820 return ReductionInstDesc(false, I);
4821 return ReductionInstDesc(I, Prev.MinMaxKind);
4822 case Instruction::Sub:
4823 case Instruction::Add:
4824 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4825 case Instruction::Mul:
4826 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4827 case Instruction::And:
4828 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4829 case Instruction::Or:
4830 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4831 case Instruction::Xor:
4832 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4833 case Instruction::FMul:
4834 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4835 case Instruction::FAdd:
4836 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4837 case Instruction::FCmp:
4838 case Instruction::ICmp:
4839 case Instruction::Select:
4840 if (Kind != RK_IntegerMinMax &&
4841 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4842 return ReductionInstDesc(false, I);
4843 return isMinMaxSelectCmpPattern(I, Prev);
4847 LoopVectorizationLegality::InductionKind
4848 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4849 Type *PhiTy = Phi->getType();
4850 // We only handle integer and pointer inductions variables.
4851 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4852 return IK_NoInduction;
4854 // Check that the PHI is consecutive.
4855 const SCEV *PhiScev = SE->getSCEV(Phi);
4856 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4858 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4859 return IK_NoInduction;
4861 const SCEV *Step = AR->getStepRecurrence(*SE);
4863 // Integer inductions need to have a stride of one.
4864 if (PhiTy->isIntegerTy()) {
4866 return IK_IntInduction;
4867 if (Step->isAllOnesValue())
4868 return IK_ReverseIntInduction;
4869 return IK_NoInduction;
4872 // Calculate the pointer stride and check if it is consecutive.
4873 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4875 return IK_NoInduction;
4877 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4878 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4879 if (C->getValue()->equalsInt(Size))
4880 return IK_PtrInduction;
4881 else if (C->getValue()->equalsInt(0 - Size))
4882 return IK_ReversePtrInduction;
4884 return IK_NoInduction;
4887 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4888 Value *In0 = const_cast<Value*>(V);
4889 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4893 return Inductions.count(PN);
4896 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4897 assert(TheLoop->contains(BB) && "Unknown block used");
4899 // Blocks that do not dominate the latch need predication.
4900 BasicBlock* Latch = TheLoop->getLoopLatch();
4901 return !DT->dominates(BB, Latch);
4904 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4905 SmallPtrSet<Value *, 8>& SafePtrs) {
4906 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4907 // We might be able to hoist the load.
4908 if (it->mayReadFromMemory()) {
4909 LoadInst *LI = dyn_cast<LoadInst>(it);
4910 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4914 // We don't predicate stores at the moment.
4915 if (it->mayWriteToMemory()) {
4916 StoreInst *SI = dyn_cast<StoreInst>(it);
4917 // We only support predication of stores in basic blocks with one
4919 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
4920 !SafePtrs.count(SI->getPointerOperand()) ||
4921 !SI->getParent()->getSinglePredecessor())
4927 // Check that we don't have a constant expression that can trap as operand.
4928 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4930 if (Constant *C = dyn_cast<Constant>(*OI))
4935 // The instructions below can trap.
4936 switch (it->getOpcode()) {
4938 case Instruction::UDiv:
4939 case Instruction::SDiv:
4940 case Instruction::URem:
4941 case Instruction::SRem:
4949 LoopVectorizationCostModel::VectorizationFactor
4950 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4952 // Width 1 means no vectorize
4953 VectorizationFactor Factor = { 1U, 0U };
4954 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4955 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4959 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
4960 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4964 // Find the trip count.
4965 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4966 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4968 unsigned WidestType = getWidestType();
4969 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4970 unsigned MaxSafeDepDist = -1U;
4971 if (Legal->getMaxSafeDepDistBytes() != -1U)
4972 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4973 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4974 WidestRegister : MaxSafeDepDist);
4975 unsigned MaxVectorSize = WidestRegister / WidestType;
4976 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4977 DEBUG(dbgs() << "LV: The Widest register is: "
4978 << WidestRegister << " bits.\n");
4980 if (MaxVectorSize == 0) {
4981 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4985 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4986 " into one vector!");
4988 unsigned VF = MaxVectorSize;
4990 // If we optimize the program for size, avoid creating the tail loop.
4992 // If we are unable to calculate the trip count then don't try to vectorize.
4994 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4998 // Find the maximum SIMD width that can fit within the trip count.
4999 VF = TC % MaxVectorSize;
5004 // If the trip count that we found modulo the vectorization factor is not
5005 // zero then we require a tail.
5007 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5013 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5014 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5016 Factor.Width = UserVF;
5020 float Cost = expectedCost(1);
5022 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
5023 for (unsigned i=2; i <= VF; i*=2) {
5024 // Notice that the vector loop needs to be executed less times, so
5025 // we need to divide the cost of the vector loops by the width of
5026 // the vector elements.
5027 float VectorCost = expectedCost(i) / (float)i;
5028 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5029 (int)VectorCost << ".\n");
5030 if (VectorCost < Cost) {
5036 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
5037 Factor.Width = Width;
5038 Factor.Cost = Width * Cost;
5042 unsigned LoopVectorizationCostModel::getWidestType() {
5043 unsigned MaxWidth = 8;
5046 for (Loop::block_iterator bb = TheLoop->block_begin(),
5047 be = TheLoop->block_end(); bb != be; ++bb) {
5048 BasicBlock *BB = *bb;
5050 // For each instruction in the loop.
5051 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5052 Type *T = it->getType();
5054 // Only examine Loads, Stores and PHINodes.
5055 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5058 // Examine PHI nodes that are reduction variables.
5059 if (PHINode *PN = dyn_cast<PHINode>(it))
5060 if (!Legal->getReductionVars()->count(PN))
5063 // Examine the stored values.
5064 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5065 T = ST->getValueOperand()->getType();
5067 // Ignore loaded pointer types and stored pointer types that are not
5068 // consecutive. However, we do want to take consecutive stores/loads of
5069 // pointer vectors into account.
5070 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5073 MaxWidth = std::max(MaxWidth,
5074 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5082 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5085 unsigned LoopCost) {
5087 // -- The unroll heuristics --
5088 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5089 // There are many micro-architectural considerations that we can't predict
5090 // at this level. For example frontend pressure (on decode or fetch) due to
5091 // code size, or the number and capabilities of the execution ports.
5093 // We use the following heuristics to select the unroll factor:
5094 // 1. If the code has reductions the we unroll in order to break the cross
5095 // iteration dependency.
5096 // 2. If the loop is really small then we unroll in order to reduce the loop
5098 // 3. We don't unroll if we think that we will spill registers to memory due
5099 // to the increased register pressure.
5101 // Use the user preference, unless 'auto' is selected.
5105 // When we optimize for size we don't unroll.
5109 // We used the distance for the unroll factor.
5110 if (Legal->getMaxSafeDepDistBytes() != -1U)
5113 // Do not unroll loops with a relatively small trip count.
5114 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5115 TheLoop->getLoopLatch());
5116 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5119 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5120 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5124 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5125 TargetNumRegisters = ForceTargetNumScalarRegs;
5127 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5128 TargetNumRegisters = ForceTargetNumVectorRegs;
5131 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5132 // We divide by these constants so assume that we have at least one
5133 // instruction that uses at least one register.
5134 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5135 R.NumInstructions = std::max(R.NumInstructions, 1U);
5137 // We calculate the unroll factor using the following formula.
5138 // Subtract the number of loop invariants from the number of available
5139 // registers. These registers are used by all of the unrolled instances.
5140 // Next, divide the remaining registers by the number of registers that is
5141 // required by the loop, in order to estimate how many parallel instances
5142 // fit without causing spills. All of this is rounded down if necessary to be
5143 // a power of two. We want power of two unroll factors to simplify any
5144 // addressing operations or alignment considerations.
5145 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5148 // Clamp the unroll factor ranges to reasonable factors.
5149 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5151 // Check if the user has overridden the unroll max.
5153 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5154 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5156 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5157 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5160 // If we did not calculate the cost for VF (because the user selected the VF)
5161 // then we calculate the cost of VF here.
5163 LoopCost = expectedCost(VF);
5165 // Clamp the calculated UF to be between the 1 and the max unroll factor
5166 // that the target allows.
5167 if (UF > MaxUnrollSize)
5172 // Unroll if we vectorized this loop and there is a reduction that could
5173 // benefit from unrolling.
5174 if (VF > 1 && Legal->getReductionVars()->size()) {
5175 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5179 if (EnableLoadStoreRuntimeUnroll &&
5180 !Legal->getRuntimePointerCheck()->Need &&
5181 LoopCost < SmallLoopCost) {
5182 // Unroll until store/load ports (estimated by max unroll factor) are
5184 unsigned UnrollStores = UF / (Legal->NumStores ? Legal->NumStores : 1);
5185 unsigned UnrollLoads = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5186 UF = std::max(std::min(UnrollStores, UnrollLoads), 1u);
5190 // We want to unroll tiny loops in order to reduce the loop overhead.
5191 // We assume that the cost overhead is 1 and we use the cost model
5192 // to estimate the cost of the loop and unroll until the cost of the
5193 // loop overhead is about 5% of the cost of the loop.
5194 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5195 if (LoopCost < SmallLoopCost) {
5196 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5197 unsigned NewUF = PowerOf2Floor(SmallLoopCost / LoopCost);
5198 return std::min(NewUF, UF);
5201 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5205 LoopVectorizationCostModel::RegisterUsage
5206 LoopVectorizationCostModel::calculateRegisterUsage() {
5207 // This function calculates the register usage by measuring the highest number
5208 // of values that are alive at a single location. Obviously, this is a very
5209 // rough estimation. We scan the loop in a topological order in order and
5210 // assign a number to each instruction. We use RPO to ensure that defs are
5211 // met before their users. We assume that each instruction that has in-loop
5212 // users starts an interval. We record every time that an in-loop value is
5213 // used, so we have a list of the first and last occurrences of each
5214 // instruction. Next, we transpose this data structure into a multi map that
5215 // holds the list of intervals that *end* at a specific location. This multi
5216 // map allows us to perform a linear search. We scan the instructions linearly
5217 // and record each time that a new interval starts, by placing it in a set.
5218 // If we find this value in the multi-map then we remove it from the set.
5219 // The max register usage is the maximum size of the set.
5220 // We also search for instructions that are defined outside the loop, but are
5221 // used inside the loop. We need this number separately from the max-interval
5222 // usage number because when we unroll, loop-invariant values do not take
5224 LoopBlocksDFS DFS(TheLoop);
5228 R.NumInstructions = 0;
5230 // Each 'key' in the map opens a new interval. The values
5231 // of the map are the index of the 'last seen' usage of the
5232 // instruction that is the key.
5233 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5234 // Maps instruction to its index.
5235 DenseMap<unsigned, Instruction*> IdxToInstr;
5236 // Marks the end of each interval.
5237 IntervalMap EndPoint;
5238 // Saves the list of instruction indices that are used in the loop.
5239 SmallSet<Instruction*, 8> Ends;
5240 // Saves the list of values that are used in the loop but are
5241 // defined outside the loop, such as arguments and constants.
5242 SmallPtrSet<Value*, 8> LoopInvariants;
5245 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5246 be = DFS.endRPO(); bb != be; ++bb) {
5247 R.NumInstructions += (*bb)->size();
5248 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5250 Instruction *I = it;
5251 IdxToInstr[Index++] = I;
5253 // Save the end location of each USE.
5254 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5255 Value *U = I->getOperand(i);
5256 Instruction *Instr = dyn_cast<Instruction>(U);
5258 // Ignore non-instruction values such as arguments, constants, etc.
5259 if (!Instr) continue;
5261 // If this instruction is outside the loop then record it and continue.
5262 if (!TheLoop->contains(Instr)) {
5263 LoopInvariants.insert(Instr);
5267 // Overwrite previous end points.
5268 EndPoint[Instr] = Index;
5274 // Saves the list of intervals that end with the index in 'key'.
5275 typedef SmallVector<Instruction*, 2> InstrList;
5276 DenseMap<unsigned, InstrList> TransposeEnds;
5278 // Transpose the EndPoints to a list of values that end at each index.
5279 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5281 TransposeEnds[it->second].push_back(it->first);
5283 SmallSet<Instruction*, 8> OpenIntervals;
5284 unsigned MaxUsage = 0;
5287 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5288 for (unsigned int i = 0; i < Index; ++i) {
5289 Instruction *I = IdxToInstr[i];
5290 // Ignore instructions that are never used within the loop.
5291 if (!Ends.count(I)) continue;
5293 // Remove all of the instructions that end at this location.
5294 InstrList &List = TransposeEnds[i];
5295 for (unsigned int j=0, e = List.size(); j < e; ++j)
5296 OpenIntervals.erase(List[j]);
5298 // Count the number of live interals.
5299 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5301 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5302 OpenIntervals.size() << '\n');
5304 // Add the current instruction to the list of open intervals.
5305 OpenIntervals.insert(I);
5308 unsigned Invariant = LoopInvariants.size();
5309 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5310 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5311 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5313 R.LoopInvariantRegs = Invariant;
5314 R.MaxLocalUsers = MaxUsage;
5318 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5322 for (Loop::block_iterator bb = TheLoop->block_begin(),
5323 be = TheLoop->block_end(); bb != be; ++bb) {
5324 unsigned BlockCost = 0;
5325 BasicBlock *BB = *bb;
5327 // For each instruction in the old loop.
5328 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5329 // Skip dbg intrinsics.
5330 if (isa<DbgInfoIntrinsic>(it))
5333 unsigned C = getInstructionCost(it, VF);
5335 // Check if we should override the cost.
5336 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5337 C = ForceTargetInstructionCost;
5340 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5341 VF << " For instruction: " << *it << '\n');
5344 // We assume that if-converted blocks have a 50% chance of being executed.
5345 // When the code is scalar then some of the blocks are avoided due to CF.
5346 // When the code is vectorized we execute all code paths.
5347 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5356 /// \brief Check whether the address computation for a non-consecutive memory
5357 /// access looks like an unlikely candidate for being merged into the indexing
5360 /// We look for a GEP which has one index that is an induction variable and all
5361 /// other indices are loop invariant. If the stride of this access is also
5362 /// within a small bound we decide that this address computation can likely be
5363 /// merged into the addressing mode.
5364 /// In all other cases, we identify the address computation as complex.
5365 static bool isLikelyComplexAddressComputation(Value *Ptr,
5366 LoopVectorizationLegality *Legal,
5367 ScalarEvolution *SE,
5368 const Loop *TheLoop) {
5369 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5373 // We are looking for a gep with all loop invariant indices except for one
5374 // which should be an induction variable.
5375 unsigned NumOperands = Gep->getNumOperands();
5376 for (unsigned i = 1; i < NumOperands; ++i) {
5377 Value *Opd = Gep->getOperand(i);
5378 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5379 !Legal->isInductionVariable(Opd))
5383 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5384 // can likely be merged into the address computation.
5385 unsigned MaxMergeDistance = 64;
5387 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5391 // Check the step is constant.
5392 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5393 // Calculate the pointer stride and check if it is consecutive.
5394 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5398 const APInt &APStepVal = C->getValue()->getValue();
5400 // Huge step value - give up.
5401 if (APStepVal.getBitWidth() > 64)
5404 int64_t StepVal = APStepVal.getSExtValue();
5406 return StepVal > MaxMergeDistance;
5409 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5410 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5416 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5417 // If we know that this instruction will remain uniform, check the cost of
5418 // the scalar version.
5419 if (Legal->isUniformAfterVectorization(I))
5422 Type *RetTy = I->getType();
5423 Type *VectorTy = ToVectorTy(RetTy, VF);
5425 // TODO: We need to estimate the cost of intrinsic calls.
5426 switch (I->getOpcode()) {
5427 case Instruction::GetElementPtr:
5428 // We mark this instruction as zero-cost because the cost of GEPs in
5429 // vectorized code depends on whether the corresponding memory instruction
5430 // is scalarized or not. Therefore, we handle GEPs with the memory
5431 // instruction cost.
5433 case Instruction::Br: {
5434 return TTI.getCFInstrCost(I->getOpcode());
5436 case Instruction::PHI:
5437 //TODO: IF-converted IFs become selects.
5439 case Instruction::Add:
5440 case Instruction::FAdd:
5441 case Instruction::Sub:
5442 case Instruction::FSub:
5443 case Instruction::Mul:
5444 case Instruction::FMul:
5445 case Instruction::UDiv:
5446 case Instruction::SDiv:
5447 case Instruction::FDiv:
5448 case Instruction::URem:
5449 case Instruction::SRem:
5450 case Instruction::FRem:
5451 case Instruction::Shl:
5452 case Instruction::LShr:
5453 case Instruction::AShr:
5454 case Instruction::And:
5455 case Instruction::Or:
5456 case Instruction::Xor: {
5457 // Since we will replace the stride by 1 the multiplication should go away.
5458 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5460 // Certain instructions can be cheaper to vectorize if they have a constant
5461 // second vector operand. One example of this are shifts on x86.
5462 TargetTransformInfo::OperandValueKind Op1VK =
5463 TargetTransformInfo::OK_AnyValue;
5464 TargetTransformInfo::OperandValueKind Op2VK =
5465 TargetTransformInfo::OK_AnyValue;
5467 if (isa<ConstantInt>(I->getOperand(1)))
5468 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5470 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5472 case Instruction::Select: {
5473 SelectInst *SI = cast<SelectInst>(I);
5474 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5475 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5476 Type *CondTy = SI->getCondition()->getType();
5478 CondTy = VectorType::get(CondTy, VF);
5480 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5482 case Instruction::ICmp:
5483 case Instruction::FCmp: {
5484 Type *ValTy = I->getOperand(0)->getType();
5485 VectorTy = ToVectorTy(ValTy, VF);
5486 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5488 case Instruction::Store:
5489 case Instruction::Load: {
5490 StoreInst *SI = dyn_cast<StoreInst>(I);
5491 LoadInst *LI = dyn_cast<LoadInst>(I);
5492 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5494 VectorTy = ToVectorTy(ValTy, VF);
5496 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5497 unsigned AS = SI ? SI->getPointerAddressSpace() :
5498 LI->getPointerAddressSpace();
5499 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5500 // We add the cost of address computation here instead of with the gep
5501 // instruction because only here we know whether the operation is
5504 return TTI.getAddressComputationCost(VectorTy) +
5505 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5507 // Scalarized loads/stores.
5508 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5509 bool Reverse = ConsecutiveStride < 0;
5510 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5511 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5512 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5513 bool IsComplexComputation =
5514 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5516 // The cost of extracting from the value vector and pointer vector.
5517 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5518 for (unsigned i = 0; i < VF; ++i) {
5519 // The cost of extracting the pointer operand.
5520 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5521 // In case of STORE, the cost of ExtractElement from the vector.
5522 // In case of LOAD, the cost of InsertElement into the returned
5524 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5525 Instruction::InsertElement,
5529 // The cost of the scalar loads/stores.
5530 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5531 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5536 // Wide load/stores.
5537 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5538 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5541 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5545 case Instruction::ZExt:
5546 case Instruction::SExt:
5547 case Instruction::FPToUI:
5548 case Instruction::FPToSI:
5549 case Instruction::FPExt:
5550 case Instruction::PtrToInt:
5551 case Instruction::IntToPtr:
5552 case Instruction::SIToFP:
5553 case Instruction::UIToFP:
5554 case Instruction::Trunc:
5555 case Instruction::FPTrunc:
5556 case Instruction::BitCast: {
5557 // We optimize the truncation of induction variable.
5558 // The cost of these is the same as the scalar operation.
5559 if (I->getOpcode() == Instruction::Trunc &&
5560 Legal->isInductionVariable(I->getOperand(0)))
5561 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5562 I->getOperand(0)->getType());
5564 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5565 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5567 case Instruction::Call: {
5568 CallInst *CI = cast<CallInst>(I);
5569 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5570 assert(ID && "Not an intrinsic call!");
5571 Type *RetTy = ToVectorTy(CI->getType(), VF);
5572 SmallVector<Type*, 4> Tys;
5573 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5574 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5575 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5578 // We are scalarizing the instruction. Return the cost of the scalar
5579 // instruction, plus the cost of insert and extract into vector
5580 // elements, times the vector width.
5583 if (!RetTy->isVoidTy() && VF != 1) {
5584 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5586 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5589 // The cost of inserting the results plus extracting each one of the
5591 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5594 // The cost of executing VF copies of the scalar instruction. This opcode
5595 // is unknown. Assume that it is the same as 'mul'.
5596 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5602 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5603 if (Scalar->isVoidTy() || VF == 1)
5605 return VectorType::get(Scalar, VF);
5608 char LoopVectorize::ID = 0;
5609 static const char lv_name[] = "Loop Vectorization";
5610 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5611 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5612 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5613 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5614 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5615 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5616 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5617 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5618 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5621 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5622 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5626 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5627 // Check for a store.
5628 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5629 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5631 // Check for a load.
5632 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5633 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5639 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5640 bool IfPredicateStore) {
5641 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5642 // Holds vector parameters or scalars, in case of uniform vals.
5643 SmallVector<VectorParts, 4> Params;
5645 setDebugLocFromInst(Builder, Instr);
5647 // Find all of the vectorized parameters.
5648 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5649 Value *SrcOp = Instr->getOperand(op);
5651 // If we are accessing the old induction variable, use the new one.
5652 if (SrcOp == OldInduction) {
5653 Params.push_back(getVectorValue(SrcOp));
5657 // Try using previously calculated values.
5658 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5660 // If the src is an instruction that appeared earlier in the basic block
5661 // then it should already be vectorized.
5662 if (SrcInst && OrigLoop->contains(SrcInst)) {
5663 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5664 // The parameter is a vector value from earlier.
5665 Params.push_back(WidenMap.get(SrcInst));
5667 // The parameter is a scalar from outside the loop. Maybe even a constant.
5668 VectorParts Scalars;
5669 Scalars.append(UF, SrcOp);
5670 Params.push_back(Scalars);
5674 assert(Params.size() == Instr->getNumOperands() &&
5675 "Invalid number of operands");
5677 // Does this instruction return a value ?
5678 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5680 Value *UndefVec = IsVoidRetTy ? 0 :
5681 UndefValue::get(Instr->getType());
5682 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5683 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5685 Instruction *InsertPt = Builder.GetInsertPoint();
5686 BasicBlock *IfBlock = Builder.GetInsertBlock();
5687 BasicBlock *CondBlock = 0;
5691 if (IfPredicateStore) {
5692 assert(Instr->getParent()->getSinglePredecessor() &&
5693 "Only support single predecessor blocks");
5694 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5695 Instr->getParent());
5696 VectorLp = LI->getLoopFor(IfBlock);
5697 assert(VectorLp && "Must have a loop for this block");
5700 // For each vector unroll 'part':
5701 for (unsigned Part = 0; Part < UF; ++Part) {
5702 // For each scalar that we create:
5704 // Start an "if (pred) a[i] = ..." block.
5706 if (IfPredicateStore) {
5707 if (Cond[Part]->getType()->isVectorTy())
5709 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5710 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5711 ConstantInt::get(Cond[Part]->getType(), 1));
5712 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5713 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
5714 // Update Builder with newly created basic block.
5715 Builder.SetInsertPoint(InsertPt);
5718 Instruction *Cloned = Instr->clone();
5720 Cloned->setName(Instr->getName() + ".cloned");
5721 // Replace the operands of the cloned instructions with extracted scalars.
5722 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5723 Value *Op = Params[op][Part];
5724 Cloned->setOperand(op, Op);
5727 // Place the cloned scalar in the new loop.
5728 Builder.Insert(Cloned);
5730 // If the original scalar returns a value we need to place it in a vector
5731 // so that future users will be able to use it.
5733 VecResults[Part] = Cloned;
5736 if (IfPredicateStore) {
5737 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5738 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
5739 Builder.SetInsertPoint(InsertPt);
5740 Instruction *OldBr = IfBlock->getTerminator();
5741 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5742 OldBr->eraseFromParent();
5743 IfBlock = NewIfBlock;
5748 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5749 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5750 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5752 return scalarizeInstruction(Instr, IfPredicateStore);
5755 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5759 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5763 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5765 // When unrolling and the VF is 1, we only need to add a simple scalar.
5766 Type *ITy = Val->getType();
5767 assert(!ITy->isVectorTy() && "Val must be a scalar");
5768 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5769 return Builder.CreateAdd(Val, C, "induction");