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 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/BlockFrequencyInfo.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
68 #include "llvm/IR/DebugInfo.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.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/PatternMatch.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/Value.h"
81 #include "llvm/IR/ValueHandle.h"
82 #include "llvm/IR/Verifier.h"
83 #include "llvm/Pass.h"
84 #include "llvm/Support/BranchProbability.h"
85 #include "llvm/Support/CommandLine.h"
86 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Scalar.h"
89 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
90 #include "llvm/Transforms/Utils/Local.h"
91 #include "llvm/Transforms/Utils/VectorUtils.h"
97 using namespace llvm::PatternMatch;
99 #define LV_NAME "loop-vectorize"
100 #define DEBUG_TYPE LV_NAME
102 STATISTIC(LoopsVectorized, "Number of loops vectorized");
103 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
105 static cl::opt<unsigned>
106 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
107 cl::desc("Sets the SIMD width. Zero is autoselect."));
109 static cl::opt<unsigned>
110 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
111 cl::desc("Sets the vectorization unroll count. "
112 "Zero is autoselect."));
115 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
116 cl::desc("Enable if-conversion during vectorization."));
118 /// We don't vectorize loops with a known constant trip count below this number.
119 static cl::opt<unsigned>
120 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
122 cl::desc("Don't vectorize loops with a constant "
123 "trip count that is smaller than this "
126 /// This enables versioning on the strides of symbolically striding memory
127 /// accesses in code like the following.
128 /// for (i = 0; i < N; ++i)
129 /// A[i * Stride1] += B[i * Stride2] ...
131 /// Will be roughly translated to
132 /// if (Stride1 == 1 && Stride2 == 1) {
133 /// for (i = 0; i < N; i+=4)
137 static cl::opt<bool> EnableMemAccessVersioning(
138 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
139 cl::desc("Enable symblic stride memory access versioning"));
141 /// We don't unroll loops with a known constant trip count below this number.
142 static const unsigned TinyTripCountUnrollThreshold = 128;
144 /// When performing memory disambiguation checks at runtime do not make more
145 /// than this number of comparisons.
146 static const unsigned RuntimeMemoryCheckThreshold = 8;
148 /// Maximum simd width.
149 static const unsigned MaxVectorWidth = 64;
151 static cl::opt<unsigned> ForceTargetNumScalarRegs(
152 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
153 cl::desc("A flag that overrides the target's number of scalar registers."));
155 static cl::opt<unsigned> ForceTargetNumVectorRegs(
156 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's number of vector registers."));
159 /// Maximum vectorization unroll count.
160 static const unsigned MaxUnrollFactor = 16;
162 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
163 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
164 cl::desc("A flag that overrides the target's max unroll factor for scalar "
167 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
168 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
169 cl::desc("A flag that overrides the target's max unroll factor for "
170 "vectorized loops."));
172 static cl::opt<unsigned> ForceTargetInstructionCost(
173 "force-target-instruction-cost", cl::init(0), cl::Hidden,
174 cl::desc("A flag that overrides the target's expected cost for "
175 "an instruction to a single constant value. Mostly "
176 "useful for getting consistent testing."));
178 static cl::opt<unsigned> SmallLoopCost(
179 "small-loop-cost", cl::init(20), cl::Hidden,
180 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
182 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
183 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
184 cl::desc("Enable the use of the block frequency analysis to access PGO "
185 "heuristics minimizing code growth in cold regions and being more "
186 "aggressive in hot regions."));
188 // Runtime unroll loops for load/store throughput.
189 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
190 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
191 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
193 /// The number of stores in a loop that are allowed to need predication.
194 static cl::opt<unsigned> NumberOfStoresToPredicate(
195 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
196 cl::desc("Max number of stores to be predicated behind an if."));
198 static cl::opt<bool> EnableIndVarRegisterHeur(
199 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
200 cl::desc("Count the induction variable only once when unrolling"));
202 static cl::opt<bool> EnableCondStoresVectorization(
203 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
204 cl::desc("Enable if predication of stores during vectorization."));
208 // Forward declarations.
209 class LoopVectorizationLegality;
210 class LoopVectorizationCostModel;
212 /// InnerLoopVectorizer vectorizes loops which contain only one basic
213 /// block to a specified vectorization factor (VF).
214 /// This class performs the widening of scalars into vectors, or multiple
215 /// scalars. This class also implements the following features:
216 /// * It inserts an epilogue loop for handling loops that don't have iteration
217 /// counts that are known to be a multiple of the vectorization factor.
218 /// * It handles the code generation for reduction variables.
219 /// * Scalarization (implementation using scalars) of un-vectorizable
221 /// InnerLoopVectorizer does not perform any vectorization-legality
222 /// checks, and relies on the caller to check for the different legality
223 /// aspects. The InnerLoopVectorizer relies on the
224 /// LoopVectorizationLegality class to provide information about the induction
225 /// and reduction variables that were found to a given vectorization factor.
226 class InnerLoopVectorizer {
228 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
229 DominatorTree *DT, const DataLayout *DL,
230 const TargetLibraryInfo *TLI, unsigned VecWidth,
231 unsigned UnrollFactor)
232 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
233 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
234 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
237 // Perform the actual loop widening (vectorization).
238 void vectorize(LoopVectorizationLegality *L) {
240 // Create a new empty loop. Unlink the old loop and connect the new one.
242 // Widen each instruction in the old loop to a new one in the new loop.
243 // Use the Legality module to find the induction and reduction variables.
245 // Register the new loop and update the analysis passes.
249 virtual ~InnerLoopVectorizer() {}
252 /// A small list of PHINodes.
253 typedef SmallVector<PHINode*, 4> PhiVector;
254 /// When we unroll loops we have multiple vector values for each scalar.
255 /// This data structure holds the unrolled and vectorized values that
256 /// originated from one scalar instruction.
257 typedef SmallVector<Value*, 2> VectorParts;
259 // When we if-convert we need create edge masks. We have to cache values so
260 // that we don't end up with exponential recursion/IR.
261 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
262 VectorParts> EdgeMaskCache;
264 /// \brief Add code that checks at runtime if the accessed arrays overlap.
266 /// Returns a pair of instructions where the first element is the first
267 /// instruction generated in possibly a sequence of instructions and the
268 /// second value is the final comparator value or NULL if no check is needed.
269 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
271 /// \brief Add checks for strides that where assumed to be 1.
273 /// Returns the last check instruction and the first check instruction in the
274 /// pair as (first, last).
275 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
277 /// Create an empty loop, based on the loop ranges of the old loop.
278 void createEmptyLoop();
279 /// Copy and widen the instructions from the old loop.
280 virtual void vectorizeLoop();
282 /// \brief The Loop exit block may have single value PHI nodes where the
283 /// incoming value is 'Undef'. While vectorizing we only handled real values
284 /// that were defined inside the loop. Here we fix the 'undef case'.
288 /// A helper function that computes the predicate of the block BB, assuming
289 /// that the header block of the loop is set to True. It returns the *entry*
290 /// mask for the block BB.
291 VectorParts createBlockInMask(BasicBlock *BB);
292 /// A helper function that computes the predicate of the edge between SRC
294 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
296 /// A helper function to vectorize a single BB within the innermost loop.
297 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
299 /// Vectorize a single PHINode in a block. This method handles the induction
300 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
301 /// arbitrary length vectors.
302 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
303 unsigned UF, unsigned VF, PhiVector *PV);
305 /// Insert the new loop to the loop hierarchy and pass manager
306 /// and update the analysis passes.
307 void updateAnalysis();
309 /// This instruction is un-vectorizable. Implement it as a sequence
310 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
311 /// scalarized instruction behind an if block predicated on the control
312 /// dependence of the instruction.
313 virtual void scalarizeInstruction(Instruction *Instr,
314 bool IfPredicateStore=false);
316 /// Vectorize Load and Store instructions,
317 virtual void vectorizeMemoryInstruction(Instruction *Instr);
319 /// Create a broadcast instruction. This method generates a broadcast
320 /// instruction (shuffle) for loop invariant values and for the induction
321 /// value. If this is the induction variable then we extend it to N, N+1, ...
322 /// this is needed because each iteration in the loop corresponds to a SIMD
324 virtual Value *getBroadcastInstrs(Value *V);
326 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
327 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
328 /// The sequence starts at StartIndex.
329 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
331 /// When we go over instructions in the basic block we rely on previous
332 /// values within the current basic block or on loop invariant values.
333 /// When we widen (vectorize) values we place them in the map. If the values
334 /// are not within the map, they have to be loop invariant, so we simply
335 /// broadcast them into a vector.
336 VectorParts &getVectorValue(Value *V);
338 /// Generate a shuffle sequence that will reverse the vector Vec.
339 virtual Value *reverseVector(Value *Vec);
341 /// This is a helper class that holds the vectorizer state. It maps scalar
342 /// instructions to vector instructions. When the code is 'unrolled' then
343 /// then a single scalar value is mapped to multiple vector parts. The parts
344 /// are stored in the VectorPart type.
346 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
348 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
350 /// \return True if 'Key' is saved in the Value Map.
351 bool has(Value *Key) const { return MapStorage.count(Key); }
353 /// Initializes a new entry in the map. Sets all of the vector parts to the
354 /// save value in 'Val'.
355 /// \return A reference to a vector with splat values.
356 VectorParts &splat(Value *Key, Value *Val) {
357 VectorParts &Entry = MapStorage[Key];
358 Entry.assign(UF, Val);
362 ///\return A reference to the value that is stored at 'Key'.
363 VectorParts &get(Value *Key) {
364 VectorParts &Entry = MapStorage[Key];
367 assert(Entry.size() == UF);
372 /// The unroll factor. Each entry in the map stores this number of vector
376 /// Map storage. We use std::map and not DenseMap because insertions to a
377 /// dense map invalidates its iterators.
378 std::map<Value *, VectorParts> MapStorage;
381 /// The original loop.
383 /// Scev analysis to use.
390 const DataLayout *DL;
391 /// Target Library Info.
392 const TargetLibraryInfo *TLI;
394 /// The vectorization SIMD factor to use. Each vector will have this many
399 /// The vectorization unroll factor to use. Each scalar is vectorized to this
400 /// many different vector instructions.
403 /// The builder that we use
406 // --- Vectorization state ---
408 /// The vector-loop preheader.
409 BasicBlock *LoopVectorPreHeader;
410 /// The scalar-loop preheader.
411 BasicBlock *LoopScalarPreHeader;
412 /// Middle Block between the vector and the scalar.
413 BasicBlock *LoopMiddleBlock;
414 ///The ExitBlock of the scalar loop.
415 BasicBlock *LoopExitBlock;
416 ///The vector loop body.
417 SmallVector<BasicBlock *, 4> LoopVectorBody;
418 ///The scalar loop body.
419 BasicBlock *LoopScalarBody;
420 /// A list of all bypass blocks. The first block is the entry of the loop.
421 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
423 /// The new Induction variable which was added to the new block.
425 /// The induction variable of the old basic block.
426 PHINode *OldInduction;
427 /// Holds the extended (to the widest induction type) start index.
429 /// Maps scalars to widened vectors.
431 EdgeMaskCache MaskCache;
433 LoopVectorizationLegality *Legal;
436 class InnerLoopUnroller : public InnerLoopVectorizer {
438 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
439 DominatorTree *DT, const DataLayout *DL,
440 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
441 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
444 void scalarizeInstruction(Instruction *Instr,
445 bool IfPredicateStore = false) override;
446 void vectorizeMemoryInstruction(Instruction *Instr) override;
447 Value *getBroadcastInstrs(Value *V) override;
448 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
449 Value *reverseVector(Value *Vec) override;
452 /// \brief Look for a meaningful debug location on the instruction or it's
454 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
459 if (I->getDebugLoc() != Empty)
462 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
463 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
464 if (OpInst->getDebugLoc() != Empty)
471 /// \brief Set the debug location in the builder using the debug location in the
473 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
474 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
475 B.SetCurrentDebugLocation(Inst->getDebugLoc());
477 B.SetCurrentDebugLocation(DebugLoc());
481 /// \return string containing a file name and a line # for the given loop.
482 static std::string getDebugLocString(const Loop *L) {
485 raw_string_ostream OS(Result);
486 const DebugLoc LoopDbgLoc = L->getStartLoc();
487 if (!LoopDbgLoc.isUnknown())
488 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
490 // Just print the module name.
491 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
498 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
499 /// to what vectorization factor.
500 /// This class does not look at the profitability of vectorization, only the
501 /// legality. This class has two main kinds of checks:
502 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
503 /// will change the order of memory accesses in a way that will change the
504 /// correctness of the program.
505 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
506 /// checks for a number of different conditions, such as the availability of a
507 /// single induction variable, that all types are supported and vectorize-able,
508 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
509 /// This class is also used by InnerLoopVectorizer for identifying
510 /// induction variable and the different reduction variables.
511 class LoopVectorizationLegality {
515 unsigned NumPredStores;
517 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
518 DominatorTree *DT, TargetLibraryInfo *TLI)
519 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
520 DT(DT), TLI(TLI), Induction(nullptr), WidestIndTy(nullptr),
521 HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {}
523 /// This enum represents the kinds of reductions that we support.
525 RK_NoReduction, ///< Not a reduction.
526 RK_IntegerAdd, ///< Sum of integers.
527 RK_IntegerMult, ///< Product of integers.
528 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
529 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
530 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
531 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
532 RK_FloatAdd, ///< Sum of floats.
533 RK_FloatMult, ///< Product of floats.
534 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
537 /// This enum represents the kinds of inductions that we support.
539 IK_NoInduction, ///< Not an induction variable.
540 IK_IntInduction, ///< Integer induction variable. Step = 1.
541 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
542 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
543 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
546 // This enum represents the kind of minmax reduction.
547 enum MinMaxReductionKind {
557 /// This struct holds information about reduction variables.
558 struct ReductionDescriptor {
559 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
560 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
562 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
563 MinMaxReductionKind MK)
564 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
566 // The starting value of the reduction.
567 // It does not have to be zero!
568 TrackingVH<Value> StartValue;
569 // The instruction who's value is used outside the loop.
570 Instruction *LoopExitInstr;
571 // The kind of the reduction.
573 // If this a min/max reduction the kind of reduction.
574 MinMaxReductionKind MinMaxKind;
577 /// This POD struct holds information about a potential reduction operation.
578 struct ReductionInstDesc {
579 ReductionInstDesc(bool IsRedux, Instruction *I) :
580 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
582 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
583 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
585 // Is this instruction a reduction candidate.
587 // The last instruction in a min/max pattern (select of the select(icmp())
588 // pattern), or the current reduction instruction otherwise.
589 Instruction *PatternLastInst;
590 // If this is a min/max pattern the comparison predicate.
591 MinMaxReductionKind MinMaxKind;
594 /// This struct holds information about the memory runtime legality
595 /// check that a group of pointers do not overlap.
596 struct RuntimePointerCheck {
597 RuntimePointerCheck() : Need(false) {}
599 /// Reset the state of the pointer runtime information.
606 DependencySetId.clear();
609 /// Insert a pointer and calculate the start and end SCEVs.
610 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
611 unsigned DepSetId, ValueToValueMap &Strides);
613 /// This flag indicates if we need to add the runtime check.
615 /// Holds the pointers that we need to check.
616 SmallVector<TrackingVH<Value>, 2> Pointers;
617 /// Holds the pointer value at the beginning of the loop.
618 SmallVector<const SCEV*, 2> Starts;
619 /// Holds the pointer value at the end of the loop.
620 SmallVector<const SCEV*, 2> Ends;
621 /// Holds the information if this pointer is used for writing to memory.
622 SmallVector<bool, 2> IsWritePtr;
623 /// Holds the id of the set of pointers that could be dependent because of a
624 /// shared underlying object.
625 SmallVector<unsigned, 2> DependencySetId;
628 /// A struct for saving information about induction variables.
629 struct InductionInfo {
630 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
631 InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
633 TrackingVH<Value> StartValue;
638 /// ReductionList contains the reduction descriptors for all
639 /// of the reductions that were found in the loop.
640 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
642 /// InductionList saves induction variables and maps them to the
643 /// induction descriptor.
644 typedef MapVector<PHINode*, InductionInfo> InductionList;
646 /// Returns true if it is legal to vectorize this loop.
647 /// This does not mean that it is profitable to vectorize this
648 /// loop, only that it is legal to do so.
651 /// Returns the Induction variable.
652 PHINode *getInduction() { return Induction; }
654 /// Returns the reduction variables found in the loop.
655 ReductionList *getReductionVars() { return &Reductions; }
657 /// Returns the induction variables found in the loop.
658 InductionList *getInductionVars() { return &Inductions; }
660 /// Returns the widest induction type.
661 Type *getWidestInductionType() { return WidestIndTy; }
663 /// Returns True if V is an induction variable in this loop.
664 bool isInductionVariable(const Value *V);
666 /// Return true if the block BB needs to be predicated in order for the loop
667 /// to be vectorized.
668 bool blockNeedsPredication(BasicBlock *BB);
670 /// Check if this pointer is consecutive when vectorizing. This happens
671 /// when the last index of the GEP is the induction variable, or that the
672 /// pointer itself is an induction variable.
673 /// This check allows us to vectorize A[idx] into a wide load/store.
675 /// 0 - Stride is unknown or non-consecutive.
676 /// 1 - Address is consecutive.
677 /// -1 - Address is consecutive, and decreasing.
678 int isConsecutivePtr(Value *Ptr);
680 /// Returns true if the value V is uniform within the loop.
681 bool isUniform(Value *V);
683 /// Returns true if this instruction will remain scalar after vectorization.
684 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
686 /// Returns the information that we collected about runtime memory check.
687 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
689 /// This function returns the identity element (or neutral element) for
691 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
693 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
695 bool hasStride(Value *V) { return StrideSet.count(V); }
696 bool mustCheckStrides() { return !StrideSet.empty(); }
697 SmallPtrSet<Value *, 8>::iterator strides_begin() {
698 return StrideSet.begin();
700 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
703 /// Check if a single basic block loop is vectorizable.
704 /// At this point we know that this is a loop with a constant trip count
705 /// and we only need to check individual instructions.
706 bool canVectorizeInstrs();
708 /// When we vectorize loops we may change the order in which
709 /// we read and write from memory. This method checks if it is
710 /// legal to vectorize the code, considering only memory constrains.
711 /// Returns true if the loop is vectorizable
712 bool canVectorizeMemory();
714 /// Return true if we can vectorize this loop using the IF-conversion
716 bool canVectorizeWithIfConvert();
718 /// Collect the variables that need to stay uniform after vectorization.
719 void collectLoopUniforms();
721 /// Return true if all of the instructions in the block can be speculatively
722 /// executed. \p SafePtrs is a list of addresses that are known to be legal
723 /// and we know that we can read from them without segfault.
724 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
726 /// Returns True, if 'Phi' is the kind of reduction variable for type
727 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
728 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
729 /// Returns a struct describing if the instruction 'I' can be a reduction
730 /// variable of type 'Kind'. If the reduction is a min/max pattern of
731 /// select(icmp()) this function advances the instruction pointer 'I' from the
732 /// compare instruction to the select instruction and stores this pointer in
733 /// 'PatternLastInst' member of the returned struct.
734 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
735 ReductionInstDesc &Desc);
736 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
737 /// pattern corresponding to a min(X, Y) or max(X, Y).
738 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
739 ReductionInstDesc &Prev);
740 /// Returns the induction kind of Phi. This function may return NoInduction
741 /// if the PHI is not an induction variable.
742 InductionKind isInductionVariable(PHINode *Phi);
744 /// \brief Collect memory access with loop invariant strides.
746 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
748 void collectStridedAcccess(Value *LoadOrStoreInst);
750 /// The loop that we evaluate.
754 /// DataLayout analysis.
755 const DataLayout *DL;
758 /// Target Library Info.
759 TargetLibraryInfo *TLI;
761 // --- vectorization state --- //
763 /// Holds the integer induction variable. This is the counter of the
766 /// Holds the reduction variables.
767 ReductionList Reductions;
768 /// Holds all of the induction variables that we found in the loop.
769 /// Notice that inductions don't need to start at zero and that induction
770 /// variables can be pointers.
771 InductionList Inductions;
772 /// Holds the widest induction type encountered.
775 /// Allowed outside users. This holds the reduction
776 /// vars which can be accessed from outside the loop.
777 SmallPtrSet<Value*, 4> AllowedExit;
778 /// This set holds the variables which are known to be uniform after
780 SmallPtrSet<Instruction*, 4> Uniforms;
781 /// We need to check that all of the pointers in this list are disjoint
783 RuntimePointerCheck PtrRtCheck;
784 /// Can we assume the absence of NaNs.
785 bool HasFunNoNaNAttr;
787 unsigned MaxSafeDepDistBytes;
789 ValueToValueMap Strides;
790 SmallPtrSet<Value *, 8> StrideSet;
793 /// LoopVectorizationCostModel - estimates the expected speedups due to
795 /// In many cases vectorization is not profitable. This can happen because of
796 /// a number of reasons. In this class we mainly attempt to predict the
797 /// expected speedup/slowdowns due to the supported instruction set. We use the
798 /// TargetTransformInfo to query the different backends for the cost of
799 /// different operations.
800 class LoopVectorizationCostModel {
802 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
803 LoopVectorizationLegality *Legal,
804 const TargetTransformInfo &TTI,
805 const DataLayout *DL, const TargetLibraryInfo *TLI)
806 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
808 /// Information about vectorization costs
809 struct VectorizationFactor {
810 unsigned Width; // Vector width with best cost
811 unsigned Cost; // Cost of the loop with that width
813 /// \return The most profitable vectorization factor and the cost of that VF.
814 /// This method checks every power of two up to VF. If UserVF is not ZERO
815 /// then this vectorization factor will be selected if vectorization is
817 VectorizationFactor selectVectorizationFactor(bool OptForSize,
819 bool ForceVectorization);
821 /// \return The size (in bits) of the widest type in the code that
822 /// needs to be vectorized. We ignore values that remain scalar such as
823 /// 64 bit loop indices.
824 unsigned getWidestType();
826 /// \return The most profitable unroll factor.
827 /// If UserUF is non-zero then this method finds the best unroll-factor
828 /// based on register pressure and other parameters.
829 /// VF and LoopCost are the selected vectorization factor and the cost of the
831 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
834 /// \brief A struct that represents some properties of the register usage
836 struct RegisterUsage {
837 /// Holds the number of loop invariant values that are used in the loop.
838 unsigned LoopInvariantRegs;
839 /// Holds the maximum number of concurrent live intervals in the loop.
840 unsigned MaxLocalUsers;
841 /// Holds the number of instructions in the loop.
842 unsigned NumInstructions;
845 /// \return information about the register usage of the loop.
846 RegisterUsage calculateRegisterUsage();
849 /// Returns the expected execution cost. The unit of the cost does
850 /// not matter because we use the 'cost' units to compare different
851 /// vector widths. The cost that is returned is *not* normalized by
852 /// the factor width.
853 unsigned expectedCost(unsigned VF);
855 /// Returns the execution time cost of an instruction for a given vector
856 /// width. Vector width of one means scalar.
857 unsigned getInstructionCost(Instruction *I, unsigned VF);
859 /// A helper function for converting Scalar types to vector types.
860 /// If the incoming type is void, we return void. If the VF is 1, we return
862 static Type* ToVectorTy(Type *Scalar, unsigned VF);
864 /// Returns whether the instruction is a load or store and will be a emitted
865 /// as a vector operation.
866 bool isConsecutiveLoadOrStore(Instruction *I);
868 /// The loop that we evaluate.
872 /// Loop Info analysis.
874 /// Vectorization legality.
875 LoopVectorizationLegality *Legal;
876 /// Vector target information.
877 const TargetTransformInfo &TTI;
878 /// Target data layout information.
879 const DataLayout *DL;
880 /// Target Library Info.
881 const TargetLibraryInfo *TLI;
884 /// Utility class for getting and setting loop vectorizer hints in the form
885 /// of loop metadata.
886 class LoopVectorizeHints {
889 FK_Undefined = -1, ///< Not selected.
890 FK_Disabled = 0, ///< Forcing disabled.
891 FK_Enabled = 1, ///< Forcing enabled.
894 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
895 : Width(VectorizationFactor),
896 Unroll(DisableUnrolling),
898 LoopID(L->getLoopID()) {
900 // force-vector-unroll overrides DisableUnrolling.
901 if (VectorizationUnroll.getNumOccurrences() > 0)
902 Unroll = VectorizationUnroll;
904 DEBUG(if (DisableUnrolling && Unroll == 1) dbgs()
905 << "LV: Unrolling disabled by the pass manager\n");
908 /// Return the loop vectorizer metadata prefix.
909 static StringRef Prefix() { return "llvm.vectorizer."; }
911 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) const {
912 SmallVector<Value*, 2> Vals;
913 Vals.push_back(MDString::get(Context, Name));
914 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
915 return MDNode::get(Context, Vals);
918 /// Mark the loop L as already vectorized by setting the width to 1.
919 void setAlreadyVectorized(Loop *L) {
920 LLVMContext &Context = L->getHeader()->getContext();
924 // Create a new loop id with one more operand for the already_vectorized
925 // hint. If the loop already has a loop id then copy the existing operands.
926 SmallVector<Value*, 4> Vals(1);
928 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
929 Vals.push_back(LoopID->getOperand(i));
931 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
932 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
934 MDNode *NewLoopID = MDNode::get(Context, Vals);
935 // Set operand 0 to refer to the loop id itself.
936 NewLoopID->replaceOperandWith(0, NewLoopID);
938 L->setLoopID(NewLoopID);
940 LoopID->replaceAllUsesWith(NewLoopID);
945 unsigned getWidth() const { return Width; }
946 unsigned getUnroll() const { return Unroll; }
947 enum ForceKind getForce() const { return Force; }
948 MDNode *getLoopID() const { return LoopID; }
951 /// Find hints specified in the loop metadata.
952 void getHints(const Loop *L) {
956 // First operand should refer to the loop id itself.
957 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
958 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
960 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
961 const MDString *S = nullptr;
962 SmallVector<Value*, 4> Args;
964 // The expected hint is either a MDString or a MDNode with the first
965 // operand a MDString.
966 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
967 if (!MD || MD->getNumOperands() == 0)
969 S = dyn_cast<MDString>(MD->getOperand(0));
970 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
971 Args.push_back(MD->getOperand(i));
973 S = dyn_cast<MDString>(LoopID->getOperand(i));
974 assert(Args.size() == 0 && "too many arguments for MDString");
980 // Check if the hint starts with the vectorizer prefix.
981 StringRef Hint = S->getString();
982 if (!Hint.startswith(Prefix()))
984 // Remove the prefix.
985 Hint = Hint.substr(Prefix().size(), StringRef::npos);
987 if (Args.size() == 1)
988 getHint(Hint, Args[0]);
992 // Check string hint with one operand.
993 void getHint(StringRef Hint, Value *Arg) {
994 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
996 unsigned Val = C->getZExtValue();
998 if (Hint == "width") {
999 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
1002 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
1003 } else if (Hint == "unroll") {
1004 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
1007 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
1008 } else if (Hint == "enable") {
1009 if (C->getBitWidth() == 1)
1010 Force = Val == 1 ? LoopVectorizeHints::FK_Enabled
1011 : LoopVectorizeHints::FK_Disabled;
1013 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
1015 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
1019 /// Vectorization width.
1021 /// Vectorization unroll factor.
1023 /// Vectorization forced
1024 enum ForceKind Force;
1029 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1031 return V.push_back(&L);
1033 for (Loop *InnerL : L)
1034 addInnerLoop(*InnerL, V);
1037 /// The LoopVectorize Pass.
1038 struct LoopVectorize : public FunctionPass {
1039 /// Pass identification, replacement for typeid
1042 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1044 DisableUnrolling(NoUnrolling),
1045 AlwaysVectorize(AlwaysVectorize) {
1046 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1049 ScalarEvolution *SE;
1050 const DataLayout *DL;
1052 TargetTransformInfo *TTI;
1054 BlockFrequencyInfo *BFI;
1055 TargetLibraryInfo *TLI;
1056 bool DisableUnrolling;
1057 bool AlwaysVectorize;
1059 BlockFrequency ColdEntryFreq;
1061 bool runOnFunction(Function &F) override {
1062 SE = &getAnalysis<ScalarEvolution>();
1063 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1064 DL = DLP ? &DLP->getDataLayout() : nullptr;
1065 LI = &getAnalysis<LoopInfo>();
1066 TTI = &getAnalysis<TargetTransformInfo>();
1067 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1068 BFI = &getAnalysis<BlockFrequencyInfo>();
1069 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1071 // Compute some weights outside of the loop over the loops. Compute this
1072 // using a BranchProbability to re-use its scaling math.
1073 const BranchProbability ColdProb(1, 5); // 20%
1074 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1076 // If the target claims to have no vector registers don't attempt
1078 if (!TTI->getNumberOfRegisters(true))
1082 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1083 << ": Missing data layout\n");
1087 // Build up a worklist of inner-loops to vectorize. This is necessary as
1088 // the act of vectorizing or partially unrolling a loop creates new loops
1089 // and can invalidate iterators across the loops.
1090 SmallVector<Loop *, 8> Worklist;
1093 addInnerLoop(*L, Worklist);
1095 LoopsAnalyzed += Worklist.size();
1097 // Now walk the identified inner loops.
1098 bool Changed = false;
1099 while (!Worklist.empty())
1100 Changed |= processLoop(Worklist.pop_back_val());
1102 // Process each loop nest in the function.
1106 bool processLoop(Loop *L) {
1107 assert(L->empty() && "Only process inner loops.");
1110 const std::string DebugLocStr = getDebugLocString(L);
1113 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1114 << L->getHeader()->getParent()->getName() << "\" from "
1115 << DebugLocStr << "\n");
1117 LoopVectorizeHints Hints(L, DisableUnrolling);
1119 DEBUG(dbgs() << "LV: Loop hints:"
1121 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1123 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1125 : "?")) << " width=" << Hints.getWidth()
1126 << " unroll=" << Hints.getUnroll() << "\n");
1128 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1129 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1133 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1134 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1138 if (Hints.getWidth() == 1 && Hints.getUnroll() == 1) {
1139 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1143 // Check the loop for a trip count threshold:
1144 // do not vectorize loops with a tiny trip count.
1145 BasicBlock *Latch = L->getLoopLatch();
1146 const unsigned TC = SE->getSmallConstantTripCount(L, Latch);
1147 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1148 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1149 << "This loop is not worth vectorizing.");
1150 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1151 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1153 DEBUG(dbgs() << "\n");
1158 // Check if it is legal to vectorize the loop.
1159 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1160 if (!LVL.canVectorize()) {
1161 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1165 // Use the cost model.
1166 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1168 // Check the function attributes to find out if this function should be
1169 // optimized for size.
1170 Function *F = L->getHeader()->getParent();
1171 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1172 F->hasFnAttribute(Attribute::OptimizeForSize);
1174 // Compute the weighted frequency of this loop being executed and see if it
1175 // is less than 20% of the function entry baseline frequency. Note that we
1176 // always have a canonical loop here because we think we *can* vectoriez.
1177 // FIXME: This is hidden behind a flag due to pervasive problems with
1178 // exactly what block frequency models.
1179 if (LoopVectorizeWithBlockFrequency) {
1180 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1181 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1182 LoopEntryFreq < ColdEntryFreq)
1186 // Check the function attributes to see if implicit floats are allowed.a
1187 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1188 // an integer loop and the vector instructions selected are purely integer
1189 // vector instructions?
1190 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1191 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1192 "attribute is used.\n");
1196 // Select the optimal vectorization factor.
1197 const LoopVectorizationCostModel::VectorizationFactor VF =
1198 CM.selectVectorizationFactor(OptForSize, Hints.getWidth(),
1200 LoopVectorizeHints::FK_Enabled);
1202 // Select the unroll factor.
1204 CM.selectUnrollFactor(OptForSize, Hints.getUnroll(), VF.Width, VF.Cost);
1206 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1207 << DebugLocStr << '\n');
1208 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1210 if (VF.Width == 1) {
1211 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1214 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1216 // Report the unrolling decision.
1217 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1218 Twine("unrolled with interleaving factor " +
1220 " (vectorization not beneficial)"));
1222 // We decided not to vectorize, but we may want to unroll.
1223 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1224 Unroller.vectorize(&LVL);
1226 // If we decided that it is *legal* to vectorize the loop then do it.
1227 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1231 // Report the vectorization decision.
1232 emitOptimizationRemark(
1233 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1234 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1235 ", unrolling interleave factor: " + Twine(UF) + ")");
1238 // Mark the loop as already vectorized to avoid vectorizing again.
1239 Hints.setAlreadyVectorized(L);
1241 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1245 void getAnalysisUsage(AnalysisUsage &AU) const override {
1246 AU.addRequiredID(LoopSimplifyID);
1247 AU.addRequiredID(LCSSAID);
1248 AU.addRequired<BlockFrequencyInfo>();
1249 AU.addRequired<DominatorTreeWrapperPass>();
1250 AU.addRequired<LoopInfo>();
1251 AU.addRequired<ScalarEvolution>();
1252 AU.addRequired<TargetTransformInfo>();
1253 AU.addPreserved<LoopInfo>();
1254 AU.addPreserved<DominatorTreeWrapperPass>();
1259 } // end anonymous namespace
1261 //===----------------------------------------------------------------------===//
1262 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1263 // LoopVectorizationCostModel.
1264 //===----------------------------------------------------------------------===//
1266 static Value *stripIntegerCast(Value *V) {
1267 if (CastInst *CI = dyn_cast<CastInst>(V))
1268 if (CI->getOperand(0)->getType()->isIntegerTy())
1269 return CI->getOperand(0);
1273 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1275 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1277 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1278 ValueToValueMap &PtrToStride,
1279 Value *Ptr, Value *OrigPtr = nullptr) {
1281 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1283 // If there is an entry in the map return the SCEV of the pointer with the
1284 // symbolic stride replaced by one.
1285 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1286 if (SI != PtrToStride.end()) {
1287 Value *StrideVal = SI->second;
1290 StrideVal = stripIntegerCast(StrideVal);
1292 // Replace symbolic stride by one.
1293 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1294 ValueToValueMap RewriteMap;
1295 RewriteMap[StrideVal] = One;
1298 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1299 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1304 // Otherwise, just return the SCEV of the original pointer.
1305 return SE->getSCEV(Ptr);
1308 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1309 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1310 ValueToValueMap &Strides) {
1311 // Get the stride replaced scev.
1312 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1313 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1314 assert(AR && "Invalid addrec expression");
1315 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1316 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1317 Pointers.push_back(Ptr);
1318 Starts.push_back(AR->getStart());
1319 Ends.push_back(ScEnd);
1320 IsWritePtr.push_back(WritePtr);
1321 DependencySetId.push_back(DepSetId);
1324 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1325 // We need to place the broadcast of invariant variables outside the loop.
1326 Instruction *Instr = dyn_cast<Instruction>(V);
1328 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1329 Instr->getParent()) != LoopVectorBody.end());
1330 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1332 // Place the code for broadcasting invariant variables in the new preheader.
1333 IRBuilder<>::InsertPointGuard Guard(Builder);
1335 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1337 // Broadcast the scalar into all locations in the vector.
1338 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1343 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1345 assert(Val->getType()->isVectorTy() && "Must be a vector");
1346 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1347 "Elem must be an integer");
1348 // Create the types.
1349 Type *ITy = Val->getType()->getScalarType();
1350 VectorType *Ty = cast<VectorType>(Val->getType());
1351 int VLen = Ty->getNumElements();
1352 SmallVector<Constant*, 8> Indices;
1354 // Create a vector of consecutive numbers from zero to VF.
1355 for (int i = 0; i < VLen; ++i) {
1356 int64_t Idx = Negate ? (-i) : i;
1357 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1360 // Add the consecutive indices to the vector value.
1361 Constant *Cv = ConstantVector::get(Indices);
1362 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1363 return Builder.CreateAdd(Val, Cv, "induction");
1366 /// \brief Find the operand of the GEP that should be checked for consecutive
1367 /// stores. This ignores trailing indices that have no effect on the final
1369 static unsigned getGEPInductionOperand(const DataLayout *DL,
1370 const GetElementPtrInst *Gep) {
1371 unsigned LastOperand = Gep->getNumOperands() - 1;
1372 unsigned GEPAllocSize = DL->getTypeAllocSize(
1373 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1375 // Walk backwards and try to peel off zeros.
1376 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1377 // Find the type we're currently indexing into.
1378 gep_type_iterator GEPTI = gep_type_begin(Gep);
1379 std::advance(GEPTI, LastOperand - 1);
1381 // If it's a type with the same allocation size as the result of the GEP we
1382 // can peel off the zero index.
1383 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1391 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1392 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1393 // Make sure that the pointer does not point to structs.
1394 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1397 // If this value is a pointer induction variable we know it is consecutive.
1398 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1399 if (Phi && Inductions.count(Phi)) {
1400 InductionInfo II = Inductions[Phi];
1401 if (IK_PtrInduction == II.IK)
1403 else if (IK_ReversePtrInduction == II.IK)
1407 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1411 unsigned NumOperands = Gep->getNumOperands();
1412 Value *GpPtr = Gep->getPointerOperand();
1413 // If this GEP value is a consecutive pointer induction variable and all of
1414 // the indices are constant then we know it is consecutive. We can
1415 Phi = dyn_cast<PHINode>(GpPtr);
1416 if (Phi && Inductions.count(Phi)) {
1418 // Make sure that the pointer does not point to structs.
1419 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1420 if (GepPtrType->getElementType()->isAggregateType())
1423 // Make sure that all of the index operands are loop invariant.
1424 for (unsigned i = 1; i < NumOperands; ++i)
1425 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1428 InductionInfo II = Inductions[Phi];
1429 if (IK_PtrInduction == II.IK)
1431 else if (IK_ReversePtrInduction == II.IK)
1435 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1437 // Check that all of the gep indices are uniform except for our induction
1439 for (unsigned i = 0; i != NumOperands; ++i)
1440 if (i != InductionOperand &&
1441 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1444 // We can emit wide load/stores only if the last non-zero index is the
1445 // induction variable.
1446 const SCEV *Last = nullptr;
1447 if (!Strides.count(Gep))
1448 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1450 // Because of the multiplication by a stride we can have a s/zext cast.
1451 // We are going to replace this stride by 1 so the cast is safe to ignore.
1453 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1454 // %0 = trunc i64 %indvars.iv to i32
1455 // %mul = mul i32 %0, %Stride1
1456 // %idxprom = zext i32 %mul to i64 << Safe cast.
1457 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1459 Last = replaceSymbolicStrideSCEV(SE, Strides,
1460 Gep->getOperand(InductionOperand), Gep);
1461 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1463 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1467 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1468 const SCEV *Step = AR->getStepRecurrence(*SE);
1470 // The memory is consecutive because the last index is consecutive
1471 // and all other indices are loop invariant.
1474 if (Step->isAllOnesValue())
1481 bool LoopVectorizationLegality::isUniform(Value *V) {
1482 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1485 InnerLoopVectorizer::VectorParts&
1486 InnerLoopVectorizer::getVectorValue(Value *V) {
1487 assert(V != Induction && "The new induction variable should not be used.");
1488 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1490 // If we have a stride that is replaced by one, do it here.
1491 if (Legal->hasStride(V))
1492 V = ConstantInt::get(V->getType(), 1);
1494 // If we have this scalar in the map, return it.
1495 if (WidenMap.has(V))
1496 return WidenMap.get(V);
1498 // If this scalar is unknown, assume that it is a constant or that it is
1499 // loop invariant. Broadcast V and save the value for future uses.
1500 Value *B = getBroadcastInstrs(V);
1501 return WidenMap.splat(V, B);
1504 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1505 assert(Vec->getType()->isVectorTy() && "Invalid type");
1506 SmallVector<Constant*, 8> ShuffleMask;
1507 for (unsigned i = 0; i < VF; ++i)
1508 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1510 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1511 ConstantVector::get(ShuffleMask),
1515 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1516 // Attempt to issue a wide load.
1517 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1518 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1520 assert((LI || SI) && "Invalid Load/Store instruction");
1522 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1523 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1524 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1525 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1526 // An alignment of 0 means target abi alignment. We need to use the scalar's
1527 // target abi alignment in such a case.
1529 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1530 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1531 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1532 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1534 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1535 return scalarizeInstruction(Instr, true);
1537 if (ScalarAllocatedSize != VectorElementSize)
1538 return scalarizeInstruction(Instr);
1540 // If the pointer is loop invariant or if it is non-consecutive,
1541 // scalarize the load.
1542 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1543 bool Reverse = ConsecutiveStride < 0;
1544 bool UniformLoad = LI && Legal->isUniform(Ptr);
1545 if (!ConsecutiveStride || UniformLoad)
1546 return scalarizeInstruction(Instr);
1548 Constant *Zero = Builder.getInt32(0);
1549 VectorParts &Entry = WidenMap.get(Instr);
1551 // Handle consecutive loads/stores.
1552 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1553 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1554 setDebugLocFromInst(Builder, Gep);
1555 Value *PtrOperand = Gep->getPointerOperand();
1556 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1557 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1559 // Create the new GEP with the new induction variable.
1560 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1561 Gep2->setOperand(0, FirstBasePtr);
1562 Gep2->setName("gep.indvar.base");
1563 Ptr = Builder.Insert(Gep2);
1565 setDebugLocFromInst(Builder, Gep);
1566 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1567 OrigLoop) && "Base ptr must be invariant");
1569 // The last index does not have to be the induction. It can be
1570 // consecutive and be a function of the index. For example A[I+1];
1571 unsigned NumOperands = Gep->getNumOperands();
1572 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1573 // Create the new GEP with the new induction variable.
1574 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1576 for (unsigned i = 0; i < NumOperands; ++i) {
1577 Value *GepOperand = Gep->getOperand(i);
1578 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1580 // Update last index or loop invariant instruction anchored in loop.
1581 if (i == InductionOperand ||
1582 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1583 assert((i == InductionOperand ||
1584 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1585 "Must be last index or loop invariant");
1587 VectorParts &GEPParts = getVectorValue(GepOperand);
1588 Value *Index = GEPParts[0];
1589 Index = Builder.CreateExtractElement(Index, Zero);
1590 Gep2->setOperand(i, Index);
1591 Gep2->setName("gep.indvar.idx");
1594 Ptr = Builder.Insert(Gep2);
1596 // Use the induction element ptr.
1597 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1598 setDebugLocFromInst(Builder, Ptr);
1599 VectorParts &PtrVal = getVectorValue(Ptr);
1600 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1605 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1606 "We do not allow storing to uniform addresses");
1607 setDebugLocFromInst(Builder, SI);
1608 // We don't want to update the value in the map as it might be used in
1609 // another expression. So don't use a reference type for "StoredVal".
1610 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1612 for (unsigned Part = 0; Part < UF; ++Part) {
1613 // Calculate the pointer for the specific unroll-part.
1614 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1617 // If we store to reverse consecutive memory locations then we need
1618 // to reverse the order of elements in the stored value.
1619 StoredVal[Part] = reverseVector(StoredVal[Part]);
1620 // If the address is consecutive but reversed, then the
1621 // wide store needs to start at the last vector element.
1622 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1623 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1626 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1627 DataTy->getPointerTo(AddressSpace));
1628 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1634 assert(LI && "Must have a load instruction");
1635 setDebugLocFromInst(Builder, LI);
1636 for (unsigned Part = 0; Part < UF; ++Part) {
1637 // Calculate the pointer for the specific unroll-part.
1638 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1641 // If the address is consecutive but reversed, then the
1642 // wide store needs to start at the last vector element.
1643 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1644 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1647 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1648 DataTy->getPointerTo(AddressSpace));
1649 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1650 cast<LoadInst>(LI)->setAlignment(Alignment);
1651 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1655 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1656 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1657 // Holds vector parameters or scalars, in case of uniform vals.
1658 SmallVector<VectorParts, 4> Params;
1660 setDebugLocFromInst(Builder, Instr);
1662 // Find all of the vectorized parameters.
1663 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1664 Value *SrcOp = Instr->getOperand(op);
1666 // If we are accessing the old induction variable, use the new one.
1667 if (SrcOp == OldInduction) {
1668 Params.push_back(getVectorValue(SrcOp));
1672 // Try using previously calculated values.
1673 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1675 // If the src is an instruction that appeared earlier in the basic block
1676 // then it should already be vectorized.
1677 if (SrcInst && OrigLoop->contains(SrcInst)) {
1678 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1679 // The parameter is a vector value from earlier.
1680 Params.push_back(WidenMap.get(SrcInst));
1682 // The parameter is a scalar from outside the loop. Maybe even a constant.
1683 VectorParts Scalars;
1684 Scalars.append(UF, SrcOp);
1685 Params.push_back(Scalars);
1689 assert(Params.size() == Instr->getNumOperands() &&
1690 "Invalid number of operands");
1692 // Does this instruction return a value ?
1693 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1695 Value *UndefVec = IsVoidRetTy ? nullptr :
1696 UndefValue::get(VectorType::get(Instr->getType(), VF));
1697 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1698 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1700 Instruction *InsertPt = Builder.GetInsertPoint();
1701 BasicBlock *IfBlock = Builder.GetInsertBlock();
1702 BasicBlock *CondBlock = nullptr;
1705 Loop *VectorLp = nullptr;
1706 if (IfPredicateStore) {
1707 assert(Instr->getParent()->getSinglePredecessor() &&
1708 "Only support single predecessor blocks");
1709 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1710 Instr->getParent());
1711 VectorLp = LI->getLoopFor(IfBlock);
1712 assert(VectorLp && "Must have a loop for this block");
1715 // For each vector unroll 'part':
1716 for (unsigned Part = 0; Part < UF; ++Part) {
1717 // For each scalar that we create:
1718 for (unsigned Width = 0; Width < VF; ++Width) {
1721 Value *Cmp = nullptr;
1722 if (IfPredicateStore) {
1723 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1724 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1725 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1726 LoopVectorBody.push_back(CondBlock);
1727 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1728 // Update Builder with newly created basic block.
1729 Builder.SetInsertPoint(InsertPt);
1732 Instruction *Cloned = Instr->clone();
1734 Cloned->setName(Instr->getName() + ".cloned");
1735 // Replace the operands of the cloned instructions with extracted scalars.
1736 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1737 Value *Op = Params[op][Part];
1738 // Param is a vector. Need to extract the right lane.
1739 if (Op->getType()->isVectorTy())
1740 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1741 Cloned->setOperand(op, Op);
1744 // Place the cloned scalar in the new loop.
1745 Builder.Insert(Cloned);
1747 // If the original scalar returns a value we need to place it in a vector
1748 // so that future users will be able to use it.
1750 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1751 Builder.getInt32(Width));
1753 if (IfPredicateStore) {
1754 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1755 LoopVectorBody.push_back(NewIfBlock);
1756 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1757 Builder.SetInsertPoint(InsertPt);
1758 Instruction *OldBr = IfBlock->getTerminator();
1759 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1760 OldBr->eraseFromParent();
1761 IfBlock = NewIfBlock;
1767 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1771 if (Instruction *I = dyn_cast<Instruction>(V))
1772 return I->getParent() == Loc->getParent() ? I : nullptr;
1776 std::pair<Instruction *, Instruction *>
1777 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1778 Instruction *tnullptr = nullptr;
1779 if (!Legal->mustCheckStrides())
1780 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1782 IRBuilder<> ChkBuilder(Loc);
1785 Value *Check = nullptr;
1786 Instruction *FirstInst = nullptr;
1787 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1788 SE = Legal->strides_end();
1790 Value *Ptr = stripIntegerCast(*SI);
1791 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1793 // Store the first instruction we create.
1794 FirstInst = getFirstInst(FirstInst, C, Loc);
1796 Check = ChkBuilder.CreateOr(Check, C);
1801 // We have to do this trickery because the IRBuilder might fold the check to a
1802 // constant expression in which case there is no Instruction anchored in a
1804 LLVMContext &Ctx = Loc->getContext();
1805 Instruction *TheCheck =
1806 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1807 ChkBuilder.Insert(TheCheck, "stride.not.one");
1808 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1810 return std::make_pair(FirstInst, TheCheck);
1813 std::pair<Instruction *, Instruction *>
1814 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1815 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1816 Legal->getRuntimePointerCheck();
1818 Instruction *tnullptr = nullptr;
1819 if (!PtrRtCheck->Need)
1820 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1822 unsigned NumPointers = PtrRtCheck->Pointers.size();
1823 SmallVector<TrackingVH<Value> , 2> Starts;
1824 SmallVector<TrackingVH<Value> , 2> Ends;
1826 LLVMContext &Ctx = Loc->getContext();
1827 SCEVExpander Exp(*SE, "induction");
1828 Instruction *FirstInst = nullptr;
1830 for (unsigned i = 0; i < NumPointers; ++i) {
1831 Value *Ptr = PtrRtCheck->Pointers[i];
1832 const SCEV *Sc = SE->getSCEV(Ptr);
1834 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1835 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1837 Starts.push_back(Ptr);
1838 Ends.push_back(Ptr);
1840 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1841 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1843 // Use this type for pointer arithmetic.
1844 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1846 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1847 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1848 Starts.push_back(Start);
1849 Ends.push_back(End);
1853 IRBuilder<> ChkBuilder(Loc);
1854 // Our instructions might fold to a constant.
1855 Value *MemoryRuntimeCheck = nullptr;
1856 for (unsigned i = 0; i < NumPointers; ++i) {
1857 for (unsigned j = i+1; j < NumPointers; ++j) {
1858 // No need to check if two readonly pointers intersect.
1859 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1862 // Only need to check pointers between two different dependency sets.
1863 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1866 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1867 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1869 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1870 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1871 "Trying to bounds check pointers with different address spaces");
1873 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1874 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1876 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1877 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1878 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1879 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1881 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1882 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1883 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1884 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1885 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1886 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1887 if (MemoryRuntimeCheck) {
1888 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1890 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1892 MemoryRuntimeCheck = IsConflict;
1896 // We have to do this trickery because the IRBuilder might fold the check to a
1897 // constant expression in which case there is no Instruction anchored in a
1899 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1900 ConstantInt::getTrue(Ctx));
1901 ChkBuilder.Insert(Check, "memcheck.conflict");
1902 FirstInst = getFirstInst(FirstInst, Check, Loc);
1903 return std::make_pair(FirstInst, Check);
1906 void InnerLoopVectorizer::createEmptyLoop() {
1908 In this function we generate a new loop. The new loop will contain
1909 the vectorized instructions while the old loop will continue to run the
1912 [ ] <-- Back-edge taken count overflow check.
1915 | [ ] <-- vector loop bypass (may consist of multiple blocks).
1918 || [ ] <-- vector pre header.
1922 || [ ]_| <-- vector loop.
1925 | >[ ] <--- middle-block.
1928 -|- >[ ] <--- new preheader.
1932 | [ ]_| <-- old scalar loop to handle remainder.
1935 >[ ] <-- exit block.
1939 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1940 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1941 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1942 assert(BypassBlock && "Invalid loop structure");
1943 assert(ExitBlock && "Must have an exit block");
1945 // Some loops have a single integer induction variable, while other loops
1946 // don't. One example is c++ iterators that often have multiple pointer
1947 // induction variables. In the code below we also support a case where we
1948 // don't have a single induction variable.
1949 OldInduction = Legal->getInduction();
1950 Type *IdxTy = Legal->getWidestInductionType();
1952 // Find the loop boundaries.
1953 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1954 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1956 // The exit count might have the type of i64 while the phi is i32. This can
1957 // happen if we have an induction variable that is sign extended before the
1958 // compare. The only way that we get a backedge taken count is that the
1959 // induction variable was signed and as such will not overflow. In such a case
1960 // truncation is legal.
1961 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1962 IdxTy->getPrimitiveSizeInBits())
1963 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1965 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1966 // Get the total trip count from the count by adding 1.
1967 ExitCount = SE->getAddExpr(BackedgeTakeCount,
1968 SE->getConstant(BackedgeTakeCount->getType(), 1));
1970 // Expand the trip count and place the new instructions in the preheader.
1971 // Notice that the pre-header does not change, only the loop body.
1972 SCEVExpander Exp(*SE, "induction");
1974 // We need to test whether the backedge-taken count is uint##_max. Adding one
1975 // to it will cause overflow and an incorrect loop trip count in the vector
1976 // body. In case of overflow we want to directly jump to the scalar remainder
1978 Value *BackedgeCount =
1979 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
1980 BypassBlock->getTerminator());
1981 if (BackedgeCount->getType()->isPointerTy())
1982 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
1983 "backedge.ptrcnt.to.int",
1984 BypassBlock->getTerminator());
1985 Instruction *CheckBCOverflow =
1986 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
1987 Constant::getAllOnesValue(BackedgeCount->getType()),
1988 "backedge.overflow", BypassBlock->getTerminator());
1990 // Count holds the overall loop count (N).
1991 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1992 BypassBlock->getTerminator());
1994 // The loop index does not have to start at Zero. Find the original start
1995 // value from the induction PHI node. If we don't have an induction variable
1996 // then we know that it starts at zero.
1997 Builder.SetInsertPoint(BypassBlock->getTerminator());
1998 Value *StartIdx = ExtendedIdx = OldInduction ?
1999 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2001 ConstantInt::get(IdxTy, 0);
2003 LoopBypassBlocks.push_back(BypassBlock);
2005 // Split the single block loop into the two loop structure described above.
2006 BasicBlock *VectorPH =
2007 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2008 BasicBlock *VecBody =
2009 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2010 BasicBlock *MiddleBlock =
2011 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2012 BasicBlock *ScalarPH =
2013 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2015 // Create and register the new vector loop.
2016 Loop* Lp = new Loop();
2017 Loop *ParentLoop = OrigLoop->getParentLoop();
2019 // Insert the new loop into the loop nest and register the new basic blocks
2020 // before calling any utilities such as SCEV that require valid LoopInfo.
2022 ParentLoop->addChildLoop(Lp);
2023 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2024 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2025 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2027 LI->addTopLevelLoop(Lp);
2029 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2031 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2033 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2035 // Generate the induction variable.
2036 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2037 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2038 // The loop step is equal to the vectorization factor (num of SIMD elements)
2039 // times the unroll factor (num of SIMD instructions).
2040 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2042 // This is the IR builder that we use to add all of the logic for bypassing
2043 // the new vector loop.
2044 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2045 setDebugLocFromInst(BypassBuilder,
2046 getDebugLocFromInstOrOperands(OldInduction));
2048 // We may need to extend the index in case there is a type mismatch.
2049 // We know that the count starts at zero and does not overflow.
2050 if (Count->getType() != IdxTy) {
2051 // The exit count can be of pointer type. Convert it to the correct
2053 if (ExitCount->getType()->isPointerTy())
2054 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2056 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2059 // Add the start index to the loop count to get the new end index.
2060 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2062 // Now we need to generate the expression for N - (N % VF), which is
2063 // the part that the vectorized body will execute.
2064 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2065 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2066 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2067 "end.idx.rnd.down");
2069 // Now, compare the new count to zero. If it is zero skip the vector loop and
2070 // jump to the scalar loop.
2071 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
2074 BasicBlock *LastBypassBlock = BypassBlock;
2076 // Generate code to check that the loops trip count that we computed by adding
2077 // one to the backedge-taken count will not overflow.
2079 auto PastOverflowCheck = std::next(BasicBlock::iterator(CheckBCOverflow));
2080 BasicBlock *CheckBlock =
2081 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2083 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2084 LoopBypassBlocks.push_back(CheckBlock);
2085 Instruction *OldTerm = LastBypassBlock->getTerminator();
2086 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2087 OldTerm->eraseFromParent();
2088 LastBypassBlock = CheckBlock;
2091 // Generate the code to check that the strides we assumed to be one are really
2092 // one. We want the new basic block to start at the first instruction in a
2093 // sequence of instructions that form a check.
2094 Instruction *StrideCheck;
2095 Instruction *FirstCheckInst;
2096 std::tie(FirstCheckInst, StrideCheck) =
2097 addStrideCheck(LastBypassBlock->getTerminator());
2099 // Create a new block containing the stride check.
2100 BasicBlock *CheckBlock =
2101 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2103 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2104 LoopBypassBlocks.push_back(CheckBlock);
2106 // Replace the branch into the memory check block with a conditional branch
2107 // for the "few elements case".
2108 Instruction *OldTerm = LastBypassBlock->getTerminator();
2109 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2110 OldTerm->eraseFromParent();
2113 LastBypassBlock = CheckBlock;
2116 // Generate the code that checks in runtime if arrays overlap. We put the
2117 // checks into a separate block to make the more common case of few elements
2119 Instruction *MemRuntimeCheck;
2120 std::tie(FirstCheckInst, MemRuntimeCheck) =
2121 addRuntimeCheck(LastBypassBlock->getTerminator());
2122 if (MemRuntimeCheck) {
2123 // Create a new block containing the memory check.
2124 BasicBlock *CheckBlock =
2125 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2127 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2128 LoopBypassBlocks.push_back(CheckBlock);
2130 // Replace the branch into the memory check block with a conditional branch
2131 // for the "few elements case".
2132 Instruction *OldTerm = LastBypassBlock->getTerminator();
2133 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2134 OldTerm->eraseFromParent();
2136 Cmp = MemRuntimeCheck;
2137 LastBypassBlock = CheckBlock;
2140 LastBypassBlock->getTerminator()->eraseFromParent();
2141 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2144 // We are going to resume the execution of the scalar loop.
2145 // Go over all of the induction variables that we found and fix the
2146 // PHIs that are left in the scalar version of the loop.
2147 // The starting values of PHI nodes depend on the counter of the last
2148 // iteration in the vectorized loop.
2149 // If we come from a bypass edge then we need to start from the original
2152 // This variable saves the new starting index for the scalar loop.
2153 PHINode *ResumeIndex = nullptr;
2154 LoopVectorizationLegality::InductionList::iterator I, E;
2155 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2156 // Set builder to point to last bypass block.
2157 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2158 for (I = List->begin(), E = List->end(); I != E; ++I) {
2159 PHINode *OrigPhi = I->first;
2160 LoopVectorizationLegality::InductionInfo II = I->second;
2162 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2163 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2164 MiddleBlock->getTerminator());
2165 // We might have extended the type of the induction variable but we need a
2166 // truncated version for the scalar loop.
2167 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2168 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2169 MiddleBlock->getTerminator()) : nullptr;
2171 // Create phi nodes to merge from the backedge-taken check block.
2172 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2173 ScalarPH->getTerminator());
2174 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2176 PHINode *BCTruncResumeVal = nullptr;
2177 if (OrigPhi == OldInduction) {
2179 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2180 ScalarPH->getTerminator());
2181 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2184 Value *EndValue = nullptr;
2186 case LoopVectorizationLegality::IK_NoInduction:
2187 llvm_unreachable("Unknown induction");
2188 case LoopVectorizationLegality::IK_IntInduction: {
2189 // Handle the integer induction counter.
2190 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2192 // We have the canonical induction variable.
2193 if (OrigPhi == OldInduction) {
2194 // Create a truncated version of the resume value for the scalar loop,
2195 // we might have promoted the type to a larger width.
2197 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2198 // The new PHI merges the original incoming value, in case of a bypass,
2199 // or the value at the end of the vectorized loop.
2200 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2201 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2202 TruncResumeVal->addIncoming(EndValue, VecBody);
2204 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2206 // We know what the end value is.
2207 EndValue = IdxEndRoundDown;
2208 // We also know which PHI node holds it.
2209 ResumeIndex = ResumeVal;
2213 // Not the canonical induction variable - add the vector loop count to the
2215 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2216 II.StartValue->getType(),
2218 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2221 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2222 // Convert the CountRoundDown variable to the PHI size.
2223 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2224 II.StartValue->getType(),
2226 // Handle reverse integer induction counter.
2227 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2230 case LoopVectorizationLegality::IK_PtrInduction: {
2231 // For pointer induction variables, calculate the offset using
2233 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2237 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2238 // The value at the end of the loop for the reverse pointer is calculated
2239 // by creating a GEP with a negative index starting from the start value.
2240 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2241 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2243 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2249 // The new PHI merges the original incoming value, in case of a bypass,
2250 // or the value at the end of the vectorized loop.
2251 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2252 if (OrigPhi == OldInduction)
2253 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2255 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2257 ResumeVal->addIncoming(EndValue, VecBody);
2259 // Fix the scalar body counter (PHI node).
2260 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2262 // The old induction's phi node in the scalar body needs the truncated
2264 if (OrigPhi == OldInduction) {
2265 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2266 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2268 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2269 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2273 // If we are generating a new induction variable then we also need to
2274 // generate the code that calculates the exit value. This value is not
2275 // simply the end of the counter because we may skip the vectorized body
2276 // in case of a runtime check.
2278 assert(!ResumeIndex && "Unexpected resume value found");
2279 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2280 MiddleBlock->getTerminator());
2281 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2282 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2283 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2286 // Make sure that we found the index where scalar loop needs to continue.
2287 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2288 "Invalid resume Index");
2290 // Add a check in the middle block to see if we have completed
2291 // all of the iterations in the first vector loop.
2292 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2293 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2294 ResumeIndex, "cmp.n",
2295 MiddleBlock->getTerminator());
2297 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2298 // Remove the old terminator.
2299 MiddleBlock->getTerminator()->eraseFromParent();
2301 // Create i+1 and fill the PHINode.
2302 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2303 Induction->addIncoming(StartIdx, VectorPH);
2304 Induction->addIncoming(NextIdx, VecBody);
2305 // Create the compare.
2306 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2307 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2309 // Now we have two terminators. Remove the old one from the block.
2310 VecBody->getTerminator()->eraseFromParent();
2312 // Get ready to start creating new instructions into the vectorized body.
2313 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2316 LoopVectorPreHeader = VectorPH;
2317 LoopScalarPreHeader = ScalarPH;
2318 LoopMiddleBlock = MiddleBlock;
2319 LoopExitBlock = ExitBlock;
2320 LoopVectorBody.push_back(VecBody);
2321 LoopScalarBody = OldBasicBlock;
2323 LoopVectorizeHints Hints(Lp, true);
2324 Hints.setAlreadyVectorized(Lp);
2327 /// This function returns the identity element (or neutral element) for
2328 /// the operation K.
2330 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2335 // Adding, Xoring, Oring zero to a number does not change it.
2336 return ConstantInt::get(Tp, 0);
2337 case RK_IntegerMult:
2338 // Multiplying a number by 1 does not change it.
2339 return ConstantInt::get(Tp, 1);
2341 // AND-ing a number with an all-1 value does not change it.
2342 return ConstantInt::get(Tp, -1, true);
2344 // Multiplying a number by 1 does not change it.
2345 return ConstantFP::get(Tp, 1.0L);
2347 // Adding zero to a number does not change it.
2348 return ConstantFP::get(Tp, 0.0L);
2350 llvm_unreachable("Unknown reduction kind");
2354 /// This function translates the reduction kind to an LLVM binary operator.
2356 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2358 case LoopVectorizationLegality::RK_IntegerAdd:
2359 return Instruction::Add;
2360 case LoopVectorizationLegality::RK_IntegerMult:
2361 return Instruction::Mul;
2362 case LoopVectorizationLegality::RK_IntegerOr:
2363 return Instruction::Or;
2364 case LoopVectorizationLegality::RK_IntegerAnd:
2365 return Instruction::And;
2366 case LoopVectorizationLegality::RK_IntegerXor:
2367 return Instruction::Xor;
2368 case LoopVectorizationLegality::RK_FloatMult:
2369 return Instruction::FMul;
2370 case LoopVectorizationLegality::RK_FloatAdd:
2371 return Instruction::FAdd;
2372 case LoopVectorizationLegality::RK_IntegerMinMax:
2373 return Instruction::ICmp;
2374 case LoopVectorizationLegality::RK_FloatMinMax:
2375 return Instruction::FCmp;
2377 llvm_unreachable("Unknown reduction operation");
2381 Value *createMinMaxOp(IRBuilder<> &Builder,
2382 LoopVectorizationLegality::MinMaxReductionKind RK,
2385 CmpInst::Predicate P = CmpInst::ICMP_NE;
2388 llvm_unreachable("Unknown min/max reduction kind");
2389 case LoopVectorizationLegality::MRK_UIntMin:
2390 P = CmpInst::ICMP_ULT;
2392 case LoopVectorizationLegality::MRK_UIntMax:
2393 P = CmpInst::ICMP_UGT;
2395 case LoopVectorizationLegality::MRK_SIntMin:
2396 P = CmpInst::ICMP_SLT;
2398 case LoopVectorizationLegality::MRK_SIntMax:
2399 P = CmpInst::ICMP_SGT;
2401 case LoopVectorizationLegality::MRK_FloatMin:
2402 P = CmpInst::FCMP_OLT;
2404 case LoopVectorizationLegality::MRK_FloatMax:
2405 P = CmpInst::FCMP_OGT;
2410 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2411 RK == LoopVectorizationLegality::MRK_FloatMax)
2412 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2414 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2416 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2421 struct CSEDenseMapInfo {
2422 static bool canHandle(Instruction *I) {
2423 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2424 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2426 static inline Instruction *getEmptyKey() {
2427 return DenseMapInfo<Instruction *>::getEmptyKey();
2429 static inline Instruction *getTombstoneKey() {
2430 return DenseMapInfo<Instruction *>::getTombstoneKey();
2432 static unsigned getHashValue(Instruction *I) {
2433 assert(canHandle(I) && "Unknown instruction!");
2434 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2435 I->value_op_end()));
2437 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2438 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2439 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2441 return LHS->isIdenticalTo(RHS);
2446 /// \brief Check whether this block is a predicated block.
2447 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2448 /// = ...; " blocks. We start with one vectorized basic block. For every
2449 /// conditional block we split this vectorized block. Therefore, every second
2450 /// block will be a predicated one.
2451 static bool isPredicatedBlock(unsigned BlockNum) {
2452 return BlockNum % 2;
2455 ///\brief Perform cse of induction variable instructions.
2456 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2457 // Perform simple cse.
2458 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2459 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2460 BasicBlock *BB = BBs[i];
2461 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2462 Instruction *In = I++;
2464 if (!CSEDenseMapInfo::canHandle(In))
2467 // Check if we can replace this instruction with any of the
2468 // visited instructions.
2469 if (Instruction *V = CSEMap.lookup(In)) {
2470 In->replaceAllUsesWith(V);
2471 In->eraseFromParent();
2474 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2475 // ...;" blocks for predicated stores. Every second block is a predicated
2477 if (isPredicatedBlock(i))
2485 /// \brief Adds a 'fast' flag to floating point operations.
2486 static Value *addFastMathFlag(Value *V) {
2487 if (isa<FPMathOperator>(V)){
2488 FastMathFlags Flags;
2489 Flags.setUnsafeAlgebra();
2490 cast<Instruction>(V)->setFastMathFlags(Flags);
2495 void InnerLoopVectorizer::vectorizeLoop() {
2496 //===------------------------------------------------===//
2498 // Notice: any optimization or new instruction that go
2499 // into the code below should be also be implemented in
2502 //===------------------------------------------------===//
2503 Constant *Zero = Builder.getInt32(0);
2505 // In order to support reduction variables we need to be able to vectorize
2506 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2507 // stages. First, we create a new vector PHI node with no incoming edges.
2508 // We use this value when we vectorize all of the instructions that use the
2509 // PHI. Next, after all of the instructions in the block are complete we
2510 // add the new incoming edges to the PHI. At this point all of the
2511 // instructions in the basic block are vectorized, so we can use them to
2512 // construct the PHI.
2513 PhiVector RdxPHIsToFix;
2515 // Scan the loop in a topological order to ensure that defs are vectorized
2517 LoopBlocksDFS DFS(OrigLoop);
2520 // Vectorize all of the blocks in the original loop.
2521 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2522 be = DFS.endRPO(); bb != be; ++bb)
2523 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2525 // At this point every instruction in the original loop is widened to
2526 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2527 // that we vectorized. The PHI nodes are currently empty because we did
2528 // not want to introduce cycles. Notice that the remaining PHI nodes
2529 // that we need to fix are reduction variables.
2531 // Create the 'reduced' values for each of the induction vars.
2532 // The reduced values are the vector values that we scalarize and combine
2533 // after the loop is finished.
2534 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2536 PHINode *RdxPhi = *it;
2537 assert(RdxPhi && "Unable to recover vectorized PHI");
2539 // Find the reduction variable descriptor.
2540 assert(Legal->getReductionVars()->count(RdxPhi) &&
2541 "Unable to find the reduction variable");
2542 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2543 (*Legal->getReductionVars())[RdxPhi];
2545 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2547 // We need to generate a reduction vector from the incoming scalar.
2548 // To do so, we need to generate the 'identity' vector and override
2549 // one of the elements with the incoming scalar reduction. We need
2550 // to do it in the vector-loop preheader.
2551 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2553 // This is the vector-clone of the value that leaves the loop.
2554 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2555 Type *VecTy = VectorExit[0]->getType();
2557 // Find the reduction identity variable. Zero for addition, or, xor,
2558 // one for multiplication, -1 for And.
2561 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2562 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2563 // MinMax reduction have the start value as their identify.
2565 VectorStart = Identity = RdxDesc.StartValue;
2567 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2572 // Handle other reduction kinds:
2574 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2575 VecTy->getScalarType());
2578 // This vector is the Identity vector where the first element is the
2579 // incoming scalar reduction.
2580 VectorStart = RdxDesc.StartValue;
2582 Identity = ConstantVector::getSplat(VF, Iden);
2584 // This vector is the Identity vector where the first element is the
2585 // incoming scalar reduction.
2586 VectorStart = Builder.CreateInsertElement(Identity,
2587 RdxDesc.StartValue, Zero);
2591 // Fix the vector-loop phi.
2592 // We created the induction variable so we know that the
2593 // preheader is the first entry.
2594 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2596 // Reductions do not have to start at zero. They can start with
2597 // any loop invariant values.
2598 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2599 BasicBlock *Latch = OrigLoop->getLoopLatch();
2600 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2601 VectorParts &Val = getVectorValue(LoopVal);
2602 for (unsigned part = 0; part < UF; ++part) {
2603 // Make sure to add the reduction stat value only to the
2604 // first unroll part.
2605 Value *StartVal = (part == 0) ? VectorStart : Identity;
2606 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2607 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2608 LoopVectorBody.back());
2611 // Before each round, move the insertion point right between
2612 // the PHIs and the values we are going to write.
2613 // This allows us to write both PHINodes and the extractelement
2615 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2617 VectorParts RdxParts;
2618 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2619 for (unsigned part = 0; part < UF; ++part) {
2620 // This PHINode contains the vectorized reduction variable, or
2621 // the initial value vector, if we bypass the vector loop.
2622 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2623 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2624 Value *StartVal = (part == 0) ? VectorStart : Identity;
2625 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2626 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2627 NewPhi->addIncoming(RdxExitVal[part],
2628 LoopVectorBody.back());
2629 RdxParts.push_back(NewPhi);
2632 // Reduce all of the unrolled parts into a single vector.
2633 Value *ReducedPartRdx = RdxParts[0];
2634 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2635 setDebugLocFromInst(Builder, ReducedPartRdx);
2636 for (unsigned part = 1; part < UF; ++part) {
2637 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2638 // Floating point operations had to be 'fast' to enable the reduction.
2639 ReducedPartRdx = addFastMathFlag(
2640 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2641 ReducedPartRdx, "bin.rdx"));
2643 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2644 ReducedPartRdx, RdxParts[part]);
2648 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2649 // and vector ops, reducing the set of values being computed by half each
2651 assert(isPowerOf2_32(VF) &&
2652 "Reduction emission only supported for pow2 vectors!");
2653 Value *TmpVec = ReducedPartRdx;
2654 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2655 for (unsigned i = VF; i != 1; i >>= 1) {
2656 // Move the upper half of the vector to the lower half.
2657 for (unsigned j = 0; j != i/2; ++j)
2658 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2660 // Fill the rest of the mask with undef.
2661 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2662 UndefValue::get(Builder.getInt32Ty()));
2665 Builder.CreateShuffleVector(TmpVec,
2666 UndefValue::get(TmpVec->getType()),
2667 ConstantVector::get(ShuffleMask),
2670 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2671 // Floating point operations had to be 'fast' to enable the reduction.
2672 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2673 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2675 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2678 // The result is in the first element of the vector.
2679 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2680 Builder.getInt32(0));
2683 // Create a phi node that merges control-flow from the backedge-taken check
2684 // block and the middle block.
2685 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2686 LoopScalarPreHeader->getTerminator());
2687 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2688 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2690 // Now, we need to fix the users of the reduction variable
2691 // inside and outside of the scalar remainder loop.
2692 // We know that the loop is in LCSSA form. We need to update the
2693 // PHI nodes in the exit blocks.
2694 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2695 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2696 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2697 if (!LCSSAPhi) break;
2699 // All PHINodes need to have a single entry edge, or two if
2700 // we already fixed them.
2701 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2703 // We found our reduction value exit-PHI. Update it with the
2704 // incoming bypass edge.
2705 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2706 // Add an edge coming from the bypass.
2707 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2710 }// end of the LCSSA phi scan.
2712 // Fix the scalar loop reduction variable with the incoming reduction sum
2713 // from the vector body and from the backedge value.
2714 int IncomingEdgeBlockIdx =
2715 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2716 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2717 // Pick the other block.
2718 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2719 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2720 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2721 }// end of for each redux variable.
2725 // Remove redundant induction instructions.
2726 cse(LoopVectorBody);
2729 void InnerLoopVectorizer::fixLCSSAPHIs() {
2730 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2731 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2732 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2733 if (!LCSSAPhi) break;
2734 if (LCSSAPhi->getNumIncomingValues() == 1)
2735 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2740 InnerLoopVectorizer::VectorParts
2741 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2742 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2745 // Look for cached value.
2746 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2747 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2748 if (ECEntryIt != MaskCache.end())
2749 return ECEntryIt->second;
2751 VectorParts SrcMask = createBlockInMask(Src);
2753 // The terminator has to be a branch inst!
2754 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2755 assert(BI && "Unexpected terminator found");
2757 if (BI->isConditional()) {
2758 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2760 if (BI->getSuccessor(0) != Dst)
2761 for (unsigned part = 0; part < UF; ++part)
2762 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2764 for (unsigned part = 0; part < UF; ++part)
2765 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2767 MaskCache[Edge] = EdgeMask;
2771 MaskCache[Edge] = SrcMask;
2775 InnerLoopVectorizer::VectorParts
2776 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2777 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2779 // Loop incoming mask is all-one.
2780 if (OrigLoop->getHeader() == BB) {
2781 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2782 return getVectorValue(C);
2785 // This is the block mask. We OR all incoming edges, and with zero.
2786 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2787 VectorParts BlockMask = getVectorValue(Zero);
2790 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2791 VectorParts EM = createEdgeMask(*it, BB);
2792 for (unsigned part = 0; part < UF; ++part)
2793 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2799 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2800 InnerLoopVectorizer::VectorParts &Entry,
2801 unsigned UF, unsigned VF, PhiVector *PV) {
2802 PHINode* P = cast<PHINode>(PN);
2803 // Handle reduction variables:
2804 if (Legal->getReductionVars()->count(P)) {
2805 for (unsigned part = 0; part < UF; ++part) {
2806 // This is phase one of vectorizing PHIs.
2807 Type *VecTy = (VF == 1) ? PN->getType() :
2808 VectorType::get(PN->getType(), VF);
2809 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2810 LoopVectorBody.back()-> getFirstInsertionPt());
2816 setDebugLocFromInst(Builder, P);
2817 // Check for PHI nodes that are lowered to vector selects.
2818 if (P->getParent() != OrigLoop->getHeader()) {
2819 // We know that all PHIs in non-header blocks are converted into
2820 // selects, so we don't have to worry about the insertion order and we
2821 // can just use the builder.
2822 // At this point we generate the predication tree. There may be
2823 // duplications since this is a simple recursive scan, but future
2824 // optimizations will clean it up.
2826 unsigned NumIncoming = P->getNumIncomingValues();
2828 // Generate a sequence of selects of the form:
2829 // SELECT(Mask3, In3,
2830 // SELECT(Mask2, In2,
2832 for (unsigned In = 0; In < NumIncoming; In++) {
2833 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2835 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2837 for (unsigned part = 0; part < UF; ++part) {
2838 // We might have single edge PHIs (blocks) - use an identity
2839 // 'select' for the first PHI operand.
2841 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2844 // Select between the current value and the previous incoming edge
2845 // based on the incoming mask.
2846 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2847 Entry[part], "predphi");
2853 // This PHINode must be an induction variable.
2854 // Make sure that we know about it.
2855 assert(Legal->getInductionVars()->count(P) &&
2856 "Not an induction variable");
2858 LoopVectorizationLegality::InductionInfo II =
2859 Legal->getInductionVars()->lookup(P);
2862 case LoopVectorizationLegality::IK_NoInduction:
2863 llvm_unreachable("Unknown induction");
2864 case LoopVectorizationLegality::IK_IntInduction: {
2865 assert(P->getType() == II.StartValue->getType() && "Types must match");
2866 Type *PhiTy = P->getType();
2868 if (P == OldInduction) {
2869 // Handle the canonical induction variable. We might have had to
2871 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2873 // Handle other induction variables that are now based on the
2875 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2877 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2878 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2881 Broadcasted = getBroadcastInstrs(Broadcasted);
2882 // After broadcasting the induction variable we need to make the vector
2883 // consecutive by adding 0, 1, 2, etc.
2884 for (unsigned part = 0; part < UF; ++part)
2885 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2888 case LoopVectorizationLegality::IK_ReverseIntInduction:
2889 case LoopVectorizationLegality::IK_PtrInduction:
2890 case LoopVectorizationLegality::IK_ReversePtrInduction:
2891 // Handle reverse integer and pointer inductions.
2892 Value *StartIdx = ExtendedIdx;
2893 // This is the normalized GEP that starts counting at zero.
2894 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2897 // Handle the reverse integer induction variable case.
2898 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2899 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2900 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2902 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2905 // This is a new value so do not hoist it out.
2906 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2907 // After broadcasting the induction variable we need to make the
2908 // vector consecutive by adding ... -3, -2, -1, 0.
2909 for (unsigned part = 0; part < UF; ++part)
2910 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2915 // Handle the pointer induction variable case.
2916 assert(P->getType()->isPointerTy() && "Unexpected type.");
2918 // Is this a reverse induction ptr or a consecutive induction ptr.
2919 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2922 // This is the vector of results. Notice that we don't generate
2923 // vector geps because scalar geps result in better code.
2924 for (unsigned part = 0; part < UF; ++part) {
2926 int EltIndex = (part) * (Reverse ? -1 : 1);
2927 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2930 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2932 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2934 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2936 Entry[part] = SclrGep;
2940 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2941 for (unsigned int i = 0; i < VF; ++i) {
2942 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2943 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2946 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2948 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2950 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2952 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2953 Builder.getInt32(i),
2956 Entry[part] = VecVal;
2962 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2963 // For each instruction in the old loop.
2964 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2965 VectorParts &Entry = WidenMap.get(it);
2966 switch (it->getOpcode()) {
2967 case Instruction::Br:
2968 // Nothing to do for PHIs and BR, since we already took care of the
2969 // loop control flow instructions.
2971 case Instruction::PHI:{
2972 // Vectorize PHINodes.
2973 widenPHIInstruction(it, Entry, UF, VF, PV);
2977 case Instruction::Add:
2978 case Instruction::FAdd:
2979 case Instruction::Sub:
2980 case Instruction::FSub:
2981 case Instruction::Mul:
2982 case Instruction::FMul:
2983 case Instruction::UDiv:
2984 case Instruction::SDiv:
2985 case Instruction::FDiv:
2986 case Instruction::URem:
2987 case Instruction::SRem:
2988 case Instruction::FRem:
2989 case Instruction::Shl:
2990 case Instruction::LShr:
2991 case Instruction::AShr:
2992 case Instruction::And:
2993 case Instruction::Or:
2994 case Instruction::Xor: {
2995 // Just widen binops.
2996 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2997 setDebugLocFromInst(Builder, BinOp);
2998 VectorParts &A = getVectorValue(it->getOperand(0));
2999 VectorParts &B = getVectorValue(it->getOperand(1));
3001 // Use this vector value for all users of the original instruction.
3002 for (unsigned Part = 0; Part < UF; ++Part) {
3003 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3005 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
3006 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
3007 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
3008 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
3009 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
3011 if (VecOp && isa<PossiblyExactOperator>(VecOp))
3012 VecOp->setIsExact(BinOp->isExact());
3014 // Copy the fast-math flags.
3015 if (VecOp && isa<FPMathOperator>(V))
3016 VecOp->setFastMathFlags(it->getFastMathFlags());
3022 case Instruction::Select: {
3024 // If the selector is loop invariant we can create a select
3025 // instruction with a scalar condition. Otherwise, use vector-select.
3026 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3028 setDebugLocFromInst(Builder, it);
3030 // The condition can be loop invariant but still defined inside the
3031 // loop. This means that we can't just use the original 'cond' value.
3032 // We have to take the 'vectorized' value and pick the first lane.
3033 // Instcombine will make this a no-op.
3034 VectorParts &Cond = getVectorValue(it->getOperand(0));
3035 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3036 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3038 Value *ScalarCond = (VF == 1) ? Cond[0] :
3039 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3041 for (unsigned Part = 0; Part < UF; ++Part) {
3042 Entry[Part] = Builder.CreateSelect(
3043 InvariantCond ? ScalarCond : Cond[Part],
3050 case Instruction::ICmp:
3051 case Instruction::FCmp: {
3052 // Widen compares. Generate vector compares.
3053 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3054 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3055 setDebugLocFromInst(Builder, it);
3056 VectorParts &A = getVectorValue(it->getOperand(0));
3057 VectorParts &B = getVectorValue(it->getOperand(1));
3058 for (unsigned Part = 0; Part < UF; ++Part) {
3061 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3063 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3069 case Instruction::Store:
3070 case Instruction::Load:
3071 vectorizeMemoryInstruction(it);
3073 case Instruction::ZExt:
3074 case Instruction::SExt:
3075 case Instruction::FPToUI:
3076 case Instruction::FPToSI:
3077 case Instruction::FPExt:
3078 case Instruction::PtrToInt:
3079 case Instruction::IntToPtr:
3080 case Instruction::SIToFP:
3081 case Instruction::UIToFP:
3082 case Instruction::Trunc:
3083 case Instruction::FPTrunc:
3084 case Instruction::BitCast: {
3085 CastInst *CI = dyn_cast<CastInst>(it);
3086 setDebugLocFromInst(Builder, it);
3087 /// Optimize the special case where the source is the induction
3088 /// variable. Notice that we can only optimize the 'trunc' case
3089 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3090 /// c. other casts depend on pointer size.
3091 if (CI->getOperand(0) == OldInduction &&
3092 it->getOpcode() == Instruction::Trunc) {
3093 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3095 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3096 for (unsigned Part = 0; Part < UF; ++Part)
3097 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3100 /// Vectorize casts.
3101 Type *DestTy = (VF == 1) ? CI->getType() :
3102 VectorType::get(CI->getType(), VF);
3104 VectorParts &A = getVectorValue(it->getOperand(0));
3105 for (unsigned Part = 0; Part < UF; ++Part)
3106 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3110 case Instruction::Call: {
3111 // Ignore dbg intrinsics.
3112 if (isa<DbgInfoIntrinsic>(it))
3114 setDebugLocFromInst(Builder, it);
3116 Module *M = BB->getParent()->getParent();
3117 CallInst *CI = cast<CallInst>(it);
3118 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3119 assert(ID && "Not an intrinsic call!");
3121 case Intrinsic::lifetime_end:
3122 case Intrinsic::lifetime_start:
3123 scalarizeInstruction(it);
3126 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3127 for (unsigned Part = 0; Part < UF; ++Part) {
3128 SmallVector<Value *, 4> Args;
3129 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3130 if (HasScalarOpd && i == 1) {
3131 Args.push_back(CI->getArgOperand(i));
3134 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3135 Args.push_back(Arg[Part]);
3137 Type *Tys[] = {CI->getType()};
3139 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3141 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3142 Entry[Part] = Builder.CreateCall(F, Args);
3150 // All other instructions are unsupported. Scalarize them.
3151 scalarizeInstruction(it);
3154 }// end of for_each instr.
3157 void InnerLoopVectorizer::updateAnalysis() {
3158 // Forget the original basic block.
3159 SE->forgetLoop(OrigLoop);
3161 // Update the dominator tree information.
3162 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3163 "Entry does not dominate exit.");
3165 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3166 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3167 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3169 // Due to if predication of stores we might create a sequence of "if(pred)
3170 // a[i] = ...; " blocks.
3171 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3173 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3174 else if (isPredicatedBlock(i)) {
3175 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3177 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3181 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3182 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3183 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3184 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3186 DEBUG(DT->verifyDomTree());
3189 /// \brief Check whether it is safe to if-convert this phi node.
3191 /// Phi nodes with constant expressions that can trap are not safe to if
3193 static bool canIfConvertPHINodes(BasicBlock *BB) {
3194 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3195 PHINode *Phi = dyn_cast<PHINode>(I);
3198 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3199 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3206 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3207 if (!EnableIfConversion)
3210 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3212 // A list of pointers that we can safely read and write to.
3213 SmallPtrSet<Value *, 8> SafePointes;
3215 // Collect safe addresses.
3216 for (Loop::block_iterator BI = TheLoop->block_begin(),
3217 BE = TheLoop->block_end(); BI != BE; ++BI) {
3218 BasicBlock *BB = *BI;
3220 if (blockNeedsPredication(BB))
3223 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3224 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3225 SafePointes.insert(LI->getPointerOperand());
3226 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3227 SafePointes.insert(SI->getPointerOperand());
3231 // Collect the blocks that need predication.
3232 BasicBlock *Header = TheLoop->getHeader();
3233 for (Loop::block_iterator BI = TheLoop->block_begin(),
3234 BE = TheLoop->block_end(); BI != BE; ++BI) {
3235 BasicBlock *BB = *BI;
3237 // We don't support switch statements inside loops.
3238 if (!isa<BranchInst>(BB->getTerminator()))
3241 // We must be able to predicate all blocks that need to be predicated.
3242 if (blockNeedsPredication(BB)) {
3243 if (!blockCanBePredicated(BB, SafePointes))
3245 } else if (BB != Header && !canIfConvertPHINodes(BB))
3250 // We can if-convert this loop.
3254 bool LoopVectorizationLegality::canVectorize() {
3255 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3256 // be canonicalized.
3257 if (!TheLoop->getLoopPreheader())
3260 // We can only vectorize innermost loops.
3261 if (TheLoop->getSubLoopsVector().size())
3264 // We must have a single backedge.
3265 if (TheLoop->getNumBackEdges() != 1)
3268 // We must have a single exiting block.
3269 if (!TheLoop->getExitingBlock())
3272 // We need to have a loop header.
3273 DEBUG(dbgs() << "LV: Found a loop: " <<
3274 TheLoop->getHeader()->getName() << '\n');
3276 // Check if we can if-convert non-single-bb loops.
3277 unsigned NumBlocks = TheLoop->getNumBlocks();
3278 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3279 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3283 // ScalarEvolution needs to be able to find the exit count.
3284 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3285 if (ExitCount == SE->getCouldNotCompute()) {
3286 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3290 // Check if we can vectorize the instructions and CFG in this loop.
3291 if (!canVectorizeInstrs()) {
3292 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3296 // Go over each instruction and look at memory deps.
3297 if (!canVectorizeMemory()) {
3298 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3302 // Collect all of the variables that remain uniform after vectorization.
3303 collectLoopUniforms();
3305 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3306 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3309 // Okay! We can vectorize. At this point we don't have any other mem analysis
3310 // which may limit our maximum vectorization factor, so just return true with
3315 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3316 if (Ty->isPointerTy())
3317 return DL.getIntPtrType(Ty);
3319 // It is possible that char's or short's overflow when we ask for the loop's
3320 // trip count, work around this by changing the type size.
3321 if (Ty->getScalarSizeInBits() < 32)
3322 return Type::getInt32Ty(Ty->getContext());
3327 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3328 Ty0 = convertPointerToIntegerType(DL, Ty0);
3329 Ty1 = convertPointerToIntegerType(DL, Ty1);
3330 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3335 /// \brief Check that the instruction has outside loop users and is not an
3336 /// identified reduction variable.
3337 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3338 SmallPtrSet<Value *, 4> &Reductions) {
3339 // Reduction instructions are allowed to have exit users. All other
3340 // instructions must not have external users.
3341 if (!Reductions.count(Inst))
3342 //Check that all of the users of the loop are inside the BB.
3343 for (User *U : Inst->users()) {
3344 Instruction *UI = cast<Instruction>(U);
3345 // This user may be a reduction exit value.
3346 if (!TheLoop->contains(UI)) {
3347 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3354 bool LoopVectorizationLegality::canVectorizeInstrs() {
3355 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3356 BasicBlock *Header = TheLoop->getHeader();
3358 // Look for the attribute signaling the absence of NaNs.
3359 Function &F = *Header->getParent();
3360 if (F.hasFnAttribute("no-nans-fp-math"))
3361 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3362 AttributeSet::FunctionIndex,
3363 "no-nans-fp-math").getValueAsString() == "true";
3365 // For each block in the loop.
3366 for (Loop::block_iterator bb = TheLoop->block_begin(),
3367 be = TheLoop->block_end(); bb != be; ++bb) {
3369 // Scan the instructions in the block and look for hazards.
3370 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3373 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3374 Type *PhiTy = Phi->getType();
3375 // Check that this PHI type is allowed.
3376 if (!PhiTy->isIntegerTy() &&
3377 !PhiTy->isFloatingPointTy() &&
3378 !PhiTy->isPointerTy()) {
3379 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3383 // If this PHINode is not in the header block, then we know that we
3384 // can convert it to select during if-conversion. No need to check if
3385 // the PHIs in this block are induction or reduction variables.
3386 if (*bb != Header) {
3387 // Check that this instruction has no outside users or is an
3388 // identified reduction value with an outside user.
3389 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3394 // We only allow if-converted PHIs with more than two incoming values.
3395 if (Phi->getNumIncomingValues() != 2) {
3396 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3400 // This is the value coming from the preheader.
3401 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3402 // Check if this is an induction variable.
3403 InductionKind IK = isInductionVariable(Phi);
3405 if (IK_NoInduction != IK) {
3406 // Get the widest type.
3408 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3410 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3412 // Int inductions are special because we only allow one IV.
3413 if (IK == IK_IntInduction) {
3414 // Use the phi node with the widest type as induction. Use the last
3415 // one if there are multiple (no good reason for doing this other
3416 // than it is expedient).
3417 if (!Induction || PhiTy == WidestIndTy)
3421 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3422 Inductions[Phi] = InductionInfo(StartValue, IK);
3424 // Until we explicitly handle the case of an induction variable with
3425 // an outside loop user we have to give up vectorizing this loop.
3426 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3432 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3433 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3436 if (AddReductionVar(Phi, RK_IntegerMult)) {
3437 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3440 if (AddReductionVar(Phi, RK_IntegerOr)) {
3441 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3444 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3445 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3448 if (AddReductionVar(Phi, RK_IntegerXor)) {
3449 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3452 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3453 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3456 if (AddReductionVar(Phi, RK_FloatMult)) {
3457 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3460 if (AddReductionVar(Phi, RK_FloatAdd)) {
3461 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3464 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3465 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3470 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3472 }// end of PHI handling
3474 // We still don't handle functions. However, we can ignore dbg intrinsic
3475 // calls and we do handle certain intrinsic and libm functions.
3476 CallInst *CI = dyn_cast<CallInst>(it);
3477 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3478 DEBUG(dbgs() << "LV: Found a call site.\n");
3482 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3483 // second argument is the same (i.e. loop invariant)
3485 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3486 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3487 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3492 // Check that the instruction return type is vectorizable.
3493 // Also, we can't vectorize extractelement instructions.
3494 if ((!VectorType::isValidElementType(it->getType()) &&
3495 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3496 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3500 // Check that the stored type is vectorizable.
3501 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3502 Type *T = ST->getValueOperand()->getType();
3503 if (!VectorType::isValidElementType(T))
3505 if (EnableMemAccessVersioning)
3506 collectStridedAcccess(ST);
3509 if (EnableMemAccessVersioning)
3510 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3511 collectStridedAcccess(LI);
3513 // Reduction instructions are allowed to have exit users.
3514 // All other instructions must not have external users.
3515 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3523 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3524 if (Inductions.empty())
3531 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3532 /// return the induction operand of the gep pointer.
3533 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3534 const DataLayout *DL, Loop *Lp) {
3535 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3539 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3541 // Check that all of the gep indices are uniform except for our induction
3543 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3544 if (i != InductionOperand &&
3545 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3547 return GEP->getOperand(InductionOperand);
3550 ///\brief Look for a cast use of the passed value.
3551 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3552 Value *UniqueCast = nullptr;
3553 for (User *U : Ptr->users()) {
3554 CastInst *CI = dyn_cast<CastInst>(U);
3555 if (CI && CI->getType() == Ty) {
3565 ///\brief Get the stride of a pointer access in a loop.
3566 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3567 /// pointer to the Value, or null otherwise.
3568 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3569 const DataLayout *DL, Loop *Lp) {
3570 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3571 if (!PtrTy || PtrTy->isAggregateType())
3574 // Try to remove a gep instruction to make the pointer (actually index at this
3575 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3576 // pointer, otherwise, we are analyzing the index.
3577 Value *OrigPtr = Ptr;
3579 // The size of the pointer access.
3580 int64_t PtrAccessSize = 1;
3582 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3583 const SCEV *V = SE->getSCEV(Ptr);
3587 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3588 V = C->getOperand();
3590 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3594 V = S->getStepRecurrence(*SE);
3598 // Strip off the size of access multiplication if we are still analyzing the
3600 if (OrigPtr == Ptr) {
3601 DL->getTypeAllocSize(PtrTy->getElementType());
3602 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3603 if (M->getOperand(0)->getSCEVType() != scConstant)
3606 const APInt &APStepVal =
3607 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3609 // Huge step value - give up.
3610 if (APStepVal.getBitWidth() > 64)
3613 int64_t StepVal = APStepVal.getSExtValue();
3614 if (PtrAccessSize != StepVal)
3616 V = M->getOperand(1);
3621 Type *StripedOffRecurrenceCast = nullptr;
3622 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3623 StripedOffRecurrenceCast = C->getType();
3624 V = C->getOperand();
3627 // Look for the loop invariant symbolic value.
3628 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3632 Value *Stride = U->getValue();
3633 if (!Lp->isLoopInvariant(Stride))
3636 // If we have stripped off the recurrence cast we have to make sure that we
3637 // return the value that is used in this loop so that we can replace it later.
3638 if (StripedOffRecurrenceCast)
3639 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3644 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3645 Value *Ptr = nullptr;
3646 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3647 Ptr = LI->getPointerOperand();
3648 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3649 Ptr = SI->getPointerOperand();
3653 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3657 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3658 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3659 Strides[Ptr] = Stride;
3660 StrideSet.insert(Stride);
3663 void LoopVectorizationLegality::collectLoopUniforms() {
3664 // We now know that the loop is vectorizable!
3665 // Collect variables that will remain uniform after vectorization.
3666 std::vector<Value*> Worklist;
3667 BasicBlock *Latch = TheLoop->getLoopLatch();
3669 // Start with the conditional branch and walk up the block.
3670 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3672 // Also add all consecutive pointer values; these values will be uniform
3673 // after vectorization (and subsequent cleanup) and, until revectorization is
3674 // supported, all dependencies must also be uniform.
3675 for (Loop::block_iterator B = TheLoop->block_begin(),
3676 BE = TheLoop->block_end(); B != BE; ++B)
3677 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3679 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3680 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3682 while (Worklist.size()) {
3683 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3684 Worklist.pop_back();
3686 // Look at instructions inside this loop.
3687 // Stop when reaching PHI nodes.
3688 // TODO: we need to follow values all over the loop, not only in this block.
3689 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3692 // This is a known uniform.
3695 // Insert all operands.
3696 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3701 /// \brief Analyses memory accesses in a loop.
3703 /// Checks whether run time pointer checks are needed and builds sets for data
3704 /// dependence checking.
3705 class AccessAnalysis {
3707 /// \brief Read or write access location.
3708 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3709 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3711 /// \brief Set of potential dependent memory accesses.
3712 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3714 AccessAnalysis(const DataLayout *Dl, DepCandidates &DA) :
3715 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3716 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3718 /// \brief Register a load and whether it is only read from.
3719 void addLoad(Value *Ptr, bool IsReadOnly) {
3720 Accesses.insert(MemAccessInfo(Ptr, false));
3722 ReadOnlyPtr.insert(Ptr);
3725 /// \brief Register a store.
3726 void addStore(Value *Ptr) {
3727 Accesses.insert(MemAccessInfo(Ptr, true));
3730 /// \brief Check whether we can check the pointers at runtime for
3731 /// non-intersection.
3732 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3733 unsigned &NumComparisons, ScalarEvolution *SE,
3734 Loop *TheLoop, ValueToValueMap &Strides,
3735 bool ShouldCheckStride = false);
3737 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3738 /// and builds sets of dependent accesses.
3739 void buildDependenceSets() {
3740 // Process read-write pointers first.
3741 processMemAccesses(false);
3742 // Next, process read pointers.
3743 processMemAccesses(true);
3746 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3748 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3749 void resetDepChecks() { CheckDeps.clear(); }
3751 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3754 typedef SetVector<MemAccessInfo> PtrAccessSet;
3755 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3757 /// \brief Go over all memory access or only the deferred ones if
3758 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3759 /// and build sets of dependency check candidates.
3760 void processMemAccesses(bool UseDeferred);
3762 /// Set of all accesses.
3763 PtrAccessSet Accesses;
3765 /// Set of access to check after all writes have been processed.
3766 PtrAccessSet DeferredAccesses;
3768 /// Map of pointers to last access encountered.
3769 UnderlyingObjToAccessMap ObjToLastAccess;
3771 /// Set of accesses that need a further dependence check.
3772 MemAccessInfoSet CheckDeps;
3774 /// Set of pointers that are read only.
3775 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3777 /// Set of underlying objects already written to.
3778 SmallPtrSet<Value*, 16> WriteObjects;
3780 const DataLayout *DL;
3782 /// Sets of potentially dependent accesses - members of one set share an
3783 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3784 /// dependence check.
3785 DepCandidates &DepCands;
3787 bool AreAllWritesIdentified;
3788 bool AreAllReadsIdentified;
3789 bool IsRTCheckNeeded;
3792 } // end anonymous namespace
3794 /// \brief Check whether a pointer can participate in a runtime bounds check.
3795 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3797 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3798 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3802 return AR->isAffine();
3805 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3806 /// the address space.
3807 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
3808 const Loop *Lp, ValueToValueMap &StridesMap);
3810 bool AccessAnalysis::canCheckPtrAtRT(
3811 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3812 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3813 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3814 // Find pointers with computable bounds. We are going to use this information
3815 // to place a runtime bound check.
3816 unsigned NumReadPtrChecks = 0;
3817 unsigned NumWritePtrChecks = 0;
3818 bool CanDoRT = true;
3820 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3821 // We assign consecutive id to access from different dependence sets.
3822 // Accesses within the same set don't need a runtime check.
3823 unsigned RunningDepId = 1;
3824 DenseMap<Value *, unsigned> DepSetId;
3826 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3828 const MemAccessInfo &Access = *AI;
3829 Value *Ptr = Access.getPointer();
3830 bool IsWrite = Access.getInt();
3832 // Just add write checks if we have both.
3833 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3837 ++NumWritePtrChecks;
3841 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3842 // When we run after a failing dependency check we have to make sure we
3843 // don't have wrapping pointers.
3844 (!ShouldCheckStride ||
3845 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3846 // The id of the dependence set.
3849 if (IsDepCheckNeeded) {
3850 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3851 unsigned &LeaderId = DepSetId[Leader];
3853 LeaderId = RunningDepId++;
3856 // Each access has its own dependence set.
3857 DepId = RunningDepId++;
3859 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3861 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3867 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3868 NumComparisons = 0; // Only one dependence set.
3870 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3871 NumWritePtrChecks - 1));
3874 // If the pointers that we would use for the bounds comparison have different
3875 // address spaces, assume the values aren't directly comparable, so we can't
3876 // use them for the runtime check. We also have to assume they could
3877 // overlap. In the future there should be metadata for whether address spaces
3879 unsigned NumPointers = RtCheck.Pointers.size();
3880 for (unsigned i = 0; i < NumPointers; ++i) {
3881 for (unsigned j = i + 1; j < NumPointers; ++j) {
3882 // Only need to check pointers between two different dependency sets.
3883 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3886 Value *PtrI = RtCheck.Pointers[i];
3887 Value *PtrJ = RtCheck.Pointers[j];
3889 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3890 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3892 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3893 " different address spaces\n");
3902 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3903 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3906 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3907 // We process the set twice: first we process read-write pointers, last we
3908 // process read-only pointers. This allows us to skip dependence tests for
3909 // read-only pointers.
3911 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3912 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3913 const MemAccessInfo &Access = *AI;
3914 Value *Ptr = Access.getPointer();
3915 bool IsWrite = Access.getInt();
3917 DepCands.insert(Access);
3919 // Memorize read-only pointers for later processing and skip them in the
3920 // first round (they need to be checked after we have seen all write
3921 // pointers). Note: we also mark pointer that are not consecutive as
3922 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3923 // second check for "!IsWrite".
3924 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3925 if (!UseDeferred && IsReadOnlyPtr) {
3926 DeferredAccesses.insert(Access);
3930 bool NeedDepCheck = false;
3931 // Check whether there is the possibility of dependency because of
3932 // underlying objects being the same.
3933 typedef SmallVector<Value*, 16> ValueVector;
3934 ValueVector TempObjects;
3935 GetUnderlyingObjects(Ptr, TempObjects, DL);
3936 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3938 Value *UnderlyingObj = *UI;
3940 // If this is a write then it needs to be an identified object. If this a
3941 // read and all writes (so far) are identified function scope objects we
3942 // don't need an identified underlying object but only an Argument (the
3943 // next write is going to invalidate this assumption if it is
3945 // This is a micro-optimization for the case where all writes are
3946 // identified and we have one argument pointer.
3947 // Otherwise, we do need a runtime check.
3948 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3949 (!IsWrite && (!AreAllWritesIdentified ||
3950 !isa<Argument>(UnderlyingObj)) &&
3951 !isIdentifiedObject(UnderlyingObj))) {
3952 DEBUG(dbgs() << "LV: Found an unidentified " <<
3953 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3955 IsRTCheckNeeded = (IsRTCheckNeeded ||
3956 !isIdentifiedObject(UnderlyingObj) ||
3957 !AreAllReadsIdentified);
3960 AreAllWritesIdentified = false;
3962 AreAllReadsIdentified = false;
3965 // If this is a write - check other reads and writes for conflicts. If
3966 // this is a read only check other writes for conflicts (but only if there
3967 // is no other write to the ptr - this is an optimization to catch "a[i] =
3968 // a[i] + " without having to do a dependence check).
3969 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3970 NeedDepCheck = true;
3973 WriteObjects.insert(UnderlyingObj);
3975 // Create sets of pointers connected by shared underlying objects.
3976 UnderlyingObjToAccessMap::iterator Prev =
3977 ObjToLastAccess.find(UnderlyingObj);
3978 if (Prev != ObjToLastAccess.end())
3979 DepCands.unionSets(Access, Prev->second);
3981 ObjToLastAccess[UnderlyingObj] = Access;
3985 CheckDeps.insert(Access);
3990 /// \brief Checks memory dependences among accesses to the same underlying
3991 /// object to determine whether there vectorization is legal or not (and at
3992 /// which vectorization factor).
3994 /// This class works under the assumption that we already checked that memory
3995 /// locations with different underlying pointers are "must-not alias".
3996 /// We use the ScalarEvolution framework to symbolically evalutate access
3997 /// functions pairs. Since we currently don't restructure the loop we can rely
3998 /// on the program order of memory accesses to determine their safety.
3999 /// At the moment we will only deem accesses as safe for:
4000 /// * A negative constant distance assuming program order.
4002 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
4003 /// a[i] = tmp; y = a[i];
4005 /// The latter case is safe because later checks guarantuee that there can't
4006 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
4007 /// the same variable: a header phi can only be an induction or a reduction, a
4008 /// reduction can't have a memory sink, an induction can't have a memory
4009 /// source). This is important and must not be violated (or we have to
4010 /// resort to checking for cycles through memory).
4012 /// * A positive constant distance assuming program order that is bigger
4013 /// than the biggest memory access.
4015 /// tmp = a[i] OR b[i] = x
4016 /// a[i+2] = tmp y = b[i+2];
4018 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4020 /// * Zero distances and all accesses have the same size.
4022 class MemoryDepChecker {
4024 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4025 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4027 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4028 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4029 ShouldRetryWithRuntimeCheck(false) {}
4031 /// \brief Register the location (instructions are given increasing numbers)
4032 /// of a write access.
4033 void addAccess(StoreInst *SI) {
4034 Value *Ptr = SI->getPointerOperand();
4035 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4036 InstMap.push_back(SI);
4040 /// \brief Register the location (instructions are given increasing numbers)
4041 /// of a write access.
4042 void addAccess(LoadInst *LI) {
4043 Value *Ptr = LI->getPointerOperand();
4044 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4045 InstMap.push_back(LI);
4049 /// \brief Check whether the dependencies between the accesses are safe.
4051 /// Only checks sets with elements in \p CheckDeps.
4052 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4053 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4055 /// \brief The maximum number of bytes of a vector register we can vectorize
4056 /// the accesses safely with.
4057 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4059 /// \brief In same cases when the dependency check fails we can still
4060 /// vectorize the loop with a dynamic array access check.
4061 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4064 ScalarEvolution *SE;
4065 const DataLayout *DL;
4066 const Loop *InnermostLoop;
4068 /// \brief Maps access locations (ptr, read/write) to program order.
4069 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4071 /// \brief Memory access instructions in program order.
4072 SmallVector<Instruction *, 16> InstMap;
4074 /// \brief The program order index to be used for the next instruction.
4077 // We can access this many bytes in parallel safely.
4078 unsigned MaxSafeDepDistBytes;
4080 /// \brief If we see a non-constant dependence distance we can still try to
4081 /// vectorize this loop with runtime checks.
4082 bool ShouldRetryWithRuntimeCheck;
4084 /// \brief Check whether there is a plausible dependence between the two
4087 /// Access \p A must happen before \p B in program order. The two indices
4088 /// identify the index into the program order map.
4090 /// This function checks whether there is a plausible dependence (or the
4091 /// absence of such can't be proved) between the two accesses. If there is a
4092 /// plausible dependence but the dependence distance is bigger than one
4093 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4094 /// distance is smaller than any other distance encountered so far).
4095 /// Otherwise, this function returns true signaling a possible dependence.
4096 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4097 const MemAccessInfo &B, unsigned BIdx,
4098 ValueToValueMap &Strides);
4100 /// \brief Check whether the data dependence could prevent store-load
4102 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4105 } // end anonymous namespace
4107 static bool isInBoundsGep(Value *Ptr) {
4108 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4109 return GEP->isInBounds();
4113 /// \brief Check whether the access through \p Ptr has a constant stride.
4114 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4115 const Loop *Lp, ValueToValueMap &StridesMap) {
4116 const Type *Ty = Ptr->getType();
4117 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4119 // Make sure that the pointer does not point to aggregate types.
4120 const PointerType *PtrTy = cast<PointerType>(Ty);
4121 if (PtrTy->getElementType()->isAggregateType()) {
4122 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4127 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4129 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4131 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4132 << *Ptr << " SCEV: " << *PtrScev << "\n");
4136 // The accesss function must stride over the innermost loop.
4137 if (Lp != AR->getLoop()) {
4138 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4139 *Ptr << " SCEV: " << *PtrScev << "\n");
4142 // The address calculation must not wrap. Otherwise, a dependence could be
4144 // An inbounds getelementptr that is a AddRec with a unit stride
4145 // cannot wrap per definition. The unit stride requirement is checked later.
4146 // An getelementptr without an inbounds attribute and unit stride would have
4147 // to access the pointer value "0" which is undefined behavior in address
4148 // space 0, therefore we can also vectorize this case.
4149 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4150 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4151 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4152 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4153 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4154 << *Ptr << " SCEV: " << *PtrScev << "\n");
4158 // Check the step is constant.
4159 const SCEV *Step = AR->getStepRecurrence(*SE);
4161 // Calculate the pointer stride and check if it is consecutive.
4162 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4164 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4165 " SCEV: " << *PtrScev << "\n");
4169 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4170 const APInt &APStepVal = C->getValue()->getValue();
4172 // Huge step value - give up.
4173 if (APStepVal.getBitWidth() > 64)
4176 int64_t StepVal = APStepVal.getSExtValue();
4179 int64_t Stride = StepVal / Size;
4180 int64_t Rem = StepVal % Size;
4184 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4185 // know we can't "wrap around the address space". In case of address space
4186 // zero we know that this won't happen without triggering undefined behavior.
4187 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4188 Stride != 1 && Stride != -1)
4194 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4195 unsigned TypeByteSize) {
4196 // If loads occur at a distance that is not a multiple of a feasible vector
4197 // factor store-load forwarding does not take place.
4198 // Positive dependences might cause troubles because vectorizing them might
4199 // prevent store-load forwarding making vectorized code run a lot slower.
4200 // a[i] = a[i-3] ^ a[i-8];
4201 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4202 // hence on your typical architecture store-load forwarding does not take
4203 // place. Vectorizing in such cases does not make sense.
4204 // Store-load forwarding distance.
4205 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4206 // Maximum vector factor.
4207 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4208 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4209 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4211 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4213 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4214 MaxVFWithoutSLForwardIssues = (vf >>=1);
4219 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4220 DEBUG(dbgs() << "LV: Distance " << Distance <<
4221 " that could cause a store-load forwarding conflict\n");
4225 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4226 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4227 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4231 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4232 const MemAccessInfo &B, unsigned BIdx,
4233 ValueToValueMap &Strides) {
4234 assert (AIdx < BIdx && "Must pass arguments in program order");
4236 Value *APtr = A.getPointer();
4237 Value *BPtr = B.getPointer();
4238 bool AIsWrite = A.getInt();
4239 bool BIsWrite = B.getInt();
4241 // Two reads are independent.
4242 if (!AIsWrite && !BIsWrite)
4245 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4246 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4248 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4249 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4251 const SCEV *Src = AScev;
4252 const SCEV *Sink = BScev;
4254 // If the induction step is negative we have to invert source and sink of the
4256 if (StrideAPtr < 0) {
4259 std::swap(APtr, BPtr);
4260 std::swap(Src, Sink);
4261 std::swap(AIsWrite, BIsWrite);
4262 std::swap(AIdx, BIdx);
4263 std::swap(StrideAPtr, StrideBPtr);
4266 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4268 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4269 << "(Induction step: " << StrideAPtr << ")\n");
4270 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4271 << *InstMap[BIdx] << ": " << *Dist << "\n");
4273 // Need consecutive accesses. We don't want to vectorize
4274 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4275 // the address space.
4276 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4277 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4281 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4283 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4284 ShouldRetryWithRuntimeCheck = true;
4288 Type *ATy = APtr->getType()->getPointerElementType();
4289 Type *BTy = BPtr->getType()->getPointerElementType();
4290 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4292 // Negative distances are not plausible dependencies.
4293 const APInt &Val = C->getValue()->getValue();
4294 if (Val.isNegative()) {
4295 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4296 if (IsTrueDataDependence &&
4297 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4301 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4305 // Write to the same location with the same size.
4306 // Could be improved to assert type sizes are the same (i32 == float, etc).
4310 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4314 assert(Val.isStrictlyPositive() && "Expect a positive value");
4316 // Positive distance bigger than max vectorization factor.
4319 "LV: ReadWrite-Write positive dependency with different types\n");
4323 unsigned Distance = (unsigned) Val.getZExtValue();
4325 // Bail out early if passed-in parameters make vectorization not feasible.
4326 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4327 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4329 // The distance must be bigger than the size needed for a vectorized version
4330 // of the operation and the size of the vectorized operation must not be
4331 // bigger than the currrent maximum size.
4332 if (Distance < 2*TypeByteSize ||
4333 2*TypeByteSize > MaxSafeDepDistBytes ||
4334 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4335 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4336 << Val.getSExtValue() << '\n');
4340 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4341 Distance : MaxSafeDepDistBytes;
4343 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4344 if (IsTrueDataDependence &&
4345 couldPreventStoreLoadForward(Distance, TypeByteSize))
4348 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4349 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4354 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4355 MemAccessInfoSet &CheckDeps,
4356 ValueToValueMap &Strides) {
4358 MaxSafeDepDistBytes = -1U;
4359 while (!CheckDeps.empty()) {
4360 MemAccessInfo CurAccess = *CheckDeps.begin();
4362 // Get the relevant memory access set.
4363 EquivalenceClasses<MemAccessInfo>::iterator I =
4364 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4366 // Check accesses within this set.
4367 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4368 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4370 // Check every access pair.
4372 CheckDeps.erase(*AI);
4373 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4375 // Check every accessing instruction pair in program order.
4376 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4377 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4378 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4379 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4380 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4382 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4393 bool LoopVectorizationLegality::canVectorizeMemory() {
4395 typedef SmallVector<Value*, 16> ValueVector;
4396 typedef SmallPtrSet<Value*, 16> ValueSet;
4398 // Holds the Load and Store *instructions*.
4402 // Holds all the different accesses in the loop.
4403 unsigned NumReads = 0;
4404 unsigned NumReadWrites = 0;
4406 PtrRtCheck.Pointers.clear();
4407 PtrRtCheck.Need = false;
4409 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4410 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4413 for (Loop::block_iterator bb = TheLoop->block_begin(),
4414 be = TheLoop->block_end(); bb != be; ++bb) {
4416 // Scan the BB and collect legal loads and stores.
4417 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4420 // If this is a load, save it. If this instruction can read from memory
4421 // but is not a load, then we quit. Notice that we don't handle function
4422 // calls that read or write.
4423 if (it->mayReadFromMemory()) {
4424 // Many math library functions read the rounding mode. We will only
4425 // vectorize a loop if it contains known function calls that don't set
4426 // the flag. Therefore, it is safe to ignore this read from memory.
4427 CallInst *Call = dyn_cast<CallInst>(it);
4428 if (Call && getIntrinsicIDForCall(Call, TLI))
4431 LoadInst *Ld = dyn_cast<LoadInst>(it);
4432 if (!Ld) return false;
4433 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4434 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4438 Loads.push_back(Ld);
4439 DepChecker.addAccess(Ld);
4443 // Save 'store' instructions. Abort if other instructions write to memory.
4444 if (it->mayWriteToMemory()) {
4445 StoreInst *St = dyn_cast<StoreInst>(it);
4446 if (!St) return false;
4447 if (!St->isSimple() && !IsAnnotatedParallel) {
4448 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4452 Stores.push_back(St);
4453 DepChecker.addAccess(St);
4458 // Now we have two lists that hold the loads and the stores.
4459 // Next, we find the pointers that they use.
4461 // Check if we see any stores. If there are no stores, then we don't
4462 // care if the pointers are *restrict*.
4463 if (!Stores.size()) {
4464 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4468 AccessAnalysis::DepCandidates DependentAccesses;
4469 AccessAnalysis Accesses(DL, DependentAccesses);
4471 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4472 // multiple times on the same object. If the ptr is accessed twice, once
4473 // for read and once for write, it will only appear once (on the write
4474 // list). This is okay, since we are going to check for conflicts between
4475 // writes and between reads and writes, but not between reads and reads.
4478 ValueVector::iterator I, IE;
4479 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4480 StoreInst *ST = cast<StoreInst>(*I);
4481 Value* Ptr = ST->getPointerOperand();
4483 if (isUniform(Ptr)) {
4484 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4488 // If we did *not* see this pointer before, insert it to the read-write
4489 // list. At this phase it is only a 'write' list.
4490 if (Seen.insert(Ptr)) {
4492 Accesses.addStore(Ptr);
4496 if (IsAnnotatedParallel) {
4498 << "LV: A loop annotated parallel, ignore memory dependency "
4503 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4504 LoadInst *LD = cast<LoadInst>(*I);
4505 Value* Ptr = LD->getPointerOperand();
4506 // If we did *not* see this pointer before, insert it to the
4507 // read list. If we *did* see it before, then it is already in
4508 // the read-write list. This allows us to vectorize expressions
4509 // such as A[i] += x; Because the address of A[i] is a read-write
4510 // pointer. This only works if the index of A[i] is consecutive.
4511 // If the address of i is unknown (for example A[B[i]]) then we may
4512 // read a few words, modify, and write a few words, and some of the
4513 // words may be written to the same address.
4514 bool IsReadOnlyPtr = false;
4515 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4517 IsReadOnlyPtr = true;
4519 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4522 // If we write (or read-write) to a single destination and there are no
4523 // other reads in this loop then is it safe to vectorize.
4524 if (NumReadWrites == 1 && NumReads == 0) {
4525 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4529 // Build dependence sets and check whether we need a runtime pointer bounds
4531 Accesses.buildDependenceSets();
4532 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4534 // Find pointers with computable bounds. We are going to use this information
4535 // to place a runtime bound check.
4536 unsigned NumComparisons = 0;
4537 bool CanDoRT = false;
4539 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4542 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4543 " pointer comparisons.\n");
4545 // If we only have one set of dependences to check pointers among we don't
4546 // need a runtime check.
4547 if (NumComparisons == 0 && NeedRTCheck)
4548 NeedRTCheck = false;
4550 // Check that we did not collect too many pointers or found an unsizeable
4552 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4558 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4561 if (NeedRTCheck && !CanDoRT) {
4562 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4563 "the array bounds.\n");
4568 PtrRtCheck.Need = NeedRTCheck;
4570 bool CanVecMem = true;
4571 if (Accesses.isDependencyCheckNeeded()) {
4572 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4573 CanVecMem = DepChecker.areDepsSafe(
4574 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4575 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4577 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4578 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4581 // Clear the dependency checks. We assume they are not needed.
4582 Accesses.resetDepChecks();
4585 PtrRtCheck.Need = true;
4587 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4588 TheLoop, Strides, true);
4589 // Check that we did not collect too many pointers or found an unsizeable
4591 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4592 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4601 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4602 " need a runtime memory check.\n");
4607 static bool hasMultipleUsesOf(Instruction *I,
4608 SmallPtrSet<Instruction *, 8> &Insts) {
4609 unsigned NumUses = 0;
4610 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4611 if (Insts.count(dyn_cast<Instruction>(*Use)))
4620 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4621 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4622 if (!Set.count(dyn_cast<Instruction>(*Use)))
4627 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4628 ReductionKind Kind) {
4629 if (Phi->getNumIncomingValues() != 2)
4632 // Reduction variables are only found in the loop header block.
4633 if (Phi->getParent() != TheLoop->getHeader())
4636 // Obtain the reduction start value from the value that comes from the loop
4638 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4640 // ExitInstruction is the single value which is used outside the loop.
4641 // We only allow for a single reduction value to be used outside the loop.
4642 // This includes users of the reduction, variables (which form a cycle
4643 // which ends in the phi node).
4644 Instruction *ExitInstruction = nullptr;
4645 // Indicates that we found a reduction operation in our scan.
4646 bool FoundReduxOp = false;
4648 // We start with the PHI node and scan for all of the users of this
4649 // instruction. All users must be instructions that can be used as reduction
4650 // variables (such as ADD). We must have a single out-of-block user. The cycle
4651 // must include the original PHI.
4652 bool FoundStartPHI = false;
4654 // To recognize min/max patterns formed by a icmp select sequence, we store
4655 // the number of instruction we saw from the recognized min/max pattern,
4656 // to make sure we only see exactly the two instructions.
4657 unsigned NumCmpSelectPatternInst = 0;
4658 ReductionInstDesc ReduxDesc(false, nullptr);
4660 SmallPtrSet<Instruction *, 8> VisitedInsts;
4661 SmallVector<Instruction *, 8> Worklist;
4662 Worklist.push_back(Phi);
4663 VisitedInsts.insert(Phi);
4665 // A value in the reduction can be used:
4666 // - By the reduction:
4667 // - Reduction operation:
4668 // - One use of reduction value (safe).
4669 // - Multiple use of reduction value (not safe).
4671 // - All uses of the PHI must be the reduction (safe).
4672 // - Otherwise, not safe.
4673 // - By one instruction outside of the loop (safe).
4674 // - By further instructions outside of the loop (not safe).
4675 // - By an instruction that is not part of the reduction (not safe).
4677 // * An instruction type other than PHI or the reduction operation.
4678 // * A PHI in the header other than the initial PHI.
4679 while (!Worklist.empty()) {
4680 Instruction *Cur = Worklist.back();
4681 Worklist.pop_back();
4684 // If the instruction has no users then this is a broken chain and can't be
4685 // a reduction variable.
4686 if (Cur->use_empty())
4689 bool IsAPhi = isa<PHINode>(Cur);
4691 // A header PHI use other than the original PHI.
4692 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4695 // Reductions of instructions such as Div, and Sub is only possible if the
4696 // LHS is the reduction variable.
4697 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4698 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4699 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4702 // Any reduction instruction must be of one of the allowed kinds.
4703 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4704 if (!ReduxDesc.IsReduction)
4707 // A reduction operation must only have one use of the reduction value.
4708 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4709 hasMultipleUsesOf(Cur, VisitedInsts))
4712 // All inputs to a PHI node must be a reduction value.
4713 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4716 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4717 isa<SelectInst>(Cur)))
4718 ++NumCmpSelectPatternInst;
4719 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4720 isa<SelectInst>(Cur)))
4721 ++NumCmpSelectPatternInst;
4723 // Check whether we found a reduction operator.
4724 FoundReduxOp |= !IsAPhi;
4726 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4727 // onto the stack. This way we are going to have seen all inputs to PHI
4728 // nodes once we get to them.
4729 SmallVector<Instruction *, 8> NonPHIs;
4730 SmallVector<Instruction *, 8> PHIs;
4731 for (User *U : Cur->users()) {
4732 Instruction *UI = cast<Instruction>(U);
4734 // Check if we found the exit user.
4735 BasicBlock *Parent = UI->getParent();
4736 if (!TheLoop->contains(Parent)) {
4737 // Exit if you find multiple outside users or if the header phi node is
4738 // being used. In this case the user uses the value of the previous
4739 // iteration, in which case we would loose "VF-1" iterations of the
4740 // reduction operation if we vectorize.
4741 if (ExitInstruction != nullptr || Cur == Phi)
4744 // The instruction used by an outside user must be the last instruction
4745 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4746 // operations on the value.
4747 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4750 ExitInstruction = Cur;
4754 // Process instructions only once (termination). Each reduction cycle
4755 // value must only be used once, except by phi nodes and min/max
4756 // reductions which are represented as a cmp followed by a select.
4757 ReductionInstDesc IgnoredVal(false, nullptr);
4758 if (VisitedInsts.insert(UI)) {
4759 if (isa<PHINode>(UI))
4762 NonPHIs.push_back(UI);
4763 } else if (!isa<PHINode>(UI) &&
4764 ((!isa<FCmpInst>(UI) &&
4765 !isa<ICmpInst>(UI) &&
4766 !isa<SelectInst>(UI)) ||
4767 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4770 // Remember that we completed the cycle.
4772 FoundStartPHI = true;
4774 Worklist.append(PHIs.begin(), PHIs.end());
4775 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4778 // This means we have seen one but not the other instruction of the
4779 // pattern or more than just a select and cmp.
4780 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4781 NumCmpSelectPatternInst != 2)
4784 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4787 // We found a reduction var if we have reached the original phi node and we
4788 // only have a single instruction with out-of-loop users.
4790 // This instruction is allowed to have out-of-loop users.
4791 AllowedExit.insert(ExitInstruction);
4793 // Save the description of this reduction variable.
4794 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4795 ReduxDesc.MinMaxKind);
4796 Reductions[Phi] = RD;
4797 // We've ended the cycle. This is a reduction variable if we have an
4798 // outside user and it has a binary op.
4803 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4804 /// pattern corresponding to a min(X, Y) or max(X, Y).
4805 LoopVectorizationLegality::ReductionInstDesc
4806 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4807 ReductionInstDesc &Prev) {
4809 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4810 "Expect a select instruction");
4811 Instruction *Cmp = nullptr;
4812 SelectInst *Select = nullptr;
4814 // We must handle the select(cmp()) as a single instruction. Advance to the
4816 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4817 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4818 return ReductionInstDesc(false, I);
4819 return ReductionInstDesc(Select, Prev.MinMaxKind);
4822 // Only handle single use cases for now.
4823 if (!(Select = dyn_cast<SelectInst>(I)))
4824 return ReductionInstDesc(false, I);
4825 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4826 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4827 return ReductionInstDesc(false, I);
4828 if (!Cmp->hasOneUse())
4829 return ReductionInstDesc(false, I);
4834 // Look for a min/max pattern.
4835 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4836 return ReductionInstDesc(Select, MRK_UIntMin);
4837 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4838 return ReductionInstDesc(Select, MRK_UIntMax);
4839 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4840 return ReductionInstDesc(Select, MRK_SIntMax);
4841 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4842 return ReductionInstDesc(Select, MRK_SIntMin);
4843 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4844 return ReductionInstDesc(Select, MRK_FloatMin);
4845 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4846 return ReductionInstDesc(Select, MRK_FloatMax);
4847 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4848 return ReductionInstDesc(Select, MRK_FloatMin);
4849 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4850 return ReductionInstDesc(Select, MRK_FloatMax);
4852 return ReductionInstDesc(false, I);
4855 LoopVectorizationLegality::ReductionInstDesc
4856 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4858 ReductionInstDesc &Prev) {
4859 bool FP = I->getType()->isFloatingPointTy();
4860 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4861 switch (I->getOpcode()) {
4863 return ReductionInstDesc(false, I);
4864 case Instruction::PHI:
4865 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4866 Kind != RK_FloatMinMax))
4867 return ReductionInstDesc(false, I);
4868 return ReductionInstDesc(I, Prev.MinMaxKind);
4869 case Instruction::Sub:
4870 case Instruction::Add:
4871 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4872 case Instruction::Mul:
4873 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4874 case Instruction::And:
4875 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4876 case Instruction::Or:
4877 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4878 case Instruction::Xor:
4879 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4880 case Instruction::FMul:
4881 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4882 case Instruction::FAdd:
4883 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4884 case Instruction::FCmp:
4885 case Instruction::ICmp:
4886 case Instruction::Select:
4887 if (Kind != RK_IntegerMinMax &&
4888 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4889 return ReductionInstDesc(false, I);
4890 return isMinMaxSelectCmpPattern(I, Prev);
4894 LoopVectorizationLegality::InductionKind
4895 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4896 Type *PhiTy = Phi->getType();
4897 // We only handle integer and pointer inductions variables.
4898 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4899 return IK_NoInduction;
4901 // Check that the PHI is consecutive.
4902 const SCEV *PhiScev = SE->getSCEV(Phi);
4903 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4905 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4906 return IK_NoInduction;
4908 const SCEV *Step = AR->getStepRecurrence(*SE);
4910 // Integer inductions need to have a stride of one.
4911 if (PhiTy->isIntegerTy()) {
4913 return IK_IntInduction;
4914 if (Step->isAllOnesValue())
4915 return IK_ReverseIntInduction;
4916 return IK_NoInduction;
4919 // Calculate the pointer stride and check if it is consecutive.
4920 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4922 return IK_NoInduction;
4924 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4925 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4926 if (C->getValue()->equalsInt(Size))
4927 return IK_PtrInduction;
4928 else if (C->getValue()->equalsInt(0 - Size))
4929 return IK_ReversePtrInduction;
4931 return IK_NoInduction;
4934 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4935 Value *In0 = const_cast<Value*>(V);
4936 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4940 return Inductions.count(PN);
4943 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4944 assert(TheLoop->contains(BB) && "Unknown block used");
4946 // Blocks that do not dominate the latch need predication.
4947 BasicBlock* Latch = TheLoop->getLoopLatch();
4948 return !DT->dominates(BB, Latch);
4951 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4952 SmallPtrSet<Value *, 8>& SafePtrs) {
4953 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4954 // We might be able to hoist the load.
4955 if (it->mayReadFromMemory()) {
4956 LoadInst *LI = dyn_cast<LoadInst>(it);
4957 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4961 // We don't predicate stores at the moment.
4962 if (it->mayWriteToMemory()) {
4963 StoreInst *SI = dyn_cast<StoreInst>(it);
4964 // We only support predication of stores in basic blocks with one
4966 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
4967 !SafePtrs.count(SI->getPointerOperand()) ||
4968 !SI->getParent()->getSinglePredecessor())
4974 // Check that we don't have a constant expression that can trap as operand.
4975 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4977 if (Constant *C = dyn_cast<Constant>(*OI))
4982 // The instructions below can trap.
4983 switch (it->getOpcode()) {
4985 case Instruction::UDiv:
4986 case Instruction::SDiv:
4987 case Instruction::URem:
4988 case Instruction::SRem:
4996 LoopVectorizationCostModel::VectorizationFactor
4997 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4999 bool ForceVectorization) {
5000 // Width 1 means no vectorize
5001 VectorizationFactor Factor = { 1U, 0U };
5002 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
5003 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
5007 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
5008 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5012 // Find the trip count.
5013 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
5014 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5016 unsigned WidestType = getWidestType();
5017 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5018 unsigned MaxSafeDepDist = -1U;
5019 if (Legal->getMaxSafeDepDistBytes() != -1U)
5020 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5021 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5022 WidestRegister : MaxSafeDepDist);
5023 unsigned MaxVectorSize = WidestRegister / WidestType;
5024 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5025 DEBUG(dbgs() << "LV: The Widest register is: "
5026 << WidestRegister << " bits.\n");
5028 if (MaxVectorSize == 0) {
5029 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5033 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
5034 " into one vector!");
5036 unsigned VF = MaxVectorSize;
5038 // If we optimize the program for size, avoid creating the tail loop.
5040 // If we are unable to calculate the trip count then don't try to vectorize.
5042 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5046 // Find the maximum SIMD width that can fit within the trip count.
5047 VF = TC % MaxVectorSize;
5052 // If the trip count that we found modulo the vectorization factor is not
5053 // zero then we require a tail.
5055 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5061 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5062 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5064 Factor.Width = UserVF;
5068 float Cost = expectedCost(1);
5070 const float ScalarCost = Cost;
5073 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5075 // Ignore scalar width, because the user explicitly wants vectorization.
5076 if (ForceVectorization && VF > 1) {
5078 Cost = expectedCost(Width) / (float)Width;
5081 for (unsigned i=2; i <= VF; i*=2) {
5082 // Notice that the vector loop needs to be executed less times, so
5083 // we need to divide the cost of the vector loops by the width of
5084 // the vector elements.
5085 float VectorCost = expectedCost(i) / (float)i;
5086 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5087 (int)VectorCost << ".\n");
5088 if (VectorCost < Cost) {
5094 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5095 << "LV: Vectorization seems to be not beneficial, "
5096 << "but was forced by a user.\n");
5097 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5098 Factor.Width = Width;
5099 Factor.Cost = Width * Cost;
5103 unsigned LoopVectorizationCostModel::getWidestType() {
5104 unsigned MaxWidth = 8;
5107 for (Loop::block_iterator bb = TheLoop->block_begin(),
5108 be = TheLoop->block_end(); bb != be; ++bb) {
5109 BasicBlock *BB = *bb;
5111 // For each instruction in the loop.
5112 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5113 Type *T = it->getType();
5115 // Only examine Loads, Stores and PHINodes.
5116 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5119 // Examine PHI nodes that are reduction variables.
5120 if (PHINode *PN = dyn_cast<PHINode>(it))
5121 if (!Legal->getReductionVars()->count(PN))
5124 // Examine the stored values.
5125 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5126 T = ST->getValueOperand()->getType();
5128 // Ignore loaded pointer types and stored pointer types that are not
5129 // consecutive. However, we do want to take consecutive stores/loads of
5130 // pointer vectors into account.
5131 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5134 MaxWidth = std::max(MaxWidth,
5135 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5143 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5146 unsigned LoopCost) {
5148 // -- The unroll heuristics --
5149 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5150 // There are many micro-architectural considerations that we can't predict
5151 // at this level. For example frontend pressure (on decode or fetch) due to
5152 // code size, or the number and capabilities of the execution ports.
5154 // We use the following heuristics to select the unroll factor:
5155 // 1. If the code has reductions the we unroll in order to break the cross
5156 // iteration dependency.
5157 // 2. If the loop is really small then we unroll in order to reduce the loop
5159 // 3. We don't unroll if we think that we will spill registers to memory due
5160 // to the increased register pressure.
5162 // Use the user preference, unless 'auto' is selected.
5166 // When we optimize for size we don't unroll.
5170 // We used the distance for the unroll factor.
5171 if (Legal->getMaxSafeDepDistBytes() != -1U)
5174 // Do not unroll loops with a relatively small trip count.
5175 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5176 TheLoop->getLoopLatch());
5177 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5180 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5181 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5185 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5186 TargetNumRegisters = ForceTargetNumScalarRegs;
5188 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5189 TargetNumRegisters = ForceTargetNumVectorRegs;
5192 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5193 // We divide by these constants so assume that we have at least one
5194 // instruction that uses at least one register.
5195 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5196 R.NumInstructions = std::max(R.NumInstructions, 1U);
5198 // We calculate the unroll factor using the following formula.
5199 // Subtract the number of loop invariants from the number of available
5200 // registers. These registers are used by all of the unrolled instances.
5201 // Next, divide the remaining registers by the number of registers that is
5202 // required by the loop, in order to estimate how many parallel instances
5203 // fit without causing spills. All of this is rounded down if necessary to be
5204 // a power of two. We want power of two unroll factors to simplify any
5205 // addressing operations or alignment considerations.
5206 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5209 // Don't count the induction variable as unrolled.
5210 if (EnableIndVarRegisterHeur)
5211 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5212 std::max(1U, (R.MaxLocalUsers - 1)));
5214 // Clamp the unroll factor ranges to reasonable factors.
5215 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5217 // Check if the user has overridden the unroll max.
5219 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5220 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5222 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5223 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5226 // If we did not calculate the cost for VF (because the user selected the VF)
5227 // then we calculate the cost of VF here.
5229 LoopCost = expectedCost(VF);
5231 // Clamp the calculated UF to be between the 1 and the max unroll factor
5232 // that the target allows.
5233 if (UF > MaxUnrollSize)
5238 // Unroll if we vectorized this loop and there is a reduction that could
5239 // benefit from unrolling.
5240 if (VF > 1 && Legal->getReductionVars()->size()) {
5241 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5245 // Note that if we've already vectorized the loop we will have done the
5246 // runtime check and so unrolling won't require further checks.
5247 bool UnrollingRequiresRuntimePointerCheck =
5248 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5250 // We want to unroll small loops in order to reduce the loop overhead and
5251 // potentially expose ILP opportunities.
5252 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5253 if (!UnrollingRequiresRuntimePointerCheck &&
5254 LoopCost < SmallLoopCost) {
5255 // We assume that the cost overhead is 1 and we use the cost model
5256 // to estimate the cost of the loop and unroll until the cost of the
5257 // loop overhead is about 5% of the cost of the loop.
5258 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5260 // Unroll until store/load ports (estimated by max unroll factor) are
5262 unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5263 unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5265 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5266 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5267 return std::max(StoresUF, LoadsUF);
5270 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5274 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5278 LoopVectorizationCostModel::RegisterUsage
5279 LoopVectorizationCostModel::calculateRegisterUsage() {
5280 // This function calculates the register usage by measuring the highest number
5281 // of values that are alive at a single location. Obviously, this is a very
5282 // rough estimation. We scan the loop in a topological order in order and
5283 // assign a number to each instruction. We use RPO to ensure that defs are
5284 // met before their users. We assume that each instruction that has in-loop
5285 // users starts an interval. We record every time that an in-loop value is
5286 // used, so we have a list of the first and last occurrences of each
5287 // instruction. Next, we transpose this data structure into a multi map that
5288 // holds the list of intervals that *end* at a specific location. This multi
5289 // map allows us to perform a linear search. We scan the instructions linearly
5290 // and record each time that a new interval starts, by placing it in a set.
5291 // If we find this value in the multi-map then we remove it from the set.
5292 // The max register usage is the maximum size of the set.
5293 // We also search for instructions that are defined outside the loop, but are
5294 // used inside the loop. We need this number separately from the max-interval
5295 // usage number because when we unroll, loop-invariant values do not take
5297 LoopBlocksDFS DFS(TheLoop);
5301 R.NumInstructions = 0;
5303 // Each 'key' in the map opens a new interval. The values
5304 // of the map are the index of the 'last seen' usage of the
5305 // instruction that is the key.
5306 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5307 // Maps instruction to its index.
5308 DenseMap<unsigned, Instruction*> IdxToInstr;
5309 // Marks the end of each interval.
5310 IntervalMap EndPoint;
5311 // Saves the list of instruction indices that are used in the loop.
5312 SmallSet<Instruction*, 8> Ends;
5313 // Saves the list of values that are used in the loop but are
5314 // defined outside the loop, such as arguments and constants.
5315 SmallPtrSet<Value*, 8> LoopInvariants;
5318 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5319 be = DFS.endRPO(); bb != be; ++bb) {
5320 R.NumInstructions += (*bb)->size();
5321 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5323 Instruction *I = it;
5324 IdxToInstr[Index++] = I;
5326 // Save the end location of each USE.
5327 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5328 Value *U = I->getOperand(i);
5329 Instruction *Instr = dyn_cast<Instruction>(U);
5331 // Ignore non-instruction values such as arguments, constants, etc.
5332 if (!Instr) continue;
5334 // If this instruction is outside the loop then record it and continue.
5335 if (!TheLoop->contains(Instr)) {
5336 LoopInvariants.insert(Instr);
5340 // Overwrite previous end points.
5341 EndPoint[Instr] = Index;
5347 // Saves the list of intervals that end with the index in 'key'.
5348 typedef SmallVector<Instruction*, 2> InstrList;
5349 DenseMap<unsigned, InstrList> TransposeEnds;
5351 // Transpose the EndPoints to a list of values that end at each index.
5352 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5354 TransposeEnds[it->second].push_back(it->first);
5356 SmallSet<Instruction*, 8> OpenIntervals;
5357 unsigned MaxUsage = 0;
5360 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5361 for (unsigned int i = 0; i < Index; ++i) {
5362 Instruction *I = IdxToInstr[i];
5363 // Ignore instructions that are never used within the loop.
5364 if (!Ends.count(I)) continue;
5366 // Remove all of the instructions that end at this location.
5367 InstrList &List = TransposeEnds[i];
5368 for (unsigned int j=0, e = List.size(); j < e; ++j)
5369 OpenIntervals.erase(List[j]);
5371 // Count the number of live interals.
5372 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5374 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5375 OpenIntervals.size() << '\n');
5377 // Add the current instruction to the list of open intervals.
5378 OpenIntervals.insert(I);
5381 unsigned Invariant = LoopInvariants.size();
5382 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5383 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5384 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5386 R.LoopInvariantRegs = Invariant;
5387 R.MaxLocalUsers = MaxUsage;
5391 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5395 for (Loop::block_iterator bb = TheLoop->block_begin(),
5396 be = TheLoop->block_end(); bb != be; ++bb) {
5397 unsigned BlockCost = 0;
5398 BasicBlock *BB = *bb;
5400 // For each instruction in the old loop.
5401 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5402 // Skip dbg intrinsics.
5403 if (isa<DbgInfoIntrinsic>(it))
5406 unsigned C = getInstructionCost(it, VF);
5408 // Check if we should override the cost.
5409 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5410 C = ForceTargetInstructionCost;
5413 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5414 VF << " For instruction: " << *it << '\n');
5417 // We assume that if-converted blocks have a 50% chance of being executed.
5418 // When the code is scalar then some of the blocks are avoided due to CF.
5419 // When the code is vectorized we execute all code paths.
5420 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5429 /// \brief Check whether the address computation for a non-consecutive memory
5430 /// access looks like an unlikely candidate for being merged into the indexing
5433 /// We look for a GEP which has one index that is an induction variable and all
5434 /// other indices are loop invariant. If the stride of this access is also
5435 /// within a small bound we decide that this address computation can likely be
5436 /// merged into the addressing mode.
5437 /// In all other cases, we identify the address computation as complex.
5438 static bool isLikelyComplexAddressComputation(Value *Ptr,
5439 LoopVectorizationLegality *Legal,
5440 ScalarEvolution *SE,
5441 const Loop *TheLoop) {
5442 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5446 // We are looking for a gep with all loop invariant indices except for one
5447 // which should be an induction variable.
5448 unsigned NumOperands = Gep->getNumOperands();
5449 for (unsigned i = 1; i < NumOperands; ++i) {
5450 Value *Opd = Gep->getOperand(i);
5451 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5452 !Legal->isInductionVariable(Opd))
5456 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5457 // can likely be merged into the address computation.
5458 unsigned MaxMergeDistance = 64;
5460 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5464 // Check the step is constant.
5465 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5466 // Calculate the pointer stride and check if it is consecutive.
5467 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5471 const APInt &APStepVal = C->getValue()->getValue();
5473 // Huge step value - give up.
5474 if (APStepVal.getBitWidth() > 64)
5477 int64_t StepVal = APStepVal.getSExtValue();
5479 return StepVal > MaxMergeDistance;
5482 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5483 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5489 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5490 // If we know that this instruction will remain uniform, check the cost of
5491 // the scalar version.
5492 if (Legal->isUniformAfterVectorization(I))
5495 Type *RetTy = I->getType();
5496 Type *VectorTy = ToVectorTy(RetTy, VF);
5498 // TODO: We need to estimate the cost of intrinsic calls.
5499 switch (I->getOpcode()) {
5500 case Instruction::GetElementPtr:
5501 // We mark this instruction as zero-cost because the cost of GEPs in
5502 // vectorized code depends on whether the corresponding memory instruction
5503 // is scalarized or not. Therefore, we handle GEPs with the memory
5504 // instruction cost.
5506 case Instruction::Br: {
5507 return TTI.getCFInstrCost(I->getOpcode());
5509 case Instruction::PHI:
5510 //TODO: IF-converted IFs become selects.
5512 case Instruction::Add:
5513 case Instruction::FAdd:
5514 case Instruction::Sub:
5515 case Instruction::FSub:
5516 case Instruction::Mul:
5517 case Instruction::FMul:
5518 case Instruction::UDiv:
5519 case Instruction::SDiv:
5520 case Instruction::FDiv:
5521 case Instruction::URem:
5522 case Instruction::SRem:
5523 case Instruction::FRem:
5524 case Instruction::Shl:
5525 case Instruction::LShr:
5526 case Instruction::AShr:
5527 case Instruction::And:
5528 case Instruction::Or:
5529 case Instruction::Xor: {
5530 // Since we will replace the stride by 1 the multiplication should go away.
5531 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5533 // Certain instructions can be cheaper to vectorize if they have a constant
5534 // second vector operand. One example of this are shifts on x86.
5535 TargetTransformInfo::OperandValueKind Op1VK =
5536 TargetTransformInfo::OK_AnyValue;
5537 TargetTransformInfo::OperandValueKind Op2VK =
5538 TargetTransformInfo::OK_AnyValue;
5539 Value *Op2 = I->getOperand(1);
5541 // Check for a splat of a constant or for a non uniform vector of constants.
5542 if (isa<ConstantInt>(Op2))
5543 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5544 else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5545 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5546 if (cast<Constant>(Op2)->getSplatValue() != nullptr)
5547 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5550 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5552 case Instruction::Select: {
5553 SelectInst *SI = cast<SelectInst>(I);
5554 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5555 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5556 Type *CondTy = SI->getCondition()->getType();
5558 CondTy = VectorType::get(CondTy, VF);
5560 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5562 case Instruction::ICmp:
5563 case Instruction::FCmp: {
5564 Type *ValTy = I->getOperand(0)->getType();
5565 VectorTy = ToVectorTy(ValTy, VF);
5566 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5568 case Instruction::Store:
5569 case Instruction::Load: {
5570 StoreInst *SI = dyn_cast<StoreInst>(I);
5571 LoadInst *LI = dyn_cast<LoadInst>(I);
5572 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5574 VectorTy = ToVectorTy(ValTy, VF);
5576 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5577 unsigned AS = SI ? SI->getPointerAddressSpace() :
5578 LI->getPointerAddressSpace();
5579 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5580 // We add the cost of address computation here instead of with the gep
5581 // instruction because only here we know whether the operation is
5584 return TTI.getAddressComputationCost(VectorTy) +
5585 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5587 // Scalarized loads/stores.
5588 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5589 bool Reverse = ConsecutiveStride < 0;
5590 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5591 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5592 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5593 bool IsComplexComputation =
5594 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5596 // The cost of extracting from the value vector and pointer vector.
5597 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5598 for (unsigned i = 0; i < VF; ++i) {
5599 // The cost of extracting the pointer operand.
5600 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5601 // In case of STORE, the cost of ExtractElement from the vector.
5602 // In case of LOAD, the cost of InsertElement into the returned
5604 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5605 Instruction::InsertElement,
5609 // The cost of the scalar loads/stores.
5610 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5611 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5616 // Wide load/stores.
5617 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5618 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5621 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5625 case Instruction::ZExt:
5626 case Instruction::SExt:
5627 case Instruction::FPToUI:
5628 case Instruction::FPToSI:
5629 case Instruction::FPExt:
5630 case Instruction::PtrToInt:
5631 case Instruction::IntToPtr:
5632 case Instruction::SIToFP:
5633 case Instruction::UIToFP:
5634 case Instruction::Trunc:
5635 case Instruction::FPTrunc:
5636 case Instruction::BitCast: {
5637 // We optimize the truncation of induction variable.
5638 // The cost of these is the same as the scalar operation.
5639 if (I->getOpcode() == Instruction::Trunc &&
5640 Legal->isInductionVariable(I->getOperand(0)))
5641 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5642 I->getOperand(0)->getType());
5644 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5645 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5647 case Instruction::Call: {
5648 CallInst *CI = cast<CallInst>(I);
5649 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5650 assert(ID && "Not an intrinsic call!");
5651 Type *RetTy = ToVectorTy(CI->getType(), VF);
5652 SmallVector<Type*, 4> Tys;
5653 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5654 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5655 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5658 // We are scalarizing the instruction. Return the cost of the scalar
5659 // instruction, plus the cost of insert and extract into vector
5660 // elements, times the vector width.
5663 if (!RetTy->isVoidTy() && VF != 1) {
5664 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5666 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5669 // The cost of inserting the results plus extracting each one of the
5671 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5674 // The cost of executing VF copies of the scalar instruction. This opcode
5675 // is unknown. Assume that it is the same as 'mul'.
5676 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5682 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5683 if (Scalar->isVoidTy() || VF == 1)
5685 return VectorType::get(Scalar, VF);
5688 char LoopVectorize::ID = 0;
5689 static const char lv_name[] = "Loop Vectorization";
5690 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5691 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5692 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5693 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5694 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5695 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5696 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5697 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5698 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5701 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5702 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5706 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5707 // Check for a store.
5708 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5709 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5711 // Check for a load.
5712 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5713 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5719 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5720 bool IfPredicateStore) {
5721 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5722 // Holds vector parameters or scalars, in case of uniform vals.
5723 SmallVector<VectorParts, 4> Params;
5725 setDebugLocFromInst(Builder, Instr);
5727 // Find all of the vectorized parameters.
5728 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5729 Value *SrcOp = Instr->getOperand(op);
5731 // If we are accessing the old induction variable, use the new one.
5732 if (SrcOp == OldInduction) {
5733 Params.push_back(getVectorValue(SrcOp));
5737 // Try using previously calculated values.
5738 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5740 // If the src is an instruction that appeared earlier in the basic block
5741 // then it should already be vectorized.
5742 if (SrcInst && OrigLoop->contains(SrcInst)) {
5743 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5744 // The parameter is a vector value from earlier.
5745 Params.push_back(WidenMap.get(SrcInst));
5747 // The parameter is a scalar from outside the loop. Maybe even a constant.
5748 VectorParts Scalars;
5749 Scalars.append(UF, SrcOp);
5750 Params.push_back(Scalars);
5754 assert(Params.size() == Instr->getNumOperands() &&
5755 "Invalid number of operands");
5757 // Does this instruction return a value ?
5758 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5760 Value *UndefVec = IsVoidRetTy ? nullptr :
5761 UndefValue::get(Instr->getType());
5762 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5763 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5765 Instruction *InsertPt = Builder.GetInsertPoint();
5766 BasicBlock *IfBlock = Builder.GetInsertBlock();
5767 BasicBlock *CondBlock = nullptr;
5770 Loop *VectorLp = nullptr;
5771 if (IfPredicateStore) {
5772 assert(Instr->getParent()->getSinglePredecessor() &&
5773 "Only support single predecessor blocks");
5774 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5775 Instr->getParent());
5776 VectorLp = LI->getLoopFor(IfBlock);
5777 assert(VectorLp && "Must have a loop for this block");
5780 // For each vector unroll 'part':
5781 for (unsigned Part = 0; Part < UF; ++Part) {
5782 // For each scalar that we create:
5784 // Start an "if (pred) a[i] = ..." block.
5785 Value *Cmp = nullptr;
5786 if (IfPredicateStore) {
5787 if (Cond[Part]->getType()->isVectorTy())
5789 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5790 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5791 ConstantInt::get(Cond[Part]->getType(), 1));
5792 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5793 LoopVectorBody.push_back(CondBlock);
5794 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
5795 // Update Builder with newly created basic block.
5796 Builder.SetInsertPoint(InsertPt);
5799 Instruction *Cloned = Instr->clone();
5801 Cloned->setName(Instr->getName() + ".cloned");
5802 // Replace the operands of the cloned instructions with extracted scalars.
5803 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5804 Value *Op = Params[op][Part];
5805 Cloned->setOperand(op, Op);
5808 // Place the cloned scalar in the new loop.
5809 Builder.Insert(Cloned);
5811 // If the original scalar returns a value we need to place it in a vector
5812 // so that future users will be able to use it.
5814 VecResults[Part] = Cloned;
5817 if (IfPredicateStore) {
5818 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5819 LoopVectorBody.push_back(NewIfBlock);
5820 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
5821 Builder.SetInsertPoint(InsertPt);
5822 Instruction *OldBr = IfBlock->getTerminator();
5823 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5824 OldBr->eraseFromParent();
5825 IfBlock = NewIfBlock;
5830 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5831 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5832 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5834 return scalarizeInstruction(Instr, IfPredicateStore);
5837 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5841 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5845 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5847 // When unrolling and the VF is 1, we only need to add a simple scalar.
5848 Type *ITy = Val->getType();
5849 assert(!ITy->isVectorTy() && "Val must be a scalar");
5850 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5851 return Builder.CreateAdd(Val, C, "induction");