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 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
176 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
177 cl::desc("Enable the use of the block frequency analysis to access PGO "
178 "heuristics minimizing code growth in cold regions and being more "
179 "aggressive in hot regions."));
181 // Runtime unroll loops for load/store throughput.
182 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
183 "enable-loadstore-runtime-unroll", cl::init(false), cl::Hidden,
184 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
186 /// The number of stores in a loop that are allowed to need predication.
187 static cl::opt<unsigned> NumberOfStoresToPredicate(
188 "vectorize-num-stores-pred", cl::init(0), cl::Hidden,
189 cl::desc("Max number of stores to be predicated behind an if."));
191 static cl::opt<bool> EnableCondStoresVectorization(
192 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
193 cl::desc("Enable if predication of stores during vectorization."));
197 // Forward declarations.
198 class LoopVectorizationLegality;
199 class LoopVectorizationCostModel;
201 /// InnerLoopVectorizer vectorizes loops which contain only one basic
202 /// block to a specified vectorization factor (VF).
203 /// This class performs the widening of scalars into vectors, or multiple
204 /// scalars. This class also implements the following features:
205 /// * It inserts an epilogue loop for handling loops that don't have iteration
206 /// counts that are known to be a multiple of the vectorization factor.
207 /// * It handles the code generation for reduction variables.
208 /// * Scalarization (implementation using scalars) of un-vectorizable
210 /// InnerLoopVectorizer does not perform any vectorization-legality
211 /// checks, and relies on the caller to check for the different legality
212 /// aspects. The InnerLoopVectorizer relies on the
213 /// LoopVectorizationLegality class to provide information about the induction
214 /// and reduction variables that were found to a given vectorization factor.
215 class InnerLoopVectorizer {
217 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
218 DominatorTree *DT, DataLayout *DL,
219 const TargetLibraryInfo *TLI, unsigned VecWidth,
220 unsigned UnrollFactor)
221 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
222 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
223 OldInduction(0), WidenMap(UnrollFactor), Legal(0) {}
225 // Perform the actual loop widening (vectorization).
226 void vectorize(LoopVectorizationLegality *L) {
228 // Create a new empty loop. Unlink the old loop and connect the new one.
230 // Widen each instruction in the old loop to a new one in the new loop.
231 // Use the Legality module to find the induction and reduction variables.
233 // Register the new loop and update the analysis passes.
237 virtual ~InnerLoopVectorizer() {}
240 /// A small list of PHINodes.
241 typedef SmallVector<PHINode*, 4> PhiVector;
242 /// When we unroll loops we have multiple vector values for each scalar.
243 /// This data structure holds the unrolled and vectorized values that
244 /// originated from one scalar instruction.
245 typedef SmallVector<Value*, 2> VectorParts;
247 // When we if-convert we need create edge masks. We have to cache values so
248 // that we don't end up with exponential recursion/IR.
249 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
250 VectorParts> EdgeMaskCache;
252 /// \brief Add code that checks at runtime if the accessed arrays overlap.
254 /// Returns a pair of instructions where the first element is the first
255 /// instruction generated in possibly a sequence of instructions and the
256 /// second value is the final comparator value or NULL if no check is needed.
257 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
259 /// \brief Add checks for strides that where assumed to be 1.
261 /// Returns the last check instruction and the first check instruction in the
262 /// pair as (first, last).
263 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
265 /// Create an empty loop, based on the loop ranges of the old loop.
266 void createEmptyLoop();
267 /// Copy and widen the instructions from the old loop.
268 virtual void vectorizeLoop();
270 /// \brief The Loop exit block may have single value PHI nodes where the
271 /// incoming value is 'Undef'. While vectorizing we only handled real values
272 /// that were defined inside the loop. Here we fix the 'undef case'.
276 /// A helper function that computes the predicate of the block BB, assuming
277 /// that the header block of the loop is set to True. It returns the *entry*
278 /// mask for the block BB.
279 VectorParts createBlockInMask(BasicBlock *BB);
280 /// A helper function that computes the predicate of the edge between SRC
282 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
284 /// A helper function to vectorize a single BB within the innermost loop.
285 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
287 /// Vectorize a single PHINode in a block. This method handles the induction
288 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
289 /// arbitrary length vectors.
290 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
291 unsigned UF, unsigned VF, PhiVector *PV);
293 /// Insert the new loop to the loop hierarchy and pass manager
294 /// and update the analysis passes.
295 void updateAnalysis();
297 /// This instruction is un-vectorizable. Implement it as a sequence
298 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
299 /// scalarized instruction behind an if block predicated on the control
300 /// dependence of the instruction.
301 virtual void scalarizeInstruction(Instruction *Instr,
302 bool IfPredicateStore=false);
304 /// Vectorize Load and Store instructions,
305 virtual void vectorizeMemoryInstruction(Instruction *Instr);
307 /// Create a broadcast instruction. This method generates a broadcast
308 /// instruction (shuffle) for loop invariant values and for the induction
309 /// value. If this is the induction variable then we extend it to N, N+1, ...
310 /// this is needed because each iteration in the loop corresponds to a SIMD
312 virtual Value *getBroadcastInstrs(Value *V);
314 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
315 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
316 /// The sequence starts at StartIndex.
317 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
319 /// When we go over instructions in the basic block we rely on previous
320 /// values within the current basic block or on loop invariant values.
321 /// When we widen (vectorize) values we place them in the map. If the values
322 /// are not within the map, they have to be loop invariant, so we simply
323 /// broadcast them into a vector.
324 VectorParts &getVectorValue(Value *V);
326 /// Generate a shuffle sequence that will reverse the vector Vec.
327 virtual Value *reverseVector(Value *Vec);
329 /// This is a helper class that holds the vectorizer state. It maps scalar
330 /// instructions to vector instructions. When the code is 'unrolled' then
331 /// then a single scalar value is mapped to multiple vector parts. The parts
332 /// are stored in the VectorPart type.
334 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
336 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
338 /// \return True if 'Key' is saved in the Value Map.
339 bool has(Value *Key) const { return MapStorage.count(Key); }
341 /// Initializes a new entry in the map. Sets all of the vector parts to the
342 /// save value in 'Val'.
343 /// \return A reference to a vector with splat values.
344 VectorParts &splat(Value *Key, Value *Val) {
345 VectorParts &Entry = MapStorage[Key];
346 Entry.assign(UF, Val);
350 ///\return A reference to the value that is stored at 'Key'.
351 VectorParts &get(Value *Key) {
352 VectorParts &Entry = MapStorage[Key];
355 assert(Entry.size() == UF);
360 /// The unroll factor. Each entry in the map stores this number of vector
364 /// Map storage. We use std::map and not DenseMap because insertions to a
365 /// dense map invalidates its iterators.
366 std::map<Value *, VectorParts> MapStorage;
369 /// The original loop.
371 /// Scev analysis to use.
379 /// Target Library Info.
380 const TargetLibraryInfo *TLI;
382 /// The vectorization SIMD factor to use. Each vector will have this many
387 /// The vectorization unroll factor to use. Each scalar is vectorized to this
388 /// many different vector instructions.
391 /// The builder that we use
394 // --- Vectorization state ---
396 /// The vector-loop preheader.
397 BasicBlock *LoopVectorPreHeader;
398 /// The scalar-loop preheader.
399 BasicBlock *LoopScalarPreHeader;
400 /// Middle Block between the vector and the scalar.
401 BasicBlock *LoopMiddleBlock;
402 ///The ExitBlock of the scalar loop.
403 BasicBlock *LoopExitBlock;
404 ///The vector loop body.
405 SmallVector<BasicBlock *, 4> LoopVectorBody;
406 ///The scalar loop body.
407 BasicBlock *LoopScalarBody;
408 /// A list of all bypass blocks. The first block is the entry of the loop.
409 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
411 /// The new Induction variable which was added to the new block.
413 /// The induction variable of the old basic block.
414 PHINode *OldInduction;
415 /// Holds the extended (to the widest induction type) start index.
417 /// Maps scalars to widened vectors.
419 EdgeMaskCache MaskCache;
421 LoopVectorizationLegality *Legal;
424 class InnerLoopUnroller : public InnerLoopVectorizer {
426 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
427 DominatorTree *DT, DataLayout *DL,
428 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
429 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
432 virtual void scalarizeInstruction(Instruction *Instr, bool IfPredicateStore = false);
433 virtual void vectorizeMemoryInstruction(Instruction *Instr);
434 virtual Value *getBroadcastInstrs(Value *V);
435 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
436 virtual Value *reverseVector(Value *Vec);
439 /// \brief Look for a meaningful debug location on the instruction or it's
441 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
446 if (I->getDebugLoc() != Empty)
449 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
450 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
451 if (OpInst->getDebugLoc() != Empty)
458 /// \brief Set the debug location in the builder using the debug location in the
460 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
461 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
462 B.SetCurrentDebugLocation(Inst->getDebugLoc());
464 B.SetCurrentDebugLocation(DebugLoc());
467 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
468 /// to what vectorization factor.
469 /// This class does not look at the profitability of vectorization, only the
470 /// legality. This class has two main kinds of checks:
471 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
472 /// will change the order of memory accesses in a way that will change the
473 /// correctness of the program.
474 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
475 /// checks for a number of different conditions, such as the availability of a
476 /// single induction variable, that all types are supported and vectorize-able,
477 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
478 /// This class is also used by InnerLoopVectorizer for identifying
479 /// induction variable and the different reduction variables.
480 class LoopVectorizationLegality {
484 unsigned NumPredStores;
486 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
487 DominatorTree *DT, TargetLibraryInfo *TLI)
488 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
489 DT(DT), TLI(TLI), Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
490 MaxSafeDepDistBytes(-1U) {}
492 /// This enum represents the kinds of reductions that we support.
494 RK_NoReduction, ///< Not a reduction.
495 RK_IntegerAdd, ///< Sum of integers.
496 RK_IntegerMult, ///< Product of integers.
497 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
498 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
499 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
500 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
501 RK_FloatAdd, ///< Sum of floats.
502 RK_FloatMult, ///< Product of floats.
503 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
506 /// This enum represents the kinds of inductions that we support.
508 IK_NoInduction, ///< Not an induction variable.
509 IK_IntInduction, ///< Integer induction variable. Step = 1.
510 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
511 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
512 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
515 // This enum represents the kind of minmax reduction.
516 enum MinMaxReductionKind {
526 /// This struct holds information about reduction variables.
527 struct ReductionDescriptor {
528 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
529 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
531 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
532 MinMaxReductionKind MK)
533 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
535 // The starting value of the reduction.
536 // It does not have to be zero!
537 TrackingVH<Value> StartValue;
538 // The instruction who's value is used outside the loop.
539 Instruction *LoopExitInstr;
540 // The kind of the reduction.
542 // If this a min/max reduction the kind of reduction.
543 MinMaxReductionKind MinMaxKind;
546 /// This POD struct holds information about a potential reduction operation.
547 struct ReductionInstDesc {
548 ReductionInstDesc(bool IsRedux, Instruction *I) :
549 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
551 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
552 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
554 // Is this instruction a reduction candidate.
556 // The last instruction in a min/max pattern (select of the select(icmp())
557 // pattern), or the current reduction instruction otherwise.
558 Instruction *PatternLastInst;
559 // If this is a min/max pattern the comparison predicate.
560 MinMaxReductionKind MinMaxKind;
563 /// This struct holds information about the memory runtime legality
564 /// check that a group of pointers do not overlap.
565 struct RuntimePointerCheck {
566 RuntimePointerCheck() : Need(false) {}
568 /// Reset the state of the pointer runtime information.
575 DependencySetId.clear();
578 /// Insert a pointer and calculate the start and end SCEVs.
579 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
580 unsigned DepSetId, ValueToValueMap &Strides);
582 /// This flag indicates if we need to add the runtime check.
584 /// Holds the pointers that we need to check.
585 SmallVector<TrackingVH<Value>, 2> Pointers;
586 /// Holds the pointer value at the beginning of the loop.
587 SmallVector<const SCEV*, 2> Starts;
588 /// Holds the pointer value at the end of the loop.
589 SmallVector<const SCEV*, 2> Ends;
590 /// Holds the information if this pointer is used for writing to memory.
591 SmallVector<bool, 2> IsWritePtr;
592 /// Holds the id of the set of pointers that could be dependent because of a
593 /// shared underlying object.
594 SmallVector<unsigned, 2> DependencySetId;
597 /// A struct for saving information about induction variables.
598 struct InductionInfo {
599 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
600 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
602 TrackingVH<Value> StartValue;
607 /// ReductionList contains the reduction descriptors for all
608 /// of the reductions that were found in the loop.
609 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
611 /// InductionList saves induction variables and maps them to the
612 /// induction descriptor.
613 typedef MapVector<PHINode*, InductionInfo> InductionList;
615 /// Returns true if it is legal to vectorize this loop.
616 /// This does not mean that it is profitable to vectorize this
617 /// loop, only that it is legal to do so.
620 /// Returns the Induction variable.
621 PHINode *getInduction() { return Induction; }
623 /// Returns the reduction variables found in the loop.
624 ReductionList *getReductionVars() { return &Reductions; }
626 /// Returns the induction variables found in the loop.
627 InductionList *getInductionVars() { return &Inductions; }
629 /// Returns the widest induction type.
630 Type *getWidestInductionType() { return WidestIndTy; }
632 /// Returns True if V is an induction variable in this loop.
633 bool isInductionVariable(const Value *V);
635 /// Return true if the block BB needs to be predicated in order for the loop
636 /// to be vectorized.
637 bool blockNeedsPredication(BasicBlock *BB);
639 /// Check if this pointer is consecutive when vectorizing. This happens
640 /// when the last index of the GEP is the induction variable, or that the
641 /// pointer itself is an induction variable.
642 /// This check allows us to vectorize A[idx] into a wide load/store.
644 /// 0 - Stride is unknown or non-consecutive.
645 /// 1 - Address is consecutive.
646 /// -1 - Address is consecutive, and decreasing.
647 int isConsecutivePtr(Value *Ptr);
649 /// Returns true if the value V is uniform within the loop.
650 bool isUniform(Value *V);
652 /// Returns true if this instruction will remain scalar after vectorization.
653 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
655 /// Returns the information that we collected about runtime memory check.
656 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
658 /// This function returns the identity element (or neutral element) for
660 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
662 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
664 bool hasStride(Value *V) { return StrideSet.count(V); }
665 bool mustCheckStrides() { return !StrideSet.empty(); }
666 SmallPtrSet<Value *, 8>::iterator strides_begin() {
667 return StrideSet.begin();
669 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
672 /// Check if a single basic block loop is vectorizable.
673 /// At this point we know that this is a loop with a constant trip count
674 /// and we only need to check individual instructions.
675 bool canVectorizeInstrs();
677 /// When we vectorize loops we may change the order in which
678 /// we read and write from memory. This method checks if it is
679 /// legal to vectorize the code, considering only memory constrains.
680 /// Returns true if the loop is vectorizable
681 bool canVectorizeMemory();
683 /// Return true if we can vectorize this loop using the IF-conversion
685 bool canVectorizeWithIfConvert();
687 /// Collect the variables that need to stay uniform after vectorization.
688 void collectLoopUniforms();
690 /// Return true if all of the instructions in the block can be speculatively
691 /// executed. \p SafePtrs is a list of addresses that are known to be legal
692 /// and we know that we can read from them without segfault.
693 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
695 /// Returns True, if 'Phi' is the kind of reduction variable for type
696 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
697 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
698 /// Returns a struct describing if the instruction 'I' can be a reduction
699 /// variable of type 'Kind'. If the reduction is a min/max pattern of
700 /// select(icmp()) this function advances the instruction pointer 'I' from the
701 /// compare instruction to the select instruction and stores this pointer in
702 /// 'PatternLastInst' member of the returned struct.
703 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
704 ReductionInstDesc &Desc);
705 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
706 /// pattern corresponding to a min(X, Y) or max(X, Y).
707 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
708 ReductionInstDesc &Prev);
709 /// Returns the induction kind of Phi. This function may return NoInduction
710 /// if the PHI is not an induction variable.
711 InductionKind isInductionVariable(PHINode *Phi);
713 /// \brief Collect memory access with loop invariant strides.
715 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
717 void collectStridedAcccess(Value *LoadOrStoreInst);
719 /// The loop that we evaluate.
723 /// DataLayout analysis.
727 /// Target Library Info.
728 TargetLibraryInfo *TLI;
730 // --- vectorization state --- //
732 /// Holds the integer induction variable. This is the counter of the
735 /// Holds the reduction variables.
736 ReductionList Reductions;
737 /// Holds all of the induction variables that we found in the loop.
738 /// Notice that inductions don't need to start at zero and that induction
739 /// variables can be pointers.
740 InductionList Inductions;
741 /// Holds the widest induction type encountered.
744 /// Allowed outside users. This holds the reduction
745 /// vars which can be accessed from outside the loop.
746 SmallPtrSet<Value*, 4> AllowedExit;
747 /// This set holds the variables which are known to be uniform after
749 SmallPtrSet<Instruction*, 4> Uniforms;
750 /// We need to check that all of the pointers in this list are disjoint
752 RuntimePointerCheck PtrRtCheck;
753 /// Can we assume the absence of NaNs.
754 bool HasFunNoNaNAttr;
756 unsigned MaxSafeDepDistBytes;
758 ValueToValueMap Strides;
759 SmallPtrSet<Value *, 8> StrideSet;
762 /// LoopVectorizationCostModel - estimates the expected speedups due to
764 /// In many cases vectorization is not profitable. This can happen because of
765 /// a number of reasons. In this class we mainly attempt to predict the
766 /// expected speedup/slowdowns due to the supported instruction set. We use the
767 /// TargetTransformInfo to query the different backends for the cost of
768 /// different operations.
769 class LoopVectorizationCostModel {
771 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
772 LoopVectorizationLegality *Legal,
773 const TargetTransformInfo &TTI,
774 DataLayout *DL, const TargetLibraryInfo *TLI)
775 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
777 /// Information about vectorization costs
778 struct VectorizationFactor {
779 unsigned Width; // Vector width with best cost
780 unsigned Cost; // Cost of the loop with that width
782 /// \return The most profitable vectorization factor and the cost of that VF.
783 /// This method checks every power of two up to VF. If UserVF is not ZERO
784 /// then this vectorization factor will be selected if vectorization is
786 VectorizationFactor selectVectorizationFactor(bool OptForSize,
789 /// \return The size (in bits) of the widest type in the code that
790 /// needs to be vectorized. We ignore values that remain scalar such as
791 /// 64 bit loop indices.
792 unsigned getWidestType();
794 /// \return The most profitable unroll factor.
795 /// If UserUF is non-zero then this method finds the best unroll-factor
796 /// based on register pressure and other parameters.
797 /// VF and LoopCost are the selected vectorization factor and the cost of the
799 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
802 /// \brief A struct that represents some properties of the register usage
804 struct RegisterUsage {
805 /// Holds the number of loop invariant values that are used in the loop.
806 unsigned LoopInvariantRegs;
807 /// Holds the maximum number of concurrent live intervals in the loop.
808 unsigned MaxLocalUsers;
809 /// Holds the number of instructions in the loop.
810 unsigned NumInstructions;
813 /// \return information about the register usage of the loop.
814 RegisterUsage calculateRegisterUsage();
817 /// Returns the expected execution cost. The unit of the cost does
818 /// not matter because we use the 'cost' units to compare different
819 /// vector widths. The cost that is returned is *not* normalized by
820 /// the factor width.
821 unsigned expectedCost(unsigned VF);
823 /// Returns the execution time cost of an instruction for a given vector
824 /// width. Vector width of one means scalar.
825 unsigned getInstructionCost(Instruction *I, unsigned VF);
827 /// A helper function for converting Scalar types to vector types.
828 /// If the incoming type is void, we return void. If the VF is 1, we return
830 static Type* ToVectorTy(Type *Scalar, unsigned VF);
832 /// Returns whether the instruction is a load or store and will be a emitted
833 /// as a vector operation.
834 bool isConsecutiveLoadOrStore(Instruction *I);
836 /// The loop that we evaluate.
840 /// Loop Info analysis.
842 /// Vectorization legality.
843 LoopVectorizationLegality *Legal;
844 /// Vector target information.
845 const TargetTransformInfo &TTI;
846 /// Target data layout information.
848 /// Target Library Info.
849 const TargetLibraryInfo *TLI;
852 /// Utility class for getting and setting loop vectorizer hints in the form
853 /// of loop metadata.
854 struct LoopVectorizeHints {
855 /// Vectorization width.
857 /// Vectorization unroll factor.
859 /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled)
862 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
863 : Width(VectorizationFactor)
864 , Unroll(DisableUnrolling ? 1 : VectorizationUnroll)
866 , LoopID(L->getLoopID()) {
868 // The command line options override any loop metadata except for when
869 // width == 1 which is used to indicate the loop is already vectorized.
870 if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
871 Width = VectorizationFactor;
872 if (VectorizationUnroll.getNumOccurrences() > 0)
873 Unroll = VectorizationUnroll;
875 DEBUG(if (DisableUnrolling && Unroll == 1)
876 dbgs() << "LV: Unrolling disabled by the pass manager\n");
879 /// Return the loop vectorizer metadata prefix.
880 static StringRef Prefix() { return "llvm.vectorizer."; }
882 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
883 SmallVector<Value*, 2> Vals;
884 Vals.push_back(MDString::get(Context, Name));
885 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
886 return MDNode::get(Context, Vals);
889 /// Mark the loop L as already vectorized by setting the width to 1.
890 void setAlreadyVectorized(Loop *L) {
891 LLVMContext &Context = L->getHeader()->getContext();
895 // Create a new loop id with one more operand for the already_vectorized
896 // hint. If the loop already has a loop id then copy the existing operands.
897 SmallVector<Value*, 4> Vals(1);
899 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
900 Vals.push_back(LoopID->getOperand(i));
902 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
903 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
905 MDNode *NewLoopID = MDNode::get(Context, Vals);
906 // Set operand 0 to refer to the loop id itself.
907 NewLoopID->replaceOperandWith(0, NewLoopID);
909 L->setLoopID(NewLoopID);
911 LoopID->replaceAllUsesWith(NewLoopID);
919 /// Find hints specified in the loop metadata.
920 void getHints(const Loop *L) {
924 // First operand should refer to the loop id itself.
925 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
926 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
928 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
929 const MDString *S = 0;
930 SmallVector<Value*, 4> Args;
932 // The expected hint is either a MDString or a MDNode with the first
933 // operand a MDString.
934 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
935 if (!MD || MD->getNumOperands() == 0)
937 S = dyn_cast<MDString>(MD->getOperand(0));
938 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
939 Args.push_back(MD->getOperand(i));
941 S = dyn_cast<MDString>(LoopID->getOperand(i));
942 assert(Args.size() == 0 && "too many arguments for MDString");
948 // Check if the hint starts with the vectorizer prefix.
949 StringRef Hint = S->getString();
950 if (!Hint.startswith(Prefix()))
952 // Remove the prefix.
953 Hint = Hint.substr(Prefix().size(), StringRef::npos);
955 if (Args.size() == 1)
956 getHint(Hint, Args[0]);
960 // Check string hint with one operand.
961 void getHint(StringRef Hint, Value *Arg) {
962 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
964 unsigned Val = C->getZExtValue();
966 if (Hint == "width") {
967 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
970 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
971 } else if (Hint == "unroll") {
972 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
975 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
976 } else if (Hint == "enable") {
977 if (C->getBitWidth() == 1)
980 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
982 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
987 static void addInnerLoop(Loop *L, SmallVectorImpl<Loop *> &V) {
989 return V.push_back(L);
991 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
995 /// The LoopVectorize Pass.
996 struct LoopVectorize : public FunctionPass {
997 /// Pass identification, replacement for typeid
1000 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1002 DisableUnrolling(NoUnrolling),
1003 AlwaysVectorize(AlwaysVectorize) {
1004 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1007 ScalarEvolution *SE;
1010 TargetTransformInfo *TTI;
1012 BlockFrequencyInfo *BFI;
1013 TargetLibraryInfo *TLI;
1014 bool DisableUnrolling;
1015 bool AlwaysVectorize;
1017 BlockFrequency ColdEntryFreq;
1019 virtual bool runOnFunction(Function &F) {
1020 SE = &getAnalysis<ScalarEvolution>();
1021 DL = getAnalysisIfAvailable<DataLayout>();
1022 LI = &getAnalysis<LoopInfo>();
1023 TTI = &getAnalysis<TargetTransformInfo>();
1024 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1025 BFI = &getAnalysis<BlockFrequencyInfo>();
1026 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1028 // Compute some weights outside of the loop over the loops. Compute this
1029 // using a BranchProbability to re-use its scaling math.
1030 const BranchProbability ColdProb(1, 5); // 20%
1031 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1033 // If the target claims to have no vector registers don't attempt
1035 if (!TTI->getNumberOfRegisters(true))
1039 DEBUG(dbgs() << "LV: Not vectorizing: Missing data layout\n");
1043 // Build up a worklist of inner-loops to vectorize. This is necessary as
1044 // the act of vectorizing or partially unrolling a loop creates new loops
1045 // and can invalidate iterators across the loops.
1046 SmallVector<Loop *, 8> Worklist;
1048 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
1049 addInnerLoop(*I, Worklist);
1051 // Now walk the identified inner loops.
1052 bool Changed = false;
1053 while (!Worklist.empty())
1054 Changed |= processLoop(Worklist.pop_back_val());
1056 // Process each loop nest in the function.
1060 bool processLoop(Loop *L) {
1061 // We only handle inner loops, so if there are children just recurse.
1063 bool Changed = false;
1064 for (Loop::iterator I = L->begin(), E = L->begin(); I != E; ++I)
1065 Changed |= processLoop(*I);
1069 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
1070 L->getHeader()->getParent()->getName() << "\"\n");
1072 LoopVectorizeHints Hints(L, DisableUnrolling);
1074 if (Hints.Force == 0) {
1075 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1079 if (!AlwaysVectorize && Hints.Force != 1) {
1080 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1084 if (Hints.Width == 1 && Hints.Unroll == 1) {
1085 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1089 // Check if it is legal to vectorize the loop.
1090 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1091 if (!LVL.canVectorize()) {
1092 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1096 // Use the cost model.
1097 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1099 // Check the function attributes to find out if this function should be
1100 // optimized for size.
1101 Function *F = L->getHeader()->getParent();
1103 Hints.Force != 1 && F->hasFnAttribute(Attribute::OptimizeForSize);
1105 // Compute the weighted frequency of this loop being executed and see if it
1106 // is less than 20% of the function entry baseline frequency. Note that we
1107 // always have a canonical loop here because we think we *can* vectoriez.
1108 // FIXME: This is hidden behind a flag due to pervasive problems with
1109 // exactly what block frequency models.
1110 if (LoopVectorizeWithBlockFrequency) {
1111 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1112 if (Hints.Force != 1 && LoopEntryFreq < ColdEntryFreq)
1116 // Check the function attributes to see if implicit floats are allowed.a
1117 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1118 // an integer loop and the vector instructions selected are purely integer
1119 // vector instructions?
1120 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1121 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1122 "attribute is used.\n");
1126 // Select the optimal vectorization factor.
1127 LoopVectorizationCostModel::VectorizationFactor VF;
1128 VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
1129 // Select the unroll factor.
1130 unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
1133 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
1134 F->getParent()->getModuleIdentifier() << '\n');
1135 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1137 if (VF.Width == 1) {
1138 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1141 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1142 // We decided not to vectorize, but we may want to unroll.
1143 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1144 Unroller.vectorize(&LVL);
1146 // If we decided that it is *legal* to vectorize the loop then do it.
1147 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1151 // Mark the loop as already vectorized to avoid vectorizing again.
1152 Hints.setAlreadyVectorized(L);
1154 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1158 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1159 AU.addRequiredID(LoopSimplifyID);
1160 AU.addRequiredID(LCSSAID);
1161 AU.addRequired<BlockFrequencyInfo>();
1162 AU.addRequired<DominatorTreeWrapperPass>();
1163 AU.addRequired<LoopInfo>();
1164 AU.addRequired<ScalarEvolution>();
1165 AU.addRequired<TargetTransformInfo>();
1166 AU.addPreserved<LoopInfo>();
1167 AU.addPreserved<DominatorTreeWrapperPass>();
1172 } // end anonymous namespace
1174 //===----------------------------------------------------------------------===//
1175 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1176 // LoopVectorizationCostModel.
1177 //===----------------------------------------------------------------------===//
1179 static Value *stripIntegerCast(Value *V) {
1180 if (CastInst *CI = dyn_cast<CastInst>(V))
1181 if (CI->getOperand(0)->getType()->isIntegerTy())
1182 return CI->getOperand(0);
1186 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1188 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1190 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1191 ValueToValueMap &PtrToStride,
1192 Value *Ptr, Value *OrigPtr = 0) {
1194 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1196 // If there is an entry in the map return the SCEV of the pointer with the
1197 // symbolic stride replaced by one.
1198 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1199 if (SI != PtrToStride.end()) {
1200 Value *StrideVal = SI->second;
1203 StrideVal = stripIntegerCast(StrideVal);
1205 // Replace symbolic stride by one.
1206 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1207 ValueToValueMap RewriteMap;
1208 RewriteMap[StrideVal] = One;
1211 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1212 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1217 // Otherwise, just return the SCEV of the original pointer.
1218 return SE->getSCEV(Ptr);
1221 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1222 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1223 ValueToValueMap &Strides) {
1224 // Get the stride replaced scev.
1225 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1226 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1227 assert(AR && "Invalid addrec expression");
1228 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1229 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1230 Pointers.push_back(Ptr);
1231 Starts.push_back(AR->getStart());
1232 Ends.push_back(ScEnd);
1233 IsWritePtr.push_back(WritePtr);
1234 DependencySetId.push_back(DepSetId);
1237 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1238 // We need to place the broadcast of invariant variables outside the loop.
1239 Instruction *Instr = dyn_cast<Instruction>(V);
1241 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1242 Instr->getParent()) != LoopVectorBody.end());
1243 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1245 // Place the code for broadcasting invariant variables in the new preheader.
1246 IRBuilder<>::InsertPointGuard Guard(Builder);
1248 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1250 // Broadcast the scalar into all locations in the vector.
1251 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1256 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1258 assert(Val->getType()->isVectorTy() && "Must be a vector");
1259 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1260 "Elem must be an integer");
1261 // Create the types.
1262 Type *ITy = Val->getType()->getScalarType();
1263 VectorType *Ty = cast<VectorType>(Val->getType());
1264 int VLen = Ty->getNumElements();
1265 SmallVector<Constant*, 8> Indices;
1267 // Create a vector of consecutive numbers from zero to VF.
1268 for (int i = 0; i < VLen; ++i) {
1269 int64_t Idx = Negate ? (-i) : i;
1270 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1273 // Add the consecutive indices to the vector value.
1274 Constant *Cv = ConstantVector::get(Indices);
1275 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1276 return Builder.CreateAdd(Val, Cv, "induction");
1279 /// \brief Find the operand of the GEP that should be checked for consecutive
1280 /// stores. This ignores trailing indices that have no effect on the final
1282 static unsigned getGEPInductionOperand(DataLayout *DL,
1283 const GetElementPtrInst *Gep) {
1284 unsigned LastOperand = Gep->getNumOperands() - 1;
1285 unsigned GEPAllocSize = DL->getTypeAllocSize(
1286 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1288 // Walk backwards and try to peel off zeros.
1289 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1290 // Find the type we're currently indexing into.
1291 gep_type_iterator GEPTI = gep_type_begin(Gep);
1292 std::advance(GEPTI, LastOperand - 1);
1294 // If it's a type with the same allocation size as the result of the GEP we
1295 // can peel off the zero index.
1296 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1304 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1305 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1306 // Make sure that the pointer does not point to structs.
1307 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1310 // If this value is a pointer induction variable we know it is consecutive.
1311 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1312 if (Phi && Inductions.count(Phi)) {
1313 InductionInfo II = Inductions[Phi];
1314 if (IK_PtrInduction == II.IK)
1316 else if (IK_ReversePtrInduction == II.IK)
1320 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1324 unsigned NumOperands = Gep->getNumOperands();
1325 Value *GpPtr = Gep->getPointerOperand();
1326 // If this GEP value is a consecutive pointer induction variable and all of
1327 // the indices are constant then we know it is consecutive. We can
1328 Phi = dyn_cast<PHINode>(GpPtr);
1329 if (Phi && Inductions.count(Phi)) {
1331 // Make sure that the pointer does not point to structs.
1332 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1333 if (GepPtrType->getElementType()->isAggregateType())
1336 // Make sure that all of the index operands are loop invariant.
1337 for (unsigned i = 1; i < NumOperands; ++i)
1338 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1341 InductionInfo II = Inductions[Phi];
1342 if (IK_PtrInduction == II.IK)
1344 else if (IK_ReversePtrInduction == II.IK)
1348 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1350 // Check that all of the gep indices are uniform except for our induction
1352 for (unsigned i = 0; i != NumOperands; ++i)
1353 if (i != InductionOperand &&
1354 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1357 // We can emit wide load/stores only if the last non-zero index is the
1358 // induction variable.
1359 const SCEV *Last = 0;
1360 if (!Strides.count(Gep))
1361 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1363 // Because of the multiplication by a stride we can have a s/zext cast.
1364 // We are going to replace this stride by 1 so the cast is safe to ignore.
1366 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1367 // %0 = trunc i64 %indvars.iv to i32
1368 // %mul = mul i32 %0, %Stride1
1369 // %idxprom = zext i32 %mul to i64 << Safe cast.
1370 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1372 Last = replaceSymbolicStrideSCEV(SE, Strides,
1373 Gep->getOperand(InductionOperand), Gep);
1374 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1376 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1380 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1381 const SCEV *Step = AR->getStepRecurrence(*SE);
1383 // The memory is consecutive because the last index is consecutive
1384 // and all other indices are loop invariant.
1387 if (Step->isAllOnesValue())
1394 bool LoopVectorizationLegality::isUniform(Value *V) {
1395 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1398 InnerLoopVectorizer::VectorParts&
1399 InnerLoopVectorizer::getVectorValue(Value *V) {
1400 assert(V != Induction && "The new induction variable should not be used.");
1401 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1403 // If we have a stride that is replaced by one, do it here.
1404 if (Legal->hasStride(V))
1405 V = ConstantInt::get(V->getType(), 1);
1407 // If we have this scalar in the map, return it.
1408 if (WidenMap.has(V))
1409 return WidenMap.get(V);
1411 // If this scalar is unknown, assume that it is a constant or that it is
1412 // loop invariant. Broadcast V and save the value for future uses.
1413 Value *B = getBroadcastInstrs(V);
1414 return WidenMap.splat(V, B);
1417 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1418 assert(Vec->getType()->isVectorTy() && "Invalid type");
1419 SmallVector<Constant*, 8> ShuffleMask;
1420 for (unsigned i = 0; i < VF; ++i)
1421 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1423 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1424 ConstantVector::get(ShuffleMask),
1428 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1429 // Attempt to issue a wide load.
1430 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1431 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1433 assert((LI || SI) && "Invalid Load/Store instruction");
1435 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1436 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1437 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1438 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1439 // An alignment of 0 means target abi alignment. We need to use the scalar's
1440 // target abi alignment in such a case.
1442 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1443 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1444 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1445 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1447 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1448 return scalarizeInstruction(Instr, true);
1450 if (ScalarAllocatedSize != VectorElementSize)
1451 return scalarizeInstruction(Instr);
1453 // If the pointer is loop invariant or if it is non-consecutive,
1454 // scalarize the load.
1455 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1456 bool Reverse = ConsecutiveStride < 0;
1457 bool UniformLoad = LI && Legal->isUniform(Ptr);
1458 if (!ConsecutiveStride || UniformLoad)
1459 return scalarizeInstruction(Instr);
1461 Constant *Zero = Builder.getInt32(0);
1462 VectorParts &Entry = WidenMap.get(Instr);
1464 // Handle consecutive loads/stores.
1465 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1466 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1467 setDebugLocFromInst(Builder, Gep);
1468 Value *PtrOperand = Gep->getPointerOperand();
1469 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1470 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1472 // Create the new GEP with the new induction variable.
1473 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1474 Gep2->setOperand(0, FirstBasePtr);
1475 Gep2->setName("gep.indvar.base");
1476 Ptr = Builder.Insert(Gep2);
1478 setDebugLocFromInst(Builder, Gep);
1479 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1480 OrigLoop) && "Base ptr must be invariant");
1482 // The last index does not have to be the induction. It can be
1483 // consecutive and be a function of the index. For example A[I+1];
1484 unsigned NumOperands = Gep->getNumOperands();
1485 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1486 // Create the new GEP with the new induction variable.
1487 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1489 for (unsigned i = 0; i < NumOperands; ++i) {
1490 Value *GepOperand = Gep->getOperand(i);
1491 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1493 // Update last index or loop invariant instruction anchored in loop.
1494 if (i == InductionOperand ||
1495 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1496 assert((i == InductionOperand ||
1497 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1498 "Must be last index or loop invariant");
1500 VectorParts &GEPParts = getVectorValue(GepOperand);
1501 Value *Index = GEPParts[0];
1502 Index = Builder.CreateExtractElement(Index, Zero);
1503 Gep2->setOperand(i, Index);
1504 Gep2->setName("gep.indvar.idx");
1507 Ptr = Builder.Insert(Gep2);
1509 // Use the induction element ptr.
1510 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1511 setDebugLocFromInst(Builder, Ptr);
1512 VectorParts &PtrVal = getVectorValue(Ptr);
1513 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1518 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1519 "We do not allow storing to uniform addresses");
1520 setDebugLocFromInst(Builder, SI);
1521 // We don't want to update the value in the map as it might be used in
1522 // another expression. So don't use a reference type for "StoredVal".
1523 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1525 for (unsigned Part = 0; Part < UF; ++Part) {
1526 // Calculate the pointer for the specific unroll-part.
1527 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1530 // If we store to reverse consecutive memory locations then we need
1531 // to reverse the order of elements in the stored value.
1532 StoredVal[Part] = reverseVector(StoredVal[Part]);
1533 // If the address is consecutive but reversed, then the
1534 // wide store needs to start at the last vector element.
1535 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1536 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1539 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1540 DataTy->getPointerTo(AddressSpace));
1541 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1547 assert(LI && "Must have a load instruction");
1548 setDebugLocFromInst(Builder, LI);
1549 for (unsigned Part = 0; Part < UF; ++Part) {
1550 // Calculate the pointer for the specific unroll-part.
1551 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1554 // If the address is consecutive but reversed, then the
1555 // wide store needs to start at the last vector element.
1556 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1557 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1560 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1561 DataTy->getPointerTo(AddressSpace));
1562 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1563 cast<LoadInst>(LI)->setAlignment(Alignment);
1564 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1568 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1569 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1570 // Holds vector parameters or scalars, in case of uniform vals.
1571 SmallVector<VectorParts, 4> Params;
1573 setDebugLocFromInst(Builder, Instr);
1575 // Find all of the vectorized parameters.
1576 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1577 Value *SrcOp = Instr->getOperand(op);
1579 // If we are accessing the old induction variable, use the new one.
1580 if (SrcOp == OldInduction) {
1581 Params.push_back(getVectorValue(SrcOp));
1585 // Try using previously calculated values.
1586 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1588 // If the src is an instruction that appeared earlier in the basic block
1589 // then it should already be vectorized.
1590 if (SrcInst && OrigLoop->contains(SrcInst)) {
1591 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1592 // The parameter is a vector value from earlier.
1593 Params.push_back(WidenMap.get(SrcInst));
1595 // The parameter is a scalar from outside the loop. Maybe even a constant.
1596 VectorParts Scalars;
1597 Scalars.append(UF, SrcOp);
1598 Params.push_back(Scalars);
1602 assert(Params.size() == Instr->getNumOperands() &&
1603 "Invalid number of operands");
1605 // Does this instruction return a value ?
1606 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1608 Value *UndefVec = IsVoidRetTy ? 0 :
1609 UndefValue::get(VectorType::get(Instr->getType(), VF));
1610 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1611 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1613 Instruction *InsertPt = Builder.GetInsertPoint();
1614 BasicBlock *IfBlock = Builder.GetInsertBlock();
1615 BasicBlock *CondBlock = 0;
1619 if (IfPredicateStore) {
1620 assert(Instr->getParent()->getSinglePredecessor() &&
1621 "Only support single predecessor blocks");
1622 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1623 Instr->getParent());
1624 VectorLp = LI->getLoopFor(IfBlock);
1625 assert(VectorLp && "Must have a loop for this block");
1628 // For each vector unroll 'part':
1629 for (unsigned Part = 0; Part < UF; ++Part) {
1630 // For each scalar that we create:
1631 for (unsigned Width = 0; Width < VF; ++Width) {
1635 if (IfPredicateStore) {
1636 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1637 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1638 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1639 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1640 // Update Builder with newly created basic block.
1641 Builder.SetInsertPoint(InsertPt);
1644 Instruction *Cloned = Instr->clone();
1646 Cloned->setName(Instr->getName() + ".cloned");
1647 // Replace the operands of the cloned instructions with extracted scalars.
1648 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1649 Value *Op = Params[op][Part];
1650 // Param is a vector. Need to extract the right lane.
1651 if (Op->getType()->isVectorTy())
1652 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1653 Cloned->setOperand(op, Op);
1656 // Place the cloned scalar in the new loop.
1657 Builder.Insert(Cloned);
1659 // If the original scalar returns a value we need to place it in a vector
1660 // so that future users will be able to use it.
1662 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1663 Builder.getInt32(Width));
1665 if (IfPredicateStore) {
1666 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1667 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1668 Builder.SetInsertPoint(InsertPt);
1669 Instruction *OldBr = IfBlock->getTerminator();
1670 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1671 OldBr->eraseFromParent();
1672 IfBlock = NewIfBlock;
1678 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1682 if (Instruction *I = dyn_cast<Instruction>(V))
1683 return I->getParent() == Loc->getParent() ? I : 0;
1687 std::pair<Instruction *, Instruction *>
1688 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1689 Instruction *tnullptr = 0;
1690 if (!Legal->mustCheckStrides())
1691 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1693 IRBuilder<> ChkBuilder(Loc);
1697 Instruction *FirstInst = 0;
1698 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1699 SE = Legal->strides_end();
1701 Value *Ptr = stripIntegerCast(*SI);
1702 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1704 // Store the first instruction we create.
1705 FirstInst = getFirstInst(FirstInst, C, Loc);
1707 Check = ChkBuilder.CreateOr(Check, C);
1712 // We have to do this trickery because the IRBuilder might fold the check to a
1713 // constant expression in which case there is no Instruction anchored in a
1715 LLVMContext &Ctx = Loc->getContext();
1716 Instruction *TheCheck =
1717 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1718 ChkBuilder.Insert(TheCheck, "stride.not.one");
1719 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1721 return std::make_pair(FirstInst, TheCheck);
1724 std::pair<Instruction *, Instruction *>
1725 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1726 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1727 Legal->getRuntimePointerCheck();
1729 Instruction *tnullptr = 0;
1730 if (!PtrRtCheck->Need)
1731 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1733 unsigned NumPointers = PtrRtCheck->Pointers.size();
1734 SmallVector<TrackingVH<Value> , 2> Starts;
1735 SmallVector<TrackingVH<Value> , 2> Ends;
1737 LLVMContext &Ctx = Loc->getContext();
1738 SCEVExpander Exp(*SE, "induction");
1739 Instruction *FirstInst = 0;
1741 for (unsigned i = 0; i < NumPointers; ++i) {
1742 Value *Ptr = PtrRtCheck->Pointers[i];
1743 const SCEV *Sc = SE->getSCEV(Ptr);
1745 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1746 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1748 Starts.push_back(Ptr);
1749 Ends.push_back(Ptr);
1751 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1752 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1754 // Use this type for pointer arithmetic.
1755 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1757 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1758 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1759 Starts.push_back(Start);
1760 Ends.push_back(End);
1764 IRBuilder<> ChkBuilder(Loc);
1765 // Our instructions might fold to a constant.
1766 Value *MemoryRuntimeCheck = 0;
1767 for (unsigned i = 0; i < NumPointers; ++i) {
1768 for (unsigned j = i+1; j < NumPointers; ++j) {
1769 // No need to check if two readonly pointers intersect.
1770 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1773 // Only need to check pointers between two different dependency sets.
1774 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1777 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1778 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1780 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1781 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1782 "Trying to bounds check pointers with different address spaces");
1784 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1785 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1787 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1788 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1789 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1790 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1792 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1793 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1794 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1795 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1796 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1797 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1798 if (MemoryRuntimeCheck) {
1799 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1801 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1803 MemoryRuntimeCheck = IsConflict;
1807 // We have to do this trickery because the IRBuilder might fold the check to a
1808 // constant expression in which case there is no Instruction anchored in a
1810 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1811 ConstantInt::getTrue(Ctx));
1812 ChkBuilder.Insert(Check, "memcheck.conflict");
1813 FirstInst = getFirstInst(FirstInst, Check, Loc);
1814 return std::make_pair(FirstInst, Check);
1817 void InnerLoopVectorizer::createEmptyLoop() {
1819 In this function we generate a new loop. The new loop will contain
1820 the vectorized instructions while the old loop will continue to run the
1823 [ ] <-- vector loop bypass (may consist of multiple blocks).
1826 | [ ] <-- vector pre header.
1830 | [ ]_| <-- vector loop.
1833 >[ ] <--- middle-block.
1836 | [ ] <--- new preheader.
1840 | [ ]_| <-- old scalar loop to handle remainder.
1843 >[ ] <-- exit block.
1847 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1848 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1849 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1850 assert(ExitBlock && "Must have an exit block");
1852 // Some loops have a single integer induction variable, while other loops
1853 // don't. One example is c++ iterators that often have multiple pointer
1854 // induction variables. In the code below we also support a case where we
1855 // don't have a single induction variable.
1856 OldInduction = Legal->getInduction();
1857 Type *IdxTy = Legal->getWidestInductionType();
1859 // Find the loop boundaries.
1860 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1861 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1863 // The exit count might have the type of i64 while the phi is i32. This can
1864 // happen if we have an induction variable that is sign extended before the
1865 // compare. The only way that we get a backedge taken count is that the
1866 // induction variable was signed and as such will not overflow. In such a case
1867 // truncation is legal.
1868 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1869 IdxTy->getPrimitiveSizeInBits())
1870 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1872 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1873 // Get the total trip count from the count by adding 1.
1874 ExitCount = SE->getAddExpr(ExitCount,
1875 SE->getConstant(ExitCount->getType(), 1));
1877 // Expand the trip count and place the new instructions in the preheader.
1878 // Notice that the pre-header does not change, only the loop body.
1879 SCEVExpander Exp(*SE, "induction");
1881 // Count holds the overall loop count (N).
1882 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1883 BypassBlock->getTerminator());
1885 // The loop index does not have to start at Zero. Find the original start
1886 // value from the induction PHI node. If we don't have an induction variable
1887 // then we know that it starts at zero.
1888 Builder.SetInsertPoint(BypassBlock->getTerminator());
1889 Value *StartIdx = ExtendedIdx = OldInduction ?
1890 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1892 ConstantInt::get(IdxTy, 0);
1894 assert(BypassBlock && "Invalid loop structure");
1895 LoopBypassBlocks.push_back(BypassBlock);
1897 // Split the single block loop into the two loop structure described above.
1898 BasicBlock *VectorPH =
1899 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1900 BasicBlock *VecBody =
1901 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1902 BasicBlock *MiddleBlock =
1903 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1904 BasicBlock *ScalarPH =
1905 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1907 // Create and register the new vector loop.
1908 Loop* Lp = new Loop();
1909 Loop *ParentLoop = OrigLoop->getParentLoop();
1911 // Insert the new loop into the loop nest and register the new basic blocks
1912 // before calling any utilities such as SCEV that require valid LoopInfo.
1914 ParentLoop->addChildLoop(Lp);
1915 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1916 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1917 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1919 LI->addTopLevelLoop(Lp);
1921 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1923 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1925 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
1927 // Generate the induction variable.
1928 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1929 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1930 // The loop step is equal to the vectorization factor (num of SIMD elements)
1931 // times the unroll factor (num of SIMD instructions).
1932 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1934 // This is the IR builder that we use to add all of the logic for bypassing
1935 // the new vector loop.
1936 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1937 setDebugLocFromInst(BypassBuilder,
1938 getDebugLocFromInstOrOperands(OldInduction));
1940 // We may need to extend the index in case there is a type mismatch.
1941 // We know that the count starts at zero and does not overflow.
1942 if (Count->getType() != IdxTy) {
1943 // The exit count can be of pointer type. Convert it to the correct
1945 if (ExitCount->getType()->isPointerTy())
1946 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1948 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1951 // Add the start index to the loop count to get the new end index.
1952 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1954 // Now we need to generate the expression for N - (N % VF), which is
1955 // the part that the vectorized body will execute.
1956 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1957 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1958 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1959 "end.idx.rnd.down");
1961 // Now, compare the new count to zero. If it is zero skip the vector loop and
1962 // jump to the scalar loop.
1963 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1966 BasicBlock *LastBypassBlock = BypassBlock;
1968 // Generate the code to check that the strides we assumed to be one are really
1969 // one. We want the new basic block to start at the first instruction in a
1970 // sequence of instructions that form a check.
1971 Instruction *StrideCheck;
1972 Instruction *FirstCheckInst;
1973 tie(FirstCheckInst, StrideCheck) =
1974 addStrideCheck(BypassBlock->getTerminator());
1976 // Create a new block containing the stride check.
1977 BasicBlock *CheckBlock =
1978 BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
1980 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1981 LoopBypassBlocks.push_back(CheckBlock);
1983 // Replace the branch into the memory check block with a conditional branch
1984 // for the "few elements case".
1985 Instruction *OldTerm = BypassBlock->getTerminator();
1986 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1987 OldTerm->eraseFromParent();
1990 LastBypassBlock = CheckBlock;
1993 // Generate the code that checks in runtime if arrays overlap. We put the
1994 // checks into a separate block to make the more common case of few elements
1996 Instruction *MemRuntimeCheck;
1997 tie(FirstCheckInst, MemRuntimeCheck) =
1998 addRuntimeCheck(LastBypassBlock->getTerminator());
1999 if (MemRuntimeCheck) {
2000 // Create a new block containing the memory check.
2001 BasicBlock *CheckBlock =
2002 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2004 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2005 LoopBypassBlocks.push_back(CheckBlock);
2007 // Replace the branch into the memory check block with a conditional branch
2008 // for the "few elements case".
2009 Instruction *OldTerm = LastBypassBlock->getTerminator();
2010 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2011 OldTerm->eraseFromParent();
2013 Cmp = MemRuntimeCheck;
2014 LastBypassBlock = CheckBlock;
2017 LastBypassBlock->getTerminator()->eraseFromParent();
2018 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2021 // We are going to resume the execution of the scalar loop.
2022 // Go over all of the induction variables that we found and fix the
2023 // PHIs that are left in the scalar version of the loop.
2024 // The starting values of PHI nodes depend on the counter of the last
2025 // iteration in the vectorized loop.
2026 // If we come from a bypass edge then we need to start from the original
2029 // This variable saves the new starting index for the scalar loop.
2030 PHINode *ResumeIndex = 0;
2031 LoopVectorizationLegality::InductionList::iterator I, E;
2032 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2033 // Set builder to point to last bypass block.
2034 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2035 for (I = List->begin(), E = List->end(); I != E; ++I) {
2036 PHINode *OrigPhi = I->first;
2037 LoopVectorizationLegality::InductionInfo II = I->second;
2039 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2040 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2041 MiddleBlock->getTerminator());
2042 // We might have extended the type of the induction variable but we need a
2043 // truncated version for the scalar loop.
2044 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2045 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2046 MiddleBlock->getTerminator()) : 0;
2048 Value *EndValue = 0;
2050 case LoopVectorizationLegality::IK_NoInduction:
2051 llvm_unreachable("Unknown induction");
2052 case LoopVectorizationLegality::IK_IntInduction: {
2053 // Handle the integer induction counter.
2054 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2056 // We have the canonical induction variable.
2057 if (OrigPhi == OldInduction) {
2058 // Create a truncated version of the resume value for the scalar loop,
2059 // we might have promoted the type to a larger width.
2061 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2062 // The new PHI merges the original incoming value, in case of a bypass,
2063 // or the value at the end of the vectorized loop.
2064 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2065 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2066 TruncResumeVal->addIncoming(EndValue, VecBody);
2068 // We know what the end value is.
2069 EndValue = IdxEndRoundDown;
2070 // We also know which PHI node holds it.
2071 ResumeIndex = ResumeVal;
2075 // Not the canonical induction variable - add the vector loop count to the
2077 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2078 II.StartValue->getType(),
2080 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2083 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2084 // Convert the CountRoundDown variable to the PHI size.
2085 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2086 II.StartValue->getType(),
2088 // Handle reverse integer induction counter.
2089 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2092 case LoopVectorizationLegality::IK_PtrInduction: {
2093 // For pointer induction variables, calculate the offset using
2095 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2099 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2100 // The value at the end of the loop for the reverse pointer is calculated
2101 // by creating a GEP with a negative index starting from the start value.
2102 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2103 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2105 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2111 // The new PHI merges the original incoming value, in case of a bypass,
2112 // or the value at the end of the vectorized loop.
2113 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
2114 if (OrigPhi == OldInduction)
2115 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2117 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2119 ResumeVal->addIncoming(EndValue, VecBody);
2121 // Fix the scalar body counter (PHI node).
2122 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2123 // The old inductions phi node in the scalar body needs the truncated value.
2124 if (OrigPhi == OldInduction)
2125 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
2127 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
2130 // If we are generating a new induction variable then we also need to
2131 // generate the code that calculates the exit value. This value is not
2132 // simply the end of the counter because we may skip the vectorized body
2133 // in case of a runtime check.
2135 assert(!ResumeIndex && "Unexpected resume value found");
2136 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2137 MiddleBlock->getTerminator());
2138 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2139 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2140 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2143 // Make sure that we found the index where scalar loop needs to continue.
2144 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2145 "Invalid resume Index");
2147 // Add a check in the middle block to see if we have completed
2148 // all of the iterations in the first vector loop.
2149 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2150 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2151 ResumeIndex, "cmp.n",
2152 MiddleBlock->getTerminator());
2154 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2155 // Remove the old terminator.
2156 MiddleBlock->getTerminator()->eraseFromParent();
2158 // Create i+1 and fill the PHINode.
2159 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2160 Induction->addIncoming(StartIdx, VectorPH);
2161 Induction->addIncoming(NextIdx, VecBody);
2162 // Create the compare.
2163 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2164 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2166 // Now we have two terminators. Remove the old one from the block.
2167 VecBody->getTerminator()->eraseFromParent();
2169 // Get ready to start creating new instructions into the vectorized body.
2170 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2173 LoopVectorPreHeader = VectorPH;
2174 LoopScalarPreHeader = ScalarPH;
2175 LoopMiddleBlock = MiddleBlock;
2176 LoopExitBlock = ExitBlock;
2177 LoopVectorBody.push_back(VecBody);
2178 LoopScalarBody = OldBasicBlock;
2180 LoopVectorizeHints Hints(Lp, true);
2181 Hints.setAlreadyVectorized(Lp);
2184 /// This function returns the identity element (or neutral element) for
2185 /// the operation K.
2187 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2192 // Adding, Xoring, Oring zero to a number does not change it.
2193 return ConstantInt::get(Tp, 0);
2194 case RK_IntegerMult:
2195 // Multiplying a number by 1 does not change it.
2196 return ConstantInt::get(Tp, 1);
2198 // AND-ing a number with an all-1 value does not change it.
2199 return ConstantInt::get(Tp, -1, true);
2201 // Multiplying a number by 1 does not change it.
2202 return ConstantFP::get(Tp, 1.0L);
2204 // Adding zero to a number does not change it.
2205 return ConstantFP::get(Tp, 0.0L);
2207 llvm_unreachable("Unknown reduction kind");
2211 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
2212 Intrinsic::ID ValidIntrinsicID) {
2213 if (I.getNumArgOperands() != 1 ||
2214 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2215 I.getType() != I.getArgOperand(0)->getType() ||
2216 !I.onlyReadsMemory())
2217 return Intrinsic::not_intrinsic;
2219 return ValidIntrinsicID;
2222 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
2223 Intrinsic::ID ValidIntrinsicID) {
2224 if (I.getNumArgOperands() != 2 ||
2225 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2226 !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
2227 I.getType() != I.getArgOperand(0)->getType() ||
2228 I.getType() != I.getArgOperand(1)->getType() ||
2229 !I.onlyReadsMemory())
2230 return Intrinsic::not_intrinsic;
2232 return ValidIntrinsicID;
2236 static Intrinsic::ID
2237 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
2238 // If we have an intrinsic call, check if it is trivially vectorizable.
2239 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2240 switch (II->getIntrinsicID()) {
2241 case Intrinsic::sqrt:
2242 case Intrinsic::sin:
2243 case Intrinsic::cos:
2244 case Intrinsic::exp:
2245 case Intrinsic::exp2:
2246 case Intrinsic::log:
2247 case Intrinsic::log10:
2248 case Intrinsic::log2:
2249 case Intrinsic::fabs:
2250 case Intrinsic::copysign:
2251 case Intrinsic::floor:
2252 case Intrinsic::ceil:
2253 case Intrinsic::trunc:
2254 case Intrinsic::rint:
2255 case Intrinsic::nearbyint:
2256 case Intrinsic::round:
2257 case Intrinsic::pow:
2258 case Intrinsic::fma:
2259 case Intrinsic::fmuladd:
2260 case Intrinsic::lifetime_start:
2261 case Intrinsic::lifetime_end:
2262 return II->getIntrinsicID();
2264 return Intrinsic::not_intrinsic;
2269 return Intrinsic::not_intrinsic;
2272 Function *F = CI->getCalledFunction();
2273 // We're going to make assumptions on the semantics of the functions, check
2274 // that the target knows that it's available in this environment and it does
2275 // not have local linkage.
2276 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
2277 return Intrinsic::not_intrinsic;
2279 // Otherwise check if we have a call to a function that can be turned into a
2280 // vector intrinsic.
2287 return checkUnaryFloatSignature(*CI, Intrinsic::sin);
2291 return checkUnaryFloatSignature(*CI, Intrinsic::cos);
2295 return checkUnaryFloatSignature(*CI, Intrinsic::exp);
2297 case LibFunc::exp2f:
2298 case LibFunc::exp2l:
2299 return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
2303 return checkUnaryFloatSignature(*CI, Intrinsic::log);
2304 case LibFunc::log10:
2305 case LibFunc::log10f:
2306 case LibFunc::log10l:
2307 return checkUnaryFloatSignature(*CI, Intrinsic::log10);
2309 case LibFunc::log2f:
2310 case LibFunc::log2l:
2311 return checkUnaryFloatSignature(*CI, Intrinsic::log2);
2313 case LibFunc::fabsf:
2314 case LibFunc::fabsl:
2315 return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
2316 case LibFunc::copysign:
2317 case LibFunc::copysignf:
2318 case LibFunc::copysignl:
2319 return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
2320 case LibFunc::floor:
2321 case LibFunc::floorf:
2322 case LibFunc::floorl:
2323 return checkUnaryFloatSignature(*CI, Intrinsic::floor);
2325 case LibFunc::ceilf:
2326 case LibFunc::ceill:
2327 return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
2328 case LibFunc::trunc:
2329 case LibFunc::truncf:
2330 case LibFunc::truncl:
2331 return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
2333 case LibFunc::rintf:
2334 case LibFunc::rintl:
2335 return checkUnaryFloatSignature(*CI, Intrinsic::rint);
2336 case LibFunc::nearbyint:
2337 case LibFunc::nearbyintf:
2338 case LibFunc::nearbyintl:
2339 return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
2340 case LibFunc::round:
2341 case LibFunc::roundf:
2342 case LibFunc::roundl:
2343 return checkUnaryFloatSignature(*CI, Intrinsic::round);
2347 return checkBinaryFloatSignature(*CI, Intrinsic::pow);
2350 return Intrinsic::not_intrinsic;
2353 /// This function translates the reduction kind to an LLVM binary operator.
2355 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2357 case LoopVectorizationLegality::RK_IntegerAdd:
2358 return Instruction::Add;
2359 case LoopVectorizationLegality::RK_IntegerMult:
2360 return Instruction::Mul;
2361 case LoopVectorizationLegality::RK_IntegerOr:
2362 return Instruction::Or;
2363 case LoopVectorizationLegality::RK_IntegerAnd:
2364 return Instruction::And;
2365 case LoopVectorizationLegality::RK_IntegerXor:
2366 return Instruction::Xor;
2367 case LoopVectorizationLegality::RK_FloatMult:
2368 return Instruction::FMul;
2369 case LoopVectorizationLegality::RK_FloatAdd:
2370 return Instruction::FAdd;
2371 case LoopVectorizationLegality::RK_IntegerMinMax:
2372 return Instruction::ICmp;
2373 case LoopVectorizationLegality::RK_FloatMinMax:
2374 return Instruction::FCmp;
2376 llvm_unreachable("Unknown reduction operation");
2380 Value *createMinMaxOp(IRBuilder<> &Builder,
2381 LoopVectorizationLegality::MinMaxReductionKind RK,
2384 CmpInst::Predicate P = CmpInst::ICMP_NE;
2387 llvm_unreachable("Unknown min/max reduction kind");
2388 case LoopVectorizationLegality::MRK_UIntMin:
2389 P = CmpInst::ICMP_ULT;
2391 case LoopVectorizationLegality::MRK_UIntMax:
2392 P = CmpInst::ICMP_UGT;
2394 case LoopVectorizationLegality::MRK_SIntMin:
2395 P = CmpInst::ICMP_SLT;
2397 case LoopVectorizationLegality::MRK_SIntMax:
2398 P = CmpInst::ICMP_SGT;
2400 case LoopVectorizationLegality::MRK_FloatMin:
2401 P = CmpInst::FCMP_OLT;
2403 case LoopVectorizationLegality::MRK_FloatMax:
2404 P = CmpInst::FCMP_OGT;
2409 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2410 RK == LoopVectorizationLegality::MRK_FloatMax)
2411 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2413 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2415 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2420 struct CSEDenseMapInfo {
2421 static bool canHandle(Instruction *I) {
2422 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2423 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2425 static inline Instruction *getEmptyKey() {
2426 return DenseMapInfo<Instruction *>::getEmptyKey();
2428 static inline Instruction *getTombstoneKey() {
2429 return DenseMapInfo<Instruction *>::getTombstoneKey();
2431 static unsigned getHashValue(Instruction *I) {
2432 assert(canHandle(I) && "Unknown instruction!");
2433 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2434 I->value_op_end()));
2436 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2437 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2438 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2440 return LHS->isIdenticalTo(RHS);
2445 /// \brief Check whether this block is a predicated block.
2446 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2447 /// = ...; " blocks. We start with one vectorized basic block. For every
2448 /// conditional block we split this vectorized block. Therefore, every second
2449 /// block will be a predicated one.
2450 static bool isPredicatedBlock(unsigned BlockNum) {
2451 return BlockNum % 2;
2454 ///\brief Perform cse of induction variable instructions.
2455 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2456 // Perform simple cse.
2457 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2458 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2459 BasicBlock *BB = BBs[i];
2460 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2461 Instruction *In = I++;
2463 if (!CSEDenseMapInfo::canHandle(In))
2466 // Check if we can replace this instruction with any of the
2467 // visited instructions.
2468 if (Instruction *V = CSEMap.lookup(In)) {
2469 In->replaceAllUsesWith(V);
2470 In->eraseFromParent();
2473 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2474 // ...;" blocks for predicated stores. Every second block is a predicated
2476 if (isPredicatedBlock(i))
2484 void InnerLoopVectorizer::vectorizeLoop() {
2485 //===------------------------------------------------===//
2487 // Notice: any optimization or new instruction that go
2488 // into the code below should be also be implemented in
2491 //===------------------------------------------------===//
2492 Constant *Zero = Builder.getInt32(0);
2494 // In order to support reduction variables we need to be able to vectorize
2495 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2496 // stages. First, we create a new vector PHI node with no incoming edges.
2497 // We use this value when we vectorize all of the instructions that use the
2498 // PHI. Next, after all of the instructions in the block are complete we
2499 // add the new incoming edges to the PHI. At this point all of the
2500 // instructions in the basic block are vectorized, so we can use them to
2501 // construct the PHI.
2502 PhiVector RdxPHIsToFix;
2504 // Scan the loop in a topological order to ensure that defs are vectorized
2506 LoopBlocksDFS DFS(OrigLoop);
2509 // Vectorize all of the blocks in the original loop.
2510 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2511 be = DFS.endRPO(); bb != be; ++bb)
2512 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2514 // At this point every instruction in the original loop is widened to
2515 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2516 // that we vectorized. The PHI nodes are currently empty because we did
2517 // not want to introduce cycles. Notice that the remaining PHI nodes
2518 // that we need to fix are reduction variables.
2520 // Create the 'reduced' values for each of the induction vars.
2521 // The reduced values are the vector values that we scalarize and combine
2522 // after the loop is finished.
2523 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2525 PHINode *RdxPhi = *it;
2526 assert(RdxPhi && "Unable to recover vectorized PHI");
2528 // Find the reduction variable descriptor.
2529 assert(Legal->getReductionVars()->count(RdxPhi) &&
2530 "Unable to find the reduction variable");
2531 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2532 (*Legal->getReductionVars())[RdxPhi];
2534 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2536 // We need to generate a reduction vector from the incoming scalar.
2537 // To do so, we need to generate the 'identity' vector and override
2538 // one of the elements with the incoming scalar reduction. We need
2539 // to do it in the vector-loop preheader.
2540 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2542 // This is the vector-clone of the value that leaves the loop.
2543 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2544 Type *VecTy = VectorExit[0]->getType();
2546 // Find the reduction identity variable. Zero for addition, or, xor,
2547 // one for multiplication, -1 for And.
2550 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2551 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2552 // MinMax reduction have the start value as their identify.
2554 VectorStart = Identity = RdxDesc.StartValue;
2556 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2561 // Handle other reduction kinds:
2563 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2564 VecTy->getScalarType());
2567 // This vector is the Identity vector where the first element is the
2568 // incoming scalar reduction.
2569 VectorStart = RdxDesc.StartValue;
2571 Identity = ConstantVector::getSplat(VF, Iden);
2573 // This vector is the Identity vector where the first element is the
2574 // incoming scalar reduction.
2575 VectorStart = Builder.CreateInsertElement(Identity,
2576 RdxDesc.StartValue, Zero);
2580 // Fix the vector-loop phi.
2581 // We created the induction variable so we know that the
2582 // preheader is the first entry.
2583 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2585 // Reductions do not have to start at zero. They can start with
2586 // any loop invariant values.
2587 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2588 BasicBlock *Latch = OrigLoop->getLoopLatch();
2589 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2590 VectorParts &Val = getVectorValue(LoopVal);
2591 for (unsigned part = 0; part < UF; ++part) {
2592 // Make sure to add the reduction stat value only to the
2593 // first unroll part.
2594 Value *StartVal = (part == 0) ? VectorStart : Identity;
2595 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2596 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2597 LoopVectorBody.back());
2600 // Before each round, move the insertion point right between
2601 // the PHIs and the values we are going to write.
2602 // This allows us to write both PHINodes and the extractelement
2604 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2606 VectorParts RdxParts;
2607 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2608 for (unsigned part = 0; part < UF; ++part) {
2609 // This PHINode contains the vectorized reduction variable, or
2610 // the initial value vector, if we bypass the vector loop.
2611 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2612 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2613 Value *StartVal = (part == 0) ? VectorStart : Identity;
2614 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2615 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2616 NewPhi->addIncoming(RdxExitVal[part],
2617 LoopVectorBody.back());
2618 RdxParts.push_back(NewPhi);
2621 // Reduce all of the unrolled parts into a single vector.
2622 Value *ReducedPartRdx = RdxParts[0];
2623 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2624 setDebugLocFromInst(Builder, ReducedPartRdx);
2625 for (unsigned part = 1; part < UF; ++part) {
2626 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2627 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2628 RdxParts[part], ReducedPartRdx,
2631 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2632 ReducedPartRdx, RdxParts[part]);
2636 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2637 // and vector ops, reducing the set of values being computed by half each
2639 assert(isPowerOf2_32(VF) &&
2640 "Reduction emission only supported for pow2 vectors!");
2641 Value *TmpVec = ReducedPartRdx;
2642 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2643 for (unsigned i = VF; i != 1; i >>= 1) {
2644 // Move the upper half of the vector to the lower half.
2645 for (unsigned j = 0; j != i/2; ++j)
2646 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2648 // Fill the rest of the mask with undef.
2649 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2650 UndefValue::get(Builder.getInt32Ty()));
2653 Builder.CreateShuffleVector(TmpVec,
2654 UndefValue::get(TmpVec->getType()),
2655 ConstantVector::get(ShuffleMask),
2658 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2659 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2662 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2665 // The result is in the first element of the vector.
2666 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2667 Builder.getInt32(0));
2670 // Now, we need to fix the users of the reduction variable
2671 // inside and outside of the scalar remainder loop.
2672 // We know that the loop is in LCSSA form. We need to update the
2673 // PHI nodes in the exit blocks.
2674 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2675 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2676 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2677 if (!LCSSAPhi) break;
2679 // All PHINodes need to have a single entry edge, or two if
2680 // we already fixed them.
2681 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2683 // We found our reduction value exit-PHI. Update it with the
2684 // incoming bypass edge.
2685 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2686 // Add an edge coming from the bypass.
2687 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2690 }// end of the LCSSA phi scan.
2692 // Fix the scalar loop reduction variable with the incoming reduction sum
2693 // from the vector body and from the backedge value.
2694 int IncomingEdgeBlockIdx =
2695 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2696 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2697 // Pick the other block.
2698 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2699 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2700 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2701 }// end of for each redux variable.
2705 // Remove redundant induction instructions.
2706 cse(LoopVectorBody);
2709 void InnerLoopVectorizer::fixLCSSAPHIs() {
2710 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2711 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2712 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2713 if (!LCSSAPhi) break;
2714 if (LCSSAPhi->getNumIncomingValues() == 1)
2715 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2720 InnerLoopVectorizer::VectorParts
2721 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2722 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2725 // Look for cached value.
2726 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2727 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2728 if (ECEntryIt != MaskCache.end())
2729 return ECEntryIt->second;
2731 VectorParts SrcMask = createBlockInMask(Src);
2733 // The terminator has to be a branch inst!
2734 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2735 assert(BI && "Unexpected terminator found");
2737 if (BI->isConditional()) {
2738 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2740 if (BI->getSuccessor(0) != Dst)
2741 for (unsigned part = 0; part < UF; ++part)
2742 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2744 for (unsigned part = 0; part < UF; ++part)
2745 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2747 MaskCache[Edge] = EdgeMask;
2751 MaskCache[Edge] = SrcMask;
2755 InnerLoopVectorizer::VectorParts
2756 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2757 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2759 // Loop incoming mask is all-one.
2760 if (OrigLoop->getHeader() == BB) {
2761 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2762 return getVectorValue(C);
2765 // This is the block mask. We OR all incoming edges, and with zero.
2766 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2767 VectorParts BlockMask = getVectorValue(Zero);
2770 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2771 VectorParts EM = createEdgeMask(*it, BB);
2772 for (unsigned part = 0; part < UF; ++part)
2773 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2779 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2780 InnerLoopVectorizer::VectorParts &Entry,
2781 unsigned UF, unsigned VF, PhiVector *PV) {
2782 PHINode* P = cast<PHINode>(PN);
2783 // Handle reduction variables:
2784 if (Legal->getReductionVars()->count(P)) {
2785 for (unsigned part = 0; part < UF; ++part) {
2786 // This is phase one of vectorizing PHIs.
2787 Type *VecTy = (VF == 1) ? PN->getType() :
2788 VectorType::get(PN->getType(), VF);
2789 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2790 LoopVectorBody.back()-> getFirstInsertionPt());
2796 setDebugLocFromInst(Builder, P);
2797 // Check for PHI nodes that are lowered to vector selects.
2798 if (P->getParent() != OrigLoop->getHeader()) {
2799 // We know that all PHIs in non-header blocks are converted into
2800 // selects, so we don't have to worry about the insertion order and we
2801 // can just use the builder.
2802 // At this point we generate the predication tree. There may be
2803 // duplications since this is a simple recursive scan, but future
2804 // optimizations will clean it up.
2806 unsigned NumIncoming = P->getNumIncomingValues();
2808 // Generate a sequence of selects of the form:
2809 // SELECT(Mask3, In3,
2810 // SELECT(Mask2, In2,
2812 for (unsigned In = 0; In < NumIncoming; In++) {
2813 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2815 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2817 for (unsigned part = 0; part < UF; ++part) {
2818 // We might have single edge PHIs (blocks) - use an identity
2819 // 'select' for the first PHI operand.
2821 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2824 // Select between the current value and the previous incoming edge
2825 // based on the incoming mask.
2826 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2827 Entry[part], "predphi");
2833 // This PHINode must be an induction variable.
2834 // Make sure that we know about it.
2835 assert(Legal->getInductionVars()->count(P) &&
2836 "Not an induction variable");
2838 LoopVectorizationLegality::InductionInfo II =
2839 Legal->getInductionVars()->lookup(P);
2842 case LoopVectorizationLegality::IK_NoInduction:
2843 llvm_unreachable("Unknown induction");
2844 case LoopVectorizationLegality::IK_IntInduction: {
2845 assert(P->getType() == II.StartValue->getType() && "Types must match");
2846 Type *PhiTy = P->getType();
2848 if (P == OldInduction) {
2849 // Handle the canonical induction variable. We might have had to
2851 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2853 // Handle other induction variables that are now based on the
2855 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2857 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2858 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2861 Broadcasted = getBroadcastInstrs(Broadcasted);
2862 // After broadcasting the induction variable we need to make the vector
2863 // consecutive by adding 0, 1, 2, etc.
2864 for (unsigned part = 0; part < UF; ++part)
2865 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2868 case LoopVectorizationLegality::IK_ReverseIntInduction:
2869 case LoopVectorizationLegality::IK_PtrInduction:
2870 case LoopVectorizationLegality::IK_ReversePtrInduction:
2871 // Handle reverse integer and pointer inductions.
2872 Value *StartIdx = ExtendedIdx;
2873 // This is the normalized GEP that starts counting at zero.
2874 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2877 // Handle the reverse integer induction variable case.
2878 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2879 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2880 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2882 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2885 // This is a new value so do not hoist it out.
2886 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2887 // After broadcasting the induction variable we need to make the
2888 // vector consecutive by adding ... -3, -2, -1, 0.
2889 for (unsigned part = 0; part < UF; ++part)
2890 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2895 // Handle the pointer induction variable case.
2896 assert(P->getType()->isPointerTy() && "Unexpected type.");
2898 // Is this a reverse induction ptr or a consecutive induction ptr.
2899 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2902 // This is the vector of results. Notice that we don't generate
2903 // vector geps because scalar geps result in better code.
2904 for (unsigned part = 0; part < UF; ++part) {
2906 int EltIndex = (part) * (Reverse ? -1 : 1);
2907 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2910 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2912 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2914 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2916 Entry[part] = SclrGep;
2920 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2921 for (unsigned int i = 0; i < VF; ++i) {
2922 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2923 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2926 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2928 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2930 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2932 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2933 Builder.getInt32(i),
2936 Entry[part] = VecVal;
2942 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2943 // For each instruction in the old loop.
2944 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2945 VectorParts &Entry = WidenMap.get(it);
2946 switch (it->getOpcode()) {
2947 case Instruction::Br:
2948 // Nothing to do for PHIs and BR, since we already took care of the
2949 // loop control flow instructions.
2951 case Instruction::PHI:{
2952 // Vectorize PHINodes.
2953 widenPHIInstruction(it, Entry, UF, VF, PV);
2957 case Instruction::Add:
2958 case Instruction::FAdd:
2959 case Instruction::Sub:
2960 case Instruction::FSub:
2961 case Instruction::Mul:
2962 case Instruction::FMul:
2963 case Instruction::UDiv:
2964 case Instruction::SDiv:
2965 case Instruction::FDiv:
2966 case Instruction::URem:
2967 case Instruction::SRem:
2968 case Instruction::FRem:
2969 case Instruction::Shl:
2970 case Instruction::LShr:
2971 case Instruction::AShr:
2972 case Instruction::And:
2973 case Instruction::Or:
2974 case Instruction::Xor: {
2975 // Just widen binops.
2976 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2977 setDebugLocFromInst(Builder, BinOp);
2978 VectorParts &A = getVectorValue(it->getOperand(0));
2979 VectorParts &B = getVectorValue(it->getOperand(1));
2981 // Use this vector value for all users of the original instruction.
2982 for (unsigned Part = 0; Part < UF; ++Part) {
2983 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2985 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2986 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2987 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2988 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2989 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2991 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2992 VecOp->setIsExact(BinOp->isExact());
2998 case Instruction::Select: {
3000 // If the selector is loop invariant we can create a select
3001 // instruction with a scalar condition. Otherwise, use vector-select.
3002 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3004 setDebugLocFromInst(Builder, it);
3006 // The condition can be loop invariant but still defined inside the
3007 // loop. This means that we can't just use the original 'cond' value.
3008 // We have to take the 'vectorized' value and pick the first lane.
3009 // Instcombine will make this a no-op.
3010 VectorParts &Cond = getVectorValue(it->getOperand(0));
3011 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3012 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3014 Value *ScalarCond = (VF == 1) ? Cond[0] :
3015 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3017 for (unsigned Part = 0; Part < UF; ++Part) {
3018 Entry[Part] = Builder.CreateSelect(
3019 InvariantCond ? ScalarCond : Cond[Part],
3026 case Instruction::ICmp:
3027 case Instruction::FCmp: {
3028 // Widen compares. Generate vector compares.
3029 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3030 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3031 setDebugLocFromInst(Builder, it);
3032 VectorParts &A = getVectorValue(it->getOperand(0));
3033 VectorParts &B = getVectorValue(it->getOperand(1));
3034 for (unsigned Part = 0; Part < UF; ++Part) {
3037 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3039 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3045 case Instruction::Store:
3046 case Instruction::Load:
3047 vectorizeMemoryInstruction(it);
3049 case Instruction::ZExt:
3050 case Instruction::SExt:
3051 case Instruction::FPToUI:
3052 case Instruction::FPToSI:
3053 case Instruction::FPExt:
3054 case Instruction::PtrToInt:
3055 case Instruction::IntToPtr:
3056 case Instruction::SIToFP:
3057 case Instruction::UIToFP:
3058 case Instruction::Trunc:
3059 case Instruction::FPTrunc:
3060 case Instruction::BitCast: {
3061 CastInst *CI = dyn_cast<CastInst>(it);
3062 setDebugLocFromInst(Builder, it);
3063 /// Optimize the special case where the source is the induction
3064 /// variable. Notice that we can only optimize the 'trunc' case
3065 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3066 /// c. other casts depend on pointer size.
3067 if (CI->getOperand(0) == OldInduction &&
3068 it->getOpcode() == Instruction::Trunc) {
3069 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3071 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3072 for (unsigned Part = 0; Part < UF; ++Part)
3073 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3076 /// Vectorize casts.
3077 Type *DestTy = (VF == 1) ? CI->getType() :
3078 VectorType::get(CI->getType(), VF);
3080 VectorParts &A = getVectorValue(it->getOperand(0));
3081 for (unsigned Part = 0; Part < UF; ++Part)
3082 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3086 case Instruction::Call: {
3087 // Ignore dbg intrinsics.
3088 if (isa<DbgInfoIntrinsic>(it))
3090 setDebugLocFromInst(Builder, it);
3092 Module *M = BB->getParent()->getParent();
3093 CallInst *CI = cast<CallInst>(it);
3094 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3095 assert(ID && "Not an intrinsic call!");
3097 case Intrinsic::lifetime_end:
3098 case Intrinsic::lifetime_start:
3099 scalarizeInstruction(it);
3102 for (unsigned Part = 0; Part < UF; ++Part) {
3103 SmallVector<Value *, 4> Args;
3104 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3105 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3106 Args.push_back(Arg[Part]);
3108 Type *Tys[] = {CI->getType()};
3110 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3112 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3113 Entry[Part] = Builder.CreateCall(F, Args);
3121 // All other instructions are unsupported. Scalarize them.
3122 scalarizeInstruction(it);
3125 }// end of for_each instr.
3128 void InnerLoopVectorizer::updateAnalysis() {
3129 // Forget the original basic block.
3130 SE->forgetLoop(OrigLoop);
3132 // Update the dominator tree information.
3133 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3134 "Entry does not dominate exit.");
3136 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3137 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3138 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3140 // Due to if predication of stores we might create a sequence of "if(pred)
3141 // a[i] = ...; " blocks.
3142 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3144 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3145 else if (isPredicatedBlock(i)) {
3146 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3148 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3152 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
3153 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
3154 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3155 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3157 DEBUG(DT->verifyDomTree());
3160 /// \brief Check whether it is safe to if-convert this phi node.
3162 /// Phi nodes with constant expressions that can trap are not safe to if
3164 static bool canIfConvertPHINodes(BasicBlock *BB) {
3165 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3166 PHINode *Phi = dyn_cast<PHINode>(I);
3169 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3170 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3177 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3178 if (!EnableIfConversion)
3181 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3183 // A list of pointers that we can safely read and write to.
3184 SmallPtrSet<Value *, 8> SafePointes;
3186 // Collect safe addresses.
3187 for (Loop::block_iterator BI = TheLoop->block_begin(),
3188 BE = TheLoop->block_end(); BI != BE; ++BI) {
3189 BasicBlock *BB = *BI;
3191 if (blockNeedsPredication(BB))
3194 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3195 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3196 SafePointes.insert(LI->getPointerOperand());
3197 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3198 SafePointes.insert(SI->getPointerOperand());
3202 // Collect the blocks that need predication.
3203 BasicBlock *Header = TheLoop->getHeader();
3204 for (Loop::block_iterator BI = TheLoop->block_begin(),
3205 BE = TheLoop->block_end(); BI != BE; ++BI) {
3206 BasicBlock *BB = *BI;
3208 // We don't support switch statements inside loops.
3209 if (!isa<BranchInst>(BB->getTerminator()))
3212 // We must be able to predicate all blocks that need to be predicated.
3213 if (blockNeedsPredication(BB)) {
3214 if (!blockCanBePredicated(BB, SafePointes))
3216 } else if (BB != Header && !canIfConvertPHINodes(BB))
3221 // We can if-convert this loop.
3225 bool LoopVectorizationLegality::canVectorize() {
3226 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3227 // be canonicalized.
3228 if (!TheLoop->getLoopPreheader())
3231 // We can only vectorize innermost loops.
3232 if (TheLoop->getSubLoopsVector().size())
3235 // We must have a single backedge.
3236 if (TheLoop->getNumBackEdges() != 1)
3239 // We must have a single exiting block.
3240 if (!TheLoop->getExitingBlock())
3243 // We need to have a loop header.
3244 DEBUG(dbgs() << "LV: Found a loop: " <<
3245 TheLoop->getHeader()->getName() << '\n');
3247 // Check if we can if-convert non-single-bb loops.
3248 unsigned NumBlocks = TheLoop->getNumBlocks();
3249 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3250 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3254 // ScalarEvolution needs to be able to find the exit count.
3255 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3256 if (ExitCount == SE->getCouldNotCompute()) {
3257 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3261 // Do not loop-vectorize loops with a tiny trip count.
3262 BasicBlock *Latch = TheLoop->getLoopLatch();
3263 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
3264 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
3265 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
3266 "This loop is not worth vectorizing.\n");
3270 // Check if we can vectorize the instructions and CFG in this loop.
3271 if (!canVectorizeInstrs()) {
3272 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3276 // Go over each instruction and look at memory deps.
3277 if (!canVectorizeMemory()) {
3278 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3282 // Collect all of the variables that remain uniform after vectorization.
3283 collectLoopUniforms();
3285 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3286 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3289 // Okay! We can vectorize. At this point we don't have any other mem analysis
3290 // which may limit our maximum vectorization factor, so just return true with
3295 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
3296 if (Ty->isPointerTy())
3297 return DL.getIntPtrType(Ty);
3299 // It is possible that char's or short's overflow when we ask for the loop's
3300 // trip count, work around this by changing the type size.
3301 if (Ty->getScalarSizeInBits() < 32)
3302 return Type::getInt32Ty(Ty->getContext());
3307 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
3308 Ty0 = convertPointerToIntegerType(DL, Ty0);
3309 Ty1 = convertPointerToIntegerType(DL, Ty1);
3310 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3315 /// \brief Check that the instruction has outside loop users and is not an
3316 /// identified reduction variable.
3317 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3318 SmallPtrSet<Value *, 4> &Reductions) {
3319 // Reduction instructions are allowed to have exit users. All other
3320 // instructions must not have external users.
3321 if (!Reductions.count(Inst))
3322 //Check that all of the users of the loop are inside the BB.
3323 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
3325 Instruction *U = cast<Instruction>(*I);
3326 // This user may be a reduction exit value.
3327 if (!TheLoop->contains(U)) {
3328 DEBUG(dbgs() << "LV: Found an outside user for : " << *U << '\n');
3335 bool LoopVectorizationLegality::canVectorizeInstrs() {
3336 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3337 BasicBlock *Header = TheLoop->getHeader();
3339 // Look for the attribute signaling the absence of NaNs.
3340 Function &F = *Header->getParent();
3341 if (F.hasFnAttribute("no-nans-fp-math"))
3342 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3343 AttributeSet::FunctionIndex,
3344 "no-nans-fp-math").getValueAsString() == "true";
3346 // For each block in the loop.
3347 for (Loop::block_iterator bb = TheLoop->block_begin(),
3348 be = TheLoop->block_end(); bb != be; ++bb) {
3350 // Scan the instructions in the block and look for hazards.
3351 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3354 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3355 Type *PhiTy = Phi->getType();
3356 // Check that this PHI type is allowed.
3357 if (!PhiTy->isIntegerTy() &&
3358 !PhiTy->isFloatingPointTy() &&
3359 !PhiTy->isPointerTy()) {
3360 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3364 // If this PHINode is not in the header block, then we know that we
3365 // can convert it to select during if-conversion. No need to check if
3366 // the PHIs in this block are induction or reduction variables.
3367 if (*bb != Header) {
3368 // Check that this instruction has no outside users or is an
3369 // identified reduction value with an outside user.
3370 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3375 // We only allow if-converted PHIs with more than two incoming values.
3376 if (Phi->getNumIncomingValues() != 2) {
3377 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3381 // This is the value coming from the preheader.
3382 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3383 // Check if this is an induction variable.
3384 InductionKind IK = isInductionVariable(Phi);
3386 if (IK_NoInduction != IK) {
3387 // Get the widest type.
3389 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3391 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3393 // Int inductions are special because we only allow one IV.
3394 if (IK == IK_IntInduction) {
3395 // Use the phi node with the widest type as induction. Use the last
3396 // one if there are multiple (no good reason for doing this other
3397 // than it is expedient).
3398 if (!Induction || PhiTy == WidestIndTy)
3402 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3403 Inductions[Phi] = InductionInfo(StartValue, IK);
3405 // Until we explicitly handle the case of an induction variable with
3406 // an outside loop user we have to give up vectorizing this loop.
3407 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3413 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3414 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3417 if (AddReductionVar(Phi, RK_IntegerMult)) {
3418 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3421 if (AddReductionVar(Phi, RK_IntegerOr)) {
3422 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3425 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3426 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3429 if (AddReductionVar(Phi, RK_IntegerXor)) {
3430 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3433 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3434 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3437 if (AddReductionVar(Phi, RK_FloatMult)) {
3438 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3441 if (AddReductionVar(Phi, RK_FloatAdd)) {
3442 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3445 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3446 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3451 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3453 }// end of PHI handling
3455 // We still don't handle functions. However, we can ignore dbg intrinsic
3456 // calls and we do handle certain intrinsic and libm functions.
3457 CallInst *CI = dyn_cast<CallInst>(it);
3458 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3459 DEBUG(dbgs() << "LV: Found a call site.\n");
3463 // Check that the instruction return type is vectorizable.
3464 // Also, we can't vectorize extractelement instructions.
3465 if ((!VectorType::isValidElementType(it->getType()) &&
3466 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3467 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3471 // Check that the stored type is vectorizable.
3472 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3473 Type *T = ST->getValueOperand()->getType();
3474 if (!VectorType::isValidElementType(T))
3476 if (EnableMemAccessVersioning)
3477 collectStridedAcccess(ST);
3480 if (EnableMemAccessVersioning)
3481 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3482 collectStridedAcccess(LI);
3484 // Reduction instructions are allowed to have exit users.
3485 // All other instructions must not have external users.
3486 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3494 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3495 if (Inductions.empty())
3502 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3503 /// return the induction operand of the gep pointer.
3504 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3505 DataLayout *DL, Loop *Lp) {
3506 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3510 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3512 // Check that all of the gep indices are uniform except for our induction
3514 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3515 if (i != InductionOperand &&
3516 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3518 return GEP->getOperand(InductionOperand);
3521 ///\brief Look for a cast use of the passed value.
3522 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3523 Value *UniqueCast = 0;
3524 for (Value::use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); UI != UE;
3526 CastInst *CI = dyn_cast<CastInst>(*UI);
3527 if (CI && CI->getType() == Ty) {
3537 ///\brief Get the stride of a pointer access in a loop.
3538 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3539 /// pointer to the Value, or null otherwise.
3540 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3541 DataLayout *DL, Loop *Lp) {
3542 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3543 if (!PtrTy || PtrTy->isAggregateType())
3546 // Try to remove a gep instruction to make the pointer (actually index at this
3547 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3548 // pointer, otherwise, we are analyzing the index.
3549 Value *OrigPtr = Ptr;
3551 // The size of the pointer access.
3552 int64_t PtrAccessSize = 1;
3554 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3555 const SCEV *V = SE->getSCEV(Ptr);
3559 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3560 V = C->getOperand();
3562 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3566 V = S->getStepRecurrence(*SE);
3570 // Strip off the size of access multiplication if we are still analyzing the
3572 if (OrigPtr == Ptr) {
3573 DL->getTypeAllocSize(PtrTy->getElementType());
3574 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3575 if (M->getOperand(0)->getSCEVType() != scConstant)
3578 const APInt &APStepVal =
3579 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3581 // Huge step value - give up.
3582 if (APStepVal.getBitWidth() > 64)
3585 int64_t StepVal = APStepVal.getSExtValue();
3586 if (PtrAccessSize != StepVal)
3588 V = M->getOperand(1);
3593 Type *StripedOffRecurrenceCast = 0;
3594 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3595 StripedOffRecurrenceCast = C->getType();
3596 V = C->getOperand();
3599 // Look for the loop invariant symbolic value.
3600 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3604 Value *Stride = U->getValue();
3605 if (!Lp->isLoopInvariant(Stride))
3608 // If we have stripped off the recurrence cast we have to make sure that we
3609 // return the value that is used in this loop so that we can replace it later.
3610 if (StripedOffRecurrenceCast)
3611 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3616 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3618 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3619 Ptr = LI->getPointerOperand();
3620 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3621 Ptr = SI->getPointerOperand();
3625 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3629 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3630 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3631 Strides[Ptr] = Stride;
3632 StrideSet.insert(Stride);
3635 void LoopVectorizationLegality::collectLoopUniforms() {
3636 // We now know that the loop is vectorizable!
3637 // Collect variables that will remain uniform after vectorization.
3638 std::vector<Value*> Worklist;
3639 BasicBlock *Latch = TheLoop->getLoopLatch();
3641 // Start with the conditional branch and walk up the block.
3642 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3644 while (Worklist.size()) {
3645 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3646 Worklist.pop_back();
3648 // Look at instructions inside this loop.
3649 // Stop when reaching PHI nodes.
3650 // TODO: we need to follow values all over the loop, not only in this block.
3651 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3654 // This is a known uniform.
3657 // Insert all operands.
3658 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3663 /// \brief Analyses memory accesses in a loop.
3665 /// Checks whether run time pointer checks are needed and builds sets for data
3666 /// dependence checking.
3667 class AccessAnalysis {
3669 /// \brief Read or write access location.
3670 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3671 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3673 /// \brief Set of potential dependent memory accesses.
3674 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3676 AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
3677 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3678 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3680 /// \brief Register a load and whether it is only read from.
3681 void addLoad(Value *Ptr, bool IsReadOnly) {
3682 Accesses.insert(MemAccessInfo(Ptr, false));
3684 ReadOnlyPtr.insert(Ptr);
3687 /// \brief Register a store.
3688 void addStore(Value *Ptr) {
3689 Accesses.insert(MemAccessInfo(Ptr, true));
3692 /// \brief Check whether we can check the pointers at runtime for
3693 /// non-intersection.
3694 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3695 unsigned &NumComparisons, ScalarEvolution *SE,
3696 Loop *TheLoop, ValueToValueMap &Strides,
3697 bool ShouldCheckStride = false);
3699 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3700 /// and builds sets of dependent accesses.
3701 void buildDependenceSets() {
3702 // Process read-write pointers first.
3703 processMemAccesses(false);
3704 // Next, process read pointers.
3705 processMemAccesses(true);
3708 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3710 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3711 void resetDepChecks() { CheckDeps.clear(); }
3713 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3716 typedef SetVector<MemAccessInfo> PtrAccessSet;
3717 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3719 /// \brief Go over all memory access or only the deferred ones if
3720 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3721 /// and build sets of dependency check candidates.
3722 void processMemAccesses(bool UseDeferred);
3724 /// Set of all accesses.
3725 PtrAccessSet Accesses;
3727 /// Set of access to check after all writes have been processed.
3728 PtrAccessSet DeferredAccesses;
3730 /// Map of pointers to last access encountered.
3731 UnderlyingObjToAccessMap ObjToLastAccess;
3733 /// Set of accesses that need a further dependence check.
3734 MemAccessInfoSet CheckDeps;
3736 /// Set of pointers that are read only.
3737 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3739 /// Set of underlying objects already written to.
3740 SmallPtrSet<Value*, 16> WriteObjects;
3744 /// Sets of potentially dependent accesses - members of one set share an
3745 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3746 /// dependence check.
3747 DepCandidates &DepCands;
3749 bool AreAllWritesIdentified;
3750 bool AreAllReadsIdentified;
3751 bool IsRTCheckNeeded;
3754 } // end anonymous namespace
3756 /// \brief Check whether a pointer can participate in a runtime bounds check.
3757 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3759 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3760 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3764 return AR->isAffine();
3767 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3768 /// the address space.
3769 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3770 const Loop *Lp, ValueToValueMap &StridesMap);
3772 bool AccessAnalysis::canCheckPtrAtRT(
3773 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3774 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3775 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3776 // Find pointers with computable bounds. We are going to use this information
3777 // to place a runtime bound check.
3778 unsigned NumReadPtrChecks = 0;
3779 unsigned NumWritePtrChecks = 0;
3780 bool CanDoRT = true;
3782 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3783 // We assign consecutive id to access from different dependence sets.
3784 // Accesses within the same set don't need a runtime check.
3785 unsigned RunningDepId = 1;
3786 DenseMap<Value *, unsigned> DepSetId;
3788 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3790 const MemAccessInfo &Access = *AI;
3791 Value *Ptr = Access.getPointer();
3792 bool IsWrite = Access.getInt();
3794 // Just add write checks if we have both.
3795 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3799 ++NumWritePtrChecks;
3803 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3804 // When we run after a failing dependency check we have to make sure we
3805 // don't have wrapping pointers.
3806 (!ShouldCheckStride ||
3807 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3808 // The id of the dependence set.
3811 if (IsDepCheckNeeded) {
3812 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3813 unsigned &LeaderId = DepSetId[Leader];
3815 LeaderId = RunningDepId++;
3818 // Each access has its own dependence set.
3819 DepId = RunningDepId++;
3821 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3823 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3829 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3830 NumComparisons = 0; // Only one dependence set.
3832 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3833 NumWritePtrChecks - 1));
3836 // If the pointers that we would use for the bounds comparison have different
3837 // address spaces, assume the values aren't directly comparable, so we can't
3838 // use them for the runtime check. We also have to assume they could
3839 // overlap. In the future there should be metadata for whether address spaces
3841 unsigned NumPointers = RtCheck.Pointers.size();
3842 for (unsigned i = 0; i < NumPointers; ++i) {
3843 for (unsigned j = i + 1; j < NumPointers; ++j) {
3844 // Only need to check pointers between two different dependency sets.
3845 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3848 Value *PtrI = RtCheck.Pointers[i];
3849 Value *PtrJ = RtCheck.Pointers[j];
3851 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3852 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3854 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3855 " different address spaces\n");
3864 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3865 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3868 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3869 // We process the set twice: first we process read-write pointers, last we
3870 // process read-only pointers. This allows us to skip dependence tests for
3871 // read-only pointers.
3873 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3874 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3875 const MemAccessInfo &Access = *AI;
3876 Value *Ptr = Access.getPointer();
3877 bool IsWrite = Access.getInt();
3879 DepCands.insert(Access);
3881 // Memorize read-only pointers for later processing and skip them in the
3882 // first round (they need to be checked after we have seen all write
3883 // pointers). Note: we also mark pointer that are not consecutive as
3884 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3885 // second check for "!IsWrite".
3886 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3887 if (!UseDeferred && IsReadOnlyPtr) {
3888 DeferredAccesses.insert(Access);
3892 bool NeedDepCheck = false;
3893 // Check whether there is the possibility of dependency because of
3894 // underlying objects being the same.
3895 typedef SmallVector<Value*, 16> ValueVector;
3896 ValueVector TempObjects;
3897 GetUnderlyingObjects(Ptr, TempObjects, DL);
3898 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3900 Value *UnderlyingObj = *UI;
3902 // If this is a write then it needs to be an identified object. If this a
3903 // read and all writes (so far) are identified function scope objects we
3904 // don't need an identified underlying object but only an Argument (the
3905 // next write is going to invalidate this assumption if it is
3907 // This is a micro-optimization for the case where all writes are
3908 // identified and we have one argument pointer.
3909 // Otherwise, we do need a runtime check.
3910 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3911 (!IsWrite && (!AreAllWritesIdentified ||
3912 !isa<Argument>(UnderlyingObj)) &&
3913 !isIdentifiedObject(UnderlyingObj))) {
3914 DEBUG(dbgs() << "LV: Found an unidentified " <<
3915 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3917 IsRTCheckNeeded = (IsRTCheckNeeded ||
3918 !isIdentifiedObject(UnderlyingObj) ||
3919 !AreAllReadsIdentified);
3922 AreAllWritesIdentified = false;
3924 AreAllReadsIdentified = false;
3927 // If this is a write - check other reads and writes for conflicts. If
3928 // this is a read only check other writes for conflicts (but only if there
3929 // is no other write to the ptr - this is an optimization to catch "a[i] =
3930 // a[i] + " without having to do a dependence check).
3931 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3932 NeedDepCheck = true;
3935 WriteObjects.insert(UnderlyingObj);
3937 // Create sets of pointers connected by shared underlying objects.
3938 UnderlyingObjToAccessMap::iterator Prev =
3939 ObjToLastAccess.find(UnderlyingObj);
3940 if (Prev != ObjToLastAccess.end())
3941 DepCands.unionSets(Access, Prev->second);
3943 ObjToLastAccess[UnderlyingObj] = Access;
3947 CheckDeps.insert(Access);
3952 /// \brief Checks memory dependences among accesses to the same underlying
3953 /// object to determine whether there vectorization is legal or not (and at
3954 /// which vectorization factor).
3956 /// This class works under the assumption that we already checked that memory
3957 /// locations with different underlying pointers are "must-not alias".
3958 /// We use the ScalarEvolution framework to symbolically evalutate access
3959 /// functions pairs. Since we currently don't restructure the loop we can rely
3960 /// on the program order of memory accesses to determine their safety.
3961 /// At the moment we will only deem accesses as safe for:
3962 /// * A negative constant distance assuming program order.
3964 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
3965 /// a[i] = tmp; y = a[i];
3967 /// The latter case is safe because later checks guarantuee that there can't
3968 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
3969 /// the same variable: a header phi can only be an induction or a reduction, a
3970 /// reduction can't have a memory sink, an induction can't have a memory
3971 /// source). This is important and must not be violated (or we have to
3972 /// resort to checking for cycles through memory).
3974 /// * A positive constant distance assuming program order that is bigger
3975 /// than the biggest memory access.
3977 /// tmp = a[i] OR b[i] = x
3978 /// a[i+2] = tmp y = b[i+2];
3980 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3982 /// * Zero distances and all accesses have the same size.
3984 class MemoryDepChecker {
3986 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3987 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3989 MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L)
3990 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
3991 ShouldRetryWithRuntimeCheck(false) {}
3993 /// \brief Register the location (instructions are given increasing numbers)
3994 /// of a write access.
3995 void addAccess(StoreInst *SI) {
3996 Value *Ptr = SI->getPointerOperand();
3997 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3998 InstMap.push_back(SI);
4002 /// \brief Register the location (instructions are given increasing numbers)
4003 /// of a write access.
4004 void addAccess(LoadInst *LI) {
4005 Value *Ptr = LI->getPointerOperand();
4006 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4007 InstMap.push_back(LI);
4011 /// \brief Check whether the dependencies between the accesses are safe.
4013 /// Only checks sets with elements in \p CheckDeps.
4014 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4015 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4017 /// \brief The maximum number of bytes of a vector register we can vectorize
4018 /// the accesses safely with.
4019 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4021 /// \brief In same cases when the dependency check fails we can still
4022 /// vectorize the loop with a dynamic array access check.
4023 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4026 ScalarEvolution *SE;
4028 const Loop *InnermostLoop;
4030 /// \brief Maps access locations (ptr, read/write) to program order.
4031 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4033 /// \brief Memory access instructions in program order.
4034 SmallVector<Instruction *, 16> InstMap;
4036 /// \brief The program order index to be used for the next instruction.
4039 // We can access this many bytes in parallel safely.
4040 unsigned MaxSafeDepDistBytes;
4042 /// \brief If we see a non-constant dependence distance we can still try to
4043 /// vectorize this loop with runtime checks.
4044 bool ShouldRetryWithRuntimeCheck;
4046 /// \brief Check whether there is a plausible dependence between the two
4049 /// Access \p A must happen before \p B in program order. The two indices
4050 /// identify the index into the program order map.
4052 /// This function checks whether there is a plausible dependence (or the
4053 /// absence of such can't be proved) between the two accesses. If there is a
4054 /// plausible dependence but the dependence distance is bigger than one
4055 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4056 /// distance is smaller than any other distance encountered so far).
4057 /// Otherwise, this function returns true signaling a possible dependence.
4058 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4059 const MemAccessInfo &B, unsigned BIdx,
4060 ValueToValueMap &Strides);
4062 /// \brief Check whether the data dependence could prevent store-load
4064 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4067 } // end anonymous namespace
4069 static bool isInBoundsGep(Value *Ptr) {
4070 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4071 return GEP->isInBounds();
4075 /// \brief Check whether the access through \p Ptr has a constant stride.
4076 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
4077 const Loop *Lp, ValueToValueMap &StridesMap) {
4078 const Type *Ty = Ptr->getType();
4079 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4081 // Make sure that the pointer does not point to aggregate types.
4082 const PointerType *PtrTy = cast<PointerType>(Ty);
4083 if (PtrTy->getElementType()->isAggregateType()) {
4084 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4089 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4091 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4093 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4094 << *Ptr << " SCEV: " << *PtrScev << "\n");
4098 // The accesss function must stride over the innermost loop.
4099 if (Lp != AR->getLoop()) {
4100 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4101 *Ptr << " SCEV: " << *PtrScev << "\n");
4104 // The address calculation must not wrap. Otherwise, a dependence could be
4106 // An inbounds getelementptr that is a AddRec with a unit stride
4107 // cannot wrap per definition. The unit stride requirement is checked later.
4108 // An getelementptr without an inbounds attribute and unit stride would have
4109 // to access the pointer value "0" which is undefined behavior in address
4110 // space 0, therefore we can also vectorize this case.
4111 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4112 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4113 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4114 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4115 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4116 << *Ptr << " SCEV: " << *PtrScev << "\n");
4120 // Check the step is constant.
4121 const SCEV *Step = AR->getStepRecurrence(*SE);
4123 // Calculate the pointer stride and check if it is consecutive.
4124 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4126 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4127 " SCEV: " << *PtrScev << "\n");
4131 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4132 const APInt &APStepVal = C->getValue()->getValue();
4134 // Huge step value - give up.
4135 if (APStepVal.getBitWidth() > 64)
4138 int64_t StepVal = APStepVal.getSExtValue();
4141 int64_t Stride = StepVal / Size;
4142 int64_t Rem = StepVal % Size;
4146 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4147 // know we can't "wrap around the address space". In case of address space
4148 // zero we know that this won't happen without triggering undefined behavior.
4149 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4150 Stride != 1 && Stride != -1)
4156 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4157 unsigned TypeByteSize) {
4158 // If loads occur at a distance that is not a multiple of a feasible vector
4159 // factor store-load forwarding does not take place.
4160 // Positive dependences might cause troubles because vectorizing them might
4161 // prevent store-load forwarding making vectorized code run a lot slower.
4162 // a[i] = a[i-3] ^ a[i-8];
4163 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4164 // hence on your typical architecture store-load forwarding does not take
4165 // place. Vectorizing in such cases does not make sense.
4166 // Store-load forwarding distance.
4167 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4168 // Maximum vector factor.
4169 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4170 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4171 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4173 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4175 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4176 MaxVFWithoutSLForwardIssues = (vf >>=1);
4181 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4182 DEBUG(dbgs() << "LV: Distance " << Distance <<
4183 " that could cause a store-load forwarding conflict\n");
4187 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4188 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4189 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4193 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4194 const MemAccessInfo &B, unsigned BIdx,
4195 ValueToValueMap &Strides) {
4196 assert (AIdx < BIdx && "Must pass arguments in program order");
4198 Value *APtr = A.getPointer();
4199 Value *BPtr = B.getPointer();
4200 bool AIsWrite = A.getInt();
4201 bool BIsWrite = B.getInt();
4203 // Two reads are independent.
4204 if (!AIsWrite && !BIsWrite)
4207 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4208 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4210 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4211 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4213 const SCEV *Src = AScev;
4214 const SCEV *Sink = BScev;
4216 // If the induction step is negative we have to invert source and sink of the
4218 if (StrideAPtr < 0) {
4221 std::swap(APtr, BPtr);
4222 std::swap(Src, Sink);
4223 std::swap(AIsWrite, BIsWrite);
4224 std::swap(AIdx, BIdx);
4225 std::swap(StrideAPtr, StrideBPtr);
4228 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4230 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4231 << "(Induction step: " << StrideAPtr << ")\n");
4232 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4233 << *InstMap[BIdx] << ": " << *Dist << "\n");
4235 // Need consecutive accesses. We don't want to vectorize
4236 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4237 // the address space.
4238 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4239 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4243 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4245 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4246 ShouldRetryWithRuntimeCheck = true;
4250 Type *ATy = APtr->getType()->getPointerElementType();
4251 Type *BTy = BPtr->getType()->getPointerElementType();
4252 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4254 // Negative distances are not plausible dependencies.
4255 const APInt &Val = C->getValue()->getValue();
4256 if (Val.isNegative()) {
4257 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4258 if (IsTrueDataDependence &&
4259 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4263 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4267 // Write to the same location with the same size.
4268 // Could be improved to assert type sizes are the same (i32 == float, etc).
4272 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4276 assert(Val.isStrictlyPositive() && "Expect a positive value");
4278 // Positive distance bigger than max vectorization factor.
4281 "LV: ReadWrite-Write positive dependency with different types\n");
4285 unsigned Distance = (unsigned) Val.getZExtValue();
4287 // Bail out early if passed-in parameters make vectorization not feasible.
4288 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4289 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4291 // The distance must be bigger than the size needed for a vectorized version
4292 // of the operation and the size of the vectorized operation must not be
4293 // bigger than the currrent maximum size.
4294 if (Distance < 2*TypeByteSize ||
4295 2*TypeByteSize > MaxSafeDepDistBytes ||
4296 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4297 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4298 << Val.getSExtValue() << '\n');
4302 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4303 Distance : MaxSafeDepDistBytes;
4305 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4306 if (IsTrueDataDependence &&
4307 couldPreventStoreLoadForward(Distance, TypeByteSize))
4310 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4311 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4316 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4317 MemAccessInfoSet &CheckDeps,
4318 ValueToValueMap &Strides) {
4320 MaxSafeDepDistBytes = -1U;
4321 while (!CheckDeps.empty()) {
4322 MemAccessInfo CurAccess = *CheckDeps.begin();
4324 // Get the relevant memory access set.
4325 EquivalenceClasses<MemAccessInfo>::iterator I =
4326 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4328 // Check accesses within this set.
4329 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4330 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4332 // Check every access pair.
4334 CheckDeps.erase(*AI);
4335 EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
4337 // Check every accessing instruction pair in program order.
4338 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4339 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4340 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4341 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4342 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4344 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4355 bool LoopVectorizationLegality::canVectorizeMemory() {
4357 typedef SmallVector<Value*, 16> ValueVector;
4358 typedef SmallPtrSet<Value*, 16> ValueSet;
4360 // Holds the Load and Store *instructions*.
4364 // Holds all the different accesses in the loop.
4365 unsigned NumReads = 0;
4366 unsigned NumReadWrites = 0;
4368 PtrRtCheck.Pointers.clear();
4369 PtrRtCheck.Need = false;
4371 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4372 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4375 for (Loop::block_iterator bb = TheLoop->block_begin(),
4376 be = TheLoop->block_end(); bb != be; ++bb) {
4378 // Scan the BB and collect legal loads and stores.
4379 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4382 // If this is a load, save it. If this instruction can read from memory
4383 // but is not a load, then we quit. Notice that we don't handle function
4384 // calls that read or write.
4385 if (it->mayReadFromMemory()) {
4386 // Many math library functions read the rounding mode. We will only
4387 // vectorize a loop if it contains known function calls that don't set
4388 // the flag. Therefore, it is safe to ignore this read from memory.
4389 CallInst *Call = dyn_cast<CallInst>(it);
4390 if (Call && getIntrinsicIDForCall(Call, TLI))
4393 LoadInst *Ld = dyn_cast<LoadInst>(it);
4394 if (!Ld) return false;
4395 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4396 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4400 Loads.push_back(Ld);
4401 DepChecker.addAccess(Ld);
4405 // Save 'store' instructions. Abort if other instructions write to memory.
4406 if (it->mayWriteToMemory()) {
4407 StoreInst *St = dyn_cast<StoreInst>(it);
4408 if (!St) return false;
4409 if (!St->isSimple() && !IsAnnotatedParallel) {
4410 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4414 Stores.push_back(St);
4415 DepChecker.addAccess(St);
4420 // Now we have two lists that hold the loads and the stores.
4421 // Next, we find the pointers that they use.
4423 // Check if we see any stores. If there are no stores, then we don't
4424 // care if the pointers are *restrict*.
4425 if (!Stores.size()) {
4426 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4430 AccessAnalysis::DepCandidates DependentAccesses;
4431 AccessAnalysis Accesses(DL, DependentAccesses);
4433 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4434 // multiple times on the same object. If the ptr is accessed twice, once
4435 // for read and once for write, it will only appear once (on the write
4436 // list). This is okay, since we are going to check for conflicts between
4437 // writes and between reads and writes, but not between reads and reads.
4440 ValueVector::iterator I, IE;
4441 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4442 StoreInst *ST = cast<StoreInst>(*I);
4443 Value* Ptr = ST->getPointerOperand();
4445 if (isUniform(Ptr)) {
4446 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4450 // If we did *not* see this pointer before, insert it to the read-write
4451 // list. At this phase it is only a 'write' list.
4452 if (Seen.insert(Ptr)) {
4454 Accesses.addStore(Ptr);
4458 if (IsAnnotatedParallel) {
4460 << "LV: A loop annotated parallel, ignore memory dependency "
4465 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4466 LoadInst *LD = cast<LoadInst>(*I);
4467 Value* Ptr = LD->getPointerOperand();
4468 // If we did *not* see this pointer before, insert it to the
4469 // read list. If we *did* see it before, then it is already in
4470 // the read-write list. This allows us to vectorize expressions
4471 // such as A[i] += x; Because the address of A[i] is a read-write
4472 // pointer. This only works if the index of A[i] is consecutive.
4473 // If the address of i is unknown (for example A[B[i]]) then we may
4474 // read a few words, modify, and write a few words, and some of the
4475 // words may be written to the same address.
4476 bool IsReadOnlyPtr = false;
4477 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4479 IsReadOnlyPtr = true;
4481 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4484 // If we write (or read-write) to a single destination and there are no
4485 // other reads in this loop then is it safe to vectorize.
4486 if (NumReadWrites == 1 && NumReads == 0) {
4487 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4491 // Build dependence sets and check whether we need a runtime pointer bounds
4493 Accesses.buildDependenceSets();
4494 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4496 // Find pointers with computable bounds. We are going to use this information
4497 // to place a runtime bound check.
4498 unsigned NumComparisons = 0;
4499 bool CanDoRT = false;
4501 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4504 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4505 " pointer comparisons.\n");
4507 // If we only have one set of dependences to check pointers among we don't
4508 // need a runtime check.
4509 if (NumComparisons == 0 && NeedRTCheck)
4510 NeedRTCheck = false;
4512 // Check that we did not collect too many pointers or found an unsizeable
4514 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4520 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4523 if (NeedRTCheck && !CanDoRT) {
4524 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4525 "the array bounds.\n");
4530 PtrRtCheck.Need = NeedRTCheck;
4532 bool CanVecMem = true;
4533 if (Accesses.isDependencyCheckNeeded()) {
4534 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4535 CanVecMem = DepChecker.areDepsSafe(
4536 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4537 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4539 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4540 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4543 // Clear the dependency checks. We assume they are not needed.
4544 Accesses.resetDepChecks();
4547 PtrRtCheck.Need = true;
4549 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4550 TheLoop, Strides, true);
4551 // Check that we did not collect too many pointers or found an unsizeable
4553 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4554 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4563 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4564 " need a runtime memory check.\n");
4569 static bool hasMultipleUsesOf(Instruction *I,
4570 SmallPtrSet<Instruction *, 8> &Insts) {
4571 unsigned NumUses = 0;
4572 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4573 if (Insts.count(dyn_cast<Instruction>(*Use)))
4582 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4583 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4584 if (!Set.count(dyn_cast<Instruction>(*Use)))
4589 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4590 ReductionKind Kind) {
4591 if (Phi->getNumIncomingValues() != 2)
4594 // Reduction variables are only found in the loop header block.
4595 if (Phi->getParent() != TheLoop->getHeader())
4598 // Obtain the reduction start value from the value that comes from the loop
4600 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4602 // ExitInstruction is the single value which is used outside the loop.
4603 // We only allow for a single reduction value to be used outside the loop.
4604 // This includes users of the reduction, variables (which form a cycle
4605 // which ends in the phi node).
4606 Instruction *ExitInstruction = 0;
4607 // Indicates that we found a reduction operation in our scan.
4608 bool FoundReduxOp = false;
4610 // We start with the PHI node and scan for all of the users of this
4611 // instruction. All users must be instructions that can be used as reduction
4612 // variables (such as ADD). We must have a single out-of-block user. The cycle
4613 // must include the original PHI.
4614 bool FoundStartPHI = false;
4616 // To recognize min/max patterns formed by a icmp select sequence, we store
4617 // the number of instruction we saw from the recognized min/max pattern,
4618 // to make sure we only see exactly the two instructions.
4619 unsigned NumCmpSelectPatternInst = 0;
4620 ReductionInstDesc ReduxDesc(false, 0);
4622 SmallPtrSet<Instruction *, 8> VisitedInsts;
4623 SmallVector<Instruction *, 8> Worklist;
4624 Worklist.push_back(Phi);
4625 VisitedInsts.insert(Phi);
4627 // A value in the reduction can be used:
4628 // - By the reduction:
4629 // - Reduction operation:
4630 // - One use of reduction value (safe).
4631 // - Multiple use of reduction value (not safe).
4633 // - All uses of the PHI must be the reduction (safe).
4634 // - Otherwise, not safe.
4635 // - By one instruction outside of the loop (safe).
4636 // - By further instructions outside of the loop (not safe).
4637 // - By an instruction that is not part of the reduction (not safe).
4639 // * An instruction type other than PHI or the reduction operation.
4640 // * A PHI in the header other than the initial PHI.
4641 while (!Worklist.empty()) {
4642 Instruction *Cur = Worklist.back();
4643 Worklist.pop_back();
4646 // If the instruction has no users then this is a broken chain and can't be
4647 // a reduction variable.
4648 if (Cur->use_empty())
4651 bool IsAPhi = isa<PHINode>(Cur);
4653 // A header PHI use other than the original PHI.
4654 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4657 // Reductions of instructions such as Div, and Sub is only possible if the
4658 // LHS is the reduction variable.
4659 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4660 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4661 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4664 // Any reduction instruction must be of one of the allowed kinds.
4665 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4666 if (!ReduxDesc.IsReduction)
4669 // A reduction operation must only have one use of the reduction value.
4670 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4671 hasMultipleUsesOf(Cur, VisitedInsts))
4674 // All inputs to a PHI node must be a reduction value.
4675 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4678 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4679 isa<SelectInst>(Cur)))
4680 ++NumCmpSelectPatternInst;
4681 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4682 isa<SelectInst>(Cur)))
4683 ++NumCmpSelectPatternInst;
4685 // Check whether we found a reduction operator.
4686 FoundReduxOp |= !IsAPhi;
4688 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4689 // onto the stack. This way we are going to have seen all inputs to PHI
4690 // nodes once we get to them.
4691 SmallVector<Instruction *, 8> NonPHIs;
4692 SmallVector<Instruction *, 8> PHIs;
4693 for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
4695 Instruction *Usr = cast<Instruction>(*UI);
4697 // Check if we found the exit user.
4698 BasicBlock *Parent = Usr->getParent();
4699 if (!TheLoop->contains(Parent)) {
4700 // Exit if you find multiple outside users or if the header phi node is
4701 // being used. In this case the user uses the value of the previous
4702 // iteration, in which case we would loose "VF-1" iterations of the
4703 // reduction operation if we vectorize.
4704 if (ExitInstruction != 0 || Cur == Phi)
4707 // The instruction used by an outside user must be the last instruction
4708 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4709 // operations on the value.
4710 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4713 ExitInstruction = Cur;
4717 // Process instructions only once (termination). Each reduction cycle
4718 // value must only be used once, except by phi nodes and min/max
4719 // reductions which are represented as a cmp followed by a select.
4720 ReductionInstDesc IgnoredVal(false, 0);
4721 if (VisitedInsts.insert(Usr)) {
4722 if (isa<PHINode>(Usr))
4723 PHIs.push_back(Usr);
4725 NonPHIs.push_back(Usr);
4726 } else if (!isa<PHINode>(Usr) &&
4727 ((!isa<FCmpInst>(Usr) &&
4728 !isa<ICmpInst>(Usr) &&
4729 !isa<SelectInst>(Usr)) ||
4730 !isMinMaxSelectCmpPattern(Usr, IgnoredVal).IsReduction))
4733 // Remember that we completed the cycle.
4735 FoundStartPHI = true;
4737 Worklist.append(PHIs.begin(), PHIs.end());
4738 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4741 // This means we have seen one but not the other instruction of the
4742 // pattern or more than just a select and cmp.
4743 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4744 NumCmpSelectPatternInst != 2)
4747 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4750 // We found a reduction var if we have reached the original phi node and we
4751 // only have a single instruction with out-of-loop users.
4753 // This instruction is allowed to have out-of-loop users.
4754 AllowedExit.insert(ExitInstruction);
4756 // Save the description of this reduction variable.
4757 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4758 ReduxDesc.MinMaxKind);
4759 Reductions[Phi] = RD;
4760 // We've ended the cycle. This is a reduction variable if we have an
4761 // outside user and it has a binary op.
4766 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4767 /// pattern corresponding to a min(X, Y) or max(X, Y).
4768 LoopVectorizationLegality::ReductionInstDesc
4769 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4770 ReductionInstDesc &Prev) {
4772 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4773 "Expect a select instruction");
4774 Instruction *Cmp = 0;
4775 SelectInst *Select = 0;
4777 // We must handle the select(cmp()) as a single instruction. Advance to the
4779 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4780 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
4781 return ReductionInstDesc(false, I);
4782 return ReductionInstDesc(Select, Prev.MinMaxKind);
4785 // Only handle single use cases for now.
4786 if (!(Select = dyn_cast<SelectInst>(I)))
4787 return ReductionInstDesc(false, I);
4788 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4789 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4790 return ReductionInstDesc(false, I);
4791 if (!Cmp->hasOneUse())
4792 return ReductionInstDesc(false, I);
4797 // Look for a min/max pattern.
4798 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4799 return ReductionInstDesc(Select, MRK_UIntMin);
4800 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4801 return ReductionInstDesc(Select, MRK_UIntMax);
4802 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4803 return ReductionInstDesc(Select, MRK_SIntMax);
4804 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4805 return ReductionInstDesc(Select, MRK_SIntMin);
4806 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4807 return ReductionInstDesc(Select, MRK_FloatMin);
4808 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4809 return ReductionInstDesc(Select, MRK_FloatMax);
4810 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4811 return ReductionInstDesc(Select, MRK_FloatMin);
4812 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4813 return ReductionInstDesc(Select, MRK_FloatMax);
4815 return ReductionInstDesc(false, I);
4818 LoopVectorizationLegality::ReductionInstDesc
4819 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4821 ReductionInstDesc &Prev) {
4822 bool FP = I->getType()->isFloatingPointTy();
4823 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4824 switch (I->getOpcode()) {
4826 return ReductionInstDesc(false, I);
4827 case Instruction::PHI:
4828 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4829 Kind != RK_FloatMinMax))
4830 return ReductionInstDesc(false, I);
4831 return ReductionInstDesc(I, Prev.MinMaxKind);
4832 case Instruction::Sub:
4833 case Instruction::Add:
4834 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4835 case Instruction::Mul:
4836 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4837 case Instruction::And:
4838 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4839 case Instruction::Or:
4840 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4841 case Instruction::Xor:
4842 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4843 case Instruction::FMul:
4844 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4845 case Instruction::FAdd:
4846 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4847 case Instruction::FCmp:
4848 case Instruction::ICmp:
4849 case Instruction::Select:
4850 if (Kind != RK_IntegerMinMax &&
4851 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4852 return ReductionInstDesc(false, I);
4853 return isMinMaxSelectCmpPattern(I, Prev);
4857 LoopVectorizationLegality::InductionKind
4858 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4859 Type *PhiTy = Phi->getType();
4860 // We only handle integer and pointer inductions variables.
4861 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4862 return IK_NoInduction;
4864 // Check that the PHI is consecutive.
4865 const SCEV *PhiScev = SE->getSCEV(Phi);
4866 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4868 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4869 return IK_NoInduction;
4871 const SCEV *Step = AR->getStepRecurrence(*SE);
4873 // Integer inductions need to have a stride of one.
4874 if (PhiTy->isIntegerTy()) {
4876 return IK_IntInduction;
4877 if (Step->isAllOnesValue())
4878 return IK_ReverseIntInduction;
4879 return IK_NoInduction;
4882 // Calculate the pointer stride and check if it is consecutive.
4883 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4885 return IK_NoInduction;
4887 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4888 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4889 if (C->getValue()->equalsInt(Size))
4890 return IK_PtrInduction;
4891 else if (C->getValue()->equalsInt(0 - Size))
4892 return IK_ReversePtrInduction;
4894 return IK_NoInduction;
4897 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4898 Value *In0 = const_cast<Value*>(V);
4899 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4903 return Inductions.count(PN);
4906 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4907 assert(TheLoop->contains(BB) && "Unknown block used");
4909 // Blocks that do not dominate the latch need predication.
4910 BasicBlock* Latch = TheLoop->getLoopLatch();
4911 return !DT->dominates(BB, Latch);
4914 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4915 SmallPtrSet<Value *, 8>& SafePtrs) {
4916 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4917 // We might be able to hoist the load.
4918 if (it->mayReadFromMemory()) {
4919 LoadInst *LI = dyn_cast<LoadInst>(it);
4920 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4924 // We don't predicate stores at the moment.
4925 if (it->mayWriteToMemory()) {
4926 StoreInst *SI = dyn_cast<StoreInst>(it);
4927 // We only support predication of stores in basic blocks with one
4929 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
4930 !SafePtrs.count(SI->getPointerOperand()) ||
4931 !SI->getParent()->getSinglePredecessor())
4937 // Check that we don't have a constant expression that can trap as operand.
4938 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4940 if (Constant *C = dyn_cast<Constant>(*OI))
4945 // The instructions below can trap.
4946 switch (it->getOpcode()) {
4948 case Instruction::UDiv:
4949 case Instruction::SDiv:
4950 case Instruction::URem:
4951 case Instruction::SRem:
4959 LoopVectorizationCostModel::VectorizationFactor
4960 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4962 // Width 1 means no vectorize
4963 VectorizationFactor Factor = { 1U, 0U };
4964 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4965 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4969 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
4970 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4974 // Find the trip count.
4975 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4976 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4978 unsigned WidestType = getWidestType();
4979 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4980 unsigned MaxSafeDepDist = -1U;
4981 if (Legal->getMaxSafeDepDistBytes() != -1U)
4982 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4983 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4984 WidestRegister : MaxSafeDepDist);
4985 unsigned MaxVectorSize = WidestRegister / WidestType;
4986 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4987 DEBUG(dbgs() << "LV: The Widest register is: "
4988 << WidestRegister << " bits.\n");
4990 if (MaxVectorSize == 0) {
4991 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4995 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4996 " into one vector!");
4998 unsigned VF = MaxVectorSize;
5000 // If we optimize the program for size, avoid creating the tail loop.
5002 // If we are unable to calculate the trip count then don't try to vectorize.
5004 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5008 // Find the maximum SIMD width that can fit within the trip count.
5009 VF = TC % MaxVectorSize;
5014 // If the trip count that we found modulo the vectorization factor is not
5015 // zero then we require a tail.
5017 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5023 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5024 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5026 Factor.Width = UserVF;
5030 float Cost = expectedCost(1);
5032 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
5033 for (unsigned i=2; i <= VF; i*=2) {
5034 // Notice that the vector loop needs to be executed less times, so
5035 // we need to divide the cost of the vector loops by the width of
5036 // the vector elements.
5037 float VectorCost = expectedCost(i) / (float)i;
5038 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5039 (int)VectorCost << ".\n");
5040 if (VectorCost < Cost) {
5046 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
5047 Factor.Width = Width;
5048 Factor.Cost = Width * Cost;
5052 unsigned LoopVectorizationCostModel::getWidestType() {
5053 unsigned MaxWidth = 8;
5056 for (Loop::block_iterator bb = TheLoop->block_begin(),
5057 be = TheLoop->block_end(); bb != be; ++bb) {
5058 BasicBlock *BB = *bb;
5060 // For each instruction in the loop.
5061 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5062 Type *T = it->getType();
5064 // Only examine Loads, Stores and PHINodes.
5065 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5068 // Examine PHI nodes that are reduction variables.
5069 if (PHINode *PN = dyn_cast<PHINode>(it))
5070 if (!Legal->getReductionVars()->count(PN))
5073 // Examine the stored values.
5074 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5075 T = ST->getValueOperand()->getType();
5077 // Ignore loaded pointer types and stored pointer types that are not
5078 // consecutive. However, we do want to take consecutive stores/loads of
5079 // pointer vectors into account.
5080 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5083 MaxWidth = std::max(MaxWidth,
5084 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5092 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5095 unsigned LoopCost) {
5097 // -- The unroll heuristics --
5098 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5099 // There are many micro-architectural considerations that we can't predict
5100 // at this level. For example frontend pressure (on decode or fetch) due to
5101 // code size, or the number and capabilities of the execution ports.
5103 // We use the following heuristics to select the unroll factor:
5104 // 1. If the code has reductions the we unroll in order to break the cross
5105 // iteration dependency.
5106 // 2. If the loop is really small then we unroll in order to reduce the loop
5108 // 3. We don't unroll if we think that we will spill registers to memory due
5109 // to the increased register pressure.
5111 // Use the user preference, unless 'auto' is selected.
5115 // When we optimize for size we don't unroll.
5119 // We used the distance for the unroll factor.
5120 if (Legal->getMaxSafeDepDistBytes() != -1U)
5123 // Do not unroll loops with a relatively small trip count.
5124 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5125 TheLoop->getLoopLatch());
5126 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5129 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5130 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5134 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5135 TargetNumRegisters = ForceTargetNumScalarRegs;
5137 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5138 TargetNumRegisters = ForceTargetNumVectorRegs;
5141 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5142 // We divide by these constants so assume that we have at least one
5143 // instruction that uses at least one register.
5144 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5145 R.NumInstructions = std::max(R.NumInstructions, 1U);
5147 // We calculate the unroll factor using the following formula.
5148 // Subtract the number of loop invariants from the number of available
5149 // registers. These registers are used by all of the unrolled instances.
5150 // Next, divide the remaining registers by the number of registers that is
5151 // required by the loop, in order to estimate how many parallel instances
5152 // fit without causing spills. All of this is rounded down if necessary to be
5153 // a power of two. We want power of two unroll factors to simplify any
5154 // addressing operations or alignment considerations.
5155 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5158 // Clamp the unroll factor ranges to reasonable factors.
5159 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5161 // Check if the user has overridden the unroll max.
5163 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5164 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5166 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5167 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5170 // If we did not calculate the cost for VF (because the user selected the VF)
5171 // then we calculate the cost of VF here.
5173 LoopCost = expectedCost(VF);
5175 // Clamp the calculated UF to be between the 1 and the max unroll factor
5176 // that the target allows.
5177 if (UF > MaxUnrollSize)
5182 // Unroll if we vectorized this loop and there is a reduction that could
5183 // benefit from unrolling.
5184 if (VF > 1 && Legal->getReductionVars()->size()) {
5185 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5189 if (EnableLoadStoreRuntimeUnroll &&
5190 !Legal->getRuntimePointerCheck()->Need &&
5191 LoopCost < SmallLoopCost) {
5192 // Unroll until store/load ports (estimated by max unroll factor) are
5194 unsigned UnrollStores = UF / (Legal->NumStores ? Legal->NumStores : 1);
5195 unsigned UnrollLoads = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5196 UF = std::max(std::min(UnrollStores, UnrollLoads), 1u);
5200 // We want to unroll tiny loops in order to reduce the loop overhead.
5201 // We assume that the cost overhead is 1 and we use the cost model
5202 // to estimate the cost of the loop and unroll until the cost of the
5203 // loop overhead is about 5% of the cost of the loop.
5204 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5205 if (LoopCost < SmallLoopCost) {
5206 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5207 unsigned NewUF = PowerOf2Floor(SmallLoopCost / LoopCost);
5208 return std::min(NewUF, UF);
5211 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5215 LoopVectorizationCostModel::RegisterUsage
5216 LoopVectorizationCostModel::calculateRegisterUsage() {
5217 // This function calculates the register usage by measuring the highest number
5218 // of values that are alive at a single location. Obviously, this is a very
5219 // rough estimation. We scan the loop in a topological order in order and
5220 // assign a number to each instruction. We use RPO to ensure that defs are
5221 // met before their users. We assume that each instruction that has in-loop
5222 // users starts an interval. We record every time that an in-loop value is
5223 // used, so we have a list of the first and last occurrences of each
5224 // instruction. Next, we transpose this data structure into a multi map that
5225 // holds the list of intervals that *end* at a specific location. This multi
5226 // map allows us to perform a linear search. We scan the instructions linearly
5227 // and record each time that a new interval starts, by placing it in a set.
5228 // If we find this value in the multi-map then we remove it from the set.
5229 // The max register usage is the maximum size of the set.
5230 // We also search for instructions that are defined outside the loop, but are
5231 // used inside the loop. We need this number separately from the max-interval
5232 // usage number because when we unroll, loop-invariant values do not take
5234 LoopBlocksDFS DFS(TheLoop);
5238 R.NumInstructions = 0;
5240 // Each 'key' in the map opens a new interval. The values
5241 // of the map are the index of the 'last seen' usage of the
5242 // instruction that is the key.
5243 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5244 // Maps instruction to its index.
5245 DenseMap<unsigned, Instruction*> IdxToInstr;
5246 // Marks the end of each interval.
5247 IntervalMap EndPoint;
5248 // Saves the list of instruction indices that are used in the loop.
5249 SmallSet<Instruction*, 8> Ends;
5250 // Saves the list of values that are used in the loop but are
5251 // defined outside the loop, such as arguments and constants.
5252 SmallPtrSet<Value*, 8> LoopInvariants;
5255 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5256 be = DFS.endRPO(); bb != be; ++bb) {
5257 R.NumInstructions += (*bb)->size();
5258 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5260 Instruction *I = it;
5261 IdxToInstr[Index++] = I;
5263 // Save the end location of each USE.
5264 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5265 Value *U = I->getOperand(i);
5266 Instruction *Instr = dyn_cast<Instruction>(U);
5268 // Ignore non-instruction values such as arguments, constants, etc.
5269 if (!Instr) continue;
5271 // If this instruction is outside the loop then record it and continue.
5272 if (!TheLoop->contains(Instr)) {
5273 LoopInvariants.insert(Instr);
5277 // Overwrite previous end points.
5278 EndPoint[Instr] = Index;
5284 // Saves the list of intervals that end with the index in 'key'.
5285 typedef SmallVector<Instruction*, 2> InstrList;
5286 DenseMap<unsigned, InstrList> TransposeEnds;
5288 // Transpose the EndPoints to a list of values that end at each index.
5289 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5291 TransposeEnds[it->second].push_back(it->first);
5293 SmallSet<Instruction*, 8> OpenIntervals;
5294 unsigned MaxUsage = 0;
5297 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5298 for (unsigned int i = 0; i < Index; ++i) {
5299 Instruction *I = IdxToInstr[i];
5300 // Ignore instructions that are never used within the loop.
5301 if (!Ends.count(I)) continue;
5303 // Remove all of the instructions that end at this location.
5304 InstrList &List = TransposeEnds[i];
5305 for (unsigned int j=0, e = List.size(); j < e; ++j)
5306 OpenIntervals.erase(List[j]);
5308 // Count the number of live interals.
5309 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5311 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5312 OpenIntervals.size() << '\n');
5314 // Add the current instruction to the list of open intervals.
5315 OpenIntervals.insert(I);
5318 unsigned Invariant = LoopInvariants.size();
5319 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5320 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5321 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5323 R.LoopInvariantRegs = Invariant;
5324 R.MaxLocalUsers = MaxUsage;
5328 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5332 for (Loop::block_iterator bb = TheLoop->block_begin(),
5333 be = TheLoop->block_end(); bb != be; ++bb) {
5334 unsigned BlockCost = 0;
5335 BasicBlock *BB = *bb;
5337 // For each instruction in the old loop.
5338 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5339 // Skip dbg intrinsics.
5340 if (isa<DbgInfoIntrinsic>(it))
5343 unsigned C = getInstructionCost(it, VF);
5345 // Check if we should override the cost.
5346 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5347 C = ForceTargetInstructionCost;
5350 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5351 VF << " For instruction: " << *it << '\n');
5354 // We assume that if-converted blocks have a 50% chance of being executed.
5355 // When the code is scalar then some of the blocks are avoided due to CF.
5356 // When the code is vectorized we execute all code paths.
5357 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5366 /// \brief Check whether the address computation for a non-consecutive memory
5367 /// access looks like an unlikely candidate for being merged into the indexing
5370 /// We look for a GEP which has one index that is an induction variable and all
5371 /// other indices are loop invariant. If the stride of this access is also
5372 /// within a small bound we decide that this address computation can likely be
5373 /// merged into the addressing mode.
5374 /// In all other cases, we identify the address computation as complex.
5375 static bool isLikelyComplexAddressComputation(Value *Ptr,
5376 LoopVectorizationLegality *Legal,
5377 ScalarEvolution *SE,
5378 const Loop *TheLoop) {
5379 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5383 // We are looking for a gep with all loop invariant indices except for one
5384 // which should be an induction variable.
5385 unsigned NumOperands = Gep->getNumOperands();
5386 for (unsigned i = 1; i < NumOperands; ++i) {
5387 Value *Opd = Gep->getOperand(i);
5388 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5389 !Legal->isInductionVariable(Opd))
5393 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5394 // can likely be merged into the address computation.
5395 unsigned MaxMergeDistance = 64;
5397 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5401 // Check the step is constant.
5402 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5403 // Calculate the pointer stride and check if it is consecutive.
5404 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5408 const APInt &APStepVal = C->getValue()->getValue();
5410 // Huge step value - give up.
5411 if (APStepVal.getBitWidth() > 64)
5414 int64_t StepVal = APStepVal.getSExtValue();
5416 return StepVal > MaxMergeDistance;
5419 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5420 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5426 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5427 // If we know that this instruction will remain uniform, check the cost of
5428 // the scalar version.
5429 if (Legal->isUniformAfterVectorization(I))
5432 Type *RetTy = I->getType();
5433 Type *VectorTy = ToVectorTy(RetTy, VF);
5435 // TODO: We need to estimate the cost of intrinsic calls.
5436 switch (I->getOpcode()) {
5437 case Instruction::GetElementPtr:
5438 // We mark this instruction as zero-cost because the cost of GEPs in
5439 // vectorized code depends on whether the corresponding memory instruction
5440 // is scalarized or not. Therefore, we handle GEPs with the memory
5441 // instruction cost.
5443 case Instruction::Br: {
5444 return TTI.getCFInstrCost(I->getOpcode());
5446 case Instruction::PHI:
5447 //TODO: IF-converted IFs become selects.
5449 case Instruction::Add:
5450 case Instruction::FAdd:
5451 case Instruction::Sub:
5452 case Instruction::FSub:
5453 case Instruction::Mul:
5454 case Instruction::FMul:
5455 case Instruction::UDiv:
5456 case Instruction::SDiv:
5457 case Instruction::FDiv:
5458 case Instruction::URem:
5459 case Instruction::SRem:
5460 case Instruction::FRem:
5461 case Instruction::Shl:
5462 case Instruction::LShr:
5463 case Instruction::AShr:
5464 case Instruction::And:
5465 case Instruction::Or:
5466 case Instruction::Xor: {
5467 // Since we will replace the stride by 1 the multiplication should go away.
5468 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5470 // Certain instructions can be cheaper to vectorize if they have a constant
5471 // second vector operand. One example of this are shifts on x86.
5472 TargetTransformInfo::OperandValueKind Op1VK =
5473 TargetTransformInfo::OK_AnyValue;
5474 TargetTransformInfo::OperandValueKind Op2VK =
5475 TargetTransformInfo::OK_AnyValue;
5477 if (isa<ConstantInt>(I->getOperand(1)))
5478 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5480 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5482 case Instruction::Select: {
5483 SelectInst *SI = cast<SelectInst>(I);
5484 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5485 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5486 Type *CondTy = SI->getCondition()->getType();
5488 CondTy = VectorType::get(CondTy, VF);
5490 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5492 case Instruction::ICmp:
5493 case Instruction::FCmp: {
5494 Type *ValTy = I->getOperand(0)->getType();
5495 VectorTy = ToVectorTy(ValTy, VF);
5496 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5498 case Instruction::Store:
5499 case Instruction::Load: {
5500 StoreInst *SI = dyn_cast<StoreInst>(I);
5501 LoadInst *LI = dyn_cast<LoadInst>(I);
5502 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5504 VectorTy = ToVectorTy(ValTy, VF);
5506 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5507 unsigned AS = SI ? SI->getPointerAddressSpace() :
5508 LI->getPointerAddressSpace();
5509 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5510 // We add the cost of address computation here instead of with the gep
5511 // instruction because only here we know whether the operation is
5514 return TTI.getAddressComputationCost(VectorTy) +
5515 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5517 // Scalarized loads/stores.
5518 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5519 bool Reverse = ConsecutiveStride < 0;
5520 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5521 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5522 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5523 bool IsComplexComputation =
5524 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5526 // The cost of extracting from the value vector and pointer vector.
5527 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5528 for (unsigned i = 0; i < VF; ++i) {
5529 // The cost of extracting the pointer operand.
5530 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5531 // In case of STORE, the cost of ExtractElement from the vector.
5532 // In case of LOAD, the cost of InsertElement into the returned
5534 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5535 Instruction::InsertElement,
5539 // The cost of the scalar loads/stores.
5540 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5541 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5546 // Wide load/stores.
5547 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5548 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5551 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5555 case Instruction::ZExt:
5556 case Instruction::SExt:
5557 case Instruction::FPToUI:
5558 case Instruction::FPToSI:
5559 case Instruction::FPExt:
5560 case Instruction::PtrToInt:
5561 case Instruction::IntToPtr:
5562 case Instruction::SIToFP:
5563 case Instruction::UIToFP:
5564 case Instruction::Trunc:
5565 case Instruction::FPTrunc:
5566 case Instruction::BitCast: {
5567 // We optimize the truncation of induction variable.
5568 // The cost of these is the same as the scalar operation.
5569 if (I->getOpcode() == Instruction::Trunc &&
5570 Legal->isInductionVariable(I->getOperand(0)))
5571 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5572 I->getOperand(0)->getType());
5574 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5575 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5577 case Instruction::Call: {
5578 CallInst *CI = cast<CallInst>(I);
5579 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5580 assert(ID && "Not an intrinsic call!");
5581 Type *RetTy = ToVectorTy(CI->getType(), VF);
5582 SmallVector<Type*, 4> Tys;
5583 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5584 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5585 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5588 // We are scalarizing the instruction. Return the cost of the scalar
5589 // instruction, plus the cost of insert and extract into vector
5590 // elements, times the vector width.
5593 if (!RetTy->isVoidTy() && VF != 1) {
5594 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5596 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5599 // The cost of inserting the results plus extracting each one of the
5601 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5604 // The cost of executing VF copies of the scalar instruction. This opcode
5605 // is unknown. Assume that it is the same as 'mul'.
5606 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5612 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5613 if (Scalar->isVoidTy() || VF == 1)
5615 return VectorType::get(Scalar, VF);
5618 char LoopVectorize::ID = 0;
5619 static const char lv_name[] = "Loop Vectorization";
5620 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5621 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5622 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5623 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5624 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5625 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5626 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5627 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5628 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5631 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5632 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5636 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5637 // Check for a store.
5638 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5639 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5641 // Check for a load.
5642 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5643 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5649 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5650 bool IfPredicateStore) {
5651 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5652 // Holds vector parameters or scalars, in case of uniform vals.
5653 SmallVector<VectorParts, 4> Params;
5655 setDebugLocFromInst(Builder, Instr);
5657 // Find all of the vectorized parameters.
5658 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5659 Value *SrcOp = Instr->getOperand(op);
5661 // If we are accessing the old induction variable, use the new one.
5662 if (SrcOp == OldInduction) {
5663 Params.push_back(getVectorValue(SrcOp));
5667 // Try using previously calculated values.
5668 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5670 // If the src is an instruction that appeared earlier in the basic block
5671 // then it should already be vectorized.
5672 if (SrcInst && OrigLoop->contains(SrcInst)) {
5673 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5674 // The parameter is a vector value from earlier.
5675 Params.push_back(WidenMap.get(SrcInst));
5677 // The parameter is a scalar from outside the loop. Maybe even a constant.
5678 VectorParts Scalars;
5679 Scalars.append(UF, SrcOp);
5680 Params.push_back(Scalars);
5684 assert(Params.size() == Instr->getNumOperands() &&
5685 "Invalid number of operands");
5687 // Does this instruction return a value ?
5688 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5690 Value *UndefVec = IsVoidRetTy ? 0 :
5691 UndefValue::get(Instr->getType());
5692 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5693 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5695 Instruction *InsertPt = Builder.GetInsertPoint();
5696 BasicBlock *IfBlock = Builder.GetInsertBlock();
5697 BasicBlock *CondBlock = 0;
5701 if (IfPredicateStore) {
5702 assert(Instr->getParent()->getSinglePredecessor() &&
5703 "Only support single predecessor blocks");
5704 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5705 Instr->getParent());
5706 VectorLp = LI->getLoopFor(IfBlock);
5707 assert(VectorLp && "Must have a loop for this block");
5710 // For each vector unroll 'part':
5711 for (unsigned Part = 0; Part < UF; ++Part) {
5712 // For each scalar that we create:
5714 // Start an "if (pred) a[i] = ..." block.
5716 if (IfPredicateStore) {
5717 if (Cond[Part]->getType()->isVectorTy())
5719 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5720 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5721 ConstantInt::get(Cond[Part]->getType(), 1));
5722 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5723 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
5724 // Update Builder with newly created basic block.
5725 Builder.SetInsertPoint(InsertPt);
5728 Instruction *Cloned = Instr->clone();
5730 Cloned->setName(Instr->getName() + ".cloned");
5731 // Replace the operands of the cloned instructions with extracted scalars.
5732 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5733 Value *Op = Params[op][Part];
5734 Cloned->setOperand(op, Op);
5737 // Place the cloned scalar in the new loop.
5738 Builder.Insert(Cloned);
5740 // If the original scalar returns a value we need to place it in a vector
5741 // so that future users will be able to use it.
5743 VecResults[Part] = Cloned;
5746 if (IfPredicateStore) {
5747 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5748 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
5749 Builder.SetInsertPoint(InsertPt);
5750 Instruction *OldBr = IfBlock->getTerminator();
5751 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5752 OldBr->eraseFromParent();
5753 IfBlock = NewIfBlock;
5758 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5759 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5760 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5762 return scalarizeInstruction(Instr, IfPredicateStore);
5765 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5769 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5773 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5775 // When unrolling and the VF is 1, we only need to add a simple scalar.
5776 Type *ITy = Val->getType();
5777 assert(!ITy->isVectorTy() && "Val must be a scalar");
5778 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5779 return Builder.CreateAdd(Val, C, "induction");