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/Dominators.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/LLVMContext.h"
76 #include "llvm/IR/Module.h"
77 #include "llvm/IR/PatternMatch.h"
78 #include "llvm/IR/Type.h"
79 #include "llvm/IR/Value.h"
80 #include "llvm/IR/ValueHandle.h"
81 #include "llvm/IR/Verifier.h"
82 #include "llvm/Pass.h"
83 #include "llvm/Support/BranchProbability.h"
84 #include "llvm/Support/CommandLine.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Transforms/Scalar.h"
88 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/VectorUtils.h"
96 using namespace llvm::PatternMatch;
98 #define LV_NAME "loop-vectorize"
99 #define DEBUG_TYPE LV_NAME
101 STATISTIC(LoopsVectorized, "Number of loops vectorized");
102 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
104 static cl::opt<unsigned>
105 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
106 cl::desc("Sets the SIMD width. Zero is autoselect."));
108 static cl::opt<unsigned>
109 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
110 cl::desc("Sets the vectorization unroll count. "
111 "Zero is autoselect."));
114 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
115 cl::desc("Enable if-conversion during vectorization."));
117 /// We don't vectorize loops with a known constant trip count below this number.
118 static cl::opt<unsigned>
119 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
121 cl::desc("Don't vectorize loops with a constant "
122 "trip count that is smaller than this "
125 /// This enables versioning on the strides of symbolically striding memory
126 /// accesses in code like the following.
127 /// for (i = 0; i < N; ++i)
128 /// A[i * Stride1] += B[i * Stride2] ...
130 /// Will be roughly translated to
131 /// if (Stride1 == 1 && Stride2 == 1) {
132 /// for (i = 0; i < N; i+=4)
136 static cl::opt<bool> EnableMemAccessVersioning(
137 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
138 cl::desc("Enable symblic stride memory access versioning"));
140 /// We don't unroll loops with a known constant trip count below this number.
141 static const unsigned TinyTripCountUnrollThreshold = 128;
143 /// When performing memory disambiguation checks at runtime do not make more
144 /// than this number of comparisons.
145 static const unsigned RuntimeMemoryCheckThreshold = 8;
147 /// Maximum simd width.
148 static const unsigned MaxVectorWidth = 64;
150 static cl::opt<unsigned> ForceTargetNumScalarRegs(
151 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
152 cl::desc("A flag that overrides the target's number of scalar registers."));
154 static cl::opt<unsigned> ForceTargetNumVectorRegs(
155 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
156 cl::desc("A flag that overrides the target's number of vector registers."));
158 /// Maximum vectorization unroll count.
159 static const unsigned MaxUnrollFactor = 16;
161 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
162 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
163 cl::desc("A flag that overrides the target's max unroll factor for scalar "
166 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
167 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
168 cl::desc("A flag that overrides the target's max unroll factor for "
169 "vectorized loops."));
171 static cl::opt<unsigned> ForceTargetInstructionCost(
172 "force-target-instruction-cost", cl::init(0), cl::Hidden,
173 cl::desc("A flag that overrides the target's expected cost for "
174 "an instruction to a single constant value. Mostly "
175 "useful for getting consistent testing."));
177 static cl::opt<unsigned> SmallLoopCost(
178 "small-loop-cost", cl::init(20), cl::Hidden,
179 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
181 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
182 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
183 cl::desc("Enable the use of the block frequency analysis to access PGO "
184 "heuristics minimizing code growth in cold regions and being more "
185 "aggressive in hot regions."));
187 // Runtime unroll loops for load/store throughput.
188 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
189 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
190 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
192 /// The number of stores in a loop that are allowed to need predication.
193 static cl::opt<unsigned> NumberOfStoresToPredicate(
194 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
195 cl::desc("Max number of stores to be predicated behind an if."));
197 static cl::opt<bool> EnableIndVarRegisterHeur(
198 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
199 cl::desc("Count the induction variable only once when unrolling"));
201 static cl::opt<bool> EnableCondStoresVectorization(
202 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
203 cl::desc("Enable if predication of stores during vectorization."));
207 // Forward declarations.
208 class LoopVectorizationLegality;
209 class LoopVectorizationCostModel;
211 /// InnerLoopVectorizer vectorizes loops which contain only one basic
212 /// block to a specified vectorization factor (VF).
213 /// This class performs the widening of scalars into vectors, or multiple
214 /// scalars. This class also implements the following features:
215 /// * It inserts an epilogue loop for handling loops that don't have iteration
216 /// counts that are known to be a multiple of the vectorization factor.
217 /// * It handles the code generation for reduction variables.
218 /// * Scalarization (implementation using scalars) of un-vectorizable
220 /// InnerLoopVectorizer does not perform any vectorization-legality
221 /// checks, and relies on the caller to check for the different legality
222 /// aspects. The InnerLoopVectorizer relies on the
223 /// LoopVectorizationLegality class to provide information about the induction
224 /// and reduction variables that were found to a given vectorization factor.
225 class InnerLoopVectorizer {
227 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
228 DominatorTree *DT, const DataLayout *DL,
229 const TargetLibraryInfo *TLI, unsigned VecWidth,
230 unsigned UnrollFactor)
231 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
232 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
233 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
236 // Perform the actual loop widening (vectorization).
237 void vectorize(LoopVectorizationLegality *L) {
239 // Create a new empty loop. Unlink the old loop and connect the new one.
241 // Widen each instruction in the old loop to a new one in the new loop.
242 // Use the Legality module to find the induction and reduction variables.
244 // Register the new loop and update the analysis passes.
248 virtual ~InnerLoopVectorizer() {}
251 /// A small list of PHINodes.
252 typedef SmallVector<PHINode*, 4> PhiVector;
253 /// When we unroll loops we have multiple vector values for each scalar.
254 /// This data structure holds the unrolled and vectorized values that
255 /// originated from one scalar instruction.
256 typedef SmallVector<Value*, 2> VectorParts;
258 // When we if-convert we need create edge masks. We have to cache values so
259 // that we don't end up with exponential recursion/IR.
260 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
261 VectorParts> EdgeMaskCache;
263 /// \brief Add code that checks at runtime if the accessed arrays overlap.
265 /// Returns a pair of instructions where the first element is the first
266 /// instruction generated in possibly a sequence of instructions and the
267 /// second value is the final comparator value or NULL if no check is needed.
268 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
270 /// \brief Add checks for strides that where assumed to be 1.
272 /// Returns the last check instruction and the first check instruction in the
273 /// pair as (first, last).
274 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
276 /// Create an empty loop, based on the loop ranges of the old loop.
277 void createEmptyLoop();
278 /// Copy and widen the instructions from the old loop.
279 virtual void vectorizeLoop();
281 /// \brief The Loop exit block may have single value PHI nodes where the
282 /// incoming value is 'Undef'. While vectorizing we only handled real values
283 /// that were defined inside the loop. Here we fix the 'undef case'.
287 /// A helper function that computes the predicate of the block BB, assuming
288 /// that the header block of the loop is set to True. It returns the *entry*
289 /// mask for the block BB.
290 VectorParts createBlockInMask(BasicBlock *BB);
291 /// A helper function that computes the predicate of the edge between SRC
293 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
295 /// A helper function to vectorize a single BB within the innermost loop.
296 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
298 /// Vectorize a single PHINode in a block. This method handles the induction
299 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
300 /// arbitrary length vectors.
301 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
302 unsigned UF, unsigned VF, PhiVector *PV);
304 /// Insert the new loop to the loop hierarchy and pass manager
305 /// and update the analysis passes.
306 void updateAnalysis();
308 /// This instruction is un-vectorizable. Implement it as a sequence
309 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
310 /// scalarized instruction behind an if block predicated on the control
311 /// dependence of the instruction.
312 virtual void scalarizeInstruction(Instruction *Instr,
313 bool IfPredicateStore=false);
315 /// Vectorize Load and Store instructions,
316 virtual void vectorizeMemoryInstruction(Instruction *Instr);
318 /// Create a broadcast instruction. This method generates a broadcast
319 /// instruction (shuffle) for loop invariant values and for the induction
320 /// value. If this is the induction variable then we extend it to N, N+1, ...
321 /// this is needed because each iteration in the loop corresponds to a SIMD
323 virtual Value *getBroadcastInstrs(Value *V);
325 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
326 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
327 /// The sequence starts at StartIndex.
328 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
330 /// When we go over instructions in the basic block we rely on previous
331 /// values within the current basic block or on loop invariant values.
332 /// When we widen (vectorize) values we place them in the map. If the values
333 /// are not within the map, they have to be loop invariant, so we simply
334 /// broadcast them into a vector.
335 VectorParts &getVectorValue(Value *V);
337 /// Generate a shuffle sequence that will reverse the vector Vec.
338 virtual Value *reverseVector(Value *Vec);
340 /// This is a helper class that holds the vectorizer state. It maps scalar
341 /// instructions to vector instructions. When the code is 'unrolled' then
342 /// then a single scalar value is mapped to multiple vector parts. The parts
343 /// are stored in the VectorPart type.
345 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
347 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
349 /// \return True if 'Key' is saved in the Value Map.
350 bool has(Value *Key) const { return MapStorage.count(Key); }
352 /// Initializes a new entry in the map. Sets all of the vector parts to the
353 /// save value in 'Val'.
354 /// \return A reference to a vector with splat values.
355 VectorParts &splat(Value *Key, Value *Val) {
356 VectorParts &Entry = MapStorage[Key];
357 Entry.assign(UF, Val);
361 ///\return A reference to the value that is stored at 'Key'.
362 VectorParts &get(Value *Key) {
363 VectorParts &Entry = MapStorage[Key];
366 assert(Entry.size() == UF);
371 /// The unroll factor. Each entry in the map stores this number of vector
375 /// Map storage. We use std::map and not DenseMap because insertions to a
376 /// dense map invalidates its iterators.
377 std::map<Value *, VectorParts> MapStorage;
380 /// The original loop.
382 /// Scev analysis to use.
389 const DataLayout *DL;
390 /// Target Library Info.
391 const TargetLibraryInfo *TLI;
393 /// The vectorization SIMD factor to use. Each vector will have this many
398 /// The vectorization unroll factor to use. Each scalar is vectorized to this
399 /// many different vector instructions.
402 /// The builder that we use
405 // --- Vectorization state ---
407 /// The vector-loop preheader.
408 BasicBlock *LoopVectorPreHeader;
409 /// The scalar-loop preheader.
410 BasicBlock *LoopScalarPreHeader;
411 /// Middle Block between the vector and the scalar.
412 BasicBlock *LoopMiddleBlock;
413 ///The ExitBlock of the scalar loop.
414 BasicBlock *LoopExitBlock;
415 ///The vector loop body.
416 SmallVector<BasicBlock *, 4> LoopVectorBody;
417 ///The scalar loop body.
418 BasicBlock *LoopScalarBody;
419 /// A list of all bypass blocks. The first block is the entry of the loop.
420 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
422 /// The new Induction variable which was added to the new block.
424 /// The induction variable of the old basic block.
425 PHINode *OldInduction;
426 /// Holds the extended (to the widest induction type) start index.
428 /// Maps scalars to widened vectors.
430 EdgeMaskCache MaskCache;
432 LoopVectorizationLegality *Legal;
435 class InnerLoopUnroller : public InnerLoopVectorizer {
437 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
438 DominatorTree *DT, const DataLayout *DL,
439 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
440 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
443 void scalarizeInstruction(Instruction *Instr,
444 bool IfPredicateStore = false) override;
445 void vectorizeMemoryInstruction(Instruction *Instr) override;
446 Value *getBroadcastInstrs(Value *V) override;
447 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
448 Value *reverseVector(Value *Vec) override;
451 /// \brief Look for a meaningful debug location on the instruction or it's
453 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
458 if (I->getDebugLoc() != Empty)
461 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
462 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
463 if (OpInst->getDebugLoc() != Empty)
470 /// \brief Set the debug location in the builder using the debug location in the
472 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
473 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
474 B.SetCurrentDebugLocation(Inst->getDebugLoc());
476 B.SetCurrentDebugLocation(DebugLoc());
480 /// \return string containing a file name and a line # for the given loop.
481 static std::string getDebugLocString(const Loop *L) {
484 raw_string_ostream OS(Result);
485 const DebugLoc LoopDbgLoc = L->getStartLoc();
486 if (!LoopDbgLoc.isUnknown())
487 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
489 // Just print the module name.
490 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
497 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
498 /// to what vectorization factor.
499 /// This class does not look at the profitability of vectorization, only the
500 /// legality. This class has two main kinds of checks:
501 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
502 /// will change the order of memory accesses in a way that will change the
503 /// correctness of the program.
504 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
505 /// checks for a number of different conditions, such as the availability of a
506 /// single induction variable, that all types are supported and vectorize-able,
507 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
508 /// This class is also used by InnerLoopVectorizer for identifying
509 /// induction variable and the different reduction variables.
510 class LoopVectorizationLegality {
514 unsigned NumPredStores;
516 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
517 DominatorTree *DT, TargetLibraryInfo *TLI)
518 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
519 DT(DT), TLI(TLI), Induction(nullptr), WidestIndTy(nullptr),
520 HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {}
522 /// This enum represents the kinds of reductions that we support.
524 RK_NoReduction, ///< Not a reduction.
525 RK_IntegerAdd, ///< Sum of integers.
526 RK_IntegerMult, ///< Product of integers.
527 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
528 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
529 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
530 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
531 RK_FloatAdd, ///< Sum of floats.
532 RK_FloatMult, ///< Product of floats.
533 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
536 /// This enum represents the kinds of inductions that we support.
538 IK_NoInduction, ///< Not an induction variable.
539 IK_IntInduction, ///< Integer induction variable. Step = 1.
540 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
541 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
542 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
545 // This enum represents the kind of minmax reduction.
546 enum MinMaxReductionKind {
556 /// This struct holds information about reduction variables.
557 struct ReductionDescriptor {
558 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
559 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
561 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
562 MinMaxReductionKind MK)
563 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
565 // The starting value of the reduction.
566 // It does not have to be zero!
567 TrackingVH<Value> StartValue;
568 // The instruction who's value is used outside the loop.
569 Instruction *LoopExitInstr;
570 // The kind of the reduction.
572 // If this a min/max reduction the kind of reduction.
573 MinMaxReductionKind MinMaxKind;
576 /// This POD struct holds information about a potential reduction operation.
577 struct ReductionInstDesc {
578 ReductionInstDesc(bool IsRedux, Instruction *I) :
579 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
581 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
582 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
584 // Is this instruction a reduction candidate.
586 // The last instruction in a min/max pattern (select of the select(icmp())
587 // pattern), or the current reduction instruction otherwise.
588 Instruction *PatternLastInst;
589 // If this is a min/max pattern the comparison predicate.
590 MinMaxReductionKind MinMaxKind;
593 /// This struct holds information about the memory runtime legality
594 /// check that a group of pointers do not overlap.
595 struct RuntimePointerCheck {
596 RuntimePointerCheck() : Need(false) {}
598 /// Reset the state of the pointer runtime information.
605 DependencySetId.clear();
608 /// Insert a pointer and calculate the start and end SCEVs.
609 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
610 unsigned DepSetId, ValueToValueMap &Strides);
612 /// This flag indicates if we need to add the runtime check.
614 /// Holds the pointers that we need to check.
615 SmallVector<TrackingVH<Value>, 2> Pointers;
616 /// Holds the pointer value at the beginning of the loop.
617 SmallVector<const SCEV*, 2> Starts;
618 /// Holds the pointer value at the end of the loop.
619 SmallVector<const SCEV*, 2> Ends;
620 /// Holds the information if this pointer is used for writing to memory.
621 SmallVector<bool, 2> IsWritePtr;
622 /// Holds the id of the set of pointers that could be dependent because of a
623 /// shared underlying object.
624 SmallVector<unsigned, 2> DependencySetId;
627 /// A struct for saving information about induction variables.
628 struct InductionInfo {
629 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
630 InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
632 TrackingVH<Value> StartValue;
637 /// ReductionList contains the reduction descriptors for all
638 /// of the reductions that were found in the loop.
639 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
641 /// InductionList saves induction variables and maps them to the
642 /// induction descriptor.
643 typedef MapVector<PHINode*, InductionInfo> InductionList;
645 /// Returns true if it is legal to vectorize this loop.
646 /// This does not mean that it is profitable to vectorize this
647 /// loop, only that it is legal to do so.
650 /// Returns the Induction variable.
651 PHINode *getInduction() { return Induction; }
653 /// Returns the reduction variables found in the loop.
654 ReductionList *getReductionVars() { return &Reductions; }
656 /// Returns the induction variables found in the loop.
657 InductionList *getInductionVars() { return &Inductions; }
659 /// Returns the widest induction type.
660 Type *getWidestInductionType() { return WidestIndTy; }
662 /// Returns True if V is an induction variable in this loop.
663 bool isInductionVariable(const Value *V);
665 /// Return true if the block BB needs to be predicated in order for the loop
666 /// to be vectorized.
667 bool blockNeedsPredication(BasicBlock *BB);
669 /// Check if this pointer is consecutive when vectorizing. This happens
670 /// when the last index of the GEP is the induction variable, or that the
671 /// pointer itself is an induction variable.
672 /// This check allows us to vectorize A[idx] into a wide load/store.
674 /// 0 - Stride is unknown or non-consecutive.
675 /// 1 - Address is consecutive.
676 /// -1 - Address is consecutive, and decreasing.
677 int isConsecutivePtr(Value *Ptr);
679 /// Returns true if the value V is uniform within the loop.
680 bool isUniform(Value *V);
682 /// Returns true if this instruction will remain scalar after vectorization.
683 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
685 /// Returns the information that we collected about runtime memory check.
686 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
688 /// This function returns the identity element (or neutral element) for
690 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
692 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
694 bool hasStride(Value *V) { return StrideSet.count(V); }
695 bool mustCheckStrides() { return !StrideSet.empty(); }
696 SmallPtrSet<Value *, 8>::iterator strides_begin() {
697 return StrideSet.begin();
699 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
702 /// Check if a single basic block loop is vectorizable.
703 /// At this point we know that this is a loop with a constant trip count
704 /// and we only need to check individual instructions.
705 bool canVectorizeInstrs();
707 /// When we vectorize loops we may change the order in which
708 /// we read and write from memory. This method checks if it is
709 /// legal to vectorize the code, considering only memory constrains.
710 /// Returns true if the loop is vectorizable
711 bool canVectorizeMemory();
713 /// Return true if we can vectorize this loop using the IF-conversion
715 bool canVectorizeWithIfConvert();
717 /// Collect the variables that need to stay uniform after vectorization.
718 void collectLoopUniforms();
720 /// Return true if all of the instructions in the block can be speculatively
721 /// executed. \p SafePtrs is a list of addresses that are known to be legal
722 /// and we know that we can read from them without segfault.
723 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
725 /// Returns True, if 'Phi' is the kind of reduction variable for type
726 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
727 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
728 /// Returns a struct describing if the instruction 'I' can be a reduction
729 /// variable of type 'Kind'. If the reduction is a min/max pattern of
730 /// select(icmp()) this function advances the instruction pointer 'I' from the
731 /// compare instruction to the select instruction and stores this pointer in
732 /// 'PatternLastInst' member of the returned struct.
733 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
734 ReductionInstDesc &Desc);
735 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
736 /// pattern corresponding to a min(X, Y) or max(X, Y).
737 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
738 ReductionInstDesc &Prev);
739 /// Returns the induction kind of Phi. This function may return NoInduction
740 /// if the PHI is not an induction variable.
741 InductionKind isInductionVariable(PHINode *Phi);
743 /// \brief Collect memory access with loop invariant strides.
745 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
747 void collectStridedAcccess(Value *LoadOrStoreInst);
749 /// The loop that we evaluate.
753 /// DataLayout analysis.
754 const DataLayout *DL;
757 /// Target Library Info.
758 TargetLibraryInfo *TLI;
760 // --- vectorization state --- //
762 /// Holds the integer induction variable. This is the counter of the
765 /// Holds the reduction variables.
766 ReductionList Reductions;
767 /// Holds all of the induction variables that we found in the loop.
768 /// Notice that inductions don't need to start at zero and that induction
769 /// variables can be pointers.
770 InductionList Inductions;
771 /// Holds the widest induction type encountered.
774 /// Allowed outside users. This holds the reduction
775 /// vars which can be accessed from outside the loop.
776 SmallPtrSet<Value*, 4> AllowedExit;
777 /// This set holds the variables which are known to be uniform after
779 SmallPtrSet<Instruction*, 4> Uniforms;
780 /// We need to check that all of the pointers in this list are disjoint
782 RuntimePointerCheck PtrRtCheck;
783 /// Can we assume the absence of NaNs.
784 bool HasFunNoNaNAttr;
786 unsigned MaxSafeDepDistBytes;
788 ValueToValueMap Strides;
789 SmallPtrSet<Value *, 8> StrideSet;
792 /// LoopVectorizationCostModel - estimates the expected speedups due to
794 /// In many cases vectorization is not profitable. This can happen because of
795 /// a number of reasons. In this class we mainly attempt to predict the
796 /// expected speedup/slowdowns due to the supported instruction set. We use the
797 /// TargetTransformInfo to query the different backends for the cost of
798 /// different operations.
799 class LoopVectorizationCostModel {
801 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
802 LoopVectorizationLegality *Legal,
803 const TargetTransformInfo &TTI,
804 const DataLayout *DL, const TargetLibraryInfo *TLI)
805 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
807 /// Information about vectorization costs
808 struct VectorizationFactor {
809 unsigned Width; // Vector width with best cost
810 unsigned Cost; // Cost of the loop with that width
812 /// \return The most profitable vectorization factor and the cost of that VF.
813 /// This method checks every power of two up to VF. If UserVF is not ZERO
814 /// then this vectorization factor will be selected if vectorization is
816 VectorizationFactor selectVectorizationFactor(bool OptForSize,
818 bool ForceVectorization);
820 /// \return The size (in bits) of the widest type in the code that
821 /// needs to be vectorized. We ignore values that remain scalar such as
822 /// 64 bit loop indices.
823 unsigned getWidestType();
825 /// \return The most profitable unroll factor.
826 /// If UserUF is non-zero then this method finds the best unroll-factor
827 /// based on register pressure and other parameters.
828 /// VF and LoopCost are the selected vectorization factor and the cost of the
830 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
833 /// \brief A struct that represents some properties of the register usage
835 struct RegisterUsage {
836 /// Holds the number of loop invariant values that are used in the loop.
837 unsigned LoopInvariantRegs;
838 /// Holds the maximum number of concurrent live intervals in the loop.
839 unsigned MaxLocalUsers;
840 /// Holds the number of instructions in the loop.
841 unsigned NumInstructions;
844 /// \return information about the register usage of the loop.
845 RegisterUsage calculateRegisterUsage();
848 /// Returns the expected execution cost. The unit of the cost does
849 /// not matter because we use the 'cost' units to compare different
850 /// vector widths. The cost that is returned is *not* normalized by
851 /// the factor width.
852 unsigned expectedCost(unsigned VF);
854 /// Returns the execution time cost of an instruction for a given vector
855 /// width. Vector width of one means scalar.
856 unsigned getInstructionCost(Instruction *I, unsigned VF);
858 /// A helper function for converting Scalar types to vector types.
859 /// If the incoming type is void, we return void. If the VF is 1, we return
861 static Type* ToVectorTy(Type *Scalar, unsigned VF);
863 /// Returns whether the instruction is a load or store and will be a emitted
864 /// as a vector operation.
865 bool isConsecutiveLoadOrStore(Instruction *I);
867 /// The loop that we evaluate.
871 /// Loop Info analysis.
873 /// Vectorization legality.
874 LoopVectorizationLegality *Legal;
875 /// Vector target information.
876 const TargetTransformInfo &TTI;
877 /// Target data layout information.
878 const DataLayout *DL;
879 /// Target Library Info.
880 const TargetLibraryInfo *TLI;
883 /// Utility class for getting and setting loop vectorizer hints in the form
884 /// of loop metadata.
885 class LoopVectorizeHints {
888 FK_Undefined = -1, ///< Not selected.
889 FK_Disabled = 0, ///< Forcing disabled.
890 FK_Enabled = 1, ///< Forcing enabled.
893 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
894 : Width(VectorizationFactor),
895 Unroll(DisableUnrolling),
897 LoopID(L->getLoopID()) {
899 // force-vector-unroll overrides DisableUnrolling.
900 if (VectorizationUnroll.getNumOccurrences() > 0)
901 Unroll = VectorizationUnroll;
903 DEBUG(if (DisableUnrolling && Unroll == 1) dbgs()
904 << "LV: Unrolling disabled by the pass manager\n");
907 /// Return the loop vectorizer metadata prefix.
908 static StringRef Prefix() { return "llvm.vectorizer."; }
910 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) const {
911 SmallVector<Value*, 2> Vals;
912 Vals.push_back(MDString::get(Context, Name));
913 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
914 return MDNode::get(Context, Vals);
917 /// Mark the loop L as already vectorized by setting the width to 1.
918 void setAlreadyVectorized(Loop *L) {
919 LLVMContext &Context = L->getHeader()->getContext();
923 // Create a new loop id with one more operand for the already_vectorized
924 // hint. If the loop already has a loop id then copy the existing operands.
925 SmallVector<Value*, 4> Vals(1);
927 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
928 Vals.push_back(LoopID->getOperand(i));
930 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
931 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
933 MDNode *NewLoopID = MDNode::get(Context, Vals);
934 // Set operand 0 to refer to the loop id itself.
935 NewLoopID->replaceOperandWith(0, NewLoopID);
937 L->setLoopID(NewLoopID);
939 LoopID->replaceAllUsesWith(NewLoopID);
944 unsigned getWidth() const { return Width; }
945 unsigned getUnroll() const { return Unroll; }
946 enum ForceKind getForce() const { return Force; }
947 MDNode *getLoopID() const { return LoopID; }
950 /// Find hints specified in the loop metadata.
951 void getHints(const Loop *L) {
955 // First operand should refer to the loop id itself.
956 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
957 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
959 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
960 const MDString *S = nullptr;
961 SmallVector<Value*, 4> Args;
963 // The expected hint is either a MDString or a MDNode with the first
964 // operand a MDString.
965 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
966 if (!MD || MD->getNumOperands() == 0)
968 S = dyn_cast<MDString>(MD->getOperand(0));
969 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
970 Args.push_back(MD->getOperand(i));
972 S = dyn_cast<MDString>(LoopID->getOperand(i));
973 assert(Args.size() == 0 && "too many arguments for MDString");
979 // Check if the hint starts with the vectorizer prefix.
980 StringRef Hint = S->getString();
981 if (!Hint.startswith(Prefix()))
983 // Remove the prefix.
984 Hint = Hint.substr(Prefix().size(), StringRef::npos);
986 if (Args.size() == 1)
987 getHint(Hint, Args[0]);
991 // Check string hint with one operand.
992 void getHint(StringRef Hint, Value *Arg) {
993 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
995 unsigned Val = C->getZExtValue();
997 if (Hint == "width") {
998 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
1001 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
1002 } else if (Hint == "unroll") {
1003 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
1006 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
1007 } else if (Hint == "enable") {
1008 if (C->getBitWidth() == 1)
1009 Force = Val == 1 ? LoopVectorizeHints::FK_Enabled
1010 : LoopVectorizeHints::FK_Disabled;
1012 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
1014 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
1018 /// Vectorization width.
1020 /// Vectorization unroll factor.
1022 /// Vectorization forced
1023 enum ForceKind Force;
1028 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1030 return V.push_back(&L);
1032 for (Loop *InnerL : L)
1033 addInnerLoop(*InnerL, V);
1036 /// The LoopVectorize Pass.
1037 struct LoopVectorize : public FunctionPass {
1038 /// Pass identification, replacement for typeid
1041 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1043 DisableUnrolling(NoUnrolling),
1044 AlwaysVectorize(AlwaysVectorize) {
1045 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1048 ScalarEvolution *SE;
1049 const DataLayout *DL;
1051 TargetTransformInfo *TTI;
1053 BlockFrequencyInfo *BFI;
1054 TargetLibraryInfo *TLI;
1055 bool DisableUnrolling;
1056 bool AlwaysVectorize;
1058 BlockFrequency ColdEntryFreq;
1060 bool runOnFunction(Function &F) override {
1061 SE = &getAnalysis<ScalarEvolution>();
1062 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1063 DL = DLP ? &DLP->getDataLayout() : nullptr;
1064 LI = &getAnalysis<LoopInfo>();
1065 TTI = &getAnalysis<TargetTransformInfo>();
1066 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1067 BFI = &getAnalysis<BlockFrequencyInfo>();
1068 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1070 // Compute some weights outside of the loop over the loops. Compute this
1071 // using a BranchProbability to re-use its scaling math.
1072 const BranchProbability ColdProb(1, 5); // 20%
1073 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1075 // If the target claims to have no vector registers don't attempt
1077 if (!TTI->getNumberOfRegisters(true))
1081 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1082 << ": Missing data layout\n");
1086 // Build up a worklist of inner-loops to vectorize. This is necessary as
1087 // the act of vectorizing or partially unrolling a loop creates new loops
1088 // and can invalidate iterators across the loops.
1089 SmallVector<Loop *, 8> Worklist;
1092 addInnerLoop(*L, Worklist);
1094 LoopsAnalyzed += Worklist.size();
1096 // Now walk the identified inner loops.
1097 bool Changed = false;
1098 while (!Worklist.empty())
1099 Changed |= processLoop(Worklist.pop_back_val());
1101 // Process each loop nest in the function.
1105 bool processLoop(Loop *L) {
1106 assert(L->empty() && "Only process inner loops.");
1109 const std::string DebugLocStr = getDebugLocString(L);
1112 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1113 << L->getHeader()->getParent()->getName() << "\" from "
1114 << DebugLocStr << "\n");
1116 LoopVectorizeHints Hints(L, DisableUnrolling);
1118 DEBUG(dbgs() << "LV: Loop hints:"
1120 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1122 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1124 : "?")) << " width=" << Hints.getWidth()
1125 << " unroll=" << Hints.getUnroll() << "\n");
1127 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1128 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1132 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1133 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1137 if (Hints.getWidth() == 1 && Hints.getUnroll() == 1) {
1138 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1142 // Check the loop for a trip count threshold:
1143 // do not vectorize loops with a tiny trip count.
1144 BasicBlock *Latch = L->getLoopLatch();
1145 const unsigned TC = SE->getSmallConstantTripCount(L, Latch);
1146 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1147 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1148 << "This loop is not worth vectorizing.");
1149 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1150 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1152 DEBUG(dbgs() << "\n");
1157 // Check if it is legal to vectorize the loop.
1158 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1159 if (!LVL.canVectorize()) {
1160 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1164 // Use the cost model.
1165 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1167 // Check the function attributes to find out if this function should be
1168 // optimized for size.
1169 Function *F = L->getHeader()->getParent();
1170 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1171 F->hasFnAttribute(Attribute::OptimizeForSize);
1173 // Compute the weighted frequency of this loop being executed and see if it
1174 // is less than 20% of the function entry baseline frequency. Note that we
1175 // always have a canonical loop here because we think we *can* vectoriez.
1176 // FIXME: This is hidden behind a flag due to pervasive problems with
1177 // exactly what block frequency models.
1178 if (LoopVectorizeWithBlockFrequency) {
1179 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1180 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1181 LoopEntryFreq < ColdEntryFreq)
1185 // Check the function attributes to see if implicit floats are allowed.a
1186 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1187 // an integer loop and the vector instructions selected are purely integer
1188 // vector instructions?
1189 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1190 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1191 "attribute is used.\n");
1195 // Select the optimal vectorization factor.
1196 const LoopVectorizationCostModel::VectorizationFactor VF =
1197 CM.selectVectorizationFactor(OptForSize, Hints.getWidth(),
1199 LoopVectorizeHints::FK_Enabled);
1201 // Select the unroll factor.
1203 CM.selectUnrollFactor(OptForSize, Hints.getUnroll(), VF.Width, VF.Cost);
1205 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1206 << DebugLocStr << '\n');
1207 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1209 if (VF.Width == 1) {
1210 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1213 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1215 // Report the unrolling decision.
1216 F->getContext().emitOptimizationRemark(
1217 DEBUG_TYPE, *F, L->getStartLoc(),
1218 Twine("unrolled with interleaving factor " + Twine(UF) +
1219 " (vectorization not beneficial)"));
1221 // We decided not to vectorize, but we may want to unroll.
1222 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1223 Unroller.vectorize(&LVL);
1225 // If we decided that it is *legal* to vectorize the loop then do it.
1226 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1230 // Report the vectorization decision.
1231 F->getContext().emitOptimizationRemark(
1232 DEBUG_TYPE, *F, L->getStartLoc(),
1233 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1234 ", unrolling interleave factor: " + Twine(UF) + ")");
1237 // Mark the loop as already vectorized to avoid vectorizing again.
1238 Hints.setAlreadyVectorized(L);
1240 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1244 void getAnalysisUsage(AnalysisUsage &AU) const override {
1245 AU.addRequiredID(LoopSimplifyID);
1246 AU.addRequiredID(LCSSAID);
1247 AU.addRequired<BlockFrequencyInfo>();
1248 AU.addRequired<DominatorTreeWrapperPass>();
1249 AU.addRequired<LoopInfo>();
1250 AU.addRequired<ScalarEvolution>();
1251 AU.addRequired<TargetTransformInfo>();
1252 AU.addPreserved<LoopInfo>();
1253 AU.addPreserved<DominatorTreeWrapperPass>();
1258 } // end anonymous namespace
1260 //===----------------------------------------------------------------------===//
1261 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1262 // LoopVectorizationCostModel.
1263 //===----------------------------------------------------------------------===//
1265 static Value *stripIntegerCast(Value *V) {
1266 if (CastInst *CI = dyn_cast<CastInst>(V))
1267 if (CI->getOperand(0)->getType()->isIntegerTy())
1268 return CI->getOperand(0);
1272 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1274 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1276 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1277 ValueToValueMap &PtrToStride,
1278 Value *Ptr, Value *OrigPtr = nullptr) {
1280 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1282 // If there is an entry in the map return the SCEV of the pointer with the
1283 // symbolic stride replaced by one.
1284 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1285 if (SI != PtrToStride.end()) {
1286 Value *StrideVal = SI->second;
1289 StrideVal = stripIntegerCast(StrideVal);
1291 // Replace symbolic stride by one.
1292 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1293 ValueToValueMap RewriteMap;
1294 RewriteMap[StrideVal] = One;
1297 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1298 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1303 // Otherwise, just return the SCEV of the original pointer.
1304 return SE->getSCEV(Ptr);
1307 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1308 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1309 ValueToValueMap &Strides) {
1310 // Get the stride replaced scev.
1311 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1312 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1313 assert(AR && "Invalid addrec expression");
1314 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1315 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1316 Pointers.push_back(Ptr);
1317 Starts.push_back(AR->getStart());
1318 Ends.push_back(ScEnd);
1319 IsWritePtr.push_back(WritePtr);
1320 DependencySetId.push_back(DepSetId);
1323 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1324 // We need to place the broadcast of invariant variables outside the loop.
1325 Instruction *Instr = dyn_cast<Instruction>(V);
1327 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1328 Instr->getParent()) != LoopVectorBody.end());
1329 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1331 // Place the code for broadcasting invariant variables in the new preheader.
1332 IRBuilder<>::InsertPointGuard Guard(Builder);
1334 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1336 // Broadcast the scalar into all locations in the vector.
1337 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1342 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1344 assert(Val->getType()->isVectorTy() && "Must be a vector");
1345 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1346 "Elem must be an integer");
1347 // Create the types.
1348 Type *ITy = Val->getType()->getScalarType();
1349 VectorType *Ty = cast<VectorType>(Val->getType());
1350 int VLen = Ty->getNumElements();
1351 SmallVector<Constant*, 8> Indices;
1353 // Create a vector of consecutive numbers from zero to VF.
1354 for (int i = 0; i < VLen; ++i) {
1355 int64_t Idx = Negate ? (-i) : i;
1356 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1359 // Add the consecutive indices to the vector value.
1360 Constant *Cv = ConstantVector::get(Indices);
1361 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1362 return Builder.CreateAdd(Val, Cv, "induction");
1365 /// \brief Find the operand of the GEP that should be checked for consecutive
1366 /// stores. This ignores trailing indices that have no effect on the final
1368 static unsigned getGEPInductionOperand(const DataLayout *DL,
1369 const GetElementPtrInst *Gep) {
1370 unsigned LastOperand = Gep->getNumOperands() - 1;
1371 unsigned GEPAllocSize = DL->getTypeAllocSize(
1372 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1374 // Walk backwards and try to peel off zeros.
1375 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1376 // Find the type we're currently indexing into.
1377 gep_type_iterator GEPTI = gep_type_begin(Gep);
1378 std::advance(GEPTI, LastOperand - 1);
1380 // If it's a type with the same allocation size as the result of the GEP we
1381 // can peel off the zero index.
1382 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1390 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1391 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1392 // Make sure that the pointer does not point to structs.
1393 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1396 // If this value is a pointer induction variable we know it is consecutive.
1397 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1398 if (Phi && Inductions.count(Phi)) {
1399 InductionInfo II = Inductions[Phi];
1400 if (IK_PtrInduction == II.IK)
1402 else if (IK_ReversePtrInduction == II.IK)
1406 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1410 unsigned NumOperands = Gep->getNumOperands();
1411 Value *GpPtr = Gep->getPointerOperand();
1412 // If this GEP value is a consecutive pointer induction variable and all of
1413 // the indices are constant then we know it is consecutive. We can
1414 Phi = dyn_cast<PHINode>(GpPtr);
1415 if (Phi && Inductions.count(Phi)) {
1417 // Make sure that the pointer does not point to structs.
1418 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1419 if (GepPtrType->getElementType()->isAggregateType())
1422 // Make sure that all of the index operands are loop invariant.
1423 for (unsigned i = 1; i < NumOperands; ++i)
1424 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1427 InductionInfo II = Inductions[Phi];
1428 if (IK_PtrInduction == II.IK)
1430 else if (IK_ReversePtrInduction == II.IK)
1434 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1436 // Check that all of the gep indices are uniform except for our induction
1438 for (unsigned i = 0; i != NumOperands; ++i)
1439 if (i != InductionOperand &&
1440 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1443 // We can emit wide load/stores only if the last non-zero index is the
1444 // induction variable.
1445 const SCEV *Last = nullptr;
1446 if (!Strides.count(Gep))
1447 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1449 // Because of the multiplication by a stride we can have a s/zext cast.
1450 // We are going to replace this stride by 1 so the cast is safe to ignore.
1452 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1453 // %0 = trunc i64 %indvars.iv to i32
1454 // %mul = mul i32 %0, %Stride1
1455 // %idxprom = zext i32 %mul to i64 << Safe cast.
1456 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1458 Last = replaceSymbolicStrideSCEV(SE, Strides,
1459 Gep->getOperand(InductionOperand), Gep);
1460 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1462 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1466 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1467 const SCEV *Step = AR->getStepRecurrence(*SE);
1469 // The memory is consecutive because the last index is consecutive
1470 // and all other indices are loop invariant.
1473 if (Step->isAllOnesValue())
1480 bool LoopVectorizationLegality::isUniform(Value *V) {
1481 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1484 InnerLoopVectorizer::VectorParts&
1485 InnerLoopVectorizer::getVectorValue(Value *V) {
1486 assert(V != Induction && "The new induction variable should not be used.");
1487 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1489 // If we have a stride that is replaced by one, do it here.
1490 if (Legal->hasStride(V))
1491 V = ConstantInt::get(V->getType(), 1);
1493 // If we have this scalar in the map, return it.
1494 if (WidenMap.has(V))
1495 return WidenMap.get(V);
1497 // If this scalar is unknown, assume that it is a constant or that it is
1498 // loop invariant. Broadcast V and save the value for future uses.
1499 Value *B = getBroadcastInstrs(V);
1500 return WidenMap.splat(V, B);
1503 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1504 assert(Vec->getType()->isVectorTy() && "Invalid type");
1505 SmallVector<Constant*, 8> ShuffleMask;
1506 for (unsigned i = 0; i < VF; ++i)
1507 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1509 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1510 ConstantVector::get(ShuffleMask),
1514 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1515 // Attempt to issue a wide load.
1516 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1517 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1519 assert((LI || SI) && "Invalid Load/Store instruction");
1521 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1522 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1523 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1524 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1525 // An alignment of 0 means target abi alignment. We need to use the scalar's
1526 // target abi alignment in such a case.
1528 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1529 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1530 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1531 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1533 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1534 return scalarizeInstruction(Instr, true);
1536 if (ScalarAllocatedSize != VectorElementSize)
1537 return scalarizeInstruction(Instr);
1539 // If the pointer is loop invariant or if it is non-consecutive,
1540 // scalarize the load.
1541 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1542 bool Reverse = ConsecutiveStride < 0;
1543 bool UniformLoad = LI && Legal->isUniform(Ptr);
1544 if (!ConsecutiveStride || UniformLoad)
1545 return scalarizeInstruction(Instr);
1547 Constant *Zero = Builder.getInt32(0);
1548 VectorParts &Entry = WidenMap.get(Instr);
1550 // Handle consecutive loads/stores.
1551 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1552 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1553 setDebugLocFromInst(Builder, Gep);
1554 Value *PtrOperand = Gep->getPointerOperand();
1555 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1556 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1558 // Create the new GEP with the new induction variable.
1559 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1560 Gep2->setOperand(0, FirstBasePtr);
1561 Gep2->setName("gep.indvar.base");
1562 Ptr = Builder.Insert(Gep2);
1564 setDebugLocFromInst(Builder, Gep);
1565 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1566 OrigLoop) && "Base ptr must be invariant");
1568 // The last index does not have to be the induction. It can be
1569 // consecutive and be a function of the index. For example A[I+1];
1570 unsigned NumOperands = Gep->getNumOperands();
1571 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1572 // Create the new GEP with the new induction variable.
1573 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1575 for (unsigned i = 0; i < NumOperands; ++i) {
1576 Value *GepOperand = Gep->getOperand(i);
1577 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1579 // Update last index or loop invariant instruction anchored in loop.
1580 if (i == InductionOperand ||
1581 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1582 assert((i == InductionOperand ||
1583 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1584 "Must be last index or loop invariant");
1586 VectorParts &GEPParts = getVectorValue(GepOperand);
1587 Value *Index = GEPParts[0];
1588 Index = Builder.CreateExtractElement(Index, Zero);
1589 Gep2->setOperand(i, Index);
1590 Gep2->setName("gep.indvar.idx");
1593 Ptr = Builder.Insert(Gep2);
1595 // Use the induction element ptr.
1596 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1597 setDebugLocFromInst(Builder, Ptr);
1598 VectorParts &PtrVal = getVectorValue(Ptr);
1599 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1604 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1605 "We do not allow storing to uniform addresses");
1606 setDebugLocFromInst(Builder, SI);
1607 // We don't want to update the value in the map as it might be used in
1608 // another expression. So don't use a reference type for "StoredVal".
1609 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1611 for (unsigned Part = 0; Part < UF; ++Part) {
1612 // Calculate the pointer for the specific unroll-part.
1613 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1616 // If we store to reverse consecutive memory locations then we need
1617 // to reverse the order of elements in the stored value.
1618 StoredVal[Part] = reverseVector(StoredVal[Part]);
1619 // If the address is consecutive but reversed, then the
1620 // wide store needs to start at the last vector element.
1621 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1622 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1625 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1626 DataTy->getPointerTo(AddressSpace));
1627 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1633 assert(LI && "Must have a load instruction");
1634 setDebugLocFromInst(Builder, LI);
1635 for (unsigned Part = 0; Part < UF; ++Part) {
1636 // Calculate the pointer for the specific unroll-part.
1637 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1640 // If the address is consecutive but reversed, then the
1641 // wide store needs to start at the last vector element.
1642 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1643 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1646 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1647 DataTy->getPointerTo(AddressSpace));
1648 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1649 cast<LoadInst>(LI)->setAlignment(Alignment);
1650 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1654 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1655 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1656 // Holds vector parameters or scalars, in case of uniform vals.
1657 SmallVector<VectorParts, 4> Params;
1659 setDebugLocFromInst(Builder, Instr);
1661 // Find all of the vectorized parameters.
1662 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1663 Value *SrcOp = Instr->getOperand(op);
1665 // If we are accessing the old induction variable, use the new one.
1666 if (SrcOp == OldInduction) {
1667 Params.push_back(getVectorValue(SrcOp));
1671 // Try using previously calculated values.
1672 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1674 // If the src is an instruction that appeared earlier in the basic block
1675 // then it should already be vectorized.
1676 if (SrcInst && OrigLoop->contains(SrcInst)) {
1677 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1678 // The parameter is a vector value from earlier.
1679 Params.push_back(WidenMap.get(SrcInst));
1681 // The parameter is a scalar from outside the loop. Maybe even a constant.
1682 VectorParts Scalars;
1683 Scalars.append(UF, SrcOp);
1684 Params.push_back(Scalars);
1688 assert(Params.size() == Instr->getNumOperands() &&
1689 "Invalid number of operands");
1691 // Does this instruction return a value ?
1692 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1694 Value *UndefVec = IsVoidRetTy ? nullptr :
1695 UndefValue::get(VectorType::get(Instr->getType(), VF));
1696 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1697 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1699 Instruction *InsertPt = Builder.GetInsertPoint();
1700 BasicBlock *IfBlock = Builder.GetInsertBlock();
1701 BasicBlock *CondBlock = nullptr;
1704 Loop *VectorLp = nullptr;
1705 if (IfPredicateStore) {
1706 assert(Instr->getParent()->getSinglePredecessor() &&
1707 "Only support single predecessor blocks");
1708 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1709 Instr->getParent());
1710 VectorLp = LI->getLoopFor(IfBlock);
1711 assert(VectorLp && "Must have a loop for this block");
1714 // For each vector unroll 'part':
1715 for (unsigned Part = 0; Part < UF; ++Part) {
1716 // For each scalar that we create:
1717 for (unsigned Width = 0; Width < VF; ++Width) {
1720 Value *Cmp = nullptr;
1721 if (IfPredicateStore) {
1722 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1723 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1724 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1725 LoopVectorBody.push_back(CondBlock);
1726 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1727 // Update Builder with newly created basic block.
1728 Builder.SetInsertPoint(InsertPt);
1731 Instruction *Cloned = Instr->clone();
1733 Cloned->setName(Instr->getName() + ".cloned");
1734 // Replace the operands of the cloned instructions with extracted scalars.
1735 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1736 Value *Op = Params[op][Part];
1737 // Param is a vector. Need to extract the right lane.
1738 if (Op->getType()->isVectorTy())
1739 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1740 Cloned->setOperand(op, Op);
1743 // Place the cloned scalar in the new loop.
1744 Builder.Insert(Cloned);
1746 // If the original scalar returns a value we need to place it in a vector
1747 // so that future users will be able to use it.
1749 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1750 Builder.getInt32(Width));
1752 if (IfPredicateStore) {
1753 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1754 LoopVectorBody.push_back(NewIfBlock);
1755 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1756 Builder.SetInsertPoint(InsertPt);
1757 Instruction *OldBr = IfBlock->getTerminator();
1758 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1759 OldBr->eraseFromParent();
1760 IfBlock = NewIfBlock;
1766 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1770 if (Instruction *I = dyn_cast<Instruction>(V))
1771 return I->getParent() == Loc->getParent() ? I : nullptr;
1775 std::pair<Instruction *, Instruction *>
1776 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1777 Instruction *tnullptr = nullptr;
1778 if (!Legal->mustCheckStrides())
1779 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1781 IRBuilder<> ChkBuilder(Loc);
1784 Value *Check = nullptr;
1785 Instruction *FirstInst = nullptr;
1786 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1787 SE = Legal->strides_end();
1789 Value *Ptr = stripIntegerCast(*SI);
1790 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1792 // Store the first instruction we create.
1793 FirstInst = getFirstInst(FirstInst, C, Loc);
1795 Check = ChkBuilder.CreateOr(Check, C);
1800 // We have to do this trickery because the IRBuilder might fold the check to a
1801 // constant expression in which case there is no Instruction anchored in a
1803 LLVMContext &Ctx = Loc->getContext();
1804 Instruction *TheCheck =
1805 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1806 ChkBuilder.Insert(TheCheck, "stride.not.one");
1807 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1809 return std::make_pair(FirstInst, TheCheck);
1812 std::pair<Instruction *, Instruction *>
1813 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1814 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1815 Legal->getRuntimePointerCheck();
1817 Instruction *tnullptr = nullptr;
1818 if (!PtrRtCheck->Need)
1819 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1821 unsigned NumPointers = PtrRtCheck->Pointers.size();
1822 SmallVector<TrackingVH<Value> , 2> Starts;
1823 SmallVector<TrackingVH<Value> , 2> Ends;
1825 LLVMContext &Ctx = Loc->getContext();
1826 SCEVExpander Exp(*SE, "induction");
1827 Instruction *FirstInst = nullptr;
1829 for (unsigned i = 0; i < NumPointers; ++i) {
1830 Value *Ptr = PtrRtCheck->Pointers[i];
1831 const SCEV *Sc = SE->getSCEV(Ptr);
1833 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1834 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1836 Starts.push_back(Ptr);
1837 Ends.push_back(Ptr);
1839 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1840 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1842 // Use this type for pointer arithmetic.
1843 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1845 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1846 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1847 Starts.push_back(Start);
1848 Ends.push_back(End);
1852 IRBuilder<> ChkBuilder(Loc);
1853 // Our instructions might fold to a constant.
1854 Value *MemoryRuntimeCheck = nullptr;
1855 for (unsigned i = 0; i < NumPointers; ++i) {
1856 for (unsigned j = i+1; j < NumPointers; ++j) {
1857 // No need to check if two readonly pointers intersect.
1858 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1861 // Only need to check pointers between two different dependency sets.
1862 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1865 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1866 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1868 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1869 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1870 "Trying to bounds check pointers with different address spaces");
1872 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1873 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1875 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1876 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1877 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1878 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1880 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1881 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1882 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1883 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1884 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1885 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1886 if (MemoryRuntimeCheck) {
1887 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1889 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1891 MemoryRuntimeCheck = IsConflict;
1895 // We have to do this trickery because the IRBuilder might fold the check to a
1896 // constant expression in which case there is no Instruction anchored in a
1898 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1899 ConstantInt::getTrue(Ctx));
1900 ChkBuilder.Insert(Check, "memcheck.conflict");
1901 FirstInst = getFirstInst(FirstInst, Check, Loc);
1902 return std::make_pair(FirstInst, Check);
1905 void InnerLoopVectorizer::createEmptyLoop() {
1907 In this function we generate a new loop. The new loop will contain
1908 the vectorized instructions while the old loop will continue to run the
1911 [ ] <-- vector loop bypass (may consist of multiple blocks).
1914 | [ ] <-- vector pre header.
1918 | [ ]_| <-- vector loop.
1921 >[ ] <--- middle-block.
1924 | [ ] <--- new preheader.
1928 | [ ]_| <-- old scalar loop to handle remainder.
1931 >[ ] <-- exit block.
1935 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1936 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1937 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1938 assert(ExitBlock && "Must have an exit block");
1940 // Some loops have a single integer induction variable, while other loops
1941 // don't. One example is c++ iterators that often have multiple pointer
1942 // induction variables. In the code below we also support a case where we
1943 // don't have a single induction variable.
1944 OldInduction = Legal->getInduction();
1945 Type *IdxTy = Legal->getWidestInductionType();
1947 // Find the loop boundaries.
1948 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1949 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1951 // The exit count might have the type of i64 while the phi is i32. This can
1952 // happen if we have an induction variable that is sign extended before the
1953 // compare. The only way that we get a backedge taken count is that the
1954 // induction variable was signed and as such will not overflow. In such a case
1955 // truncation is legal.
1956 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1957 IdxTy->getPrimitiveSizeInBits())
1958 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1960 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1961 // Get the total trip count from the count by adding 1.
1962 ExitCount = SE->getAddExpr(ExitCount,
1963 SE->getConstant(ExitCount->getType(), 1));
1965 // Expand the trip count and place the new instructions in the preheader.
1966 // Notice that the pre-header does not change, only the loop body.
1967 SCEVExpander Exp(*SE, "induction");
1969 // Count holds the overall loop count (N).
1970 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1971 BypassBlock->getTerminator());
1973 // The loop index does not have to start at Zero. Find the original start
1974 // value from the induction PHI node. If we don't have an induction variable
1975 // then we know that it starts at zero.
1976 Builder.SetInsertPoint(BypassBlock->getTerminator());
1977 Value *StartIdx = ExtendedIdx = OldInduction ?
1978 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1980 ConstantInt::get(IdxTy, 0);
1982 assert(BypassBlock && "Invalid loop structure");
1983 LoopBypassBlocks.push_back(BypassBlock);
1985 // Split the single block loop into the two loop structure described above.
1986 BasicBlock *VectorPH =
1987 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1988 BasicBlock *VecBody =
1989 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1990 BasicBlock *MiddleBlock =
1991 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1992 BasicBlock *ScalarPH =
1993 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1995 // Create and register the new vector loop.
1996 Loop* Lp = new Loop();
1997 Loop *ParentLoop = OrigLoop->getParentLoop();
1999 // Insert the new loop into the loop nest and register the new basic blocks
2000 // before calling any utilities such as SCEV that require valid LoopInfo.
2002 ParentLoop->addChildLoop(Lp);
2003 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2004 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2005 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2007 LI->addTopLevelLoop(Lp);
2009 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2011 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2013 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2015 // Generate the induction variable.
2016 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2017 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2018 // The loop step is equal to the vectorization factor (num of SIMD elements)
2019 // times the unroll factor (num of SIMD instructions).
2020 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2022 // This is the IR builder that we use to add all of the logic for bypassing
2023 // the new vector loop.
2024 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2025 setDebugLocFromInst(BypassBuilder,
2026 getDebugLocFromInstOrOperands(OldInduction));
2028 // We may need to extend the index in case there is a type mismatch.
2029 // We know that the count starts at zero and does not overflow.
2030 if (Count->getType() != IdxTy) {
2031 // The exit count can be of pointer type. Convert it to the correct
2033 if (ExitCount->getType()->isPointerTy())
2034 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2036 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2039 // Add the start index to the loop count to get the new end index.
2040 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2042 // Now we need to generate the expression for N - (N % VF), which is
2043 // the part that the vectorized body will execute.
2044 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2045 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2046 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2047 "end.idx.rnd.down");
2049 // Now, compare the new count to zero. If it is zero skip the vector loop and
2050 // jump to the scalar loop.
2051 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
2054 BasicBlock *LastBypassBlock = BypassBlock;
2056 // Generate the code to check that the strides we assumed to be one are really
2057 // one. We want the new basic block to start at the first instruction in a
2058 // sequence of instructions that form a check.
2059 Instruction *StrideCheck;
2060 Instruction *FirstCheckInst;
2061 std::tie(FirstCheckInst, StrideCheck) =
2062 addStrideCheck(BypassBlock->getTerminator());
2064 // Create a new block containing the stride check.
2065 BasicBlock *CheckBlock =
2066 BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2068 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2069 LoopBypassBlocks.push_back(CheckBlock);
2071 // Replace the branch into the memory check block with a conditional branch
2072 // for the "few elements case".
2073 Instruction *OldTerm = BypassBlock->getTerminator();
2074 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2075 OldTerm->eraseFromParent();
2078 LastBypassBlock = CheckBlock;
2081 // Generate the code that checks in runtime if arrays overlap. We put the
2082 // checks into a separate block to make the more common case of few elements
2084 Instruction *MemRuntimeCheck;
2085 std::tie(FirstCheckInst, MemRuntimeCheck) =
2086 addRuntimeCheck(LastBypassBlock->getTerminator());
2087 if (MemRuntimeCheck) {
2088 // Create a new block containing the memory check.
2089 BasicBlock *CheckBlock =
2090 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2092 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2093 LoopBypassBlocks.push_back(CheckBlock);
2095 // Replace the branch into the memory check block with a conditional branch
2096 // for the "few elements case".
2097 Instruction *OldTerm = LastBypassBlock->getTerminator();
2098 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2099 OldTerm->eraseFromParent();
2101 Cmp = MemRuntimeCheck;
2102 LastBypassBlock = CheckBlock;
2105 LastBypassBlock->getTerminator()->eraseFromParent();
2106 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2109 // We are going to resume the execution of the scalar loop.
2110 // Go over all of the induction variables that we found and fix the
2111 // PHIs that are left in the scalar version of the loop.
2112 // The starting values of PHI nodes depend on the counter of the last
2113 // iteration in the vectorized loop.
2114 // If we come from a bypass edge then we need to start from the original
2117 // This variable saves the new starting index for the scalar loop.
2118 PHINode *ResumeIndex = nullptr;
2119 LoopVectorizationLegality::InductionList::iterator I, E;
2120 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2121 // Set builder to point to last bypass block.
2122 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2123 for (I = List->begin(), E = List->end(); I != E; ++I) {
2124 PHINode *OrigPhi = I->first;
2125 LoopVectorizationLegality::InductionInfo II = I->second;
2127 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2128 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2129 MiddleBlock->getTerminator());
2130 // We might have extended the type of the induction variable but we need a
2131 // truncated version for the scalar loop.
2132 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2133 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2134 MiddleBlock->getTerminator()) : nullptr;
2136 Value *EndValue = nullptr;
2138 case LoopVectorizationLegality::IK_NoInduction:
2139 llvm_unreachable("Unknown induction");
2140 case LoopVectorizationLegality::IK_IntInduction: {
2141 // Handle the integer induction counter.
2142 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2144 // We have the canonical induction variable.
2145 if (OrigPhi == OldInduction) {
2146 // Create a truncated version of the resume value for the scalar loop,
2147 // we might have promoted the type to a larger width.
2149 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2150 // The new PHI merges the original incoming value, in case of a bypass,
2151 // or the value at the end of the vectorized loop.
2152 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2153 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2154 TruncResumeVal->addIncoming(EndValue, VecBody);
2156 // We know what the end value is.
2157 EndValue = IdxEndRoundDown;
2158 // We also know which PHI node holds it.
2159 ResumeIndex = ResumeVal;
2163 // Not the canonical induction variable - add the vector loop count to the
2165 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2166 II.StartValue->getType(),
2168 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2171 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2172 // Convert the CountRoundDown variable to the PHI size.
2173 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2174 II.StartValue->getType(),
2176 // Handle reverse integer induction counter.
2177 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2180 case LoopVectorizationLegality::IK_PtrInduction: {
2181 // For pointer induction variables, calculate the offset using
2183 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2187 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2188 // The value at the end of the loop for the reverse pointer is calculated
2189 // by creating a GEP with a negative index starting from the start value.
2190 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2191 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2193 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2199 // The new PHI merges the original incoming value, in case of a bypass,
2200 // or the value at the end of the vectorized loop.
2201 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
2202 if (OrigPhi == OldInduction)
2203 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2205 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2207 ResumeVal->addIncoming(EndValue, VecBody);
2209 // Fix the scalar body counter (PHI node).
2210 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2211 // The old inductions phi node in the scalar body needs the truncated value.
2212 if (OrigPhi == OldInduction)
2213 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
2215 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
2218 // If we are generating a new induction variable then we also need to
2219 // generate the code that calculates the exit value. This value is not
2220 // simply the end of the counter because we may skip the vectorized body
2221 // in case of a runtime check.
2223 assert(!ResumeIndex && "Unexpected resume value found");
2224 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2225 MiddleBlock->getTerminator());
2226 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2227 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2228 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2231 // Make sure that we found the index where scalar loop needs to continue.
2232 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2233 "Invalid resume Index");
2235 // Add a check in the middle block to see if we have completed
2236 // all of the iterations in the first vector loop.
2237 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2238 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2239 ResumeIndex, "cmp.n",
2240 MiddleBlock->getTerminator());
2242 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2243 // Remove the old terminator.
2244 MiddleBlock->getTerminator()->eraseFromParent();
2246 // Create i+1 and fill the PHINode.
2247 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2248 Induction->addIncoming(StartIdx, VectorPH);
2249 Induction->addIncoming(NextIdx, VecBody);
2250 // Create the compare.
2251 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2252 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2254 // Now we have two terminators. Remove the old one from the block.
2255 VecBody->getTerminator()->eraseFromParent();
2257 // Get ready to start creating new instructions into the vectorized body.
2258 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2261 LoopVectorPreHeader = VectorPH;
2262 LoopScalarPreHeader = ScalarPH;
2263 LoopMiddleBlock = MiddleBlock;
2264 LoopExitBlock = ExitBlock;
2265 LoopVectorBody.push_back(VecBody);
2266 LoopScalarBody = OldBasicBlock;
2268 LoopVectorizeHints Hints(Lp, true);
2269 Hints.setAlreadyVectorized(Lp);
2272 /// This function returns the identity element (or neutral element) for
2273 /// the operation K.
2275 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2280 // Adding, Xoring, Oring zero to a number does not change it.
2281 return ConstantInt::get(Tp, 0);
2282 case RK_IntegerMult:
2283 // Multiplying a number by 1 does not change it.
2284 return ConstantInt::get(Tp, 1);
2286 // AND-ing a number with an all-1 value does not change it.
2287 return ConstantInt::get(Tp, -1, true);
2289 // Multiplying a number by 1 does not change it.
2290 return ConstantFP::get(Tp, 1.0L);
2292 // Adding zero to a number does not change it.
2293 return ConstantFP::get(Tp, 0.0L);
2295 llvm_unreachable("Unknown reduction kind");
2299 /// This function translates the reduction kind to an LLVM binary operator.
2301 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2303 case LoopVectorizationLegality::RK_IntegerAdd:
2304 return Instruction::Add;
2305 case LoopVectorizationLegality::RK_IntegerMult:
2306 return Instruction::Mul;
2307 case LoopVectorizationLegality::RK_IntegerOr:
2308 return Instruction::Or;
2309 case LoopVectorizationLegality::RK_IntegerAnd:
2310 return Instruction::And;
2311 case LoopVectorizationLegality::RK_IntegerXor:
2312 return Instruction::Xor;
2313 case LoopVectorizationLegality::RK_FloatMult:
2314 return Instruction::FMul;
2315 case LoopVectorizationLegality::RK_FloatAdd:
2316 return Instruction::FAdd;
2317 case LoopVectorizationLegality::RK_IntegerMinMax:
2318 return Instruction::ICmp;
2319 case LoopVectorizationLegality::RK_FloatMinMax:
2320 return Instruction::FCmp;
2322 llvm_unreachable("Unknown reduction operation");
2326 Value *createMinMaxOp(IRBuilder<> &Builder,
2327 LoopVectorizationLegality::MinMaxReductionKind RK,
2330 CmpInst::Predicate P = CmpInst::ICMP_NE;
2333 llvm_unreachable("Unknown min/max reduction kind");
2334 case LoopVectorizationLegality::MRK_UIntMin:
2335 P = CmpInst::ICMP_ULT;
2337 case LoopVectorizationLegality::MRK_UIntMax:
2338 P = CmpInst::ICMP_UGT;
2340 case LoopVectorizationLegality::MRK_SIntMin:
2341 P = CmpInst::ICMP_SLT;
2343 case LoopVectorizationLegality::MRK_SIntMax:
2344 P = CmpInst::ICMP_SGT;
2346 case LoopVectorizationLegality::MRK_FloatMin:
2347 P = CmpInst::FCMP_OLT;
2349 case LoopVectorizationLegality::MRK_FloatMax:
2350 P = CmpInst::FCMP_OGT;
2355 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2356 RK == LoopVectorizationLegality::MRK_FloatMax)
2357 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2359 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2361 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2366 struct CSEDenseMapInfo {
2367 static bool canHandle(Instruction *I) {
2368 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2369 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2371 static inline Instruction *getEmptyKey() {
2372 return DenseMapInfo<Instruction *>::getEmptyKey();
2374 static inline Instruction *getTombstoneKey() {
2375 return DenseMapInfo<Instruction *>::getTombstoneKey();
2377 static unsigned getHashValue(Instruction *I) {
2378 assert(canHandle(I) && "Unknown instruction!");
2379 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2380 I->value_op_end()));
2382 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2383 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2384 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2386 return LHS->isIdenticalTo(RHS);
2391 /// \brief Check whether this block is a predicated block.
2392 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2393 /// = ...; " blocks. We start with one vectorized basic block. For every
2394 /// conditional block we split this vectorized block. Therefore, every second
2395 /// block will be a predicated one.
2396 static bool isPredicatedBlock(unsigned BlockNum) {
2397 return BlockNum % 2;
2400 ///\brief Perform cse of induction variable instructions.
2401 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2402 // Perform simple cse.
2403 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2404 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2405 BasicBlock *BB = BBs[i];
2406 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2407 Instruction *In = I++;
2409 if (!CSEDenseMapInfo::canHandle(In))
2412 // Check if we can replace this instruction with any of the
2413 // visited instructions.
2414 if (Instruction *V = CSEMap.lookup(In)) {
2415 In->replaceAllUsesWith(V);
2416 In->eraseFromParent();
2419 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2420 // ...;" blocks for predicated stores. Every second block is a predicated
2422 if (isPredicatedBlock(i))
2430 /// \brief Adds a 'fast' flag to floating point operations.
2431 static Value *addFastMathFlag(Value *V) {
2432 if (isa<FPMathOperator>(V)){
2433 FastMathFlags Flags;
2434 Flags.setUnsafeAlgebra();
2435 cast<Instruction>(V)->setFastMathFlags(Flags);
2440 void InnerLoopVectorizer::vectorizeLoop() {
2441 //===------------------------------------------------===//
2443 // Notice: any optimization or new instruction that go
2444 // into the code below should be also be implemented in
2447 //===------------------------------------------------===//
2448 Constant *Zero = Builder.getInt32(0);
2450 // In order to support reduction variables we need to be able to vectorize
2451 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2452 // stages. First, we create a new vector PHI node with no incoming edges.
2453 // We use this value when we vectorize all of the instructions that use the
2454 // PHI. Next, after all of the instructions in the block are complete we
2455 // add the new incoming edges to the PHI. At this point all of the
2456 // instructions in the basic block are vectorized, so we can use them to
2457 // construct the PHI.
2458 PhiVector RdxPHIsToFix;
2460 // Scan the loop in a topological order to ensure that defs are vectorized
2462 LoopBlocksDFS DFS(OrigLoop);
2465 // Vectorize all of the blocks in the original loop.
2466 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2467 be = DFS.endRPO(); bb != be; ++bb)
2468 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2470 // At this point every instruction in the original loop is widened to
2471 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2472 // that we vectorized. The PHI nodes are currently empty because we did
2473 // not want to introduce cycles. Notice that the remaining PHI nodes
2474 // that we need to fix are reduction variables.
2476 // Create the 'reduced' values for each of the induction vars.
2477 // The reduced values are the vector values that we scalarize and combine
2478 // after the loop is finished.
2479 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2481 PHINode *RdxPhi = *it;
2482 assert(RdxPhi && "Unable to recover vectorized PHI");
2484 // Find the reduction variable descriptor.
2485 assert(Legal->getReductionVars()->count(RdxPhi) &&
2486 "Unable to find the reduction variable");
2487 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2488 (*Legal->getReductionVars())[RdxPhi];
2490 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2492 // We need to generate a reduction vector from the incoming scalar.
2493 // To do so, we need to generate the 'identity' vector and override
2494 // one of the elements with the incoming scalar reduction. We need
2495 // to do it in the vector-loop preheader.
2496 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2498 // This is the vector-clone of the value that leaves the loop.
2499 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2500 Type *VecTy = VectorExit[0]->getType();
2502 // Find the reduction identity variable. Zero for addition, or, xor,
2503 // one for multiplication, -1 for And.
2506 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2507 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2508 // MinMax reduction have the start value as their identify.
2510 VectorStart = Identity = RdxDesc.StartValue;
2512 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2517 // Handle other reduction kinds:
2519 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2520 VecTy->getScalarType());
2523 // This vector is the Identity vector where the first element is the
2524 // incoming scalar reduction.
2525 VectorStart = RdxDesc.StartValue;
2527 Identity = ConstantVector::getSplat(VF, Iden);
2529 // This vector is the Identity vector where the first element is the
2530 // incoming scalar reduction.
2531 VectorStart = Builder.CreateInsertElement(Identity,
2532 RdxDesc.StartValue, Zero);
2536 // Fix the vector-loop phi.
2537 // We created the induction variable so we know that the
2538 // preheader is the first entry.
2539 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2541 // Reductions do not have to start at zero. They can start with
2542 // any loop invariant values.
2543 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2544 BasicBlock *Latch = OrigLoop->getLoopLatch();
2545 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2546 VectorParts &Val = getVectorValue(LoopVal);
2547 for (unsigned part = 0; part < UF; ++part) {
2548 // Make sure to add the reduction stat value only to the
2549 // first unroll part.
2550 Value *StartVal = (part == 0) ? VectorStart : Identity;
2551 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2552 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2553 LoopVectorBody.back());
2556 // Before each round, move the insertion point right between
2557 // the PHIs and the values we are going to write.
2558 // This allows us to write both PHINodes and the extractelement
2560 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2562 VectorParts RdxParts;
2563 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2564 for (unsigned part = 0; part < UF; ++part) {
2565 // This PHINode contains the vectorized reduction variable, or
2566 // the initial value vector, if we bypass the vector loop.
2567 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2568 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2569 Value *StartVal = (part == 0) ? VectorStart : Identity;
2570 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2571 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2572 NewPhi->addIncoming(RdxExitVal[part],
2573 LoopVectorBody.back());
2574 RdxParts.push_back(NewPhi);
2577 // Reduce all of the unrolled parts into a single vector.
2578 Value *ReducedPartRdx = RdxParts[0];
2579 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2580 setDebugLocFromInst(Builder, ReducedPartRdx);
2581 for (unsigned part = 1; part < UF; ++part) {
2582 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2583 // Floating point operations had to be 'fast' to enable the reduction.
2584 ReducedPartRdx = addFastMathFlag(
2585 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2586 ReducedPartRdx, "bin.rdx"));
2588 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2589 ReducedPartRdx, RdxParts[part]);
2593 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2594 // and vector ops, reducing the set of values being computed by half each
2596 assert(isPowerOf2_32(VF) &&
2597 "Reduction emission only supported for pow2 vectors!");
2598 Value *TmpVec = ReducedPartRdx;
2599 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2600 for (unsigned i = VF; i != 1; i >>= 1) {
2601 // Move the upper half of the vector to the lower half.
2602 for (unsigned j = 0; j != i/2; ++j)
2603 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2605 // Fill the rest of the mask with undef.
2606 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2607 UndefValue::get(Builder.getInt32Ty()));
2610 Builder.CreateShuffleVector(TmpVec,
2611 UndefValue::get(TmpVec->getType()),
2612 ConstantVector::get(ShuffleMask),
2615 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2616 // Floating point operations had to be 'fast' to enable the reduction.
2617 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2618 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2620 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2623 // The result is in the first element of the vector.
2624 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2625 Builder.getInt32(0));
2628 // Now, we need to fix the users of the reduction variable
2629 // inside and outside of the scalar remainder loop.
2630 // We know that the loop is in LCSSA form. We need to update the
2631 // PHI nodes in the exit blocks.
2632 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2633 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2634 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2635 if (!LCSSAPhi) break;
2637 // All PHINodes need to have a single entry edge, or two if
2638 // we already fixed them.
2639 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2641 // We found our reduction value exit-PHI. Update it with the
2642 // incoming bypass edge.
2643 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2644 // Add an edge coming from the bypass.
2645 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2648 }// end of the LCSSA phi scan.
2650 // Fix the scalar loop reduction variable with the incoming reduction sum
2651 // from the vector body and from the backedge value.
2652 int IncomingEdgeBlockIdx =
2653 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2654 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2655 // Pick the other block.
2656 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2657 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2658 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2659 }// end of for each redux variable.
2663 // Remove redundant induction instructions.
2664 cse(LoopVectorBody);
2667 void InnerLoopVectorizer::fixLCSSAPHIs() {
2668 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2669 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2670 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2671 if (!LCSSAPhi) break;
2672 if (LCSSAPhi->getNumIncomingValues() == 1)
2673 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2678 InnerLoopVectorizer::VectorParts
2679 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2680 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2683 // Look for cached value.
2684 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2685 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2686 if (ECEntryIt != MaskCache.end())
2687 return ECEntryIt->second;
2689 VectorParts SrcMask = createBlockInMask(Src);
2691 // The terminator has to be a branch inst!
2692 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2693 assert(BI && "Unexpected terminator found");
2695 if (BI->isConditional()) {
2696 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2698 if (BI->getSuccessor(0) != Dst)
2699 for (unsigned part = 0; part < UF; ++part)
2700 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2702 for (unsigned part = 0; part < UF; ++part)
2703 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2705 MaskCache[Edge] = EdgeMask;
2709 MaskCache[Edge] = SrcMask;
2713 InnerLoopVectorizer::VectorParts
2714 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2715 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2717 // Loop incoming mask is all-one.
2718 if (OrigLoop->getHeader() == BB) {
2719 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2720 return getVectorValue(C);
2723 // This is the block mask. We OR all incoming edges, and with zero.
2724 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2725 VectorParts BlockMask = getVectorValue(Zero);
2728 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2729 VectorParts EM = createEdgeMask(*it, BB);
2730 for (unsigned part = 0; part < UF; ++part)
2731 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2737 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2738 InnerLoopVectorizer::VectorParts &Entry,
2739 unsigned UF, unsigned VF, PhiVector *PV) {
2740 PHINode* P = cast<PHINode>(PN);
2741 // Handle reduction variables:
2742 if (Legal->getReductionVars()->count(P)) {
2743 for (unsigned part = 0; part < UF; ++part) {
2744 // This is phase one of vectorizing PHIs.
2745 Type *VecTy = (VF == 1) ? PN->getType() :
2746 VectorType::get(PN->getType(), VF);
2747 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2748 LoopVectorBody.back()-> getFirstInsertionPt());
2754 setDebugLocFromInst(Builder, P);
2755 // Check for PHI nodes that are lowered to vector selects.
2756 if (P->getParent() != OrigLoop->getHeader()) {
2757 // We know that all PHIs in non-header blocks are converted into
2758 // selects, so we don't have to worry about the insertion order and we
2759 // can just use the builder.
2760 // At this point we generate the predication tree. There may be
2761 // duplications since this is a simple recursive scan, but future
2762 // optimizations will clean it up.
2764 unsigned NumIncoming = P->getNumIncomingValues();
2766 // Generate a sequence of selects of the form:
2767 // SELECT(Mask3, In3,
2768 // SELECT(Mask2, In2,
2770 for (unsigned In = 0; In < NumIncoming; In++) {
2771 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2773 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2775 for (unsigned part = 0; part < UF; ++part) {
2776 // We might have single edge PHIs (blocks) - use an identity
2777 // 'select' for the first PHI operand.
2779 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2782 // Select between the current value and the previous incoming edge
2783 // based on the incoming mask.
2784 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2785 Entry[part], "predphi");
2791 // This PHINode must be an induction variable.
2792 // Make sure that we know about it.
2793 assert(Legal->getInductionVars()->count(P) &&
2794 "Not an induction variable");
2796 LoopVectorizationLegality::InductionInfo II =
2797 Legal->getInductionVars()->lookup(P);
2800 case LoopVectorizationLegality::IK_NoInduction:
2801 llvm_unreachable("Unknown induction");
2802 case LoopVectorizationLegality::IK_IntInduction: {
2803 assert(P->getType() == II.StartValue->getType() && "Types must match");
2804 Type *PhiTy = P->getType();
2806 if (P == OldInduction) {
2807 // Handle the canonical induction variable. We might have had to
2809 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2811 // Handle other induction variables that are now based on the
2813 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2815 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2816 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2819 Broadcasted = getBroadcastInstrs(Broadcasted);
2820 // After broadcasting the induction variable we need to make the vector
2821 // consecutive by adding 0, 1, 2, etc.
2822 for (unsigned part = 0; part < UF; ++part)
2823 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2826 case LoopVectorizationLegality::IK_ReverseIntInduction:
2827 case LoopVectorizationLegality::IK_PtrInduction:
2828 case LoopVectorizationLegality::IK_ReversePtrInduction:
2829 // Handle reverse integer and pointer inductions.
2830 Value *StartIdx = ExtendedIdx;
2831 // This is the normalized GEP that starts counting at zero.
2832 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2835 // Handle the reverse integer induction variable case.
2836 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2837 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2838 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2840 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2843 // This is a new value so do not hoist it out.
2844 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2845 // After broadcasting the induction variable we need to make the
2846 // vector consecutive by adding ... -3, -2, -1, 0.
2847 for (unsigned part = 0; part < UF; ++part)
2848 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2853 // Handle the pointer induction variable case.
2854 assert(P->getType()->isPointerTy() && "Unexpected type.");
2856 // Is this a reverse induction ptr or a consecutive induction ptr.
2857 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2860 // This is the vector of results. Notice that we don't generate
2861 // vector geps because scalar geps result in better code.
2862 for (unsigned part = 0; part < UF; ++part) {
2864 int EltIndex = (part) * (Reverse ? -1 : 1);
2865 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2868 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2870 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2872 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2874 Entry[part] = SclrGep;
2878 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2879 for (unsigned int i = 0; i < VF; ++i) {
2880 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2881 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2884 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2886 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2888 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2890 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2891 Builder.getInt32(i),
2894 Entry[part] = VecVal;
2900 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2901 // For each instruction in the old loop.
2902 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2903 VectorParts &Entry = WidenMap.get(it);
2904 switch (it->getOpcode()) {
2905 case Instruction::Br:
2906 // Nothing to do for PHIs and BR, since we already took care of the
2907 // loop control flow instructions.
2909 case Instruction::PHI:{
2910 // Vectorize PHINodes.
2911 widenPHIInstruction(it, Entry, UF, VF, PV);
2915 case Instruction::Add:
2916 case Instruction::FAdd:
2917 case Instruction::Sub:
2918 case Instruction::FSub:
2919 case Instruction::Mul:
2920 case Instruction::FMul:
2921 case Instruction::UDiv:
2922 case Instruction::SDiv:
2923 case Instruction::FDiv:
2924 case Instruction::URem:
2925 case Instruction::SRem:
2926 case Instruction::FRem:
2927 case Instruction::Shl:
2928 case Instruction::LShr:
2929 case Instruction::AShr:
2930 case Instruction::And:
2931 case Instruction::Or:
2932 case Instruction::Xor: {
2933 // Just widen binops.
2934 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2935 setDebugLocFromInst(Builder, BinOp);
2936 VectorParts &A = getVectorValue(it->getOperand(0));
2937 VectorParts &B = getVectorValue(it->getOperand(1));
2939 // Use this vector value for all users of the original instruction.
2940 for (unsigned Part = 0; Part < UF; ++Part) {
2941 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2943 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2944 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2945 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2946 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2947 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2949 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2950 VecOp->setIsExact(BinOp->isExact());
2952 // Copy the fast-math flags.
2953 if (VecOp && isa<FPMathOperator>(V))
2954 VecOp->setFastMathFlags(it->getFastMathFlags());
2960 case Instruction::Select: {
2962 // If the selector is loop invariant we can create a select
2963 // instruction with a scalar condition. Otherwise, use vector-select.
2964 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2966 setDebugLocFromInst(Builder, it);
2968 // The condition can be loop invariant but still defined inside the
2969 // loop. This means that we can't just use the original 'cond' value.
2970 // We have to take the 'vectorized' value and pick the first lane.
2971 // Instcombine will make this a no-op.
2972 VectorParts &Cond = getVectorValue(it->getOperand(0));
2973 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2974 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2976 Value *ScalarCond = (VF == 1) ? Cond[0] :
2977 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
2979 for (unsigned Part = 0; Part < UF; ++Part) {
2980 Entry[Part] = Builder.CreateSelect(
2981 InvariantCond ? ScalarCond : Cond[Part],
2988 case Instruction::ICmp:
2989 case Instruction::FCmp: {
2990 // Widen compares. Generate vector compares.
2991 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2992 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2993 setDebugLocFromInst(Builder, it);
2994 VectorParts &A = getVectorValue(it->getOperand(0));
2995 VectorParts &B = getVectorValue(it->getOperand(1));
2996 for (unsigned Part = 0; Part < UF; ++Part) {
2999 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3001 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3007 case Instruction::Store:
3008 case Instruction::Load:
3009 vectorizeMemoryInstruction(it);
3011 case Instruction::ZExt:
3012 case Instruction::SExt:
3013 case Instruction::FPToUI:
3014 case Instruction::FPToSI:
3015 case Instruction::FPExt:
3016 case Instruction::PtrToInt:
3017 case Instruction::IntToPtr:
3018 case Instruction::SIToFP:
3019 case Instruction::UIToFP:
3020 case Instruction::Trunc:
3021 case Instruction::FPTrunc:
3022 case Instruction::BitCast: {
3023 CastInst *CI = dyn_cast<CastInst>(it);
3024 setDebugLocFromInst(Builder, it);
3025 /// Optimize the special case where the source is the induction
3026 /// variable. Notice that we can only optimize the 'trunc' case
3027 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3028 /// c. other casts depend on pointer size.
3029 if (CI->getOperand(0) == OldInduction &&
3030 it->getOpcode() == Instruction::Trunc) {
3031 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3033 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3034 for (unsigned Part = 0; Part < UF; ++Part)
3035 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3038 /// Vectorize casts.
3039 Type *DestTy = (VF == 1) ? CI->getType() :
3040 VectorType::get(CI->getType(), VF);
3042 VectorParts &A = getVectorValue(it->getOperand(0));
3043 for (unsigned Part = 0; Part < UF; ++Part)
3044 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3048 case Instruction::Call: {
3049 // Ignore dbg intrinsics.
3050 if (isa<DbgInfoIntrinsic>(it))
3052 setDebugLocFromInst(Builder, it);
3054 Module *M = BB->getParent()->getParent();
3055 CallInst *CI = cast<CallInst>(it);
3056 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3057 assert(ID && "Not an intrinsic call!");
3059 case Intrinsic::lifetime_end:
3060 case Intrinsic::lifetime_start:
3061 scalarizeInstruction(it);
3064 for (unsigned Part = 0; Part < UF; ++Part) {
3065 SmallVector<Value *, 4> Args;
3066 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3067 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3068 Args.push_back(Arg[Part]);
3070 Type *Tys[] = {CI->getType()};
3072 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3074 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3075 Entry[Part] = Builder.CreateCall(F, Args);
3083 // All other instructions are unsupported. Scalarize them.
3084 scalarizeInstruction(it);
3087 }// end of for_each instr.
3090 void InnerLoopVectorizer::updateAnalysis() {
3091 // Forget the original basic block.
3092 SE->forgetLoop(OrigLoop);
3094 // Update the dominator tree information.
3095 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3096 "Entry does not dominate exit.");
3098 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3099 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3100 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3102 // Due to if predication of stores we might create a sequence of "if(pred)
3103 // a[i] = ...; " blocks.
3104 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3106 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3107 else if (isPredicatedBlock(i)) {
3108 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3110 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3114 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
3115 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
3116 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3117 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3119 DEBUG(DT->verifyDomTree());
3122 /// \brief Check whether it is safe to if-convert this phi node.
3124 /// Phi nodes with constant expressions that can trap are not safe to if
3126 static bool canIfConvertPHINodes(BasicBlock *BB) {
3127 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3128 PHINode *Phi = dyn_cast<PHINode>(I);
3131 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3132 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3139 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3140 if (!EnableIfConversion)
3143 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3145 // A list of pointers that we can safely read and write to.
3146 SmallPtrSet<Value *, 8> SafePointes;
3148 // Collect safe addresses.
3149 for (Loop::block_iterator BI = TheLoop->block_begin(),
3150 BE = TheLoop->block_end(); BI != BE; ++BI) {
3151 BasicBlock *BB = *BI;
3153 if (blockNeedsPredication(BB))
3156 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3157 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3158 SafePointes.insert(LI->getPointerOperand());
3159 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3160 SafePointes.insert(SI->getPointerOperand());
3164 // Collect the blocks that need predication.
3165 BasicBlock *Header = TheLoop->getHeader();
3166 for (Loop::block_iterator BI = TheLoop->block_begin(),
3167 BE = TheLoop->block_end(); BI != BE; ++BI) {
3168 BasicBlock *BB = *BI;
3170 // We don't support switch statements inside loops.
3171 if (!isa<BranchInst>(BB->getTerminator()))
3174 // We must be able to predicate all blocks that need to be predicated.
3175 if (blockNeedsPredication(BB)) {
3176 if (!blockCanBePredicated(BB, SafePointes))
3178 } else if (BB != Header && !canIfConvertPHINodes(BB))
3183 // We can if-convert this loop.
3187 bool LoopVectorizationLegality::canVectorize() {
3188 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3189 // be canonicalized.
3190 if (!TheLoop->getLoopPreheader())
3193 // We can only vectorize innermost loops.
3194 if (TheLoop->getSubLoopsVector().size())
3197 // We must have a single backedge.
3198 if (TheLoop->getNumBackEdges() != 1)
3201 // We must have a single exiting block.
3202 if (!TheLoop->getExitingBlock())
3205 // We need to have a loop header.
3206 DEBUG(dbgs() << "LV: Found a loop: " <<
3207 TheLoop->getHeader()->getName() << '\n');
3209 // Check if we can if-convert non-single-bb loops.
3210 unsigned NumBlocks = TheLoop->getNumBlocks();
3211 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3212 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3216 // ScalarEvolution needs to be able to find the exit count.
3217 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3218 if (ExitCount == SE->getCouldNotCompute()) {
3219 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3223 // Check if we can vectorize the instructions and CFG in this loop.
3224 if (!canVectorizeInstrs()) {
3225 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3229 // Go over each instruction and look at memory deps.
3230 if (!canVectorizeMemory()) {
3231 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3235 // Collect all of the variables that remain uniform after vectorization.
3236 collectLoopUniforms();
3238 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3239 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3242 // Okay! We can vectorize. At this point we don't have any other mem analysis
3243 // which may limit our maximum vectorization factor, so just return true with
3248 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3249 if (Ty->isPointerTy())
3250 return DL.getIntPtrType(Ty);
3252 // It is possible that char's or short's overflow when we ask for the loop's
3253 // trip count, work around this by changing the type size.
3254 if (Ty->getScalarSizeInBits() < 32)
3255 return Type::getInt32Ty(Ty->getContext());
3260 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3261 Ty0 = convertPointerToIntegerType(DL, Ty0);
3262 Ty1 = convertPointerToIntegerType(DL, Ty1);
3263 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3268 /// \brief Check that the instruction has outside loop users and is not an
3269 /// identified reduction variable.
3270 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3271 SmallPtrSet<Value *, 4> &Reductions) {
3272 // Reduction instructions are allowed to have exit users. All other
3273 // instructions must not have external users.
3274 if (!Reductions.count(Inst))
3275 //Check that all of the users of the loop are inside the BB.
3276 for (User *U : Inst->users()) {
3277 Instruction *UI = cast<Instruction>(U);
3278 // This user may be a reduction exit value.
3279 if (!TheLoop->contains(UI)) {
3280 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3287 bool LoopVectorizationLegality::canVectorizeInstrs() {
3288 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3289 BasicBlock *Header = TheLoop->getHeader();
3291 // Look for the attribute signaling the absence of NaNs.
3292 Function &F = *Header->getParent();
3293 if (F.hasFnAttribute("no-nans-fp-math"))
3294 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3295 AttributeSet::FunctionIndex,
3296 "no-nans-fp-math").getValueAsString() == "true";
3298 // For each block in the loop.
3299 for (Loop::block_iterator bb = TheLoop->block_begin(),
3300 be = TheLoop->block_end(); bb != be; ++bb) {
3302 // Scan the instructions in the block and look for hazards.
3303 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3306 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3307 Type *PhiTy = Phi->getType();
3308 // Check that this PHI type is allowed.
3309 if (!PhiTy->isIntegerTy() &&
3310 !PhiTy->isFloatingPointTy() &&
3311 !PhiTy->isPointerTy()) {
3312 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3316 // If this PHINode is not in the header block, then we know that we
3317 // can convert it to select during if-conversion. No need to check if
3318 // the PHIs in this block are induction or reduction variables.
3319 if (*bb != Header) {
3320 // Check that this instruction has no outside users or is an
3321 // identified reduction value with an outside user.
3322 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3327 // We only allow if-converted PHIs with more than two incoming values.
3328 if (Phi->getNumIncomingValues() != 2) {
3329 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3333 // This is the value coming from the preheader.
3334 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3335 // Check if this is an induction variable.
3336 InductionKind IK = isInductionVariable(Phi);
3338 if (IK_NoInduction != IK) {
3339 // Get the widest type.
3341 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3343 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3345 // Int inductions are special because we only allow one IV.
3346 if (IK == IK_IntInduction) {
3347 // Use the phi node with the widest type as induction. Use the last
3348 // one if there are multiple (no good reason for doing this other
3349 // than it is expedient).
3350 if (!Induction || PhiTy == WidestIndTy)
3354 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3355 Inductions[Phi] = InductionInfo(StartValue, IK);
3357 // Until we explicitly handle the case of an induction variable with
3358 // an outside loop user we have to give up vectorizing this loop.
3359 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3365 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3366 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3369 if (AddReductionVar(Phi, RK_IntegerMult)) {
3370 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3373 if (AddReductionVar(Phi, RK_IntegerOr)) {
3374 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3377 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3378 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3381 if (AddReductionVar(Phi, RK_IntegerXor)) {
3382 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3385 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3386 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3389 if (AddReductionVar(Phi, RK_FloatMult)) {
3390 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3393 if (AddReductionVar(Phi, RK_FloatAdd)) {
3394 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3397 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3398 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3403 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3405 }// end of PHI handling
3407 // We still don't handle functions. However, we can ignore dbg intrinsic
3408 // calls and we do handle certain intrinsic and libm functions.
3409 CallInst *CI = dyn_cast<CallInst>(it);
3410 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3411 DEBUG(dbgs() << "LV: Found a call site.\n");
3415 // Check that the instruction return type is vectorizable.
3416 // Also, we can't vectorize extractelement instructions.
3417 if ((!VectorType::isValidElementType(it->getType()) &&
3418 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3419 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3423 // Check that the stored type is vectorizable.
3424 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3425 Type *T = ST->getValueOperand()->getType();
3426 if (!VectorType::isValidElementType(T))
3428 if (EnableMemAccessVersioning)
3429 collectStridedAcccess(ST);
3432 if (EnableMemAccessVersioning)
3433 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3434 collectStridedAcccess(LI);
3436 // Reduction instructions are allowed to have exit users.
3437 // All other instructions must not have external users.
3438 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3446 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3447 if (Inductions.empty())
3454 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3455 /// return the induction operand of the gep pointer.
3456 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3457 const DataLayout *DL, Loop *Lp) {
3458 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3462 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3464 // Check that all of the gep indices are uniform except for our induction
3466 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3467 if (i != InductionOperand &&
3468 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3470 return GEP->getOperand(InductionOperand);
3473 ///\brief Look for a cast use of the passed value.
3474 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3475 Value *UniqueCast = nullptr;
3476 for (User *U : Ptr->users()) {
3477 CastInst *CI = dyn_cast<CastInst>(U);
3478 if (CI && CI->getType() == Ty) {
3488 ///\brief Get the stride of a pointer access in a loop.
3489 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3490 /// pointer to the Value, or null otherwise.
3491 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3492 const DataLayout *DL, Loop *Lp) {
3493 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3494 if (!PtrTy || PtrTy->isAggregateType())
3497 // Try to remove a gep instruction to make the pointer (actually index at this
3498 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3499 // pointer, otherwise, we are analyzing the index.
3500 Value *OrigPtr = Ptr;
3502 // The size of the pointer access.
3503 int64_t PtrAccessSize = 1;
3505 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3506 const SCEV *V = SE->getSCEV(Ptr);
3510 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3511 V = C->getOperand();
3513 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3517 V = S->getStepRecurrence(*SE);
3521 // Strip off the size of access multiplication if we are still analyzing the
3523 if (OrigPtr == Ptr) {
3524 DL->getTypeAllocSize(PtrTy->getElementType());
3525 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3526 if (M->getOperand(0)->getSCEVType() != scConstant)
3529 const APInt &APStepVal =
3530 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3532 // Huge step value - give up.
3533 if (APStepVal.getBitWidth() > 64)
3536 int64_t StepVal = APStepVal.getSExtValue();
3537 if (PtrAccessSize != StepVal)
3539 V = M->getOperand(1);
3544 Type *StripedOffRecurrenceCast = nullptr;
3545 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3546 StripedOffRecurrenceCast = C->getType();
3547 V = C->getOperand();
3550 // Look for the loop invariant symbolic value.
3551 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3555 Value *Stride = U->getValue();
3556 if (!Lp->isLoopInvariant(Stride))
3559 // If we have stripped off the recurrence cast we have to make sure that we
3560 // return the value that is used in this loop so that we can replace it later.
3561 if (StripedOffRecurrenceCast)
3562 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3567 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3568 Value *Ptr = nullptr;
3569 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3570 Ptr = LI->getPointerOperand();
3571 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3572 Ptr = SI->getPointerOperand();
3576 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3580 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3581 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3582 Strides[Ptr] = Stride;
3583 StrideSet.insert(Stride);
3586 void LoopVectorizationLegality::collectLoopUniforms() {
3587 // We now know that the loop is vectorizable!
3588 // Collect variables that will remain uniform after vectorization.
3589 std::vector<Value*> Worklist;
3590 BasicBlock *Latch = TheLoop->getLoopLatch();
3592 // Start with the conditional branch and walk up the block.
3593 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3595 // Also add all consecutive pointer values; these values will be uniform
3596 // after vectorization (and subsequent cleanup) and, until revectorization is
3597 // supported, all dependencies must also be uniform.
3598 for (Loop::block_iterator B = TheLoop->block_begin(),
3599 BE = TheLoop->block_end(); B != BE; ++B)
3600 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3602 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3603 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3605 while (Worklist.size()) {
3606 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3607 Worklist.pop_back();
3609 // Look at instructions inside this loop.
3610 // Stop when reaching PHI nodes.
3611 // TODO: we need to follow values all over the loop, not only in this block.
3612 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3615 // This is a known uniform.
3618 // Insert all operands.
3619 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3624 /// \brief Analyses memory accesses in a loop.
3626 /// Checks whether run time pointer checks are needed and builds sets for data
3627 /// dependence checking.
3628 class AccessAnalysis {
3630 /// \brief Read or write access location.
3631 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3632 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3634 /// \brief Set of potential dependent memory accesses.
3635 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3637 AccessAnalysis(const DataLayout *Dl, DepCandidates &DA) :
3638 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3639 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3641 /// \brief Register a load and whether it is only read from.
3642 void addLoad(Value *Ptr, bool IsReadOnly) {
3643 Accesses.insert(MemAccessInfo(Ptr, false));
3645 ReadOnlyPtr.insert(Ptr);
3648 /// \brief Register a store.
3649 void addStore(Value *Ptr) {
3650 Accesses.insert(MemAccessInfo(Ptr, true));
3653 /// \brief Check whether we can check the pointers at runtime for
3654 /// non-intersection.
3655 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3656 unsigned &NumComparisons, ScalarEvolution *SE,
3657 Loop *TheLoop, ValueToValueMap &Strides,
3658 bool ShouldCheckStride = false);
3660 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3661 /// and builds sets of dependent accesses.
3662 void buildDependenceSets() {
3663 // Process read-write pointers first.
3664 processMemAccesses(false);
3665 // Next, process read pointers.
3666 processMemAccesses(true);
3669 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3671 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3672 void resetDepChecks() { CheckDeps.clear(); }
3674 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3677 typedef SetVector<MemAccessInfo> PtrAccessSet;
3678 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3680 /// \brief Go over all memory access or only the deferred ones if
3681 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3682 /// and build sets of dependency check candidates.
3683 void processMemAccesses(bool UseDeferred);
3685 /// Set of all accesses.
3686 PtrAccessSet Accesses;
3688 /// Set of access to check after all writes have been processed.
3689 PtrAccessSet DeferredAccesses;
3691 /// Map of pointers to last access encountered.
3692 UnderlyingObjToAccessMap ObjToLastAccess;
3694 /// Set of accesses that need a further dependence check.
3695 MemAccessInfoSet CheckDeps;
3697 /// Set of pointers that are read only.
3698 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3700 /// Set of underlying objects already written to.
3701 SmallPtrSet<Value*, 16> WriteObjects;
3703 const DataLayout *DL;
3705 /// Sets of potentially dependent accesses - members of one set share an
3706 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3707 /// dependence check.
3708 DepCandidates &DepCands;
3710 bool AreAllWritesIdentified;
3711 bool AreAllReadsIdentified;
3712 bool IsRTCheckNeeded;
3715 } // end anonymous namespace
3717 /// \brief Check whether a pointer can participate in a runtime bounds check.
3718 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3720 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3721 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3725 return AR->isAffine();
3728 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3729 /// the address space.
3730 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
3731 const Loop *Lp, ValueToValueMap &StridesMap);
3733 bool AccessAnalysis::canCheckPtrAtRT(
3734 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3735 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3736 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3737 // Find pointers with computable bounds. We are going to use this information
3738 // to place a runtime bound check.
3739 unsigned NumReadPtrChecks = 0;
3740 unsigned NumWritePtrChecks = 0;
3741 bool CanDoRT = true;
3743 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3744 // We assign consecutive id to access from different dependence sets.
3745 // Accesses within the same set don't need a runtime check.
3746 unsigned RunningDepId = 1;
3747 DenseMap<Value *, unsigned> DepSetId;
3749 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3751 const MemAccessInfo &Access = *AI;
3752 Value *Ptr = Access.getPointer();
3753 bool IsWrite = Access.getInt();
3755 // Just add write checks if we have both.
3756 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3760 ++NumWritePtrChecks;
3764 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3765 // When we run after a failing dependency check we have to make sure we
3766 // don't have wrapping pointers.
3767 (!ShouldCheckStride ||
3768 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3769 // The id of the dependence set.
3772 if (IsDepCheckNeeded) {
3773 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3774 unsigned &LeaderId = DepSetId[Leader];
3776 LeaderId = RunningDepId++;
3779 // Each access has its own dependence set.
3780 DepId = RunningDepId++;
3782 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3784 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3790 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3791 NumComparisons = 0; // Only one dependence set.
3793 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3794 NumWritePtrChecks - 1));
3797 // If the pointers that we would use for the bounds comparison have different
3798 // address spaces, assume the values aren't directly comparable, so we can't
3799 // use them for the runtime check. We also have to assume they could
3800 // overlap. In the future there should be metadata for whether address spaces
3802 unsigned NumPointers = RtCheck.Pointers.size();
3803 for (unsigned i = 0; i < NumPointers; ++i) {
3804 for (unsigned j = i + 1; j < NumPointers; ++j) {
3805 // Only need to check pointers between two different dependency sets.
3806 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3809 Value *PtrI = RtCheck.Pointers[i];
3810 Value *PtrJ = RtCheck.Pointers[j];
3812 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3813 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3815 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3816 " different address spaces\n");
3825 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3826 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3829 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3830 // We process the set twice: first we process read-write pointers, last we
3831 // process read-only pointers. This allows us to skip dependence tests for
3832 // read-only pointers.
3834 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3835 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3836 const MemAccessInfo &Access = *AI;
3837 Value *Ptr = Access.getPointer();
3838 bool IsWrite = Access.getInt();
3840 DepCands.insert(Access);
3842 // Memorize read-only pointers for later processing and skip them in the
3843 // first round (they need to be checked after we have seen all write
3844 // pointers). Note: we also mark pointer that are not consecutive as
3845 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3846 // second check for "!IsWrite".
3847 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3848 if (!UseDeferred && IsReadOnlyPtr) {
3849 DeferredAccesses.insert(Access);
3853 bool NeedDepCheck = false;
3854 // Check whether there is the possibility of dependency because of
3855 // underlying objects being the same.
3856 typedef SmallVector<Value*, 16> ValueVector;
3857 ValueVector TempObjects;
3858 GetUnderlyingObjects(Ptr, TempObjects, DL);
3859 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3861 Value *UnderlyingObj = *UI;
3863 // If this is a write then it needs to be an identified object. If this a
3864 // read and all writes (so far) are identified function scope objects we
3865 // don't need an identified underlying object but only an Argument (the
3866 // next write is going to invalidate this assumption if it is
3868 // This is a micro-optimization for the case where all writes are
3869 // identified and we have one argument pointer.
3870 // Otherwise, we do need a runtime check.
3871 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3872 (!IsWrite && (!AreAllWritesIdentified ||
3873 !isa<Argument>(UnderlyingObj)) &&
3874 !isIdentifiedObject(UnderlyingObj))) {
3875 DEBUG(dbgs() << "LV: Found an unidentified " <<
3876 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3878 IsRTCheckNeeded = (IsRTCheckNeeded ||
3879 !isIdentifiedObject(UnderlyingObj) ||
3880 !AreAllReadsIdentified);
3883 AreAllWritesIdentified = false;
3885 AreAllReadsIdentified = false;
3888 // If this is a write - check other reads and writes for conflicts. If
3889 // this is a read only check other writes for conflicts (but only if there
3890 // is no other write to the ptr - this is an optimization to catch "a[i] =
3891 // a[i] + " without having to do a dependence check).
3892 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3893 NeedDepCheck = true;
3896 WriteObjects.insert(UnderlyingObj);
3898 // Create sets of pointers connected by shared underlying objects.
3899 UnderlyingObjToAccessMap::iterator Prev =
3900 ObjToLastAccess.find(UnderlyingObj);
3901 if (Prev != ObjToLastAccess.end())
3902 DepCands.unionSets(Access, Prev->second);
3904 ObjToLastAccess[UnderlyingObj] = Access;
3908 CheckDeps.insert(Access);
3913 /// \brief Checks memory dependences among accesses to the same underlying
3914 /// object to determine whether there vectorization is legal or not (and at
3915 /// which vectorization factor).
3917 /// This class works under the assumption that we already checked that memory
3918 /// locations with different underlying pointers are "must-not alias".
3919 /// We use the ScalarEvolution framework to symbolically evalutate access
3920 /// functions pairs. Since we currently don't restructure the loop we can rely
3921 /// on the program order of memory accesses to determine their safety.
3922 /// At the moment we will only deem accesses as safe for:
3923 /// * A negative constant distance assuming program order.
3925 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
3926 /// a[i] = tmp; y = a[i];
3928 /// The latter case is safe because later checks guarantuee that there can't
3929 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
3930 /// the same variable: a header phi can only be an induction or a reduction, a
3931 /// reduction can't have a memory sink, an induction can't have a memory
3932 /// source). This is important and must not be violated (or we have to
3933 /// resort to checking for cycles through memory).
3935 /// * A positive constant distance assuming program order that is bigger
3936 /// than the biggest memory access.
3938 /// tmp = a[i] OR b[i] = x
3939 /// a[i+2] = tmp y = b[i+2];
3941 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3943 /// * Zero distances and all accesses have the same size.
3945 class MemoryDepChecker {
3947 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3948 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3950 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
3951 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
3952 ShouldRetryWithRuntimeCheck(false) {}
3954 /// \brief Register the location (instructions are given increasing numbers)
3955 /// of a write access.
3956 void addAccess(StoreInst *SI) {
3957 Value *Ptr = SI->getPointerOperand();
3958 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3959 InstMap.push_back(SI);
3963 /// \brief Register the location (instructions are given increasing numbers)
3964 /// of a write access.
3965 void addAccess(LoadInst *LI) {
3966 Value *Ptr = LI->getPointerOperand();
3967 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
3968 InstMap.push_back(LI);
3972 /// \brief Check whether the dependencies between the accesses are safe.
3974 /// Only checks sets with elements in \p CheckDeps.
3975 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3976 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
3978 /// \brief The maximum number of bytes of a vector register we can vectorize
3979 /// the accesses safely with.
3980 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
3982 /// \brief In same cases when the dependency check fails we can still
3983 /// vectorize the loop with a dynamic array access check.
3984 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
3987 ScalarEvolution *SE;
3988 const DataLayout *DL;
3989 const Loop *InnermostLoop;
3991 /// \brief Maps access locations (ptr, read/write) to program order.
3992 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
3994 /// \brief Memory access instructions in program order.
3995 SmallVector<Instruction *, 16> InstMap;
3997 /// \brief The program order index to be used for the next instruction.
4000 // We can access this many bytes in parallel safely.
4001 unsigned MaxSafeDepDistBytes;
4003 /// \brief If we see a non-constant dependence distance we can still try to
4004 /// vectorize this loop with runtime checks.
4005 bool ShouldRetryWithRuntimeCheck;
4007 /// \brief Check whether there is a plausible dependence between the two
4010 /// Access \p A must happen before \p B in program order. The two indices
4011 /// identify the index into the program order map.
4013 /// This function checks whether there is a plausible dependence (or the
4014 /// absence of such can't be proved) between the two accesses. If there is a
4015 /// plausible dependence but the dependence distance is bigger than one
4016 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4017 /// distance is smaller than any other distance encountered so far).
4018 /// Otherwise, this function returns true signaling a possible dependence.
4019 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4020 const MemAccessInfo &B, unsigned BIdx,
4021 ValueToValueMap &Strides);
4023 /// \brief Check whether the data dependence could prevent store-load
4025 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4028 } // end anonymous namespace
4030 static bool isInBoundsGep(Value *Ptr) {
4031 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4032 return GEP->isInBounds();
4036 /// \brief Check whether the access through \p Ptr has a constant stride.
4037 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4038 const Loop *Lp, ValueToValueMap &StridesMap) {
4039 const Type *Ty = Ptr->getType();
4040 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4042 // Make sure that the pointer does not point to aggregate types.
4043 const PointerType *PtrTy = cast<PointerType>(Ty);
4044 if (PtrTy->getElementType()->isAggregateType()) {
4045 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4050 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4052 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4054 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4055 << *Ptr << " SCEV: " << *PtrScev << "\n");
4059 // The accesss function must stride over the innermost loop.
4060 if (Lp != AR->getLoop()) {
4061 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4062 *Ptr << " SCEV: " << *PtrScev << "\n");
4065 // The address calculation must not wrap. Otherwise, a dependence could be
4067 // An inbounds getelementptr that is a AddRec with a unit stride
4068 // cannot wrap per definition. The unit stride requirement is checked later.
4069 // An getelementptr without an inbounds attribute and unit stride would have
4070 // to access the pointer value "0" which is undefined behavior in address
4071 // space 0, therefore we can also vectorize this case.
4072 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4073 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4074 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4075 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4076 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4077 << *Ptr << " SCEV: " << *PtrScev << "\n");
4081 // Check the step is constant.
4082 const SCEV *Step = AR->getStepRecurrence(*SE);
4084 // Calculate the pointer stride and check if it is consecutive.
4085 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4087 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4088 " SCEV: " << *PtrScev << "\n");
4092 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4093 const APInt &APStepVal = C->getValue()->getValue();
4095 // Huge step value - give up.
4096 if (APStepVal.getBitWidth() > 64)
4099 int64_t StepVal = APStepVal.getSExtValue();
4102 int64_t Stride = StepVal / Size;
4103 int64_t Rem = StepVal % Size;
4107 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4108 // know we can't "wrap around the address space". In case of address space
4109 // zero we know that this won't happen without triggering undefined behavior.
4110 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4111 Stride != 1 && Stride != -1)
4117 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4118 unsigned TypeByteSize) {
4119 // If loads occur at a distance that is not a multiple of a feasible vector
4120 // factor store-load forwarding does not take place.
4121 // Positive dependences might cause troubles because vectorizing them might
4122 // prevent store-load forwarding making vectorized code run a lot slower.
4123 // a[i] = a[i-3] ^ a[i-8];
4124 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4125 // hence on your typical architecture store-load forwarding does not take
4126 // place. Vectorizing in such cases does not make sense.
4127 // Store-load forwarding distance.
4128 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4129 // Maximum vector factor.
4130 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4131 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4132 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4134 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4136 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4137 MaxVFWithoutSLForwardIssues = (vf >>=1);
4142 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4143 DEBUG(dbgs() << "LV: Distance " << Distance <<
4144 " that could cause a store-load forwarding conflict\n");
4148 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4149 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4150 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4154 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4155 const MemAccessInfo &B, unsigned BIdx,
4156 ValueToValueMap &Strides) {
4157 assert (AIdx < BIdx && "Must pass arguments in program order");
4159 Value *APtr = A.getPointer();
4160 Value *BPtr = B.getPointer();
4161 bool AIsWrite = A.getInt();
4162 bool BIsWrite = B.getInt();
4164 // Two reads are independent.
4165 if (!AIsWrite && !BIsWrite)
4168 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4169 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4171 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4172 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4174 const SCEV *Src = AScev;
4175 const SCEV *Sink = BScev;
4177 // If the induction step is negative we have to invert source and sink of the
4179 if (StrideAPtr < 0) {
4182 std::swap(APtr, BPtr);
4183 std::swap(Src, Sink);
4184 std::swap(AIsWrite, BIsWrite);
4185 std::swap(AIdx, BIdx);
4186 std::swap(StrideAPtr, StrideBPtr);
4189 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4191 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4192 << "(Induction step: " << StrideAPtr << ")\n");
4193 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4194 << *InstMap[BIdx] << ": " << *Dist << "\n");
4196 // Need consecutive accesses. We don't want to vectorize
4197 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4198 // the address space.
4199 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4200 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4204 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4206 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4207 ShouldRetryWithRuntimeCheck = true;
4211 Type *ATy = APtr->getType()->getPointerElementType();
4212 Type *BTy = BPtr->getType()->getPointerElementType();
4213 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4215 // Negative distances are not plausible dependencies.
4216 const APInt &Val = C->getValue()->getValue();
4217 if (Val.isNegative()) {
4218 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4219 if (IsTrueDataDependence &&
4220 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4224 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4228 // Write to the same location with the same size.
4229 // Could be improved to assert type sizes are the same (i32 == float, etc).
4233 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4237 assert(Val.isStrictlyPositive() && "Expect a positive value");
4239 // Positive distance bigger than max vectorization factor.
4242 "LV: ReadWrite-Write positive dependency with different types\n");
4246 unsigned Distance = (unsigned) Val.getZExtValue();
4248 // Bail out early if passed-in parameters make vectorization not feasible.
4249 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4250 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4252 // The distance must be bigger than the size needed for a vectorized version
4253 // of the operation and the size of the vectorized operation must not be
4254 // bigger than the currrent maximum size.
4255 if (Distance < 2*TypeByteSize ||
4256 2*TypeByteSize > MaxSafeDepDistBytes ||
4257 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4258 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4259 << Val.getSExtValue() << '\n');
4263 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4264 Distance : MaxSafeDepDistBytes;
4266 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4267 if (IsTrueDataDependence &&
4268 couldPreventStoreLoadForward(Distance, TypeByteSize))
4271 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4272 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4277 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4278 MemAccessInfoSet &CheckDeps,
4279 ValueToValueMap &Strides) {
4281 MaxSafeDepDistBytes = -1U;
4282 while (!CheckDeps.empty()) {
4283 MemAccessInfo CurAccess = *CheckDeps.begin();
4285 // Get the relevant memory access set.
4286 EquivalenceClasses<MemAccessInfo>::iterator I =
4287 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4289 // Check accesses within this set.
4290 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4291 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4293 // Check every access pair.
4295 CheckDeps.erase(*AI);
4296 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4298 // Check every accessing instruction pair in program order.
4299 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4300 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4301 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4302 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4303 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4305 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4316 bool LoopVectorizationLegality::canVectorizeMemory() {
4318 typedef SmallVector<Value*, 16> ValueVector;
4319 typedef SmallPtrSet<Value*, 16> ValueSet;
4321 // Holds the Load and Store *instructions*.
4325 // Holds all the different accesses in the loop.
4326 unsigned NumReads = 0;
4327 unsigned NumReadWrites = 0;
4329 PtrRtCheck.Pointers.clear();
4330 PtrRtCheck.Need = false;
4332 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4333 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4336 for (Loop::block_iterator bb = TheLoop->block_begin(),
4337 be = TheLoop->block_end(); bb != be; ++bb) {
4339 // Scan the BB and collect legal loads and stores.
4340 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4343 // If this is a load, save it. If this instruction can read from memory
4344 // but is not a load, then we quit. Notice that we don't handle function
4345 // calls that read or write.
4346 if (it->mayReadFromMemory()) {
4347 // Many math library functions read the rounding mode. We will only
4348 // vectorize a loop if it contains known function calls that don't set
4349 // the flag. Therefore, it is safe to ignore this read from memory.
4350 CallInst *Call = dyn_cast<CallInst>(it);
4351 if (Call && getIntrinsicIDForCall(Call, TLI))
4354 LoadInst *Ld = dyn_cast<LoadInst>(it);
4355 if (!Ld) return false;
4356 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4357 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4361 Loads.push_back(Ld);
4362 DepChecker.addAccess(Ld);
4366 // Save 'store' instructions. Abort if other instructions write to memory.
4367 if (it->mayWriteToMemory()) {
4368 StoreInst *St = dyn_cast<StoreInst>(it);
4369 if (!St) return false;
4370 if (!St->isSimple() && !IsAnnotatedParallel) {
4371 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4375 Stores.push_back(St);
4376 DepChecker.addAccess(St);
4381 // Now we have two lists that hold the loads and the stores.
4382 // Next, we find the pointers that they use.
4384 // Check if we see any stores. If there are no stores, then we don't
4385 // care if the pointers are *restrict*.
4386 if (!Stores.size()) {
4387 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4391 AccessAnalysis::DepCandidates DependentAccesses;
4392 AccessAnalysis Accesses(DL, DependentAccesses);
4394 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4395 // multiple times on the same object. If the ptr is accessed twice, once
4396 // for read and once for write, it will only appear once (on the write
4397 // list). This is okay, since we are going to check for conflicts between
4398 // writes and between reads and writes, but not between reads and reads.
4401 ValueVector::iterator I, IE;
4402 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4403 StoreInst *ST = cast<StoreInst>(*I);
4404 Value* Ptr = ST->getPointerOperand();
4406 if (isUniform(Ptr)) {
4407 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4411 // If we did *not* see this pointer before, insert it to the read-write
4412 // list. At this phase it is only a 'write' list.
4413 if (Seen.insert(Ptr)) {
4415 Accesses.addStore(Ptr);
4419 if (IsAnnotatedParallel) {
4421 << "LV: A loop annotated parallel, ignore memory dependency "
4426 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4427 LoadInst *LD = cast<LoadInst>(*I);
4428 Value* Ptr = LD->getPointerOperand();
4429 // If we did *not* see this pointer before, insert it to the
4430 // read list. If we *did* see it before, then it is already in
4431 // the read-write list. This allows us to vectorize expressions
4432 // such as A[i] += x; Because the address of A[i] is a read-write
4433 // pointer. This only works if the index of A[i] is consecutive.
4434 // If the address of i is unknown (for example A[B[i]]) then we may
4435 // read a few words, modify, and write a few words, and some of the
4436 // words may be written to the same address.
4437 bool IsReadOnlyPtr = false;
4438 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4440 IsReadOnlyPtr = true;
4442 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4445 // If we write (or read-write) to a single destination and there are no
4446 // other reads in this loop then is it safe to vectorize.
4447 if (NumReadWrites == 1 && NumReads == 0) {
4448 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4452 // Build dependence sets and check whether we need a runtime pointer bounds
4454 Accesses.buildDependenceSets();
4455 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4457 // Find pointers with computable bounds. We are going to use this information
4458 // to place a runtime bound check.
4459 unsigned NumComparisons = 0;
4460 bool CanDoRT = false;
4462 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4465 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4466 " pointer comparisons.\n");
4468 // If we only have one set of dependences to check pointers among we don't
4469 // need a runtime check.
4470 if (NumComparisons == 0 && NeedRTCheck)
4471 NeedRTCheck = false;
4473 // Check that we did not collect too many pointers or found an unsizeable
4475 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4481 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4484 if (NeedRTCheck && !CanDoRT) {
4485 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4486 "the array bounds.\n");
4491 PtrRtCheck.Need = NeedRTCheck;
4493 bool CanVecMem = true;
4494 if (Accesses.isDependencyCheckNeeded()) {
4495 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4496 CanVecMem = DepChecker.areDepsSafe(
4497 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4498 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4500 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4501 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4504 // Clear the dependency checks. We assume they are not needed.
4505 Accesses.resetDepChecks();
4508 PtrRtCheck.Need = true;
4510 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4511 TheLoop, Strides, true);
4512 // Check that we did not collect too many pointers or found an unsizeable
4514 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4515 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4524 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4525 " need a runtime memory check.\n");
4530 static bool hasMultipleUsesOf(Instruction *I,
4531 SmallPtrSet<Instruction *, 8> &Insts) {
4532 unsigned NumUses = 0;
4533 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4534 if (Insts.count(dyn_cast<Instruction>(*Use)))
4543 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4544 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4545 if (!Set.count(dyn_cast<Instruction>(*Use)))
4550 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4551 ReductionKind Kind) {
4552 if (Phi->getNumIncomingValues() != 2)
4555 // Reduction variables are only found in the loop header block.
4556 if (Phi->getParent() != TheLoop->getHeader())
4559 // Obtain the reduction start value from the value that comes from the loop
4561 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4563 // ExitInstruction is the single value which is used outside the loop.
4564 // We only allow for a single reduction value to be used outside the loop.
4565 // This includes users of the reduction, variables (which form a cycle
4566 // which ends in the phi node).
4567 Instruction *ExitInstruction = nullptr;
4568 // Indicates that we found a reduction operation in our scan.
4569 bool FoundReduxOp = false;
4571 // We start with the PHI node and scan for all of the users of this
4572 // instruction. All users must be instructions that can be used as reduction
4573 // variables (such as ADD). We must have a single out-of-block user. The cycle
4574 // must include the original PHI.
4575 bool FoundStartPHI = false;
4577 // To recognize min/max patterns formed by a icmp select sequence, we store
4578 // the number of instruction we saw from the recognized min/max pattern,
4579 // to make sure we only see exactly the two instructions.
4580 unsigned NumCmpSelectPatternInst = 0;
4581 ReductionInstDesc ReduxDesc(false, nullptr);
4583 SmallPtrSet<Instruction *, 8> VisitedInsts;
4584 SmallVector<Instruction *, 8> Worklist;
4585 Worklist.push_back(Phi);
4586 VisitedInsts.insert(Phi);
4588 // A value in the reduction can be used:
4589 // - By the reduction:
4590 // - Reduction operation:
4591 // - One use of reduction value (safe).
4592 // - Multiple use of reduction value (not safe).
4594 // - All uses of the PHI must be the reduction (safe).
4595 // - Otherwise, not safe.
4596 // - By one instruction outside of the loop (safe).
4597 // - By further instructions outside of the loop (not safe).
4598 // - By an instruction that is not part of the reduction (not safe).
4600 // * An instruction type other than PHI or the reduction operation.
4601 // * A PHI in the header other than the initial PHI.
4602 while (!Worklist.empty()) {
4603 Instruction *Cur = Worklist.back();
4604 Worklist.pop_back();
4607 // If the instruction has no users then this is a broken chain and can't be
4608 // a reduction variable.
4609 if (Cur->use_empty())
4612 bool IsAPhi = isa<PHINode>(Cur);
4614 // A header PHI use other than the original PHI.
4615 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4618 // Reductions of instructions such as Div, and Sub is only possible if the
4619 // LHS is the reduction variable.
4620 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4621 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4622 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4625 // Any reduction instruction must be of one of the allowed kinds.
4626 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4627 if (!ReduxDesc.IsReduction)
4630 // A reduction operation must only have one use of the reduction value.
4631 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4632 hasMultipleUsesOf(Cur, VisitedInsts))
4635 // All inputs to a PHI node must be a reduction value.
4636 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4639 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4640 isa<SelectInst>(Cur)))
4641 ++NumCmpSelectPatternInst;
4642 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4643 isa<SelectInst>(Cur)))
4644 ++NumCmpSelectPatternInst;
4646 // Check whether we found a reduction operator.
4647 FoundReduxOp |= !IsAPhi;
4649 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4650 // onto the stack. This way we are going to have seen all inputs to PHI
4651 // nodes once we get to them.
4652 SmallVector<Instruction *, 8> NonPHIs;
4653 SmallVector<Instruction *, 8> PHIs;
4654 for (User *U : Cur->users()) {
4655 Instruction *UI = cast<Instruction>(U);
4657 // Check if we found the exit user.
4658 BasicBlock *Parent = UI->getParent();
4659 if (!TheLoop->contains(Parent)) {
4660 // Exit if you find multiple outside users or if the header phi node is
4661 // being used. In this case the user uses the value of the previous
4662 // iteration, in which case we would loose "VF-1" iterations of the
4663 // reduction operation if we vectorize.
4664 if (ExitInstruction != nullptr || Cur == Phi)
4667 // The instruction used by an outside user must be the last instruction
4668 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4669 // operations on the value.
4670 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4673 ExitInstruction = Cur;
4677 // Process instructions only once (termination). Each reduction cycle
4678 // value must only be used once, except by phi nodes and min/max
4679 // reductions which are represented as a cmp followed by a select.
4680 ReductionInstDesc IgnoredVal(false, nullptr);
4681 if (VisitedInsts.insert(UI)) {
4682 if (isa<PHINode>(UI))
4685 NonPHIs.push_back(UI);
4686 } else if (!isa<PHINode>(UI) &&
4687 ((!isa<FCmpInst>(UI) &&
4688 !isa<ICmpInst>(UI) &&
4689 !isa<SelectInst>(UI)) ||
4690 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4693 // Remember that we completed the cycle.
4695 FoundStartPHI = true;
4697 Worklist.append(PHIs.begin(), PHIs.end());
4698 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4701 // This means we have seen one but not the other instruction of the
4702 // pattern or more than just a select and cmp.
4703 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4704 NumCmpSelectPatternInst != 2)
4707 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4710 // We found a reduction var if we have reached the original phi node and we
4711 // only have a single instruction with out-of-loop users.
4713 // This instruction is allowed to have out-of-loop users.
4714 AllowedExit.insert(ExitInstruction);
4716 // Save the description of this reduction variable.
4717 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4718 ReduxDesc.MinMaxKind);
4719 Reductions[Phi] = RD;
4720 // We've ended the cycle. This is a reduction variable if we have an
4721 // outside user and it has a binary op.
4726 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4727 /// pattern corresponding to a min(X, Y) or max(X, Y).
4728 LoopVectorizationLegality::ReductionInstDesc
4729 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4730 ReductionInstDesc &Prev) {
4732 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4733 "Expect a select instruction");
4734 Instruction *Cmp = nullptr;
4735 SelectInst *Select = nullptr;
4737 // We must handle the select(cmp()) as a single instruction. Advance to the
4739 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4740 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4741 return ReductionInstDesc(false, I);
4742 return ReductionInstDesc(Select, Prev.MinMaxKind);
4745 // Only handle single use cases for now.
4746 if (!(Select = dyn_cast<SelectInst>(I)))
4747 return ReductionInstDesc(false, I);
4748 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4749 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4750 return ReductionInstDesc(false, I);
4751 if (!Cmp->hasOneUse())
4752 return ReductionInstDesc(false, I);
4757 // Look for a min/max pattern.
4758 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4759 return ReductionInstDesc(Select, MRK_UIntMin);
4760 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4761 return ReductionInstDesc(Select, MRK_UIntMax);
4762 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4763 return ReductionInstDesc(Select, MRK_SIntMax);
4764 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4765 return ReductionInstDesc(Select, MRK_SIntMin);
4766 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4767 return ReductionInstDesc(Select, MRK_FloatMin);
4768 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4769 return ReductionInstDesc(Select, MRK_FloatMax);
4770 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4771 return ReductionInstDesc(Select, MRK_FloatMin);
4772 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4773 return ReductionInstDesc(Select, MRK_FloatMax);
4775 return ReductionInstDesc(false, I);
4778 LoopVectorizationLegality::ReductionInstDesc
4779 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4781 ReductionInstDesc &Prev) {
4782 bool FP = I->getType()->isFloatingPointTy();
4783 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4784 switch (I->getOpcode()) {
4786 return ReductionInstDesc(false, I);
4787 case Instruction::PHI:
4788 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4789 Kind != RK_FloatMinMax))
4790 return ReductionInstDesc(false, I);
4791 return ReductionInstDesc(I, Prev.MinMaxKind);
4792 case Instruction::Sub:
4793 case Instruction::Add:
4794 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4795 case Instruction::Mul:
4796 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4797 case Instruction::And:
4798 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4799 case Instruction::Or:
4800 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4801 case Instruction::Xor:
4802 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4803 case Instruction::FMul:
4804 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4805 case Instruction::FAdd:
4806 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4807 case Instruction::FCmp:
4808 case Instruction::ICmp:
4809 case Instruction::Select:
4810 if (Kind != RK_IntegerMinMax &&
4811 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4812 return ReductionInstDesc(false, I);
4813 return isMinMaxSelectCmpPattern(I, Prev);
4817 LoopVectorizationLegality::InductionKind
4818 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4819 Type *PhiTy = Phi->getType();
4820 // We only handle integer and pointer inductions variables.
4821 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4822 return IK_NoInduction;
4824 // Check that the PHI is consecutive.
4825 const SCEV *PhiScev = SE->getSCEV(Phi);
4826 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4828 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4829 return IK_NoInduction;
4831 const SCEV *Step = AR->getStepRecurrence(*SE);
4833 // Integer inductions need to have a stride of one.
4834 if (PhiTy->isIntegerTy()) {
4836 return IK_IntInduction;
4837 if (Step->isAllOnesValue())
4838 return IK_ReverseIntInduction;
4839 return IK_NoInduction;
4842 // Calculate the pointer stride and check if it is consecutive.
4843 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4845 return IK_NoInduction;
4847 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4848 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4849 if (C->getValue()->equalsInt(Size))
4850 return IK_PtrInduction;
4851 else if (C->getValue()->equalsInt(0 - Size))
4852 return IK_ReversePtrInduction;
4854 return IK_NoInduction;
4857 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4858 Value *In0 = const_cast<Value*>(V);
4859 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4863 return Inductions.count(PN);
4866 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4867 assert(TheLoop->contains(BB) && "Unknown block used");
4869 // Blocks that do not dominate the latch need predication.
4870 BasicBlock* Latch = TheLoop->getLoopLatch();
4871 return !DT->dominates(BB, Latch);
4874 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4875 SmallPtrSet<Value *, 8>& SafePtrs) {
4876 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4877 // We might be able to hoist the load.
4878 if (it->mayReadFromMemory()) {
4879 LoadInst *LI = dyn_cast<LoadInst>(it);
4880 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4884 // We don't predicate stores at the moment.
4885 if (it->mayWriteToMemory()) {
4886 StoreInst *SI = dyn_cast<StoreInst>(it);
4887 // We only support predication of stores in basic blocks with one
4889 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
4890 !SafePtrs.count(SI->getPointerOperand()) ||
4891 !SI->getParent()->getSinglePredecessor())
4897 // Check that we don't have a constant expression that can trap as operand.
4898 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4900 if (Constant *C = dyn_cast<Constant>(*OI))
4905 // The instructions below can trap.
4906 switch (it->getOpcode()) {
4908 case Instruction::UDiv:
4909 case Instruction::SDiv:
4910 case Instruction::URem:
4911 case Instruction::SRem:
4919 LoopVectorizationCostModel::VectorizationFactor
4920 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4922 bool ForceVectorization) {
4923 // Width 1 means no vectorize
4924 VectorizationFactor Factor = { 1U, 0U };
4925 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4926 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4930 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
4931 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4935 // Find the trip count.
4936 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4937 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4939 unsigned WidestType = getWidestType();
4940 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4941 unsigned MaxSafeDepDist = -1U;
4942 if (Legal->getMaxSafeDepDistBytes() != -1U)
4943 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4944 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4945 WidestRegister : MaxSafeDepDist);
4946 unsigned MaxVectorSize = WidestRegister / WidestType;
4947 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4948 DEBUG(dbgs() << "LV: The Widest register is: "
4949 << WidestRegister << " bits.\n");
4951 if (MaxVectorSize == 0) {
4952 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4956 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4957 " into one vector!");
4959 unsigned VF = MaxVectorSize;
4961 // If we optimize the program for size, avoid creating the tail loop.
4963 // If we are unable to calculate the trip count then don't try to vectorize.
4965 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4969 // Find the maximum SIMD width that can fit within the trip count.
4970 VF = TC % MaxVectorSize;
4975 // If the trip count that we found modulo the vectorization factor is not
4976 // zero then we require a tail.
4978 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4984 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4985 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4987 Factor.Width = UserVF;
4991 float Cost = expectedCost(1);
4993 const float ScalarCost = Cost;
4996 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4998 // Ignore scalar width, because the user explicitly wants vectorization.
4999 if (ForceVectorization && VF > 1) {
5001 Cost = expectedCost(Width) / (float)Width;
5004 for (unsigned i=2; i <= VF; i*=2) {
5005 // Notice that the vector loop needs to be executed less times, so
5006 // we need to divide the cost of the vector loops by the width of
5007 // the vector elements.
5008 float VectorCost = expectedCost(i) / (float)i;
5009 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5010 (int)VectorCost << ".\n");
5011 if (VectorCost < Cost) {
5017 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5018 << "LV: Vectorization seems to be not beneficial, "
5019 << "but was forced by a user.\n");
5020 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5021 Factor.Width = Width;
5022 Factor.Cost = Width * Cost;
5026 unsigned LoopVectorizationCostModel::getWidestType() {
5027 unsigned MaxWidth = 8;
5030 for (Loop::block_iterator bb = TheLoop->block_begin(),
5031 be = TheLoop->block_end(); bb != be; ++bb) {
5032 BasicBlock *BB = *bb;
5034 // For each instruction in the loop.
5035 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5036 Type *T = it->getType();
5038 // Only examine Loads, Stores and PHINodes.
5039 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5042 // Examine PHI nodes that are reduction variables.
5043 if (PHINode *PN = dyn_cast<PHINode>(it))
5044 if (!Legal->getReductionVars()->count(PN))
5047 // Examine the stored values.
5048 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5049 T = ST->getValueOperand()->getType();
5051 // Ignore loaded pointer types and stored pointer types that are not
5052 // consecutive. However, we do want to take consecutive stores/loads of
5053 // pointer vectors into account.
5054 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5057 MaxWidth = std::max(MaxWidth,
5058 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5066 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5069 unsigned LoopCost) {
5071 // -- The unroll heuristics --
5072 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5073 // There are many micro-architectural considerations that we can't predict
5074 // at this level. For example frontend pressure (on decode or fetch) due to
5075 // code size, or the number and capabilities of the execution ports.
5077 // We use the following heuristics to select the unroll factor:
5078 // 1. If the code has reductions the we unroll in order to break the cross
5079 // iteration dependency.
5080 // 2. If the loop is really small then we unroll in order to reduce the loop
5082 // 3. We don't unroll if we think that we will spill registers to memory due
5083 // to the increased register pressure.
5085 // Use the user preference, unless 'auto' is selected.
5089 // When we optimize for size we don't unroll.
5093 // We used the distance for the unroll factor.
5094 if (Legal->getMaxSafeDepDistBytes() != -1U)
5097 // Do not unroll loops with a relatively small trip count.
5098 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5099 TheLoop->getLoopLatch());
5100 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5103 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5104 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5108 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5109 TargetNumRegisters = ForceTargetNumScalarRegs;
5111 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5112 TargetNumRegisters = ForceTargetNumVectorRegs;
5115 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5116 // We divide by these constants so assume that we have at least one
5117 // instruction that uses at least one register.
5118 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5119 R.NumInstructions = std::max(R.NumInstructions, 1U);
5121 // We calculate the unroll factor using the following formula.
5122 // Subtract the number of loop invariants from the number of available
5123 // registers. These registers are used by all of the unrolled instances.
5124 // Next, divide the remaining registers by the number of registers that is
5125 // required by the loop, in order to estimate how many parallel instances
5126 // fit without causing spills. All of this is rounded down if necessary to be
5127 // a power of two. We want power of two unroll factors to simplify any
5128 // addressing operations or alignment considerations.
5129 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5132 // Don't count the induction variable as unrolled.
5133 if (EnableIndVarRegisterHeur)
5134 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5135 std::max(1U, (R.MaxLocalUsers - 1)));
5137 // Clamp the unroll factor ranges to reasonable factors.
5138 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5140 // Check if the user has overridden the unroll max.
5142 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5143 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5145 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5146 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5149 // If we did not calculate the cost for VF (because the user selected the VF)
5150 // then we calculate the cost of VF here.
5152 LoopCost = expectedCost(VF);
5154 // Clamp the calculated UF to be between the 1 and the max unroll factor
5155 // that the target allows.
5156 if (UF > MaxUnrollSize)
5161 // Unroll if we vectorized this loop and there is a reduction that could
5162 // benefit from unrolling.
5163 if (VF > 1 && Legal->getReductionVars()->size()) {
5164 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5168 // Note that if we've already vectorized the loop we will have done the
5169 // runtime check and so unrolling won't require further checks.
5170 bool UnrollingRequiresRuntimePointerCheck =
5171 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5173 // We want to unroll small loops in order to reduce the loop overhead and
5174 // potentially expose ILP opportunities.
5175 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5176 if (!UnrollingRequiresRuntimePointerCheck &&
5177 LoopCost < SmallLoopCost) {
5178 // We assume that the cost overhead is 1 and we use the cost model
5179 // to estimate the cost of the loop and unroll until the cost of the
5180 // loop overhead is about 5% of the cost of the loop.
5181 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5183 // Unroll until store/load ports (estimated by max unroll factor) are
5185 unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5186 unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5188 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5189 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5190 return std::max(StoresUF, LoadsUF);
5193 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5197 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5201 LoopVectorizationCostModel::RegisterUsage
5202 LoopVectorizationCostModel::calculateRegisterUsage() {
5203 // This function calculates the register usage by measuring the highest number
5204 // of values that are alive at a single location. Obviously, this is a very
5205 // rough estimation. We scan the loop in a topological order in order and
5206 // assign a number to each instruction. We use RPO to ensure that defs are
5207 // met before their users. We assume that each instruction that has in-loop
5208 // users starts an interval. We record every time that an in-loop value is
5209 // used, so we have a list of the first and last occurrences of each
5210 // instruction. Next, we transpose this data structure into a multi map that
5211 // holds the list of intervals that *end* at a specific location. This multi
5212 // map allows us to perform a linear search. We scan the instructions linearly
5213 // and record each time that a new interval starts, by placing it in a set.
5214 // If we find this value in the multi-map then we remove it from the set.
5215 // The max register usage is the maximum size of the set.
5216 // We also search for instructions that are defined outside the loop, but are
5217 // used inside the loop. We need this number separately from the max-interval
5218 // usage number because when we unroll, loop-invariant values do not take
5220 LoopBlocksDFS DFS(TheLoop);
5224 R.NumInstructions = 0;
5226 // Each 'key' in the map opens a new interval. The values
5227 // of the map are the index of the 'last seen' usage of the
5228 // instruction that is the key.
5229 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5230 // Maps instruction to its index.
5231 DenseMap<unsigned, Instruction*> IdxToInstr;
5232 // Marks the end of each interval.
5233 IntervalMap EndPoint;
5234 // Saves the list of instruction indices that are used in the loop.
5235 SmallSet<Instruction*, 8> Ends;
5236 // Saves the list of values that are used in the loop but are
5237 // defined outside the loop, such as arguments and constants.
5238 SmallPtrSet<Value*, 8> LoopInvariants;
5241 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5242 be = DFS.endRPO(); bb != be; ++bb) {
5243 R.NumInstructions += (*bb)->size();
5244 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5246 Instruction *I = it;
5247 IdxToInstr[Index++] = I;
5249 // Save the end location of each USE.
5250 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5251 Value *U = I->getOperand(i);
5252 Instruction *Instr = dyn_cast<Instruction>(U);
5254 // Ignore non-instruction values such as arguments, constants, etc.
5255 if (!Instr) continue;
5257 // If this instruction is outside the loop then record it and continue.
5258 if (!TheLoop->contains(Instr)) {
5259 LoopInvariants.insert(Instr);
5263 // Overwrite previous end points.
5264 EndPoint[Instr] = Index;
5270 // Saves the list of intervals that end with the index in 'key'.
5271 typedef SmallVector<Instruction*, 2> InstrList;
5272 DenseMap<unsigned, InstrList> TransposeEnds;
5274 // Transpose the EndPoints to a list of values that end at each index.
5275 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5277 TransposeEnds[it->second].push_back(it->first);
5279 SmallSet<Instruction*, 8> OpenIntervals;
5280 unsigned MaxUsage = 0;
5283 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5284 for (unsigned int i = 0; i < Index; ++i) {
5285 Instruction *I = IdxToInstr[i];
5286 // Ignore instructions that are never used within the loop.
5287 if (!Ends.count(I)) continue;
5289 // Remove all of the instructions that end at this location.
5290 InstrList &List = TransposeEnds[i];
5291 for (unsigned int j=0, e = List.size(); j < e; ++j)
5292 OpenIntervals.erase(List[j]);
5294 // Count the number of live interals.
5295 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5297 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5298 OpenIntervals.size() << '\n');
5300 // Add the current instruction to the list of open intervals.
5301 OpenIntervals.insert(I);
5304 unsigned Invariant = LoopInvariants.size();
5305 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5306 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5307 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5309 R.LoopInvariantRegs = Invariant;
5310 R.MaxLocalUsers = MaxUsage;
5314 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5318 for (Loop::block_iterator bb = TheLoop->block_begin(),
5319 be = TheLoop->block_end(); bb != be; ++bb) {
5320 unsigned BlockCost = 0;
5321 BasicBlock *BB = *bb;
5323 // For each instruction in the old loop.
5324 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5325 // Skip dbg intrinsics.
5326 if (isa<DbgInfoIntrinsic>(it))
5329 unsigned C = getInstructionCost(it, VF);
5331 // Check if we should override the cost.
5332 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5333 C = ForceTargetInstructionCost;
5336 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5337 VF << " For instruction: " << *it << '\n');
5340 // We assume that if-converted blocks have a 50% chance of being executed.
5341 // When the code is scalar then some of the blocks are avoided due to CF.
5342 // When the code is vectorized we execute all code paths.
5343 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5352 /// \brief Check whether the address computation for a non-consecutive memory
5353 /// access looks like an unlikely candidate for being merged into the indexing
5356 /// We look for a GEP which has one index that is an induction variable and all
5357 /// other indices are loop invariant. If the stride of this access is also
5358 /// within a small bound we decide that this address computation can likely be
5359 /// merged into the addressing mode.
5360 /// In all other cases, we identify the address computation as complex.
5361 static bool isLikelyComplexAddressComputation(Value *Ptr,
5362 LoopVectorizationLegality *Legal,
5363 ScalarEvolution *SE,
5364 const Loop *TheLoop) {
5365 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5369 // We are looking for a gep with all loop invariant indices except for one
5370 // which should be an induction variable.
5371 unsigned NumOperands = Gep->getNumOperands();
5372 for (unsigned i = 1; i < NumOperands; ++i) {
5373 Value *Opd = Gep->getOperand(i);
5374 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5375 !Legal->isInductionVariable(Opd))
5379 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5380 // can likely be merged into the address computation.
5381 unsigned MaxMergeDistance = 64;
5383 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5387 // Check the step is constant.
5388 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5389 // Calculate the pointer stride and check if it is consecutive.
5390 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5394 const APInt &APStepVal = C->getValue()->getValue();
5396 // Huge step value - give up.
5397 if (APStepVal.getBitWidth() > 64)
5400 int64_t StepVal = APStepVal.getSExtValue();
5402 return StepVal > MaxMergeDistance;
5405 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5406 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5412 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5413 // If we know that this instruction will remain uniform, check the cost of
5414 // the scalar version.
5415 if (Legal->isUniformAfterVectorization(I))
5418 Type *RetTy = I->getType();
5419 Type *VectorTy = ToVectorTy(RetTy, VF);
5421 // TODO: We need to estimate the cost of intrinsic calls.
5422 switch (I->getOpcode()) {
5423 case Instruction::GetElementPtr:
5424 // We mark this instruction as zero-cost because the cost of GEPs in
5425 // vectorized code depends on whether the corresponding memory instruction
5426 // is scalarized or not. Therefore, we handle GEPs with the memory
5427 // instruction cost.
5429 case Instruction::Br: {
5430 return TTI.getCFInstrCost(I->getOpcode());
5432 case Instruction::PHI:
5433 //TODO: IF-converted IFs become selects.
5435 case Instruction::Add:
5436 case Instruction::FAdd:
5437 case Instruction::Sub:
5438 case Instruction::FSub:
5439 case Instruction::Mul:
5440 case Instruction::FMul:
5441 case Instruction::UDiv:
5442 case Instruction::SDiv:
5443 case Instruction::FDiv:
5444 case Instruction::URem:
5445 case Instruction::SRem:
5446 case Instruction::FRem:
5447 case Instruction::Shl:
5448 case Instruction::LShr:
5449 case Instruction::AShr:
5450 case Instruction::And:
5451 case Instruction::Or:
5452 case Instruction::Xor: {
5453 // Since we will replace the stride by 1 the multiplication should go away.
5454 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5456 // Certain instructions can be cheaper to vectorize if they have a constant
5457 // second vector operand. One example of this are shifts on x86.
5458 TargetTransformInfo::OperandValueKind Op1VK =
5459 TargetTransformInfo::OK_AnyValue;
5460 TargetTransformInfo::OperandValueKind Op2VK =
5461 TargetTransformInfo::OK_AnyValue;
5462 Value *Op2 = I->getOperand(1);
5464 // Check for a splat of a constant or for a non uniform vector of constants.
5465 if (isa<ConstantInt>(Op2))
5466 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5467 else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5468 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5469 if (cast<Constant>(Op2)->getSplatValue() != nullptr)
5470 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5473 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5475 case Instruction::Select: {
5476 SelectInst *SI = cast<SelectInst>(I);
5477 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5478 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5479 Type *CondTy = SI->getCondition()->getType();
5481 CondTy = VectorType::get(CondTy, VF);
5483 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5485 case Instruction::ICmp:
5486 case Instruction::FCmp: {
5487 Type *ValTy = I->getOperand(0)->getType();
5488 VectorTy = ToVectorTy(ValTy, VF);
5489 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5491 case Instruction::Store:
5492 case Instruction::Load: {
5493 StoreInst *SI = dyn_cast<StoreInst>(I);
5494 LoadInst *LI = dyn_cast<LoadInst>(I);
5495 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5497 VectorTy = ToVectorTy(ValTy, VF);
5499 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5500 unsigned AS = SI ? SI->getPointerAddressSpace() :
5501 LI->getPointerAddressSpace();
5502 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5503 // We add the cost of address computation here instead of with the gep
5504 // instruction because only here we know whether the operation is
5507 return TTI.getAddressComputationCost(VectorTy) +
5508 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5510 // Scalarized loads/stores.
5511 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5512 bool Reverse = ConsecutiveStride < 0;
5513 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5514 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5515 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5516 bool IsComplexComputation =
5517 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5519 // The cost of extracting from the value vector and pointer vector.
5520 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5521 for (unsigned i = 0; i < VF; ++i) {
5522 // The cost of extracting the pointer operand.
5523 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5524 // In case of STORE, the cost of ExtractElement from the vector.
5525 // In case of LOAD, the cost of InsertElement into the returned
5527 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5528 Instruction::InsertElement,
5532 // The cost of the scalar loads/stores.
5533 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5534 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5539 // Wide load/stores.
5540 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5541 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5544 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5548 case Instruction::ZExt:
5549 case Instruction::SExt:
5550 case Instruction::FPToUI:
5551 case Instruction::FPToSI:
5552 case Instruction::FPExt:
5553 case Instruction::PtrToInt:
5554 case Instruction::IntToPtr:
5555 case Instruction::SIToFP:
5556 case Instruction::UIToFP:
5557 case Instruction::Trunc:
5558 case Instruction::FPTrunc:
5559 case Instruction::BitCast: {
5560 // We optimize the truncation of induction variable.
5561 // The cost of these is the same as the scalar operation.
5562 if (I->getOpcode() == Instruction::Trunc &&
5563 Legal->isInductionVariable(I->getOperand(0)))
5564 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5565 I->getOperand(0)->getType());
5567 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5568 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5570 case Instruction::Call: {
5571 CallInst *CI = cast<CallInst>(I);
5572 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5573 assert(ID && "Not an intrinsic call!");
5574 Type *RetTy = ToVectorTy(CI->getType(), VF);
5575 SmallVector<Type*, 4> Tys;
5576 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5577 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5578 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5581 // We are scalarizing the instruction. Return the cost of the scalar
5582 // instruction, plus the cost of insert and extract into vector
5583 // elements, times the vector width.
5586 if (!RetTy->isVoidTy() && VF != 1) {
5587 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5589 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5592 // The cost of inserting the results plus extracting each one of the
5594 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5597 // The cost of executing VF copies of the scalar instruction. This opcode
5598 // is unknown. Assume that it is the same as 'mul'.
5599 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5605 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5606 if (Scalar->isVoidTy() || VF == 1)
5608 return VectorType::get(Scalar, VF);
5611 char LoopVectorize::ID = 0;
5612 static const char lv_name[] = "Loop Vectorization";
5613 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5614 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5615 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5616 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5617 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5618 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5619 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5620 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5621 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5624 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5625 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5629 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5630 // Check for a store.
5631 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5632 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5634 // Check for a load.
5635 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5636 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5642 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5643 bool IfPredicateStore) {
5644 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5645 // Holds vector parameters or scalars, in case of uniform vals.
5646 SmallVector<VectorParts, 4> Params;
5648 setDebugLocFromInst(Builder, Instr);
5650 // Find all of the vectorized parameters.
5651 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5652 Value *SrcOp = Instr->getOperand(op);
5654 // If we are accessing the old induction variable, use the new one.
5655 if (SrcOp == OldInduction) {
5656 Params.push_back(getVectorValue(SrcOp));
5660 // Try using previously calculated values.
5661 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5663 // If the src is an instruction that appeared earlier in the basic block
5664 // then it should already be vectorized.
5665 if (SrcInst && OrigLoop->contains(SrcInst)) {
5666 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5667 // The parameter is a vector value from earlier.
5668 Params.push_back(WidenMap.get(SrcInst));
5670 // The parameter is a scalar from outside the loop. Maybe even a constant.
5671 VectorParts Scalars;
5672 Scalars.append(UF, SrcOp);
5673 Params.push_back(Scalars);
5677 assert(Params.size() == Instr->getNumOperands() &&
5678 "Invalid number of operands");
5680 // Does this instruction return a value ?
5681 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5683 Value *UndefVec = IsVoidRetTy ? nullptr :
5684 UndefValue::get(Instr->getType());
5685 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5686 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5688 Instruction *InsertPt = Builder.GetInsertPoint();
5689 BasicBlock *IfBlock = Builder.GetInsertBlock();
5690 BasicBlock *CondBlock = nullptr;
5693 Loop *VectorLp = nullptr;
5694 if (IfPredicateStore) {
5695 assert(Instr->getParent()->getSinglePredecessor() &&
5696 "Only support single predecessor blocks");
5697 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5698 Instr->getParent());
5699 VectorLp = LI->getLoopFor(IfBlock);
5700 assert(VectorLp && "Must have a loop for this block");
5703 // For each vector unroll 'part':
5704 for (unsigned Part = 0; Part < UF; ++Part) {
5705 // For each scalar that we create:
5707 // Start an "if (pred) a[i] = ..." block.
5708 Value *Cmp = nullptr;
5709 if (IfPredicateStore) {
5710 if (Cond[Part]->getType()->isVectorTy())
5712 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5713 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5714 ConstantInt::get(Cond[Part]->getType(), 1));
5715 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5716 LoopVectorBody.push_back(CondBlock);
5717 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
5718 // Update Builder with newly created basic block.
5719 Builder.SetInsertPoint(InsertPt);
5722 Instruction *Cloned = Instr->clone();
5724 Cloned->setName(Instr->getName() + ".cloned");
5725 // Replace the operands of the cloned instructions with extracted scalars.
5726 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5727 Value *Op = Params[op][Part];
5728 Cloned->setOperand(op, Op);
5731 // Place the cloned scalar in the new loop.
5732 Builder.Insert(Cloned);
5734 // If the original scalar returns a value we need to place it in a vector
5735 // so that future users will be able to use it.
5737 VecResults[Part] = Cloned;
5740 if (IfPredicateStore) {
5741 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5742 LoopVectorBody.push_back(NewIfBlock);
5743 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
5744 Builder.SetInsertPoint(InsertPt);
5745 Instruction *OldBr = IfBlock->getTerminator();
5746 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5747 OldBr->eraseFromParent();
5748 IfBlock = NewIfBlock;
5753 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5754 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5755 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5757 return scalarizeInstruction(Instr, IfPredicateStore);
5760 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5764 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5768 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5770 // When unrolling and the VF is 1, we only need to add a simple scalar.
5771 Type *ITy = Val->getType();
5772 assert(!ITy->isVectorTy() && "Val must be a scalar");
5773 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5774 return Builder.CreateAdd(Val, C, "induction");