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/Format.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetLibraryInfo.h"
89 #include "llvm/Transforms/Scalar.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 #include "llvm/Transforms/Utils/Local.h"
92 #include "llvm/Transforms/Utils/VectorUtils.h"
98 using namespace llvm::PatternMatch;
100 #define LV_NAME "loop-vectorize"
101 #define DEBUG_TYPE LV_NAME
103 STATISTIC(LoopsVectorized, "Number of loops vectorized");
104 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
106 static cl::opt<unsigned>
107 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
108 cl::desc("Sets the SIMD width. Zero is autoselect."));
110 static cl::opt<unsigned>
111 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
112 cl::desc("Sets the vectorization unroll count. "
113 "Zero is autoselect."));
116 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
117 cl::desc("Enable if-conversion during vectorization."));
119 /// We don't vectorize loops with a known constant trip count below this number.
120 static cl::opt<unsigned>
121 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
123 cl::desc("Don't vectorize loops with a constant "
124 "trip count that is smaller than this "
127 /// This enables versioning on the strides of symbolically striding memory
128 /// accesses in code like the following.
129 /// for (i = 0; i < N; ++i)
130 /// A[i * Stride1] += B[i * Stride2] ...
132 /// Will be roughly translated to
133 /// if (Stride1 == 1 && Stride2 == 1) {
134 /// for (i = 0; i < N; i+=4)
138 static cl::opt<bool> EnableMemAccessVersioning(
139 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
140 cl::desc("Enable symblic stride memory access versioning"));
142 /// We don't unroll loops with a known constant trip count below this number.
143 static const unsigned TinyTripCountUnrollThreshold = 128;
145 /// When performing memory disambiguation checks at runtime do not make more
146 /// than this number of comparisons.
147 static const unsigned RuntimeMemoryCheckThreshold = 8;
149 /// Maximum simd width.
150 static const unsigned MaxVectorWidth = 64;
152 static cl::opt<unsigned> ForceTargetNumScalarRegs(
153 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
154 cl::desc("A flag that overrides the target's number of scalar registers."));
156 static cl::opt<unsigned> ForceTargetNumVectorRegs(
157 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
158 cl::desc("A flag that overrides the target's number of vector registers."));
160 /// Maximum vectorization unroll count.
161 static const unsigned MaxUnrollFactor = 16;
163 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
164 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
165 cl::desc("A flag that overrides the target's max unroll factor for scalar "
168 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
169 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
170 cl::desc("A flag that overrides the target's max unroll factor for "
171 "vectorized loops."));
173 static cl::opt<unsigned> ForceTargetInstructionCost(
174 "force-target-instruction-cost", cl::init(0), cl::Hidden,
175 cl::desc("A flag that overrides the target's expected cost for "
176 "an instruction to a single constant value. Mostly "
177 "useful for getting consistent testing."));
179 static cl::opt<unsigned> SmallLoopCost(
180 "small-loop-cost", cl::init(20), cl::Hidden,
181 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
183 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
184 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
185 cl::desc("Enable the use of the block frequency analysis to access PGO "
186 "heuristics minimizing code growth in cold regions and being more "
187 "aggressive in hot regions."));
189 // Runtime unroll loops for load/store throughput.
190 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
191 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
192 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
194 /// The number of stores in a loop that are allowed to need predication.
195 static cl::opt<unsigned> NumberOfStoresToPredicate(
196 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
197 cl::desc("Max number of stores to be predicated behind an if."));
199 static cl::opt<bool> EnableIndVarRegisterHeur(
200 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
201 cl::desc("Count the induction variable only once when unrolling"));
203 static cl::opt<bool> EnableCondStoresVectorization(
204 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
205 cl::desc("Enable if predication of stores during vectorization."));
209 // Forward declarations.
210 class LoopVectorizationLegality;
211 class LoopVectorizationCostModel;
213 /// InnerLoopVectorizer vectorizes loops which contain only one basic
214 /// block to a specified vectorization factor (VF).
215 /// This class performs the widening of scalars into vectors, or multiple
216 /// scalars. This class also implements the following features:
217 /// * It inserts an epilogue loop for handling loops that don't have iteration
218 /// counts that are known to be a multiple of the vectorization factor.
219 /// * It handles the code generation for reduction variables.
220 /// * Scalarization (implementation using scalars) of un-vectorizable
222 /// InnerLoopVectorizer does not perform any vectorization-legality
223 /// checks, and relies on the caller to check for the different legality
224 /// aspects. The InnerLoopVectorizer relies on the
225 /// LoopVectorizationLegality class to provide information about the induction
226 /// and reduction variables that were found to a given vectorization factor.
227 class InnerLoopVectorizer {
229 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
230 DominatorTree *DT, const DataLayout *DL,
231 const TargetLibraryInfo *TLI, unsigned VecWidth,
232 unsigned UnrollFactor)
233 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
234 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
235 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
238 // Perform the actual loop widening (vectorization).
239 void vectorize(LoopVectorizationLegality *L) {
241 // Create a new empty loop. Unlink the old loop and connect the new one.
243 // Widen each instruction in the old loop to a new one in the new loop.
244 // Use the Legality module to find the induction and reduction variables.
246 // Register the new loop and update the analysis passes.
250 virtual ~InnerLoopVectorizer() {}
253 /// A small list of PHINodes.
254 typedef SmallVector<PHINode*, 4> PhiVector;
255 /// When we unroll loops we have multiple vector values for each scalar.
256 /// This data structure holds the unrolled and vectorized values that
257 /// originated from one scalar instruction.
258 typedef SmallVector<Value*, 2> VectorParts;
260 // When we if-convert we need create edge masks. We have to cache values so
261 // that we don't end up with exponential recursion/IR.
262 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
263 VectorParts> EdgeMaskCache;
265 /// \brief Add code that checks at runtime if the accessed arrays overlap.
267 /// Returns a pair of instructions where the first element is the first
268 /// instruction generated in possibly a sequence of instructions and the
269 /// second value is the final comparator value or NULL if no check is needed.
270 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
272 /// \brief Add checks for strides that where assumed to be 1.
274 /// Returns the last check instruction and the first check instruction in the
275 /// pair as (first, last).
276 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
278 /// Create an empty loop, based on the loop ranges of the old loop.
279 void createEmptyLoop();
280 /// Copy and widen the instructions from the old loop.
281 virtual void vectorizeLoop();
283 /// \brief The Loop exit block may have single value PHI nodes where the
284 /// incoming value is 'Undef'. While vectorizing we only handled real values
285 /// that were defined inside the loop. Here we fix the 'undef case'.
289 /// A helper function that computes the predicate of the block BB, assuming
290 /// that the header block of the loop is set to True. It returns the *entry*
291 /// mask for the block BB.
292 VectorParts createBlockInMask(BasicBlock *BB);
293 /// A helper function that computes the predicate of the edge between SRC
295 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
297 /// A helper function to vectorize a single BB within the innermost loop.
298 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
300 /// Vectorize a single PHINode in a block. This method handles the induction
301 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
302 /// arbitrary length vectors.
303 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
304 unsigned UF, unsigned VF, PhiVector *PV);
306 /// Insert the new loop to the loop hierarchy and pass manager
307 /// and update the analysis passes.
308 void updateAnalysis();
310 /// This instruction is un-vectorizable. Implement it as a sequence
311 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
312 /// scalarized instruction behind an if block predicated on the control
313 /// dependence of the instruction.
314 virtual void scalarizeInstruction(Instruction *Instr,
315 bool IfPredicateStore=false);
317 /// Vectorize Load and Store instructions,
318 virtual void vectorizeMemoryInstruction(Instruction *Instr);
320 /// Create a broadcast instruction. This method generates a broadcast
321 /// instruction (shuffle) for loop invariant values and for the induction
322 /// value. If this is the induction variable then we extend it to N, N+1, ...
323 /// this is needed because each iteration in the loop corresponds to a SIMD
325 virtual Value *getBroadcastInstrs(Value *V);
327 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
328 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
329 /// The sequence starts at StartIndex.
330 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
332 /// When we go over instructions in the basic block we rely on previous
333 /// values within the current basic block or on loop invariant values.
334 /// When we widen (vectorize) values we place them in the map. If the values
335 /// are not within the map, they have to be loop invariant, so we simply
336 /// broadcast them into a vector.
337 VectorParts &getVectorValue(Value *V);
339 /// Generate a shuffle sequence that will reverse the vector Vec.
340 virtual Value *reverseVector(Value *Vec);
342 /// This is a helper class that holds the vectorizer state. It maps scalar
343 /// instructions to vector instructions. When the code is 'unrolled' then
344 /// then a single scalar value is mapped to multiple vector parts. The parts
345 /// are stored in the VectorPart type.
347 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
349 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
351 /// \return True if 'Key' is saved in the Value Map.
352 bool has(Value *Key) const { return MapStorage.count(Key); }
354 /// Initializes a new entry in the map. Sets all of the vector parts to the
355 /// save value in 'Val'.
356 /// \return A reference to a vector with splat values.
357 VectorParts &splat(Value *Key, Value *Val) {
358 VectorParts &Entry = MapStorage[Key];
359 Entry.assign(UF, Val);
363 ///\return A reference to the value that is stored at 'Key'.
364 VectorParts &get(Value *Key) {
365 VectorParts &Entry = MapStorage[Key];
368 assert(Entry.size() == UF);
373 /// The unroll factor. Each entry in the map stores this number of vector
377 /// Map storage. We use std::map and not DenseMap because insertions to a
378 /// dense map invalidates its iterators.
379 std::map<Value *, VectorParts> MapStorage;
382 /// The original loop.
384 /// Scev analysis to use.
391 const DataLayout *DL;
392 /// Target Library Info.
393 const TargetLibraryInfo *TLI;
395 /// The vectorization SIMD factor to use. Each vector will have this many
400 /// The vectorization unroll factor to use. Each scalar is vectorized to this
401 /// many different vector instructions.
404 /// The builder that we use
407 // --- Vectorization state ---
409 /// The vector-loop preheader.
410 BasicBlock *LoopVectorPreHeader;
411 /// The scalar-loop preheader.
412 BasicBlock *LoopScalarPreHeader;
413 /// Middle Block between the vector and the scalar.
414 BasicBlock *LoopMiddleBlock;
415 ///The ExitBlock of the scalar loop.
416 BasicBlock *LoopExitBlock;
417 ///The vector loop body.
418 SmallVector<BasicBlock *, 4> LoopVectorBody;
419 ///The scalar loop body.
420 BasicBlock *LoopScalarBody;
421 /// A list of all bypass blocks. The first block is the entry of the loop.
422 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
424 /// The new Induction variable which was added to the new block.
426 /// The induction variable of the old basic block.
427 PHINode *OldInduction;
428 /// Holds the extended (to the widest induction type) start index.
430 /// Maps scalars to widened vectors.
432 EdgeMaskCache MaskCache;
434 LoopVectorizationLegality *Legal;
437 class InnerLoopUnroller : public InnerLoopVectorizer {
439 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
440 DominatorTree *DT, const DataLayout *DL,
441 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
442 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
445 void scalarizeInstruction(Instruction *Instr,
446 bool IfPredicateStore = false) override;
447 void vectorizeMemoryInstruction(Instruction *Instr) override;
448 Value *getBroadcastInstrs(Value *V) override;
449 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
450 Value *reverseVector(Value *Vec) override;
453 /// \brief Look for a meaningful debug location on the instruction or it's
455 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
460 if (I->getDebugLoc() != Empty)
463 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
464 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
465 if (OpInst->getDebugLoc() != Empty)
472 /// \brief Set the debug location in the builder using the debug location in the
474 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
475 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
476 B.SetCurrentDebugLocation(Inst->getDebugLoc());
478 B.SetCurrentDebugLocation(DebugLoc());
482 /// \return string containing a file name and a line # for the given
484 static format_object3<const char *, const char *, unsigned>
485 getDebugLocString(const Instruction *I) {
487 return format<const char *, const char *, unsigned>("", "", "", 0U);
488 MDNode *N = I->getMetadata("dbg");
490 const StringRef ModuleName =
491 I->getParent()->getParent()->getParent()->getModuleIdentifier();
492 return format<const char *, const char *, unsigned>("%s", ModuleName.data(),
495 const DILocation Loc(N);
496 const unsigned LineNo = Loc.getLineNumber();
497 const char *DirName = Loc.getDirectory().data();
498 const char *FileName = Loc.getFilename().data();
499 return format("%s/%s:%u", DirName, FileName, LineNo);
503 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
504 /// to what vectorization factor.
505 /// This class does not look at the profitability of vectorization, only the
506 /// legality. This class has two main kinds of checks:
507 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
508 /// will change the order of memory accesses in a way that will change the
509 /// correctness of the program.
510 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
511 /// checks for a number of different conditions, such as the availability of a
512 /// single induction variable, that all types are supported and vectorize-able,
513 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
514 /// This class is also used by InnerLoopVectorizer for identifying
515 /// induction variable and the different reduction variables.
516 class LoopVectorizationLegality {
520 unsigned NumPredStores;
522 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
523 DominatorTree *DT, TargetLibraryInfo *TLI)
524 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
525 DT(DT), TLI(TLI), Induction(nullptr), WidestIndTy(nullptr),
526 HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {}
528 /// This enum represents the kinds of reductions that we support.
530 RK_NoReduction, ///< Not a reduction.
531 RK_IntegerAdd, ///< Sum of integers.
532 RK_IntegerMult, ///< Product of integers.
533 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
534 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
535 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
536 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
537 RK_FloatAdd, ///< Sum of floats.
538 RK_FloatMult, ///< Product of floats.
539 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
542 /// This enum represents the kinds of inductions that we support.
544 IK_NoInduction, ///< Not an induction variable.
545 IK_IntInduction, ///< Integer induction variable. Step = 1.
546 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
547 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
548 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
551 // This enum represents the kind of minmax reduction.
552 enum MinMaxReductionKind {
562 /// This struct holds information about reduction variables.
563 struct ReductionDescriptor {
564 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
565 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
567 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
568 MinMaxReductionKind MK)
569 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
571 // The starting value of the reduction.
572 // It does not have to be zero!
573 TrackingVH<Value> StartValue;
574 // The instruction who's value is used outside the loop.
575 Instruction *LoopExitInstr;
576 // The kind of the reduction.
578 // If this a min/max reduction the kind of reduction.
579 MinMaxReductionKind MinMaxKind;
582 /// This POD struct holds information about a potential reduction operation.
583 struct ReductionInstDesc {
584 ReductionInstDesc(bool IsRedux, Instruction *I) :
585 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
587 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
588 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
590 // Is this instruction a reduction candidate.
592 // The last instruction in a min/max pattern (select of the select(icmp())
593 // pattern), or the current reduction instruction otherwise.
594 Instruction *PatternLastInst;
595 // If this is a min/max pattern the comparison predicate.
596 MinMaxReductionKind MinMaxKind;
599 /// This struct holds information about the memory runtime legality
600 /// check that a group of pointers do not overlap.
601 struct RuntimePointerCheck {
602 RuntimePointerCheck() : Need(false) {}
604 /// Reset the state of the pointer runtime information.
611 DependencySetId.clear();
614 /// Insert a pointer and calculate the start and end SCEVs.
615 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
616 unsigned DepSetId, ValueToValueMap &Strides);
618 /// This flag indicates if we need to add the runtime check.
620 /// Holds the pointers that we need to check.
621 SmallVector<TrackingVH<Value>, 2> Pointers;
622 /// Holds the pointer value at the beginning of the loop.
623 SmallVector<const SCEV*, 2> Starts;
624 /// Holds the pointer value at the end of the loop.
625 SmallVector<const SCEV*, 2> Ends;
626 /// Holds the information if this pointer is used for writing to memory.
627 SmallVector<bool, 2> IsWritePtr;
628 /// Holds the id of the set of pointers that could be dependent because of a
629 /// shared underlying object.
630 SmallVector<unsigned, 2> DependencySetId;
633 /// A struct for saving information about induction variables.
634 struct InductionInfo {
635 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
636 InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
638 TrackingVH<Value> StartValue;
643 /// ReductionList contains the reduction descriptors for all
644 /// of the reductions that were found in the loop.
645 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
647 /// InductionList saves induction variables and maps them to the
648 /// induction descriptor.
649 typedef MapVector<PHINode*, InductionInfo> InductionList;
651 /// Returns true if it is legal to vectorize this loop.
652 /// This does not mean that it is profitable to vectorize this
653 /// loop, only that it is legal to do so.
656 /// Returns the Induction variable.
657 PHINode *getInduction() { return Induction; }
659 /// Returns the reduction variables found in the loop.
660 ReductionList *getReductionVars() { return &Reductions; }
662 /// Returns the induction variables found in the loop.
663 InductionList *getInductionVars() { return &Inductions; }
665 /// Returns the widest induction type.
666 Type *getWidestInductionType() { return WidestIndTy; }
668 /// Returns True if V is an induction variable in this loop.
669 bool isInductionVariable(const Value *V);
671 /// Return true if the block BB needs to be predicated in order for the loop
672 /// to be vectorized.
673 bool blockNeedsPredication(BasicBlock *BB);
675 /// Check if this pointer is consecutive when vectorizing. This happens
676 /// when the last index of the GEP is the induction variable, or that the
677 /// pointer itself is an induction variable.
678 /// This check allows us to vectorize A[idx] into a wide load/store.
680 /// 0 - Stride is unknown or non-consecutive.
681 /// 1 - Address is consecutive.
682 /// -1 - Address is consecutive, and decreasing.
683 int isConsecutivePtr(Value *Ptr);
685 /// Returns true if the value V is uniform within the loop.
686 bool isUniform(Value *V);
688 /// Returns true if this instruction will remain scalar after vectorization.
689 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
691 /// Returns the information that we collected about runtime memory check.
692 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
694 /// This function returns the identity element (or neutral element) for
696 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
698 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
700 bool hasStride(Value *V) { return StrideSet.count(V); }
701 bool mustCheckStrides() { return !StrideSet.empty(); }
702 SmallPtrSet<Value *, 8>::iterator strides_begin() {
703 return StrideSet.begin();
705 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
708 /// Check if a single basic block loop is vectorizable.
709 /// At this point we know that this is a loop with a constant trip count
710 /// and we only need to check individual instructions.
711 bool canVectorizeInstrs();
713 /// When we vectorize loops we may change the order in which
714 /// we read and write from memory. This method checks if it is
715 /// legal to vectorize the code, considering only memory constrains.
716 /// Returns true if the loop is vectorizable
717 bool canVectorizeMemory();
719 /// Return true if we can vectorize this loop using the IF-conversion
721 bool canVectorizeWithIfConvert();
723 /// Collect the variables that need to stay uniform after vectorization.
724 void collectLoopUniforms();
726 /// Return true if all of the instructions in the block can be speculatively
727 /// executed. \p SafePtrs is a list of addresses that are known to be legal
728 /// and we know that we can read from them without segfault.
729 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
731 /// Returns True, if 'Phi' is the kind of reduction variable for type
732 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
733 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
734 /// Returns a struct describing if the instruction 'I' can be a reduction
735 /// variable of type 'Kind'. If the reduction is a min/max pattern of
736 /// select(icmp()) this function advances the instruction pointer 'I' from the
737 /// compare instruction to the select instruction and stores this pointer in
738 /// 'PatternLastInst' member of the returned struct.
739 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
740 ReductionInstDesc &Desc);
741 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
742 /// pattern corresponding to a min(X, Y) or max(X, Y).
743 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
744 ReductionInstDesc &Prev);
745 /// Returns the induction kind of Phi. This function may return NoInduction
746 /// if the PHI is not an induction variable.
747 InductionKind isInductionVariable(PHINode *Phi);
749 /// \brief Collect memory access with loop invariant strides.
751 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
753 void collectStridedAcccess(Value *LoadOrStoreInst);
755 /// The loop that we evaluate.
759 /// DataLayout analysis.
760 const DataLayout *DL;
763 /// Target Library Info.
764 TargetLibraryInfo *TLI;
766 // --- vectorization state --- //
768 /// Holds the integer induction variable. This is the counter of the
771 /// Holds the reduction variables.
772 ReductionList Reductions;
773 /// Holds all of the induction variables that we found in the loop.
774 /// Notice that inductions don't need to start at zero and that induction
775 /// variables can be pointers.
776 InductionList Inductions;
777 /// Holds the widest induction type encountered.
780 /// Allowed outside users. This holds the reduction
781 /// vars which can be accessed from outside the loop.
782 SmallPtrSet<Value*, 4> AllowedExit;
783 /// This set holds the variables which are known to be uniform after
785 SmallPtrSet<Instruction*, 4> Uniforms;
786 /// We need to check that all of the pointers in this list are disjoint
788 RuntimePointerCheck PtrRtCheck;
789 /// Can we assume the absence of NaNs.
790 bool HasFunNoNaNAttr;
792 unsigned MaxSafeDepDistBytes;
794 ValueToValueMap Strides;
795 SmallPtrSet<Value *, 8> StrideSet;
798 /// LoopVectorizationCostModel - estimates the expected speedups due to
800 /// In many cases vectorization is not profitable. This can happen because of
801 /// a number of reasons. In this class we mainly attempt to predict the
802 /// expected speedup/slowdowns due to the supported instruction set. We use the
803 /// TargetTransformInfo to query the different backends for the cost of
804 /// different operations.
805 class LoopVectorizationCostModel {
807 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
808 LoopVectorizationLegality *Legal,
809 const TargetTransformInfo &TTI,
810 const DataLayout *DL, const TargetLibraryInfo *TLI)
811 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
813 /// Information about vectorization costs
814 struct VectorizationFactor {
815 unsigned Width; // Vector width with best cost
816 unsigned Cost; // Cost of the loop with that width
818 /// \return The most profitable vectorization factor and the cost of that VF.
819 /// This method checks every power of two up to VF. If UserVF is not ZERO
820 /// then this vectorization factor will be selected if vectorization is
822 VectorizationFactor selectVectorizationFactor(bool OptForSize,
824 bool ForceVectorization);
826 /// \return The size (in bits) of the widest type in the code that
827 /// needs to be vectorized. We ignore values that remain scalar such as
828 /// 64 bit loop indices.
829 unsigned getWidestType();
831 /// \return The most profitable unroll factor.
832 /// If UserUF is non-zero then this method finds the best unroll-factor
833 /// based on register pressure and other parameters.
834 /// VF and LoopCost are the selected vectorization factor and the cost of the
836 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
839 /// \brief A struct that represents some properties of the register usage
841 struct RegisterUsage {
842 /// Holds the number of loop invariant values that are used in the loop.
843 unsigned LoopInvariantRegs;
844 /// Holds the maximum number of concurrent live intervals in the loop.
845 unsigned MaxLocalUsers;
846 /// Holds the number of instructions in the loop.
847 unsigned NumInstructions;
850 /// \return information about the register usage of the loop.
851 RegisterUsage calculateRegisterUsage();
854 /// Returns the expected execution cost. The unit of the cost does
855 /// not matter because we use the 'cost' units to compare different
856 /// vector widths. The cost that is returned is *not* normalized by
857 /// the factor width.
858 unsigned expectedCost(unsigned VF);
860 /// Returns the execution time cost of an instruction for a given vector
861 /// width. Vector width of one means scalar.
862 unsigned getInstructionCost(Instruction *I, unsigned VF);
864 /// A helper function for converting Scalar types to vector types.
865 /// If the incoming type is void, we return void. If the VF is 1, we return
867 static Type* ToVectorTy(Type *Scalar, unsigned VF);
869 /// Returns whether the instruction is a load or store and will be a emitted
870 /// as a vector operation.
871 bool isConsecutiveLoadOrStore(Instruction *I);
873 /// The loop that we evaluate.
877 /// Loop Info analysis.
879 /// Vectorization legality.
880 LoopVectorizationLegality *Legal;
881 /// Vector target information.
882 const TargetTransformInfo &TTI;
883 /// Target data layout information.
884 const DataLayout *DL;
885 /// Target Library Info.
886 const TargetLibraryInfo *TLI;
889 /// Utility class for getting and setting loop vectorizer hints in the form
890 /// of loop metadata.
891 class LoopVectorizeHints {
894 FK_Undefined = -1, ///< Not selected.
895 FK_Disabled = 0, ///< Forcing disabled.
896 FK_Enabled = 1, ///< Forcing enabled.
899 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
900 : Width(VectorizationFactor),
901 Unroll(DisableUnrolling),
903 LoopID(L->getLoopID()) {
905 // force-vector-unroll overrides DisableUnrolling.
906 if (VectorizationUnroll.getNumOccurrences() > 0)
907 Unroll = VectorizationUnroll;
909 DEBUG(if (DisableUnrolling && Unroll == 1) dbgs()
910 << "LV: Unrolling disabled by the pass manager\n");
913 /// Return the loop vectorizer metadata prefix.
914 static StringRef Prefix() { return "llvm.vectorizer."; }
916 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) const {
917 SmallVector<Value*, 2> Vals;
918 Vals.push_back(MDString::get(Context, Name));
919 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
920 return MDNode::get(Context, Vals);
923 /// Mark the loop L as already vectorized by setting the width to 1.
924 void setAlreadyVectorized(Loop *L) {
925 LLVMContext &Context = L->getHeader()->getContext();
929 // Create a new loop id with one more operand for the already_vectorized
930 // hint. If the loop already has a loop id then copy the existing operands.
931 SmallVector<Value*, 4> Vals(1);
933 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
934 Vals.push_back(LoopID->getOperand(i));
936 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
937 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
939 MDNode *NewLoopID = MDNode::get(Context, Vals);
940 // Set operand 0 to refer to the loop id itself.
941 NewLoopID->replaceOperandWith(0, NewLoopID);
943 L->setLoopID(NewLoopID);
945 LoopID->replaceAllUsesWith(NewLoopID);
950 unsigned getWidth() const { return Width; }
951 unsigned getUnroll() const { return Unroll; }
952 enum ForceKind getForce() const { return Force; }
953 MDNode *getLoopID() const { return LoopID; }
956 /// Find hints specified in the loop metadata.
957 void getHints(const Loop *L) {
961 // First operand should refer to the loop id itself.
962 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
963 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
965 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
966 const MDString *S = nullptr;
967 SmallVector<Value*, 4> Args;
969 // The expected hint is either a MDString or a MDNode with the first
970 // operand a MDString.
971 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
972 if (!MD || MD->getNumOperands() == 0)
974 S = dyn_cast<MDString>(MD->getOperand(0));
975 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
976 Args.push_back(MD->getOperand(i));
978 S = dyn_cast<MDString>(LoopID->getOperand(i));
979 assert(Args.size() == 0 && "too many arguments for MDString");
985 // Check if the hint starts with the vectorizer prefix.
986 StringRef Hint = S->getString();
987 if (!Hint.startswith(Prefix()))
989 // Remove the prefix.
990 Hint = Hint.substr(Prefix().size(), StringRef::npos);
992 if (Args.size() == 1)
993 getHint(Hint, Args[0]);
997 // Check string hint with one operand.
998 void getHint(StringRef Hint, Value *Arg) {
999 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
1001 unsigned Val = C->getZExtValue();
1003 if (Hint == "width") {
1004 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
1007 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
1008 } else if (Hint == "unroll") {
1009 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
1012 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
1013 } else if (Hint == "enable") {
1014 if (C->getBitWidth() == 1)
1015 Force = Val == 1 ? LoopVectorizeHints::FK_Enabled
1016 : LoopVectorizeHints::FK_Disabled;
1018 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
1020 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
1024 /// Vectorization width.
1026 /// Vectorization unroll factor.
1028 /// Vectorization forced
1029 enum ForceKind Force;
1034 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1036 return V.push_back(&L);
1038 for (Loop *InnerL : L)
1039 addInnerLoop(*InnerL, V);
1042 /// The LoopVectorize Pass.
1043 struct LoopVectorize : public FunctionPass {
1044 /// Pass identification, replacement for typeid
1047 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1049 DisableUnrolling(NoUnrolling),
1050 AlwaysVectorize(AlwaysVectorize) {
1051 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1054 ScalarEvolution *SE;
1055 const DataLayout *DL;
1057 TargetTransformInfo *TTI;
1059 BlockFrequencyInfo *BFI;
1060 TargetLibraryInfo *TLI;
1061 bool DisableUnrolling;
1062 bool AlwaysVectorize;
1064 BlockFrequency ColdEntryFreq;
1066 bool runOnFunction(Function &F) override {
1067 SE = &getAnalysis<ScalarEvolution>();
1068 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1069 DL = DLP ? &DLP->getDataLayout() : nullptr;
1070 LI = &getAnalysis<LoopInfo>();
1071 TTI = &getAnalysis<TargetTransformInfo>();
1072 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1073 BFI = &getAnalysis<BlockFrequencyInfo>();
1074 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1076 // Compute some weights outside of the loop over the loops. Compute this
1077 // using a BranchProbability to re-use its scaling math.
1078 const BranchProbability ColdProb(1, 5); // 20%
1079 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1081 // If the target claims to have no vector registers don't attempt
1083 if (!TTI->getNumberOfRegisters(true))
1087 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1088 << ": Missing data layout\n");
1092 // Build up a worklist of inner-loops to vectorize. This is necessary as
1093 // the act of vectorizing or partially unrolling a loop creates new loops
1094 // and can invalidate iterators across the loops.
1095 SmallVector<Loop *, 8> Worklist;
1098 addInnerLoop(*L, Worklist);
1100 LoopsAnalyzed += Worklist.size();
1102 // Now walk the identified inner loops.
1103 bool Changed = false;
1104 while (!Worklist.empty())
1105 Changed |= processLoop(Worklist.pop_back_val());
1107 // Process each loop nest in the function.
1111 bool processLoop(Loop *L) {
1112 assert(L->empty() && "Only process inner loops.");
1113 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1114 << L->getHeader()->getParent()->getName() << "\" from "
1115 << getDebugLocString(L->getHeader()->getFirstNonPHIOrDbg())
1118 LoopVectorizeHints Hints(L, DisableUnrolling);
1120 DEBUG(dbgs() << "LV: Loop hints:"
1122 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1124 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1126 : "?")) << " width=" << Hints.getWidth()
1127 << " unroll=" << Hints.getUnroll() << "\n");
1129 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1130 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1134 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1135 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1139 if (Hints.getWidth() == 1 && Hints.getUnroll() == 1) {
1140 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1144 // Check the loop for a trip count threshold:
1145 // do not vectorize loops with a tiny trip count.
1146 BasicBlock *Latch = L->getLoopLatch();
1147 const unsigned TC = SE->getSmallConstantTripCount(L, Latch);
1148 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1149 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1150 << "This loop is not worth vectorizing.");
1151 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1152 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1154 DEBUG(dbgs() << "\n");
1159 // Check if it is legal to vectorize the loop.
1160 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1161 if (!LVL.canVectorize()) {
1162 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1166 // Use the cost model.
1167 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1169 // Check the function attributes to find out if this function should be
1170 // optimized for size.
1171 Function *F = L->getHeader()->getParent();
1172 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1173 F->hasFnAttribute(Attribute::OptimizeForSize);
1175 // Compute the weighted frequency of this loop being executed and see if it
1176 // is less than 20% of the function entry baseline frequency. Note that we
1177 // always have a canonical loop here because we think we *can* vectoriez.
1178 // FIXME: This is hidden behind a flag due to pervasive problems with
1179 // exactly what block frequency models.
1180 if (LoopVectorizeWithBlockFrequency) {
1181 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1182 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1183 LoopEntryFreq < ColdEntryFreq)
1187 // Check the function attributes to see if implicit floats are allowed.a
1188 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1189 // an integer loop and the vector instructions selected are purely integer
1190 // vector instructions?
1191 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1192 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1193 "attribute is used.\n");
1197 // Select the optimal vectorization factor.
1198 const LoopVectorizationCostModel::VectorizationFactor VF =
1199 CM.selectVectorizationFactor(OptForSize, Hints.getWidth(),
1201 LoopVectorizeHints::FK_Enabled);
1203 // Select the unroll factor.
1205 CM.selectUnrollFactor(OptForSize, Hints.getUnroll(), VF.Width, VF.Cost);
1207 DEBUG(dbgs() << "LV: Found a vectorizable loop ("
1208 << VF.Width << ") in "
1209 << getDebugLocString(L->getHeader()->getFirstNonPHIOrDbg())
1211 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1213 if (VF.Width == 1) {
1214 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1217 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1219 // Report the unrolling decision.
1220 F->getContext().emitOptimizationRemark(
1221 DEBUG_TYPE, *F, L->getStartLoc(),
1222 Twine("unrolled with interleaving factor " + Twine(UF) +
1223 " (vectorization not beneficial)"));
1225 // We decided not to vectorize, but we may want to unroll.
1226 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1227 Unroller.vectorize(&LVL);
1229 // If we decided that it is *legal* to vectorize the loop then do it.
1230 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1234 // Report the vectorization decision.
1235 F->getContext().emitOptimizationRemark(
1236 DEBUG_TYPE, *F, L->getStartLoc(),
1237 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1238 ", unrolling interleave factor: " + Twine(UF) + ")");
1241 // Mark the loop as already vectorized to avoid vectorizing again.
1242 Hints.setAlreadyVectorized(L);
1244 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1248 void getAnalysisUsage(AnalysisUsage &AU) const override {
1249 AU.addRequiredID(LoopSimplifyID);
1250 AU.addRequiredID(LCSSAID);
1251 AU.addRequired<BlockFrequencyInfo>();
1252 AU.addRequired<DominatorTreeWrapperPass>();
1253 AU.addRequired<LoopInfo>();
1254 AU.addRequired<ScalarEvolution>();
1255 AU.addRequired<TargetTransformInfo>();
1256 AU.addPreserved<LoopInfo>();
1257 AU.addPreserved<DominatorTreeWrapperPass>();
1262 } // end anonymous namespace
1264 //===----------------------------------------------------------------------===//
1265 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1266 // LoopVectorizationCostModel.
1267 //===----------------------------------------------------------------------===//
1269 static Value *stripIntegerCast(Value *V) {
1270 if (CastInst *CI = dyn_cast<CastInst>(V))
1271 if (CI->getOperand(0)->getType()->isIntegerTy())
1272 return CI->getOperand(0);
1276 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1278 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1280 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1281 ValueToValueMap &PtrToStride,
1282 Value *Ptr, Value *OrigPtr = nullptr) {
1284 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1286 // If there is an entry in the map return the SCEV of the pointer with the
1287 // symbolic stride replaced by one.
1288 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1289 if (SI != PtrToStride.end()) {
1290 Value *StrideVal = SI->second;
1293 StrideVal = stripIntegerCast(StrideVal);
1295 // Replace symbolic stride by one.
1296 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1297 ValueToValueMap RewriteMap;
1298 RewriteMap[StrideVal] = One;
1301 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1302 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1307 // Otherwise, just return the SCEV of the original pointer.
1308 return SE->getSCEV(Ptr);
1311 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1312 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1313 ValueToValueMap &Strides) {
1314 // Get the stride replaced scev.
1315 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1316 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1317 assert(AR && "Invalid addrec expression");
1318 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1319 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1320 Pointers.push_back(Ptr);
1321 Starts.push_back(AR->getStart());
1322 Ends.push_back(ScEnd);
1323 IsWritePtr.push_back(WritePtr);
1324 DependencySetId.push_back(DepSetId);
1327 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1328 // We need to place the broadcast of invariant variables outside the loop.
1329 Instruction *Instr = dyn_cast<Instruction>(V);
1331 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1332 Instr->getParent()) != LoopVectorBody.end());
1333 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1335 // Place the code for broadcasting invariant variables in the new preheader.
1336 IRBuilder<>::InsertPointGuard Guard(Builder);
1338 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1340 // Broadcast the scalar into all locations in the vector.
1341 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1346 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1348 assert(Val->getType()->isVectorTy() && "Must be a vector");
1349 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1350 "Elem must be an integer");
1351 // Create the types.
1352 Type *ITy = Val->getType()->getScalarType();
1353 VectorType *Ty = cast<VectorType>(Val->getType());
1354 int VLen = Ty->getNumElements();
1355 SmallVector<Constant*, 8> Indices;
1357 // Create a vector of consecutive numbers from zero to VF.
1358 for (int i = 0; i < VLen; ++i) {
1359 int64_t Idx = Negate ? (-i) : i;
1360 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1363 // Add the consecutive indices to the vector value.
1364 Constant *Cv = ConstantVector::get(Indices);
1365 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1366 return Builder.CreateAdd(Val, Cv, "induction");
1369 /// \brief Find the operand of the GEP that should be checked for consecutive
1370 /// stores. This ignores trailing indices that have no effect on the final
1372 static unsigned getGEPInductionOperand(const DataLayout *DL,
1373 const GetElementPtrInst *Gep) {
1374 unsigned LastOperand = Gep->getNumOperands() - 1;
1375 unsigned GEPAllocSize = DL->getTypeAllocSize(
1376 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1378 // Walk backwards and try to peel off zeros.
1379 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1380 // Find the type we're currently indexing into.
1381 gep_type_iterator GEPTI = gep_type_begin(Gep);
1382 std::advance(GEPTI, LastOperand - 1);
1384 // If it's a type with the same allocation size as the result of the GEP we
1385 // can peel off the zero index.
1386 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1394 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1395 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1396 // Make sure that the pointer does not point to structs.
1397 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1400 // If this value is a pointer induction variable we know it is consecutive.
1401 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1402 if (Phi && Inductions.count(Phi)) {
1403 InductionInfo II = Inductions[Phi];
1404 if (IK_PtrInduction == II.IK)
1406 else if (IK_ReversePtrInduction == II.IK)
1410 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1414 unsigned NumOperands = Gep->getNumOperands();
1415 Value *GpPtr = Gep->getPointerOperand();
1416 // If this GEP value is a consecutive pointer induction variable and all of
1417 // the indices are constant then we know it is consecutive. We can
1418 Phi = dyn_cast<PHINode>(GpPtr);
1419 if (Phi && Inductions.count(Phi)) {
1421 // Make sure that the pointer does not point to structs.
1422 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1423 if (GepPtrType->getElementType()->isAggregateType())
1426 // Make sure that all of the index operands are loop invariant.
1427 for (unsigned i = 1; i < NumOperands; ++i)
1428 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1431 InductionInfo II = Inductions[Phi];
1432 if (IK_PtrInduction == II.IK)
1434 else if (IK_ReversePtrInduction == II.IK)
1438 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1440 // Check that all of the gep indices are uniform except for our induction
1442 for (unsigned i = 0; i != NumOperands; ++i)
1443 if (i != InductionOperand &&
1444 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1447 // We can emit wide load/stores only if the last non-zero index is the
1448 // induction variable.
1449 const SCEV *Last = nullptr;
1450 if (!Strides.count(Gep))
1451 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1453 // Because of the multiplication by a stride we can have a s/zext cast.
1454 // We are going to replace this stride by 1 so the cast is safe to ignore.
1456 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1457 // %0 = trunc i64 %indvars.iv to i32
1458 // %mul = mul i32 %0, %Stride1
1459 // %idxprom = zext i32 %mul to i64 << Safe cast.
1460 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1462 Last = replaceSymbolicStrideSCEV(SE, Strides,
1463 Gep->getOperand(InductionOperand), Gep);
1464 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1466 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1470 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1471 const SCEV *Step = AR->getStepRecurrence(*SE);
1473 // The memory is consecutive because the last index is consecutive
1474 // and all other indices are loop invariant.
1477 if (Step->isAllOnesValue())
1484 bool LoopVectorizationLegality::isUniform(Value *V) {
1485 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1488 InnerLoopVectorizer::VectorParts&
1489 InnerLoopVectorizer::getVectorValue(Value *V) {
1490 assert(V != Induction && "The new induction variable should not be used.");
1491 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1493 // If we have a stride that is replaced by one, do it here.
1494 if (Legal->hasStride(V))
1495 V = ConstantInt::get(V->getType(), 1);
1497 // If we have this scalar in the map, return it.
1498 if (WidenMap.has(V))
1499 return WidenMap.get(V);
1501 // If this scalar is unknown, assume that it is a constant or that it is
1502 // loop invariant. Broadcast V and save the value for future uses.
1503 Value *B = getBroadcastInstrs(V);
1504 return WidenMap.splat(V, B);
1507 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1508 assert(Vec->getType()->isVectorTy() && "Invalid type");
1509 SmallVector<Constant*, 8> ShuffleMask;
1510 for (unsigned i = 0; i < VF; ++i)
1511 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1513 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1514 ConstantVector::get(ShuffleMask),
1518 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1519 // Attempt to issue a wide load.
1520 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1521 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1523 assert((LI || SI) && "Invalid Load/Store instruction");
1525 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1526 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1527 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1528 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1529 // An alignment of 0 means target abi alignment. We need to use the scalar's
1530 // target abi alignment in such a case.
1532 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1533 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1534 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1535 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1537 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1538 return scalarizeInstruction(Instr, true);
1540 if (ScalarAllocatedSize != VectorElementSize)
1541 return scalarizeInstruction(Instr);
1543 // If the pointer is loop invariant or if it is non-consecutive,
1544 // scalarize the load.
1545 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1546 bool Reverse = ConsecutiveStride < 0;
1547 bool UniformLoad = LI && Legal->isUniform(Ptr);
1548 if (!ConsecutiveStride || UniformLoad)
1549 return scalarizeInstruction(Instr);
1551 Constant *Zero = Builder.getInt32(0);
1552 VectorParts &Entry = WidenMap.get(Instr);
1554 // Handle consecutive loads/stores.
1555 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1556 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1557 setDebugLocFromInst(Builder, Gep);
1558 Value *PtrOperand = Gep->getPointerOperand();
1559 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1560 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1562 // Create the new GEP with the new induction variable.
1563 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1564 Gep2->setOperand(0, FirstBasePtr);
1565 Gep2->setName("gep.indvar.base");
1566 Ptr = Builder.Insert(Gep2);
1568 setDebugLocFromInst(Builder, Gep);
1569 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1570 OrigLoop) && "Base ptr must be invariant");
1572 // The last index does not have to be the induction. It can be
1573 // consecutive and be a function of the index. For example A[I+1];
1574 unsigned NumOperands = Gep->getNumOperands();
1575 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1576 // Create the new GEP with the new induction variable.
1577 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1579 for (unsigned i = 0; i < NumOperands; ++i) {
1580 Value *GepOperand = Gep->getOperand(i);
1581 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1583 // Update last index or loop invariant instruction anchored in loop.
1584 if (i == InductionOperand ||
1585 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1586 assert((i == InductionOperand ||
1587 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1588 "Must be last index or loop invariant");
1590 VectorParts &GEPParts = getVectorValue(GepOperand);
1591 Value *Index = GEPParts[0];
1592 Index = Builder.CreateExtractElement(Index, Zero);
1593 Gep2->setOperand(i, Index);
1594 Gep2->setName("gep.indvar.idx");
1597 Ptr = Builder.Insert(Gep2);
1599 // Use the induction element ptr.
1600 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1601 setDebugLocFromInst(Builder, Ptr);
1602 VectorParts &PtrVal = getVectorValue(Ptr);
1603 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1608 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1609 "We do not allow storing to uniform addresses");
1610 setDebugLocFromInst(Builder, SI);
1611 // We don't want to update the value in the map as it might be used in
1612 // another expression. So don't use a reference type for "StoredVal".
1613 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1615 for (unsigned Part = 0; Part < UF; ++Part) {
1616 // Calculate the pointer for the specific unroll-part.
1617 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1620 // If we store to reverse consecutive memory locations then we need
1621 // to reverse the order of elements in the stored value.
1622 StoredVal[Part] = reverseVector(StoredVal[Part]);
1623 // If the address is consecutive but reversed, then the
1624 // wide store needs to start at the last vector element.
1625 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1626 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1629 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1630 DataTy->getPointerTo(AddressSpace));
1631 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1637 assert(LI && "Must have a load instruction");
1638 setDebugLocFromInst(Builder, LI);
1639 for (unsigned Part = 0; Part < UF; ++Part) {
1640 // Calculate the pointer for the specific unroll-part.
1641 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1644 // If the address is consecutive but reversed, then the
1645 // wide store needs to start at the last vector element.
1646 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1647 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1650 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1651 DataTy->getPointerTo(AddressSpace));
1652 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1653 cast<LoadInst>(LI)->setAlignment(Alignment);
1654 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1658 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1659 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1660 // Holds vector parameters or scalars, in case of uniform vals.
1661 SmallVector<VectorParts, 4> Params;
1663 setDebugLocFromInst(Builder, Instr);
1665 // Find all of the vectorized parameters.
1666 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1667 Value *SrcOp = Instr->getOperand(op);
1669 // If we are accessing the old induction variable, use the new one.
1670 if (SrcOp == OldInduction) {
1671 Params.push_back(getVectorValue(SrcOp));
1675 // Try using previously calculated values.
1676 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1678 // If the src is an instruction that appeared earlier in the basic block
1679 // then it should already be vectorized.
1680 if (SrcInst && OrigLoop->contains(SrcInst)) {
1681 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1682 // The parameter is a vector value from earlier.
1683 Params.push_back(WidenMap.get(SrcInst));
1685 // The parameter is a scalar from outside the loop. Maybe even a constant.
1686 VectorParts Scalars;
1687 Scalars.append(UF, SrcOp);
1688 Params.push_back(Scalars);
1692 assert(Params.size() == Instr->getNumOperands() &&
1693 "Invalid number of operands");
1695 // Does this instruction return a value ?
1696 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1698 Value *UndefVec = IsVoidRetTy ? nullptr :
1699 UndefValue::get(VectorType::get(Instr->getType(), VF));
1700 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1701 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1703 Instruction *InsertPt = Builder.GetInsertPoint();
1704 BasicBlock *IfBlock = Builder.GetInsertBlock();
1705 BasicBlock *CondBlock = nullptr;
1708 Loop *VectorLp = nullptr;
1709 if (IfPredicateStore) {
1710 assert(Instr->getParent()->getSinglePredecessor() &&
1711 "Only support single predecessor blocks");
1712 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1713 Instr->getParent());
1714 VectorLp = LI->getLoopFor(IfBlock);
1715 assert(VectorLp && "Must have a loop for this block");
1718 // For each vector unroll 'part':
1719 for (unsigned Part = 0; Part < UF; ++Part) {
1720 // For each scalar that we create:
1721 for (unsigned Width = 0; Width < VF; ++Width) {
1724 Value *Cmp = nullptr;
1725 if (IfPredicateStore) {
1726 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1727 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1728 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1729 LoopVectorBody.push_back(CondBlock);
1730 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1731 // Update Builder with newly created basic block.
1732 Builder.SetInsertPoint(InsertPt);
1735 Instruction *Cloned = Instr->clone();
1737 Cloned->setName(Instr->getName() + ".cloned");
1738 // Replace the operands of the cloned instructions with extracted scalars.
1739 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1740 Value *Op = Params[op][Part];
1741 // Param is a vector. Need to extract the right lane.
1742 if (Op->getType()->isVectorTy())
1743 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1744 Cloned->setOperand(op, Op);
1747 // Place the cloned scalar in the new loop.
1748 Builder.Insert(Cloned);
1750 // If the original scalar returns a value we need to place it in a vector
1751 // so that future users will be able to use it.
1753 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1754 Builder.getInt32(Width));
1756 if (IfPredicateStore) {
1757 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1758 LoopVectorBody.push_back(NewIfBlock);
1759 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1760 Builder.SetInsertPoint(InsertPt);
1761 Instruction *OldBr = IfBlock->getTerminator();
1762 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1763 OldBr->eraseFromParent();
1764 IfBlock = NewIfBlock;
1770 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1774 if (Instruction *I = dyn_cast<Instruction>(V))
1775 return I->getParent() == Loc->getParent() ? I : nullptr;
1779 std::pair<Instruction *, Instruction *>
1780 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1781 Instruction *tnullptr = nullptr;
1782 if (!Legal->mustCheckStrides())
1783 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1785 IRBuilder<> ChkBuilder(Loc);
1788 Value *Check = nullptr;
1789 Instruction *FirstInst = nullptr;
1790 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1791 SE = Legal->strides_end();
1793 Value *Ptr = stripIntegerCast(*SI);
1794 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1796 // Store the first instruction we create.
1797 FirstInst = getFirstInst(FirstInst, C, Loc);
1799 Check = ChkBuilder.CreateOr(Check, C);
1804 // We have to do this trickery because the IRBuilder might fold the check to a
1805 // constant expression in which case there is no Instruction anchored in a
1807 LLVMContext &Ctx = Loc->getContext();
1808 Instruction *TheCheck =
1809 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1810 ChkBuilder.Insert(TheCheck, "stride.not.one");
1811 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1813 return std::make_pair(FirstInst, TheCheck);
1816 std::pair<Instruction *, Instruction *>
1817 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1818 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1819 Legal->getRuntimePointerCheck();
1821 Instruction *tnullptr = nullptr;
1822 if (!PtrRtCheck->Need)
1823 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1825 unsigned NumPointers = PtrRtCheck->Pointers.size();
1826 SmallVector<TrackingVH<Value> , 2> Starts;
1827 SmallVector<TrackingVH<Value> , 2> Ends;
1829 LLVMContext &Ctx = Loc->getContext();
1830 SCEVExpander Exp(*SE, "induction");
1831 Instruction *FirstInst = nullptr;
1833 for (unsigned i = 0; i < NumPointers; ++i) {
1834 Value *Ptr = PtrRtCheck->Pointers[i];
1835 const SCEV *Sc = SE->getSCEV(Ptr);
1837 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1838 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1840 Starts.push_back(Ptr);
1841 Ends.push_back(Ptr);
1843 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1844 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1846 // Use this type for pointer arithmetic.
1847 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1849 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1850 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1851 Starts.push_back(Start);
1852 Ends.push_back(End);
1856 IRBuilder<> ChkBuilder(Loc);
1857 // Our instructions might fold to a constant.
1858 Value *MemoryRuntimeCheck = nullptr;
1859 for (unsigned i = 0; i < NumPointers; ++i) {
1860 for (unsigned j = i+1; j < NumPointers; ++j) {
1861 // No need to check if two readonly pointers intersect.
1862 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1865 // Only need to check pointers between two different dependency sets.
1866 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1869 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1870 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1872 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1873 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1874 "Trying to bounds check pointers with different address spaces");
1876 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1877 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1879 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1880 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1881 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1882 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1884 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1885 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1886 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1887 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1888 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1889 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1890 if (MemoryRuntimeCheck) {
1891 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1893 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1895 MemoryRuntimeCheck = IsConflict;
1899 // We have to do this trickery because the IRBuilder might fold the check to a
1900 // constant expression in which case there is no Instruction anchored in a
1902 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1903 ConstantInt::getTrue(Ctx));
1904 ChkBuilder.Insert(Check, "memcheck.conflict");
1905 FirstInst = getFirstInst(FirstInst, Check, Loc);
1906 return std::make_pair(FirstInst, Check);
1909 void InnerLoopVectorizer::createEmptyLoop() {
1911 In this function we generate a new loop. The new loop will contain
1912 the vectorized instructions while the old loop will continue to run the
1915 [ ] <-- vector loop bypass (may consist of multiple blocks).
1918 | [ ] <-- vector pre header.
1922 | [ ]_| <-- vector loop.
1925 >[ ] <--- middle-block.
1928 | [ ] <--- new preheader.
1932 | [ ]_| <-- old scalar loop to handle remainder.
1935 >[ ] <-- exit block.
1939 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1940 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1941 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1942 assert(ExitBlock && "Must have an exit block");
1944 // Some loops have a single integer induction variable, while other loops
1945 // don't. One example is c++ iterators that often have multiple pointer
1946 // induction variables. In the code below we also support a case where we
1947 // don't have a single induction variable.
1948 OldInduction = Legal->getInduction();
1949 Type *IdxTy = Legal->getWidestInductionType();
1951 // Find the loop boundaries.
1952 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1953 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1955 // The exit count might have the type of i64 while the phi is i32. This can
1956 // happen if we have an induction variable that is sign extended before the
1957 // compare. The only way that we get a backedge taken count is that the
1958 // induction variable was signed and as such will not overflow. In such a case
1959 // truncation is legal.
1960 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1961 IdxTy->getPrimitiveSizeInBits())
1962 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1964 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1965 // Get the total trip count from the count by adding 1.
1966 ExitCount = SE->getAddExpr(ExitCount,
1967 SE->getConstant(ExitCount->getType(), 1));
1969 // Expand the trip count and place the new instructions in the preheader.
1970 // Notice that the pre-header does not change, only the loop body.
1971 SCEVExpander Exp(*SE, "induction");
1973 // Count holds the overall loop count (N).
1974 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1975 BypassBlock->getTerminator());
1977 // The loop index does not have to start at Zero. Find the original start
1978 // value from the induction PHI node. If we don't have an induction variable
1979 // then we know that it starts at zero.
1980 Builder.SetInsertPoint(BypassBlock->getTerminator());
1981 Value *StartIdx = ExtendedIdx = OldInduction ?
1982 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1984 ConstantInt::get(IdxTy, 0);
1986 assert(BypassBlock && "Invalid loop structure");
1987 LoopBypassBlocks.push_back(BypassBlock);
1989 // Split the single block loop into the two loop structure described above.
1990 BasicBlock *VectorPH =
1991 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1992 BasicBlock *VecBody =
1993 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1994 BasicBlock *MiddleBlock =
1995 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1996 BasicBlock *ScalarPH =
1997 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1999 // Create and register the new vector loop.
2000 Loop* Lp = new Loop();
2001 Loop *ParentLoop = OrigLoop->getParentLoop();
2003 // Insert the new loop into the loop nest and register the new basic blocks
2004 // before calling any utilities such as SCEV that require valid LoopInfo.
2006 ParentLoop->addChildLoop(Lp);
2007 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2008 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2009 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2011 LI->addTopLevelLoop(Lp);
2013 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2015 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2017 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2019 // Generate the induction variable.
2020 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2021 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2022 // The loop step is equal to the vectorization factor (num of SIMD elements)
2023 // times the unroll factor (num of SIMD instructions).
2024 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2026 // This is the IR builder that we use to add all of the logic for bypassing
2027 // the new vector loop.
2028 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2029 setDebugLocFromInst(BypassBuilder,
2030 getDebugLocFromInstOrOperands(OldInduction));
2032 // We may need to extend the index in case there is a type mismatch.
2033 // We know that the count starts at zero and does not overflow.
2034 if (Count->getType() != IdxTy) {
2035 // The exit count can be of pointer type. Convert it to the correct
2037 if (ExitCount->getType()->isPointerTy())
2038 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2040 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2043 // Add the start index to the loop count to get the new end index.
2044 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2046 // Now we need to generate the expression for N - (N % VF), which is
2047 // the part that the vectorized body will execute.
2048 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2049 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2050 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2051 "end.idx.rnd.down");
2053 // Now, compare the new count to zero. If it is zero skip the vector loop and
2054 // jump to the scalar loop.
2055 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
2058 BasicBlock *LastBypassBlock = BypassBlock;
2060 // Generate the code to check that the strides we assumed to be one are really
2061 // one. We want the new basic block to start at the first instruction in a
2062 // sequence of instructions that form a check.
2063 Instruction *StrideCheck;
2064 Instruction *FirstCheckInst;
2065 std::tie(FirstCheckInst, StrideCheck) =
2066 addStrideCheck(BypassBlock->getTerminator());
2068 // Create a new block containing the stride check.
2069 BasicBlock *CheckBlock =
2070 BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2072 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2073 LoopBypassBlocks.push_back(CheckBlock);
2075 // Replace the branch into the memory check block with a conditional branch
2076 // for the "few elements case".
2077 Instruction *OldTerm = BypassBlock->getTerminator();
2078 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2079 OldTerm->eraseFromParent();
2082 LastBypassBlock = CheckBlock;
2085 // Generate the code that checks in runtime if arrays overlap. We put the
2086 // checks into a separate block to make the more common case of few elements
2088 Instruction *MemRuntimeCheck;
2089 std::tie(FirstCheckInst, MemRuntimeCheck) =
2090 addRuntimeCheck(LastBypassBlock->getTerminator());
2091 if (MemRuntimeCheck) {
2092 // Create a new block containing the memory check.
2093 BasicBlock *CheckBlock =
2094 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2096 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2097 LoopBypassBlocks.push_back(CheckBlock);
2099 // Replace the branch into the memory check block with a conditional branch
2100 // for the "few elements case".
2101 Instruction *OldTerm = LastBypassBlock->getTerminator();
2102 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2103 OldTerm->eraseFromParent();
2105 Cmp = MemRuntimeCheck;
2106 LastBypassBlock = CheckBlock;
2109 LastBypassBlock->getTerminator()->eraseFromParent();
2110 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2113 // We are going to resume the execution of the scalar loop.
2114 // Go over all of the induction variables that we found and fix the
2115 // PHIs that are left in the scalar version of the loop.
2116 // The starting values of PHI nodes depend on the counter of the last
2117 // iteration in the vectorized loop.
2118 // If we come from a bypass edge then we need to start from the original
2121 // This variable saves the new starting index for the scalar loop.
2122 PHINode *ResumeIndex = nullptr;
2123 LoopVectorizationLegality::InductionList::iterator I, E;
2124 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2125 // Set builder to point to last bypass block.
2126 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2127 for (I = List->begin(), E = List->end(); I != E; ++I) {
2128 PHINode *OrigPhi = I->first;
2129 LoopVectorizationLegality::InductionInfo II = I->second;
2131 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2132 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2133 MiddleBlock->getTerminator());
2134 // We might have extended the type of the induction variable but we need a
2135 // truncated version for the scalar loop.
2136 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2137 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2138 MiddleBlock->getTerminator()) : nullptr;
2140 Value *EndValue = nullptr;
2142 case LoopVectorizationLegality::IK_NoInduction:
2143 llvm_unreachable("Unknown induction");
2144 case LoopVectorizationLegality::IK_IntInduction: {
2145 // Handle the integer induction counter.
2146 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2148 // We have the canonical induction variable.
2149 if (OrigPhi == OldInduction) {
2150 // Create a truncated version of the resume value for the scalar loop,
2151 // we might have promoted the type to a larger width.
2153 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2154 // The new PHI merges the original incoming value, in case of a bypass,
2155 // or the value at the end of the vectorized loop.
2156 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2157 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2158 TruncResumeVal->addIncoming(EndValue, VecBody);
2160 // We know what the end value is.
2161 EndValue = IdxEndRoundDown;
2162 // We also know which PHI node holds it.
2163 ResumeIndex = ResumeVal;
2167 // Not the canonical induction variable - add the vector loop count to the
2169 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2170 II.StartValue->getType(),
2172 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2175 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2176 // Convert the CountRoundDown variable to the PHI size.
2177 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2178 II.StartValue->getType(),
2180 // Handle reverse integer induction counter.
2181 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2184 case LoopVectorizationLegality::IK_PtrInduction: {
2185 // For pointer induction variables, calculate the offset using
2187 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2191 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2192 // The value at the end of the loop for the reverse pointer is calculated
2193 // by creating a GEP with a negative index starting from the start value.
2194 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2195 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2197 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2203 // The new PHI merges the original incoming value, in case of a bypass,
2204 // or the value at the end of the vectorized loop.
2205 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
2206 if (OrigPhi == OldInduction)
2207 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2209 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2211 ResumeVal->addIncoming(EndValue, VecBody);
2213 // Fix the scalar body counter (PHI node).
2214 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2215 // The old inductions phi node in the scalar body needs the truncated value.
2216 if (OrigPhi == OldInduction)
2217 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
2219 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
2222 // If we are generating a new induction variable then we also need to
2223 // generate the code that calculates the exit value. This value is not
2224 // simply the end of the counter because we may skip the vectorized body
2225 // in case of a runtime check.
2227 assert(!ResumeIndex && "Unexpected resume value found");
2228 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2229 MiddleBlock->getTerminator());
2230 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2231 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2232 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2235 // Make sure that we found the index where scalar loop needs to continue.
2236 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2237 "Invalid resume Index");
2239 // Add a check in the middle block to see if we have completed
2240 // all of the iterations in the first vector loop.
2241 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2242 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2243 ResumeIndex, "cmp.n",
2244 MiddleBlock->getTerminator());
2246 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2247 // Remove the old terminator.
2248 MiddleBlock->getTerminator()->eraseFromParent();
2250 // Create i+1 and fill the PHINode.
2251 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2252 Induction->addIncoming(StartIdx, VectorPH);
2253 Induction->addIncoming(NextIdx, VecBody);
2254 // Create the compare.
2255 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2256 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2258 // Now we have two terminators. Remove the old one from the block.
2259 VecBody->getTerminator()->eraseFromParent();
2261 // Get ready to start creating new instructions into the vectorized body.
2262 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2265 LoopVectorPreHeader = VectorPH;
2266 LoopScalarPreHeader = ScalarPH;
2267 LoopMiddleBlock = MiddleBlock;
2268 LoopExitBlock = ExitBlock;
2269 LoopVectorBody.push_back(VecBody);
2270 LoopScalarBody = OldBasicBlock;
2272 LoopVectorizeHints Hints(Lp, true);
2273 Hints.setAlreadyVectorized(Lp);
2276 /// This function returns the identity element (or neutral element) for
2277 /// the operation K.
2279 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2284 // Adding, Xoring, Oring zero to a number does not change it.
2285 return ConstantInt::get(Tp, 0);
2286 case RK_IntegerMult:
2287 // Multiplying a number by 1 does not change it.
2288 return ConstantInt::get(Tp, 1);
2290 // AND-ing a number with an all-1 value does not change it.
2291 return ConstantInt::get(Tp, -1, true);
2293 // Multiplying a number by 1 does not change it.
2294 return ConstantFP::get(Tp, 1.0L);
2296 // Adding zero to a number does not change it.
2297 return ConstantFP::get(Tp, 0.0L);
2299 llvm_unreachable("Unknown reduction kind");
2303 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
2304 Intrinsic::ID ValidIntrinsicID) {
2305 if (I.getNumArgOperands() != 1 ||
2306 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2307 I.getType() != I.getArgOperand(0)->getType() ||
2308 !I.onlyReadsMemory())
2309 return Intrinsic::not_intrinsic;
2311 return ValidIntrinsicID;
2314 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
2315 Intrinsic::ID ValidIntrinsicID) {
2316 if (I.getNumArgOperands() != 2 ||
2317 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2318 !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
2319 I.getType() != I.getArgOperand(0)->getType() ||
2320 I.getType() != I.getArgOperand(1)->getType() ||
2321 !I.onlyReadsMemory())
2322 return Intrinsic::not_intrinsic;
2324 return ValidIntrinsicID;
2328 static Intrinsic::ID
2329 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
2330 // If we have an intrinsic call, check if it is trivially vectorizable.
2331 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2332 Intrinsic::ID ID = II->getIntrinsicID();
2333 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
2334 ID == Intrinsic::lifetime_end)
2337 return Intrinsic::not_intrinsic;
2341 return Intrinsic::not_intrinsic;
2344 Function *F = CI->getCalledFunction();
2345 // We're going to make assumptions on the semantics of the functions, check
2346 // that the target knows that it's available in this environment and it does
2347 // not have local linkage.
2348 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
2349 return Intrinsic::not_intrinsic;
2351 // Otherwise check if we have a call to a function that can be turned into a
2352 // vector intrinsic.
2359 return checkUnaryFloatSignature(*CI, Intrinsic::sin);
2363 return checkUnaryFloatSignature(*CI, Intrinsic::cos);
2367 return checkUnaryFloatSignature(*CI, Intrinsic::exp);
2369 case LibFunc::exp2f:
2370 case LibFunc::exp2l:
2371 return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
2375 return checkUnaryFloatSignature(*CI, Intrinsic::log);
2376 case LibFunc::log10:
2377 case LibFunc::log10f:
2378 case LibFunc::log10l:
2379 return checkUnaryFloatSignature(*CI, Intrinsic::log10);
2381 case LibFunc::log2f:
2382 case LibFunc::log2l:
2383 return checkUnaryFloatSignature(*CI, Intrinsic::log2);
2385 case LibFunc::fabsf:
2386 case LibFunc::fabsl:
2387 return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
2388 case LibFunc::copysign:
2389 case LibFunc::copysignf:
2390 case LibFunc::copysignl:
2391 return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
2392 case LibFunc::floor:
2393 case LibFunc::floorf:
2394 case LibFunc::floorl:
2395 return checkUnaryFloatSignature(*CI, Intrinsic::floor);
2397 case LibFunc::ceilf:
2398 case LibFunc::ceill:
2399 return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
2400 case LibFunc::trunc:
2401 case LibFunc::truncf:
2402 case LibFunc::truncl:
2403 return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
2405 case LibFunc::rintf:
2406 case LibFunc::rintl:
2407 return checkUnaryFloatSignature(*CI, Intrinsic::rint);
2408 case LibFunc::nearbyint:
2409 case LibFunc::nearbyintf:
2410 case LibFunc::nearbyintl:
2411 return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
2412 case LibFunc::round:
2413 case LibFunc::roundf:
2414 case LibFunc::roundl:
2415 return checkUnaryFloatSignature(*CI, Intrinsic::round);
2419 return checkBinaryFloatSignature(*CI, Intrinsic::pow);
2422 return Intrinsic::not_intrinsic;
2425 /// This function translates the reduction kind to an LLVM binary operator.
2427 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2429 case LoopVectorizationLegality::RK_IntegerAdd:
2430 return Instruction::Add;
2431 case LoopVectorizationLegality::RK_IntegerMult:
2432 return Instruction::Mul;
2433 case LoopVectorizationLegality::RK_IntegerOr:
2434 return Instruction::Or;
2435 case LoopVectorizationLegality::RK_IntegerAnd:
2436 return Instruction::And;
2437 case LoopVectorizationLegality::RK_IntegerXor:
2438 return Instruction::Xor;
2439 case LoopVectorizationLegality::RK_FloatMult:
2440 return Instruction::FMul;
2441 case LoopVectorizationLegality::RK_FloatAdd:
2442 return Instruction::FAdd;
2443 case LoopVectorizationLegality::RK_IntegerMinMax:
2444 return Instruction::ICmp;
2445 case LoopVectorizationLegality::RK_FloatMinMax:
2446 return Instruction::FCmp;
2448 llvm_unreachable("Unknown reduction operation");
2452 Value *createMinMaxOp(IRBuilder<> &Builder,
2453 LoopVectorizationLegality::MinMaxReductionKind RK,
2456 CmpInst::Predicate P = CmpInst::ICMP_NE;
2459 llvm_unreachable("Unknown min/max reduction kind");
2460 case LoopVectorizationLegality::MRK_UIntMin:
2461 P = CmpInst::ICMP_ULT;
2463 case LoopVectorizationLegality::MRK_UIntMax:
2464 P = CmpInst::ICMP_UGT;
2466 case LoopVectorizationLegality::MRK_SIntMin:
2467 P = CmpInst::ICMP_SLT;
2469 case LoopVectorizationLegality::MRK_SIntMax:
2470 P = CmpInst::ICMP_SGT;
2472 case LoopVectorizationLegality::MRK_FloatMin:
2473 P = CmpInst::FCMP_OLT;
2475 case LoopVectorizationLegality::MRK_FloatMax:
2476 P = CmpInst::FCMP_OGT;
2481 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2482 RK == LoopVectorizationLegality::MRK_FloatMax)
2483 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2485 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2487 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2492 struct CSEDenseMapInfo {
2493 static bool canHandle(Instruction *I) {
2494 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2495 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2497 static inline Instruction *getEmptyKey() {
2498 return DenseMapInfo<Instruction *>::getEmptyKey();
2500 static inline Instruction *getTombstoneKey() {
2501 return DenseMapInfo<Instruction *>::getTombstoneKey();
2503 static unsigned getHashValue(Instruction *I) {
2504 assert(canHandle(I) && "Unknown instruction!");
2505 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2506 I->value_op_end()));
2508 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2509 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2510 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2512 return LHS->isIdenticalTo(RHS);
2517 /// \brief Check whether this block is a predicated block.
2518 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2519 /// = ...; " blocks. We start with one vectorized basic block. For every
2520 /// conditional block we split this vectorized block. Therefore, every second
2521 /// block will be a predicated one.
2522 static bool isPredicatedBlock(unsigned BlockNum) {
2523 return BlockNum % 2;
2526 ///\brief Perform cse of induction variable instructions.
2527 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2528 // Perform simple cse.
2529 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2530 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2531 BasicBlock *BB = BBs[i];
2532 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2533 Instruction *In = I++;
2535 if (!CSEDenseMapInfo::canHandle(In))
2538 // Check if we can replace this instruction with any of the
2539 // visited instructions.
2540 if (Instruction *V = CSEMap.lookup(In)) {
2541 In->replaceAllUsesWith(V);
2542 In->eraseFromParent();
2545 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2546 // ...;" blocks for predicated stores. Every second block is a predicated
2548 if (isPredicatedBlock(i))
2556 /// \brief Adds a 'fast' flag to floating point operations.
2557 static Value *addFastMathFlag(Value *V) {
2558 if (isa<FPMathOperator>(V)){
2559 FastMathFlags Flags;
2560 Flags.setUnsafeAlgebra();
2561 cast<Instruction>(V)->setFastMathFlags(Flags);
2566 void InnerLoopVectorizer::vectorizeLoop() {
2567 //===------------------------------------------------===//
2569 // Notice: any optimization or new instruction that go
2570 // into the code below should be also be implemented in
2573 //===------------------------------------------------===//
2574 Constant *Zero = Builder.getInt32(0);
2576 // In order to support reduction variables we need to be able to vectorize
2577 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2578 // stages. First, we create a new vector PHI node with no incoming edges.
2579 // We use this value when we vectorize all of the instructions that use the
2580 // PHI. Next, after all of the instructions in the block are complete we
2581 // add the new incoming edges to the PHI. At this point all of the
2582 // instructions in the basic block are vectorized, so we can use them to
2583 // construct the PHI.
2584 PhiVector RdxPHIsToFix;
2586 // Scan the loop in a topological order to ensure that defs are vectorized
2588 LoopBlocksDFS DFS(OrigLoop);
2591 // Vectorize all of the blocks in the original loop.
2592 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2593 be = DFS.endRPO(); bb != be; ++bb)
2594 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2596 // At this point every instruction in the original loop is widened to
2597 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2598 // that we vectorized. The PHI nodes are currently empty because we did
2599 // not want to introduce cycles. Notice that the remaining PHI nodes
2600 // that we need to fix are reduction variables.
2602 // Create the 'reduced' values for each of the induction vars.
2603 // The reduced values are the vector values that we scalarize and combine
2604 // after the loop is finished.
2605 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2607 PHINode *RdxPhi = *it;
2608 assert(RdxPhi && "Unable to recover vectorized PHI");
2610 // Find the reduction variable descriptor.
2611 assert(Legal->getReductionVars()->count(RdxPhi) &&
2612 "Unable to find the reduction variable");
2613 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2614 (*Legal->getReductionVars())[RdxPhi];
2616 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2618 // We need to generate a reduction vector from the incoming scalar.
2619 // To do so, we need to generate the 'identity' vector and override
2620 // one of the elements with the incoming scalar reduction. We need
2621 // to do it in the vector-loop preheader.
2622 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2624 // This is the vector-clone of the value that leaves the loop.
2625 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2626 Type *VecTy = VectorExit[0]->getType();
2628 // Find the reduction identity variable. Zero for addition, or, xor,
2629 // one for multiplication, -1 for And.
2632 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2633 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2634 // MinMax reduction have the start value as their identify.
2636 VectorStart = Identity = RdxDesc.StartValue;
2638 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2643 // Handle other reduction kinds:
2645 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2646 VecTy->getScalarType());
2649 // This vector is the Identity vector where the first element is the
2650 // incoming scalar reduction.
2651 VectorStart = RdxDesc.StartValue;
2653 Identity = ConstantVector::getSplat(VF, Iden);
2655 // This vector is the Identity vector where the first element is the
2656 // incoming scalar reduction.
2657 VectorStart = Builder.CreateInsertElement(Identity,
2658 RdxDesc.StartValue, Zero);
2662 // Fix the vector-loop phi.
2663 // We created the induction variable so we know that the
2664 // preheader is the first entry.
2665 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2667 // Reductions do not have to start at zero. They can start with
2668 // any loop invariant values.
2669 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2670 BasicBlock *Latch = OrigLoop->getLoopLatch();
2671 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2672 VectorParts &Val = getVectorValue(LoopVal);
2673 for (unsigned part = 0; part < UF; ++part) {
2674 // Make sure to add the reduction stat value only to the
2675 // first unroll part.
2676 Value *StartVal = (part == 0) ? VectorStart : Identity;
2677 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2678 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2679 LoopVectorBody.back());
2682 // Before each round, move the insertion point right between
2683 // the PHIs and the values we are going to write.
2684 // This allows us to write both PHINodes and the extractelement
2686 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2688 VectorParts RdxParts;
2689 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2690 for (unsigned part = 0; part < UF; ++part) {
2691 // This PHINode contains the vectorized reduction variable, or
2692 // the initial value vector, if we bypass the vector loop.
2693 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2694 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2695 Value *StartVal = (part == 0) ? VectorStart : Identity;
2696 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2697 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2698 NewPhi->addIncoming(RdxExitVal[part],
2699 LoopVectorBody.back());
2700 RdxParts.push_back(NewPhi);
2703 // Reduce all of the unrolled parts into a single vector.
2704 Value *ReducedPartRdx = RdxParts[0];
2705 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2706 setDebugLocFromInst(Builder, ReducedPartRdx);
2707 for (unsigned part = 1; part < UF; ++part) {
2708 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2709 // Floating point operations had to be 'fast' to enable the reduction.
2710 ReducedPartRdx = addFastMathFlag(
2711 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2712 ReducedPartRdx, "bin.rdx"));
2714 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2715 ReducedPartRdx, RdxParts[part]);
2719 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2720 // and vector ops, reducing the set of values being computed by half each
2722 assert(isPowerOf2_32(VF) &&
2723 "Reduction emission only supported for pow2 vectors!");
2724 Value *TmpVec = ReducedPartRdx;
2725 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2726 for (unsigned i = VF; i != 1; i >>= 1) {
2727 // Move the upper half of the vector to the lower half.
2728 for (unsigned j = 0; j != i/2; ++j)
2729 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2731 // Fill the rest of the mask with undef.
2732 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2733 UndefValue::get(Builder.getInt32Ty()));
2736 Builder.CreateShuffleVector(TmpVec,
2737 UndefValue::get(TmpVec->getType()),
2738 ConstantVector::get(ShuffleMask),
2741 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2742 // Floating point operations had to be 'fast' to enable the reduction.
2743 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2744 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2746 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2749 // The result is in the first element of the vector.
2750 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2751 Builder.getInt32(0));
2754 // Now, we need to fix the users of the reduction variable
2755 // inside and outside of the scalar remainder loop.
2756 // We know that the loop is in LCSSA form. We need to update the
2757 // PHI nodes in the exit blocks.
2758 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2759 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2760 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2761 if (!LCSSAPhi) break;
2763 // All PHINodes need to have a single entry edge, or two if
2764 // we already fixed them.
2765 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2767 // We found our reduction value exit-PHI. Update it with the
2768 // incoming bypass edge.
2769 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2770 // Add an edge coming from the bypass.
2771 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2774 }// end of the LCSSA phi scan.
2776 // Fix the scalar loop reduction variable with the incoming reduction sum
2777 // from the vector body and from the backedge value.
2778 int IncomingEdgeBlockIdx =
2779 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2780 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2781 // Pick the other block.
2782 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2783 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2784 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2785 }// end of for each redux variable.
2789 // Remove redundant induction instructions.
2790 cse(LoopVectorBody);
2793 void InnerLoopVectorizer::fixLCSSAPHIs() {
2794 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2795 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2796 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2797 if (!LCSSAPhi) break;
2798 if (LCSSAPhi->getNumIncomingValues() == 1)
2799 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2804 InnerLoopVectorizer::VectorParts
2805 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2806 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2809 // Look for cached value.
2810 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2811 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2812 if (ECEntryIt != MaskCache.end())
2813 return ECEntryIt->second;
2815 VectorParts SrcMask = createBlockInMask(Src);
2817 // The terminator has to be a branch inst!
2818 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2819 assert(BI && "Unexpected terminator found");
2821 if (BI->isConditional()) {
2822 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2824 if (BI->getSuccessor(0) != Dst)
2825 for (unsigned part = 0; part < UF; ++part)
2826 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2828 for (unsigned part = 0; part < UF; ++part)
2829 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2831 MaskCache[Edge] = EdgeMask;
2835 MaskCache[Edge] = SrcMask;
2839 InnerLoopVectorizer::VectorParts
2840 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2841 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2843 // Loop incoming mask is all-one.
2844 if (OrigLoop->getHeader() == BB) {
2845 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2846 return getVectorValue(C);
2849 // This is the block mask. We OR all incoming edges, and with zero.
2850 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2851 VectorParts BlockMask = getVectorValue(Zero);
2854 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2855 VectorParts EM = createEdgeMask(*it, BB);
2856 for (unsigned part = 0; part < UF; ++part)
2857 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2863 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2864 InnerLoopVectorizer::VectorParts &Entry,
2865 unsigned UF, unsigned VF, PhiVector *PV) {
2866 PHINode* P = cast<PHINode>(PN);
2867 // Handle reduction variables:
2868 if (Legal->getReductionVars()->count(P)) {
2869 for (unsigned part = 0; part < UF; ++part) {
2870 // This is phase one of vectorizing PHIs.
2871 Type *VecTy = (VF == 1) ? PN->getType() :
2872 VectorType::get(PN->getType(), VF);
2873 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2874 LoopVectorBody.back()-> getFirstInsertionPt());
2880 setDebugLocFromInst(Builder, P);
2881 // Check for PHI nodes that are lowered to vector selects.
2882 if (P->getParent() != OrigLoop->getHeader()) {
2883 // We know that all PHIs in non-header blocks are converted into
2884 // selects, so we don't have to worry about the insertion order and we
2885 // can just use the builder.
2886 // At this point we generate the predication tree. There may be
2887 // duplications since this is a simple recursive scan, but future
2888 // optimizations will clean it up.
2890 unsigned NumIncoming = P->getNumIncomingValues();
2892 // Generate a sequence of selects of the form:
2893 // SELECT(Mask3, In3,
2894 // SELECT(Mask2, In2,
2896 for (unsigned In = 0; In < NumIncoming; In++) {
2897 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2899 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2901 for (unsigned part = 0; part < UF; ++part) {
2902 // We might have single edge PHIs (blocks) - use an identity
2903 // 'select' for the first PHI operand.
2905 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2908 // Select between the current value and the previous incoming edge
2909 // based on the incoming mask.
2910 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2911 Entry[part], "predphi");
2917 // This PHINode must be an induction variable.
2918 // Make sure that we know about it.
2919 assert(Legal->getInductionVars()->count(P) &&
2920 "Not an induction variable");
2922 LoopVectorizationLegality::InductionInfo II =
2923 Legal->getInductionVars()->lookup(P);
2926 case LoopVectorizationLegality::IK_NoInduction:
2927 llvm_unreachable("Unknown induction");
2928 case LoopVectorizationLegality::IK_IntInduction: {
2929 assert(P->getType() == II.StartValue->getType() && "Types must match");
2930 Type *PhiTy = P->getType();
2932 if (P == OldInduction) {
2933 // Handle the canonical induction variable. We might have had to
2935 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2937 // Handle other induction variables that are now based on the
2939 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2941 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2942 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2945 Broadcasted = getBroadcastInstrs(Broadcasted);
2946 // After broadcasting the induction variable we need to make the vector
2947 // consecutive by adding 0, 1, 2, etc.
2948 for (unsigned part = 0; part < UF; ++part)
2949 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2952 case LoopVectorizationLegality::IK_ReverseIntInduction:
2953 case LoopVectorizationLegality::IK_PtrInduction:
2954 case LoopVectorizationLegality::IK_ReversePtrInduction:
2955 // Handle reverse integer and pointer inductions.
2956 Value *StartIdx = ExtendedIdx;
2957 // This is the normalized GEP that starts counting at zero.
2958 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2961 // Handle the reverse integer induction variable case.
2962 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2963 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2964 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2966 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2969 // This is a new value so do not hoist it out.
2970 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2971 // After broadcasting the induction variable we need to make the
2972 // vector consecutive by adding ... -3, -2, -1, 0.
2973 for (unsigned part = 0; part < UF; ++part)
2974 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2979 // Handle the pointer induction variable case.
2980 assert(P->getType()->isPointerTy() && "Unexpected type.");
2982 // Is this a reverse induction ptr or a consecutive induction ptr.
2983 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2986 // This is the vector of results. Notice that we don't generate
2987 // vector geps because scalar geps result in better code.
2988 for (unsigned part = 0; part < UF; ++part) {
2990 int EltIndex = (part) * (Reverse ? -1 : 1);
2991 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2994 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2996 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2998 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3000 Entry[part] = SclrGep;
3004 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3005 for (unsigned int i = 0; i < VF; ++i) {
3006 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
3007 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3010 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3012 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3014 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3016 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3017 Builder.getInt32(i),
3020 Entry[part] = VecVal;
3026 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3027 // For each instruction in the old loop.
3028 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3029 VectorParts &Entry = WidenMap.get(it);
3030 switch (it->getOpcode()) {
3031 case Instruction::Br:
3032 // Nothing to do for PHIs and BR, since we already took care of the
3033 // loop control flow instructions.
3035 case Instruction::PHI:{
3036 // Vectorize PHINodes.
3037 widenPHIInstruction(it, Entry, UF, VF, PV);
3041 case Instruction::Add:
3042 case Instruction::FAdd:
3043 case Instruction::Sub:
3044 case Instruction::FSub:
3045 case Instruction::Mul:
3046 case Instruction::FMul:
3047 case Instruction::UDiv:
3048 case Instruction::SDiv:
3049 case Instruction::FDiv:
3050 case Instruction::URem:
3051 case Instruction::SRem:
3052 case Instruction::FRem:
3053 case Instruction::Shl:
3054 case Instruction::LShr:
3055 case Instruction::AShr:
3056 case Instruction::And:
3057 case Instruction::Or:
3058 case Instruction::Xor: {
3059 // Just widen binops.
3060 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3061 setDebugLocFromInst(Builder, BinOp);
3062 VectorParts &A = getVectorValue(it->getOperand(0));
3063 VectorParts &B = getVectorValue(it->getOperand(1));
3065 // Use this vector value for all users of the original instruction.
3066 for (unsigned Part = 0; Part < UF; ++Part) {
3067 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3069 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
3070 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
3071 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
3072 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
3073 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
3075 if (VecOp && isa<PossiblyExactOperator>(VecOp))
3076 VecOp->setIsExact(BinOp->isExact());
3078 // Copy the fast-math flags.
3079 if (VecOp && isa<FPMathOperator>(V))
3080 VecOp->setFastMathFlags(it->getFastMathFlags());
3086 case Instruction::Select: {
3088 // If the selector is loop invariant we can create a select
3089 // instruction with a scalar condition. Otherwise, use vector-select.
3090 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3092 setDebugLocFromInst(Builder, it);
3094 // The condition can be loop invariant but still defined inside the
3095 // loop. This means that we can't just use the original 'cond' value.
3096 // We have to take the 'vectorized' value and pick the first lane.
3097 // Instcombine will make this a no-op.
3098 VectorParts &Cond = getVectorValue(it->getOperand(0));
3099 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3100 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3102 Value *ScalarCond = (VF == 1) ? Cond[0] :
3103 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3105 for (unsigned Part = 0; Part < UF; ++Part) {
3106 Entry[Part] = Builder.CreateSelect(
3107 InvariantCond ? ScalarCond : Cond[Part],
3114 case Instruction::ICmp:
3115 case Instruction::FCmp: {
3116 // Widen compares. Generate vector compares.
3117 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3118 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3119 setDebugLocFromInst(Builder, it);
3120 VectorParts &A = getVectorValue(it->getOperand(0));
3121 VectorParts &B = getVectorValue(it->getOperand(1));
3122 for (unsigned Part = 0; Part < UF; ++Part) {
3125 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3127 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3133 case Instruction::Store:
3134 case Instruction::Load:
3135 vectorizeMemoryInstruction(it);
3137 case Instruction::ZExt:
3138 case Instruction::SExt:
3139 case Instruction::FPToUI:
3140 case Instruction::FPToSI:
3141 case Instruction::FPExt:
3142 case Instruction::PtrToInt:
3143 case Instruction::IntToPtr:
3144 case Instruction::SIToFP:
3145 case Instruction::UIToFP:
3146 case Instruction::Trunc:
3147 case Instruction::FPTrunc:
3148 case Instruction::BitCast: {
3149 CastInst *CI = dyn_cast<CastInst>(it);
3150 setDebugLocFromInst(Builder, it);
3151 /// Optimize the special case where the source is the induction
3152 /// variable. Notice that we can only optimize the 'trunc' case
3153 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3154 /// c. other casts depend on pointer size.
3155 if (CI->getOperand(0) == OldInduction &&
3156 it->getOpcode() == Instruction::Trunc) {
3157 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3159 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3160 for (unsigned Part = 0; Part < UF; ++Part)
3161 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3164 /// Vectorize casts.
3165 Type *DestTy = (VF == 1) ? CI->getType() :
3166 VectorType::get(CI->getType(), VF);
3168 VectorParts &A = getVectorValue(it->getOperand(0));
3169 for (unsigned Part = 0; Part < UF; ++Part)
3170 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3174 case Instruction::Call: {
3175 // Ignore dbg intrinsics.
3176 if (isa<DbgInfoIntrinsic>(it))
3178 setDebugLocFromInst(Builder, it);
3180 Module *M = BB->getParent()->getParent();
3181 CallInst *CI = cast<CallInst>(it);
3182 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3183 assert(ID && "Not an intrinsic call!");
3185 case Intrinsic::lifetime_end:
3186 case Intrinsic::lifetime_start:
3187 scalarizeInstruction(it);
3190 for (unsigned Part = 0; Part < UF; ++Part) {
3191 SmallVector<Value *, 4> Args;
3192 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3193 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3194 Args.push_back(Arg[Part]);
3196 Type *Tys[] = {CI->getType()};
3198 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3200 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3201 Entry[Part] = Builder.CreateCall(F, Args);
3209 // All other instructions are unsupported. Scalarize them.
3210 scalarizeInstruction(it);
3213 }// end of for_each instr.
3216 void InnerLoopVectorizer::updateAnalysis() {
3217 // Forget the original basic block.
3218 SE->forgetLoop(OrigLoop);
3220 // Update the dominator tree information.
3221 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3222 "Entry does not dominate exit.");
3224 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3225 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3226 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3228 // Due to if predication of stores we might create a sequence of "if(pred)
3229 // a[i] = ...; " blocks.
3230 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3232 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3233 else if (isPredicatedBlock(i)) {
3234 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3236 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3240 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
3241 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
3242 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3243 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3245 DEBUG(DT->verifyDomTree());
3248 /// \brief Check whether it is safe to if-convert this phi node.
3250 /// Phi nodes with constant expressions that can trap are not safe to if
3252 static bool canIfConvertPHINodes(BasicBlock *BB) {
3253 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3254 PHINode *Phi = dyn_cast<PHINode>(I);
3257 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3258 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3265 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3266 if (!EnableIfConversion)
3269 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3271 // A list of pointers that we can safely read and write to.
3272 SmallPtrSet<Value *, 8> SafePointes;
3274 // Collect safe addresses.
3275 for (Loop::block_iterator BI = TheLoop->block_begin(),
3276 BE = TheLoop->block_end(); BI != BE; ++BI) {
3277 BasicBlock *BB = *BI;
3279 if (blockNeedsPredication(BB))
3282 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3283 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3284 SafePointes.insert(LI->getPointerOperand());
3285 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3286 SafePointes.insert(SI->getPointerOperand());
3290 // Collect the blocks that need predication.
3291 BasicBlock *Header = TheLoop->getHeader();
3292 for (Loop::block_iterator BI = TheLoop->block_begin(),
3293 BE = TheLoop->block_end(); BI != BE; ++BI) {
3294 BasicBlock *BB = *BI;
3296 // We don't support switch statements inside loops.
3297 if (!isa<BranchInst>(BB->getTerminator()))
3300 // We must be able to predicate all blocks that need to be predicated.
3301 if (blockNeedsPredication(BB)) {
3302 if (!blockCanBePredicated(BB, SafePointes))
3304 } else if (BB != Header && !canIfConvertPHINodes(BB))
3309 // We can if-convert this loop.
3313 bool LoopVectorizationLegality::canVectorize() {
3314 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3315 // be canonicalized.
3316 if (!TheLoop->getLoopPreheader())
3319 // We can only vectorize innermost loops.
3320 if (TheLoop->getSubLoopsVector().size())
3323 // We must have a single backedge.
3324 if (TheLoop->getNumBackEdges() != 1)
3327 // We must have a single exiting block.
3328 if (!TheLoop->getExitingBlock())
3331 // We need to have a loop header.
3332 DEBUG(dbgs() << "LV: Found a loop: " <<
3333 TheLoop->getHeader()->getName() << '\n');
3335 // Check if we can if-convert non-single-bb loops.
3336 unsigned NumBlocks = TheLoop->getNumBlocks();
3337 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3338 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3342 // ScalarEvolution needs to be able to find the exit count.
3343 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3344 if (ExitCount == SE->getCouldNotCompute()) {
3345 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3349 // Check if we can vectorize the instructions and CFG in this loop.
3350 if (!canVectorizeInstrs()) {
3351 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3355 // Go over each instruction and look at memory deps.
3356 if (!canVectorizeMemory()) {
3357 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3361 // Collect all of the variables that remain uniform after vectorization.
3362 collectLoopUniforms();
3364 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3365 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3368 // Okay! We can vectorize. At this point we don't have any other mem analysis
3369 // which may limit our maximum vectorization factor, so just return true with
3374 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3375 if (Ty->isPointerTy())
3376 return DL.getIntPtrType(Ty);
3378 // It is possible that char's or short's overflow when we ask for the loop's
3379 // trip count, work around this by changing the type size.
3380 if (Ty->getScalarSizeInBits() < 32)
3381 return Type::getInt32Ty(Ty->getContext());
3386 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3387 Ty0 = convertPointerToIntegerType(DL, Ty0);
3388 Ty1 = convertPointerToIntegerType(DL, Ty1);
3389 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3394 /// \brief Check that the instruction has outside loop users and is not an
3395 /// identified reduction variable.
3396 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3397 SmallPtrSet<Value *, 4> &Reductions) {
3398 // Reduction instructions are allowed to have exit users. All other
3399 // instructions must not have external users.
3400 if (!Reductions.count(Inst))
3401 //Check that all of the users of the loop are inside the BB.
3402 for (User *U : Inst->users()) {
3403 Instruction *UI = cast<Instruction>(U);
3404 // This user may be a reduction exit value.
3405 if (!TheLoop->contains(UI)) {
3406 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3413 bool LoopVectorizationLegality::canVectorizeInstrs() {
3414 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3415 BasicBlock *Header = TheLoop->getHeader();
3417 // Look for the attribute signaling the absence of NaNs.
3418 Function &F = *Header->getParent();
3419 if (F.hasFnAttribute("no-nans-fp-math"))
3420 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3421 AttributeSet::FunctionIndex,
3422 "no-nans-fp-math").getValueAsString() == "true";
3424 // For each block in the loop.
3425 for (Loop::block_iterator bb = TheLoop->block_begin(),
3426 be = TheLoop->block_end(); bb != be; ++bb) {
3428 // Scan the instructions in the block and look for hazards.
3429 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3432 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3433 Type *PhiTy = Phi->getType();
3434 // Check that this PHI type is allowed.
3435 if (!PhiTy->isIntegerTy() &&
3436 !PhiTy->isFloatingPointTy() &&
3437 !PhiTy->isPointerTy()) {
3438 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3442 // If this PHINode is not in the header block, then we know that we
3443 // can convert it to select during if-conversion. No need to check if
3444 // the PHIs in this block are induction or reduction variables.
3445 if (*bb != Header) {
3446 // Check that this instruction has no outside users or is an
3447 // identified reduction value with an outside user.
3448 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3453 // We only allow if-converted PHIs with more than two incoming values.
3454 if (Phi->getNumIncomingValues() != 2) {
3455 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3459 // This is the value coming from the preheader.
3460 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3461 // Check if this is an induction variable.
3462 InductionKind IK = isInductionVariable(Phi);
3464 if (IK_NoInduction != IK) {
3465 // Get the widest type.
3467 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3469 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3471 // Int inductions are special because we only allow one IV.
3472 if (IK == IK_IntInduction) {
3473 // Use the phi node with the widest type as induction. Use the last
3474 // one if there are multiple (no good reason for doing this other
3475 // than it is expedient).
3476 if (!Induction || PhiTy == WidestIndTy)
3480 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3481 Inductions[Phi] = InductionInfo(StartValue, IK);
3483 // Until we explicitly handle the case of an induction variable with
3484 // an outside loop user we have to give up vectorizing this loop.
3485 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3491 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3492 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3495 if (AddReductionVar(Phi, RK_IntegerMult)) {
3496 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3499 if (AddReductionVar(Phi, RK_IntegerOr)) {
3500 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3503 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3504 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3507 if (AddReductionVar(Phi, RK_IntegerXor)) {
3508 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3511 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3512 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3515 if (AddReductionVar(Phi, RK_FloatMult)) {
3516 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3519 if (AddReductionVar(Phi, RK_FloatAdd)) {
3520 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3523 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3524 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3529 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3531 }// end of PHI handling
3533 // We still don't handle functions. However, we can ignore dbg intrinsic
3534 // calls and we do handle certain intrinsic and libm functions.
3535 CallInst *CI = dyn_cast<CallInst>(it);
3536 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3537 DEBUG(dbgs() << "LV: Found a call site.\n");
3541 // Check that the instruction return type is vectorizable.
3542 // Also, we can't vectorize extractelement instructions.
3543 if ((!VectorType::isValidElementType(it->getType()) &&
3544 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3545 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3549 // Check that the stored type is vectorizable.
3550 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3551 Type *T = ST->getValueOperand()->getType();
3552 if (!VectorType::isValidElementType(T))
3554 if (EnableMemAccessVersioning)
3555 collectStridedAcccess(ST);
3558 if (EnableMemAccessVersioning)
3559 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3560 collectStridedAcccess(LI);
3562 // Reduction instructions are allowed to have exit users.
3563 // All other instructions must not have external users.
3564 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3572 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3573 if (Inductions.empty())
3580 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3581 /// return the induction operand of the gep pointer.
3582 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3583 const DataLayout *DL, Loop *Lp) {
3584 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3588 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3590 // Check that all of the gep indices are uniform except for our induction
3592 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3593 if (i != InductionOperand &&
3594 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3596 return GEP->getOperand(InductionOperand);
3599 ///\brief Look for a cast use of the passed value.
3600 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3601 Value *UniqueCast = nullptr;
3602 for (User *U : Ptr->users()) {
3603 CastInst *CI = dyn_cast<CastInst>(U);
3604 if (CI && CI->getType() == Ty) {
3614 ///\brief Get the stride of a pointer access in a loop.
3615 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3616 /// pointer to the Value, or null otherwise.
3617 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3618 const DataLayout *DL, Loop *Lp) {
3619 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3620 if (!PtrTy || PtrTy->isAggregateType())
3623 // Try to remove a gep instruction to make the pointer (actually index at this
3624 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3625 // pointer, otherwise, we are analyzing the index.
3626 Value *OrigPtr = Ptr;
3628 // The size of the pointer access.
3629 int64_t PtrAccessSize = 1;
3631 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3632 const SCEV *V = SE->getSCEV(Ptr);
3636 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3637 V = C->getOperand();
3639 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3643 V = S->getStepRecurrence(*SE);
3647 // Strip off the size of access multiplication if we are still analyzing the
3649 if (OrigPtr == Ptr) {
3650 DL->getTypeAllocSize(PtrTy->getElementType());
3651 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3652 if (M->getOperand(0)->getSCEVType() != scConstant)
3655 const APInt &APStepVal =
3656 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3658 // Huge step value - give up.
3659 if (APStepVal.getBitWidth() > 64)
3662 int64_t StepVal = APStepVal.getSExtValue();
3663 if (PtrAccessSize != StepVal)
3665 V = M->getOperand(1);
3670 Type *StripedOffRecurrenceCast = nullptr;
3671 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3672 StripedOffRecurrenceCast = C->getType();
3673 V = C->getOperand();
3676 // Look for the loop invariant symbolic value.
3677 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3681 Value *Stride = U->getValue();
3682 if (!Lp->isLoopInvariant(Stride))
3685 // If we have stripped off the recurrence cast we have to make sure that we
3686 // return the value that is used in this loop so that we can replace it later.
3687 if (StripedOffRecurrenceCast)
3688 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3693 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3694 Value *Ptr = nullptr;
3695 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3696 Ptr = LI->getPointerOperand();
3697 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3698 Ptr = SI->getPointerOperand();
3702 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3706 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3707 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3708 Strides[Ptr] = Stride;
3709 StrideSet.insert(Stride);
3712 void LoopVectorizationLegality::collectLoopUniforms() {
3713 // We now know that the loop is vectorizable!
3714 // Collect variables that will remain uniform after vectorization.
3715 std::vector<Value*> Worklist;
3716 BasicBlock *Latch = TheLoop->getLoopLatch();
3718 // Start with the conditional branch and walk up the block.
3719 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3721 // Also add all consecutive pointer values; these values will be uniform
3722 // after vectorization (and subsequent cleanup) and, until revectorization is
3723 // supported, all dependencies must also be uniform.
3724 for (Loop::block_iterator B = TheLoop->block_begin(),
3725 BE = TheLoop->block_end(); B != BE; ++B)
3726 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3728 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3729 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3731 while (Worklist.size()) {
3732 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3733 Worklist.pop_back();
3735 // Look at instructions inside this loop.
3736 // Stop when reaching PHI nodes.
3737 // TODO: we need to follow values all over the loop, not only in this block.
3738 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3741 // This is a known uniform.
3744 // Insert all operands.
3745 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3750 /// \brief Analyses memory accesses in a loop.
3752 /// Checks whether run time pointer checks are needed and builds sets for data
3753 /// dependence checking.
3754 class AccessAnalysis {
3756 /// \brief Read or write access location.
3757 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3758 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3760 /// \brief Set of potential dependent memory accesses.
3761 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3763 AccessAnalysis(const DataLayout *Dl, DepCandidates &DA) :
3764 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3765 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3767 /// \brief Register a load and whether it is only read from.
3768 void addLoad(Value *Ptr, bool IsReadOnly) {
3769 Accesses.insert(MemAccessInfo(Ptr, false));
3771 ReadOnlyPtr.insert(Ptr);
3774 /// \brief Register a store.
3775 void addStore(Value *Ptr) {
3776 Accesses.insert(MemAccessInfo(Ptr, true));
3779 /// \brief Check whether we can check the pointers at runtime for
3780 /// non-intersection.
3781 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3782 unsigned &NumComparisons, ScalarEvolution *SE,
3783 Loop *TheLoop, ValueToValueMap &Strides,
3784 bool ShouldCheckStride = false);
3786 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3787 /// and builds sets of dependent accesses.
3788 void buildDependenceSets() {
3789 // Process read-write pointers first.
3790 processMemAccesses(false);
3791 // Next, process read pointers.
3792 processMemAccesses(true);
3795 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3797 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3798 void resetDepChecks() { CheckDeps.clear(); }
3800 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3803 typedef SetVector<MemAccessInfo> PtrAccessSet;
3804 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3806 /// \brief Go over all memory access or only the deferred ones if
3807 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3808 /// and build sets of dependency check candidates.
3809 void processMemAccesses(bool UseDeferred);
3811 /// Set of all accesses.
3812 PtrAccessSet Accesses;
3814 /// Set of access to check after all writes have been processed.
3815 PtrAccessSet DeferredAccesses;
3817 /// Map of pointers to last access encountered.
3818 UnderlyingObjToAccessMap ObjToLastAccess;
3820 /// Set of accesses that need a further dependence check.
3821 MemAccessInfoSet CheckDeps;
3823 /// Set of pointers that are read only.
3824 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3826 /// Set of underlying objects already written to.
3827 SmallPtrSet<Value*, 16> WriteObjects;
3829 const DataLayout *DL;
3831 /// Sets of potentially dependent accesses - members of one set share an
3832 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3833 /// dependence check.
3834 DepCandidates &DepCands;
3836 bool AreAllWritesIdentified;
3837 bool AreAllReadsIdentified;
3838 bool IsRTCheckNeeded;
3841 } // end anonymous namespace
3843 /// \brief Check whether a pointer can participate in a runtime bounds check.
3844 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3846 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3847 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3851 return AR->isAffine();
3854 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3855 /// the address space.
3856 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
3857 const Loop *Lp, ValueToValueMap &StridesMap);
3859 bool AccessAnalysis::canCheckPtrAtRT(
3860 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3861 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3862 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3863 // Find pointers with computable bounds. We are going to use this information
3864 // to place a runtime bound check.
3865 unsigned NumReadPtrChecks = 0;
3866 unsigned NumWritePtrChecks = 0;
3867 bool CanDoRT = true;
3869 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3870 // We assign consecutive id to access from different dependence sets.
3871 // Accesses within the same set don't need a runtime check.
3872 unsigned RunningDepId = 1;
3873 DenseMap<Value *, unsigned> DepSetId;
3875 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3877 const MemAccessInfo &Access = *AI;
3878 Value *Ptr = Access.getPointer();
3879 bool IsWrite = Access.getInt();
3881 // Just add write checks if we have both.
3882 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3886 ++NumWritePtrChecks;
3890 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3891 // When we run after a failing dependency check we have to make sure we
3892 // don't have wrapping pointers.
3893 (!ShouldCheckStride ||
3894 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3895 // The id of the dependence set.
3898 if (IsDepCheckNeeded) {
3899 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3900 unsigned &LeaderId = DepSetId[Leader];
3902 LeaderId = RunningDepId++;
3905 // Each access has its own dependence set.
3906 DepId = RunningDepId++;
3908 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3910 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3916 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3917 NumComparisons = 0; // Only one dependence set.
3919 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3920 NumWritePtrChecks - 1));
3923 // If the pointers that we would use for the bounds comparison have different
3924 // address spaces, assume the values aren't directly comparable, so we can't
3925 // use them for the runtime check. We also have to assume they could
3926 // overlap. In the future there should be metadata for whether address spaces
3928 unsigned NumPointers = RtCheck.Pointers.size();
3929 for (unsigned i = 0; i < NumPointers; ++i) {
3930 for (unsigned j = i + 1; j < NumPointers; ++j) {
3931 // Only need to check pointers between two different dependency sets.
3932 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3935 Value *PtrI = RtCheck.Pointers[i];
3936 Value *PtrJ = RtCheck.Pointers[j];
3938 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3939 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3941 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3942 " different address spaces\n");
3951 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3952 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3955 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3956 // We process the set twice: first we process read-write pointers, last we
3957 // process read-only pointers. This allows us to skip dependence tests for
3958 // read-only pointers.
3960 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3961 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3962 const MemAccessInfo &Access = *AI;
3963 Value *Ptr = Access.getPointer();
3964 bool IsWrite = Access.getInt();
3966 DepCands.insert(Access);
3968 // Memorize read-only pointers for later processing and skip them in the
3969 // first round (they need to be checked after we have seen all write
3970 // pointers). Note: we also mark pointer that are not consecutive as
3971 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3972 // second check for "!IsWrite".
3973 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3974 if (!UseDeferred && IsReadOnlyPtr) {
3975 DeferredAccesses.insert(Access);
3979 bool NeedDepCheck = false;
3980 // Check whether there is the possibility of dependency because of
3981 // underlying objects being the same.
3982 typedef SmallVector<Value*, 16> ValueVector;
3983 ValueVector TempObjects;
3984 GetUnderlyingObjects(Ptr, TempObjects, DL);
3985 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3987 Value *UnderlyingObj = *UI;
3989 // If this is a write then it needs to be an identified object. If this a
3990 // read and all writes (so far) are identified function scope objects we
3991 // don't need an identified underlying object but only an Argument (the
3992 // next write is going to invalidate this assumption if it is
3994 // This is a micro-optimization for the case where all writes are
3995 // identified and we have one argument pointer.
3996 // Otherwise, we do need a runtime check.
3997 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3998 (!IsWrite && (!AreAllWritesIdentified ||
3999 !isa<Argument>(UnderlyingObj)) &&
4000 !isIdentifiedObject(UnderlyingObj))) {
4001 DEBUG(dbgs() << "LV: Found an unidentified " <<
4002 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
4004 IsRTCheckNeeded = (IsRTCheckNeeded ||
4005 !isIdentifiedObject(UnderlyingObj) ||
4006 !AreAllReadsIdentified);
4009 AreAllWritesIdentified = false;
4011 AreAllReadsIdentified = false;
4014 // If this is a write - check other reads and writes for conflicts. If
4015 // this is a read only check other writes for conflicts (but only if there
4016 // is no other write to the ptr - this is an optimization to catch "a[i] =
4017 // a[i] + " without having to do a dependence check).
4018 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
4019 NeedDepCheck = true;
4022 WriteObjects.insert(UnderlyingObj);
4024 // Create sets of pointers connected by shared underlying objects.
4025 UnderlyingObjToAccessMap::iterator Prev =
4026 ObjToLastAccess.find(UnderlyingObj);
4027 if (Prev != ObjToLastAccess.end())
4028 DepCands.unionSets(Access, Prev->second);
4030 ObjToLastAccess[UnderlyingObj] = Access;
4034 CheckDeps.insert(Access);
4039 /// \brief Checks memory dependences among accesses to the same underlying
4040 /// object to determine whether there vectorization is legal or not (and at
4041 /// which vectorization factor).
4043 /// This class works under the assumption that we already checked that memory
4044 /// locations with different underlying pointers are "must-not alias".
4045 /// We use the ScalarEvolution framework to symbolically evalutate access
4046 /// functions pairs. Since we currently don't restructure the loop we can rely
4047 /// on the program order of memory accesses to determine their safety.
4048 /// At the moment we will only deem accesses as safe for:
4049 /// * A negative constant distance assuming program order.
4051 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
4052 /// a[i] = tmp; y = a[i];
4054 /// The latter case is safe because later checks guarantuee that there can't
4055 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
4056 /// the same variable: a header phi can only be an induction or a reduction, a
4057 /// reduction can't have a memory sink, an induction can't have a memory
4058 /// source). This is important and must not be violated (or we have to
4059 /// resort to checking for cycles through memory).
4061 /// * A positive constant distance assuming program order that is bigger
4062 /// than the biggest memory access.
4064 /// tmp = a[i] OR b[i] = x
4065 /// a[i+2] = tmp y = b[i+2];
4067 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4069 /// * Zero distances and all accesses have the same size.
4071 class MemoryDepChecker {
4073 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4074 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4076 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4077 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4078 ShouldRetryWithRuntimeCheck(false) {}
4080 /// \brief Register the location (instructions are given increasing numbers)
4081 /// of a write access.
4082 void addAccess(StoreInst *SI) {
4083 Value *Ptr = SI->getPointerOperand();
4084 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4085 InstMap.push_back(SI);
4089 /// \brief Register the location (instructions are given increasing numbers)
4090 /// of a write access.
4091 void addAccess(LoadInst *LI) {
4092 Value *Ptr = LI->getPointerOperand();
4093 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4094 InstMap.push_back(LI);
4098 /// \brief Check whether the dependencies between the accesses are safe.
4100 /// Only checks sets with elements in \p CheckDeps.
4101 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4102 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4104 /// \brief The maximum number of bytes of a vector register we can vectorize
4105 /// the accesses safely with.
4106 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4108 /// \brief In same cases when the dependency check fails we can still
4109 /// vectorize the loop with a dynamic array access check.
4110 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4113 ScalarEvolution *SE;
4114 const DataLayout *DL;
4115 const Loop *InnermostLoop;
4117 /// \brief Maps access locations (ptr, read/write) to program order.
4118 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4120 /// \brief Memory access instructions in program order.
4121 SmallVector<Instruction *, 16> InstMap;
4123 /// \brief The program order index to be used for the next instruction.
4126 // We can access this many bytes in parallel safely.
4127 unsigned MaxSafeDepDistBytes;
4129 /// \brief If we see a non-constant dependence distance we can still try to
4130 /// vectorize this loop with runtime checks.
4131 bool ShouldRetryWithRuntimeCheck;
4133 /// \brief Check whether there is a plausible dependence between the two
4136 /// Access \p A must happen before \p B in program order. The two indices
4137 /// identify the index into the program order map.
4139 /// This function checks whether there is a plausible dependence (or the
4140 /// absence of such can't be proved) between the two accesses. If there is a
4141 /// plausible dependence but the dependence distance is bigger than one
4142 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4143 /// distance is smaller than any other distance encountered so far).
4144 /// Otherwise, this function returns true signaling a possible dependence.
4145 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4146 const MemAccessInfo &B, unsigned BIdx,
4147 ValueToValueMap &Strides);
4149 /// \brief Check whether the data dependence could prevent store-load
4151 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4154 } // end anonymous namespace
4156 static bool isInBoundsGep(Value *Ptr) {
4157 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4158 return GEP->isInBounds();
4162 /// \brief Check whether the access through \p Ptr has a constant stride.
4163 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4164 const Loop *Lp, ValueToValueMap &StridesMap) {
4165 const Type *Ty = Ptr->getType();
4166 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4168 // Make sure that the pointer does not point to aggregate types.
4169 const PointerType *PtrTy = cast<PointerType>(Ty);
4170 if (PtrTy->getElementType()->isAggregateType()) {
4171 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4176 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4178 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4180 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4181 << *Ptr << " SCEV: " << *PtrScev << "\n");
4185 // The accesss function must stride over the innermost loop.
4186 if (Lp != AR->getLoop()) {
4187 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4188 *Ptr << " SCEV: " << *PtrScev << "\n");
4191 // The address calculation must not wrap. Otherwise, a dependence could be
4193 // An inbounds getelementptr that is a AddRec with a unit stride
4194 // cannot wrap per definition. The unit stride requirement is checked later.
4195 // An getelementptr without an inbounds attribute and unit stride would have
4196 // to access the pointer value "0" which is undefined behavior in address
4197 // space 0, therefore we can also vectorize this case.
4198 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4199 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4200 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4201 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4202 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4203 << *Ptr << " SCEV: " << *PtrScev << "\n");
4207 // Check the step is constant.
4208 const SCEV *Step = AR->getStepRecurrence(*SE);
4210 // Calculate the pointer stride and check if it is consecutive.
4211 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4213 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4214 " SCEV: " << *PtrScev << "\n");
4218 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4219 const APInt &APStepVal = C->getValue()->getValue();
4221 // Huge step value - give up.
4222 if (APStepVal.getBitWidth() > 64)
4225 int64_t StepVal = APStepVal.getSExtValue();
4228 int64_t Stride = StepVal / Size;
4229 int64_t Rem = StepVal % Size;
4233 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4234 // know we can't "wrap around the address space". In case of address space
4235 // zero we know that this won't happen without triggering undefined behavior.
4236 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4237 Stride != 1 && Stride != -1)
4243 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4244 unsigned TypeByteSize) {
4245 // If loads occur at a distance that is not a multiple of a feasible vector
4246 // factor store-load forwarding does not take place.
4247 // Positive dependences might cause troubles because vectorizing them might
4248 // prevent store-load forwarding making vectorized code run a lot slower.
4249 // a[i] = a[i-3] ^ a[i-8];
4250 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4251 // hence on your typical architecture store-load forwarding does not take
4252 // place. Vectorizing in such cases does not make sense.
4253 // Store-load forwarding distance.
4254 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4255 // Maximum vector factor.
4256 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4257 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4258 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4260 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4262 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4263 MaxVFWithoutSLForwardIssues = (vf >>=1);
4268 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4269 DEBUG(dbgs() << "LV: Distance " << Distance <<
4270 " that could cause a store-load forwarding conflict\n");
4274 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4275 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4276 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4280 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4281 const MemAccessInfo &B, unsigned BIdx,
4282 ValueToValueMap &Strides) {
4283 assert (AIdx < BIdx && "Must pass arguments in program order");
4285 Value *APtr = A.getPointer();
4286 Value *BPtr = B.getPointer();
4287 bool AIsWrite = A.getInt();
4288 bool BIsWrite = B.getInt();
4290 // Two reads are independent.
4291 if (!AIsWrite && !BIsWrite)
4294 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4295 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4297 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4298 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4300 const SCEV *Src = AScev;
4301 const SCEV *Sink = BScev;
4303 // If the induction step is negative we have to invert source and sink of the
4305 if (StrideAPtr < 0) {
4308 std::swap(APtr, BPtr);
4309 std::swap(Src, Sink);
4310 std::swap(AIsWrite, BIsWrite);
4311 std::swap(AIdx, BIdx);
4312 std::swap(StrideAPtr, StrideBPtr);
4315 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4317 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4318 << "(Induction step: " << StrideAPtr << ")\n");
4319 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4320 << *InstMap[BIdx] << ": " << *Dist << "\n");
4322 // Need consecutive accesses. We don't want to vectorize
4323 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4324 // the address space.
4325 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4326 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4330 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4332 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4333 ShouldRetryWithRuntimeCheck = true;
4337 Type *ATy = APtr->getType()->getPointerElementType();
4338 Type *BTy = BPtr->getType()->getPointerElementType();
4339 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4341 // Negative distances are not plausible dependencies.
4342 const APInt &Val = C->getValue()->getValue();
4343 if (Val.isNegative()) {
4344 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4345 if (IsTrueDataDependence &&
4346 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4350 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4354 // Write to the same location with the same size.
4355 // Could be improved to assert type sizes are the same (i32 == float, etc).
4359 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4363 assert(Val.isStrictlyPositive() && "Expect a positive value");
4365 // Positive distance bigger than max vectorization factor.
4368 "LV: ReadWrite-Write positive dependency with different types\n");
4372 unsigned Distance = (unsigned) Val.getZExtValue();
4374 // Bail out early if passed-in parameters make vectorization not feasible.
4375 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4376 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4378 // The distance must be bigger than the size needed for a vectorized version
4379 // of the operation and the size of the vectorized operation must not be
4380 // bigger than the currrent maximum size.
4381 if (Distance < 2*TypeByteSize ||
4382 2*TypeByteSize > MaxSafeDepDistBytes ||
4383 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4384 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4385 << Val.getSExtValue() << '\n');
4389 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4390 Distance : MaxSafeDepDistBytes;
4392 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4393 if (IsTrueDataDependence &&
4394 couldPreventStoreLoadForward(Distance, TypeByteSize))
4397 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4398 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4403 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4404 MemAccessInfoSet &CheckDeps,
4405 ValueToValueMap &Strides) {
4407 MaxSafeDepDistBytes = -1U;
4408 while (!CheckDeps.empty()) {
4409 MemAccessInfo CurAccess = *CheckDeps.begin();
4411 // Get the relevant memory access set.
4412 EquivalenceClasses<MemAccessInfo>::iterator I =
4413 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4415 // Check accesses within this set.
4416 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4417 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4419 // Check every access pair.
4421 CheckDeps.erase(*AI);
4422 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4424 // Check every accessing instruction pair in program order.
4425 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4426 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4427 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4428 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4429 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4431 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4442 bool LoopVectorizationLegality::canVectorizeMemory() {
4444 typedef SmallVector<Value*, 16> ValueVector;
4445 typedef SmallPtrSet<Value*, 16> ValueSet;
4447 // Holds the Load and Store *instructions*.
4451 // Holds all the different accesses in the loop.
4452 unsigned NumReads = 0;
4453 unsigned NumReadWrites = 0;
4455 PtrRtCheck.Pointers.clear();
4456 PtrRtCheck.Need = false;
4458 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4459 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4462 for (Loop::block_iterator bb = TheLoop->block_begin(),
4463 be = TheLoop->block_end(); bb != be; ++bb) {
4465 // Scan the BB and collect legal loads and stores.
4466 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4469 // If this is a load, save it. If this instruction can read from memory
4470 // but is not a load, then we quit. Notice that we don't handle function
4471 // calls that read or write.
4472 if (it->mayReadFromMemory()) {
4473 // Many math library functions read the rounding mode. We will only
4474 // vectorize a loop if it contains known function calls that don't set
4475 // the flag. Therefore, it is safe to ignore this read from memory.
4476 CallInst *Call = dyn_cast<CallInst>(it);
4477 if (Call && getIntrinsicIDForCall(Call, TLI))
4480 LoadInst *Ld = dyn_cast<LoadInst>(it);
4481 if (!Ld) return false;
4482 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4483 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4487 Loads.push_back(Ld);
4488 DepChecker.addAccess(Ld);
4492 // Save 'store' instructions. Abort if other instructions write to memory.
4493 if (it->mayWriteToMemory()) {
4494 StoreInst *St = dyn_cast<StoreInst>(it);
4495 if (!St) return false;
4496 if (!St->isSimple() && !IsAnnotatedParallel) {
4497 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4501 Stores.push_back(St);
4502 DepChecker.addAccess(St);
4507 // Now we have two lists that hold the loads and the stores.
4508 // Next, we find the pointers that they use.
4510 // Check if we see any stores. If there are no stores, then we don't
4511 // care if the pointers are *restrict*.
4512 if (!Stores.size()) {
4513 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4517 AccessAnalysis::DepCandidates DependentAccesses;
4518 AccessAnalysis Accesses(DL, DependentAccesses);
4520 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4521 // multiple times on the same object. If the ptr is accessed twice, once
4522 // for read and once for write, it will only appear once (on the write
4523 // list). This is okay, since we are going to check for conflicts between
4524 // writes and between reads and writes, but not between reads and reads.
4527 ValueVector::iterator I, IE;
4528 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4529 StoreInst *ST = cast<StoreInst>(*I);
4530 Value* Ptr = ST->getPointerOperand();
4532 if (isUniform(Ptr)) {
4533 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4537 // If we did *not* see this pointer before, insert it to the read-write
4538 // list. At this phase it is only a 'write' list.
4539 if (Seen.insert(Ptr)) {
4541 Accesses.addStore(Ptr);
4545 if (IsAnnotatedParallel) {
4547 << "LV: A loop annotated parallel, ignore memory dependency "
4552 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4553 LoadInst *LD = cast<LoadInst>(*I);
4554 Value* Ptr = LD->getPointerOperand();
4555 // If we did *not* see this pointer before, insert it to the
4556 // read list. If we *did* see it before, then it is already in
4557 // the read-write list. This allows us to vectorize expressions
4558 // such as A[i] += x; Because the address of A[i] is a read-write
4559 // pointer. This only works if the index of A[i] is consecutive.
4560 // If the address of i is unknown (for example A[B[i]]) then we may
4561 // read a few words, modify, and write a few words, and some of the
4562 // words may be written to the same address.
4563 bool IsReadOnlyPtr = false;
4564 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4566 IsReadOnlyPtr = true;
4568 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4571 // If we write (or read-write) to a single destination and there are no
4572 // other reads in this loop then is it safe to vectorize.
4573 if (NumReadWrites == 1 && NumReads == 0) {
4574 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4578 // Build dependence sets and check whether we need a runtime pointer bounds
4580 Accesses.buildDependenceSets();
4581 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4583 // Find pointers with computable bounds. We are going to use this information
4584 // to place a runtime bound check.
4585 unsigned NumComparisons = 0;
4586 bool CanDoRT = false;
4588 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4591 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4592 " pointer comparisons.\n");
4594 // If we only have one set of dependences to check pointers among we don't
4595 // need a runtime check.
4596 if (NumComparisons == 0 && NeedRTCheck)
4597 NeedRTCheck = false;
4599 // Check that we did not collect too many pointers or found an unsizeable
4601 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4607 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4610 if (NeedRTCheck && !CanDoRT) {
4611 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4612 "the array bounds.\n");
4617 PtrRtCheck.Need = NeedRTCheck;
4619 bool CanVecMem = true;
4620 if (Accesses.isDependencyCheckNeeded()) {
4621 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4622 CanVecMem = DepChecker.areDepsSafe(
4623 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4624 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4626 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4627 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4630 // Clear the dependency checks. We assume they are not needed.
4631 Accesses.resetDepChecks();
4634 PtrRtCheck.Need = true;
4636 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4637 TheLoop, Strides, true);
4638 // Check that we did not collect too many pointers or found an unsizeable
4640 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4641 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4650 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4651 " need a runtime memory check.\n");
4656 static bool hasMultipleUsesOf(Instruction *I,
4657 SmallPtrSet<Instruction *, 8> &Insts) {
4658 unsigned NumUses = 0;
4659 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4660 if (Insts.count(dyn_cast<Instruction>(*Use)))
4669 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4670 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4671 if (!Set.count(dyn_cast<Instruction>(*Use)))
4676 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4677 ReductionKind Kind) {
4678 if (Phi->getNumIncomingValues() != 2)
4681 // Reduction variables are only found in the loop header block.
4682 if (Phi->getParent() != TheLoop->getHeader())
4685 // Obtain the reduction start value from the value that comes from the loop
4687 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4689 // ExitInstruction is the single value which is used outside the loop.
4690 // We only allow for a single reduction value to be used outside the loop.
4691 // This includes users of the reduction, variables (which form a cycle
4692 // which ends in the phi node).
4693 Instruction *ExitInstruction = nullptr;
4694 // Indicates that we found a reduction operation in our scan.
4695 bool FoundReduxOp = false;
4697 // We start with the PHI node and scan for all of the users of this
4698 // instruction. All users must be instructions that can be used as reduction
4699 // variables (such as ADD). We must have a single out-of-block user. The cycle
4700 // must include the original PHI.
4701 bool FoundStartPHI = false;
4703 // To recognize min/max patterns formed by a icmp select sequence, we store
4704 // the number of instruction we saw from the recognized min/max pattern,
4705 // to make sure we only see exactly the two instructions.
4706 unsigned NumCmpSelectPatternInst = 0;
4707 ReductionInstDesc ReduxDesc(false, nullptr);
4709 SmallPtrSet<Instruction *, 8> VisitedInsts;
4710 SmallVector<Instruction *, 8> Worklist;
4711 Worklist.push_back(Phi);
4712 VisitedInsts.insert(Phi);
4714 // A value in the reduction can be used:
4715 // - By the reduction:
4716 // - Reduction operation:
4717 // - One use of reduction value (safe).
4718 // - Multiple use of reduction value (not safe).
4720 // - All uses of the PHI must be the reduction (safe).
4721 // - Otherwise, not safe.
4722 // - By one instruction outside of the loop (safe).
4723 // - By further instructions outside of the loop (not safe).
4724 // - By an instruction that is not part of the reduction (not safe).
4726 // * An instruction type other than PHI or the reduction operation.
4727 // * A PHI in the header other than the initial PHI.
4728 while (!Worklist.empty()) {
4729 Instruction *Cur = Worklist.back();
4730 Worklist.pop_back();
4733 // If the instruction has no users then this is a broken chain and can't be
4734 // a reduction variable.
4735 if (Cur->use_empty())
4738 bool IsAPhi = isa<PHINode>(Cur);
4740 // A header PHI use other than the original PHI.
4741 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4744 // Reductions of instructions such as Div, and Sub is only possible if the
4745 // LHS is the reduction variable.
4746 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4747 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4748 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4751 // Any reduction instruction must be of one of the allowed kinds.
4752 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4753 if (!ReduxDesc.IsReduction)
4756 // A reduction operation must only have one use of the reduction value.
4757 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4758 hasMultipleUsesOf(Cur, VisitedInsts))
4761 // All inputs to a PHI node must be a reduction value.
4762 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4765 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4766 isa<SelectInst>(Cur)))
4767 ++NumCmpSelectPatternInst;
4768 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4769 isa<SelectInst>(Cur)))
4770 ++NumCmpSelectPatternInst;
4772 // Check whether we found a reduction operator.
4773 FoundReduxOp |= !IsAPhi;
4775 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4776 // onto the stack. This way we are going to have seen all inputs to PHI
4777 // nodes once we get to them.
4778 SmallVector<Instruction *, 8> NonPHIs;
4779 SmallVector<Instruction *, 8> PHIs;
4780 for (User *U : Cur->users()) {
4781 Instruction *UI = cast<Instruction>(U);
4783 // Check if we found the exit user.
4784 BasicBlock *Parent = UI->getParent();
4785 if (!TheLoop->contains(Parent)) {
4786 // Exit if you find multiple outside users or if the header phi node is
4787 // being used. In this case the user uses the value of the previous
4788 // iteration, in which case we would loose "VF-1" iterations of the
4789 // reduction operation if we vectorize.
4790 if (ExitInstruction != nullptr || Cur == Phi)
4793 // The instruction used by an outside user must be the last instruction
4794 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4795 // operations on the value.
4796 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4799 ExitInstruction = Cur;
4803 // Process instructions only once (termination). Each reduction cycle
4804 // value must only be used once, except by phi nodes and min/max
4805 // reductions which are represented as a cmp followed by a select.
4806 ReductionInstDesc IgnoredVal(false, nullptr);
4807 if (VisitedInsts.insert(UI)) {
4808 if (isa<PHINode>(UI))
4811 NonPHIs.push_back(UI);
4812 } else if (!isa<PHINode>(UI) &&
4813 ((!isa<FCmpInst>(UI) &&
4814 !isa<ICmpInst>(UI) &&
4815 !isa<SelectInst>(UI)) ||
4816 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4819 // Remember that we completed the cycle.
4821 FoundStartPHI = true;
4823 Worklist.append(PHIs.begin(), PHIs.end());
4824 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4827 // This means we have seen one but not the other instruction of the
4828 // pattern or more than just a select and cmp.
4829 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4830 NumCmpSelectPatternInst != 2)
4833 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4836 // We found a reduction var if we have reached the original phi node and we
4837 // only have a single instruction with out-of-loop users.
4839 // This instruction is allowed to have out-of-loop users.
4840 AllowedExit.insert(ExitInstruction);
4842 // Save the description of this reduction variable.
4843 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4844 ReduxDesc.MinMaxKind);
4845 Reductions[Phi] = RD;
4846 // We've ended the cycle. This is a reduction variable if we have an
4847 // outside user and it has a binary op.
4852 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4853 /// pattern corresponding to a min(X, Y) or max(X, Y).
4854 LoopVectorizationLegality::ReductionInstDesc
4855 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4856 ReductionInstDesc &Prev) {
4858 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4859 "Expect a select instruction");
4860 Instruction *Cmp = nullptr;
4861 SelectInst *Select = nullptr;
4863 // We must handle the select(cmp()) as a single instruction. Advance to the
4865 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4866 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4867 return ReductionInstDesc(false, I);
4868 return ReductionInstDesc(Select, Prev.MinMaxKind);
4871 // Only handle single use cases for now.
4872 if (!(Select = dyn_cast<SelectInst>(I)))
4873 return ReductionInstDesc(false, I);
4874 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4875 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4876 return ReductionInstDesc(false, I);
4877 if (!Cmp->hasOneUse())
4878 return ReductionInstDesc(false, I);
4883 // Look for a min/max pattern.
4884 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4885 return ReductionInstDesc(Select, MRK_UIntMin);
4886 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4887 return ReductionInstDesc(Select, MRK_UIntMax);
4888 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4889 return ReductionInstDesc(Select, MRK_SIntMax);
4890 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4891 return ReductionInstDesc(Select, MRK_SIntMin);
4892 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4893 return ReductionInstDesc(Select, MRK_FloatMin);
4894 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4895 return ReductionInstDesc(Select, MRK_FloatMax);
4896 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4897 return ReductionInstDesc(Select, MRK_FloatMin);
4898 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4899 return ReductionInstDesc(Select, MRK_FloatMax);
4901 return ReductionInstDesc(false, I);
4904 LoopVectorizationLegality::ReductionInstDesc
4905 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4907 ReductionInstDesc &Prev) {
4908 bool FP = I->getType()->isFloatingPointTy();
4909 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4910 switch (I->getOpcode()) {
4912 return ReductionInstDesc(false, I);
4913 case Instruction::PHI:
4914 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4915 Kind != RK_FloatMinMax))
4916 return ReductionInstDesc(false, I);
4917 return ReductionInstDesc(I, Prev.MinMaxKind);
4918 case Instruction::Sub:
4919 case Instruction::Add:
4920 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4921 case Instruction::Mul:
4922 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4923 case Instruction::And:
4924 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4925 case Instruction::Or:
4926 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4927 case Instruction::Xor:
4928 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4929 case Instruction::FMul:
4930 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4931 case Instruction::FAdd:
4932 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4933 case Instruction::FCmp:
4934 case Instruction::ICmp:
4935 case Instruction::Select:
4936 if (Kind != RK_IntegerMinMax &&
4937 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4938 return ReductionInstDesc(false, I);
4939 return isMinMaxSelectCmpPattern(I, Prev);
4943 LoopVectorizationLegality::InductionKind
4944 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4945 Type *PhiTy = Phi->getType();
4946 // We only handle integer and pointer inductions variables.
4947 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4948 return IK_NoInduction;
4950 // Check that the PHI is consecutive.
4951 const SCEV *PhiScev = SE->getSCEV(Phi);
4952 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4954 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4955 return IK_NoInduction;
4957 const SCEV *Step = AR->getStepRecurrence(*SE);
4959 // Integer inductions need to have a stride of one.
4960 if (PhiTy->isIntegerTy()) {
4962 return IK_IntInduction;
4963 if (Step->isAllOnesValue())
4964 return IK_ReverseIntInduction;
4965 return IK_NoInduction;
4968 // Calculate the pointer stride and check if it is consecutive.
4969 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4971 return IK_NoInduction;
4973 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4974 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4975 if (C->getValue()->equalsInt(Size))
4976 return IK_PtrInduction;
4977 else if (C->getValue()->equalsInt(0 - Size))
4978 return IK_ReversePtrInduction;
4980 return IK_NoInduction;
4983 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4984 Value *In0 = const_cast<Value*>(V);
4985 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4989 return Inductions.count(PN);
4992 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4993 assert(TheLoop->contains(BB) && "Unknown block used");
4995 // Blocks that do not dominate the latch need predication.
4996 BasicBlock* Latch = TheLoop->getLoopLatch();
4997 return !DT->dominates(BB, Latch);
5000 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
5001 SmallPtrSet<Value *, 8>& SafePtrs) {
5002 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5003 // We might be able to hoist the load.
5004 if (it->mayReadFromMemory()) {
5005 LoadInst *LI = dyn_cast<LoadInst>(it);
5006 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
5010 // We don't predicate stores at the moment.
5011 if (it->mayWriteToMemory()) {
5012 StoreInst *SI = dyn_cast<StoreInst>(it);
5013 // We only support predication of stores in basic blocks with one
5015 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
5016 !SafePtrs.count(SI->getPointerOperand()) ||
5017 !SI->getParent()->getSinglePredecessor())
5023 // Check that we don't have a constant expression that can trap as operand.
5024 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
5026 if (Constant *C = dyn_cast<Constant>(*OI))
5031 // The instructions below can trap.
5032 switch (it->getOpcode()) {
5034 case Instruction::UDiv:
5035 case Instruction::SDiv:
5036 case Instruction::URem:
5037 case Instruction::SRem:
5045 LoopVectorizationCostModel::VectorizationFactor
5046 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
5048 bool ForceVectorization) {
5049 // Width 1 means no vectorize
5050 VectorizationFactor Factor = { 1U, 0U };
5051 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
5052 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
5056 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
5057 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5061 // Find the trip count.
5062 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
5063 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5065 unsigned WidestType = getWidestType();
5066 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5067 unsigned MaxSafeDepDist = -1U;
5068 if (Legal->getMaxSafeDepDistBytes() != -1U)
5069 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5070 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5071 WidestRegister : MaxSafeDepDist);
5072 unsigned MaxVectorSize = WidestRegister / WidestType;
5073 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5074 DEBUG(dbgs() << "LV: The Widest register is: "
5075 << WidestRegister << " bits.\n");
5077 if (MaxVectorSize == 0) {
5078 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5082 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
5083 " into one vector!");
5085 unsigned VF = MaxVectorSize;
5087 // If we optimize the program for size, avoid creating the tail loop.
5089 // If we are unable to calculate the trip count then don't try to vectorize.
5091 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5095 // Find the maximum SIMD width that can fit within the trip count.
5096 VF = TC % MaxVectorSize;
5101 // If the trip count that we found modulo the vectorization factor is not
5102 // zero then we require a tail.
5104 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5110 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5111 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5113 Factor.Width = UserVF;
5117 float Cost = expectedCost(1);
5119 const float ScalarCost = Cost;
5122 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5124 // Ignore scalar width, because the user explicitly wants vectorization.
5125 if (ForceVectorization && VF > 1) {
5127 Cost = expectedCost(Width) / (float)Width;
5130 for (unsigned i=2; i <= VF; i*=2) {
5131 // Notice that the vector loop needs to be executed less times, so
5132 // we need to divide the cost of the vector loops by the width of
5133 // the vector elements.
5134 float VectorCost = expectedCost(i) / (float)i;
5135 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5136 (int)VectorCost << ".\n");
5137 if (VectorCost < Cost) {
5143 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5144 << "LV: Vectorization seems to be not beneficial, "
5145 << "but was forced by a user.\n");
5146 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5147 Factor.Width = Width;
5148 Factor.Cost = Width * Cost;
5152 unsigned LoopVectorizationCostModel::getWidestType() {
5153 unsigned MaxWidth = 8;
5156 for (Loop::block_iterator bb = TheLoop->block_begin(),
5157 be = TheLoop->block_end(); bb != be; ++bb) {
5158 BasicBlock *BB = *bb;
5160 // For each instruction in the loop.
5161 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5162 Type *T = it->getType();
5164 // Only examine Loads, Stores and PHINodes.
5165 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5168 // Examine PHI nodes that are reduction variables.
5169 if (PHINode *PN = dyn_cast<PHINode>(it))
5170 if (!Legal->getReductionVars()->count(PN))
5173 // Examine the stored values.
5174 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5175 T = ST->getValueOperand()->getType();
5177 // Ignore loaded pointer types and stored pointer types that are not
5178 // consecutive. However, we do want to take consecutive stores/loads of
5179 // pointer vectors into account.
5180 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5183 MaxWidth = std::max(MaxWidth,
5184 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5192 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5195 unsigned LoopCost) {
5197 // -- The unroll heuristics --
5198 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5199 // There are many micro-architectural considerations that we can't predict
5200 // at this level. For example frontend pressure (on decode or fetch) due to
5201 // code size, or the number and capabilities of the execution ports.
5203 // We use the following heuristics to select the unroll factor:
5204 // 1. If the code has reductions the we unroll in order to break the cross
5205 // iteration dependency.
5206 // 2. If the loop is really small then we unroll in order to reduce the loop
5208 // 3. We don't unroll if we think that we will spill registers to memory due
5209 // to the increased register pressure.
5211 // Use the user preference, unless 'auto' is selected.
5215 // When we optimize for size we don't unroll.
5219 // We used the distance for the unroll factor.
5220 if (Legal->getMaxSafeDepDistBytes() != -1U)
5223 // Do not unroll loops with a relatively small trip count.
5224 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5225 TheLoop->getLoopLatch());
5226 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5229 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5230 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5234 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5235 TargetNumRegisters = ForceTargetNumScalarRegs;
5237 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5238 TargetNumRegisters = ForceTargetNumVectorRegs;
5241 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5242 // We divide by these constants so assume that we have at least one
5243 // instruction that uses at least one register.
5244 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5245 R.NumInstructions = std::max(R.NumInstructions, 1U);
5247 // We calculate the unroll factor using the following formula.
5248 // Subtract the number of loop invariants from the number of available
5249 // registers. These registers are used by all of the unrolled instances.
5250 // Next, divide the remaining registers by the number of registers that is
5251 // required by the loop, in order to estimate how many parallel instances
5252 // fit without causing spills. All of this is rounded down if necessary to be
5253 // a power of two. We want power of two unroll factors to simplify any
5254 // addressing operations or alignment considerations.
5255 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5258 // Don't count the induction variable as unrolled.
5259 if (EnableIndVarRegisterHeur)
5260 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5261 std::max(1U, (R.MaxLocalUsers - 1)));
5263 // Clamp the unroll factor ranges to reasonable factors.
5264 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5266 // Check if the user has overridden the unroll max.
5268 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5269 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5271 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5272 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5275 // If we did not calculate the cost for VF (because the user selected the VF)
5276 // then we calculate the cost of VF here.
5278 LoopCost = expectedCost(VF);
5280 // Clamp the calculated UF to be between the 1 and the max unroll factor
5281 // that the target allows.
5282 if (UF > MaxUnrollSize)
5287 // Unroll if we vectorized this loop and there is a reduction that could
5288 // benefit from unrolling.
5289 if (VF > 1 && Legal->getReductionVars()->size()) {
5290 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5294 // Note that if we've already vectorized the loop we will have done the
5295 // runtime check and so unrolling won't require further checks.
5296 bool UnrollingRequiresRuntimePointerCheck =
5297 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5299 // We want to unroll small loops in order to reduce the loop overhead and
5300 // potentially expose ILP opportunities.
5301 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5302 if (!UnrollingRequiresRuntimePointerCheck &&
5303 LoopCost < SmallLoopCost) {
5304 // We assume that the cost overhead is 1 and we use the cost model
5305 // to estimate the cost of the loop and unroll until the cost of the
5306 // loop overhead is about 5% of the cost of the loop.
5307 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5309 // Unroll until store/load ports (estimated by max unroll factor) are
5311 unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5312 unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5314 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5315 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5316 return std::max(StoresUF, LoadsUF);
5319 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5323 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5327 LoopVectorizationCostModel::RegisterUsage
5328 LoopVectorizationCostModel::calculateRegisterUsage() {
5329 // This function calculates the register usage by measuring the highest number
5330 // of values that are alive at a single location. Obviously, this is a very
5331 // rough estimation. We scan the loop in a topological order in order and
5332 // assign a number to each instruction. We use RPO to ensure that defs are
5333 // met before their users. We assume that each instruction that has in-loop
5334 // users starts an interval. We record every time that an in-loop value is
5335 // used, so we have a list of the first and last occurrences of each
5336 // instruction. Next, we transpose this data structure into a multi map that
5337 // holds the list of intervals that *end* at a specific location. This multi
5338 // map allows us to perform a linear search. We scan the instructions linearly
5339 // and record each time that a new interval starts, by placing it in a set.
5340 // If we find this value in the multi-map then we remove it from the set.
5341 // The max register usage is the maximum size of the set.
5342 // We also search for instructions that are defined outside the loop, but are
5343 // used inside the loop. We need this number separately from the max-interval
5344 // usage number because when we unroll, loop-invariant values do not take
5346 LoopBlocksDFS DFS(TheLoop);
5350 R.NumInstructions = 0;
5352 // Each 'key' in the map opens a new interval. The values
5353 // of the map are the index of the 'last seen' usage of the
5354 // instruction that is the key.
5355 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5356 // Maps instruction to its index.
5357 DenseMap<unsigned, Instruction*> IdxToInstr;
5358 // Marks the end of each interval.
5359 IntervalMap EndPoint;
5360 // Saves the list of instruction indices that are used in the loop.
5361 SmallSet<Instruction*, 8> Ends;
5362 // Saves the list of values that are used in the loop but are
5363 // defined outside the loop, such as arguments and constants.
5364 SmallPtrSet<Value*, 8> LoopInvariants;
5367 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5368 be = DFS.endRPO(); bb != be; ++bb) {
5369 R.NumInstructions += (*bb)->size();
5370 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5372 Instruction *I = it;
5373 IdxToInstr[Index++] = I;
5375 // Save the end location of each USE.
5376 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5377 Value *U = I->getOperand(i);
5378 Instruction *Instr = dyn_cast<Instruction>(U);
5380 // Ignore non-instruction values such as arguments, constants, etc.
5381 if (!Instr) continue;
5383 // If this instruction is outside the loop then record it and continue.
5384 if (!TheLoop->contains(Instr)) {
5385 LoopInvariants.insert(Instr);
5389 // Overwrite previous end points.
5390 EndPoint[Instr] = Index;
5396 // Saves the list of intervals that end with the index in 'key'.
5397 typedef SmallVector<Instruction*, 2> InstrList;
5398 DenseMap<unsigned, InstrList> TransposeEnds;
5400 // Transpose the EndPoints to a list of values that end at each index.
5401 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5403 TransposeEnds[it->second].push_back(it->first);
5405 SmallSet<Instruction*, 8> OpenIntervals;
5406 unsigned MaxUsage = 0;
5409 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5410 for (unsigned int i = 0; i < Index; ++i) {
5411 Instruction *I = IdxToInstr[i];
5412 // Ignore instructions that are never used within the loop.
5413 if (!Ends.count(I)) continue;
5415 // Remove all of the instructions that end at this location.
5416 InstrList &List = TransposeEnds[i];
5417 for (unsigned int j=0, e = List.size(); j < e; ++j)
5418 OpenIntervals.erase(List[j]);
5420 // Count the number of live interals.
5421 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5423 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5424 OpenIntervals.size() << '\n');
5426 // Add the current instruction to the list of open intervals.
5427 OpenIntervals.insert(I);
5430 unsigned Invariant = LoopInvariants.size();
5431 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5432 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5433 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5435 R.LoopInvariantRegs = Invariant;
5436 R.MaxLocalUsers = MaxUsage;
5440 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5444 for (Loop::block_iterator bb = TheLoop->block_begin(),
5445 be = TheLoop->block_end(); bb != be; ++bb) {
5446 unsigned BlockCost = 0;
5447 BasicBlock *BB = *bb;
5449 // For each instruction in the old loop.
5450 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5451 // Skip dbg intrinsics.
5452 if (isa<DbgInfoIntrinsic>(it))
5455 unsigned C = getInstructionCost(it, VF);
5457 // Check if we should override the cost.
5458 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5459 C = ForceTargetInstructionCost;
5462 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5463 VF << " For instruction: " << *it << '\n');
5466 // We assume that if-converted blocks have a 50% chance of being executed.
5467 // When the code is scalar then some of the blocks are avoided due to CF.
5468 // When the code is vectorized we execute all code paths.
5469 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5478 /// \brief Check whether the address computation for a non-consecutive memory
5479 /// access looks like an unlikely candidate for being merged into the indexing
5482 /// We look for a GEP which has one index that is an induction variable and all
5483 /// other indices are loop invariant. If the stride of this access is also
5484 /// within a small bound we decide that this address computation can likely be
5485 /// merged into the addressing mode.
5486 /// In all other cases, we identify the address computation as complex.
5487 static bool isLikelyComplexAddressComputation(Value *Ptr,
5488 LoopVectorizationLegality *Legal,
5489 ScalarEvolution *SE,
5490 const Loop *TheLoop) {
5491 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5495 // We are looking for a gep with all loop invariant indices except for one
5496 // which should be an induction variable.
5497 unsigned NumOperands = Gep->getNumOperands();
5498 for (unsigned i = 1; i < NumOperands; ++i) {
5499 Value *Opd = Gep->getOperand(i);
5500 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5501 !Legal->isInductionVariable(Opd))
5505 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5506 // can likely be merged into the address computation.
5507 unsigned MaxMergeDistance = 64;
5509 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5513 // Check the step is constant.
5514 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5515 // Calculate the pointer stride and check if it is consecutive.
5516 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5520 const APInt &APStepVal = C->getValue()->getValue();
5522 // Huge step value - give up.
5523 if (APStepVal.getBitWidth() > 64)
5526 int64_t StepVal = APStepVal.getSExtValue();
5528 return StepVal > MaxMergeDistance;
5531 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5532 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5538 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5539 // If we know that this instruction will remain uniform, check the cost of
5540 // the scalar version.
5541 if (Legal->isUniformAfterVectorization(I))
5544 Type *RetTy = I->getType();
5545 Type *VectorTy = ToVectorTy(RetTy, VF);
5547 // TODO: We need to estimate the cost of intrinsic calls.
5548 switch (I->getOpcode()) {
5549 case Instruction::GetElementPtr:
5550 // We mark this instruction as zero-cost because the cost of GEPs in
5551 // vectorized code depends on whether the corresponding memory instruction
5552 // is scalarized or not. Therefore, we handle GEPs with the memory
5553 // instruction cost.
5555 case Instruction::Br: {
5556 return TTI.getCFInstrCost(I->getOpcode());
5558 case Instruction::PHI:
5559 //TODO: IF-converted IFs become selects.
5561 case Instruction::Add:
5562 case Instruction::FAdd:
5563 case Instruction::Sub:
5564 case Instruction::FSub:
5565 case Instruction::Mul:
5566 case Instruction::FMul:
5567 case Instruction::UDiv:
5568 case Instruction::SDiv:
5569 case Instruction::FDiv:
5570 case Instruction::URem:
5571 case Instruction::SRem:
5572 case Instruction::FRem:
5573 case Instruction::Shl:
5574 case Instruction::LShr:
5575 case Instruction::AShr:
5576 case Instruction::And:
5577 case Instruction::Or:
5578 case Instruction::Xor: {
5579 // Since we will replace the stride by 1 the multiplication should go away.
5580 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5582 // Certain instructions can be cheaper to vectorize if they have a constant
5583 // second vector operand. One example of this are shifts on x86.
5584 TargetTransformInfo::OperandValueKind Op1VK =
5585 TargetTransformInfo::OK_AnyValue;
5586 TargetTransformInfo::OperandValueKind Op2VK =
5587 TargetTransformInfo::OK_AnyValue;
5588 Value *Op2 = I->getOperand(1);
5590 // Check for a splat of a constant or for a non uniform vector of constants.
5591 if (isa<ConstantInt>(Op2))
5592 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5593 else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5594 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5595 if (cast<Constant>(Op2)->getSplatValue() != nullptr)
5596 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5599 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5601 case Instruction::Select: {
5602 SelectInst *SI = cast<SelectInst>(I);
5603 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5604 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5605 Type *CondTy = SI->getCondition()->getType();
5607 CondTy = VectorType::get(CondTy, VF);
5609 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5611 case Instruction::ICmp:
5612 case Instruction::FCmp: {
5613 Type *ValTy = I->getOperand(0)->getType();
5614 VectorTy = ToVectorTy(ValTy, VF);
5615 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5617 case Instruction::Store:
5618 case Instruction::Load: {
5619 StoreInst *SI = dyn_cast<StoreInst>(I);
5620 LoadInst *LI = dyn_cast<LoadInst>(I);
5621 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5623 VectorTy = ToVectorTy(ValTy, VF);
5625 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5626 unsigned AS = SI ? SI->getPointerAddressSpace() :
5627 LI->getPointerAddressSpace();
5628 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5629 // We add the cost of address computation here instead of with the gep
5630 // instruction because only here we know whether the operation is
5633 return TTI.getAddressComputationCost(VectorTy) +
5634 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5636 // Scalarized loads/stores.
5637 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5638 bool Reverse = ConsecutiveStride < 0;
5639 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5640 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5641 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5642 bool IsComplexComputation =
5643 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5645 // The cost of extracting from the value vector and pointer vector.
5646 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5647 for (unsigned i = 0; i < VF; ++i) {
5648 // The cost of extracting the pointer operand.
5649 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5650 // In case of STORE, the cost of ExtractElement from the vector.
5651 // In case of LOAD, the cost of InsertElement into the returned
5653 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5654 Instruction::InsertElement,
5658 // The cost of the scalar loads/stores.
5659 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5660 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5665 // Wide load/stores.
5666 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5667 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5670 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5674 case Instruction::ZExt:
5675 case Instruction::SExt:
5676 case Instruction::FPToUI:
5677 case Instruction::FPToSI:
5678 case Instruction::FPExt:
5679 case Instruction::PtrToInt:
5680 case Instruction::IntToPtr:
5681 case Instruction::SIToFP:
5682 case Instruction::UIToFP:
5683 case Instruction::Trunc:
5684 case Instruction::FPTrunc:
5685 case Instruction::BitCast: {
5686 // We optimize the truncation of induction variable.
5687 // The cost of these is the same as the scalar operation.
5688 if (I->getOpcode() == Instruction::Trunc &&
5689 Legal->isInductionVariable(I->getOperand(0)))
5690 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5691 I->getOperand(0)->getType());
5693 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5694 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5696 case Instruction::Call: {
5697 CallInst *CI = cast<CallInst>(I);
5698 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5699 assert(ID && "Not an intrinsic call!");
5700 Type *RetTy = ToVectorTy(CI->getType(), VF);
5701 SmallVector<Type*, 4> Tys;
5702 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5703 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5704 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5707 // We are scalarizing the instruction. Return the cost of the scalar
5708 // instruction, plus the cost of insert and extract into vector
5709 // elements, times the vector width.
5712 if (!RetTy->isVoidTy() && VF != 1) {
5713 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5715 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5718 // The cost of inserting the results plus extracting each one of the
5720 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5723 // The cost of executing VF copies of the scalar instruction. This opcode
5724 // is unknown. Assume that it is the same as 'mul'.
5725 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5731 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5732 if (Scalar->isVoidTy() || VF == 1)
5734 return VectorType::get(Scalar, VF);
5737 char LoopVectorize::ID = 0;
5738 static const char lv_name[] = "Loop Vectorization";
5739 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5740 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5741 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5742 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5743 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5744 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5745 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5746 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5747 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5750 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5751 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5755 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5756 // Check for a store.
5757 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5758 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5760 // Check for a load.
5761 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5762 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5768 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5769 bool IfPredicateStore) {
5770 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5771 // Holds vector parameters or scalars, in case of uniform vals.
5772 SmallVector<VectorParts, 4> Params;
5774 setDebugLocFromInst(Builder, Instr);
5776 // Find all of the vectorized parameters.
5777 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5778 Value *SrcOp = Instr->getOperand(op);
5780 // If we are accessing the old induction variable, use the new one.
5781 if (SrcOp == OldInduction) {
5782 Params.push_back(getVectorValue(SrcOp));
5786 // Try using previously calculated values.
5787 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5789 // If the src is an instruction that appeared earlier in the basic block
5790 // then it should already be vectorized.
5791 if (SrcInst && OrigLoop->contains(SrcInst)) {
5792 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5793 // The parameter is a vector value from earlier.
5794 Params.push_back(WidenMap.get(SrcInst));
5796 // The parameter is a scalar from outside the loop. Maybe even a constant.
5797 VectorParts Scalars;
5798 Scalars.append(UF, SrcOp);
5799 Params.push_back(Scalars);
5803 assert(Params.size() == Instr->getNumOperands() &&
5804 "Invalid number of operands");
5806 // Does this instruction return a value ?
5807 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5809 Value *UndefVec = IsVoidRetTy ? nullptr :
5810 UndefValue::get(Instr->getType());
5811 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5812 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5814 Instruction *InsertPt = Builder.GetInsertPoint();
5815 BasicBlock *IfBlock = Builder.GetInsertBlock();
5816 BasicBlock *CondBlock = nullptr;
5819 Loop *VectorLp = nullptr;
5820 if (IfPredicateStore) {
5821 assert(Instr->getParent()->getSinglePredecessor() &&
5822 "Only support single predecessor blocks");
5823 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5824 Instr->getParent());
5825 VectorLp = LI->getLoopFor(IfBlock);
5826 assert(VectorLp && "Must have a loop for this block");
5829 // For each vector unroll 'part':
5830 for (unsigned Part = 0; Part < UF; ++Part) {
5831 // For each scalar that we create:
5833 // Start an "if (pred) a[i] = ..." block.
5834 Value *Cmp = nullptr;
5835 if (IfPredicateStore) {
5836 if (Cond[Part]->getType()->isVectorTy())
5838 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5839 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5840 ConstantInt::get(Cond[Part]->getType(), 1));
5841 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5842 LoopVectorBody.push_back(CondBlock);
5843 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
5844 // Update Builder with newly created basic block.
5845 Builder.SetInsertPoint(InsertPt);
5848 Instruction *Cloned = Instr->clone();
5850 Cloned->setName(Instr->getName() + ".cloned");
5851 // Replace the operands of the cloned instructions with extracted scalars.
5852 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5853 Value *Op = Params[op][Part];
5854 Cloned->setOperand(op, Op);
5857 // Place the cloned scalar in the new loop.
5858 Builder.Insert(Cloned);
5860 // If the original scalar returns a value we need to place it in a vector
5861 // so that future users will be able to use it.
5863 VecResults[Part] = Cloned;
5866 if (IfPredicateStore) {
5867 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5868 LoopVectorBody.push_back(NewIfBlock);
5869 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
5870 Builder.SetInsertPoint(InsertPt);
5871 Instruction *OldBr = IfBlock->getTerminator();
5872 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5873 OldBr->eraseFromParent();
5874 IfBlock = NewIfBlock;
5879 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5880 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5881 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5883 return scalarizeInstruction(Instr, IfPredicateStore);
5886 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5890 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5894 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5896 // When unrolling and the VF is 1, we only need to add a simple scalar.
5897 Type *ITy = Val->getType();
5898 assert(!ITy->isVectorTy() && "Val must be a scalar");
5899 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5900 return Builder.CreateAdd(Val, C, "induction");