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 // The interleaved access vectorization is based on the paper:
38 // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
41 // Other ideas/concepts are from:
42 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
44 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
45 // Vectorizing Compilers.
47 //===----------------------------------------------------------------------===//
49 #include "llvm/Transforms/Vectorize.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/EquivalenceClasses.h"
52 #include "llvm/ADT/Hashing.h"
53 #include "llvm/ADT/MapVector.h"
54 #include "llvm/ADT/SetVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/SmallSet.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/StringExtras.h"
60 #include "llvm/Analysis/AliasAnalysis.h"
61 #include "llvm/Analysis/BasicAliasAnalysis.h"
62 #include "llvm/Analysis/AliasSetTracker.h"
63 #include "llvm/Analysis/AssumptionCache.h"
64 #include "llvm/Analysis/BlockFrequencyInfo.h"
65 #include "llvm/Analysis/CodeMetrics.h"
66 #include "llvm/Analysis/GlobalsModRef.h"
67 #include "llvm/Analysis/LoopAccessAnalysis.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Analysis/LoopIterator.h"
70 #include "llvm/Analysis/LoopPass.h"
71 #include "llvm/Analysis/ScalarEvolution.h"
72 #include "llvm/Analysis/ScalarEvolutionExpander.h"
73 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
74 #include "llvm/Analysis/TargetTransformInfo.h"
75 #include "llvm/Analysis/ValueTracking.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfo.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/DiagnosticInfo.h"
81 #include "llvm/IR/Dominators.h"
82 #include "llvm/IR/Function.h"
83 #include "llvm/IR/IRBuilder.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Module.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/IR/ValueHandle.h"
92 #include "llvm/IR/Verifier.h"
93 #include "llvm/Pass.h"
94 #include "llvm/Support/BranchProbability.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/raw_ostream.h"
98 #include "llvm/Transforms/Scalar.h"
99 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
100 #include "llvm/Transforms/Utils/Local.h"
101 #include "llvm/Analysis/VectorUtils.h"
102 #include "llvm/Transforms/Utils/LoopUtils.h"
107 using namespace llvm;
108 using namespace llvm::PatternMatch;
110 #define LV_NAME "loop-vectorize"
111 #define DEBUG_TYPE LV_NAME
113 STATISTIC(LoopsVectorized, "Number of loops vectorized");
114 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
117 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
118 cl::desc("Enable if-conversion during vectorization."));
120 /// We don't vectorize loops with a known constant trip count below this number.
121 static cl::opt<unsigned>
122 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
124 cl::desc("Don't vectorize loops with a constant "
125 "trip count that is smaller than this "
128 /// This enables versioning on the strides of symbolically striding memory
129 /// accesses in code like the following.
130 /// for (i = 0; i < N; ++i)
131 /// A[i * Stride1] += B[i * Stride2] ...
133 /// Will be roughly translated to
134 /// if (Stride1 == 1 && Stride2 == 1) {
135 /// for (i = 0; i < N; i+=4)
139 static cl::opt<bool> EnableMemAccessVersioning(
140 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
141 cl::desc("Enable symblic stride memory access versioning"));
143 static cl::opt<bool> EnableInterleavedMemAccesses(
144 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
145 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
147 /// Maximum factor for an interleaved memory access.
148 static cl::opt<unsigned> MaxInterleaveGroupFactor(
149 "max-interleave-group-factor", cl::Hidden,
150 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
153 /// We don't interleave loops with a known constant trip count below this
155 static const unsigned TinyTripCountInterleaveThreshold = 128;
157 static cl::opt<unsigned> ForceTargetNumScalarRegs(
158 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
159 cl::desc("A flag that overrides the target's number of scalar registers."));
161 static cl::opt<unsigned> ForceTargetNumVectorRegs(
162 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
163 cl::desc("A flag that overrides the target's number of vector registers."));
165 /// Maximum vectorization interleave count.
166 static const unsigned MaxInterleaveFactor = 16;
168 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
169 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
170 cl::desc("A flag that overrides the target's max interleave factor for "
173 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
174 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
175 cl::desc("A flag that overrides the target's max interleave factor for "
176 "vectorized loops."));
178 static cl::opt<unsigned> ForceTargetInstructionCost(
179 "force-target-instruction-cost", cl::init(0), cl::Hidden,
180 cl::desc("A flag that overrides the target's expected cost for "
181 "an instruction to a single constant value. Mostly "
182 "useful for getting consistent testing."));
184 static cl::opt<unsigned> SmallLoopCost(
185 "small-loop-cost", cl::init(20), cl::Hidden,
187 "The cost of a loop that is considered 'small' by the interleaver."));
189 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
190 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
191 cl::desc("Enable the use of the block frequency analysis to access PGO "
192 "heuristics minimizing code growth in cold regions and being more "
193 "aggressive in hot regions."));
195 // Runtime interleave loops for load/store throughput.
196 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
197 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
199 "Enable runtime interleaving until load/store ports are saturated"));
201 /// The number of stores in a loop that are allowed to need predication.
202 static cl::opt<unsigned> NumberOfStoresToPredicate(
203 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
204 cl::desc("Max number of stores to be predicated behind an if."));
206 static cl::opt<bool> EnableIndVarRegisterHeur(
207 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
208 cl::desc("Count the induction variable only once when interleaving"));
210 static cl::opt<bool> EnableCondStoresVectorization(
211 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
212 cl::desc("Enable if predication of stores during vectorization."));
214 static cl::opt<unsigned> MaxNestedScalarReductionIC(
215 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
216 cl::desc("The maximum interleave count to use when interleaving a scalar "
217 "reduction in a nested loop."));
219 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
220 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
221 cl::desc("The maximum allowed number of runtime memory checks with a "
222 "vectorize(enable) pragma."));
226 // Forward declarations.
227 class LoopVectorizeHints;
228 class LoopVectorizationLegality;
229 class LoopVectorizationCostModel;
230 class LoopVectorizationRequirements;
232 /// \brief This modifies LoopAccessReport to initialize message with
233 /// loop-vectorizer-specific part.
234 class VectorizationReport : public LoopAccessReport {
236 VectorizationReport(Instruction *I = nullptr)
237 : LoopAccessReport("loop not vectorized: ", I) {}
239 /// \brief This allows promotion of the loop-access analysis report into the
240 /// loop-vectorizer report. It modifies the message to add the
241 /// loop-vectorizer-specific part of the message.
242 explicit VectorizationReport(const LoopAccessReport &R)
243 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
247 /// A helper function for converting Scalar types to vector types.
248 /// If the incoming type is void, we return void. If the VF is 1, we return
250 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
251 if (Scalar->isVoidTy() || VF == 1)
253 return VectorType::get(Scalar, VF);
256 /// InnerLoopVectorizer vectorizes loops which contain only one basic
257 /// block to a specified vectorization factor (VF).
258 /// This class performs the widening of scalars into vectors, or multiple
259 /// scalars. This class also implements the following features:
260 /// * It inserts an epilogue loop for handling loops that don't have iteration
261 /// counts that are known to be a multiple of the vectorization factor.
262 /// * It handles the code generation for reduction variables.
263 /// * Scalarization (implementation using scalars) of un-vectorizable
265 /// InnerLoopVectorizer does not perform any vectorization-legality
266 /// checks, and relies on the caller to check for the different legality
267 /// aspects. The InnerLoopVectorizer relies on the
268 /// LoopVectorizationLegality class to provide information about the induction
269 /// and reduction variables that were found to a given vectorization factor.
270 class InnerLoopVectorizer {
272 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
273 DominatorTree *DT, const TargetLibraryInfo *TLI,
274 const TargetTransformInfo *TTI, unsigned VecWidth,
275 unsigned UnrollFactor)
276 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
277 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
278 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
279 TripCount(nullptr), VectorTripCount(nullptr), Legal(nullptr),
280 AddedSafetyChecks(false) {}
282 // Perform the actual loop widening (vectorization).
283 void vectorize(LoopVectorizationLegality *L) {
285 // Create a new empty loop. Unlink the old loop and connect the new one.
287 // Widen each instruction in the old loop to a new one in the new loop.
288 // Use the Legality module to find the induction and reduction variables.
292 // Return true if any runtime check is added.
293 bool IsSafetyChecksAdded() {
294 return AddedSafetyChecks;
297 virtual ~InnerLoopVectorizer() {}
300 /// A small list of PHINodes.
301 typedef SmallVector<PHINode*, 4> PhiVector;
302 /// When we unroll loops we have multiple vector values for each scalar.
303 /// This data structure holds the unrolled and vectorized values that
304 /// originated from one scalar instruction.
305 typedef SmallVector<Value*, 2> VectorParts;
307 // When we if-convert we need to create edge masks. We have to cache values
308 // so that we don't end up with exponential recursion/IR.
309 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
310 VectorParts> EdgeMaskCache;
312 /// \brief Add checks for strides that were assumed to be 1.
314 /// Returns the last check instruction and the first check instruction in the
315 /// pair as (first, last).
316 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
318 /// Create an empty loop, based on the loop ranges of the old loop.
319 void createEmptyLoop();
320 /// Create a new induction variable inside L.
321 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
322 Value *Step, Instruction *DL);
323 /// Copy and widen the instructions from the old loop.
324 virtual void vectorizeLoop();
326 /// \brief The Loop exit block may have single value PHI nodes where the
327 /// incoming value is 'Undef'. While vectorizing we only handled real values
328 /// that were defined inside the loop. Here we fix the 'undef case'.
332 /// A helper function that computes the predicate of the block BB, assuming
333 /// that the header block of the loop is set to True. It returns the *entry*
334 /// mask for the block BB.
335 VectorParts createBlockInMask(BasicBlock *BB);
336 /// A helper function that computes the predicate of the edge between SRC
338 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
340 /// A helper function to vectorize a single BB within the innermost loop.
341 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
343 /// Vectorize a single PHINode in a block. This method handles the induction
344 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
345 /// arbitrary length vectors.
346 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
347 unsigned UF, unsigned VF, PhiVector *PV);
349 /// Insert the new loop to the loop hierarchy and pass manager
350 /// and update the analysis passes.
351 void updateAnalysis();
353 /// This instruction is un-vectorizable. Implement it as a sequence
354 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
355 /// scalarized instruction behind an if block predicated on the control
356 /// dependence of the instruction.
357 virtual void scalarizeInstruction(Instruction *Instr,
358 bool IfPredicateStore=false);
360 /// Vectorize Load and Store instructions,
361 virtual void vectorizeMemoryInstruction(Instruction *Instr);
363 /// Create a broadcast instruction. This method generates a broadcast
364 /// instruction (shuffle) for loop invariant values and for the induction
365 /// value. If this is the induction variable then we extend it to N, N+1, ...
366 /// this is needed because each iteration in the loop corresponds to a SIMD
368 virtual Value *getBroadcastInstrs(Value *V);
370 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
371 /// to each vector element of Val. The sequence starts at StartIndex.
372 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
374 /// When we go over instructions in the basic block we rely on previous
375 /// values within the current basic block or on loop invariant values.
376 /// When we widen (vectorize) values we place them in the map. If the values
377 /// are not within the map, they have to be loop invariant, so we simply
378 /// broadcast them into a vector.
379 VectorParts &getVectorValue(Value *V);
381 /// Try to vectorize the interleaved access group that \p Instr belongs to.
382 void vectorizeInterleaveGroup(Instruction *Instr);
384 /// Generate a shuffle sequence that will reverse the vector Vec.
385 virtual Value *reverseVector(Value *Vec);
387 /// Returns (and creates if needed) the original loop trip count.
388 Value *getOrCreateTripCount(Loop *NewLoop);
390 /// Returns (and creates if needed) the trip count of the widened loop.
391 Value *getOrCreateVectorTripCount(Loop *NewLoop);
393 /// Emit a bypass check to see if the trip count would overflow, or we
394 /// wouldn't have enough iterations to execute one vector loop.
395 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
396 /// Emit a bypass check to see if the vector trip count is nonzero.
397 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
398 /// Emit bypass checks to check if strides we've assumed to be one really are.
399 void emitStrideChecks(Loop *L, BasicBlock *Bypass);
400 /// Emit bypass checks to check any memory assumptions we may have made.
401 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
403 /// This is a helper class that holds the vectorizer state. It maps scalar
404 /// instructions to vector instructions. When the code is 'unrolled' then
405 /// then a single scalar value is mapped to multiple vector parts. The parts
406 /// are stored in the VectorPart type.
408 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
410 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
412 /// \return True if 'Key' is saved in the Value Map.
413 bool has(Value *Key) const { return MapStorage.count(Key); }
415 /// Initializes a new entry in the map. Sets all of the vector parts to the
416 /// save value in 'Val'.
417 /// \return A reference to a vector with splat values.
418 VectorParts &splat(Value *Key, Value *Val) {
419 VectorParts &Entry = MapStorage[Key];
420 Entry.assign(UF, Val);
424 ///\return A reference to the value that is stored at 'Key'.
425 VectorParts &get(Value *Key) {
426 VectorParts &Entry = MapStorage[Key];
429 assert(Entry.size() == UF);
434 /// The unroll factor. Each entry in the map stores this number of vector
438 /// Map storage. We use std::map and not DenseMap because insertions to a
439 /// dense map invalidates its iterators.
440 std::map<Value *, VectorParts> MapStorage;
443 /// The original loop.
445 /// Scev analysis to use.
453 /// Target Library Info.
454 const TargetLibraryInfo *TLI;
455 /// Target Transform Info.
456 const TargetTransformInfo *TTI;
458 /// The vectorization SIMD factor to use. Each vector will have this many
463 /// The vectorization unroll factor to use. Each scalar is vectorized to this
464 /// many different vector instructions.
467 /// The builder that we use
470 // --- Vectorization state ---
472 /// The vector-loop preheader.
473 BasicBlock *LoopVectorPreHeader;
474 /// The scalar-loop preheader.
475 BasicBlock *LoopScalarPreHeader;
476 /// Middle Block between the vector and the scalar.
477 BasicBlock *LoopMiddleBlock;
478 ///The ExitBlock of the scalar loop.
479 BasicBlock *LoopExitBlock;
480 ///The vector loop body.
481 SmallVector<BasicBlock *, 4> LoopVectorBody;
482 ///The scalar loop body.
483 BasicBlock *LoopScalarBody;
484 /// A list of all bypass blocks. The first block is the entry of the loop.
485 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
487 /// The new Induction variable which was added to the new block.
489 /// The induction variable of the old basic block.
490 PHINode *OldInduction;
491 /// Maps scalars to widened vectors.
493 /// Store instructions that should be predicated, as a pair
494 /// <StoreInst, Predicate>
495 SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
496 EdgeMaskCache MaskCache;
497 /// Trip count of the original loop.
499 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
500 Value *VectorTripCount;
502 LoopVectorizationLegality *Legal;
504 // Record whether runtime check is added.
505 bool AddedSafetyChecks;
508 class InnerLoopUnroller : public InnerLoopVectorizer {
510 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
511 DominatorTree *DT, const TargetLibraryInfo *TLI,
512 const TargetTransformInfo *TTI, unsigned UnrollFactor)
513 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
516 void scalarizeInstruction(Instruction *Instr,
517 bool IfPredicateStore = false) override;
518 void vectorizeMemoryInstruction(Instruction *Instr) override;
519 Value *getBroadcastInstrs(Value *V) override;
520 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
521 Value *reverseVector(Value *Vec) override;
524 /// \brief Look for a meaningful debug location on the instruction or it's
526 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
531 if (I->getDebugLoc() != Empty)
534 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
535 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
536 if (OpInst->getDebugLoc() != Empty)
543 /// \brief Set the debug location in the builder using the debug location in the
545 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
546 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
547 B.SetCurrentDebugLocation(Inst->getDebugLoc());
549 B.SetCurrentDebugLocation(DebugLoc());
553 /// \return string containing a file name and a line # for the given loop.
554 static std::string getDebugLocString(const Loop *L) {
557 raw_string_ostream OS(Result);
558 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
559 LoopDbgLoc.print(OS);
561 // Just print the module name.
562 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
569 /// \brief Propagate known metadata from one instruction to another.
570 static void propagateMetadata(Instruction *To, const Instruction *From) {
571 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
572 From->getAllMetadataOtherThanDebugLoc(Metadata);
574 for (auto M : Metadata) {
575 unsigned Kind = M.first;
577 // These are safe to transfer (this is safe for TBAA, even when we
578 // if-convert, because should that metadata have had a control dependency
579 // on the condition, and thus actually aliased with some other
580 // non-speculated memory access when the condition was false, this would be
581 // caught by the runtime overlap checks).
582 if (Kind != LLVMContext::MD_tbaa &&
583 Kind != LLVMContext::MD_alias_scope &&
584 Kind != LLVMContext::MD_noalias &&
585 Kind != LLVMContext::MD_fpmath &&
586 Kind != LLVMContext::MD_nontemporal)
589 To->setMetadata(Kind, M.second);
593 /// \brief Propagate known metadata from one instruction to a vector of others.
594 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
596 if (Instruction *I = dyn_cast<Instruction>(V))
597 propagateMetadata(I, From);
600 /// \brief The group of interleaved loads/stores sharing the same stride and
601 /// close to each other.
603 /// Each member in this group has an index starting from 0, and the largest
604 /// index should be less than interleaved factor, which is equal to the absolute
605 /// value of the access's stride.
607 /// E.g. An interleaved load group of factor 4:
608 /// for (unsigned i = 0; i < 1024; i+=4) {
609 /// a = A[i]; // Member of index 0
610 /// b = A[i+1]; // Member of index 1
611 /// d = A[i+3]; // Member of index 3
615 /// An interleaved store group of factor 4:
616 /// for (unsigned i = 0; i < 1024; i+=4) {
618 /// A[i] = a; // Member of index 0
619 /// A[i+1] = b; // Member of index 1
620 /// A[i+2] = c; // Member of index 2
621 /// A[i+3] = d; // Member of index 3
624 /// Note: the interleaved load group could have gaps (missing members), but
625 /// the interleaved store group doesn't allow gaps.
626 class InterleaveGroup {
628 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
629 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
630 assert(Align && "The alignment should be non-zero");
632 Factor = std::abs(Stride);
633 assert(Factor > 1 && "Invalid interleave factor");
635 Reverse = Stride < 0;
639 bool isReverse() const { return Reverse; }
640 unsigned getFactor() const { return Factor; }
641 unsigned getAlignment() const { return Align; }
642 unsigned getNumMembers() const { return Members.size(); }
644 /// \brief Try to insert a new member \p Instr with index \p Index and
645 /// alignment \p NewAlign. The index is related to the leader and it could be
646 /// negative if it is the new leader.
648 /// \returns false if the instruction doesn't belong to the group.
649 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
650 assert(NewAlign && "The new member's alignment should be non-zero");
652 int Key = Index + SmallestKey;
654 // Skip if there is already a member with the same index.
655 if (Members.count(Key))
658 if (Key > LargestKey) {
659 // The largest index is always less than the interleave factor.
660 if (Index >= static_cast<int>(Factor))
664 } else if (Key < SmallestKey) {
665 // The largest index is always less than the interleave factor.
666 if (LargestKey - Key >= static_cast<int>(Factor))
672 // It's always safe to select the minimum alignment.
673 Align = std::min(Align, NewAlign);
674 Members[Key] = Instr;
678 /// \brief Get the member with the given index \p Index
680 /// \returns nullptr if contains no such member.
681 Instruction *getMember(unsigned Index) const {
682 int Key = SmallestKey + Index;
683 if (!Members.count(Key))
686 return Members.find(Key)->second;
689 /// \brief Get the index for the given member. Unlike the key in the member
690 /// map, the index starts from 0.
691 unsigned getIndex(Instruction *Instr) const {
692 for (auto I : Members)
693 if (I.second == Instr)
694 return I.first - SmallestKey;
696 llvm_unreachable("InterleaveGroup contains no such member");
699 Instruction *getInsertPos() const { return InsertPos; }
700 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
703 unsigned Factor; // Interleave Factor.
706 DenseMap<int, Instruction *> Members;
710 // To avoid breaking dependences, vectorized instructions of an interleave
711 // group should be inserted at either the first load or the last store in
714 // E.g. %even = load i32 // Insert Position
715 // %add = add i32 %even // Use of %even
719 // %odd = add i32 // Def of %odd
720 // store i32 %odd // Insert Position
721 Instruction *InsertPos;
724 /// \brief Drive the analysis of interleaved memory accesses in the loop.
726 /// Use this class to analyze interleaved accesses only when we can vectorize
727 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
728 /// on interleaved accesses is unsafe.
730 /// The analysis collects interleave groups and records the relationships
731 /// between the member and the group in a map.
732 class InterleavedAccessInfo {
734 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
735 : SE(SE), TheLoop(L), DT(DT) {}
737 ~InterleavedAccessInfo() {
738 SmallSet<InterleaveGroup *, 4> DelSet;
739 // Avoid releasing a pointer twice.
740 for (auto &I : InterleaveGroupMap)
741 DelSet.insert(I.second);
742 for (auto *Ptr : DelSet)
746 /// \brief Analyze the interleaved accesses and collect them in interleave
747 /// groups. Substitute symbolic strides using \p Strides.
748 void analyzeInterleaving(const ValueToValueMap &Strides);
750 /// \brief Check if \p Instr belongs to any interleave group.
751 bool isInterleaved(Instruction *Instr) const {
752 return InterleaveGroupMap.count(Instr);
755 /// \brief Get the interleave group that \p Instr belongs to.
757 /// \returns nullptr if doesn't have such group.
758 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
759 if (InterleaveGroupMap.count(Instr))
760 return InterleaveGroupMap.find(Instr)->second;
769 /// Holds the relationships between the members and the interleave group.
770 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
772 /// \brief The descriptor for a strided memory access.
773 struct StrideDescriptor {
774 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
776 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
778 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
780 int Stride; // The access's stride. It is negative for a reverse access.
781 const SCEV *Scev; // The scalar expression of this access
782 unsigned Size; // The size of the memory object.
783 unsigned Align; // The alignment of this access.
786 /// \brief Create a new interleave group with the given instruction \p Instr,
787 /// stride \p Stride and alignment \p Align.
789 /// \returns the newly created interleave group.
790 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
792 assert(!InterleaveGroupMap.count(Instr) &&
793 "Already in an interleaved access group");
794 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
795 return InterleaveGroupMap[Instr];
798 /// \brief Release the group and remove all the relationships.
799 void releaseGroup(InterleaveGroup *Group) {
800 for (unsigned i = 0; i < Group->getFactor(); i++)
801 if (Instruction *Member = Group->getMember(i))
802 InterleaveGroupMap.erase(Member);
807 /// \brief Collect all the accesses with a constant stride in program order.
808 void collectConstStridedAccesses(
809 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
810 const ValueToValueMap &Strides);
813 /// Utility class for getting and setting loop vectorizer hints in the form
814 /// of loop metadata.
815 /// This class keeps a number of loop annotations locally (as member variables)
816 /// and can, upon request, write them back as metadata on the loop. It will
817 /// initially scan the loop for existing metadata, and will update the local
818 /// values based on information in the loop.
819 /// We cannot write all values to metadata, as the mere presence of some info,
820 /// for example 'force', means a decision has been made. So, we need to be
821 /// careful NOT to add them if the user hasn't specifically asked so.
822 class LoopVectorizeHints {
829 /// Hint - associates name and validation with the hint value.
832 unsigned Value; // This may have to change for non-numeric values.
835 Hint(const char * Name, unsigned Value, HintKind Kind)
836 : Name(Name), Value(Value), Kind(Kind) { }
838 bool validate(unsigned Val) {
841 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
843 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
851 /// Vectorization width.
853 /// Vectorization interleave factor.
855 /// Vectorization forced
858 /// Return the loop metadata prefix.
859 static StringRef Prefix() { return "llvm.loop."; }
863 FK_Undefined = -1, ///< Not selected.
864 FK_Disabled = 0, ///< Forcing disabled.
865 FK_Enabled = 1, ///< Forcing enabled.
868 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
869 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
871 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
872 Force("vectorize.enable", FK_Undefined, HK_FORCE),
874 // Populate values with existing loop metadata.
875 getHintsFromMetadata();
877 // force-vector-interleave overrides DisableInterleaving.
878 if (VectorizerParams::isInterleaveForced())
879 Interleave.Value = VectorizerParams::VectorizationInterleave;
881 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
882 << "LV: Interleaving disabled by the pass manager\n");
885 /// Mark the loop L as already vectorized by setting the width to 1.
886 void setAlreadyVectorized() {
887 Width.Value = Interleave.Value = 1;
888 Hint Hints[] = {Width, Interleave};
889 writeHintsToMetadata(Hints);
892 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
893 if (getForce() == LoopVectorizeHints::FK_Disabled) {
894 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
895 emitOptimizationRemarkAnalysis(F->getContext(),
896 vectorizeAnalysisPassName(), *F,
897 L->getStartLoc(), emitRemark());
901 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
902 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
903 emitOptimizationRemarkAnalysis(F->getContext(),
904 vectorizeAnalysisPassName(), *F,
905 L->getStartLoc(), emitRemark());
909 if (getWidth() == 1 && getInterleave() == 1) {
910 // FIXME: Add a separate metadata to indicate when the loop has already
911 // been vectorized instead of setting width and count to 1.
912 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
913 // FIXME: Add interleave.disable metadata. This will allow
914 // vectorize.disable to be used without disabling the pass and errors
915 // to differentiate between disabled vectorization and a width of 1.
916 emitOptimizationRemarkAnalysis(
917 F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
918 "loop not vectorized: vectorization and interleaving are explicitly "
919 "disabled, or vectorize width and interleave count are both set to "
927 /// Dumps all the hint information.
928 std::string emitRemark() const {
929 VectorizationReport R;
930 if (Force.Value == LoopVectorizeHints::FK_Disabled)
931 R << "vectorization is explicitly disabled";
933 R << "use -Rpass-analysis=loop-vectorize for more info";
934 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
936 if (Width.Value != 0)
937 R << ", Vector Width=" << Width.Value;
938 if (Interleave.Value != 0)
939 R << ", Interleave Count=" << Interleave.Value;
947 unsigned getWidth() const { return Width.Value; }
948 unsigned getInterleave() const { return Interleave.Value; }
949 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
950 const char *vectorizeAnalysisPassName() const {
951 // If hints are provided that don't disable vectorization use the
952 // AlwaysPrint pass name to force the frontend to print the diagnostic.
955 if (getForce() == LoopVectorizeHints::FK_Disabled)
957 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
959 return DiagnosticInfo::AlwaysPrint;
962 bool allowReordering() const {
963 // When enabling loop hints are provided we allow the vectorizer to change
964 // the order of operations that is given by the scalar loop. This is not
965 // enabled by default because can be unsafe or inefficient. For example,
966 // reordering floating-point operations will change the way round-off
967 // error accumulates in the loop.
968 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
972 /// Find hints specified in the loop metadata and update local values.
973 void getHintsFromMetadata() {
974 MDNode *LoopID = TheLoop->getLoopID();
978 // First operand should refer to the loop id itself.
979 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
980 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
982 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
983 const MDString *S = nullptr;
984 SmallVector<Metadata *, 4> Args;
986 // The expected hint is either a MDString or a MDNode with the first
987 // operand a MDString.
988 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
989 if (!MD || MD->getNumOperands() == 0)
991 S = dyn_cast<MDString>(MD->getOperand(0));
992 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
993 Args.push_back(MD->getOperand(i));
995 S = dyn_cast<MDString>(LoopID->getOperand(i));
996 assert(Args.size() == 0 && "too many arguments for MDString");
1002 // Check if the hint starts with the loop metadata prefix.
1003 StringRef Name = S->getString();
1004 if (Args.size() == 1)
1005 setHint(Name, Args[0]);
1009 /// Checks string hint with one operand and set value if valid.
1010 void setHint(StringRef Name, Metadata *Arg) {
1011 if (!Name.startswith(Prefix()))
1013 Name = Name.substr(Prefix().size(), StringRef::npos);
1015 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1017 unsigned Val = C->getZExtValue();
1019 Hint *Hints[] = {&Width, &Interleave, &Force};
1020 for (auto H : Hints) {
1021 if (Name == H->Name) {
1022 if (H->validate(Val))
1025 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1031 /// Create a new hint from name / value pair.
1032 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1033 LLVMContext &Context = TheLoop->getHeader()->getContext();
1034 Metadata *MDs[] = {MDString::get(Context, Name),
1035 ConstantAsMetadata::get(
1036 ConstantInt::get(Type::getInt32Ty(Context), V))};
1037 return MDNode::get(Context, MDs);
1040 /// Matches metadata with hint name.
1041 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1042 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1046 for (auto H : HintTypes)
1047 if (Name->getString().endswith(H.Name))
1052 /// Sets current hints into loop metadata, keeping other values intact.
1053 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1054 if (HintTypes.size() == 0)
1057 // Reserve the first element to LoopID (see below).
1058 SmallVector<Metadata *, 4> MDs(1);
1059 // If the loop already has metadata, then ignore the existing operands.
1060 MDNode *LoopID = TheLoop->getLoopID();
1062 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1063 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1064 // If node in update list, ignore old value.
1065 if (!matchesHintMetadataName(Node, HintTypes))
1066 MDs.push_back(Node);
1070 // Now, add the missing hints.
1071 for (auto H : HintTypes)
1072 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1074 // Replace current metadata node with new one.
1075 LLVMContext &Context = TheLoop->getHeader()->getContext();
1076 MDNode *NewLoopID = MDNode::get(Context, MDs);
1077 // Set operand 0 to refer to the loop id itself.
1078 NewLoopID->replaceOperandWith(0, NewLoopID);
1080 TheLoop->setLoopID(NewLoopID);
1083 /// The loop these hints belong to.
1084 const Loop *TheLoop;
1087 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1088 const LoopVectorizeHints &Hints,
1089 const LoopAccessReport &Message) {
1090 const char *Name = Hints.vectorizeAnalysisPassName();
1091 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1094 static void emitMissedWarning(Function *F, Loop *L,
1095 const LoopVectorizeHints &LH) {
1096 emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1099 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1100 if (LH.getWidth() != 1)
1101 emitLoopVectorizeWarning(
1102 F->getContext(), *F, L->getStartLoc(),
1103 "failed explicitly specified loop vectorization");
1104 else if (LH.getInterleave() != 1)
1105 emitLoopInterleaveWarning(
1106 F->getContext(), *F, L->getStartLoc(),
1107 "failed explicitly specified loop interleaving");
1111 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1112 /// to what vectorization factor.
1113 /// This class does not look at the profitability of vectorization, only the
1114 /// legality. This class has two main kinds of checks:
1115 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1116 /// will change the order of memory accesses in a way that will change the
1117 /// correctness of the program.
1118 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1119 /// checks for a number of different conditions, such as the availability of a
1120 /// single induction variable, that all types are supported and vectorize-able,
1121 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1122 /// This class is also used by InnerLoopVectorizer for identifying
1123 /// induction variable and the different reduction variables.
1124 class LoopVectorizationLegality {
1126 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1127 TargetLibraryInfo *TLI, AliasAnalysis *AA,
1128 Function *F, const TargetTransformInfo *TTI,
1129 LoopAccessAnalysis *LAA,
1130 LoopVectorizationRequirements *R,
1131 const LoopVectorizeHints *H)
1132 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
1133 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
1134 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
1135 Requirements(R), Hints(H) {}
1137 /// ReductionList contains the reduction descriptors for all
1138 /// of the reductions that were found in the loop.
1139 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1141 /// InductionList saves induction variables and maps them to the
1142 /// induction descriptor.
1143 typedef MapVector<PHINode*, InductionDescriptor> InductionList;
1145 /// Returns true if it is legal to vectorize this loop.
1146 /// This does not mean that it is profitable to vectorize this
1147 /// loop, only that it is legal to do so.
1148 bool canVectorize();
1150 /// Returns the Induction variable.
1151 PHINode *getInduction() { return Induction; }
1153 /// Returns the reduction variables found in the loop.
1154 ReductionList *getReductionVars() { return &Reductions; }
1156 /// Returns the induction variables found in the loop.
1157 InductionList *getInductionVars() { return &Inductions; }
1159 /// Returns the widest induction type.
1160 Type *getWidestInductionType() { return WidestIndTy; }
1162 /// Returns True if V is an induction variable in this loop.
1163 bool isInductionVariable(const Value *V);
1165 /// Return true if the block BB needs to be predicated in order for the loop
1166 /// to be vectorized.
1167 bool blockNeedsPredication(BasicBlock *BB);
1169 /// Check if this pointer is consecutive when vectorizing. This happens
1170 /// when the last index of the GEP is the induction variable, or that the
1171 /// pointer itself is an induction variable.
1172 /// This check allows us to vectorize A[idx] into a wide load/store.
1174 /// 0 - Stride is unknown or non-consecutive.
1175 /// 1 - Address is consecutive.
1176 /// -1 - Address is consecutive, and decreasing.
1177 int isConsecutivePtr(Value *Ptr);
1179 /// Returns true if the value V is uniform within the loop.
1180 bool isUniform(Value *V);
1182 /// Returns true if this instruction will remain scalar after vectorization.
1183 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
1185 /// Returns the information that we collected about runtime memory check.
1186 const RuntimePointerChecking *getRuntimePointerChecking() const {
1187 return LAI->getRuntimePointerChecking();
1190 const LoopAccessInfo *getLAI() const {
1194 /// \brief Check if \p Instr belongs to any interleaved access group.
1195 bool isAccessInterleaved(Instruction *Instr) {
1196 return InterleaveInfo.isInterleaved(Instr);
1199 /// \brief Get the interleaved access group that \p Instr belongs to.
1200 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1201 return InterleaveInfo.getInterleaveGroup(Instr);
1204 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1206 bool hasStride(Value *V) { return StrideSet.count(V); }
1207 bool mustCheckStrides() { return !StrideSet.empty(); }
1208 SmallPtrSet<Value *, 8>::iterator strides_begin() {
1209 return StrideSet.begin();
1211 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
1213 /// Returns true if the target machine supports masked store operation
1214 /// for the given \p DataType and kind of access to \p Ptr.
1215 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1216 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
1218 /// Returns true if the target machine supports masked load operation
1219 /// for the given \p DataType and kind of access to \p Ptr.
1220 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1221 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
1223 /// Returns true if vector representation of the instruction \p I
1225 bool isMaskRequired(const Instruction* I) {
1226 return (MaskedOp.count(I) != 0);
1228 unsigned getNumStores() const {
1229 return LAI->getNumStores();
1231 unsigned getNumLoads() const {
1232 return LAI->getNumLoads();
1234 unsigned getNumPredStores() const {
1235 return NumPredStores;
1238 /// Check if a single basic block loop is vectorizable.
1239 /// At this point we know that this is a loop with a constant trip count
1240 /// and we only need to check individual instructions.
1241 bool canVectorizeInstrs();
1243 /// When we vectorize loops we may change the order in which
1244 /// we read and write from memory. This method checks if it is
1245 /// legal to vectorize the code, considering only memory constrains.
1246 /// Returns true if the loop is vectorizable
1247 bool canVectorizeMemory();
1249 /// Return true if we can vectorize this loop using the IF-conversion
1251 bool canVectorizeWithIfConvert();
1253 /// Collect the variables that need to stay uniform after vectorization.
1254 void collectLoopUniforms();
1256 /// Return true if all of the instructions in the block can be speculatively
1257 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1258 /// and we know that we can read from them without segfault.
1259 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1261 /// \brief Collect memory access with loop invariant strides.
1263 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1265 void collectStridedAccess(Value *LoadOrStoreInst);
1267 /// Report an analysis message to assist the user in diagnosing loops that are
1268 /// not vectorized. These are handled as LoopAccessReport rather than
1269 /// VectorizationReport because the << operator of VectorizationReport returns
1270 /// LoopAccessReport.
1271 void emitAnalysis(const LoopAccessReport &Message) const {
1272 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1275 unsigned NumPredStores;
1277 /// The loop that we evaluate.
1280 ScalarEvolution *SE;
1281 /// Target Library Info.
1282 TargetLibraryInfo *TLI;
1284 Function *TheFunction;
1285 /// Target Transform Info
1286 const TargetTransformInfo *TTI;
1289 // LoopAccess analysis.
1290 LoopAccessAnalysis *LAA;
1291 // And the loop-accesses info corresponding to this loop. This pointer is
1292 // null until canVectorizeMemory sets it up.
1293 const LoopAccessInfo *LAI;
1295 /// The interleave access information contains groups of interleaved accesses
1296 /// with the same stride and close to each other.
1297 InterleavedAccessInfo InterleaveInfo;
1299 // --- vectorization state --- //
1301 /// Holds the integer induction variable. This is the counter of the
1304 /// Holds the reduction variables.
1305 ReductionList Reductions;
1306 /// Holds all of the induction variables that we found in the loop.
1307 /// Notice that inductions don't need to start at zero and that induction
1308 /// variables can be pointers.
1309 InductionList Inductions;
1310 /// Holds the widest induction type encountered.
1313 /// Allowed outside users. This holds the reduction
1314 /// vars which can be accessed from outside the loop.
1315 SmallPtrSet<Value*, 4> AllowedExit;
1316 /// This set holds the variables which are known to be uniform after
1318 SmallPtrSet<Instruction*, 4> Uniforms;
1320 /// Can we assume the absence of NaNs.
1321 bool HasFunNoNaNAttr;
1323 /// Vectorization requirements that will go through late-evaluation.
1324 LoopVectorizationRequirements *Requirements;
1326 /// Used to emit an analysis of any legality issues.
1327 const LoopVectorizeHints *Hints;
1329 ValueToValueMap Strides;
1330 SmallPtrSet<Value *, 8> StrideSet;
1332 /// While vectorizing these instructions we have to generate a
1333 /// call to the appropriate masked intrinsic
1334 SmallPtrSet<const Instruction*, 8> MaskedOp;
1337 /// LoopVectorizationCostModel - estimates the expected speedups due to
1339 /// In many cases vectorization is not profitable. This can happen because of
1340 /// a number of reasons. In this class we mainly attempt to predict the
1341 /// expected speedup/slowdowns due to the supported instruction set. We use the
1342 /// TargetTransformInfo to query the different backends for the cost of
1343 /// different operations.
1344 class LoopVectorizationCostModel {
1346 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1347 LoopVectorizationLegality *Legal,
1348 const TargetTransformInfo &TTI,
1349 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1350 const Function *F, const LoopVectorizeHints *Hints,
1351 SmallPtrSetImpl<const Value *> &ValuesToIgnore)
1352 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1353 TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
1355 /// Information about vectorization costs
1356 struct VectorizationFactor {
1357 unsigned Width; // Vector width with best cost
1358 unsigned Cost; // Cost of the loop with that width
1360 /// \return The most profitable vectorization factor and the cost of that VF.
1361 /// This method checks every power of two up to VF. If UserVF is not ZERO
1362 /// then this vectorization factor will be selected if vectorization is
1364 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1366 /// \return The size (in bits) of the widest type in the code that
1367 /// needs to be vectorized. We ignore values that remain scalar such as
1368 /// 64 bit loop indices.
1369 unsigned getWidestType();
1371 /// \return The desired interleave count.
1372 /// If interleave count has been specified by metadata it will be returned.
1373 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1374 /// are the selected vectorization factor and the cost of the selected VF.
1375 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1378 /// \return The most profitable unroll factor.
1379 /// This method finds the best unroll-factor based on register pressure and
1380 /// other parameters. VF and LoopCost are the selected vectorization factor
1381 /// and the cost of the selected VF.
1382 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1385 /// \brief A struct that represents some properties of the register usage
1387 struct RegisterUsage {
1388 /// Holds the number of loop invariant values that are used in the loop.
1389 unsigned LoopInvariantRegs;
1390 /// Holds the maximum number of concurrent live intervals in the loop.
1391 unsigned MaxLocalUsers;
1392 /// Holds the number of instructions in the loop.
1393 unsigned NumInstructions;
1396 /// \return information about the register usage of the loop.
1397 RegisterUsage calculateRegisterUsage();
1400 /// Returns the expected execution cost. The unit of the cost does
1401 /// not matter because we use the 'cost' units to compare different
1402 /// vector widths. The cost that is returned is *not* normalized by
1403 /// the factor width.
1404 unsigned expectedCost(unsigned VF);
1406 /// Returns the execution time cost of an instruction for a given vector
1407 /// width. Vector width of one means scalar.
1408 unsigned getInstructionCost(Instruction *I, unsigned VF);
1410 /// Returns whether the instruction is a load or store and will be a emitted
1411 /// as a vector operation.
1412 bool isConsecutiveLoadOrStore(Instruction *I);
1414 /// Report an analysis message to assist the user in diagnosing loops that are
1415 /// not vectorized. These are handled as LoopAccessReport rather than
1416 /// VectorizationReport because the << operator of VectorizationReport returns
1417 /// LoopAccessReport.
1418 void emitAnalysis(const LoopAccessReport &Message) const {
1419 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1422 /// The loop that we evaluate.
1425 ScalarEvolution *SE;
1426 /// Loop Info analysis.
1428 /// Vectorization legality.
1429 LoopVectorizationLegality *Legal;
1430 /// Vector target information.
1431 const TargetTransformInfo &TTI;
1432 /// Target Library Info.
1433 const TargetLibraryInfo *TLI;
1434 const Function *TheFunction;
1435 // Loop Vectorize Hint.
1436 const LoopVectorizeHints *Hints;
1437 // Values to ignore in the cost model.
1438 const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
1441 /// \brief This holds vectorization requirements that must be verified late in
1442 /// the process. The requirements are set by legalize and costmodel. Once
1443 /// vectorization has been determined to be possible and profitable the
1444 /// requirements can be verified by looking for metadata or compiler options.
1445 /// For example, some loops require FP commutativity which is only allowed if
1446 /// vectorization is explicitly specified or if the fast-math compiler option
1447 /// has been provided.
1448 /// Late evaluation of these requirements allows helpful diagnostics to be
1449 /// composed that tells the user what need to be done to vectorize the loop. For
1450 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1451 /// evaluation should be used only when diagnostics can generated that can be
1452 /// followed by a non-expert user.
1453 class LoopVectorizationRequirements {
1455 LoopVectorizationRequirements()
1456 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1458 void addUnsafeAlgebraInst(Instruction *I) {
1459 // First unsafe algebra instruction.
1460 if (!UnsafeAlgebraInst)
1461 UnsafeAlgebraInst = I;
1464 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1466 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1467 const char *Name = Hints.vectorizeAnalysisPassName();
1468 bool Failed = false;
1469 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1470 emitOptimizationRemarkAnalysisFPCommute(
1471 F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1472 VectorizationReport() << "cannot prove it is safe to reorder "
1473 "floating-point operations");
1477 // Test if runtime memcheck thresholds are exceeded.
1478 bool PragmaThresholdReached =
1479 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1480 bool ThresholdReached =
1481 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1482 if ((ThresholdReached && !Hints.allowReordering()) ||
1483 PragmaThresholdReached) {
1484 emitOptimizationRemarkAnalysisAliasing(
1485 F->getContext(), Name, *F, L->getStartLoc(),
1486 VectorizationReport()
1487 << "cannot prove it is safe to reorder memory operations");
1488 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1496 unsigned NumRuntimePointerChecks;
1497 Instruction *UnsafeAlgebraInst;
1500 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1502 return V.push_back(&L);
1504 for (Loop *InnerL : L)
1505 addInnerLoop(*InnerL, V);
1508 /// The LoopVectorize Pass.
1509 struct LoopVectorize : public FunctionPass {
1510 /// Pass identification, replacement for typeid
1513 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1515 DisableUnrolling(NoUnrolling),
1516 AlwaysVectorize(AlwaysVectorize) {
1517 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1520 ScalarEvolution *SE;
1522 TargetTransformInfo *TTI;
1524 BlockFrequencyInfo *BFI;
1525 TargetLibraryInfo *TLI;
1527 AssumptionCache *AC;
1528 LoopAccessAnalysis *LAA;
1529 bool DisableUnrolling;
1530 bool AlwaysVectorize;
1532 BlockFrequency ColdEntryFreq;
1534 bool runOnFunction(Function &F) override {
1535 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1536 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1537 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1538 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1539 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1540 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1541 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1542 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1543 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1544 LAA = &getAnalysis<LoopAccessAnalysis>();
1546 // Compute some weights outside of the loop over the loops. Compute this
1547 // using a BranchProbability to re-use its scaling math.
1548 const BranchProbability ColdProb(1, 5); // 20%
1549 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1552 // 1. the target claims to have no vector registers, and
1553 // 2. interleaving won't help ILP.
1555 // The second condition is necessary because, even if the target has no
1556 // vector registers, loop vectorization may still enable scalar
1558 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1561 // Build up a worklist of inner-loops to vectorize. This is necessary as
1562 // the act of vectorizing or partially unrolling a loop creates new loops
1563 // and can invalidate iterators across the loops.
1564 SmallVector<Loop *, 8> Worklist;
1567 addInnerLoop(*L, Worklist);
1569 LoopsAnalyzed += Worklist.size();
1571 // Now walk the identified inner loops.
1572 bool Changed = false;
1573 while (!Worklist.empty())
1574 Changed |= processLoop(Worklist.pop_back_val());
1576 // Process each loop nest in the function.
1580 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1581 SmallVector<Metadata *, 4> MDs;
1582 // Reserve first location for self reference to the LoopID metadata node.
1583 MDs.push_back(nullptr);
1584 bool IsUnrollMetadata = false;
1585 MDNode *LoopID = L->getLoopID();
1587 // First find existing loop unrolling disable metadata.
1588 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1589 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1591 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1593 S && S->getString().startswith("llvm.loop.unroll.disable");
1595 MDs.push_back(LoopID->getOperand(i));
1599 if (!IsUnrollMetadata) {
1600 // Add runtime unroll disable metadata.
1601 LLVMContext &Context = L->getHeader()->getContext();
1602 SmallVector<Metadata *, 1> DisableOperands;
1603 DisableOperands.push_back(
1604 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1605 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1606 MDs.push_back(DisableNode);
1607 MDNode *NewLoopID = MDNode::get(Context, MDs);
1608 // Set operand 0 to refer to the loop id itself.
1609 NewLoopID->replaceOperandWith(0, NewLoopID);
1610 L->setLoopID(NewLoopID);
1614 bool processLoop(Loop *L) {
1615 assert(L->empty() && "Only process inner loops.");
1618 const std::string DebugLocStr = getDebugLocString(L);
1621 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1622 << L->getHeader()->getParent()->getName() << "\" from "
1623 << DebugLocStr << "\n");
1625 LoopVectorizeHints Hints(L, DisableUnrolling);
1627 DEBUG(dbgs() << "LV: Loop hints:"
1629 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1631 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1633 : "?")) << " width=" << Hints.getWidth()
1634 << " unroll=" << Hints.getInterleave() << "\n");
1636 // Function containing loop
1637 Function *F = L->getHeader()->getParent();
1639 // Looking at the diagnostic output is the only way to determine if a loop
1640 // was vectorized (other than looking at the IR or machine code), so it
1641 // is important to generate an optimization remark for each loop. Most of
1642 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1643 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1644 // less verbose reporting vectorized loops and unvectorized loops that may
1645 // benefit from vectorization, respectively.
1647 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1648 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1652 // Check the loop for a trip count threshold:
1653 // do not vectorize loops with a tiny trip count.
1654 const unsigned TC = SE->getSmallConstantTripCount(L);
1655 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1656 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1657 << "This loop is not worth vectorizing.");
1658 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1659 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1661 DEBUG(dbgs() << "\n");
1662 emitAnalysisDiag(F, L, Hints, VectorizationReport()
1663 << "vectorization is not beneficial "
1664 "and is not explicitly forced");
1669 // Check if it is legal to vectorize the loop.
1670 LoopVectorizationRequirements Requirements;
1671 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1672 &Requirements, &Hints);
1673 if (!LVL.canVectorize()) {
1674 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1675 emitMissedWarning(F, L, Hints);
1679 // Collect values we want to ignore in the cost model. This includes
1680 // type-promoting instructions we identified during reduction detection.
1681 SmallPtrSet<const Value *, 32> ValuesToIgnore;
1682 CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
1683 for (auto &Reduction : *LVL.getReductionVars()) {
1684 RecurrenceDescriptor &RedDes = Reduction.second;
1685 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
1686 ValuesToIgnore.insert(Casts.begin(), Casts.end());
1689 // Use the cost model.
1690 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints,
1693 // Check the function attributes to find out if this function should be
1694 // optimized for size.
1695 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1698 // Compute the weighted frequency of this loop being executed and see if it
1699 // is less than 20% of the function entry baseline frequency. Note that we
1700 // always have a canonical loop here because we think we *can* vectorize.
1701 // FIXME: This is hidden behind a flag due to pervasive problems with
1702 // exactly what block frequency models.
1703 if (LoopVectorizeWithBlockFrequency) {
1704 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1705 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1706 LoopEntryFreq < ColdEntryFreq)
1710 // Check the function attributes to see if implicit floats are allowed.
1711 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1712 // an integer loop and the vector instructions selected are purely integer
1713 // vector instructions?
1714 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1715 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1716 "attribute is used.\n");
1719 VectorizationReport()
1720 << "loop not vectorized due to NoImplicitFloat attribute");
1721 emitMissedWarning(F, L, Hints);
1725 // Select the optimal vectorization factor.
1726 const LoopVectorizationCostModel::VectorizationFactor VF =
1727 CM.selectVectorizationFactor(OptForSize);
1729 // Select the interleave count.
1730 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1732 // Get user interleave count.
1733 unsigned UserIC = Hints.getInterleave();
1735 // Identify the diagnostic messages that should be produced.
1736 std::string VecDiagMsg, IntDiagMsg;
1737 bool VectorizeLoop = true, InterleaveLoop = true;
1739 if (Requirements.doesNotMeet(F, L, Hints)) {
1740 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1742 emitMissedWarning(F, L, Hints);
1746 if (VF.Width == 1) {
1747 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1749 "the cost-model indicates that vectorization is not beneficial";
1750 VectorizeLoop = false;
1753 if (IC == 1 && UserIC <= 1) {
1754 // Tell the user interleaving is not beneficial.
1755 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1757 "the cost-model indicates that interleaving is not beneficial";
1758 InterleaveLoop = false;
1761 " and is explicitly disabled or interleave count is set to 1";
1762 } else if (IC > 1 && UserIC == 1) {
1763 // Tell the user interleaving is beneficial, but it explicitly disabled.
1765 << "LV: Interleaving is beneficial but is explicitly disabled.");
1766 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1767 "but is explicitly disabled or interleave count is set to 1";
1768 InterleaveLoop = false;
1771 // Override IC if user provided an interleave count.
1772 IC = UserIC > 0 ? UserIC : IC;
1774 // Emit diagnostic messages, if any.
1775 const char *VAPassName = Hints.vectorizeAnalysisPassName();
1776 if (!VectorizeLoop && !InterleaveLoop) {
1777 // Do not vectorize or interleaving the loop.
1778 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1779 L->getStartLoc(), VecDiagMsg);
1780 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1781 L->getStartLoc(), IntDiagMsg);
1783 } else if (!VectorizeLoop && InterleaveLoop) {
1784 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1785 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1786 L->getStartLoc(), VecDiagMsg);
1787 } else if (VectorizeLoop && !InterleaveLoop) {
1788 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1789 << DebugLocStr << '\n');
1790 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1791 L->getStartLoc(), IntDiagMsg);
1792 } else if (VectorizeLoop && InterleaveLoop) {
1793 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1794 << DebugLocStr << '\n');
1795 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1798 if (!VectorizeLoop) {
1799 assert(IC > 1 && "interleave count should not be 1 or 0");
1800 // If we decided that it is not legal to vectorize the loop then
1802 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC);
1803 Unroller.vectorize(&LVL);
1805 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1806 Twine("interleaved loop (interleaved count: ") +
1809 // If we decided that it is *legal* to vectorize the loop then do it.
1810 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC);
1814 // Add metadata to disable runtime unrolling scalar loop when there's no
1815 // runtime check about strides and memory. Because at this situation,
1816 // scalar loop is rarely used not worthy to be unrolled.
1817 if (!LB.IsSafetyChecksAdded())
1818 AddRuntimeUnrollDisableMetaData(L);
1820 // Report the vectorization decision.
1821 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1822 Twine("vectorized loop (vectorization width: ") +
1823 Twine(VF.Width) + ", interleaved count: " +
1827 // Mark the loop as already vectorized to avoid vectorizing again.
1828 Hints.setAlreadyVectorized();
1830 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1834 void getAnalysisUsage(AnalysisUsage &AU) const override {
1835 AU.addRequired<AssumptionCacheTracker>();
1836 AU.addRequiredID(LoopSimplifyID);
1837 AU.addRequiredID(LCSSAID);
1838 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1839 AU.addRequired<DominatorTreeWrapperPass>();
1840 AU.addRequired<LoopInfoWrapperPass>();
1841 AU.addRequired<ScalarEvolutionWrapperPass>();
1842 AU.addRequired<TargetTransformInfoWrapperPass>();
1843 AU.addRequired<AAResultsWrapperPass>();
1844 AU.addRequired<LoopAccessAnalysis>();
1845 AU.addPreserved<LoopInfoWrapperPass>();
1846 AU.addPreserved<DominatorTreeWrapperPass>();
1847 AU.addPreserved<BasicAAWrapperPass>();
1848 AU.addPreserved<AAResultsWrapperPass>();
1849 AU.addPreserved<GlobalsAAWrapperPass>();
1854 } // end anonymous namespace
1856 //===----------------------------------------------------------------------===//
1857 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1858 // LoopVectorizationCostModel.
1859 //===----------------------------------------------------------------------===//
1861 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1862 // We need to place the broadcast of invariant variables outside the loop.
1863 Instruction *Instr = dyn_cast<Instruction>(V);
1865 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1866 Instr->getParent()) != LoopVectorBody.end());
1867 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1869 // Place the code for broadcasting invariant variables in the new preheader.
1870 IRBuilder<>::InsertPointGuard Guard(Builder);
1872 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1874 // Broadcast the scalar into all locations in the vector.
1875 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1880 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1882 assert(Val->getType()->isVectorTy() && "Must be a vector");
1883 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1884 "Elem must be an integer");
1885 assert(Step->getType() == Val->getType()->getScalarType() &&
1886 "Step has wrong type");
1887 // Create the types.
1888 Type *ITy = Val->getType()->getScalarType();
1889 VectorType *Ty = cast<VectorType>(Val->getType());
1890 int VLen = Ty->getNumElements();
1891 SmallVector<Constant*, 8> Indices;
1893 // Create a vector of consecutive numbers from zero to VF.
1894 for (int i = 0; i < VLen; ++i)
1895 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1897 // Add the consecutive indices to the vector value.
1898 Constant *Cv = ConstantVector::get(Indices);
1899 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1900 Step = Builder.CreateVectorSplat(VLen, Step);
1901 assert(Step->getType() == Val->getType() && "Invalid step vec");
1902 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1903 // which can be found from the original scalar operations.
1904 Step = Builder.CreateMul(Cv, Step);
1905 return Builder.CreateAdd(Val, Step, "induction");
1908 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1909 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1910 // Make sure that the pointer does not point to structs.
1911 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1914 // If this value is a pointer induction variable we know it is consecutive.
1915 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1916 if (Phi && Inductions.count(Phi)) {
1917 InductionDescriptor II = Inductions[Phi];
1918 return II.getConsecutiveDirection();
1921 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1925 unsigned NumOperands = Gep->getNumOperands();
1926 Value *GpPtr = Gep->getPointerOperand();
1927 // If this GEP value is a consecutive pointer induction variable and all of
1928 // the indices are constant then we know it is consecutive. We can
1929 Phi = dyn_cast<PHINode>(GpPtr);
1930 if (Phi && Inductions.count(Phi)) {
1932 // Make sure that the pointer does not point to structs.
1933 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1934 if (GepPtrType->getElementType()->isAggregateType())
1937 // Make sure that all of the index operands are loop invariant.
1938 for (unsigned i = 1; i < NumOperands; ++i)
1939 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1942 InductionDescriptor II = Inductions[Phi];
1943 return II.getConsecutiveDirection();
1946 unsigned InductionOperand = getGEPInductionOperand(Gep);
1948 // Check that all of the gep indices are uniform except for our induction
1950 for (unsigned i = 0; i != NumOperands; ++i)
1951 if (i != InductionOperand &&
1952 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1955 // We can emit wide load/stores only if the last non-zero index is the
1956 // induction variable.
1957 const SCEV *Last = nullptr;
1958 if (!Strides.count(Gep))
1959 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1961 // Because of the multiplication by a stride we can have a s/zext cast.
1962 // We are going to replace this stride by 1 so the cast is safe to ignore.
1964 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1965 // %0 = trunc i64 %indvars.iv to i32
1966 // %mul = mul i32 %0, %Stride1
1967 // %idxprom = zext i32 %mul to i64 << Safe cast.
1968 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1970 Last = replaceSymbolicStrideSCEV(SE, Strides,
1971 Gep->getOperand(InductionOperand), Gep);
1972 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1974 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1978 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1979 const SCEV *Step = AR->getStepRecurrence(*SE);
1981 // The memory is consecutive because the last index is consecutive
1982 // and all other indices are loop invariant.
1985 if (Step->isAllOnesValue())
1992 bool LoopVectorizationLegality::isUniform(Value *V) {
1993 return LAI->isUniform(V);
1996 InnerLoopVectorizer::VectorParts&
1997 InnerLoopVectorizer::getVectorValue(Value *V) {
1998 assert(V != Induction && "The new induction variable should not be used.");
1999 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2001 // If we have a stride that is replaced by one, do it here.
2002 if (Legal->hasStride(V))
2003 V = ConstantInt::get(V->getType(), 1);
2005 // If we have this scalar in the map, return it.
2006 if (WidenMap.has(V))
2007 return WidenMap.get(V);
2009 // If this scalar is unknown, assume that it is a constant or that it is
2010 // loop invariant. Broadcast V and save the value for future uses.
2011 Value *B = getBroadcastInstrs(V);
2012 return WidenMap.splat(V, B);
2015 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2016 assert(Vec->getType()->isVectorTy() && "Invalid type");
2017 SmallVector<Constant*, 8> ShuffleMask;
2018 for (unsigned i = 0; i < VF; ++i)
2019 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2021 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2022 ConstantVector::get(ShuffleMask),
2026 // Get a mask to interleave \p NumVec vectors into a wide vector.
2027 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2028 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2029 // <0, 4, 1, 5, 2, 6, 3, 7>
2030 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2032 SmallVector<Constant *, 16> Mask;
2033 for (unsigned i = 0; i < VF; i++)
2034 for (unsigned j = 0; j < NumVec; j++)
2035 Mask.push_back(Builder.getInt32(j * VF + i));
2037 return ConstantVector::get(Mask);
2040 // Get the strided mask starting from index \p Start.
2041 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2042 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2043 unsigned Stride, unsigned VF) {
2044 SmallVector<Constant *, 16> Mask;
2045 for (unsigned i = 0; i < VF; i++)
2046 Mask.push_back(Builder.getInt32(Start + i * Stride));
2048 return ConstantVector::get(Mask);
2051 // Get a mask of two parts: The first part consists of sequential integers
2052 // starting from 0, The second part consists of UNDEFs.
2053 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2054 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2055 unsigned NumUndef) {
2056 SmallVector<Constant *, 16> Mask;
2057 for (unsigned i = 0; i < NumInt; i++)
2058 Mask.push_back(Builder.getInt32(i));
2060 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2061 for (unsigned i = 0; i < NumUndef; i++)
2062 Mask.push_back(Undef);
2064 return ConstantVector::get(Mask);
2067 // Concatenate two vectors with the same element type. The 2nd vector should
2068 // not have more elements than the 1st vector. If the 2nd vector has less
2069 // elements, extend it with UNDEFs.
2070 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2072 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2073 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2074 assert(VecTy1 && VecTy2 &&
2075 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2076 "Expect two vectors with the same element type");
2078 unsigned NumElts1 = VecTy1->getNumElements();
2079 unsigned NumElts2 = VecTy2->getNumElements();
2080 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2082 if (NumElts1 > NumElts2) {
2083 // Extend with UNDEFs.
2085 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2086 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2089 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2090 return Builder.CreateShuffleVector(V1, V2, Mask);
2093 // Concatenate vectors in the given list. All vectors have the same type.
2094 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2095 ArrayRef<Value *> InputList) {
2096 unsigned NumVec = InputList.size();
2097 assert(NumVec > 1 && "Should be at least two vectors");
2099 SmallVector<Value *, 8> ResList;
2100 ResList.append(InputList.begin(), InputList.end());
2102 SmallVector<Value *, 8> TmpList;
2103 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2104 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2105 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2106 "Only the last vector may have a different type");
2108 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2111 // Push the last vector if the total number of vectors is odd.
2112 if (NumVec % 2 != 0)
2113 TmpList.push_back(ResList[NumVec - 1]);
2116 NumVec = ResList.size();
2117 } while (NumVec > 1);
2122 // Try to vectorize the interleave group that \p Instr belongs to.
2124 // E.g. Translate following interleaved load group (factor = 3):
2125 // for (i = 0; i < N; i+=3) {
2126 // R = Pic[i]; // Member of index 0
2127 // G = Pic[i+1]; // Member of index 1
2128 // B = Pic[i+2]; // Member of index 2
2129 // ... // do something to R, G, B
2132 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2133 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2134 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2135 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2137 // Or translate following interleaved store group (factor = 3):
2138 // for (i = 0; i < N; i+=3) {
2139 // ... do something to R, G, B
2140 // Pic[i] = R; // Member of index 0
2141 // Pic[i+1] = G; // Member of index 1
2142 // Pic[i+2] = B; // Member of index 2
2145 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2146 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2147 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2148 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2149 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2150 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2151 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2152 assert(Group && "Fail to get an interleaved access group.");
2154 // Skip if current instruction is not the insert position.
2155 if (Instr != Group->getInsertPos())
2158 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2159 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2160 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2162 // Prepare for the vector type of the interleaved load/store.
2163 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2164 unsigned InterleaveFactor = Group->getFactor();
2165 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2166 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2168 // Prepare for the new pointers.
2169 setDebugLocFromInst(Builder, Ptr);
2170 VectorParts &PtrParts = getVectorValue(Ptr);
2171 SmallVector<Value *, 2> NewPtrs;
2172 unsigned Index = Group->getIndex(Instr);
2173 for (unsigned Part = 0; Part < UF; Part++) {
2174 // Extract the pointer for current instruction from the pointer vector. A
2175 // reverse access uses the pointer in the last lane.
2176 Value *NewPtr = Builder.CreateExtractElement(
2178 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2180 // Notice current instruction could be any index. Need to adjust the address
2181 // to the member of index 0.
2183 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2184 // b = A[i]; // Member of index 0
2185 // Current pointer is pointed to A[i+1], adjust it to A[i].
2187 // E.g. A[i+1] = a; // Member of index 1
2188 // A[i] = b; // Member of index 0
2189 // A[i+2] = c; // Member of index 2 (Current instruction)
2190 // Current pointer is pointed to A[i+2], adjust it to A[i].
2191 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2193 // Cast to the vector pointer type.
2194 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2197 setDebugLocFromInst(Builder, Instr);
2198 Value *UndefVec = UndefValue::get(VecTy);
2200 // Vectorize the interleaved load group.
2202 for (unsigned Part = 0; Part < UF; Part++) {
2203 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2204 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2206 for (unsigned i = 0; i < InterleaveFactor; i++) {
2207 Instruction *Member = Group->getMember(i);
2209 // Skip the gaps in the group.
2213 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2214 Value *StridedVec = Builder.CreateShuffleVector(
2215 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2217 // If this member has different type, cast the result type.
2218 if (Member->getType() != ScalarTy) {
2219 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2220 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2223 VectorParts &Entry = WidenMap.get(Member);
2225 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2228 propagateMetadata(NewLoadInstr, Instr);
2233 // The sub vector type for current instruction.
2234 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2236 // Vectorize the interleaved store group.
2237 for (unsigned Part = 0; Part < UF; Part++) {
2238 // Collect the stored vector from each member.
2239 SmallVector<Value *, 4> StoredVecs;
2240 for (unsigned i = 0; i < InterleaveFactor; i++) {
2241 // Interleaved store group doesn't allow a gap, so each index has a member
2242 Instruction *Member = Group->getMember(i);
2243 assert(Member && "Fail to get a member from an interleaved store group");
2246 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2247 if (Group->isReverse())
2248 StoredVec = reverseVector(StoredVec);
2250 // If this member has different type, cast it to an unified type.
2251 if (StoredVec->getType() != SubVT)
2252 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2254 StoredVecs.push_back(StoredVec);
2257 // Concatenate all vectors into a wide vector.
2258 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2260 // Interleave the elements in the wide vector.
2261 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2262 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2265 Instruction *NewStoreInstr =
2266 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2267 propagateMetadata(NewStoreInstr, Instr);
2271 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2272 // Attempt to issue a wide load.
2273 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2274 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2276 assert((LI || SI) && "Invalid Load/Store instruction");
2278 // Try to vectorize the interleave group if this access is interleaved.
2279 if (Legal->isAccessInterleaved(Instr))
2280 return vectorizeInterleaveGroup(Instr);
2282 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2283 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2284 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2285 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2286 // An alignment of 0 means target abi alignment. We need to use the scalar's
2287 // target abi alignment in such a case.
2288 const DataLayout &DL = Instr->getModule()->getDataLayout();
2290 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2291 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2292 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2293 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2295 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2296 !Legal->isMaskRequired(SI))
2297 return scalarizeInstruction(Instr, true);
2299 if (ScalarAllocatedSize != VectorElementSize)
2300 return scalarizeInstruction(Instr);
2302 // If the pointer is loop invariant or if it is non-consecutive,
2303 // scalarize the load.
2304 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2305 bool Reverse = ConsecutiveStride < 0;
2306 bool UniformLoad = LI && Legal->isUniform(Ptr);
2307 if (!ConsecutiveStride || UniformLoad)
2308 return scalarizeInstruction(Instr);
2310 Constant *Zero = Builder.getInt32(0);
2311 VectorParts &Entry = WidenMap.get(Instr);
2313 // Handle consecutive loads/stores.
2314 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2315 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2316 setDebugLocFromInst(Builder, Gep);
2317 Value *PtrOperand = Gep->getPointerOperand();
2318 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2319 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2321 // Create the new GEP with the new induction variable.
2322 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2323 Gep2->setOperand(0, FirstBasePtr);
2324 Gep2->setName("gep.indvar.base");
2325 Ptr = Builder.Insert(Gep2);
2327 setDebugLocFromInst(Builder, Gep);
2328 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2329 OrigLoop) && "Base ptr must be invariant");
2331 // The last index does not have to be the induction. It can be
2332 // consecutive and be a function of the index. For example A[I+1];
2333 unsigned NumOperands = Gep->getNumOperands();
2334 unsigned InductionOperand = getGEPInductionOperand(Gep);
2335 // Create the new GEP with the new induction variable.
2336 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2338 for (unsigned i = 0; i < NumOperands; ++i) {
2339 Value *GepOperand = Gep->getOperand(i);
2340 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2342 // Update last index or loop invariant instruction anchored in loop.
2343 if (i == InductionOperand ||
2344 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2345 assert((i == InductionOperand ||
2346 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2347 "Must be last index or loop invariant");
2349 VectorParts &GEPParts = getVectorValue(GepOperand);
2350 Value *Index = GEPParts[0];
2351 Index = Builder.CreateExtractElement(Index, Zero);
2352 Gep2->setOperand(i, Index);
2353 Gep2->setName("gep.indvar.idx");
2356 Ptr = Builder.Insert(Gep2);
2358 // Use the induction element ptr.
2359 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2360 setDebugLocFromInst(Builder, Ptr);
2361 VectorParts &PtrVal = getVectorValue(Ptr);
2362 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2365 VectorParts Mask = createBlockInMask(Instr->getParent());
2368 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2369 "We do not allow storing to uniform addresses");
2370 setDebugLocFromInst(Builder, SI);
2371 // We don't want to update the value in the map as it might be used in
2372 // another expression. So don't use a reference type for "StoredVal".
2373 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2375 for (unsigned Part = 0; Part < UF; ++Part) {
2376 // Calculate the pointer for the specific unroll-part.
2378 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2381 // If we store to reverse consecutive memory locations, then we need
2382 // to reverse the order of elements in the stored value.
2383 StoredVal[Part] = reverseVector(StoredVal[Part]);
2384 // If the address is consecutive but reversed, then the
2385 // wide store needs to start at the last vector element.
2386 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2387 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2388 Mask[Part] = reverseVector(Mask[Part]);
2391 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2392 DataTy->getPointerTo(AddressSpace));
2395 if (Legal->isMaskRequired(SI))
2396 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2399 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2400 propagateMetadata(NewSI, SI);
2406 assert(LI && "Must have a load instruction");
2407 setDebugLocFromInst(Builder, LI);
2408 for (unsigned Part = 0; Part < UF; ++Part) {
2409 // Calculate the pointer for the specific unroll-part.
2411 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2414 // If the address is consecutive but reversed, then the
2415 // wide load needs to start at the last vector element.
2416 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2417 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2418 Mask[Part] = reverseVector(Mask[Part]);
2422 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2423 DataTy->getPointerTo(AddressSpace));
2424 if (Legal->isMaskRequired(LI))
2425 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2426 UndefValue::get(DataTy),
2427 "wide.masked.load");
2429 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2430 propagateMetadata(NewLI, LI);
2431 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2435 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2436 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2437 // Holds vector parameters or scalars, in case of uniform vals.
2438 SmallVector<VectorParts, 4> Params;
2440 setDebugLocFromInst(Builder, Instr);
2442 // Find all of the vectorized parameters.
2443 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2444 Value *SrcOp = Instr->getOperand(op);
2446 // If we are accessing the old induction variable, use the new one.
2447 if (SrcOp == OldInduction) {
2448 Params.push_back(getVectorValue(SrcOp));
2452 // Try using previously calculated values.
2453 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2455 // If the src is an instruction that appeared earlier in the basic block,
2456 // then it should already be vectorized.
2457 if (SrcInst && OrigLoop->contains(SrcInst)) {
2458 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2459 // The parameter is a vector value from earlier.
2460 Params.push_back(WidenMap.get(SrcInst));
2462 // The parameter is a scalar from outside the loop. Maybe even a constant.
2463 VectorParts Scalars;
2464 Scalars.append(UF, SrcOp);
2465 Params.push_back(Scalars);
2469 assert(Params.size() == Instr->getNumOperands() &&
2470 "Invalid number of operands");
2472 // Does this instruction return a value ?
2473 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2475 Value *UndefVec = IsVoidRetTy ? nullptr :
2476 UndefValue::get(VectorType::get(Instr->getType(), VF));
2477 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2478 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2481 if (IfPredicateStore) {
2482 assert(Instr->getParent()->getSinglePredecessor() &&
2483 "Only support single predecessor blocks");
2484 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2485 Instr->getParent());
2488 // For each vector unroll 'part':
2489 for (unsigned Part = 0; Part < UF; ++Part) {
2490 // For each scalar that we create:
2491 for (unsigned Width = 0; Width < VF; ++Width) {
2494 Value *Cmp = nullptr;
2495 if (IfPredicateStore) {
2496 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2497 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2500 Instruction *Cloned = Instr->clone();
2502 Cloned->setName(Instr->getName() + ".cloned");
2503 // Replace the operands of the cloned instructions with extracted scalars.
2504 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2505 Value *Op = Params[op][Part];
2506 // Param is a vector. Need to extract the right lane.
2507 if (Op->getType()->isVectorTy())
2508 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2509 Cloned->setOperand(op, Op);
2512 // Place the cloned scalar in the new loop.
2513 Builder.Insert(Cloned);
2515 // If the original scalar returns a value we need to place it in a vector
2516 // so that future users will be able to use it.
2518 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2519 Builder.getInt32(Width));
2521 if (IfPredicateStore)
2522 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
2528 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2532 if (Instruction *I = dyn_cast<Instruction>(V))
2533 return I->getParent() == Loc->getParent() ? I : nullptr;
2537 std::pair<Instruction *, Instruction *>
2538 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2539 Instruction *tnullptr = nullptr;
2540 if (!Legal->mustCheckStrides())
2541 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2543 IRBuilder<> ChkBuilder(Loc);
2546 Value *Check = nullptr;
2547 Instruction *FirstInst = nullptr;
2548 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2549 SE = Legal->strides_end();
2551 Value *Ptr = stripIntegerCast(*SI);
2552 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2554 // Store the first instruction we create.
2555 FirstInst = getFirstInst(FirstInst, C, Loc);
2557 Check = ChkBuilder.CreateOr(Check, C);
2562 // We have to do this trickery because the IRBuilder might fold the check to a
2563 // constant expression in which case there is no Instruction anchored in a
2565 LLVMContext &Ctx = Loc->getContext();
2566 Instruction *TheCheck =
2567 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2568 ChkBuilder.Insert(TheCheck, "stride.not.one");
2569 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2571 return std::make_pair(FirstInst, TheCheck);
2574 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L,
2579 BasicBlock *Header = L->getHeader();
2580 BasicBlock *Latch = L->getLoopLatch();
2581 // As we're just creating this loop, it's possible no latch exists
2582 // yet. If so, use the header as this will be a single block loop.
2586 IRBuilder<> Builder(Header->getFirstInsertionPt());
2587 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2588 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2590 Builder.SetInsertPoint(Latch->getTerminator());
2592 // Create i+1 and fill the PHINode.
2593 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2594 Induction->addIncoming(Start, L->getLoopPreheader());
2595 Induction->addIncoming(Next, Latch);
2596 // Create the compare.
2597 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2598 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2600 // Now we have two terminators. Remove the old one from the block.
2601 Latch->getTerminator()->eraseFromParent();
2606 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2610 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2611 // Find the loop boundaries.
2612 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(OrigLoop);
2613 assert(BackedgeTakenCount != SE->getCouldNotCompute() && "Invalid loop count");
2615 Type *IdxTy = Legal->getWidestInductionType();
2617 // The exit count might have the type of i64 while the phi is i32. This can
2618 // happen if we have an induction variable that is sign extended before the
2619 // compare. The only way that we get a backedge taken count is that the
2620 // induction variable was signed and as such will not overflow. In such a case
2621 // truncation is legal.
2622 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2623 IdxTy->getPrimitiveSizeInBits())
2624 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2625 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2627 // Get the total trip count from the count by adding 1.
2628 const SCEV *ExitCount = SE->getAddExpr(
2629 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2631 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2633 // Expand the trip count and place the new instructions in the preheader.
2634 // Notice that the pre-header does not change, only the loop body.
2635 SCEVExpander Exp(*SE, DL, "induction");
2637 // Count holds the overall loop count (N).
2638 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2639 L->getLoopPreheader()->getTerminator());
2641 if (TripCount->getType()->isPointerTy())
2643 CastInst::CreatePointerCast(TripCount, IdxTy,
2644 "exitcount.ptrcnt.to.int",
2645 L->getLoopPreheader()->getTerminator());
2650 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2651 if (VectorTripCount)
2652 return VectorTripCount;
2654 Value *TC = getOrCreateTripCount(L);
2655 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2657 // Now we need to generate the expression for N - (N % VF), which is
2658 // the part that the vectorized body will execute.
2659 // The loop step is equal to the vectorization factor (num of SIMD elements)
2660 // times the unroll factor (num of SIMD instructions).
2661 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2662 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2663 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2665 return VectorTripCount;
2668 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2669 BasicBlock *Bypass) {
2670 Value *Count = getOrCreateTripCount(L);
2671 BasicBlock *BB = L->getLoopPreheader();
2672 IRBuilder<> Builder(BB->getTerminator());
2674 // Generate code to check that the loop's trip count that we computed by
2675 // adding one to the backedge-taken count will not overflow.
2676 Value *CheckMinIters =
2677 Builder.CreateICmpULT(Count,
2678 ConstantInt::get(Count->getType(), VF * UF),
2681 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2682 "min.iters.checked");
2683 if (L->getParentLoop())
2684 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2685 ReplaceInstWithInst(BB->getTerminator(),
2686 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2687 LoopBypassBlocks.push_back(BB);
2690 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2691 BasicBlock *Bypass) {
2692 Value *TC = getOrCreateVectorTripCount(L);
2693 BasicBlock *BB = L->getLoopPreheader();
2694 IRBuilder<> Builder(BB->getTerminator());
2696 // Now, compare the new count to zero. If it is zero skip the vector loop and
2697 // jump to the scalar loop.
2698 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2701 // Generate code to check that the loop's trip count that we computed by
2702 // adding one to the backedge-taken count will not overflow.
2703 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2705 if (L->getParentLoop())
2706 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2707 ReplaceInstWithInst(BB->getTerminator(),
2708 BranchInst::Create(Bypass, NewBB, Cmp));
2709 LoopBypassBlocks.push_back(BB);
2712 void InnerLoopVectorizer::emitStrideChecks(Loop *L,
2713 BasicBlock *Bypass) {
2714 BasicBlock *BB = L->getLoopPreheader();
2716 // Generate the code to check that the strides we assumed to be one are really
2717 // one. We want the new basic block to start at the first instruction in a
2718 // sequence of instructions that form a check.
2719 Instruction *StrideCheck;
2720 Instruction *FirstCheckInst;
2721 std::tie(FirstCheckInst, StrideCheck) = addStrideCheck(BB->getTerminator());
2725 // Create a new block containing the stride check.
2726 BB->setName("vector.stridecheck");
2727 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2728 if (L->getParentLoop())
2729 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2730 ReplaceInstWithInst(BB->getTerminator(),
2731 BranchInst::Create(Bypass, NewBB, StrideCheck));
2732 LoopBypassBlocks.push_back(BB);
2733 AddedSafetyChecks = true;
2736 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
2737 BasicBlock *Bypass) {
2738 BasicBlock *BB = L->getLoopPreheader();
2740 // Generate the code that checks in runtime if arrays overlap. We put the
2741 // checks into a separate block to make the more common case of few elements
2743 Instruction *FirstCheckInst;
2744 Instruction *MemRuntimeCheck;
2745 std::tie(FirstCheckInst, MemRuntimeCheck) =
2746 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2747 if (!MemRuntimeCheck)
2750 // Create a new block containing the memory check.
2751 BB->setName("vector.memcheck");
2752 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2753 if (L->getParentLoop())
2754 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2755 ReplaceInstWithInst(BB->getTerminator(),
2756 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2757 LoopBypassBlocks.push_back(BB);
2758 AddedSafetyChecks = true;
2762 void InnerLoopVectorizer::createEmptyLoop() {
2764 In this function we generate a new loop. The new loop will contain
2765 the vectorized instructions while the old loop will continue to run the
2768 [ ] <-- loop iteration number check.
2771 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2774 || [ ] <-- vector pre header.
2778 | [ ]_| <-- vector loop.
2781 | -[ ] <--- middle-block.
2784 -|- >[ ] <--- new preheader.
2788 | [ ]_| <-- old scalar loop to handle remainder.
2791 >[ ] <-- exit block.
2795 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2796 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2797 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2798 assert(VectorPH && "Invalid loop structure");
2799 assert(ExitBlock && "Must have an exit block");
2801 // Some loops have a single integer induction variable, while other loops
2802 // don't. One example is c++ iterators that often have multiple pointer
2803 // induction variables. In the code below we also support a case where we
2804 // don't have a single induction variable.
2806 // We try to obtain an induction variable from the original loop as hard
2807 // as possible. However if we don't find one that:
2809 // - counts from zero, stepping by one
2810 // - is the size of the widest induction variable type
2811 // then we create a new one.
2812 OldInduction = Legal->getInduction();
2813 Type *IdxTy = Legal->getWidestInductionType();
2815 // Split the single block loop into the two loop structure described above.
2816 BasicBlock *VecBody =
2817 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2818 BasicBlock *MiddleBlock =
2819 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2820 BasicBlock *ScalarPH =
2821 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2823 // Create and register the new vector loop.
2824 Loop* Lp = new Loop();
2825 Loop *ParentLoop = OrigLoop->getParentLoop();
2827 // Insert the new loop into the loop nest and register the new basic blocks
2828 // before calling any utilities such as SCEV that require valid LoopInfo.
2830 ParentLoop->addChildLoop(Lp);
2831 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2832 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2834 LI->addTopLevelLoop(Lp);
2836 Lp->addBasicBlockToLoop(VecBody, *LI);
2838 // Find the loop boundaries.
2839 Value *Count = getOrCreateTripCount(Lp);
2841 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2843 // We need to test whether the backedge-taken count is uint##_max. Adding one
2844 // to it will cause overflow and an incorrect loop trip count in the vector
2845 // body. In case of overflow we want to directly jump to the scalar remainder
2847 emitMinimumIterationCountCheck(Lp, ScalarPH);
2848 // Now, compare the new count to zero. If it is zero skip the vector loop and
2849 // jump to the scalar loop.
2850 emitVectorLoopEnteredCheck(Lp, ScalarPH);
2851 // Generate the code to check that the strides we assumed to be one are really
2852 // one. We want the new basic block to start at the first instruction in a
2853 // sequence of instructions that form a check.
2854 emitStrideChecks(Lp, ScalarPH);
2855 // Generate the code that checks in runtime if arrays overlap. We put the
2856 // checks into a separate block to make the more common case of few elements
2858 emitMemRuntimeChecks(Lp, ScalarPH);
2860 // Generate the induction variable.
2861 // The loop step is equal to the vectorization factor (num of SIMD elements)
2862 // times the unroll factor (num of SIMD instructions).
2863 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2864 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2866 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2867 getDebugLocFromInstOrOperands(OldInduction));
2869 // We are going to resume the execution of the scalar loop.
2870 // Go over all of the induction variables that we found and fix the
2871 // PHIs that are left in the scalar version of the loop.
2872 // The starting values of PHI nodes depend on the counter of the last
2873 // iteration in the vectorized loop.
2874 // If we come from a bypass edge then we need to start from the original
2877 // This variable saves the new starting index for the scalar loop. It is used
2878 // to test if there are any tail iterations left once the vector loop has
2880 LoopVectorizationLegality::InductionList::iterator I, E;
2881 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2882 for (I = List->begin(), E = List->end(); I != E; ++I) {
2883 PHINode *OrigPhi = I->first;
2884 InductionDescriptor II = I->second;
2886 // Create phi nodes to merge from the backedge-taken check block.
2887 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
2889 ScalarPH->getTerminator());
2891 if (OrigPhi == OldInduction) {
2892 // We know what the end value is.
2893 EndValue = CountRoundDown;
2895 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
2896 Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
2897 II.getStepValue()->getType(),
2899 EndValue = II.transform(B, CRD);
2900 EndValue->setName("ind.end");
2903 // The new PHI merges the original incoming value, in case of a bypass,
2904 // or the value at the end of the vectorized loop.
2905 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2907 // Fix the scalar body counter (PHI node).
2908 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2910 // The old induction's phi node in the scalar body needs the truncated
2912 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2913 BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
2914 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2917 // Add a check in the middle block to see if we have completed
2918 // all of the iterations in the first vector loop.
2919 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2920 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2921 CountRoundDown, "cmp.n",
2922 MiddleBlock->getTerminator());
2923 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2924 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2926 // Get ready to start creating new instructions into the vectorized body.
2927 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2930 LoopVectorPreHeader = Lp->getLoopPreheader();
2931 LoopScalarPreHeader = ScalarPH;
2932 LoopMiddleBlock = MiddleBlock;
2933 LoopExitBlock = ExitBlock;
2934 LoopVectorBody.push_back(VecBody);
2935 LoopScalarBody = OldBasicBlock;
2937 LoopVectorizeHints Hints(Lp, true);
2938 Hints.setAlreadyVectorized();
2942 struct CSEDenseMapInfo {
2943 static bool canHandle(Instruction *I) {
2944 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2945 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2947 static inline Instruction *getEmptyKey() {
2948 return DenseMapInfo<Instruction *>::getEmptyKey();
2950 static inline Instruction *getTombstoneKey() {
2951 return DenseMapInfo<Instruction *>::getTombstoneKey();
2953 static unsigned getHashValue(Instruction *I) {
2954 assert(canHandle(I) && "Unknown instruction!");
2955 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2956 I->value_op_end()));
2958 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2959 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2960 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2962 return LHS->isIdenticalTo(RHS);
2967 /// \brief Check whether this block is a predicated block.
2968 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2969 /// = ...; " blocks. We start with one vectorized basic block. For every
2970 /// conditional block we split this vectorized block. Therefore, every second
2971 /// block will be a predicated one.
2972 static bool isPredicatedBlock(unsigned BlockNum) {
2973 return BlockNum % 2;
2976 ///\brief Perform cse of induction variable instructions.
2977 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2978 // Perform simple cse.
2979 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2980 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2981 BasicBlock *BB = BBs[i];
2982 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2983 Instruction *In = I++;
2985 if (!CSEDenseMapInfo::canHandle(In))
2988 // Check if we can replace this instruction with any of the
2989 // visited instructions.
2990 if (Instruction *V = CSEMap.lookup(In)) {
2991 In->replaceAllUsesWith(V);
2992 In->eraseFromParent();
2995 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2996 // ...;" blocks for predicated stores. Every second block is a predicated
2998 if (isPredicatedBlock(i))
3006 /// \brief Adds a 'fast' flag to floating point operations.
3007 static Value *addFastMathFlag(Value *V) {
3008 if (isa<FPMathOperator>(V)){
3009 FastMathFlags Flags;
3010 Flags.setUnsafeAlgebra();
3011 cast<Instruction>(V)->setFastMathFlags(Flags);
3016 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3017 /// the result needs to be inserted and/or extracted from vectors.
3018 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3019 const TargetTransformInfo &TTI) {
3023 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3026 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3028 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3030 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3036 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3037 // Return the cost of the instruction, including scalarization overhead if it's
3038 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3039 // i.e. either vector version isn't available, or is too expensive.
3040 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3041 const TargetTransformInfo &TTI,
3042 const TargetLibraryInfo *TLI,
3043 bool &NeedToScalarize) {
3044 Function *F = CI->getCalledFunction();
3045 StringRef FnName = CI->getCalledFunction()->getName();
3046 Type *ScalarRetTy = CI->getType();
3047 SmallVector<Type *, 4> Tys, ScalarTys;
3048 for (auto &ArgOp : CI->arg_operands())
3049 ScalarTys.push_back(ArgOp->getType());
3051 // Estimate cost of scalarized vector call. The source operands are assumed
3052 // to be vectors, so we need to extract individual elements from there,
3053 // execute VF scalar calls, and then gather the result into the vector return
3055 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3057 return ScalarCallCost;
3059 // Compute corresponding vector type for return value and arguments.
3060 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3061 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3062 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3064 // Compute costs of unpacking argument values for the scalar calls and
3065 // packing the return values to a vector.
3066 unsigned ScalarizationCost =
3067 getScalarizationOverhead(RetTy, true, false, TTI);
3068 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3069 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3071 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3073 // If we can't emit a vector call for this function, then the currently found
3074 // cost is the cost we need to return.
3075 NeedToScalarize = true;
3076 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3079 // If the corresponding vector cost is cheaper, return its cost.
3080 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3081 if (VectorCallCost < Cost) {
3082 NeedToScalarize = false;
3083 return VectorCallCost;
3088 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3089 // factor VF. Return the cost of the instruction, including scalarization
3090 // overhead if it's needed.
3091 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3092 const TargetTransformInfo &TTI,
3093 const TargetLibraryInfo *TLI) {
3094 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3095 assert(ID && "Expected intrinsic call!");
3097 Type *RetTy = ToVectorTy(CI->getType(), VF);
3098 SmallVector<Type *, 4> Tys;
3099 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3100 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3102 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3105 void InnerLoopVectorizer::vectorizeLoop() {
3106 //===------------------------------------------------===//
3108 // Notice: any optimization or new instruction that go
3109 // into the code below should be also be implemented in
3112 //===------------------------------------------------===//
3113 Constant *Zero = Builder.getInt32(0);
3115 // In order to support reduction variables we need to be able to vectorize
3116 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3117 // stages. First, we create a new vector PHI node with no incoming edges.
3118 // We use this value when we vectorize all of the instructions that use the
3119 // PHI. Next, after all of the instructions in the block are complete we
3120 // add the new incoming edges to the PHI. At this point all of the
3121 // instructions in the basic block are vectorized, so we can use them to
3122 // construct the PHI.
3123 PhiVector RdxPHIsToFix;
3125 // Scan the loop in a topological order to ensure that defs are vectorized
3127 LoopBlocksDFS DFS(OrigLoop);
3130 // Vectorize all of the blocks in the original loop.
3131 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3132 be = DFS.endRPO(); bb != be; ++bb)
3133 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3135 // At this point every instruction in the original loop is widened to
3136 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3137 // that we vectorized. The PHI nodes are currently empty because we did
3138 // not want to introduce cycles. Notice that the remaining PHI nodes
3139 // that we need to fix are reduction variables.
3141 // Create the 'reduced' values for each of the induction vars.
3142 // The reduced values are the vector values that we scalarize and combine
3143 // after the loop is finished.
3144 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3146 PHINode *RdxPhi = *it;
3147 assert(RdxPhi && "Unable to recover vectorized PHI");
3149 // Find the reduction variable descriptor.
3150 assert(Legal->getReductionVars()->count(RdxPhi) &&
3151 "Unable to find the reduction variable");
3152 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3154 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3155 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3156 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3157 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3158 RdxDesc.getMinMaxRecurrenceKind();
3159 setDebugLocFromInst(Builder, ReductionStartValue);
3161 // We need to generate a reduction vector from the incoming scalar.
3162 // To do so, we need to generate the 'identity' vector and override
3163 // one of the elements with the incoming scalar reduction. We need
3164 // to do it in the vector-loop preheader.
3165 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3167 // This is the vector-clone of the value that leaves the loop.
3168 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3169 Type *VecTy = VectorExit[0]->getType();
3171 // Find the reduction identity variable. Zero for addition, or, xor,
3172 // one for multiplication, -1 for And.
3175 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3176 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3177 // MinMax reduction have the start value as their identify.
3179 VectorStart = Identity = ReductionStartValue;
3181 VectorStart = Identity =
3182 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3185 // Handle other reduction kinds:
3186 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3187 RK, VecTy->getScalarType());
3190 // This vector is the Identity vector where the first element is the
3191 // incoming scalar reduction.
3192 VectorStart = ReductionStartValue;
3194 Identity = ConstantVector::getSplat(VF, Iden);
3196 // This vector is the Identity vector where the first element is the
3197 // incoming scalar reduction.
3199 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3203 // Fix the vector-loop phi.
3205 // Reductions do not have to start at zero. They can start with
3206 // any loop invariant values.
3207 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3208 BasicBlock *Latch = OrigLoop->getLoopLatch();
3209 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3210 VectorParts &Val = getVectorValue(LoopVal);
3211 for (unsigned part = 0; part < UF; ++part) {
3212 // Make sure to add the reduction stat value only to the
3213 // first unroll part.
3214 Value *StartVal = (part == 0) ? VectorStart : Identity;
3215 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3216 LoopVectorPreHeader);
3217 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3218 LoopVectorBody.back());
3221 // Before each round, move the insertion point right between
3222 // the PHIs and the values we are going to write.
3223 // This allows us to write both PHINodes and the extractelement
3225 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3227 VectorParts RdxParts = getVectorValue(LoopExitInst);
3228 setDebugLocFromInst(Builder, LoopExitInst);
3230 // If the vector reduction can be performed in a smaller type, we truncate
3231 // then extend the loop exit value to enable InstCombine to evaluate the
3232 // entire expression in the smaller type.
3233 if (VF > 1 && RdxPhi->getType() != RdxDesc.getRecurrenceType()) {
3234 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3235 Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
3236 for (unsigned part = 0; part < UF; ++part) {
3237 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3238 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3239 : Builder.CreateZExt(Trunc, VecTy);
3240 for (Value::user_iterator UI = RdxParts[part]->user_begin();
3241 UI != RdxParts[part]->user_end();)
3243 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3244 RdxParts[part] = Extnd;
3249 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3250 for (unsigned part = 0; part < UF; ++part)
3251 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3254 // Reduce all of the unrolled parts into a single vector.
3255 Value *ReducedPartRdx = RdxParts[0];
3256 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3257 setDebugLocFromInst(Builder, ReducedPartRdx);
3258 for (unsigned part = 1; part < UF; ++part) {
3259 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3260 // Floating point operations had to be 'fast' to enable the reduction.
3261 ReducedPartRdx = addFastMathFlag(
3262 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3263 ReducedPartRdx, "bin.rdx"));
3265 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3266 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3270 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3271 // and vector ops, reducing the set of values being computed by half each
3273 assert(isPowerOf2_32(VF) &&
3274 "Reduction emission only supported for pow2 vectors!");
3275 Value *TmpVec = ReducedPartRdx;
3276 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3277 for (unsigned i = VF; i != 1; i >>= 1) {
3278 // Move the upper half of the vector to the lower half.
3279 for (unsigned j = 0; j != i/2; ++j)
3280 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3282 // Fill the rest of the mask with undef.
3283 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3284 UndefValue::get(Builder.getInt32Ty()));
3287 Builder.CreateShuffleVector(TmpVec,
3288 UndefValue::get(TmpVec->getType()),
3289 ConstantVector::get(ShuffleMask),
3292 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3293 // Floating point operations had to be 'fast' to enable the reduction.
3294 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3295 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3297 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3301 // The result is in the first element of the vector.
3302 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3303 Builder.getInt32(0));
3305 // If the reduction can be performed in a smaller type, we need to extend
3306 // the reduction to the wider type before we branch to the original loop.
3307 if (RdxPhi->getType() != RdxDesc.getRecurrenceType())
3310 ? Builder.CreateSExt(ReducedPartRdx, RdxPhi->getType())
3311 : Builder.CreateZExt(ReducedPartRdx, RdxPhi->getType());
3314 // Create a phi node that merges control-flow from the backedge-taken check
3315 // block and the middle block.
3316 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3317 LoopScalarPreHeader->getTerminator());
3318 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3319 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3320 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3322 // Now, we need to fix the users of the reduction variable
3323 // inside and outside of the scalar remainder loop.
3324 // We know that the loop is in LCSSA form. We need to update the
3325 // PHI nodes in the exit blocks.
3326 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3327 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3328 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3329 if (!LCSSAPhi) break;
3331 // All PHINodes need to have a single entry edge, or two if
3332 // we already fixed them.
3333 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3335 // We found our reduction value exit-PHI. Update it with the
3336 // incoming bypass edge.
3337 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3338 // Add an edge coming from the bypass.
3339 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3342 }// end of the LCSSA phi scan.
3344 // Fix the scalar loop reduction variable with the incoming reduction sum
3345 // from the vector body and from the backedge value.
3346 int IncomingEdgeBlockIdx =
3347 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3348 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3349 // Pick the other block.
3350 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3351 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3352 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3353 }// end of for each redux variable.
3357 // Make sure DomTree is updated.
3360 // Predicate any stores.
3361 for (auto KV : PredicatedStores) {
3362 BasicBlock::iterator I(KV.first);
3363 auto *BB = SplitBlock(I->getParent(), std::next(I), DT, LI);
3364 auto *T = SplitBlockAndInsertIfThen(KV.second, I, /*Unreachable=*/false,
3365 /*BranchWeights=*/nullptr, DT);
3367 I->getParent()->setName("pred.store.if");
3368 BB->setName("pred.store.continue");
3370 DEBUG(DT->verifyDomTree());
3371 // Remove redundant induction instructions.
3372 cse(LoopVectorBody);
3375 void InnerLoopVectorizer::fixLCSSAPHIs() {
3376 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3377 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3378 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3379 if (!LCSSAPhi) break;
3380 if (LCSSAPhi->getNumIncomingValues() == 1)
3381 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3386 InnerLoopVectorizer::VectorParts
3387 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3388 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3391 // Look for cached value.
3392 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3393 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3394 if (ECEntryIt != MaskCache.end())
3395 return ECEntryIt->second;
3397 VectorParts SrcMask = createBlockInMask(Src);
3399 // The terminator has to be a branch inst!
3400 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3401 assert(BI && "Unexpected terminator found");
3403 if (BI->isConditional()) {
3404 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3406 if (BI->getSuccessor(0) != Dst)
3407 for (unsigned part = 0; part < UF; ++part)
3408 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3410 for (unsigned part = 0; part < UF; ++part)
3411 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3413 MaskCache[Edge] = EdgeMask;
3417 MaskCache[Edge] = SrcMask;
3421 InnerLoopVectorizer::VectorParts
3422 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3423 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3425 // Loop incoming mask is all-one.
3426 if (OrigLoop->getHeader() == BB) {
3427 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3428 return getVectorValue(C);
3431 // This is the block mask. We OR all incoming edges, and with zero.
3432 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3433 VectorParts BlockMask = getVectorValue(Zero);
3436 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3437 VectorParts EM = createEdgeMask(*it, BB);
3438 for (unsigned part = 0; part < UF; ++part)
3439 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3445 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3446 InnerLoopVectorizer::VectorParts &Entry,
3447 unsigned UF, unsigned VF, PhiVector *PV) {
3448 PHINode* P = cast<PHINode>(PN);
3449 // Handle reduction variables:
3450 if (Legal->getReductionVars()->count(P)) {
3451 for (unsigned part = 0; part < UF; ++part) {
3452 // This is phase one of vectorizing PHIs.
3453 Type *VecTy = (VF == 1) ? PN->getType() :
3454 VectorType::get(PN->getType(), VF);
3455 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3456 LoopVectorBody.back()-> getFirstInsertionPt());
3462 setDebugLocFromInst(Builder, P);
3463 // Check for PHI nodes that are lowered to vector selects.
3464 if (P->getParent() != OrigLoop->getHeader()) {
3465 // We know that all PHIs in non-header blocks are converted into
3466 // selects, so we don't have to worry about the insertion order and we
3467 // can just use the builder.
3468 // At this point we generate the predication tree. There may be
3469 // duplications since this is a simple recursive scan, but future
3470 // optimizations will clean it up.
3472 unsigned NumIncoming = P->getNumIncomingValues();
3474 // Generate a sequence of selects of the form:
3475 // SELECT(Mask3, In3,
3476 // SELECT(Mask2, In2,
3478 for (unsigned In = 0; In < NumIncoming; In++) {
3479 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3481 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3483 for (unsigned part = 0; part < UF; ++part) {
3484 // We might have single edge PHIs (blocks) - use an identity
3485 // 'select' for the first PHI operand.
3487 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3490 // Select between the current value and the previous incoming edge
3491 // based on the incoming mask.
3492 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3493 Entry[part], "predphi");
3499 // This PHINode must be an induction variable.
3500 // Make sure that we know about it.
3501 assert(Legal->getInductionVars()->count(P) &&
3502 "Not an induction variable");
3504 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3506 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3507 // which can be found from the original scalar operations.
3508 switch (II.getKind()) {
3509 case InductionDescriptor::IK_NoInduction:
3510 llvm_unreachable("Unknown induction");
3511 case InductionDescriptor::IK_IntInduction: {
3512 assert(P->getType() == II.getStartValue()->getType() && "Types must match");
3513 // Handle other induction variables that are now based on the
3515 Value *V = Induction;
3516 if (P != OldInduction) {
3517 V = Builder.CreateSExtOrTrunc(Induction, P->getType());
3518 V = II.transform(Builder, V);
3519 V->setName("offset.idx");
3521 Value *Broadcasted = getBroadcastInstrs(V);
3522 // After broadcasting the induction variable we need to make the vector
3523 // consecutive by adding 0, 1, 2, etc.
3524 for (unsigned part = 0; part < UF; ++part)
3525 Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
3528 case InductionDescriptor::IK_PtrInduction:
3529 // Handle the pointer induction variable case.
3530 assert(P->getType()->isPointerTy() && "Unexpected type.");
3531 // This is the normalized GEP that starts counting at zero.
3532 Value *PtrInd = Induction;
3533 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
3534 // This is the vector of results. Notice that we don't generate
3535 // vector geps because scalar geps result in better code.
3536 for (unsigned part = 0; part < UF; ++part) {
3538 int EltIndex = part;
3539 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3540 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3541 Value *SclrGep = II.transform(Builder, GlobalIdx);
3542 SclrGep->setName("next.gep");
3543 Entry[part] = SclrGep;
3547 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3548 for (unsigned int i = 0; i < VF; ++i) {
3549 int EltIndex = i + part * VF;
3550 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3551 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3552 Value *SclrGep = II.transform(Builder, GlobalIdx);
3553 SclrGep->setName("next.gep");
3554 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3555 Builder.getInt32(i),
3558 Entry[part] = VecVal;
3564 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3565 // For each instruction in the old loop.
3566 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3567 VectorParts &Entry = WidenMap.get(it);
3568 switch (it->getOpcode()) {
3569 case Instruction::Br:
3570 // Nothing to do for PHIs and BR, since we already took care of the
3571 // loop control flow instructions.
3573 case Instruction::PHI: {
3574 // Vectorize PHINodes.
3575 widenPHIInstruction(it, Entry, UF, VF, PV);
3579 case Instruction::Add:
3580 case Instruction::FAdd:
3581 case Instruction::Sub:
3582 case Instruction::FSub:
3583 case Instruction::Mul:
3584 case Instruction::FMul:
3585 case Instruction::UDiv:
3586 case Instruction::SDiv:
3587 case Instruction::FDiv:
3588 case Instruction::URem:
3589 case Instruction::SRem:
3590 case Instruction::FRem:
3591 case Instruction::Shl:
3592 case Instruction::LShr:
3593 case Instruction::AShr:
3594 case Instruction::And:
3595 case Instruction::Or:
3596 case Instruction::Xor: {
3597 // Just widen binops.
3598 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3599 setDebugLocFromInst(Builder, BinOp);
3600 VectorParts &A = getVectorValue(it->getOperand(0));
3601 VectorParts &B = getVectorValue(it->getOperand(1));
3603 // Use this vector value for all users of the original instruction.
3604 for (unsigned Part = 0; Part < UF; ++Part) {
3605 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3607 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3608 VecOp->copyIRFlags(BinOp);
3613 propagateMetadata(Entry, it);
3616 case Instruction::Select: {
3618 // If the selector is loop invariant we can create a select
3619 // instruction with a scalar condition. Otherwise, use vector-select.
3620 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3622 setDebugLocFromInst(Builder, it);
3624 // The condition can be loop invariant but still defined inside the
3625 // loop. This means that we can't just use the original 'cond' value.
3626 // We have to take the 'vectorized' value and pick the first lane.
3627 // Instcombine will make this a no-op.
3628 VectorParts &Cond = getVectorValue(it->getOperand(0));
3629 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3630 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3632 Value *ScalarCond = (VF == 1) ? Cond[0] :
3633 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3635 for (unsigned Part = 0; Part < UF; ++Part) {
3636 Entry[Part] = Builder.CreateSelect(
3637 InvariantCond ? ScalarCond : Cond[Part],
3642 propagateMetadata(Entry, it);
3646 case Instruction::ICmp:
3647 case Instruction::FCmp: {
3648 // Widen compares. Generate vector compares.
3649 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3650 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3651 setDebugLocFromInst(Builder, it);
3652 VectorParts &A = getVectorValue(it->getOperand(0));
3653 VectorParts &B = getVectorValue(it->getOperand(1));
3654 for (unsigned Part = 0; Part < UF; ++Part) {
3657 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3658 cast<FCmpInst>(C)->copyFastMathFlags(it);
3660 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3665 propagateMetadata(Entry, it);
3669 case Instruction::Store:
3670 case Instruction::Load:
3671 vectorizeMemoryInstruction(it);
3673 case Instruction::ZExt:
3674 case Instruction::SExt:
3675 case Instruction::FPToUI:
3676 case Instruction::FPToSI:
3677 case Instruction::FPExt:
3678 case Instruction::PtrToInt:
3679 case Instruction::IntToPtr:
3680 case Instruction::SIToFP:
3681 case Instruction::UIToFP:
3682 case Instruction::Trunc:
3683 case Instruction::FPTrunc:
3684 case Instruction::BitCast: {
3685 CastInst *CI = dyn_cast<CastInst>(it);
3686 setDebugLocFromInst(Builder, it);
3687 /// Optimize the special case where the source is the induction
3688 /// variable. Notice that we can only optimize the 'trunc' case
3689 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3690 /// c. other casts depend on pointer size.
3691 if (CI->getOperand(0) == OldInduction &&
3692 it->getOpcode() == Instruction::Trunc) {
3693 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3695 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3696 InductionDescriptor II = Legal->getInductionVars()->lookup(OldInduction);
3698 ConstantInt::getSigned(CI->getType(), II.getStepValue()->getSExtValue());
3699 for (unsigned Part = 0; Part < UF; ++Part)
3700 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3701 propagateMetadata(Entry, it);
3704 /// Vectorize casts.
3705 Type *DestTy = (VF == 1) ? CI->getType() :
3706 VectorType::get(CI->getType(), VF);
3708 VectorParts &A = getVectorValue(it->getOperand(0));
3709 for (unsigned Part = 0; Part < UF; ++Part)
3710 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3711 propagateMetadata(Entry, it);
3715 case Instruction::Call: {
3716 // Ignore dbg intrinsics.
3717 if (isa<DbgInfoIntrinsic>(it))
3719 setDebugLocFromInst(Builder, it);
3721 Module *M = BB->getParent()->getParent();
3722 CallInst *CI = cast<CallInst>(it);
3724 StringRef FnName = CI->getCalledFunction()->getName();
3725 Function *F = CI->getCalledFunction();
3726 Type *RetTy = ToVectorTy(CI->getType(), VF);
3727 SmallVector<Type *, 4> Tys;
3728 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3729 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3731 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3733 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3734 ID == Intrinsic::lifetime_start)) {
3735 scalarizeInstruction(it);
3738 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3739 // version of the instruction.
3740 // Is it beneficial to perform intrinsic call compared to lib call?
3741 bool NeedToScalarize;
3742 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3743 bool UseVectorIntrinsic =
3744 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3745 if (!UseVectorIntrinsic && NeedToScalarize) {
3746 scalarizeInstruction(it);
3750 for (unsigned Part = 0; Part < UF; ++Part) {
3751 SmallVector<Value *, 4> Args;
3752 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3753 Value *Arg = CI->getArgOperand(i);
3754 // Some intrinsics have a scalar argument - don't replace it with a
3756 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3757 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3758 Arg = VectorArg[Part];
3760 Args.push_back(Arg);
3764 if (UseVectorIntrinsic) {
3765 // Use vector version of the intrinsic.
3766 Type *TysForDecl[] = {CI->getType()};
3768 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3769 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3771 // Use vector version of the library call.
3772 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3773 assert(!VFnName.empty() && "Vector function name is empty.");
3774 VectorF = M->getFunction(VFnName);
3776 // Generate a declaration
3777 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3779 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3780 VectorF->copyAttributesFrom(F);
3783 assert(VectorF && "Can't create vector function.");
3784 Entry[Part] = Builder.CreateCall(VectorF, Args);
3787 propagateMetadata(Entry, it);
3792 // All other instructions are unsupported. Scalarize them.
3793 scalarizeInstruction(it);
3796 }// end of for_each instr.
3799 void InnerLoopVectorizer::updateAnalysis() {
3800 // Forget the original basic block.
3801 SE->forgetLoop(OrigLoop);
3803 // Update the dominator tree information.
3804 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3805 "Entry does not dominate exit.");
3807 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3808 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3809 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3811 // We don't predicate stores by this point, so the vector body should be a
3813 assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
3814 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3816 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
3817 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3818 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3819 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3821 DEBUG(DT->verifyDomTree());
3824 /// \brief Check whether it is safe to if-convert this phi node.
3826 /// Phi nodes with constant expressions that can trap are not safe to if
3828 static bool canIfConvertPHINodes(BasicBlock *BB) {
3829 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3830 PHINode *Phi = dyn_cast<PHINode>(I);
3833 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3834 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3841 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3842 if (!EnableIfConversion) {
3843 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3847 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3849 // A list of pointers that we can safely read and write to.
3850 SmallPtrSet<Value *, 8> SafePointes;
3852 // Collect safe addresses.
3853 for (Loop::block_iterator BI = TheLoop->block_begin(),
3854 BE = TheLoop->block_end(); BI != BE; ++BI) {
3855 BasicBlock *BB = *BI;
3857 if (blockNeedsPredication(BB))
3860 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3861 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3862 SafePointes.insert(LI->getPointerOperand());
3863 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3864 SafePointes.insert(SI->getPointerOperand());
3868 // Collect the blocks that need predication.
3869 BasicBlock *Header = TheLoop->getHeader();
3870 for (Loop::block_iterator BI = TheLoop->block_begin(),
3871 BE = TheLoop->block_end(); BI != BE; ++BI) {
3872 BasicBlock *BB = *BI;
3874 // We don't support switch statements inside loops.
3875 if (!isa<BranchInst>(BB->getTerminator())) {
3876 emitAnalysis(VectorizationReport(BB->getTerminator())
3877 << "loop contains a switch statement");
3881 // We must be able to predicate all blocks that need to be predicated.
3882 if (blockNeedsPredication(BB)) {
3883 if (!blockCanBePredicated(BB, SafePointes)) {
3884 emitAnalysis(VectorizationReport(BB->getTerminator())
3885 << "control flow cannot be substituted for a select");
3888 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3889 emitAnalysis(VectorizationReport(BB->getTerminator())
3890 << "control flow cannot be substituted for a select");
3895 // We can if-convert this loop.
3899 bool LoopVectorizationLegality::canVectorize() {
3900 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3901 // be canonicalized.
3902 if (!TheLoop->getLoopPreheader()) {
3904 VectorizationReport() <<
3905 "loop control flow is not understood by vectorizer");
3909 // We can only vectorize innermost loops.
3910 if (!TheLoop->empty()) {
3911 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3915 // We must have a single backedge.
3916 if (TheLoop->getNumBackEdges() != 1) {
3918 VectorizationReport() <<
3919 "loop control flow is not understood by vectorizer");
3923 // We must have a single exiting block.
3924 if (!TheLoop->getExitingBlock()) {
3926 VectorizationReport() <<
3927 "loop control flow is not understood by vectorizer");
3931 // We only handle bottom-tested loops, i.e. loop in which the condition is
3932 // checked at the end of each iteration. With that we can assume that all
3933 // instructions in the loop are executed the same number of times.
3934 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3936 VectorizationReport() <<
3937 "loop control flow is not understood by vectorizer");
3941 // We need to have a loop header.
3942 DEBUG(dbgs() << "LV: Found a loop: " <<
3943 TheLoop->getHeader()->getName() << '\n');
3945 // Check if we can if-convert non-single-bb loops.
3946 unsigned NumBlocks = TheLoop->getNumBlocks();
3947 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3948 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3952 // ScalarEvolution needs to be able to find the exit count.
3953 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3954 if (ExitCount == SE->getCouldNotCompute()) {
3955 emitAnalysis(VectorizationReport() <<
3956 "could not determine number of loop iterations");
3957 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3961 // Check if we can vectorize the instructions and CFG in this loop.
3962 if (!canVectorizeInstrs()) {
3963 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3967 // Go over each instruction and look at memory deps.
3968 if (!canVectorizeMemory()) {
3969 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3973 // Collect all of the variables that remain uniform after vectorization.
3974 collectLoopUniforms();
3976 DEBUG(dbgs() << "LV: We can vectorize this loop"
3977 << (LAI->getRuntimePointerChecking()->Need
3978 ? " (with a runtime bound check)"
3982 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
3984 // If an override option has been passed in for interleaved accesses, use it.
3985 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
3986 UseInterleaved = EnableInterleavedMemAccesses;
3988 // Analyze interleaved memory accesses.
3990 InterleaveInfo.analyzeInterleaving(Strides);
3992 // Okay! We can vectorize. At this point we don't have any other mem analysis
3993 // which may limit our maximum vectorization factor, so just return true with
3998 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3999 if (Ty->isPointerTy())
4000 return DL.getIntPtrType(Ty);
4002 // It is possible that char's or short's overflow when we ask for the loop's
4003 // trip count, work around this by changing the type size.
4004 if (Ty->getScalarSizeInBits() < 32)
4005 return Type::getInt32Ty(Ty->getContext());
4010 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4011 Ty0 = convertPointerToIntegerType(DL, Ty0);
4012 Ty1 = convertPointerToIntegerType(DL, Ty1);
4013 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4018 /// \brief Check that the instruction has outside loop users and is not an
4019 /// identified reduction variable.
4020 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4021 SmallPtrSetImpl<Value *> &Reductions) {
4022 // Reduction instructions are allowed to have exit users. All other
4023 // instructions must not have external users.
4024 if (!Reductions.count(Inst))
4025 //Check that all of the users of the loop are inside the BB.
4026 for (User *U : Inst->users()) {
4027 Instruction *UI = cast<Instruction>(U);
4028 // This user may be a reduction exit value.
4029 if (!TheLoop->contains(UI)) {
4030 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4037 bool LoopVectorizationLegality::canVectorizeInstrs() {
4038 BasicBlock *Header = TheLoop->getHeader();
4040 // Look for the attribute signaling the absence of NaNs.
4041 Function &F = *Header->getParent();
4042 const DataLayout &DL = F.getParent()->getDataLayout();
4043 if (F.hasFnAttribute("no-nans-fp-math"))
4045 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4047 // For each block in the loop.
4048 for (Loop::block_iterator bb = TheLoop->block_begin(),
4049 be = TheLoop->block_end(); bb != be; ++bb) {
4051 // Scan the instructions in the block and look for hazards.
4052 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4055 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4056 Type *PhiTy = Phi->getType();
4057 // Check that this PHI type is allowed.
4058 if (!PhiTy->isIntegerTy() &&
4059 !PhiTy->isFloatingPointTy() &&
4060 !PhiTy->isPointerTy()) {
4061 emitAnalysis(VectorizationReport(it)
4062 << "loop control flow is not understood by vectorizer");
4063 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4067 // If this PHINode is not in the header block, then we know that we
4068 // can convert it to select during if-conversion. No need to check if
4069 // the PHIs in this block are induction or reduction variables.
4070 if (*bb != Header) {
4071 // Check that this instruction has no outside users or is an
4072 // identified reduction value with an outside user.
4073 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
4075 emitAnalysis(VectorizationReport(it) <<
4076 "value could not be identified as "
4077 "an induction or reduction variable");
4081 // We only allow if-converted PHIs with exactly two incoming values.
4082 if (Phi->getNumIncomingValues() != 2) {
4083 emitAnalysis(VectorizationReport(it)
4084 << "control flow not understood by vectorizer");
4085 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4089 InductionDescriptor ID;
4090 if (InductionDescriptor::isInductionPHI(Phi, SE, ID)) {
4091 Inductions[Phi] = ID;
4092 // Get the widest type.
4094 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4096 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4098 // Int inductions are special because we only allow one IV.
4099 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4100 ID.getStepValue()->isOne() &&
4101 isa<Constant>(ID.getStartValue()) &&
4102 cast<Constant>(ID.getStartValue())->isNullValue()) {
4103 // Use the phi node with the widest type as induction. Use the last
4104 // one if there are multiple (no good reason for doing this other
4105 // than it is expedient). We've checked that it begins at zero and
4106 // steps by one, so this is a canonical induction variable.
4107 if (!Induction || PhiTy == WidestIndTy)
4111 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4113 // Until we explicitly handle the case of an induction variable with
4114 // an outside loop user we have to give up vectorizing this loop.
4115 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4116 emitAnalysis(VectorizationReport(it) <<
4117 "use of induction value outside of the "
4118 "loop is not handled by vectorizer");
4125 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4127 if (Reductions[Phi].hasUnsafeAlgebra())
4128 Requirements->addUnsafeAlgebraInst(
4129 Reductions[Phi].getUnsafeAlgebraInst());
4130 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4134 emitAnalysis(VectorizationReport(it) <<
4135 "value that could not be identified as "
4136 "reduction is used outside the loop");
4137 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4139 }// end of PHI handling
4141 // We handle calls that:
4142 // * Are debug info intrinsics.
4143 // * Have a mapping to an IR intrinsic.
4144 // * Have a vector version available.
4145 CallInst *CI = dyn_cast<CallInst>(it);
4146 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4147 !(CI->getCalledFunction() && TLI &&
4148 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4149 emitAnalysis(VectorizationReport(it) <<
4150 "call instruction cannot be vectorized");
4151 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4155 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4156 // second argument is the same (i.e. loop invariant)
4158 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4159 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4160 emitAnalysis(VectorizationReport(it)
4161 << "intrinsic instruction cannot be vectorized");
4162 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4167 // Check that the instruction return type is vectorizable.
4168 // Also, we can't vectorize extractelement instructions.
4169 if ((!VectorType::isValidElementType(it->getType()) &&
4170 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4171 emitAnalysis(VectorizationReport(it)
4172 << "instruction return type cannot be vectorized");
4173 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4177 // Check that the stored type is vectorizable.
4178 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4179 Type *T = ST->getValueOperand()->getType();
4180 if (!VectorType::isValidElementType(T)) {
4181 emitAnalysis(VectorizationReport(ST) <<
4182 "store instruction cannot be vectorized");
4185 if (EnableMemAccessVersioning)
4186 collectStridedAccess(ST);
4189 if (EnableMemAccessVersioning)
4190 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4191 collectStridedAccess(LI);
4193 // Reduction instructions are allowed to have exit users.
4194 // All other instructions must not have external users.
4195 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4196 emitAnalysis(VectorizationReport(it) <<
4197 "value cannot be used outside the loop");
4206 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4207 if (Inductions.empty()) {
4208 emitAnalysis(VectorizationReport()
4209 << "loop induction variable could not be identified");
4214 // Now we know the widest induction type, check if our found induction
4215 // is the same size. If it's not, unset it here and InnerLoopVectorizer
4216 // will create another.
4217 if (Induction && WidestIndTy != Induction->getType())
4218 Induction = nullptr;
4223 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4224 Value *Ptr = nullptr;
4225 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4226 Ptr = LI->getPointerOperand();
4227 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4228 Ptr = SI->getPointerOperand();
4232 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4236 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4237 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4238 Strides[Ptr] = Stride;
4239 StrideSet.insert(Stride);
4242 void LoopVectorizationLegality::collectLoopUniforms() {
4243 // We now know that the loop is vectorizable!
4244 // Collect variables that will remain uniform after vectorization.
4245 std::vector<Value*> Worklist;
4246 BasicBlock *Latch = TheLoop->getLoopLatch();
4248 // Start with the conditional branch and walk up the block.
4249 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4251 // Also add all consecutive pointer values; these values will be uniform
4252 // after vectorization (and subsequent cleanup) and, until revectorization is
4253 // supported, all dependencies must also be uniform.
4254 for (Loop::block_iterator B = TheLoop->block_begin(),
4255 BE = TheLoop->block_end(); B != BE; ++B)
4256 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4258 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4259 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4261 while (!Worklist.empty()) {
4262 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4263 Worklist.pop_back();
4265 // Look at instructions inside this loop.
4266 // Stop when reaching PHI nodes.
4267 // TODO: we need to follow values all over the loop, not only in this block.
4268 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4271 // This is a known uniform.
4274 // Insert all operands.
4275 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4279 bool LoopVectorizationLegality::canVectorizeMemory() {
4280 LAI = &LAA->getInfo(TheLoop, Strides);
4281 auto &OptionalReport = LAI->getReport();
4283 emitAnalysis(VectorizationReport(*OptionalReport));
4284 if (!LAI->canVectorizeMemory())
4287 if (LAI->hasStoreToLoopInvariantAddress()) {
4289 VectorizationReport()
4290 << "write to a loop invariant address could not be vectorized");
4291 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4295 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4300 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4301 Value *In0 = const_cast<Value*>(V);
4302 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4306 return Inductions.count(PN);
4309 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4310 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4313 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4314 SmallPtrSetImpl<Value *> &SafePtrs) {
4316 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4317 // Check that we don't have a constant expression that can trap as operand.
4318 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4320 if (Constant *C = dyn_cast<Constant>(*OI))
4324 // We might be able to hoist the load.
4325 if (it->mayReadFromMemory()) {
4326 LoadInst *LI = dyn_cast<LoadInst>(it);
4329 if (!SafePtrs.count(LI->getPointerOperand())) {
4330 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4331 MaskedOp.insert(LI);
4338 // We don't predicate stores at the moment.
4339 if (it->mayWriteToMemory()) {
4340 StoreInst *SI = dyn_cast<StoreInst>(it);
4341 // We only support predication of stores in basic blocks with one
4346 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4347 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4349 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4350 !isSinglePredecessor) {
4351 // Build a masked store if it is legal for the target, otherwise scalarize
4353 bool isLegalMaskedOp =
4354 isLegalMaskedStore(SI->getValueOperand()->getType(),
4355 SI->getPointerOperand());
4356 if (isLegalMaskedOp) {
4358 MaskedOp.insert(SI);
4367 // The instructions below can trap.
4368 switch (it->getOpcode()) {
4370 case Instruction::UDiv:
4371 case Instruction::SDiv:
4372 case Instruction::URem:
4373 case Instruction::SRem:
4381 void InterleavedAccessInfo::collectConstStridedAccesses(
4382 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4383 const ValueToValueMap &Strides) {
4384 // Holds load/store instructions in program order.
4385 SmallVector<Instruction *, 16> AccessList;
4387 for (auto *BB : TheLoop->getBlocks()) {
4388 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4390 for (auto &I : *BB) {
4391 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4393 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4397 AccessList.push_back(&I);
4401 if (AccessList.empty())
4404 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4405 for (auto I : AccessList) {
4406 LoadInst *LI = dyn_cast<LoadInst>(I);
4407 StoreInst *SI = dyn_cast<StoreInst>(I);
4409 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4410 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4412 // The factor of the corresponding interleave group.
4413 unsigned Factor = std::abs(Stride);
4415 // Ignore the access if the factor is too small or too large.
4416 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4419 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4420 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4421 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4423 // An alignment of 0 means target ABI alignment.
4424 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4426 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4428 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4432 // Analyze interleaved accesses and collect them into interleave groups.
4434 // Notice that the vectorization on interleaved groups will change instruction
4435 // orders and may break dependences. But the memory dependence check guarantees
4436 // that there is no overlap between two pointers of different strides, element
4437 // sizes or underlying bases.
4439 // For pointers sharing the same stride, element size and underlying base, no
4440 // need to worry about Read-After-Write dependences and Write-After-Read
4443 // E.g. The RAW dependence: A[i] = a;
4445 // This won't exist as it is a store-load forwarding conflict, which has
4446 // already been checked and forbidden in the dependence check.
4448 // E.g. The WAR dependence: a = A[i]; // (1)
4450 // The store group of (2) is always inserted at or below (2), and the load group
4451 // of (1) is always inserted at or above (1). The dependence is safe.
4452 void InterleavedAccessInfo::analyzeInterleaving(
4453 const ValueToValueMap &Strides) {
4454 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4456 // Holds all the stride accesses.
4457 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4458 collectConstStridedAccesses(StrideAccesses, Strides);
4460 if (StrideAccesses.empty())
4463 // Holds all interleaved store groups temporarily.
4464 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4466 // Search the load-load/write-write pair B-A in bottom-up order and try to
4467 // insert B into the interleave group of A according to 3 rules:
4468 // 1. A and B have the same stride.
4469 // 2. A and B have the same memory object size.
4470 // 3. B belongs to the group according to the distance.
4472 // The bottom-up order can avoid breaking the Write-After-Write dependences
4473 // between two pointers of the same base.
4474 // E.g. A[i] = a; (1)
4477 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4478 // above (1), which guarantees that (1) is always above (2).
4479 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4481 Instruction *A = I->first;
4482 StrideDescriptor DesA = I->second;
4484 InterleaveGroup *Group = getInterleaveGroup(A);
4486 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4487 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4490 if (A->mayWriteToMemory())
4491 StoreGroups.insert(Group);
4493 for (auto II = std::next(I); II != E; ++II) {
4494 Instruction *B = II->first;
4495 StrideDescriptor DesB = II->second;
4497 // Ignore if B is already in a group or B is a different memory operation.
4498 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4501 // Check the rule 1 and 2.
4502 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4505 // Calculate the distance and prepare for the rule 3.
4506 const SCEVConstant *DistToA =
4507 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4511 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4513 // Skip if the distance is not multiple of size as they are not in the
4515 if (DistanceToA % static_cast<int>(DesA.Size))
4518 // The index of B is the index of A plus the related index to A.
4520 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4522 // Try to insert B into the group.
4523 if (Group->insertMember(B, IndexB, DesB.Align)) {
4524 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4525 << " into the interleave group with" << *A << '\n');
4526 InterleaveGroupMap[B] = Group;
4528 // Set the first load in program order as the insert position.
4529 if (B->mayReadFromMemory())
4530 Group->setInsertPos(B);
4532 } // Iteration on instruction B
4533 } // Iteration on instruction A
4535 // Remove interleaved store groups with gaps.
4536 for (InterleaveGroup *Group : StoreGroups)
4537 if (Group->getNumMembers() != Group->getFactor())
4538 releaseGroup(Group);
4541 LoopVectorizationCostModel::VectorizationFactor
4542 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4543 // Width 1 means no vectorize
4544 VectorizationFactor Factor = { 1U, 0U };
4545 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4546 emitAnalysis(VectorizationReport() <<
4547 "runtime pointer checks needed. Enable vectorization of this "
4548 "loop with '#pragma clang loop vectorize(enable)' when "
4549 "compiling with -Os/-Oz");
4551 "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4555 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4556 emitAnalysis(VectorizationReport() <<
4557 "store that is conditionally executed prevents vectorization");
4558 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4562 // Find the trip count.
4563 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4564 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4566 unsigned WidestType = getWidestType();
4567 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4568 unsigned MaxSafeDepDist = -1U;
4569 if (Legal->getMaxSafeDepDistBytes() != -1U)
4570 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4571 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4572 WidestRegister : MaxSafeDepDist);
4573 unsigned MaxVectorSize = WidestRegister / WidestType;
4574 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4575 DEBUG(dbgs() << "LV: The Widest register is: "
4576 << WidestRegister << " bits.\n");
4578 if (MaxVectorSize == 0) {
4579 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4583 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4584 " into one vector!");
4586 unsigned VF = MaxVectorSize;
4588 // If we optimize the program for size, avoid creating the tail loop.
4590 // If we are unable to calculate the trip count then don't try to vectorize.
4593 (VectorizationReport() <<
4594 "unable to calculate the loop count due to complex control flow");
4595 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4599 // Find the maximum SIMD width that can fit within the trip count.
4600 VF = TC % MaxVectorSize;
4605 // If the trip count that we found modulo the vectorization factor is not
4606 // zero then we require a tail.
4607 emitAnalysis(VectorizationReport() <<
4608 "cannot optimize for size and vectorize at the "
4609 "same time. Enable vectorization of this loop "
4610 "with '#pragma clang loop vectorize(enable)' "
4611 "when compiling with -Os/-Oz");
4612 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4617 int UserVF = Hints->getWidth();
4619 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4620 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4622 Factor.Width = UserVF;
4626 float Cost = expectedCost(1);
4628 const float ScalarCost = Cost;
4631 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4633 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4634 // Ignore scalar width, because the user explicitly wants vectorization.
4635 if (ForceVectorization && VF > 1) {
4637 Cost = expectedCost(Width) / (float)Width;
4640 for (unsigned i=2; i <= VF; i*=2) {
4641 // Notice that the vector loop needs to be executed less times, so
4642 // we need to divide the cost of the vector loops by the width of
4643 // the vector elements.
4644 float VectorCost = expectedCost(i) / (float)i;
4645 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4646 (int)VectorCost << ".\n");
4647 if (VectorCost < Cost) {
4653 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4654 << "LV: Vectorization seems to be not beneficial, "
4655 << "but was forced by a user.\n");
4656 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4657 Factor.Width = Width;
4658 Factor.Cost = Width * Cost;
4662 unsigned LoopVectorizationCostModel::getWidestType() {
4663 unsigned MaxWidth = 8;
4664 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4667 for (Loop::block_iterator bb = TheLoop->block_begin(),
4668 be = TheLoop->block_end(); bb != be; ++bb) {
4669 BasicBlock *BB = *bb;
4671 // For each instruction in the loop.
4672 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4673 Type *T = it->getType();
4675 // Skip ignored values.
4676 if (ValuesToIgnore.count(it))
4679 // Only examine Loads, Stores and PHINodes.
4680 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4683 // Examine PHI nodes that are reduction variables. Update the type to
4684 // account for the recurrence type.
4685 if (PHINode *PN = dyn_cast<PHINode>(it)) {
4686 if (!Legal->getReductionVars()->count(PN))
4688 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4689 T = RdxDesc.getRecurrenceType();
4692 // Examine the stored values.
4693 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4694 T = ST->getValueOperand()->getType();
4696 // Ignore loaded pointer types and stored pointer types that are not
4697 // consecutive. However, we do want to take consecutive stores/loads of
4698 // pointer vectors into account.
4699 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4702 MaxWidth = std::max(MaxWidth,
4703 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4710 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4712 unsigned LoopCost) {
4714 // -- The interleave heuristics --
4715 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4716 // There are many micro-architectural considerations that we can't predict
4717 // at this level. For example, frontend pressure (on decode or fetch) due to
4718 // code size, or the number and capabilities of the execution ports.
4720 // We use the following heuristics to select the interleave count:
4721 // 1. If the code has reductions, then we interleave to break the cross
4722 // iteration dependency.
4723 // 2. If the loop is really small, then we interleave to reduce the loop
4725 // 3. We don't interleave if we think that we will spill registers to memory
4726 // due to the increased register pressure.
4728 // When we optimize for size, we don't interleave.
4732 // We used the distance for the interleave count.
4733 if (Legal->getMaxSafeDepDistBytes() != -1U)
4736 // Do not interleave loops with a relatively small trip count.
4737 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4738 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4741 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4742 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4746 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4747 TargetNumRegisters = ForceTargetNumScalarRegs;
4749 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4750 TargetNumRegisters = ForceTargetNumVectorRegs;
4753 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4754 // We divide by these constants so assume that we have at least one
4755 // instruction that uses at least one register.
4756 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4757 R.NumInstructions = std::max(R.NumInstructions, 1U);
4759 // We calculate the interleave count using the following formula.
4760 // Subtract the number of loop invariants from the number of available
4761 // registers. These registers are used by all of the interleaved instances.
4762 // Next, divide the remaining registers by the number of registers that is
4763 // required by the loop, in order to estimate how many parallel instances
4764 // fit without causing spills. All of this is rounded down if necessary to be
4765 // a power of two. We want power of two interleave count to simplify any
4766 // addressing operations or alignment considerations.
4767 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4770 // Don't count the induction variable as interleaved.
4771 if (EnableIndVarRegisterHeur)
4772 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4773 std::max(1U, (R.MaxLocalUsers - 1)));
4775 // Clamp the interleave ranges to reasonable counts.
4776 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4778 // Check if the user has overridden the max.
4780 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4781 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4783 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4784 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4787 // If we did not calculate the cost for VF (because the user selected the VF)
4788 // then we calculate the cost of VF here.
4790 LoopCost = expectedCost(VF);
4792 // Clamp the calculated IC to be between the 1 and the max interleave count
4793 // that the target allows.
4794 if (IC > MaxInterleaveCount)
4795 IC = MaxInterleaveCount;
4799 // Interleave if we vectorized this loop and there is a reduction that could
4800 // benefit from interleaving.
4801 if (VF > 1 && Legal->getReductionVars()->size()) {
4802 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4806 // Note that if we've already vectorized the loop we will have done the
4807 // runtime check and so interleaving won't require further checks.
4808 bool InterleavingRequiresRuntimePointerCheck =
4809 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4811 // We want to interleave small loops in order to reduce the loop overhead and
4812 // potentially expose ILP opportunities.
4813 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4814 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4815 // We assume that the cost overhead is 1 and we use the cost model
4816 // to estimate the cost of the loop and interleave until the cost of the
4817 // loop overhead is about 5% of the cost of the loop.
4819 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4821 // Interleave until store/load ports (estimated by max interleave count) are
4823 unsigned NumStores = Legal->getNumStores();
4824 unsigned NumLoads = Legal->getNumLoads();
4825 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4826 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4828 // If we have a scalar reduction (vector reductions are already dealt with
4829 // by this point), we can increase the critical path length if the loop
4830 // we're interleaving is inside another loop. Limit, by default to 2, so the
4831 // critical path only gets increased by one reduction operation.
4832 if (Legal->getReductionVars()->size() &&
4833 TheLoop->getLoopDepth() > 1) {
4834 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4835 SmallIC = std::min(SmallIC, F);
4836 StoresIC = std::min(StoresIC, F);
4837 LoadsIC = std::min(LoadsIC, F);
4840 if (EnableLoadStoreRuntimeInterleave &&
4841 std::max(StoresIC, LoadsIC) > SmallIC) {
4842 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4843 return std::max(StoresIC, LoadsIC);
4846 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4850 // Interleave if this is a large loop (small loops are already dealt with by
4852 // point) that could benefit from interleaving.
4853 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4854 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4855 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4859 DEBUG(dbgs() << "LV: Not Interleaving.\n");
4863 LoopVectorizationCostModel::RegisterUsage
4864 LoopVectorizationCostModel::calculateRegisterUsage() {
4865 // This function calculates the register usage by measuring the highest number
4866 // of values that are alive at a single location. Obviously, this is a very
4867 // rough estimation. We scan the loop in a topological order in order and
4868 // assign a number to each instruction. We use RPO to ensure that defs are
4869 // met before their users. We assume that each instruction that has in-loop
4870 // users starts an interval. We record every time that an in-loop value is
4871 // used, so we have a list of the first and last occurrences of each
4872 // instruction. Next, we transpose this data structure into a multi map that
4873 // holds the list of intervals that *end* at a specific location. This multi
4874 // map allows us to perform a linear search. We scan the instructions linearly
4875 // and record each time that a new interval starts, by placing it in a set.
4876 // If we find this value in the multi-map then we remove it from the set.
4877 // The max register usage is the maximum size of the set.
4878 // We also search for instructions that are defined outside the loop, but are
4879 // used inside the loop. We need this number separately from the max-interval
4880 // usage number because when we unroll, loop-invariant values do not take
4882 LoopBlocksDFS DFS(TheLoop);
4886 R.NumInstructions = 0;
4888 // Each 'key' in the map opens a new interval. The values
4889 // of the map are the index of the 'last seen' usage of the
4890 // instruction that is the key.
4891 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4892 // Maps instruction to its index.
4893 DenseMap<unsigned, Instruction*> IdxToInstr;
4894 // Marks the end of each interval.
4895 IntervalMap EndPoint;
4896 // Saves the list of instruction indices that are used in the loop.
4897 SmallSet<Instruction*, 8> Ends;
4898 // Saves the list of values that are used in the loop but are
4899 // defined outside the loop, such as arguments and constants.
4900 SmallPtrSet<Value*, 8> LoopInvariants;
4903 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4904 be = DFS.endRPO(); bb != be; ++bb) {
4905 R.NumInstructions += (*bb)->size();
4906 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4908 Instruction *I = it;
4909 IdxToInstr[Index++] = I;
4911 // Save the end location of each USE.
4912 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4913 Value *U = I->getOperand(i);
4914 Instruction *Instr = dyn_cast<Instruction>(U);
4916 // Ignore non-instruction values such as arguments, constants, etc.
4917 if (!Instr) continue;
4919 // If this instruction is outside the loop then record it and continue.
4920 if (!TheLoop->contains(Instr)) {
4921 LoopInvariants.insert(Instr);
4925 // Overwrite previous end points.
4926 EndPoint[Instr] = Index;
4932 // Saves the list of intervals that end with the index in 'key'.
4933 typedef SmallVector<Instruction*, 2> InstrList;
4934 DenseMap<unsigned, InstrList> TransposeEnds;
4936 // Transpose the EndPoints to a list of values that end at each index.
4937 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4939 TransposeEnds[it->second].push_back(it->first);
4941 SmallSet<Instruction*, 8> OpenIntervals;
4942 unsigned MaxUsage = 0;
4945 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4946 for (unsigned int i = 0; i < Index; ++i) {
4947 Instruction *I = IdxToInstr[i];
4948 // Ignore instructions that are never used within the loop.
4949 if (!Ends.count(I)) continue;
4951 // Skip ignored values.
4952 if (ValuesToIgnore.count(I))
4955 // Remove all of the instructions that end at this location.
4956 InstrList &List = TransposeEnds[i];
4957 for (unsigned int j=0, e = List.size(); j < e; ++j)
4958 OpenIntervals.erase(List[j]);
4960 // Count the number of live interals.
4961 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4963 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4964 OpenIntervals.size() << '\n');
4966 // Add the current instruction to the list of open intervals.
4967 OpenIntervals.insert(I);
4970 unsigned Invariant = LoopInvariants.size();
4971 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4972 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4973 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4975 R.LoopInvariantRegs = Invariant;
4976 R.MaxLocalUsers = MaxUsage;
4980 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4984 for (Loop::block_iterator bb = TheLoop->block_begin(),
4985 be = TheLoop->block_end(); bb != be; ++bb) {
4986 unsigned BlockCost = 0;
4987 BasicBlock *BB = *bb;
4989 // For each instruction in the old loop.
4990 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4991 // Skip dbg intrinsics.
4992 if (isa<DbgInfoIntrinsic>(it))
4995 // Skip ignored values.
4996 if (ValuesToIgnore.count(it))
4999 unsigned C = getInstructionCost(it, VF);
5001 // Check if we should override the cost.
5002 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5003 C = ForceTargetInstructionCost;
5006 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5007 VF << " For instruction: " << *it << '\n');
5010 // We assume that if-converted blocks have a 50% chance of being executed.
5011 // When the code is scalar then some of the blocks are avoided due to CF.
5012 // When the code is vectorized we execute all code paths.
5013 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5022 /// \brief Check whether the address computation for a non-consecutive memory
5023 /// access looks like an unlikely candidate for being merged into the indexing
5026 /// We look for a GEP which has one index that is an induction variable and all
5027 /// other indices are loop invariant. If the stride of this access is also
5028 /// within a small bound we decide that this address computation can likely be
5029 /// merged into the addressing mode.
5030 /// In all other cases, we identify the address computation as complex.
5031 static bool isLikelyComplexAddressComputation(Value *Ptr,
5032 LoopVectorizationLegality *Legal,
5033 ScalarEvolution *SE,
5034 const Loop *TheLoop) {
5035 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5039 // We are looking for a gep with all loop invariant indices except for one
5040 // which should be an induction variable.
5041 unsigned NumOperands = Gep->getNumOperands();
5042 for (unsigned i = 1; i < NumOperands; ++i) {
5043 Value *Opd = Gep->getOperand(i);
5044 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5045 !Legal->isInductionVariable(Opd))
5049 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5050 // can likely be merged into the address computation.
5051 unsigned MaxMergeDistance = 64;
5053 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5057 // Check the step is constant.
5058 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5059 // Calculate the pointer stride and check if it is consecutive.
5060 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5064 const APInt &APStepVal = C->getValue()->getValue();
5066 // Huge step value - give up.
5067 if (APStepVal.getBitWidth() > 64)
5070 int64_t StepVal = APStepVal.getSExtValue();
5072 return StepVal > MaxMergeDistance;
5075 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5076 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5082 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5083 // If we know that this instruction will remain uniform, check the cost of
5084 // the scalar version.
5085 if (Legal->isUniformAfterVectorization(I))
5088 Type *RetTy = I->getType();
5089 Type *VectorTy = ToVectorTy(RetTy, VF);
5091 // TODO: We need to estimate the cost of intrinsic calls.
5092 switch (I->getOpcode()) {
5093 case Instruction::GetElementPtr:
5094 // We mark this instruction as zero-cost because the cost of GEPs in
5095 // vectorized code depends on whether the corresponding memory instruction
5096 // is scalarized or not. Therefore, we handle GEPs with the memory
5097 // instruction cost.
5099 case Instruction::Br: {
5100 return TTI.getCFInstrCost(I->getOpcode());
5102 case Instruction::PHI:
5103 //TODO: IF-converted IFs become selects.
5105 case Instruction::Add:
5106 case Instruction::FAdd:
5107 case Instruction::Sub:
5108 case Instruction::FSub:
5109 case Instruction::Mul:
5110 case Instruction::FMul:
5111 case Instruction::UDiv:
5112 case Instruction::SDiv:
5113 case Instruction::FDiv:
5114 case Instruction::URem:
5115 case Instruction::SRem:
5116 case Instruction::FRem:
5117 case Instruction::Shl:
5118 case Instruction::LShr:
5119 case Instruction::AShr:
5120 case Instruction::And:
5121 case Instruction::Or:
5122 case Instruction::Xor: {
5123 // Since we will replace the stride by 1 the multiplication should go away.
5124 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5126 // Certain instructions can be cheaper to vectorize if they have a constant
5127 // second vector operand. One example of this are shifts on x86.
5128 TargetTransformInfo::OperandValueKind Op1VK =
5129 TargetTransformInfo::OK_AnyValue;
5130 TargetTransformInfo::OperandValueKind Op2VK =
5131 TargetTransformInfo::OK_AnyValue;
5132 TargetTransformInfo::OperandValueProperties Op1VP =
5133 TargetTransformInfo::OP_None;
5134 TargetTransformInfo::OperandValueProperties Op2VP =
5135 TargetTransformInfo::OP_None;
5136 Value *Op2 = I->getOperand(1);
5138 // Check for a splat of a constant or for a non uniform vector of constants.
5139 if (isa<ConstantInt>(Op2)) {
5140 ConstantInt *CInt = cast<ConstantInt>(Op2);
5141 if (CInt && CInt->getValue().isPowerOf2())
5142 Op2VP = TargetTransformInfo::OP_PowerOf2;
5143 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5144 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5145 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5146 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5148 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5149 if (CInt && CInt->getValue().isPowerOf2())
5150 Op2VP = TargetTransformInfo::OP_PowerOf2;
5151 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5155 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5158 case Instruction::Select: {
5159 SelectInst *SI = cast<SelectInst>(I);
5160 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5161 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5162 Type *CondTy = SI->getCondition()->getType();
5164 CondTy = VectorType::get(CondTy, VF);
5166 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5168 case Instruction::ICmp:
5169 case Instruction::FCmp: {
5170 Type *ValTy = I->getOperand(0)->getType();
5171 VectorTy = ToVectorTy(ValTy, VF);
5172 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5174 case Instruction::Store:
5175 case Instruction::Load: {
5176 StoreInst *SI = dyn_cast<StoreInst>(I);
5177 LoadInst *LI = dyn_cast<LoadInst>(I);
5178 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5180 VectorTy = ToVectorTy(ValTy, VF);
5182 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5183 unsigned AS = SI ? SI->getPointerAddressSpace() :
5184 LI->getPointerAddressSpace();
5185 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5186 // We add the cost of address computation here instead of with the gep
5187 // instruction because only here we know whether the operation is
5190 return TTI.getAddressComputationCost(VectorTy) +
5191 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5193 // For an interleaved access, calculate the total cost of the whole
5194 // interleave group.
5195 if (Legal->isAccessInterleaved(I)) {
5196 auto Group = Legal->getInterleavedAccessGroup(I);
5197 assert(Group && "Fail to get an interleaved access group.");
5199 // Only calculate the cost once at the insert position.
5200 if (Group->getInsertPos() != I)
5203 unsigned InterleaveFactor = Group->getFactor();
5205 VectorType::get(VectorTy->getVectorElementType(),
5206 VectorTy->getVectorNumElements() * InterleaveFactor);
5208 // Holds the indices of existing members in an interleaved load group.
5209 // An interleaved store group doesn't need this as it dones't allow gaps.
5210 SmallVector<unsigned, 4> Indices;
5212 for (unsigned i = 0; i < InterleaveFactor; i++)
5213 if (Group->getMember(i))
5214 Indices.push_back(i);
5217 // Calculate the cost of the whole interleaved group.
5218 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5219 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5220 Group->getAlignment(), AS);
5222 if (Group->isReverse())
5224 Group->getNumMembers() *
5225 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5227 // FIXME: The interleaved load group with a huge gap could be even more
5228 // expensive than scalar operations. Then we could ignore such group and
5229 // use scalar operations instead.
5233 // Scalarized loads/stores.
5234 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5235 bool Reverse = ConsecutiveStride < 0;
5236 const DataLayout &DL = I->getModule()->getDataLayout();
5237 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5238 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5239 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5240 bool IsComplexComputation =
5241 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5243 // The cost of extracting from the value vector and pointer vector.
5244 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5245 for (unsigned i = 0; i < VF; ++i) {
5246 // The cost of extracting the pointer operand.
5247 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5248 // In case of STORE, the cost of ExtractElement from the vector.
5249 // In case of LOAD, the cost of InsertElement into the returned
5251 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5252 Instruction::InsertElement,
5256 // The cost of the scalar loads/stores.
5257 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5258 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5263 // Wide load/stores.
5264 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5265 if (Legal->isMaskRequired(I))
5266 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5269 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5272 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5276 case Instruction::ZExt:
5277 case Instruction::SExt:
5278 case Instruction::FPToUI:
5279 case Instruction::FPToSI:
5280 case Instruction::FPExt:
5281 case Instruction::PtrToInt:
5282 case Instruction::IntToPtr:
5283 case Instruction::SIToFP:
5284 case Instruction::UIToFP:
5285 case Instruction::Trunc:
5286 case Instruction::FPTrunc:
5287 case Instruction::BitCast: {
5288 // We optimize the truncation of induction variable.
5289 // The cost of these is the same as the scalar operation.
5290 if (I->getOpcode() == Instruction::Trunc &&
5291 Legal->isInductionVariable(I->getOperand(0)))
5292 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5293 I->getOperand(0)->getType());
5295 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5296 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5298 case Instruction::Call: {
5299 bool NeedToScalarize;
5300 CallInst *CI = cast<CallInst>(I);
5301 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5302 if (getIntrinsicIDForCall(CI, TLI))
5303 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5307 // We are scalarizing the instruction. Return the cost of the scalar
5308 // instruction, plus the cost of insert and extract into vector
5309 // elements, times the vector width.
5312 if (!RetTy->isVoidTy() && VF != 1) {
5313 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5315 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5318 // The cost of inserting the results plus extracting each one of the
5320 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5323 // The cost of executing VF copies of the scalar instruction. This opcode
5324 // is unknown. Assume that it is the same as 'mul'.
5325 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5331 char LoopVectorize::ID = 0;
5332 static const char lv_name[] = "Loop Vectorization";
5333 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5334 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5335 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
5336 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5337 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
5338 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5339 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5340 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5341 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5342 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5343 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5344 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5345 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5346 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5349 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5350 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5354 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5355 // Check for a store.
5356 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5357 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5359 // Check for a load.
5360 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5361 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5367 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5368 bool IfPredicateStore) {
5369 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5370 // Holds vector parameters or scalars, in case of uniform vals.
5371 SmallVector<VectorParts, 4> Params;
5373 setDebugLocFromInst(Builder, Instr);
5375 // Find all of the vectorized parameters.
5376 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5377 Value *SrcOp = Instr->getOperand(op);
5379 // If we are accessing the old induction variable, use the new one.
5380 if (SrcOp == OldInduction) {
5381 Params.push_back(getVectorValue(SrcOp));
5385 // Try using previously calculated values.
5386 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5388 // If the src is an instruction that appeared earlier in the basic block
5389 // then it should already be vectorized.
5390 if (SrcInst && OrigLoop->contains(SrcInst)) {
5391 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5392 // The parameter is a vector value from earlier.
5393 Params.push_back(WidenMap.get(SrcInst));
5395 // The parameter is a scalar from outside the loop. Maybe even a constant.
5396 VectorParts Scalars;
5397 Scalars.append(UF, SrcOp);
5398 Params.push_back(Scalars);
5402 assert(Params.size() == Instr->getNumOperands() &&
5403 "Invalid number of operands");
5405 // Does this instruction return a value ?
5406 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5408 Value *UndefVec = IsVoidRetTy ? nullptr :
5409 UndefValue::get(Instr->getType());
5410 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5411 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5414 if (IfPredicateStore) {
5415 assert(Instr->getParent()->getSinglePredecessor() &&
5416 "Only support single predecessor blocks");
5417 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5418 Instr->getParent());
5421 // For each vector unroll 'part':
5422 for (unsigned Part = 0; Part < UF; ++Part) {
5423 // For each scalar that we create:
5425 // Start an "if (pred) a[i] = ..." block.
5426 Value *Cmp = nullptr;
5427 if (IfPredicateStore) {
5428 if (Cond[Part]->getType()->isVectorTy())
5430 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5431 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5432 ConstantInt::get(Cond[Part]->getType(), 1));
5435 Instruction *Cloned = Instr->clone();
5437 Cloned->setName(Instr->getName() + ".cloned");
5438 // Replace the operands of the cloned instructions with extracted scalars.
5439 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5440 Value *Op = Params[op][Part];
5441 Cloned->setOperand(op, Op);
5444 // Place the cloned scalar in the new loop.
5445 Builder.Insert(Cloned);
5447 // If the original scalar returns a value we need to place it in a vector
5448 // so that future users will be able to use it.
5450 VecResults[Part] = Cloned;
5453 if (IfPredicateStore)
5454 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
5459 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5460 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5461 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5463 return scalarizeInstruction(Instr, IfPredicateStore);
5466 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5470 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5474 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5475 // When unrolling and the VF is 1, we only need to add a simple scalar.
5476 Type *ITy = Val->getType();
5477 assert(!ITy->isVectorTy() && "Val must be a scalar");
5478 Constant *C = ConstantInt::get(ITy, StartIdx);
5479 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");