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/AliasSetTracker.h"
62 #include "llvm/Analysis/AssumptionCache.h"
63 #include "llvm/Analysis/BlockFrequencyInfo.h"
64 #include "llvm/Analysis/CodeMetrics.h"
65 #include "llvm/Analysis/LoopAccessAnalysis.h"
66 #include "llvm/Analysis/LoopInfo.h"
67 #include "llvm/Analysis/LoopIterator.h"
68 #include "llvm/Analysis/LoopPass.h"
69 #include "llvm/Analysis/ScalarEvolution.h"
70 #include "llvm/Analysis/ScalarEvolutionExpander.h"
71 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
72 #include "llvm/Analysis/TargetTransformInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfo.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/DiagnosticInfo.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/IRBuilder.h"
82 #include "llvm/IR/Instructions.h"
83 #include "llvm/IR/IntrinsicInst.h"
84 #include "llvm/IR/LLVMContext.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/Value.h"
89 #include "llvm/IR/ValueHandle.h"
90 #include "llvm/IR/Verifier.h"
91 #include "llvm/Pass.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/CommandLine.h"
94 #include "llvm/Support/Debug.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Transforms/Scalar.h"
97 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
98 #include "llvm/Transforms/Utils/Local.h"
99 #include "llvm/Analysis/VectorUtils.h"
100 #include "llvm/Transforms/Utils/LoopUtils.h"
105 using namespace llvm;
106 using namespace llvm::PatternMatch;
108 #define LV_NAME "loop-vectorize"
109 #define DEBUG_TYPE LV_NAME
111 STATISTIC(LoopsVectorized, "Number of loops vectorized");
112 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
115 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
116 cl::desc("Enable if-conversion during vectorization."));
118 /// We don't vectorize loops with a known constant trip count below this number.
119 static cl::opt<unsigned>
120 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
122 cl::desc("Don't vectorize loops with a constant "
123 "trip count that is smaller than this "
126 /// This enables versioning on the strides of symbolically striding memory
127 /// accesses in code like the following.
128 /// for (i = 0; i < N; ++i)
129 /// A[i * Stride1] += B[i * Stride2] ...
131 /// Will be roughly translated to
132 /// if (Stride1 == 1 && Stride2 == 1) {
133 /// for (i = 0; i < N; i+=4)
137 static cl::opt<bool> EnableMemAccessVersioning(
138 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
139 cl::desc("Enable symblic stride memory access versioning"));
141 static cl::opt<bool> EnableInterleavedMemAccesses(
142 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
143 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
145 /// Maximum factor for an interleaved memory access.
146 static cl::opt<unsigned> MaxInterleaveGroupFactor(
147 "max-interleave-group-factor", cl::Hidden,
148 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
151 /// We don't unroll loops with a known constant trip count below this number.
152 static const unsigned TinyTripCountUnrollThreshold = 128;
154 static cl::opt<unsigned> ForceTargetNumScalarRegs(
155 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
156 cl::desc("A flag that overrides the target's number of scalar registers."));
158 static cl::opt<unsigned> ForceTargetNumVectorRegs(
159 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
160 cl::desc("A flag that overrides the target's number of vector registers."));
162 /// Maximum vectorization interleave count.
163 static const unsigned MaxInterleaveFactor = 16;
165 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
166 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
167 cl::desc("A flag that overrides the target's max interleave factor for "
170 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
171 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
172 cl::desc("A flag that overrides the target's max interleave factor for "
173 "vectorized loops."));
175 static cl::opt<unsigned> ForceTargetInstructionCost(
176 "force-target-instruction-cost", cl::init(0), cl::Hidden,
177 cl::desc("A flag that overrides the target's expected cost for "
178 "an instruction to a single constant value. Mostly "
179 "useful for getting consistent testing."));
181 static cl::opt<unsigned> SmallLoopCost(
182 "small-loop-cost", cl::init(20), cl::Hidden,
183 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
185 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
186 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
187 cl::desc("Enable the use of the block frequency analysis to access PGO "
188 "heuristics minimizing code growth in cold regions and being more "
189 "aggressive in hot regions."));
191 // Runtime unroll loops for load/store throughput.
192 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
193 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
194 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
196 /// The number of stores in a loop that are allowed to need predication.
197 static cl::opt<unsigned> NumberOfStoresToPredicate(
198 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
199 cl::desc("Max number of stores to be predicated behind an if."));
201 static cl::opt<bool> EnableIndVarRegisterHeur(
202 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
203 cl::desc("Count the induction variable only once when unrolling"));
205 static cl::opt<bool> EnableCondStoresVectorization(
206 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
207 cl::desc("Enable if predication of stores during vectorization."));
209 static cl::opt<unsigned> MaxNestedScalarReductionUF(
210 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
211 cl::desc("The maximum unroll factor to use when unrolling a scalar "
212 "reduction in a nested loop."));
216 // Forward declarations.
217 class LoopVectorizationLegality;
218 class LoopVectorizationCostModel;
219 class LoopVectorizeHints;
221 /// \brief This modifies LoopAccessReport to initialize message with
222 /// loop-vectorizer-specific part.
223 class VectorizationReport : public LoopAccessReport {
225 VectorizationReport(Instruction *I = nullptr)
226 : LoopAccessReport("loop not vectorized: ", I) {}
228 /// \brief This allows promotion of the loop-access analysis report into the
229 /// loop-vectorizer report. It modifies the message to add the
230 /// loop-vectorizer-specific part of the message.
231 explicit VectorizationReport(const LoopAccessReport &R)
232 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
236 /// A helper function for converting Scalar types to vector types.
237 /// If the incoming type is void, we return void. If the VF is 1, we return
239 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
240 if (Scalar->isVoidTy() || VF == 1)
242 return VectorType::get(Scalar, VF);
245 /// InnerLoopVectorizer vectorizes loops which contain only one basic
246 /// block to a specified vectorization factor (VF).
247 /// This class performs the widening of scalars into vectors, or multiple
248 /// scalars. This class also implements the following features:
249 /// * It inserts an epilogue loop for handling loops that don't have iteration
250 /// counts that are known to be a multiple of the vectorization factor.
251 /// * It handles the code generation for reduction variables.
252 /// * Scalarization (implementation using scalars) of un-vectorizable
254 /// InnerLoopVectorizer does not perform any vectorization-legality
255 /// checks, and relies on the caller to check for the different legality
256 /// aspects. The InnerLoopVectorizer relies on the
257 /// LoopVectorizationLegality class to provide information about the induction
258 /// and reduction variables that were found to a given vectorization factor.
259 class InnerLoopVectorizer {
261 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
262 DominatorTree *DT, const TargetLibraryInfo *TLI,
263 const TargetTransformInfo *TTI, unsigned VecWidth,
264 unsigned UnrollFactor)
265 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
266 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
267 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
268 Legal(nullptr), AddedSafetyChecks(false) {}
270 // Perform the actual loop widening (vectorization).
271 void vectorize(LoopVectorizationLegality *L) {
273 // Create a new empty loop. Unlink the old loop and connect the new one.
275 // Widen each instruction in the old loop to a new one in the new loop.
276 // Use the Legality module to find the induction and reduction variables.
278 // Register the new loop and update the analysis passes.
282 // Return true if any runtime check is added.
283 bool IsSafetyChecksAdded() {
284 return AddedSafetyChecks;
287 virtual ~InnerLoopVectorizer() {}
290 /// A small list of PHINodes.
291 typedef SmallVector<PHINode*, 4> PhiVector;
292 /// When we unroll loops we have multiple vector values for each scalar.
293 /// This data structure holds the unrolled and vectorized values that
294 /// originated from one scalar instruction.
295 typedef SmallVector<Value*, 2> VectorParts;
297 // When we if-convert we need to create edge masks. We have to cache values
298 // so that we don't end up with exponential recursion/IR.
299 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
300 VectorParts> EdgeMaskCache;
302 /// \brief Add checks for strides that were assumed to be 1.
304 /// Returns the last check instruction and the first check instruction in the
305 /// pair as (first, last).
306 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
308 /// Create an empty loop, based on the loop ranges of the old loop.
309 void createEmptyLoop();
310 /// Copy and widen the instructions from the old loop.
311 virtual void vectorizeLoop();
313 /// \brief The Loop exit block may have single value PHI nodes where the
314 /// incoming value is 'Undef'. While vectorizing we only handled real values
315 /// that were defined inside the loop. Here we fix the 'undef case'.
319 /// A helper function that computes the predicate of the block BB, assuming
320 /// that the header block of the loop is set to True. It returns the *entry*
321 /// mask for the block BB.
322 VectorParts createBlockInMask(BasicBlock *BB);
323 /// A helper function that computes the predicate of the edge between SRC
325 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
327 /// A helper function to vectorize a single BB within the innermost loop.
328 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
330 /// Vectorize a single PHINode in a block. This method handles the induction
331 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
332 /// arbitrary length vectors.
333 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
334 unsigned UF, unsigned VF, PhiVector *PV);
336 /// Insert the new loop to the loop hierarchy and pass manager
337 /// and update the analysis passes.
338 void updateAnalysis();
340 /// This instruction is un-vectorizable. Implement it as a sequence
341 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
342 /// scalarized instruction behind an if block predicated on the control
343 /// dependence of the instruction.
344 virtual void scalarizeInstruction(Instruction *Instr,
345 bool IfPredicateStore=false);
347 /// Vectorize Load and Store instructions,
348 virtual void vectorizeMemoryInstruction(Instruction *Instr);
350 /// Create a broadcast instruction. This method generates a broadcast
351 /// instruction (shuffle) for loop invariant values and for the induction
352 /// value. If this is the induction variable then we extend it to N, N+1, ...
353 /// this is needed because each iteration in the loop corresponds to a SIMD
355 virtual Value *getBroadcastInstrs(Value *V);
357 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
358 /// to each vector element of Val. The sequence starts at StartIndex.
359 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
361 /// When we go over instructions in the basic block we rely on previous
362 /// values within the current basic block or on loop invariant values.
363 /// When we widen (vectorize) values we place them in the map. If the values
364 /// are not within the map, they have to be loop invariant, so we simply
365 /// broadcast them into a vector.
366 VectorParts &getVectorValue(Value *V);
368 /// Try to vectorize the interleaved access group that \p Instr belongs to.
369 void vectorizeInterleaveGroup(Instruction *Instr);
371 /// Generate a shuffle sequence that will reverse the vector Vec.
372 virtual Value *reverseVector(Value *Vec);
374 /// This is a helper class that holds the vectorizer state. It maps scalar
375 /// instructions to vector instructions. When the code is 'unrolled' then
376 /// then a single scalar value is mapped to multiple vector parts. The parts
377 /// are stored in the VectorPart type.
379 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
381 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
383 /// \return True if 'Key' is saved in the Value Map.
384 bool has(Value *Key) const { return MapStorage.count(Key); }
386 /// Initializes a new entry in the map. Sets all of the vector parts to the
387 /// save value in 'Val'.
388 /// \return A reference to a vector with splat values.
389 VectorParts &splat(Value *Key, Value *Val) {
390 VectorParts &Entry = MapStorage[Key];
391 Entry.assign(UF, Val);
395 ///\return A reference to the value that is stored at 'Key'.
396 VectorParts &get(Value *Key) {
397 VectorParts &Entry = MapStorage[Key];
400 assert(Entry.size() == UF);
405 /// The unroll factor. Each entry in the map stores this number of vector
409 /// Map storage. We use std::map and not DenseMap because insertions to a
410 /// dense map invalidates its iterators.
411 std::map<Value *, VectorParts> MapStorage;
414 /// The original loop.
416 /// Scev analysis to use.
424 /// Target Library Info.
425 const TargetLibraryInfo *TLI;
426 /// Target Transform Info.
427 const TargetTransformInfo *TTI;
429 /// The vectorization SIMD factor to use. Each vector will have this many
434 /// The vectorization unroll factor to use. Each scalar is vectorized to this
435 /// many different vector instructions.
438 /// The builder that we use
441 // --- Vectorization state ---
443 /// The vector-loop preheader.
444 BasicBlock *LoopVectorPreHeader;
445 /// The scalar-loop preheader.
446 BasicBlock *LoopScalarPreHeader;
447 /// Middle Block between the vector and the scalar.
448 BasicBlock *LoopMiddleBlock;
449 ///The ExitBlock of the scalar loop.
450 BasicBlock *LoopExitBlock;
451 ///The vector loop body.
452 SmallVector<BasicBlock *, 4> LoopVectorBody;
453 ///The scalar loop body.
454 BasicBlock *LoopScalarBody;
455 /// A list of all bypass blocks. The first block is the entry of the loop.
456 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
458 /// The new Induction variable which was added to the new block.
460 /// The induction variable of the old basic block.
461 PHINode *OldInduction;
462 /// Holds the extended (to the widest induction type) start index.
464 /// Maps scalars to widened vectors.
466 EdgeMaskCache MaskCache;
468 LoopVectorizationLegality *Legal;
470 // Record whether runtime check is added.
471 bool AddedSafetyChecks;
474 class InnerLoopUnroller : public InnerLoopVectorizer {
476 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
477 DominatorTree *DT, const TargetLibraryInfo *TLI,
478 const TargetTransformInfo *TTI, unsigned UnrollFactor)
479 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
482 void scalarizeInstruction(Instruction *Instr,
483 bool IfPredicateStore = false) override;
484 void vectorizeMemoryInstruction(Instruction *Instr) override;
485 Value *getBroadcastInstrs(Value *V) override;
486 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
487 Value *reverseVector(Value *Vec) override;
490 /// \brief Look for a meaningful debug location on the instruction or it's
492 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
497 if (I->getDebugLoc() != Empty)
500 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
501 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
502 if (OpInst->getDebugLoc() != Empty)
509 /// \brief Set the debug location in the builder using the debug location in the
511 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
512 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
513 B.SetCurrentDebugLocation(Inst->getDebugLoc());
515 B.SetCurrentDebugLocation(DebugLoc());
519 /// \return string containing a file name and a line # for the given loop.
520 static std::string getDebugLocString(const Loop *L) {
523 raw_string_ostream OS(Result);
524 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
525 LoopDbgLoc.print(OS);
527 // Just print the module name.
528 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
535 /// \brief Propagate known metadata from one instruction to another.
536 static void propagateMetadata(Instruction *To, const Instruction *From) {
537 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
538 From->getAllMetadataOtherThanDebugLoc(Metadata);
540 for (auto M : Metadata) {
541 unsigned Kind = M.first;
543 // These are safe to transfer (this is safe for TBAA, even when we
544 // if-convert, because should that metadata have had a control dependency
545 // on the condition, and thus actually aliased with some other
546 // non-speculated memory access when the condition was false, this would be
547 // caught by the runtime overlap checks).
548 if (Kind != LLVMContext::MD_tbaa &&
549 Kind != LLVMContext::MD_alias_scope &&
550 Kind != LLVMContext::MD_noalias &&
551 Kind != LLVMContext::MD_fpmath)
554 To->setMetadata(Kind, M.second);
558 /// \brief Propagate known metadata from one instruction to a vector of others.
559 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
561 if (Instruction *I = dyn_cast<Instruction>(V))
562 propagateMetadata(I, From);
565 /// \brief The group of interleaved loads/stores sharing the same stride and
566 /// close to each other.
568 /// Each member in this group has an index starting from 0, and the largest
569 /// index should be less than interleaved factor, which is equal to the absolute
570 /// value of the access's stride.
572 /// E.g. An interleaved load group of factor 4:
573 /// for (unsigned i = 0; i < 1024; i+=4) {
574 /// a = A[i]; // Member of index 0
575 /// b = A[i+1]; // Member of index 1
576 /// d = A[i+3]; // Member of index 3
580 /// An interleaved store group of factor 4:
581 /// for (unsigned i = 0; i < 1024; i+=4) {
583 /// A[i] = a; // Member of index 0
584 /// A[i+1] = b; // Member of index 1
585 /// A[i+2] = c; // Member of index 2
586 /// A[i+3] = d; // Member of index 3
589 /// Note: the interleaved load group could have gaps (missing members), but
590 /// the interleaved store group doesn't allow gaps.
591 class InterleaveGroup {
593 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
594 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
595 assert(Align && "The alignment should be non-zero");
597 Factor = std::abs(Stride);
598 assert(Factor > 1 && "Invalid interleave factor");
600 Reverse = Stride < 0;
604 bool isReverse() const { return Reverse; }
605 unsigned getFactor() const { return Factor; }
606 unsigned getAlignment() const { return Align; }
607 unsigned getNumMembers() const { return Members.size(); }
609 /// \brief Try to insert a new member \p Instr with index \p Index and
610 /// alignment \p NewAlign. The index is related to the leader and it could be
611 /// negative if it is the new leader.
613 /// \returns false if the instruction doesn't belong to the group.
614 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
615 assert(NewAlign && "The new member's alignment should be non-zero");
617 int Key = Index + SmallestKey;
619 // Skip if there is already a member with the same index.
620 if (Members.count(Key))
623 if (Key > LargestKey) {
624 // The largest index is always less than the interleave factor.
625 if (Index >= static_cast<int>(Factor))
629 } else if (Key < SmallestKey) {
630 // The largest index is always less than the interleave factor.
631 if (LargestKey - Key >= static_cast<int>(Factor))
637 // It's always safe to select the minimum alignment.
638 Align = std::min(Align, NewAlign);
639 Members[Key] = Instr;
643 /// \brief Get the member with the given index \p Index
645 /// \returns nullptr if contains no such member.
646 Instruction *getMember(unsigned Index) const {
647 int Key = SmallestKey + Index;
648 if (!Members.count(Key))
651 return Members.find(Key)->second;
654 /// \brief Get the index for the given member. Unlike the key in the member
655 /// map, the index starts from 0.
656 unsigned getIndex(Instruction *Instr) const {
657 for (auto I : Members)
658 if (I.second == Instr)
659 return I.first - SmallestKey;
661 llvm_unreachable("InterleaveGroup contains no such member");
664 Instruction *getInsertPos() const { return InsertPos; }
665 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
668 unsigned Factor; // Interleave Factor.
671 DenseMap<int, Instruction *> Members;
675 // To avoid breaking dependences, vectorized instructions of an interleave
676 // group should be inserted at either the first load or the last store in
679 // E.g. %even = load i32 // Insert Position
680 // %add = add i32 %even // Use of %even
684 // %odd = add i32 // Def of %odd
685 // store i32 %odd // Insert Position
686 Instruction *InsertPos;
689 /// \brief Drive the analysis of interleaved memory accesses in the loop.
691 /// Use this class to analyze interleaved accesses only when we can vectorize
692 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
693 /// on interleaved accesses is unsafe.
695 /// The analysis collects interleave groups and records the relationships
696 /// between the member and the group in a map.
697 class InterleavedAccessInfo {
699 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
700 : SE(SE), TheLoop(L), DT(DT) {}
702 ~InterleavedAccessInfo() {
703 SmallSet<InterleaveGroup *, 4> DelSet;
704 // Avoid releasing a pointer twice.
705 for (auto &I : InterleaveGroupMap)
706 DelSet.insert(I.second);
707 for (auto *Ptr : DelSet)
711 /// \brief Analyze the interleaved accesses and collect them in interleave
712 /// groups. Substitute symbolic strides using \p Strides.
713 void analyzeInterleaving(const ValueToValueMap &Strides);
715 /// \brief Check if \p Instr belongs to any interleave group.
716 bool isInterleaved(Instruction *Instr) const {
717 return InterleaveGroupMap.count(Instr);
720 /// \brief Get the interleave group that \p Instr belongs to.
722 /// \returns nullptr if doesn't have such group.
723 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
724 if (InterleaveGroupMap.count(Instr))
725 return InterleaveGroupMap.find(Instr)->second;
734 /// Holds the relationships between the members and the interleave group.
735 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
737 /// \brief The descriptor for a strided memory access.
738 struct StrideDescriptor {
739 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
741 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
743 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
745 int Stride; // The access's stride. It is negative for a reverse access.
746 const SCEV *Scev; // The scalar expression of this access
747 unsigned Size; // The size of the memory object.
748 unsigned Align; // The alignment of this access.
751 /// \brief Create a new interleave group with the given instruction \p Instr,
752 /// stride \p Stride and alignment \p Align.
754 /// \returns the newly created interleave group.
755 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
757 assert(!InterleaveGroupMap.count(Instr) &&
758 "Already in an interleaved access group");
759 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
760 return InterleaveGroupMap[Instr];
763 /// \brief Release the group and remove all the relationships.
764 void releaseGroup(InterleaveGroup *Group) {
765 for (unsigned i = 0; i < Group->getFactor(); i++)
766 if (Instruction *Member = Group->getMember(i))
767 InterleaveGroupMap.erase(Member);
772 /// \brief Collect all the accesses with a constant stride in program order.
773 void collectConstStridedAccesses(
774 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
775 const ValueToValueMap &Strides);
778 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
779 /// to what vectorization factor.
780 /// This class does not look at the profitability of vectorization, only the
781 /// legality. This class has two main kinds of checks:
782 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
783 /// will change the order of memory accesses in a way that will change the
784 /// correctness of the program.
785 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
786 /// checks for a number of different conditions, such as the availability of a
787 /// single induction variable, that all types are supported and vectorize-able,
788 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
789 /// This class is also used by InnerLoopVectorizer for identifying
790 /// induction variable and the different reduction variables.
791 class LoopVectorizationLegality {
793 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
794 TargetLibraryInfo *TLI, AliasAnalysis *AA,
795 Function *F, const TargetTransformInfo *TTI,
796 LoopAccessAnalysis *LAA)
797 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
798 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
799 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false) {}
801 /// This enum represents the kinds of inductions that we support.
803 IK_NoInduction, ///< Not an induction variable.
804 IK_IntInduction, ///< Integer induction variable. Step = C.
805 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
808 /// A struct for saving information about induction variables.
809 struct InductionInfo {
810 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
811 : StartValue(Start), IK(K), StepValue(Step) {
812 assert(IK != IK_NoInduction && "Not an induction");
813 assert(StartValue && "StartValue is null");
814 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
815 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
816 "StartValue is not a pointer for pointer induction");
817 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
818 "StartValue is not an integer for integer induction");
819 assert(StepValue->getType()->isIntegerTy() &&
820 "StepValue is not an integer");
823 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
825 /// Get the consecutive direction. Returns:
826 /// 0 - unknown or non-consecutive.
827 /// 1 - consecutive and increasing.
828 /// -1 - consecutive and decreasing.
829 int getConsecutiveDirection() const {
830 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
831 return StepValue->getSExtValue();
835 /// Compute the transformed value of Index at offset StartValue using step
837 /// For integer induction, returns StartValue + Index * StepValue.
838 /// For pointer induction, returns StartValue[Index * StepValue].
839 /// FIXME: The newly created binary instructions should contain nsw/nuw
840 /// flags, which can be found from the original scalar operations.
841 Value *transform(IRBuilder<> &B, Value *Index) const {
843 case IK_IntInduction:
844 assert(Index->getType() == StartValue->getType() &&
845 "Index type does not match StartValue type");
846 if (StepValue->isMinusOne())
847 return B.CreateSub(StartValue, Index);
848 if (!StepValue->isOne())
849 Index = B.CreateMul(Index, StepValue);
850 return B.CreateAdd(StartValue, Index);
852 case IK_PtrInduction:
853 assert(Index->getType() == StepValue->getType() &&
854 "Index type does not match StepValue type");
855 if (StepValue->isMinusOne())
856 Index = B.CreateNeg(Index);
857 else if (!StepValue->isOne())
858 Index = B.CreateMul(Index, StepValue);
859 return B.CreateGEP(nullptr, StartValue, Index);
864 llvm_unreachable("invalid enum");
868 TrackingVH<Value> StartValue;
872 ConstantInt *StepValue;
875 /// ReductionList contains the reduction descriptors for all
876 /// of the reductions that were found in the loop.
877 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
879 /// InductionList saves induction variables and maps them to the
880 /// induction descriptor.
881 typedef MapVector<PHINode*, InductionInfo> InductionList;
883 /// Returns true if it is legal to vectorize this loop.
884 /// This does not mean that it is profitable to vectorize this
885 /// loop, only that it is legal to do so.
888 /// Returns the Induction variable.
889 PHINode *getInduction() { return Induction; }
891 /// Returns the reduction variables found in the loop.
892 ReductionList *getReductionVars() { return &Reductions; }
894 /// Returns the induction variables found in the loop.
895 InductionList *getInductionVars() { return &Inductions; }
897 /// Returns the widest induction type.
898 Type *getWidestInductionType() { return WidestIndTy; }
900 /// Returns True if V is an induction variable in this loop.
901 bool isInductionVariable(const Value *V);
903 /// Return true if the block BB needs to be predicated in order for the loop
904 /// to be vectorized.
905 bool blockNeedsPredication(BasicBlock *BB);
907 /// Check if this pointer is consecutive when vectorizing. This happens
908 /// when the last index of the GEP is the induction variable, or that the
909 /// pointer itself is an induction variable.
910 /// This check allows us to vectorize A[idx] into a wide load/store.
912 /// 0 - Stride is unknown or non-consecutive.
913 /// 1 - Address is consecutive.
914 /// -1 - Address is consecutive, and decreasing.
915 int isConsecutivePtr(Value *Ptr);
917 /// Returns true if the value V is uniform within the loop.
918 bool isUniform(Value *V);
920 /// Returns true if this instruction will remain scalar after vectorization.
921 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
923 /// Returns the information that we collected about runtime memory check.
924 const LoopAccessInfo::RuntimePointerCheck *getRuntimePointerCheck() const {
925 return LAI->getRuntimePointerCheck();
928 const LoopAccessInfo *getLAI() const {
932 /// \brief Check if \p Instr belongs to any interleaved access group.
933 bool isAccessInterleaved(Instruction *Instr) {
934 return InterleaveInfo.isInterleaved(Instr);
937 /// \brief Get the interleaved access group that \p Instr belongs to.
938 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
939 return InterleaveInfo.getInterleaveGroup(Instr);
942 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
944 bool hasStride(Value *V) { return StrideSet.count(V); }
945 bool mustCheckStrides() { return !StrideSet.empty(); }
946 SmallPtrSet<Value *, 8>::iterator strides_begin() {
947 return StrideSet.begin();
949 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
951 /// Returns true if the target machine supports masked store operation
952 /// for the given \p DataType and kind of access to \p Ptr.
953 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
954 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
956 /// Returns true if the target machine supports masked load operation
957 /// for the given \p DataType and kind of access to \p Ptr.
958 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
959 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
961 /// Returns true if vector representation of the instruction \p I
963 bool isMaskRequired(const Instruction* I) {
964 return (MaskedOp.count(I) != 0);
966 unsigned getNumStores() const {
967 return LAI->getNumStores();
969 unsigned getNumLoads() const {
970 return LAI->getNumLoads();
972 unsigned getNumPredStores() const {
973 return NumPredStores;
976 /// Check if a single basic block loop is vectorizable.
977 /// At this point we know that this is a loop with a constant trip count
978 /// and we only need to check individual instructions.
979 bool canVectorizeInstrs();
981 /// When we vectorize loops we may change the order in which
982 /// we read and write from memory. This method checks if it is
983 /// legal to vectorize the code, considering only memory constrains.
984 /// Returns true if the loop is vectorizable
985 bool canVectorizeMemory();
987 /// Return true if we can vectorize this loop using the IF-conversion
989 bool canVectorizeWithIfConvert();
991 /// Collect the variables that need to stay uniform after vectorization.
992 void collectLoopUniforms();
994 /// Return true if all of the instructions in the block can be speculatively
995 /// executed. \p SafePtrs is a list of addresses that are known to be legal
996 /// and we know that we can read from them without segfault.
997 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
999 /// Returns the induction kind of Phi and record the step. This function may
1000 /// return NoInduction if the PHI is not an induction variable.
1001 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
1003 /// \brief Collect memory access with loop invariant strides.
1005 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1007 void collectStridedAccess(Value *LoadOrStoreInst);
1009 /// Report an analysis message to assist the user in diagnosing loops that are
1010 /// not vectorized. These are handled as LoopAccessReport rather than
1011 /// VectorizationReport because the << operator of VectorizationReport returns
1012 /// LoopAccessReport.
1013 void emitAnalysis(const LoopAccessReport &Message) {
1014 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1017 unsigned NumPredStores;
1019 /// The loop that we evaluate.
1022 ScalarEvolution *SE;
1023 /// Target Library Info.
1024 TargetLibraryInfo *TLI;
1026 Function *TheFunction;
1027 /// Target Transform Info
1028 const TargetTransformInfo *TTI;
1031 // LoopAccess analysis.
1032 LoopAccessAnalysis *LAA;
1033 // And the loop-accesses info corresponding to this loop. This pointer is
1034 // null until canVectorizeMemory sets it up.
1035 const LoopAccessInfo *LAI;
1037 /// The interleave access information contains groups of interleaved accesses
1038 /// with the same stride and close to each other.
1039 InterleavedAccessInfo InterleaveInfo;
1041 // --- vectorization state --- //
1043 /// Holds the integer induction variable. This is the counter of the
1046 /// Holds the reduction variables.
1047 ReductionList Reductions;
1048 /// Holds all of the induction variables that we found in the loop.
1049 /// Notice that inductions don't need to start at zero and that induction
1050 /// variables can be pointers.
1051 InductionList Inductions;
1052 /// Holds the widest induction type encountered.
1055 /// Allowed outside users. This holds the reduction
1056 /// vars which can be accessed from outside the loop.
1057 SmallPtrSet<Value*, 4> AllowedExit;
1058 /// This set holds the variables which are known to be uniform after
1060 SmallPtrSet<Instruction*, 4> Uniforms;
1062 /// Can we assume the absence of NaNs.
1063 bool HasFunNoNaNAttr;
1065 ValueToValueMap Strides;
1066 SmallPtrSet<Value *, 8> StrideSet;
1068 /// While vectorizing these instructions we have to generate a
1069 /// call to the appropriate masked intrinsic
1070 SmallPtrSet<const Instruction*, 8> MaskedOp;
1073 /// LoopVectorizationCostModel - estimates the expected speedups due to
1075 /// In many cases vectorization is not profitable. This can happen because of
1076 /// a number of reasons. In this class we mainly attempt to predict the
1077 /// expected speedup/slowdowns due to the supported instruction set. We use the
1078 /// TargetTransformInfo to query the different backends for the cost of
1079 /// different operations.
1080 class LoopVectorizationCostModel {
1082 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1083 LoopVectorizationLegality *Legal,
1084 const TargetTransformInfo &TTI,
1085 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1086 const Function *F, const LoopVectorizeHints *Hints)
1087 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1088 TheFunction(F), Hints(Hints) {
1089 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
1092 /// Information about vectorization costs
1093 struct VectorizationFactor {
1094 unsigned Width; // Vector width with best cost
1095 unsigned Cost; // Cost of the loop with that width
1097 /// \return The most profitable vectorization factor and the cost of that VF.
1098 /// This method checks every power of two up to VF. If UserVF is not ZERO
1099 /// then this vectorization factor will be selected if vectorization is
1101 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1103 /// \return The size (in bits) of the widest type in the code that
1104 /// needs to be vectorized. We ignore values that remain scalar such as
1105 /// 64 bit loop indices.
1106 unsigned getWidestType();
1108 /// \return The most profitable unroll factor.
1109 /// If UserUF is non-zero then this method finds the best unroll-factor
1110 /// based on register pressure and other parameters.
1111 /// VF and LoopCost are the selected vectorization factor and the cost of the
1113 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
1115 /// \brief A struct that represents some properties of the register usage
1117 struct RegisterUsage {
1118 /// Holds the number of loop invariant values that are used in the loop.
1119 unsigned LoopInvariantRegs;
1120 /// Holds the maximum number of concurrent live intervals in the loop.
1121 unsigned MaxLocalUsers;
1122 /// Holds the number of instructions in the loop.
1123 unsigned NumInstructions;
1126 /// \return information about the register usage of the loop.
1127 RegisterUsage calculateRegisterUsage();
1130 /// Returns the expected execution cost. The unit of the cost does
1131 /// not matter because we use the 'cost' units to compare different
1132 /// vector widths. The cost that is returned is *not* normalized by
1133 /// the factor width.
1134 unsigned expectedCost(unsigned VF);
1136 /// Returns the execution time cost of an instruction for a given vector
1137 /// width. Vector width of one means scalar.
1138 unsigned getInstructionCost(Instruction *I, unsigned VF);
1140 /// Returns whether the instruction is a load or store and will be a emitted
1141 /// as a vector operation.
1142 bool isConsecutiveLoadOrStore(Instruction *I);
1144 /// Report an analysis message to assist the user in diagnosing loops that are
1145 /// not vectorized. These are handled as LoopAccessReport rather than
1146 /// VectorizationReport because the << operator of VectorizationReport returns
1147 /// LoopAccessReport.
1148 void emitAnalysis(const LoopAccessReport &Message) {
1149 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1152 /// Values used only by @llvm.assume calls.
1153 SmallPtrSet<const Value *, 32> EphValues;
1155 /// The loop that we evaluate.
1158 ScalarEvolution *SE;
1159 /// Loop Info analysis.
1161 /// Vectorization legality.
1162 LoopVectorizationLegality *Legal;
1163 /// Vector target information.
1164 const TargetTransformInfo &TTI;
1165 /// Target Library Info.
1166 const TargetLibraryInfo *TLI;
1167 const Function *TheFunction;
1168 // Loop Vectorize Hint.
1169 const LoopVectorizeHints *Hints;
1172 /// Utility class for getting and setting loop vectorizer hints in the form
1173 /// of loop metadata.
1174 /// This class keeps a number of loop annotations locally (as member variables)
1175 /// and can, upon request, write them back as metadata on the loop. It will
1176 /// initially scan the loop for existing metadata, and will update the local
1177 /// values based on information in the loop.
1178 /// We cannot write all values to metadata, as the mere presence of some info,
1179 /// for example 'force', means a decision has been made. So, we need to be
1180 /// careful NOT to add them if the user hasn't specifically asked so.
1181 class LoopVectorizeHints {
1188 /// Hint - associates name and validation with the hint value.
1191 unsigned Value; // This may have to change for non-numeric values.
1194 Hint(const char * Name, unsigned Value, HintKind Kind)
1195 : Name(Name), Value(Value), Kind(Kind) { }
1197 bool validate(unsigned Val) {
1200 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1202 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1210 /// Vectorization width.
1212 /// Vectorization interleave factor.
1214 /// Vectorization forced
1217 /// Return the loop metadata prefix.
1218 static StringRef Prefix() { return "llvm.loop."; }
1222 FK_Undefined = -1, ///< Not selected.
1223 FK_Disabled = 0, ///< Forcing disabled.
1224 FK_Enabled = 1, ///< Forcing enabled.
1227 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1228 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1230 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1231 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1233 // Populate values with existing loop metadata.
1234 getHintsFromMetadata();
1236 // force-vector-interleave overrides DisableInterleaving.
1237 if (VectorizerParams::isInterleaveForced())
1238 Interleave.Value = VectorizerParams::VectorizationInterleave;
1240 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1241 << "LV: Interleaving disabled by the pass manager\n");
1244 /// Mark the loop L as already vectorized by setting the width to 1.
1245 void setAlreadyVectorized() {
1246 Width.Value = Interleave.Value = 1;
1247 Hint Hints[] = {Width, Interleave};
1248 writeHintsToMetadata(Hints);
1251 /// Dumps all the hint information.
1252 std::string emitRemark() const {
1253 VectorizationReport R;
1254 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1255 R << "vectorization is explicitly disabled";
1257 R << "use -Rpass-analysis=loop-vectorize for more info";
1258 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1259 R << " (Force=true";
1260 if (Width.Value != 0)
1261 R << ", Vector Width=" << Width.Value;
1262 if (Interleave.Value != 0)
1263 R << ", Interleave Count=" << Interleave.Value;
1271 unsigned getWidth() const { return Width.Value; }
1272 unsigned getInterleave() const { return Interleave.Value; }
1273 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1276 /// Find hints specified in the loop metadata and update local values.
1277 void getHintsFromMetadata() {
1278 MDNode *LoopID = TheLoop->getLoopID();
1282 // First operand should refer to the loop id itself.
1283 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1284 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1286 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1287 const MDString *S = nullptr;
1288 SmallVector<Metadata *, 4> Args;
1290 // The expected hint is either a MDString or a MDNode with the first
1291 // operand a MDString.
1292 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1293 if (!MD || MD->getNumOperands() == 0)
1295 S = dyn_cast<MDString>(MD->getOperand(0));
1296 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1297 Args.push_back(MD->getOperand(i));
1299 S = dyn_cast<MDString>(LoopID->getOperand(i));
1300 assert(Args.size() == 0 && "too many arguments for MDString");
1306 // Check if the hint starts with the loop metadata prefix.
1307 StringRef Name = S->getString();
1308 if (Args.size() == 1)
1309 setHint(Name, Args[0]);
1313 /// Checks string hint with one operand and set value if valid.
1314 void setHint(StringRef Name, Metadata *Arg) {
1315 if (!Name.startswith(Prefix()))
1317 Name = Name.substr(Prefix().size(), StringRef::npos);
1319 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1321 unsigned Val = C->getZExtValue();
1323 Hint *Hints[] = {&Width, &Interleave, &Force};
1324 for (auto H : Hints) {
1325 if (Name == H->Name) {
1326 if (H->validate(Val))
1329 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1335 /// Create a new hint from name / value pair.
1336 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1337 LLVMContext &Context = TheLoop->getHeader()->getContext();
1338 Metadata *MDs[] = {MDString::get(Context, Name),
1339 ConstantAsMetadata::get(
1340 ConstantInt::get(Type::getInt32Ty(Context), V))};
1341 return MDNode::get(Context, MDs);
1344 /// Matches metadata with hint name.
1345 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1346 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1350 for (auto H : HintTypes)
1351 if (Name->getString().endswith(H.Name))
1356 /// Sets current hints into loop metadata, keeping other values intact.
1357 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1358 if (HintTypes.size() == 0)
1361 // Reserve the first element to LoopID (see below).
1362 SmallVector<Metadata *, 4> MDs(1);
1363 // If the loop already has metadata, then ignore the existing operands.
1364 MDNode *LoopID = TheLoop->getLoopID();
1366 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1367 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1368 // If node in update list, ignore old value.
1369 if (!matchesHintMetadataName(Node, HintTypes))
1370 MDs.push_back(Node);
1374 // Now, add the missing hints.
1375 for (auto H : HintTypes)
1376 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1378 // Replace current metadata node with new one.
1379 LLVMContext &Context = TheLoop->getHeader()->getContext();
1380 MDNode *NewLoopID = MDNode::get(Context, MDs);
1381 // Set operand 0 to refer to the loop id itself.
1382 NewLoopID->replaceOperandWith(0, NewLoopID);
1384 TheLoop->setLoopID(NewLoopID);
1387 /// The loop these hints belong to.
1388 const Loop *TheLoop;
1391 static void emitMissedWarning(Function *F, Loop *L,
1392 const LoopVectorizeHints &LH) {
1393 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1394 L->getStartLoc(), LH.emitRemark());
1396 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1397 if (LH.getWidth() != 1)
1398 emitLoopVectorizeWarning(
1399 F->getContext(), *F, L->getStartLoc(),
1400 "failed explicitly specified loop vectorization");
1401 else if (LH.getInterleave() != 1)
1402 emitLoopInterleaveWarning(
1403 F->getContext(), *F, L->getStartLoc(),
1404 "failed explicitly specified loop interleaving");
1408 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1410 return V.push_back(&L);
1412 for (Loop *InnerL : L)
1413 addInnerLoop(*InnerL, V);
1416 /// The LoopVectorize Pass.
1417 struct LoopVectorize : public FunctionPass {
1418 /// Pass identification, replacement for typeid
1421 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1423 DisableUnrolling(NoUnrolling),
1424 AlwaysVectorize(AlwaysVectorize) {
1425 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1428 ScalarEvolution *SE;
1430 TargetTransformInfo *TTI;
1432 BlockFrequencyInfo *BFI;
1433 TargetLibraryInfo *TLI;
1435 AssumptionCache *AC;
1436 LoopAccessAnalysis *LAA;
1437 bool DisableUnrolling;
1438 bool AlwaysVectorize;
1440 BlockFrequency ColdEntryFreq;
1442 bool runOnFunction(Function &F) override {
1443 SE = &getAnalysis<ScalarEvolution>();
1444 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1445 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1446 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1447 BFI = &getAnalysis<BlockFrequencyInfo>();
1448 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1449 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1450 AA = &getAnalysis<AliasAnalysis>();
1451 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1452 LAA = &getAnalysis<LoopAccessAnalysis>();
1454 // Compute some weights outside of the loop over the loops. Compute this
1455 // using a BranchProbability to re-use its scaling math.
1456 const BranchProbability ColdProb(1, 5); // 20%
1457 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1460 // 1. the target claims to have no vector registers, and
1461 // 2. interleaving won't help ILP.
1463 // The second condition is necessary because, even if the target has no
1464 // vector registers, loop vectorization may still enable scalar
1466 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1469 // Build up a worklist of inner-loops to vectorize. This is necessary as
1470 // the act of vectorizing or partially unrolling a loop creates new loops
1471 // and can invalidate iterators across the loops.
1472 SmallVector<Loop *, 8> Worklist;
1475 addInnerLoop(*L, Worklist);
1477 LoopsAnalyzed += Worklist.size();
1479 // Now walk the identified inner loops.
1480 bool Changed = false;
1481 while (!Worklist.empty())
1482 Changed |= processLoop(Worklist.pop_back_val());
1484 // Process each loop nest in the function.
1488 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1489 SmallVector<Metadata *, 4> MDs;
1490 // Reserve first location for self reference to the LoopID metadata node.
1491 MDs.push_back(nullptr);
1492 bool IsUnrollMetadata = false;
1493 MDNode *LoopID = L->getLoopID();
1495 // First find existing loop unrolling disable metadata.
1496 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1497 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1499 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1501 S && S->getString().startswith("llvm.loop.unroll.disable");
1503 MDs.push_back(LoopID->getOperand(i));
1507 if (!IsUnrollMetadata) {
1508 // Add runtime unroll disable metadata.
1509 LLVMContext &Context = L->getHeader()->getContext();
1510 SmallVector<Metadata *, 1> DisableOperands;
1511 DisableOperands.push_back(
1512 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1513 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1514 MDs.push_back(DisableNode);
1515 MDNode *NewLoopID = MDNode::get(Context, MDs);
1516 // Set operand 0 to refer to the loop id itself.
1517 NewLoopID->replaceOperandWith(0, NewLoopID);
1518 L->setLoopID(NewLoopID);
1522 bool processLoop(Loop *L) {
1523 assert(L->empty() && "Only process inner loops.");
1526 const std::string DebugLocStr = getDebugLocString(L);
1529 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1530 << L->getHeader()->getParent()->getName() << "\" from "
1531 << DebugLocStr << "\n");
1533 LoopVectorizeHints Hints(L, DisableUnrolling);
1535 DEBUG(dbgs() << "LV: Loop hints:"
1537 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1539 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1541 : "?")) << " width=" << Hints.getWidth()
1542 << " unroll=" << Hints.getInterleave() << "\n");
1544 // Function containing loop
1545 Function *F = L->getHeader()->getParent();
1547 // Looking at the diagnostic output is the only way to determine if a loop
1548 // was vectorized (other than looking at the IR or machine code), so it
1549 // is important to generate an optimization remark for each loop. Most of
1550 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1551 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1552 // less verbose reporting vectorized loops and unvectorized loops that may
1553 // benefit from vectorization, respectively.
1555 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1556 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1557 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1558 L->getStartLoc(), Hints.emitRemark());
1562 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1563 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1564 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1565 L->getStartLoc(), Hints.emitRemark());
1569 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1570 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1571 emitOptimizationRemarkAnalysis(
1572 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1573 "loop not vectorized: vector width and interleave count are "
1574 "explicitly set to 1");
1578 // Check the loop for a trip count threshold:
1579 // do not vectorize loops with a tiny trip count.
1580 const unsigned TC = SE->getSmallConstantTripCount(L);
1581 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1582 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1583 << "This loop is not worth vectorizing.");
1584 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1585 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1587 DEBUG(dbgs() << "\n");
1588 emitOptimizationRemarkAnalysis(
1589 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1590 "vectorization is not beneficial and is not explicitly forced");
1595 // Check if it is legal to vectorize the loop.
1596 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA);
1597 if (!LVL.canVectorize()) {
1598 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1599 emitMissedWarning(F, L, Hints);
1603 // Use the cost model.
1604 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints);
1606 // Check the function attributes to find out if this function should be
1607 // optimized for size.
1608 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1609 F->hasFnAttribute(Attribute::OptimizeForSize);
1611 // Compute the weighted frequency of this loop being executed and see if it
1612 // is less than 20% of the function entry baseline frequency. Note that we
1613 // always have a canonical loop here because we think we *can* vectoriez.
1614 // FIXME: This is hidden behind a flag due to pervasive problems with
1615 // exactly what block frequency models.
1616 if (LoopVectorizeWithBlockFrequency) {
1617 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1618 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1619 LoopEntryFreq < ColdEntryFreq)
1623 // Check the function attributes to see if implicit floats are allowed.a
1624 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1625 // an integer loop and the vector instructions selected are purely integer
1626 // vector instructions?
1627 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1628 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1629 "attribute is used.\n");
1630 emitOptimizationRemarkAnalysis(
1631 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1632 "loop not vectorized due to NoImplicitFloat attribute");
1633 emitMissedWarning(F, L, Hints);
1637 // Select the optimal vectorization factor.
1638 const LoopVectorizationCostModel::VectorizationFactor VF =
1639 CM.selectVectorizationFactor(OptForSize);
1641 // Select the unroll factor.
1643 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1645 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1646 << DebugLocStr << '\n');
1647 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1649 if (VF.Width == 1) {
1650 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1653 emitOptimizationRemarkAnalysis(
1654 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1655 "not beneficial to vectorize and user disabled interleaving");
1658 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1660 // Report the unrolling decision.
1661 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1662 Twine("unrolled with interleaving factor " +
1664 " (vectorization not beneficial)"));
1666 // We decided not to vectorize, but we may want to unroll.
1668 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, UF);
1669 Unroller.vectorize(&LVL);
1671 // If we decided that it is *legal* to vectorize the loop then do it.
1672 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, UF);
1676 // Add metadata to disable runtime unrolling scalar loop when there's no
1677 // runtime check about strides and memory. Because at this situation,
1678 // scalar loop is rarely used not worthy to be unrolled.
1679 if (!LB.IsSafetyChecksAdded())
1680 AddRuntimeUnrollDisableMetaData(L);
1682 // Report the vectorization decision.
1683 emitOptimizationRemark(
1684 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1685 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1686 ", unrolling interleave factor: " + Twine(UF) + ")");
1689 // Mark the loop as already vectorized to avoid vectorizing again.
1690 Hints.setAlreadyVectorized();
1692 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1696 void getAnalysisUsage(AnalysisUsage &AU) const override {
1697 AU.addRequired<AssumptionCacheTracker>();
1698 AU.addRequiredID(LoopSimplifyID);
1699 AU.addRequiredID(LCSSAID);
1700 AU.addRequired<BlockFrequencyInfo>();
1701 AU.addRequired<DominatorTreeWrapperPass>();
1702 AU.addRequired<LoopInfoWrapperPass>();
1703 AU.addRequired<ScalarEvolution>();
1704 AU.addRequired<TargetTransformInfoWrapperPass>();
1705 AU.addRequired<AliasAnalysis>();
1706 AU.addRequired<LoopAccessAnalysis>();
1707 AU.addPreserved<LoopInfoWrapperPass>();
1708 AU.addPreserved<DominatorTreeWrapperPass>();
1709 AU.addPreserved<AliasAnalysis>();
1714 } // end anonymous namespace
1716 //===----------------------------------------------------------------------===//
1717 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1718 // LoopVectorizationCostModel.
1719 //===----------------------------------------------------------------------===//
1721 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1722 // We need to place the broadcast of invariant variables outside the loop.
1723 Instruction *Instr = dyn_cast<Instruction>(V);
1725 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1726 Instr->getParent()) != LoopVectorBody.end());
1727 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1729 // Place the code for broadcasting invariant variables in the new preheader.
1730 IRBuilder<>::InsertPointGuard Guard(Builder);
1732 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1734 // Broadcast the scalar into all locations in the vector.
1735 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1740 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1742 assert(Val->getType()->isVectorTy() && "Must be a vector");
1743 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1744 "Elem must be an integer");
1745 assert(Step->getType() == Val->getType()->getScalarType() &&
1746 "Step has wrong type");
1747 // Create the types.
1748 Type *ITy = Val->getType()->getScalarType();
1749 VectorType *Ty = cast<VectorType>(Val->getType());
1750 int VLen = Ty->getNumElements();
1751 SmallVector<Constant*, 8> Indices;
1753 // Create a vector of consecutive numbers from zero to VF.
1754 for (int i = 0; i < VLen; ++i)
1755 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1757 // Add the consecutive indices to the vector value.
1758 Constant *Cv = ConstantVector::get(Indices);
1759 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1760 Step = Builder.CreateVectorSplat(VLen, Step);
1761 assert(Step->getType() == Val->getType() && "Invalid step vec");
1762 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1763 // which can be found from the original scalar operations.
1764 Step = Builder.CreateMul(Cv, Step);
1765 return Builder.CreateAdd(Val, Step, "induction");
1768 /// \brief Find the operand of the GEP that should be checked for consecutive
1769 /// stores. This ignores trailing indices that have no effect on the final
1771 static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
1772 const DataLayout &DL = Gep->getModule()->getDataLayout();
1773 unsigned LastOperand = Gep->getNumOperands() - 1;
1774 unsigned GEPAllocSize = DL.getTypeAllocSize(
1775 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1777 // Walk backwards and try to peel off zeros.
1778 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1779 // Find the type we're currently indexing into.
1780 gep_type_iterator GEPTI = gep_type_begin(Gep);
1781 std::advance(GEPTI, LastOperand - 1);
1783 // If it's a type with the same allocation size as the result of the GEP we
1784 // can peel off the zero index.
1785 if (DL.getTypeAllocSize(*GEPTI) != GEPAllocSize)
1793 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1794 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1795 // Make sure that the pointer does not point to structs.
1796 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1799 // If this value is a pointer induction variable we know it is consecutive.
1800 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1801 if (Phi && Inductions.count(Phi)) {
1802 InductionInfo II = Inductions[Phi];
1803 return II.getConsecutiveDirection();
1806 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1810 unsigned NumOperands = Gep->getNumOperands();
1811 Value *GpPtr = Gep->getPointerOperand();
1812 // If this GEP value is a consecutive pointer induction variable and all of
1813 // the indices are constant then we know it is consecutive. We can
1814 Phi = dyn_cast<PHINode>(GpPtr);
1815 if (Phi && Inductions.count(Phi)) {
1817 // Make sure that the pointer does not point to structs.
1818 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1819 if (GepPtrType->getElementType()->isAggregateType())
1822 // Make sure that all of the index operands are loop invariant.
1823 for (unsigned i = 1; i < NumOperands; ++i)
1824 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1827 InductionInfo II = Inductions[Phi];
1828 return II.getConsecutiveDirection();
1831 unsigned InductionOperand = getGEPInductionOperand(Gep);
1833 // Check that all of the gep indices are uniform except for our induction
1835 for (unsigned i = 0; i != NumOperands; ++i)
1836 if (i != InductionOperand &&
1837 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1840 // We can emit wide load/stores only if the last non-zero index is the
1841 // induction variable.
1842 const SCEV *Last = nullptr;
1843 if (!Strides.count(Gep))
1844 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1846 // Because of the multiplication by a stride we can have a s/zext cast.
1847 // We are going to replace this stride by 1 so the cast is safe to ignore.
1849 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1850 // %0 = trunc i64 %indvars.iv to i32
1851 // %mul = mul i32 %0, %Stride1
1852 // %idxprom = zext i32 %mul to i64 << Safe cast.
1853 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1855 Last = replaceSymbolicStrideSCEV(SE, Strides,
1856 Gep->getOperand(InductionOperand), Gep);
1857 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1859 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1863 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1864 const SCEV *Step = AR->getStepRecurrence(*SE);
1866 // The memory is consecutive because the last index is consecutive
1867 // and all other indices are loop invariant.
1870 if (Step->isAllOnesValue())
1877 bool LoopVectorizationLegality::isUniform(Value *V) {
1878 return LAI->isUniform(V);
1881 InnerLoopVectorizer::VectorParts&
1882 InnerLoopVectorizer::getVectorValue(Value *V) {
1883 assert(V != Induction && "The new induction variable should not be used.");
1884 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1886 // If we have a stride that is replaced by one, do it here.
1887 if (Legal->hasStride(V))
1888 V = ConstantInt::get(V->getType(), 1);
1890 // If we have this scalar in the map, return it.
1891 if (WidenMap.has(V))
1892 return WidenMap.get(V);
1894 // If this scalar is unknown, assume that it is a constant or that it is
1895 // loop invariant. Broadcast V and save the value for future uses.
1896 Value *B = getBroadcastInstrs(V);
1897 return WidenMap.splat(V, B);
1900 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1901 assert(Vec->getType()->isVectorTy() && "Invalid type");
1902 SmallVector<Constant*, 8> ShuffleMask;
1903 for (unsigned i = 0; i < VF; ++i)
1904 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1906 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1907 ConstantVector::get(ShuffleMask),
1911 // Get a mask to interleave \p NumVec vectors into a wide vector.
1912 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
1913 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
1914 // <0, 4, 1, 5, 2, 6, 3, 7>
1915 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
1917 SmallVector<Constant *, 16> Mask;
1918 for (unsigned i = 0; i < VF; i++)
1919 for (unsigned j = 0; j < NumVec; j++)
1920 Mask.push_back(Builder.getInt32(j * VF + i));
1922 return ConstantVector::get(Mask);
1925 // Get the strided mask starting from index \p Start.
1926 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
1927 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
1928 unsigned Stride, unsigned VF) {
1929 SmallVector<Constant *, 16> Mask;
1930 for (unsigned i = 0; i < VF; i++)
1931 Mask.push_back(Builder.getInt32(Start + i * Stride));
1933 return ConstantVector::get(Mask);
1936 // Get a mask of two parts: The first part consists of sequential integers
1937 // starting from 0, The second part consists of UNDEFs.
1938 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
1939 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
1940 unsigned NumUndef) {
1941 SmallVector<Constant *, 16> Mask;
1942 for (unsigned i = 0; i < NumInt; i++)
1943 Mask.push_back(Builder.getInt32(i));
1945 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
1946 for (unsigned i = 0; i < NumUndef; i++)
1947 Mask.push_back(Undef);
1949 return ConstantVector::get(Mask);
1952 // Concatenate two vectors with the same element type. The 2nd vector should
1953 // not have more elements than the 1st vector. If the 2nd vector has less
1954 // elements, extend it with UNDEFs.
1955 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
1957 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
1958 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
1959 assert(VecTy1 && VecTy2 &&
1960 VecTy1->getScalarType() == VecTy2->getScalarType() &&
1961 "Expect two vectors with the same element type");
1963 unsigned NumElts1 = VecTy1->getNumElements();
1964 unsigned NumElts2 = VecTy2->getNumElements();
1965 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
1967 if (NumElts1 > NumElts2) {
1968 // Extend with UNDEFs.
1970 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
1971 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
1974 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
1975 return Builder.CreateShuffleVector(V1, V2, Mask);
1978 // Concatenate vectors in the given list. All vectors have the same type.
1979 static Value *ConcatenateVectors(IRBuilder<> &Builder,
1980 ArrayRef<Value *> InputList) {
1981 unsigned NumVec = InputList.size();
1982 assert(NumVec > 1 && "Should be at least two vectors");
1984 SmallVector<Value *, 8> ResList;
1985 ResList.append(InputList.begin(), InputList.end());
1987 SmallVector<Value *, 8> TmpList;
1988 for (unsigned i = 0; i < NumVec - 1; i += 2) {
1989 Value *V0 = ResList[i], *V1 = ResList[i + 1];
1990 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
1991 "Only the last vector may have a different type");
1993 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
1996 // Push the last vector if the total number of vectors is odd.
1997 if (NumVec % 2 != 0)
1998 TmpList.push_back(ResList[NumVec - 1]);
2001 NumVec = ResList.size();
2002 } while (NumVec > 1);
2007 // Try to vectorize the interleave group that \p Instr belongs to.
2009 // E.g. Translate following interleaved load group (factor = 3):
2010 // for (i = 0; i < N; i+=3) {
2011 // R = Pic[i]; // Member of index 0
2012 // G = Pic[i+1]; // Member of index 1
2013 // B = Pic[i+2]; // Member of index 2
2014 // ... // do something to R, G, B
2017 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2018 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2019 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2020 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2022 // Or translate following interleaved store group (factor = 3):
2023 // for (i = 0; i < N; i+=3) {
2024 // ... do something to R, G, B
2025 // Pic[i] = R; // Member of index 0
2026 // Pic[i+1] = G; // Member of index 1
2027 // Pic[i+2] = B; // Member of index 2
2030 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2031 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2032 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2033 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2034 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2035 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2036 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2037 assert(Group && "Fail to get an interleaved access group.");
2039 // Skip if current instruction is not the insert position.
2040 if (Instr != Group->getInsertPos())
2043 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2044 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2045 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2047 // Prepare for the vector type of the interleaved load/store.
2048 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2049 unsigned InterleaveFactor = Group->getFactor();
2050 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2051 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2053 // Prepare for the new pointers.
2054 setDebugLocFromInst(Builder, Ptr);
2055 VectorParts &PtrParts = getVectorValue(Ptr);
2056 SmallVector<Value *, 2> NewPtrs;
2057 unsigned Index = Group->getIndex(Instr);
2058 for (unsigned Part = 0; Part < UF; Part++) {
2059 // Extract the pointer for current instruction from the pointer vector. A
2060 // reverse access uses the pointer in the last lane.
2061 Value *NewPtr = Builder.CreateExtractElement(
2063 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2065 // Notice current instruction could be any index. Need to adjust the address
2066 // to the member of index 0.
2068 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2069 // b = A[i]; // Member of index 0
2070 // Current pointer is pointed to A[i+1], adjust it to A[i].
2072 // E.g. A[i+1] = a; // Member of index 1
2073 // A[i] = b; // Member of index 0
2074 // A[i+2] = c; // Member of index 2 (Current instruction)
2075 // Current pointer is pointed to A[i+2], adjust it to A[i].
2076 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2078 // Cast to the vector pointer type.
2079 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2082 setDebugLocFromInst(Builder, Instr);
2083 Value *UndefVec = UndefValue::get(VecTy);
2085 // Vectorize the interleaved load group.
2087 for (unsigned Part = 0; Part < UF; Part++) {
2088 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2089 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2091 for (unsigned i = 0; i < InterleaveFactor; i++) {
2092 Instruction *Member = Group->getMember(i);
2094 // Skip the gaps in the group.
2098 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2099 Value *StridedVec = Builder.CreateShuffleVector(
2100 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2102 // If this member has different type, cast the result type.
2103 if (Member->getType() != ScalarTy) {
2104 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2105 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2108 VectorParts &Entry = WidenMap.get(Member);
2110 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2113 propagateMetadata(NewLoadInstr, Instr);
2118 // The sub vector type for current instruction.
2119 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2121 // Vectorize the interleaved store group.
2122 for (unsigned Part = 0; Part < UF; Part++) {
2123 // Collect the stored vector from each member.
2124 SmallVector<Value *, 4> StoredVecs;
2125 for (unsigned i = 0; i < InterleaveFactor; i++) {
2126 // Interleaved store group doesn't allow a gap, so each index has a member
2127 Instruction *Member = Group->getMember(i);
2128 assert(Member && "Fail to get a member from an interleaved store group");
2131 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2132 if (Group->isReverse())
2133 StoredVec = reverseVector(StoredVec);
2135 // If this member has different type, cast it to an unified type.
2136 if (StoredVec->getType() != SubVT)
2137 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2139 StoredVecs.push_back(StoredVec);
2142 // Concatenate all vectors into a wide vector.
2143 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2145 // Interleave the elements in the wide vector.
2146 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2147 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2150 Instruction *NewStoreInstr =
2151 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2152 propagateMetadata(NewStoreInstr, Instr);
2156 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2157 // Attempt to issue a wide load.
2158 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2159 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2161 assert((LI || SI) && "Invalid Load/Store instruction");
2163 // Try to vectorize the interleave group if this access is interleaved.
2164 if (Legal->isAccessInterleaved(Instr))
2165 return vectorizeInterleaveGroup(Instr);
2167 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2168 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2169 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2170 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2171 // An alignment of 0 means target abi alignment. We need to use the scalar's
2172 // target abi alignment in such a case.
2173 const DataLayout &DL = Instr->getModule()->getDataLayout();
2175 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2176 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2177 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2178 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2180 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2181 !Legal->isMaskRequired(SI))
2182 return scalarizeInstruction(Instr, true);
2184 if (ScalarAllocatedSize != VectorElementSize)
2185 return scalarizeInstruction(Instr);
2187 // If the pointer is loop invariant or if it is non-consecutive,
2188 // scalarize the load.
2189 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2190 bool Reverse = ConsecutiveStride < 0;
2191 bool UniformLoad = LI && Legal->isUniform(Ptr);
2192 if (!ConsecutiveStride || UniformLoad)
2193 return scalarizeInstruction(Instr);
2195 Constant *Zero = Builder.getInt32(0);
2196 VectorParts &Entry = WidenMap.get(Instr);
2198 // Handle consecutive loads/stores.
2199 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2200 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2201 setDebugLocFromInst(Builder, Gep);
2202 Value *PtrOperand = Gep->getPointerOperand();
2203 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2204 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2206 // Create the new GEP with the new induction variable.
2207 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2208 Gep2->setOperand(0, FirstBasePtr);
2209 Gep2->setName("gep.indvar.base");
2210 Ptr = Builder.Insert(Gep2);
2212 setDebugLocFromInst(Builder, Gep);
2213 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2214 OrigLoop) && "Base ptr must be invariant");
2216 // The last index does not have to be the induction. It can be
2217 // consecutive and be a function of the index. For example A[I+1];
2218 unsigned NumOperands = Gep->getNumOperands();
2219 unsigned InductionOperand = getGEPInductionOperand(Gep);
2220 // Create the new GEP with the new induction variable.
2221 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2223 for (unsigned i = 0; i < NumOperands; ++i) {
2224 Value *GepOperand = Gep->getOperand(i);
2225 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2227 // Update last index or loop invariant instruction anchored in loop.
2228 if (i == InductionOperand ||
2229 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2230 assert((i == InductionOperand ||
2231 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2232 "Must be last index or loop invariant");
2234 VectorParts &GEPParts = getVectorValue(GepOperand);
2235 Value *Index = GEPParts[0];
2236 Index = Builder.CreateExtractElement(Index, Zero);
2237 Gep2->setOperand(i, Index);
2238 Gep2->setName("gep.indvar.idx");
2241 Ptr = Builder.Insert(Gep2);
2243 // Use the induction element ptr.
2244 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2245 setDebugLocFromInst(Builder, Ptr);
2246 VectorParts &PtrVal = getVectorValue(Ptr);
2247 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2250 VectorParts Mask = createBlockInMask(Instr->getParent());
2253 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2254 "We do not allow storing to uniform addresses");
2255 setDebugLocFromInst(Builder, SI);
2256 // We don't want to update the value in the map as it might be used in
2257 // another expression. So don't use a reference type for "StoredVal".
2258 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2260 for (unsigned Part = 0; Part < UF; ++Part) {
2261 // Calculate the pointer for the specific unroll-part.
2263 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2266 // If we store to reverse consecutive memory locations then we need
2267 // to reverse the order of elements in the stored value.
2268 StoredVal[Part] = reverseVector(StoredVal[Part]);
2269 // If the address is consecutive but reversed, then the
2270 // wide store needs to start at the last vector element.
2271 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2272 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2273 Mask[Part] = reverseVector(Mask[Part]);
2276 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2277 DataTy->getPointerTo(AddressSpace));
2280 if (Legal->isMaskRequired(SI))
2281 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2284 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2285 propagateMetadata(NewSI, SI);
2291 assert(LI && "Must have a load instruction");
2292 setDebugLocFromInst(Builder, LI);
2293 for (unsigned Part = 0; Part < UF; ++Part) {
2294 // Calculate the pointer for the specific unroll-part.
2296 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2299 // If the address is consecutive but reversed, then the
2300 // wide load needs to start at the last vector element.
2301 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2302 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2303 Mask[Part] = reverseVector(Mask[Part]);
2307 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2308 DataTy->getPointerTo(AddressSpace));
2309 if (Legal->isMaskRequired(LI))
2310 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2311 UndefValue::get(DataTy),
2312 "wide.masked.load");
2314 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2315 propagateMetadata(NewLI, LI);
2316 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2320 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2321 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2322 // Holds vector parameters or scalars, in case of uniform vals.
2323 SmallVector<VectorParts, 4> Params;
2325 setDebugLocFromInst(Builder, Instr);
2327 // Find all of the vectorized parameters.
2328 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2329 Value *SrcOp = Instr->getOperand(op);
2331 // If we are accessing the old induction variable, use the new one.
2332 if (SrcOp == OldInduction) {
2333 Params.push_back(getVectorValue(SrcOp));
2337 // Try using previously calculated values.
2338 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2340 // If the src is an instruction that appeared earlier in the basic block
2341 // then it should already be vectorized.
2342 if (SrcInst && OrigLoop->contains(SrcInst)) {
2343 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2344 // The parameter is a vector value from earlier.
2345 Params.push_back(WidenMap.get(SrcInst));
2347 // The parameter is a scalar from outside the loop. Maybe even a constant.
2348 VectorParts Scalars;
2349 Scalars.append(UF, SrcOp);
2350 Params.push_back(Scalars);
2354 assert(Params.size() == Instr->getNumOperands() &&
2355 "Invalid number of operands");
2357 // Does this instruction return a value ?
2358 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2360 Value *UndefVec = IsVoidRetTy ? nullptr :
2361 UndefValue::get(VectorType::get(Instr->getType(), VF));
2362 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2363 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2365 Instruction *InsertPt = Builder.GetInsertPoint();
2366 BasicBlock *IfBlock = Builder.GetInsertBlock();
2367 BasicBlock *CondBlock = nullptr;
2370 Loop *VectorLp = nullptr;
2371 if (IfPredicateStore) {
2372 assert(Instr->getParent()->getSinglePredecessor() &&
2373 "Only support single predecessor blocks");
2374 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2375 Instr->getParent());
2376 VectorLp = LI->getLoopFor(IfBlock);
2377 assert(VectorLp && "Must have a loop for this block");
2380 // For each vector unroll 'part':
2381 for (unsigned Part = 0; Part < UF; ++Part) {
2382 // For each scalar that we create:
2383 for (unsigned Width = 0; Width < VF; ++Width) {
2386 Value *Cmp = nullptr;
2387 if (IfPredicateStore) {
2388 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2389 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2390 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2391 LoopVectorBody.push_back(CondBlock);
2392 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
2393 // Update Builder with newly created basic block.
2394 Builder.SetInsertPoint(InsertPt);
2397 Instruction *Cloned = Instr->clone();
2399 Cloned->setName(Instr->getName() + ".cloned");
2400 // Replace the operands of the cloned instructions with extracted scalars.
2401 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2402 Value *Op = Params[op][Part];
2403 // Param is a vector. Need to extract the right lane.
2404 if (Op->getType()->isVectorTy())
2405 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2406 Cloned->setOperand(op, Op);
2409 // Place the cloned scalar in the new loop.
2410 Builder.Insert(Cloned);
2412 // If the original scalar returns a value we need to place it in a vector
2413 // so that future users will be able to use it.
2415 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2416 Builder.getInt32(Width));
2418 if (IfPredicateStore) {
2419 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2420 LoopVectorBody.push_back(NewIfBlock);
2421 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
2422 Builder.SetInsertPoint(InsertPt);
2423 ReplaceInstWithInst(IfBlock->getTerminator(),
2424 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
2425 IfBlock = NewIfBlock;
2431 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2435 if (Instruction *I = dyn_cast<Instruction>(V))
2436 return I->getParent() == Loc->getParent() ? I : nullptr;
2440 std::pair<Instruction *, Instruction *>
2441 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2442 Instruction *tnullptr = nullptr;
2443 if (!Legal->mustCheckStrides())
2444 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2446 IRBuilder<> ChkBuilder(Loc);
2449 Value *Check = nullptr;
2450 Instruction *FirstInst = nullptr;
2451 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2452 SE = Legal->strides_end();
2454 Value *Ptr = stripIntegerCast(*SI);
2455 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2457 // Store the first instruction we create.
2458 FirstInst = getFirstInst(FirstInst, C, Loc);
2460 Check = ChkBuilder.CreateOr(Check, C);
2465 // We have to do this trickery because the IRBuilder might fold the check to a
2466 // constant expression in which case there is no Instruction anchored in a
2468 LLVMContext &Ctx = Loc->getContext();
2469 Instruction *TheCheck =
2470 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2471 ChkBuilder.Insert(TheCheck, "stride.not.one");
2472 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2474 return std::make_pair(FirstInst, TheCheck);
2477 void InnerLoopVectorizer::createEmptyLoop() {
2479 In this function we generate a new loop. The new loop will contain
2480 the vectorized instructions while the old loop will continue to run the
2483 [ ] <-- Back-edge taken count overflow check.
2486 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2489 || [ ] <-- vector pre header.
2493 || [ ]_| <-- vector loop.
2496 | >[ ] <--- middle-block.
2499 -|- >[ ] <--- new preheader.
2503 | [ ]_| <-- old scalar loop to handle remainder.
2506 >[ ] <-- exit block.
2510 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2511 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2512 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2513 assert(VectorPH && "Invalid loop structure");
2514 assert(ExitBlock && "Must have an exit block");
2516 // Some loops have a single integer induction variable, while other loops
2517 // don't. One example is c++ iterators that often have multiple pointer
2518 // induction variables. In the code below we also support a case where we
2519 // don't have a single induction variable.
2520 OldInduction = Legal->getInduction();
2521 Type *IdxTy = Legal->getWidestInductionType();
2523 // Find the loop boundaries.
2524 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2525 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2527 // The exit count might have the type of i64 while the phi is i32. This can
2528 // happen if we have an induction variable that is sign extended before the
2529 // compare. The only way that we get a backedge taken count is that the
2530 // induction variable was signed and as such will not overflow. In such a case
2531 // truncation is legal.
2532 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2533 IdxTy->getPrimitiveSizeInBits())
2534 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2536 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2537 // Get the total trip count from the count by adding 1.
2538 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2539 SE->getConstant(BackedgeTakeCount->getType(), 1));
2541 const DataLayout &DL = OldBasicBlock->getModule()->getDataLayout();
2543 // Expand the trip count and place the new instructions in the preheader.
2544 // Notice that the pre-header does not change, only the loop body.
2545 SCEVExpander Exp(*SE, DL, "induction");
2547 // We need to test whether the backedge-taken count is uint##_max. Adding one
2548 // to it will cause overflow and an incorrect loop trip count in the vector
2549 // body. In case of overflow we want to directly jump to the scalar remainder
2551 Value *BackedgeCount =
2552 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2553 VectorPH->getTerminator());
2554 if (BackedgeCount->getType()->isPointerTy())
2555 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2556 "backedge.ptrcnt.to.int",
2557 VectorPH->getTerminator());
2558 Instruction *CheckBCOverflow =
2559 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2560 Constant::getAllOnesValue(BackedgeCount->getType()),
2561 "backedge.overflow", VectorPH->getTerminator());
2563 // The loop index does not have to start at Zero. Find the original start
2564 // value from the induction PHI node. If we don't have an induction variable
2565 // then we know that it starts at zero.
2566 Builder.SetInsertPoint(VectorPH->getTerminator());
2567 Value *StartIdx = ExtendedIdx =
2569 ? Builder.CreateZExt(OldInduction->getIncomingValueForBlock(VectorPH),
2571 : ConstantInt::get(IdxTy, 0);
2573 // Count holds the overall loop count (N).
2574 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2575 VectorPH->getTerminator());
2577 LoopBypassBlocks.push_back(VectorPH);
2579 // Split the single block loop into the two loop structure described above.
2580 BasicBlock *VecBody =
2581 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2582 BasicBlock *MiddleBlock =
2583 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2584 BasicBlock *ScalarPH =
2585 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2587 // Create and register the new vector loop.
2588 Loop* Lp = new Loop();
2589 Loop *ParentLoop = OrigLoop->getParentLoop();
2591 // Insert the new loop into the loop nest and register the new basic blocks
2592 // before calling any utilities such as SCEV that require valid LoopInfo.
2594 ParentLoop->addChildLoop(Lp);
2595 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2596 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2598 LI->addTopLevelLoop(Lp);
2600 Lp->addBasicBlockToLoop(VecBody, *LI);
2602 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2604 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2606 // Generate the induction variable.
2607 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2608 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2609 // The loop step is equal to the vectorization factor (num of SIMD elements)
2610 // times the unroll factor (num of SIMD instructions).
2611 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2613 // Generate code to check that the loop's trip count that we computed by
2614 // adding one to the backedge-taken count will not overflow.
2615 BasicBlock *NewVectorPH =
2616 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "overflow.checked");
2618 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2619 ReplaceInstWithInst(
2620 VectorPH->getTerminator(),
2621 BranchInst::Create(ScalarPH, NewVectorPH, CheckBCOverflow));
2622 VectorPH = NewVectorPH;
2624 // This is the IR builder that we use to add all of the logic for bypassing
2625 // the new vector loop.
2626 IRBuilder<> BypassBuilder(VectorPH->getTerminator());
2627 setDebugLocFromInst(BypassBuilder,
2628 getDebugLocFromInstOrOperands(OldInduction));
2630 // We may need to extend the index in case there is a type mismatch.
2631 // We know that the count starts at zero and does not overflow.
2632 if (Count->getType() != IdxTy) {
2633 // The exit count can be of pointer type. Convert it to the correct
2635 if (ExitCount->getType()->isPointerTy())
2636 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2638 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2641 // Add the start index to the loop count to get the new end index.
2642 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2644 // Now we need to generate the expression for N - (N % VF), which is
2645 // the part that the vectorized body will execute.
2646 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2647 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2648 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2649 "end.idx.rnd.down");
2651 // Now, compare the new count to zero. If it is zero skip the vector loop and
2652 // jump to the scalar loop.
2654 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2656 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2658 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2659 LoopBypassBlocks.push_back(VectorPH);
2660 ReplaceInstWithInst(VectorPH->getTerminator(),
2661 BranchInst::Create(MiddleBlock, NewVectorPH, Cmp));
2662 VectorPH = NewVectorPH;
2664 // Generate the code to check that the strides we assumed to be one are really
2665 // one. We want the new basic block to start at the first instruction in a
2666 // sequence of instructions that form a check.
2667 Instruction *StrideCheck;
2668 Instruction *FirstCheckInst;
2669 std::tie(FirstCheckInst, StrideCheck) =
2670 addStrideCheck(VectorPH->getTerminator());
2672 AddedSafetyChecks = true;
2673 // Create a new block containing the stride check.
2674 VectorPH->setName("vector.stridecheck");
2676 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2678 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2679 LoopBypassBlocks.push_back(VectorPH);
2681 // Replace the branch into the memory check block with a conditional branch
2682 // for the "few elements case".
2683 ReplaceInstWithInst(
2684 VectorPH->getTerminator(),
2685 BranchInst::Create(MiddleBlock, NewVectorPH, StrideCheck));
2687 VectorPH = NewVectorPH;
2690 // Generate the code that checks in runtime if arrays overlap. We put the
2691 // checks into a separate block to make the more common case of few elements
2693 Instruction *MemRuntimeCheck;
2694 std::tie(FirstCheckInst, MemRuntimeCheck) =
2695 Legal->getLAI()->addRuntimeCheck(VectorPH->getTerminator());
2696 if (MemRuntimeCheck) {
2697 AddedSafetyChecks = true;
2698 // Create a new block containing the memory check.
2699 VectorPH->setName("vector.memcheck");
2701 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2703 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2704 LoopBypassBlocks.push_back(VectorPH);
2706 // Replace the branch into the memory check block with a conditional branch
2707 // for the "few elements case".
2708 ReplaceInstWithInst(
2709 VectorPH->getTerminator(),
2710 BranchInst::Create(MiddleBlock, NewVectorPH, MemRuntimeCheck));
2712 VectorPH = NewVectorPH;
2715 // We are going to resume the execution of the scalar loop.
2716 // Go over all of the induction variables that we found and fix the
2717 // PHIs that are left in the scalar version of the loop.
2718 // The starting values of PHI nodes depend on the counter of the last
2719 // iteration in the vectorized loop.
2720 // If we come from a bypass edge then we need to start from the original
2723 // This variable saves the new starting index for the scalar loop.
2724 PHINode *ResumeIndex = nullptr;
2725 LoopVectorizationLegality::InductionList::iterator I, E;
2726 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2727 // Set builder to point to last bypass block.
2728 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2729 for (I = List->begin(), E = List->end(); I != E; ++I) {
2730 PHINode *OrigPhi = I->first;
2731 LoopVectorizationLegality::InductionInfo II = I->second;
2733 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2734 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2735 MiddleBlock->getTerminator());
2736 // We might have extended the type of the induction variable but we need a
2737 // truncated version for the scalar loop.
2738 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2739 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2740 MiddleBlock->getTerminator()) : nullptr;
2742 // Create phi nodes to merge from the backedge-taken check block.
2743 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2744 ScalarPH->getTerminator());
2745 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2747 PHINode *BCTruncResumeVal = nullptr;
2748 if (OrigPhi == OldInduction) {
2750 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2751 ScalarPH->getTerminator());
2752 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2755 Value *EndValue = nullptr;
2757 case LoopVectorizationLegality::IK_NoInduction:
2758 llvm_unreachable("Unknown induction");
2759 case LoopVectorizationLegality::IK_IntInduction: {
2760 // Handle the integer induction counter.
2761 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2763 // We have the canonical induction variable.
2764 if (OrigPhi == OldInduction) {
2765 // Create a truncated version of the resume value for the scalar loop,
2766 // we might have promoted the type to a larger width.
2768 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2769 // The new PHI merges the original incoming value, in case of a bypass,
2770 // or the value at the end of the vectorized loop.
2771 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2772 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2773 TruncResumeVal->addIncoming(EndValue, VecBody);
2775 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2777 // We know what the end value is.
2778 EndValue = IdxEndRoundDown;
2779 // We also know which PHI node holds it.
2780 ResumeIndex = ResumeVal;
2784 // Not the canonical induction variable - add the vector loop count to the
2786 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2787 II.StartValue->getType(),
2789 EndValue = II.transform(BypassBuilder, CRD);
2790 EndValue->setName("ind.end");
2793 case LoopVectorizationLegality::IK_PtrInduction: {
2794 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2795 II.StepValue->getType(),
2797 EndValue = II.transform(BypassBuilder, CRD);
2798 EndValue->setName("ptr.ind.end");
2803 // The new PHI merges the original incoming value, in case of a bypass,
2804 // or the value at the end of the vectorized loop.
2805 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2806 if (OrigPhi == OldInduction)
2807 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2809 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2811 ResumeVal->addIncoming(EndValue, VecBody);
2813 // Fix the scalar body counter (PHI node).
2814 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2816 // The old induction's phi node in the scalar body needs the truncated
2818 if (OrigPhi == OldInduction) {
2819 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2820 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2822 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2823 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2827 // If we are generating a new induction variable then we also need to
2828 // generate the code that calculates the exit value. This value is not
2829 // simply the end of the counter because we may skip the vectorized body
2830 // in case of a runtime check.
2832 assert(!ResumeIndex && "Unexpected resume value found");
2833 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2834 MiddleBlock->getTerminator());
2835 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2836 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2837 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2840 // Make sure that we found the index where scalar loop needs to continue.
2841 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2842 "Invalid resume Index");
2844 // Add a check in the middle block to see if we have completed
2845 // all of the iterations in the first vector loop.
2846 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2847 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2848 ResumeIndex, "cmp.n",
2849 MiddleBlock->getTerminator());
2850 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2851 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2853 // Create i+1 and fill the PHINode.
2854 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2855 Induction->addIncoming(StartIdx, VectorPH);
2856 Induction->addIncoming(NextIdx, VecBody);
2857 // Create the compare.
2858 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2859 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2861 // Now we have two terminators. Remove the old one from the block.
2862 VecBody->getTerminator()->eraseFromParent();
2864 // Get ready to start creating new instructions into the vectorized body.
2865 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2868 LoopVectorPreHeader = VectorPH;
2869 LoopScalarPreHeader = ScalarPH;
2870 LoopMiddleBlock = MiddleBlock;
2871 LoopExitBlock = ExitBlock;
2872 LoopVectorBody.push_back(VecBody);
2873 LoopScalarBody = OldBasicBlock;
2875 LoopVectorizeHints Hints(Lp, true);
2876 Hints.setAlreadyVectorized();
2880 struct CSEDenseMapInfo {
2881 static bool canHandle(Instruction *I) {
2882 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2883 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2885 static inline Instruction *getEmptyKey() {
2886 return DenseMapInfo<Instruction *>::getEmptyKey();
2888 static inline Instruction *getTombstoneKey() {
2889 return DenseMapInfo<Instruction *>::getTombstoneKey();
2891 static unsigned getHashValue(Instruction *I) {
2892 assert(canHandle(I) && "Unknown instruction!");
2893 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2894 I->value_op_end()));
2896 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2897 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2898 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2900 return LHS->isIdenticalTo(RHS);
2905 /// \brief Check whether this block is a predicated block.
2906 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2907 /// = ...; " blocks. We start with one vectorized basic block. For every
2908 /// conditional block we split this vectorized block. Therefore, every second
2909 /// block will be a predicated one.
2910 static bool isPredicatedBlock(unsigned BlockNum) {
2911 return BlockNum % 2;
2914 ///\brief Perform cse of induction variable instructions.
2915 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2916 // Perform simple cse.
2917 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2918 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2919 BasicBlock *BB = BBs[i];
2920 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2921 Instruction *In = I++;
2923 if (!CSEDenseMapInfo::canHandle(In))
2926 // Check if we can replace this instruction with any of the
2927 // visited instructions.
2928 if (Instruction *V = CSEMap.lookup(In)) {
2929 In->replaceAllUsesWith(V);
2930 In->eraseFromParent();
2933 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2934 // ...;" blocks for predicated stores. Every second block is a predicated
2936 if (isPredicatedBlock(i))
2944 /// \brief Adds a 'fast' flag to floating point operations.
2945 static Value *addFastMathFlag(Value *V) {
2946 if (isa<FPMathOperator>(V)){
2947 FastMathFlags Flags;
2948 Flags.setUnsafeAlgebra();
2949 cast<Instruction>(V)->setFastMathFlags(Flags);
2954 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
2955 /// the result needs to be inserted and/or extracted from vectors.
2956 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
2957 const TargetTransformInfo &TTI) {
2961 assert(Ty->isVectorTy() && "Can only scalarize vectors");
2964 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
2966 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
2968 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
2974 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
2975 // Return the cost of the instruction, including scalarization overhead if it's
2976 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
2977 // i.e. either vector version isn't available, or is too expensive.
2978 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
2979 const TargetTransformInfo &TTI,
2980 const TargetLibraryInfo *TLI,
2981 bool &NeedToScalarize) {
2982 Function *F = CI->getCalledFunction();
2983 StringRef FnName = CI->getCalledFunction()->getName();
2984 Type *ScalarRetTy = CI->getType();
2985 SmallVector<Type *, 4> Tys, ScalarTys;
2986 for (auto &ArgOp : CI->arg_operands())
2987 ScalarTys.push_back(ArgOp->getType());
2989 // Estimate cost of scalarized vector call. The source operands are assumed
2990 // to be vectors, so we need to extract individual elements from there,
2991 // execute VF scalar calls, and then gather the result into the vector return
2993 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
2995 return ScalarCallCost;
2997 // Compute corresponding vector type for return value and arguments.
2998 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
2999 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3000 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3002 // Compute costs of unpacking argument values for the scalar calls and
3003 // packing the return values to a vector.
3004 unsigned ScalarizationCost =
3005 getScalarizationOverhead(RetTy, true, false, TTI);
3006 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3007 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3009 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3011 // If we can't emit a vector call for this function, then the currently found
3012 // cost is the cost we need to return.
3013 NeedToScalarize = true;
3014 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3017 // If the corresponding vector cost is cheaper, return its cost.
3018 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3019 if (VectorCallCost < Cost) {
3020 NeedToScalarize = false;
3021 return VectorCallCost;
3026 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3027 // factor VF. Return the cost of the instruction, including scalarization
3028 // overhead if it's needed.
3029 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3030 const TargetTransformInfo &TTI,
3031 const TargetLibraryInfo *TLI) {
3032 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3033 assert(ID && "Expected intrinsic call!");
3035 Type *RetTy = ToVectorTy(CI->getType(), VF);
3036 SmallVector<Type *, 4> Tys;
3037 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3038 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3040 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3043 void InnerLoopVectorizer::vectorizeLoop() {
3044 //===------------------------------------------------===//
3046 // Notice: any optimization or new instruction that go
3047 // into the code below should be also be implemented in
3050 //===------------------------------------------------===//
3051 Constant *Zero = Builder.getInt32(0);
3053 // In order to support reduction variables we need to be able to vectorize
3054 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3055 // stages. First, we create a new vector PHI node with no incoming edges.
3056 // We use this value when we vectorize all of the instructions that use the
3057 // PHI. Next, after all of the instructions in the block are complete we
3058 // add the new incoming edges to the PHI. At this point all of the
3059 // instructions in the basic block are vectorized, so we can use them to
3060 // construct the PHI.
3061 PhiVector RdxPHIsToFix;
3063 // Scan the loop in a topological order to ensure that defs are vectorized
3065 LoopBlocksDFS DFS(OrigLoop);
3068 // Vectorize all of the blocks in the original loop.
3069 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3070 be = DFS.endRPO(); bb != be; ++bb)
3071 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3073 // At this point every instruction in the original loop is widened to
3074 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3075 // that we vectorized. The PHI nodes are currently empty because we did
3076 // not want to introduce cycles. Notice that the remaining PHI nodes
3077 // that we need to fix are reduction variables.
3079 // Create the 'reduced' values for each of the induction vars.
3080 // The reduced values are the vector values that we scalarize and combine
3081 // after the loop is finished.
3082 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3084 PHINode *RdxPhi = *it;
3085 assert(RdxPhi && "Unable to recover vectorized PHI");
3087 // Find the reduction variable descriptor.
3088 assert(Legal->getReductionVars()->count(RdxPhi) &&
3089 "Unable to find the reduction variable");
3090 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3092 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3093 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3094 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3095 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3096 RdxDesc.getMinMaxRecurrenceKind();
3097 setDebugLocFromInst(Builder, ReductionStartValue);
3099 // We need to generate a reduction vector from the incoming scalar.
3100 // To do so, we need to generate the 'identity' vector and override
3101 // one of the elements with the incoming scalar reduction. We need
3102 // to do it in the vector-loop preheader.
3103 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3105 // This is the vector-clone of the value that leaves the loop.
3106 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3107 Type *VecTy = VectorExit[0]->getType();
3109 // Find the reduction identity variable. Zero for addition, or, xor,
3110 // one for multiplication, -1 for And.
3113 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3114 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3115 // MinMax reduction have the start value as their identify.
3117 VectorStart = Identity = ReductionStartValue;
3119 VectorStart = Identity =
3120 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3123 // Handle other reduction kinds:
3124 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3125 RK, VecTy->getScalarType());
3128 // This vector is the Identity vector where the first element is the
3129 // incoming scalar reduction.
3130 VectorStart = ReductionStartValue;
3132 Identity = ConstantVector::getSplat(VF, Iden);
3134 // This vector is the Identity vector where the first element is the
3135 // incoming scalar reduction.
3137 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3141 // Fix the vector-loop phi.
3143 // Reductions do not have to start at zero. They can start with
3144 // any loop invariant values.
3145 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3146 BasicBlock *Latch = OrigLoop->getLoopLatch();
3147 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3148 VectorParts &Val = getVectorValue(LoopVal);
3149 for (unsigned part = 0; part < UF; ++part) {
3150 // Make sure to add the reduction stat value only to the
3151 // first unroll part.
3152 Value *StartVal = (part == 0) ? VectorStart : Identity;
3153 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3154 LoopVectorPreHeader);
3155 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3156 LoopVectorBody.back());
3159 // Before each round, move the insertion point right between
3160 // the PHIs and the values we are going to write.
3161 // This allows us to write both PHINodes and the extractelement
3163 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3165 VectorParts RdxParts;
3166 setDebugLocFromInst(Builder, LoopExitInst);
3167 for (unsigned part = 0; part < UF; ++part) {
3168 // This PHINode contains the vectorized reduction variable, or
3169 // the initial value vector, if we bypass the vector loop.
3170 VectorParts &RdxExitVal = getVectorValue(LoopExitInst);
3171 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
3172 Value *StartVal = (part == 0) ? VectorStart : Identity;
3173 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3174 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
3175 NewPhi->addIncoming(RdxExitVal[part],
3176 LoopVectorBody.back());
3177 RdxParts.push_back(NewPhi);
3180 // Reduce all of the unrolled parts into a single vector.
3181 Value *ReducedPartRdx = RdxParts[0];
3182 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3183 setDebugLocFromInst(Builder, ReducedPartRdx);
3184 for (unsigned part = 1; part < UF; ++part) {
3185 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3186 // Floating point operations had to be 'fast' to enable the reduction.
3187 ReducedPartRdx = addFastMathFlag(
3188 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3189 ReducedPartRdx, "bin.rdx"));
3191 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3192 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3196 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3197 // and vector ops, reducing the set of values being computed by half each
3199 assert(isPowerOf2_32(VF) &&
3200 "Reduction emission only supported for pow2 vectors!");
3201 Value *TmpVec = ReducedPartRdx;
3202 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3203 for (unsigned i = VF; i != 1; i >>= 1) {
3204 // Move the upper half of the vector to the lower half.
3205 for (unsigned j = 0; j != i/2; ++j)
3206 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3208 // Fill the rest of the mask with undef.
3209 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3210 UndefValue::get(Builder.getInt32Ty()));
3213 Builder.CreateShuffleVector(TmpVec,
3214 UndefValue::get(TmpVec->getType()),
3215 ConstantVector::get(ShuffleMask),
3218 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3219 // Floating point operations had to be 'fast' to enable the reduction.
3220 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3221 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3223 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3227 // The result is in the first element of the vector.
3228 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3229 Builder.getInt32(0));
3232 // Create a phi node that merges control-flow from the backedge-taken check
3233 // block and the middle block.
3234 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3235 LoopScalarPreHeader->getTerminator());
3236 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[0]);
3237 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3239 // Now, we need to fix the users of the reduction variable
3240 // inside and outside of the scalar remainder loop.
3241 // We know that the loop is in LCSSA form. We need to update the
3242 // PHI nodes in the exit blocks.
3243 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3244 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3245 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3246 if (!LCSSAPhi) break;
3248 // All PHINodes need to have a single entry edge, or two if
3249 // we already fixed them.
3250 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3252 // We found our reduction value exit-PHI. Update it with the
3253 // incoming bypass edge.
3254 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3255 // Add an edge coming from the bypass.
3256 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3259 }// end of the LCSSA phi scan.
3261 // Fix the scalar loop reduction variable with the incoming reduction sum
3262 // from the vector body and from the backedge value.
3263 int IncomingEdgeBlockIdx =
3264 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3265 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3266 // Pick the other block.
3267 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3268 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3269 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3270 }// end of for each redux variable.
3274 // Remove redundant induction instructions.
3275 cse(LoopVectorBody);
3278 void InnerLoopVectorizer::fixLCSSAPHIs() {
3279 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3280 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3281 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3282 if (!LCSSAPhi) break;
3283 if (LCSSAPhi->getNumIncomingValues() == 1)
3284 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3289 InnerLoopVectorizer::VectorParts
3290 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3291 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3294 // Look for cached value.
3295 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3296 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3297 if (ECEntryIt != MaskCache.end())
3298 return ECEntryIt->second;
3300 VectorParts SrcMask = createBlockInMask(Src);
3302 // The terminator has to be a branch inst!
3303 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3304 assert(BI && "Unexpected terminator found");
3306 if (BI->isConditional()) {
3307 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3309 if (BI->getSuccessor(0) != Dst)
3310 for (unsigned part = 0; part < UF; ++part)
3311 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3313 for (unsigned part = 0; part < UF; ++part)
3314 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3316 MaskCache[Edge] = EdgeMask;
3320 MaskCache[Edge] = SrcMask;
3324 InnerLoopVectorizer::VectorParts
3325 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3326 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3328 // Loop incoming mask is all-one.
3329 if (OrigLoop->getHeader() == BB) {
3330 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3331 return getVectorValue(C);
3334 // This is the block mask. We OR all incoming edges, and with zero.
3335 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3336 VectorParts BlockMask = getVectorValue(Zero);
3339 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3340 VectorParts EM = createEdgeMask(*it, BB);
3341 for (unsigned part = 0; part < UF; ++part)
3342 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3348 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3349 InnerLoopVectorizer::VectorParts &Entry,
3350 unsigned UF, unsigned VF, PhiVector *PV) {
3351 PHINode* P = cast<PHINode>(PN);
3352 // Handle reduction variables:
3353 if (Legal->getReductionVars()->count(P)) {
3354 for (unsigned part = 0; part < UF; ++part) {
3355 // This is phase one of vectorizing PHIs.
3356 Type *VecTy = (VF == 1) ? PN->getType() :
3357 VectorType::get(PN->getType(), VF);
3358 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3359 LoopVectorBody.back()-> getFirstInsertionPt());
3365 setDebugLocFromInst(Builder, P);
3366 // Check for PHI nodes that are lowered to vector selects.
3367 if (P->getParent() != OrigLoop->getHeader()) {
3368 // We know that all PHIs in non-header blocks are converted into
3369 // selects, so we don't have to worry about the insertion order and we
3370 // can just use the builder.
3371 // At this point we generate the predication tree. There may be
3372 // duplications since this is a simple recursive scan, but future
3373 // optimizations will clean it up.
3375 unsigned NumIncoming = P->getNumIncomingValues();
3377 // Generate a sequence of selects of the form:
3378 // SELECT(Mask3, In3,
3379 // SELECT(Mask2, In2,
3381 for (unsigned In = 0; In < NumIncoming; In++) {
3382 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3384 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3386 for (unsigned part = 0; part < UF; ++part) {
3387 // We might have single edge PHIs (blocks) - use an identity
3388 // 'select' for the first PHI operand.
3390 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3393 // Select between the current value and the previous incoming edge
3394 // based on the incoming mask.
3395 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3396 Entry[part], "predphi");
3402 // This PHINode must be an induction variable.
3403 // Make sure that we know about it.
3404 assert(Legal->getInductionVars()->count(P) &&
3405 "Not an induction variable");
3407 LoopVectorizationLegality::InductionInfo II =
3408 Legal->getInductionVars()->lookup(P);
3410 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3411 // which can be found from the original scalar operations.
3413 case LoopVectorizationLegality::IK_NoInduction:
3414 llvm_unreachable("Unknown induction");
3415 case LoopVectorizationLegality::IK_IntInduction: {
3416 assert(P->getType() == II.StartValue->getType() && "Types must match");
3417 Type *PhiTy = P->getType();
3419 if (P == OldInduction) {
3420 // Handle the canonical induction variable. We might have had to
3422 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3424 // Handle other induction variables that are now based on the
3426 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3428 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3429 Broadcasted = II.transform(Builder, NormalizedIdx);
3430 Broadcasted->setName("offset.idx");
3432 Broadcasted = getBroadcastInstrs(Broadcasted);
3433 // After broadcasting the induction variable we need to make the vector
3434 // consecutive by adding 0, 1, 2, etc.
3435 for (unsigned part = 0; part < UF; ++part)
3436 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
3439 case LoopVectorizationLegality::IK_PtrInduction:
3440 // Handle the pointer induction variable case.
3441 assert(P->getType()->isPointerTy() && "Unexpected type.");
3442 // This is the normalized GEP that starts counting at zero.
3443 Value *NormalizedIdx =
3444 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
3446 Builder.CreateSExtOrTrunc(NormalizedIdx, II.StepValue->getType());
3447 // This is the vector of results. Notice that we don't generate
3448 // vector geps because scalar geps result in better code.
3449 for (unsigned part = 0; part < UF; ++part) {
3451 int EltIndex = part;
3452 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3453 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3454 Value *SclrGep = II.transform(Builder, GlobalIdx);
3455 SclrGep->setName("next.gep");
3456 Entry[part] = SclrGep;
3460 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3461 for (unsigned int i = 0; i < VF; ++i) {
3462 int EltIndex = i + part * VF;
3463 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3464 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3465 Value *SclrGep = II.transform(Builder, GlobalIdx);
3466 SclrGep->setName("next.gep");
3467 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3468 Builder.getInt32(i),
3471 Entry[part] = VecVal;
3477 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3478 // For each instruction in the old loop.
3479 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3480 VectorParts &Entry = WidenMap.get(it);
3481 switch (it->getOpcode()) {
3482 case Instruction::Br:
3483 // Nothing to do for PHIs and BR, since we already took care of the
3484 // loop control flow instructions.
3486 case Instruction::PHI: {
3487 // Vectorize PHINodes.
3488 widenPHIInstruction(it, Entry, UF, VF, PV);
3492 case Instruction::Add:
3493 case Instruction::FAdd:
3494 case Instruction::Sub:
3495 case Instruction::FSub:
3496 case Instruction::Mul:
3497 case Instruction::FMul:
3498 case Instruction::UDiv:
3499 case Instruction::SDiv:
3500 case Instruction::FDiv:
3501 case Instruction::URem:
3502 case Instruction::SRem:
3503 case Instruction::FRem:
3504 case Instruction::Shl:
3505 case Instruction::LShr:
3506 case Instruction::AShr:
3507 case Instruction::And:
3508 case Instruction::Or:
3509 case Instruction::Xor: {
3510 // Just widen binops.
3511 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3512 setDebugLocFromInst(Builder, BinOp);
3513 VectorParts &A = getVectorValue(it->getOperand(0));
3514 VectorParts &B = getVectorValue(it->getOperand(1));
3516 // Use this vector value for all users of the original instruction.
3517 for (unsigned Part = 0; Part < UF; ++Part) {
3518 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3520 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3521 VecOp->copyIRFlags(BinOp);
3526 propagateMetadata(Entry, it);
3529 case Instruction::Select: {
3531 // If the selector is loop invariant we can create a select
3532 // instruction with a scalar condition. Otherwise, use vector-select.
3533 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3535 setDebugLocFromInst(Builder, it);
3537 // The condition can be loop invariant but still defined inside the
3538 // loop. This means that we can't just use the original 'cond' value.
3539 // We have to take the 'vectorized' value and pick the first lane.
3540 // Instcombine will make this a no-op.
3541 VectorParts &Cond = getVectorValue(it->getOperand(0));
3542 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3543 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3545 Value *ScalarCond = (VF == 1) ? Cond[0] :
3546 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3548 for (unsigned Part = 0; Part < UF; ++Part) {
3549 Entry[Part] = Builder.CreateSelect(
3550 InvariantCond ? ScalarCond : Cond[Part],
3555 propagateMetadata(Entry, it);
3559 case Instruction::ICmp:
3560 case Instruction::FCmp: {
3561 // Widen compares. Generate vector compares.
3562 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3563 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3564 setDebugLocFromInst(Builder, it);
3565 VectorParts &A = getVectorValue(it->getOperand(0));
3566 VectorParts &B = getVectorValue(it->getOperand(1));
3567 for (unsigned Part = 0; Part < UF; ++Part) {
3570 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3572 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3576 propagateMetadata(Entry, it);
3580 case Instruction::Store:
3581 case Instruction::Load:
3582 vectorizeMemoryInstruction(it);
3584 case Instruction::ZExt:
3585 case Instruction::SExt:
3586 case Instruction::FPToUI:
3587 case Instruction::FPToSI:
3588 case Instruction::FPExt:
3589 case Instruction::PtrToInt:
3590 case Instruction::IntToPtr:
3591 case Instruction::SIToFP:
3592 case Instruction::UIToFP:
3593 case Instruction::Trunc:
3594 case Instruction::FPTrunc:
3595 case Instruction::BitCast: {
3596 CastInst *CI = dyn_cast<CastInst>(it);
3597 setDebugLocFromInst(Builder, it);
3598 /// Optimize the special case where the source is the induction
3599 /// variable. Notice that we can only optimize the 'trunc' case
3600 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3601 /// c. other casts depend on pointer size.
3602 if (CI->getOperand(0) == OldInduction &&
3603 it->getOpcode() == Instruction::Trunc) {
3604 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3606 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3607 LoopVectorizationLegality::InductionInfo II =
3608 Legal->getInductionVars()->lookup(OldInduction);
3610 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3611 for (unsigned Part = 0; Part < UF; ++Part)
3612 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3613 propagateMetadata(Entry, it);
3616 /// Vectorize casts.
3617 Type *DestTy = (VF == 1) ? CI->getType() :
3618 VectorType::get(CI->getType(), VF);
3620 VectorParts &A = getVectorValue(it->getOperand(0));
3621 for (unsigned Part = 0; Part < UF; ++Part)
3622 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3623 propagateMetadata(Entry, it);
3627 case Instruction::Call: {
3628 // Ignore dbg intrinsics.
3629 if (isa<DbgInfoIntrinsic>(it))
3631 setDebugLocFromInst(Builder, it);
3633 Module *M = BB->getParent()->getParent();
3634 CallInst *CI = cast<CallInst>(it);
3636 StringRef FnName = CI->getCalledFunction()->getName();
3637 Function *F = CI->getCalledFunction();
3638 Type *RetTy = ToVectorTy(CI->getType(), VF);
3639 SmallVector<Type *, 4> Tys;
3640 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3641 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3643 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3645 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3646 ID == Intrinsic::lifetime_start)) {
3647 scalarizeInstruction(it);
3650 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3651 // version of the instruction.
3652 // Is it beneficial to perform intrinsic call compared to lib call?
3653 bool NeedToScalarize;
3654 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3655 bool UseVectorIntrinsic =
3656 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3657 if (!UseVectorIntrinsic && NeedToScalarize) {
3658 scalarizeInstruction(it);
3662 for (unsigned Part = 0; Part < UF; ++Part) {
3663 SmallVector<Value *, 4> Args;
3664 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3665 Value *Arg = CI->getArgOperand(i);
3666 // Some intrinsics have a scalar argument - don't replace it with a
3668 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3669 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3670 Arg = VectorArg[Part];
3672 Args.push_back(Arg);
3676 if (UseVectorIntrinsic) {
3677 // Use vector version of the intrinsic.
3678 Type *TysForDecl[] = {CI->getType()};
3680 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3681 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3683 // Use vector version of the library call.
3684 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3685 assert(!VFnName.empty() && "Vector function name is empty.");
3686 VectorF = M->getFunction(VFnName);
3688 // Generate a declaration
3689 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3691 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3692 VectorF->copyAttributesFrom(F);
3695 assert(VectorF && "Can't create vector function.");
3696 Entry[Part] = Builder.CreateCall(VectorF, Args);
3699 propagateMetadata(Entry, it);
3704 // All other instructions are unsupported. Scalarize them.
3705 scalarizeInstruction(it);
3708 }// end of for_each instr.
3711 void InnerLoopVectorizer::updateAnalysis() {
3712 // Forget the original basic block.
3713 SE->forgetLoop(OrigLoop);
3715 // Update the dominator tree information.
3716 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3717 "Entry does not dominate exit.");
3719 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3720 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3721 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3723 // Due to if predication of stores we might create a sequence of "if(pred)
3724 // a[i] = ...; " blocks.
3725 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3727 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3728 else if (isPredicatedBlock(i)) {
3729 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3731 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3735 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3736 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3737 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3738 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3740 DEBUG(DT->verifyDomTree());
3743 /// \brief Check whether it is safe to if-convert this phi node.
3745 /// Phi nodes with constant expressions that can trap are not safe to if
3747 static bool canIfConvertPHINodes(BasicBlock *BB) {
3748 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3749 PHINode *Phi = dyn_cast<PHINode>(I);
3752 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3753 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3760 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3761 if (!EnableIfConversion) {
3762 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3766 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3768 // A list of pointers that we can safely read and write to.
3769 SmallPtrSet<Value *, 8> SafePointes;
3771 // Collect safe addresses.
3772 for (Loop::block_iterator BI = TheLoop->block_begin(),
3773 BE = TheLoop->block_end(); BI != BE; ++BI) {
3774 BasicBlock *BB = *BI;
3776 if (blockNeedsPredication(BB))
3779 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3780 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3781 SafePointes.insert(LI->getPointerOperand());
3782 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3783 SafePointes.insert(SI->getPointerOperand());
3787 // Collect the blocks that need predication.
3788 BasicBlock *Header = TheLoop->getHeader();
3789 for (Loop::block_iterator BI = TheLoop->block_begin(),
3790 BE = TheLoop->block_end(); BI != BE; ++BI) {
3791 BasicBlock *BB = *BI;
3793 // We don't support switch statements inside loops.
3794 if (!isa<BranchInst>(BB->getTerminator())) {
3795 emitAnalysis(VectorizationReport(BB->getTerminator())
3796 << "loop contains a switch statement");
3800 // We must be able to predicate all blocks that need to be predicated.
3801 if (blockNeedsPredication(BB)) {
3802 if (!blockCanBePredicated(BB, SafePointes)) {
3803 emitAnalysis(VectorizationReport(BB->getTerminator())
3804 << "control flow cannot be substituted for a select");
3807 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3808 emitAnalysis(VectorizationReport(BB->getTerminator())
3809 << "control flow cannot be substituted for a select");
3814 // We can if-convert this loop.
3818 bool LoopVectorizationLegality::canVectorize() {
3819 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3820 // be canonicalized.
3821 if (!TheLoop->getLoopPreheader()) {
3823 VectorizationReport() <<
3824 "loop control flow is not understood by vectorizer");
3828 // We can only vectorize innermost loops.
3829 if (!TheLoop->getSubLoopsVector().empty()) {
3830 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3834 // We must have a single backedge.
3835 if (TheLoop->getNumBackEdges() != 1) {
3837 VectorizationReport() <<
3838 "loop control flow is not understood by vectorizer");
3842 // We must have a single exiting block.
3843 if (!TheLoop->getExitingBlock()) {
3845 VectorizationReport() <<
3846 "loop control flow is not understood by vectorizer");
3850 // We only handle bottom-tested loops, i.e. loop in which the condition is
3851 // checked at the end of each iteration. With that we can assume that all
3852 // instructions in the loop are executed the same number of times.
3853 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3855 VectorizationReport() <<
3856 "loop control flow is not understood by vectorizer");
3860 // We need to have a loop header.
3861 DEBUG(dbgs() << "LV: Found a loop: " <<
3862 TheLoop->getHeader()->getName() << '\n');
3864 // Check if we can if-convert non-single-bb loops.
3865 unsigned NumBlocks = TheLoop->getNumBlocks();
3866 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3867 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3871 // ScalarEvolution needs to be able to find the exit count.
3872 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3873 if (ExitCount == SE->getCouldNotCompute()) {
3874 emitAnalysis(VectorizationReport() <<
3875 "could not determine number of loop iterations");
3876 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3880 // Check if we can vectorize the instructions and CFG in this loop.
3881 if (!canVectorizeInstrs()) {
3882 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3886 // Go over each instruction and look at memory deps.
3887 if (!canVectorizeMemory()) {
3888 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3892 // Collect all of the variables that remain uniform after vectorization.
3893 collectLoopUniforms();
3895 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3896 (LAI->getRuntimePointerCheck()->Need ? " (with a runtime bound check)" :
3900 // Analyze interleaved memory accesses.
3901 if (EnableInterleavedMemAccesses)
3902 InterleaveInfo.analyzeInterleaving(Strides);
3904 // Okay! We can vectorize. At this point we don't have any other mem analysis
3905 // which may limit our maximum vectorization factor, so just return true with
3910 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3911 if (Ty->isPointerTy())
3912 return DL.getIntPtrType(Ty);
3914 // It is possible that char's or short's overflow when we ask for the loop's
3915 // trip count, work around this by changing the type size.
3916 if (Ty->getScalarSizeInBits() < 32)
3917 return Type::getInt32Ty(Ty->getContext());
3922 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3923 Ty0 = convertPointerToIntegerType(DL, Ty0);
3924 Ty1 = convertPointerToIntegerType(DL, Ty1);
3925 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3930 /// \brief Check that the instruction has outside loop users and is not an
3931 /// identified reduction variable.
3932 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3933 SmallPtrSetImpl<Value *> &Reductions) {
3934 // Reduction instructions are allowed to have exit users. All other
3935 // instructions must not have external users.
3936 if (!Reductions.count(Inst))
3937 //Check that all of the users of the loop are inside the BB.
3938 for (User *U : Inst->users()) {
3939 Instruction *UI = cast<Instruction>(U);
3940 // This user may be a reduction exit value.
3941 if (!TheLoop->contains(UI)) {
3942 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3949 bool LoopVectorizationLegality::canVectorizeInstrs() {
3950 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3951 BasicBlock *Header = TheLoop->getHeader();
3953 // Look for the attribute signaling the absence of NaNs.
3954 Function &F = *Header->getParent();
3955 const DataLayout &DL = F.getParent()->getDataLayout();
3956 if (F.hasFnAttribute("no-nans-fp-math"))
3958 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
3960 // For each block in the loop.
3961 for (Loop::block_iterator bb = TheLoop->block_begin(),
3962 be = TheLoop->block_end(); bb != be; ++bb) {
3964 // Scan the instructions in the block and look for hazards.
3965 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3968 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3969 Type *PhiTy = Phi->getType();
3970 // Check that this PHI type is allowed.
3971 if (!PhiTy->isIntegerTy() &&
3972 !PhiTy->isFloatingPointTy() &&
3973 !PhiTy->isPointerTy()) {
3974 emitAnalysis(VectorizationReport(it)
3975 << "loop control flow is not understood by vectorizer");
3976 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3980 // If this PHINode is not in the header block, then we know that we
3981 // can convert it to select during if-conversion. No need to check if
3982 // the PHIs in this block are induction or reduction variables.
3983 if (*bb != Header) {
3984 // Check that this instruction has no outside users or is an
3985 // identified reduction value with an outside user.
3986 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3988 emitAnalysis(VectorizationReport(it) <<
3989 "value could not be identified as "
3990 "an induction or reduction variable");
3994 // We only allow if-converted PHIs with exactly two incoming values.
3995 if (Phi->getNumIncomingValues() != 2) {
3996 emitAnalysis(VectorizationReport(it)
3997 << "control flow not understood by vectorizer");
3998 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4002 // This is the value coming from the preheader.
4003 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
4004 ConstantInt *StepValue = nullptr;
4005 // Check if this is an induction variable.
4006 InductionKind IK = isInductionVariable(Phi, StepValue);
4008 if (IK_NoInduction != IK) {
4009 // Get the widest type.
4011 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4013 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4015 // Int inductions are special because we only allow one IV.
4016 if (IK == IK_IntInduction && StepValue->isOne()) {
4017 // Use the phi node with the widest type as induction. Use the last
4018 // one if there are multiple (no good reason for doing this other
4019 // than it is expedient).
4020 if (!Induction || PhiTy == WidestIndTy)
4024 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4025 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
4027 // Until we explicitly handle the case of an induction variable with
4028 // an outside loop user we have to give up vectorizing this loop.
4029 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4030 emitAnalysis(VectorizationReport(it) <<
4031 "use of induction value outside of the "
4032 "loop is not handled by vectorizer");
4039 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4041 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4045 emitAnalysis(VectorizationReport(it) <<
4046 "value that could not be identified as "
4047 "reduction is used outside the loop");
4048 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4050 }// end of PHI handling
4052 // We handle calls that:
4053 // * Are debug info intrinsics.
4054 // * Have a mapping to an IR intrinsic.
4055 // * Have a vector version available.
4056 CallInst *CI = dyn_cast<CallInst>(it);
4057 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4058 !(CI->getCalledFunction() && TLI &&
4059 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4060 emitAnalysis(VectorizationReport(it) <<
4061 "call instruction cannot be vectorized");
4062 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4066 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4067 // second argument is the same (i.e. loop invariant)
4069 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4070 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4071 emitAnalysis(VectorizationReport(it)
4072 << "intrinsic instruction cannot be vectorized");
4073 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4078 // Check that the instruction return type is vectorizable.
4079 // Also, we can't vectorize extractelement instructions.
4080 if ((!VectorType::isValidElementType(it->getType()) &&
4081 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4082 emitAnalysis(VectorizationReport(it)
4083 << "instruction return type cannot be vectorized");
4084 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4088 // Check that the stored type is vectorizable.
4089 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4090 Type *T = ST->getValueOperand()->getType();
4091 if (!VectorType::isValidElementType(T)) {
4092 emitAnalysis(VectorizationReport(ST) <<
4093 "store instruction cannot be vectorized");
4096 if (EnableMemAccessVersioning)
4097 collectStridedAccess(ST);
4100 if (EnableMemAccessVersioning)
4101 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4102 collectStridedAccess(LI);
4104 // Reduction instructions are allowed to have exit users.
4105 // All other instructions must not have external users.
4106 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4107 emitAnalysis(VectorizationReport(it) <<
4108 "value cannot be used outside the loop");
4117 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4118 if (Inductions.empty()) {
4119 emitAnalysis(VectorizationReport()
4120 << "loop induction variable could not be identified");
4128 ///\brief Remove GEPs whose indices but the last one are loop invariant and
4129 /// return the induction operand of the gep pointer.
4130 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
4131 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4135 unsigned InductionOperand = getGEPInductionOperand(GEP);
4137 // Check that all of the gep indices are uniform except for our induction
4139 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
4140 if (i != InductionOperand &&
4141 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
4143 return GEP->getOperand(InductionOperand);
4146 ///\brief Look for a cast use of the passed value.
4147 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
4148 Value *UniqueCast = nullptr;
4149 for (User *U : Ptr->users()) {
4150 CastInst *CI = dyn_cast<CastInst>(U);
4151 if (CI && CI->getType() == Ty) {
4161 ///\brief Get the stride of a pointer access in a loop.
4162 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
4163 /// pointer to the Value, or null otherwise.
4164 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
4165 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4166 if (!PtrTy || PtrTy->isAggregateType())
4169 // Try to remove a gep instruction to make the pointer (actually index at this
4170 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
4171 // pointer, otherwise, we are analyzing the index.
4172 Value *OrigPtr = Ptr;
4174 // The size of the pointer access.
4175 int64_t PtrAccessSize = 1;
4177 Ptr = stripGetElementPtr(Ptr, SE, Lp);
4178 const SCEV *V = SE->getSCEV(Ptr);
4182 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
4183 V = C->getOperand();
4185 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
4189 V = S->getStepRecurrence(*SE);
4193 // Strip off the size of access multiplication if we are still analyzing the
4195 if (OrigPtr == Ptr) {
4196 const DataLayout &DL = Lp->getHeader()->getModule()->getDataLayout();
4197 DL.getTypeAllocSize(PtrTy->getElementType());
4198 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
4199 if (M->getOperand(0)->getSCEVType() != scConstant)
4202 const APInt &APStepVal =
4203 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
4205 // Huge step value - give up.
4206 if (APStepVal.getBitWidth() > 64)
4209 int64_t StepVal = APStepVal.getSExtValue();
4210 if (PtrAccessSize != StepVal)
4212 V = M->getOperand(1);
4217 Type *StripedOffRecurrenceCast = nullptr;
4218 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
4219 StripedOffRecurrenceCast = C->getType();
4220 V = C->getOperand();
4223 // Look for the loop invariant symbolic value.
4224 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
4228 Value *Stride = U->getValue();
4229 if (!Lp->isLoopInvariant(Stride))
4232 // If we have stripped off the recurrence cast we have to make sure that we
4233 // return the value that is used in this loop so that we can replace it later.
4234 if (StripedOffRecurrenceCast)
4235 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
4240 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4241 Value *Ptr = nullptr;
4242 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4243 Ptr = LI->getPointerOperand();
4244 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4245 Ptr = SI->getPointerOperand();
4249 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4253 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4254 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4255 Strides[Ptr] = Stride;
4256 StrideSet.insert(Stride);
4259 void LoopVectorizationLegality::collectLoopUniforms() {
4260 // We now know that the loop is vectorizable!
4261 // Collect variables that will remain uniform after vectorization.
4262 std::vector<Value*> Worklist;
4263 BasicBlock *Latch = TheLoop->getLoopLatch();
4265 // Start with the conditional branch and walk up the block.
4266 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4268 // Also add all consecutive pointer values; these values will be uniform
4269 // after vectorization (and subsequent cleanup) and, until revectorization is
4270 // supported, all dependencies must also be uniform.
4271 for (Loop::block_iterator B = TheLoop->block_begin(),
4272 BE = TheLoop->block_end(); B != BE; ++B)
4273 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4275 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4276 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4278 while (!Worklist.empty()) {
4279 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4280 Worklist.pop_back();
4282 // Look at instructions inside this loop.
4283 // Stop when reaching PHI nodes.
4284 // TODO: we need to follow values all over the loop, not only in this block.
4285 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4288 // This is a known uniform.
4291 // Insert all operands.
4292 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4296 bool LoopVectorizationLegality::canVectorizeMemory() {
4297 LAI = &LAA->getInfo(TheLoop, Strides);
4298 auto &OptionalReport = LAI->getReport();
4300 emitAnalysis(VectorizationReport(*OptionalReport));
4301 if (!LAI->canVectorizeMemory())
4304 if (LAI->hasStoreToLoopInvariantAddress()) {
4306 VectorizationReport()
4307 << "write to a loop invariant address could not be vectorized");
4308 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4312 if (LAI->getNumRuntimePointerChecks() >
4313 VectorizerParams::RuntimeMemoryCheckThreshold) {
4314 emitAnalysis(VectorizationReport()
4315 << LAI->getNumRuntimePointerChecks() << " exceeds limit of "
4316 << VectorizerParams::RuntimeMemoryCheckThreshold
4317 << " dependent memory operations checked at runtime");
4318 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
4324 LoopVectorizationLegality::InductionKind
4325 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4326 ConstantInt *&StepValue) {
4327 if (!isInductionPHI(Phi, SE, StepValue))
4328 return IK_NoInduction;
4330 Type *PhiTy = Phi->getType();
4331 // Found an Integer induction variable.
4332 if (PhiTy->isIntegerTy())
4333 return IK_IntInduction;
4334 // Found an Pointer induction variable.
4335 return IK_PtrInduction;
4338 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4339 Value *In0 = const_cast<Value*>(V);
4340 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4344 return Inductions.count(PN);
4347 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4348 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4351 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4352 SmallPtrSetImpl<Value *> &SafePtrs) {
4354 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4355 // Check that we don't have a constant expression that can trap as operand.
4356 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4358 if (Constant *C = dyn_cast<Constant>(*OI))
4362 // We might be able to hoist the load.
4363 if (it->mayReadFromMemory()) {
4364 LoadInst *LI = dyn_cast<LoadInst>(it);
4367 if (!SafePtrs.count(LI->getPointerOperand())) {
4368 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4369 MaskedOp.insert(LI);
4376 // We don't predicate stores at the moment.
4377 if (it->mayWriteToMemory()) {
4378 StoreInst *SI = dyn_cast<StoreInst>(it);
4379 // We only support predication of stores in basic blocks with one
4384 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4385 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4387 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4388 !isSinglePredecessor) {
4389 // Build a masked store if it is legal for the target, otherwise scalarize
4391 bool isLegalMaskedOp =
4392 isLegalMaskedStore(SI->getValueOperand()->getType(),
4393 SI->getPointerOperand());
4394 if (isLegalMaskedOp) {
4396 MaskedOp.insert(SI);
4405 // The instructions below can trap.
4406 switch (it->getOpcode()) {
4408 case Instruction::UDiv:
4409 case Instruction::SDiv:
4410 case Instruction::URem:
4411 case Instruction::SRem:
4419 void InterleavedAccessInfo::collectConstStridedAccesses(
4420 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4421 const ValueToValueMap &Strides) {
4422 // Holds load/store instructions in program order.
4423 SmallVector<Instruction *, 16> AccessList;
4425 for (auto *BB : TheLoop->getBlocks()) {
4426 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4428 for (auto &I : *BB) {
4429 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4431 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4435 AccessList.push_back(&I);
4439 if (AccessList.empty())
4442 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4443 for (auto I : AccessList) {
4444 LoadInst *LI = dyn_cast<LoadInst>(I);
4445 StoreInst *SI = dyn_cast<StoreInst>(I);
4447 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4448 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4450 // The factor of the corresponding interleave group.
4451 unsigned Factor = std::abs(Stride);
4453 // Ignore the access if the factor is too small or too large.
4454 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4457 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4458 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4459 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4461 // An alignment of 0 means target ABI alignment.
4462 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4464 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4466 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4470 // Analyze interleaved accesses and collect them into interleave groups.
4472 // Notice that the vectorization on interleaved groups will change instruction
4473 // orders and may break dependences. But the memory dependence check guarantees
4474 // that there is no overlap between two pointers of different strides, element
4475 // sizes or underlying bases.
4477 // For pointers sharing the same stride, element size and underlying base, no
4478 // need to worry about Read-After-Write dependences and Write-After-Read
4481 // E.g. The RAW dependence: A[i] = a;
4483 // This won't exist as it is a store-load forwarding conflict, which has
4484 // already been checked and forbidden in the dependence check.
4486 // E.g. The WAR dependence: a = A[i]; // (1)
4488 // The store group of (2) is always inserted at or below (2), and the load group
4489 // of (1) is always inserted at or above (1). The dependence is safe.
4490 void InterleavedAccessInfo::analyzeInterleaving(
4491 const ValueToValueMap &Strides) {
4492 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4494 // Holds all the stride accesses.
4495 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4496 collectConstStridedAccesses(StrideAccesses, Strides);
4498 if (StrideAccesses.empty())
4501 // Holds all interleaved store groups temporarily.
4502 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4504 // Search the load-load/write-write pair B-A in bottom-up order and try to
4505 // insert B into the interleave group of A according to 3 rules:
4506 // 1. A and B have the same stride.
4507 // 2. A and B have the same memory object size.
4508 // 3. B belongs to the group according to the distance.
4510 // The bottom-up order can avoid breaking the Write-After-Write dependences
4511 // between two pointers of the same base.
4512 // E.g. A[i] = a; (1)
4515 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4516 // above (1), which guarantees that (1) is always above (2).
4517 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4519 Instruction *A = I->first;
4520 StrideDescriptor DesA = I->second;
4522 InterleaveGroup *Group = getInterleaveGroup(A);
4524 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4525 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4528 if (A->mayWriteToMemory())
4529 StoreGroups.insert(Group);
4531 for (auto II = std::next(I); II != E; ++II) {
4532 Instruction *B = II->first;
4533 StrideDescriptor DesB = II->second;
4535 // Ignore if B is already in a group or B is a different memory operation.
4536 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4539 // Check the rule 1 and 2.
4540 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4543 // Calculate the distance and prepare for the rule 3.
4544 const SCEVConstant *DistToA =
4545 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4549 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4551 // Skip if the distance is not multiple of size as they are not in the
4553 if (DistanceToA % static_cast<int>(DesA.Size))
4556 // The index of B is the index of A plus the related index to A.
4558 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4560 // Try to insert B into the group.
4561 if (Group->insertMember(B, IndexB, DesB.Align)) {
4562 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4563 << " into the interleave group with" << *A << '\n');
4564 InterleaveGroupMap[B] = Group;
4566 // Set the first load in program order as the insert position.
4567 if (B->mayReadFromMemory())
4568 Group->setInsertPos(B);
4570 } // Iteration on instruction B
4571 } // Iteration on instruction A
4573 // Remove interleaved store groups with gaps.
4574 for (InterleaveGroup *Group : StoreGroups)
4575 if (Group->getNumMembers() != Group->getFactor())
4576 releaseGroup(Group);
4579 LoopVectorizationCostModel::VectorizationFactor
4580 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4581 // Width 1 means no vectorize
4582 VectorizationFactor Factor = { 1U, 0U };
4583 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4584 emitAnalysis(VectorizationReport() <<
4585 "runtime pointer checks needed. Enable vectorization of this "
4586 "loop with '#pragma clang loop vectorize(enable)' when "
4587 "compiling with -Os");
4588 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4592 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4593 emitAnalysis(VectorizationReport() <<
4594 "store that is conditionally executed prevents vectorization");
4595 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4599 // Find the trip count.
4600 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4601 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4603 unsigned WidestType = getWidestType();
4604 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4605 unsigned MaxSafeDepDist = -1U;
4606 if (Legal->getMaxSafeDepDistBytes() != -1U)
4607 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4608 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4609 WidestRegister : MaxSafeDepDist);
4610 unsigned MaxVectorSize = WidestRegister / WidestType;
4611 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4612 DEBUG(dbgs() << "LV: The Widest register is: "
4613 << WidestRegister << " bits.\n");
4615 if (MaxVectorSize == 0) {
4616 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4620 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4621 " into one vector!");
4623 unsigned VF = MaxVectorSize;
4625 // If we optimize the program for size, avoid creating the tail loop.
4627 // If we are unable to calculate the trip count then don't try to vectorize.
4630 (VectorizationReport() <<
4631 "unable to calculate the loop count due to complex control flow");
4632 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4636 // Find the maximum SIMD width that can fit within the trip count.
4637 VF = TC % MaxVectorSize;
4642 // If the trip count that we found modulo the vectorization factor is not
4643 // zero then we require a tail.
4644 emitAnalysis(VectorizationReport() <<
4645 "cannot optimize for size and vectorize at the "
4646 "same time. Enable vectorization of this loop "
4647 "with '#pragma clang loop vectorize(enable)' "
4648 "when compiling with -Os");
4649 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4654 int UserVF = Hints->getWidth();
4656 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4657 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4659 Factor.Width = UserVF;
4663 float Cost = expectedCost(1);
4665 const float ScalarCost = Cost;
4668 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4670 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4671 // Ignore scalar width, because the user explicitly wants vectorization.
4672 if (ForceVectorization && VF > 1) {
4674 Cost = expectedCost(Width) / (float)Width;
4677 for (unsigned i=2; i <= VF; i*=2) {
4678 // Notice that the vector loop needs to be executed less times, so
4679 // we need to divide the cost of the vector loops by the width of
4680 // the vector elements.
4681 float VectorCost = expectedCost(i) / (float)i;
4682 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4683 (int)VectorCost << ".\n");
4684 if (VectorCost < Cost) {
4690 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4691 << "LV: Vectorization seems to be not beneficial, "
4692 << "but was forced by a user.\n");
4693 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4694 Factor.Width = Width;
4695 Factor.Cost = Width * Cost;
4699 unsigned LoopVectorizationCostModel::getWidestType() {
4700 unsigned MaxWidth = 8;
4701 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4704 for (Loop::block_iterator bb = TheLoop->block_begin(),
4705 be = TheLoop->block_end(); bb != be; ++bb) {
4706 BasicBlock *BB = *bb;
4708 // For each instruction in the loop.
4709 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4710 Type *T = it->getType();
4712 // Ignore ephemeral values.
4713 if (EphValues.count(it))
4716 // Only examine Loads, Stores and PHINodes.
4717 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4720 // Examine PHI nodes that are reduction variables.
4721 if (PHINode *PN = dyn_cast<PHINode>(it))
4722 if (!Legal->getReductionVars()->count(PN))
4725 // Examine the stored values.
4726 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4727 T = ST->getValueOperand()->getType();
4729 // Ignore loaded pointer types and stored pointer types that are not
4730 // consecutive. However, we do want to take consecutive stores/loads of
4731 // pointer vectors into account.
4732 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4735 MaxWidth = std::max(MaxWidth,
4736 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4744 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4746 unsigned LoopCost) {
4748 // -- The unroll heuristics --
4749 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4750 // There are many micro-architectural considerations that we can't predict
4751 // at this level. For example, frontend pressure (on decode or fetch) due to
4752 // code size, or the number and capabilities of the execution ports.
4754 // We use the following heuristics to select the unroll factor:
4755 // 1. If the code has reductions, then we unroll in order to break the cross
4756 // iteration dependency.
4757 // 2. If the loop is really small, then we unroll in order to reduce the loop
4759 // 3. We don't unroll if we think that we will spill registers to memory due
4760 // to the increased register pressure.
4762 // Use the user preference, unless 'auto' is selected.
4763 int UserUF = Hints->getInterleave();
4767 // When we optimize for size, we don't unroll.
4771 // We used the distance for the unroll factor.
4772 if (Legal->getMaxSafeDepDistBytes() != -1U)
4775 // Do not unroll loops with a relatively small trip count.
4776 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4777 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4780 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4781 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4785 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4786 TargetNumRegisters = ForceTargetNumScalarRegs;
4788 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4789 TargetNumRegisters = ForceTargetNumVectorRegs;
4792 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4793 // We divide by these constants so assume that we have at least one
4794 // instruction that uses at least one register.
4795 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4796 R.NumInstructions = std::max(R.NumInstructions, 1U);
4798 // We calculate the unroll factor using the following formula.
4799 // Subtract the number of loop invariants from the number of available
4800 // registers. These registers are used by all of the unrolled instances.
4801 // Next, divide the remaining registers by the number of registers that is
4802 // required by the loop, in order to estimate how many parallel instances
4803 // fit without causing spills. All of this is rounded down if necessary to be
4804 // a power of two. We want power of two unroll factors to simplify any
4805 // addressing operations or alignment considerations.
4806 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4809 // Don't count the induction variable as unrolled.
4810 if (EnableIndVarRegisterHeur)
4811 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4812 std::max(1U, (R.MaxLocalUsers - 1)));
4814 // Clamp the unroll factor ranges to reasonable factors.
4815 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor(VF);
4817 // Check if the user has overridden the unroll max.
4819 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4820 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
4822 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4823 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
4826 // If we did not calculate the cost for VF (because the user selected the VF)
4827 // then we calculate the cost of VF here.
4829 LoopCost = expectedCost(VF);
4831 // Clamp the calculated UF to be between the 1 and the max unroll factor
4832 // that the target allows.
4833 if (UF > MaxInterleaveSize)
4834 UF = MaxInterleaveSize;
4838 // Unroll if we vectorized this loop and there is a reduction that could
4839 // benefit from unrolling.
4840 if (VF > 1 && Legal->getReductionVars()->size()) {
4841 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4845 // Note that if we've already vectorized the loop we will have done the
4846 // runtime check and so unrolling won't require further checks.
4847 bool UnrollingRequiresRuntimePointerCheck =
4848 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
4850 // We want to unroll small loops in order to reduce the loop overhead and
4851 // potentially expose ILP opportunities.
4852 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4853 if (!UnrollingRequiresRuntimePointerCheck &&
4854 LoopCost < SmallLoopCost) {
4855 // We assume that the cost overhead is 1 and we use the cost model
4856 // to estimate the cost of the loop and unroll until the cost of the
4857 // loop overhead is about 5% of the cost of the loop.
4858 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4860 // Unroll until store/load ports (estimated by max unroll factor) are
4862 unsigned NumStores = Legal->getNumStores();
4863 unsigned NumLoads = Legal->getNumLoads();
4864 unsigned StoresUF = UF / (NumStores ? NumStores : 1);
4865 unsigned LoadsUF = UF / (NumLoads ? NumLoads : 1);
4867 // If we have a scalar reduction (vector reductions are already dealt with
4868 // by this point), we can increase the critical path length if the loop
4869 // we're unrolling is inside another loop. Limit, by default to 2, so the
4870 // critical path only gets increased by one reduction operation.
4871 if (Legal->getReductionVars()->size() &&
4872 TheLoop->getLoopDepth() > 1) {
4873 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
4874 SmallUF = std::min(SmallUF, F);
4875 StoresUF = std::min(StoresUF, F);
4876 LoadsUF = std::min(LoadsUF, F);
4879 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
4880 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
4881 return std::max(StoresUF, LoadsUF);
4884 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4888 // Unroll if this is a large loop (small loops are already dealt with by this
4889 // point) that could benefit from interleaved unrolling.
4890 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4891 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4892 DEBUG(dbgs() << "LV: Unrolling to expose ILP.\n");
4896 DEBUG(dbgs() << "LV: Not Unrolling.\n");
4900 LoopVectorizationCostModel::RegisterUsage
4901 LoopVectorizationCostModel::calculateRegisterUsage() {
4902 // This function calculates the register usage by measuring the highest number
4903 // of values that are alive at a single location. Obviously, this is a very
4904 // rough estimation. We scan the loop in a topological order in order and
4905 // assign a number to each instruction. We use RPO to ensure that defs are
4906 // met before their users. We assume that each instruction that has in-loop
4907 // users starts an interval. We record every time that an in-loop value is
4908 // used, so we have a list of the first and last occurrences of each
4909 // instruction. Next, we transpose this data structure into a multi map that
4910 // holds the list of intervals that *end* at a specific location. This multi
4911 // map allows us to perform a linear search. We scan the instructions linearly
4912 // and record each time that a new interval starts, by placing it in a set.
4913 // If we find this value in the multi-map then we remove it from the set.
4914 // The max register usage is the maximum size of the set.
4915 // We also search for instructions that are defined outside the loop, but are
4916 // used inside the loop. We need this number separately from the max-interval
4917 // usage number because when we unroll, loop-invariant values do not take
4919 LoopBlocksDFS DFS(TheLoop);
4923 R.NumInstructions = 0;
4925 // Each 'key' in the map opens a new interval. The values
4926 // of the map are the index of the 'last seen' usage of the
4927 // instruction that is the key.
4928 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4929 // Maps instruction to its index.
4930 DenseMap<unsigned, Instruction*> IdxToInstr;
4931 // Marks the end of each interval.
4932 IntervalMap EndPoint;
4933 // Saves the list of instruction indices that are used in the loop.
4934 SmallSet<Instruction*, 8> Ends;
4935 // Saves the list of values that are used in the loop but are
4936 // defined outside the loop, such as arguments and constants.
4937 SmallPtrSet<Value*, 8> LoopInvariants;
4940 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4941 be = DFS.endRPO(); bb != be; ++bb) {
4942 R.NumInstructions += (*bb)->size();
4943 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4945 Instruction *I = it;
4946 IdxToInstr[Index++] = I;
4948 // Save the end location of each USE.
4949 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4950 Value *U = I->getOperand(i);
4951 Instruction *Instr = dyn_cast<Instruction>(U);
4953 // Ignore non-instruction values such as arguments, constants, etc.
4954 if (!Instr) continue;
4956 // If this instruction is outside the loop then record it and continue.
4957 if (!TheLoop->contains(Instr)) {
4958 LoopInvariants.insert(Instr);
4962 // Overwrite previous end points.
4963 EndPoint[Instr] = Index;
4969 // Saves the list of intervals that end with the index in 'key'.
4970 typedef SmallVector<Instruction*, 2> InstrList;
4971 DenseMap<unsigned, InstrList> TransposeEnds;
4973 // Transpose the EndPoints to a list of values that end at each index.
4974 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4976 TransposeEnds[it->second].push_back(it->first);
4978 SmallSet<Instruction*, 8> OpenIntervals;
4979 unsigned MaxUsage = 0;
4982 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4983 for (unsigned int i = 0; i < Index; ++i) {
4984 Instruction *I = IdxToInstr[i];
4985 // Ignore instructions that are never used within the loop.
4986 if (!Ends.count(I)) continue;
4988 // Ignore ephemeral values.
4989 if (EphValues.count(I))
4992 // Remove all of the instructions that end at this location.
4993 InstrList &List = TransposeEnds[i];
4994 for (unsigned int j=0, e = List.size(); j < e; ++j)
4995 OpenIntervals.erase(List[j]);
4997 // Count the number of live interals.
4998 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5000 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5001 OpenIntervals.size() << '\n');
5003 // Add the current instruction to the list of open intervals.
5004 OpenIntervals.insert(I);
5007 unsigned Invariant = LoopInvariants.size();
5008 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5009 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5010 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5012 R.LoopInvariantRegs = Invariant;
5013 R.MaxLocalUsers = MaxUsage;
5017 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5021 for (Loop::block_iterator bb = TheLoop->block_begin(),
5022 be = TheLoop->block_end(); bb != be; ++bb) {
5023 unsigned BlockCost = 0;
5024 BasicBlock *BB = *bb;
5026 // For each instruction in the old loop.
5027 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5028 // Skip dbg intrinsics.
5029 if (isa<DbgInfoIntrinsic>(it))
5032 // Ignore ephemeral values.
5033 if (EphValues.count(it))
5036 unsigned C = getInstructionCost(it, VF);
5038 // Check if we should override the cost.
5039 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5040 C = ForceTargetInstructionCost;
5043 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5044 VF << " For instruction: " << *it << '\n');
5047 // We assume that if-converted blocks have a 50% chance of being executed.
5048 // When the code is scalar then some of the blocks are avoided due to CF.
5049 // When the code is vectorized we execute all code paths.
5050 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5059 /// \brief Check whether the address computation for a non-consecutive memory
5060 /// access looks like an unlikely candidate for being merged into the indexing
5063 /// We look for a GEP which has one index that is an induction variable and all
5064 /// other indices are loop invariant. If the stride of this access is also
5065 /// within a small bound we decide that this address computation can likely be
5066 /// merged into the addressing mode.
5067 /// In all other cases, we identify the address computation as complex.
5068 static bool isLikelyComplexAddressComputation(Value *Ptr,
5069 LoopVectorizationLegality *Legal,
5070 ScalarEvolution *SE,
5071 const Loop *TheLoop) {
5072 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5076 // We are looking for a gep with all loop invariant indices except for one
5077 // which should be an induction variable.
5078 unsigned NumOperands = Gep->getNumOperands();
5079 for (unsigned i = 1; i < NumOperands; ++i) {
5080 Value *Opd = Gep->getOperand(i);
5081 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5082 !Legal->isInductionVariable(Opd))
5086 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5087 // can likely be merged into the address computation.
5088 unsigned MaxMergeDistance = 64;
5090 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5094 // Check the step is constant.
5095 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5096 // Calculate the pointer stride and check if it is consecutive.
5097 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5101 const APInt &APStepVal = C->getValue()->getValue();
5103 // Huge step value - give up.
5104 if (APStepVal.getBitWidth() > 64)
5107 int64_t StepVal = APStepVal.getSExtValue();
5109 return StepVal > MaxMergeDistance;
5112 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5113 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5119 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5120 // If we know that this instruction will remain uniform, check the cost of
5121 // the scalar version.
5122 if (Legal->isUniformAfterVectorization(I))
5125 Type *RetTy = I->getType();
5126 Type *VectorTy = ToVectorTy(RetTy, VF);
5128 // TODO: We need to estimate the cost of intrinsic calls.
5129 switch (I->getOpcode()) {
5130 case Instruction::GetElementPtr:
5131 // We mark this instruction as zero-cost because the cost of GEPs in
5132 // vectorized code depends on whether the corresponding memory instruction
5133 // is scalarized or not. Therefore, we handle GEPs with the memory
5134 // instruction cost.
5136 case Instruction::Br: {
5137 return TTI.getCFInstrCost(I->getOpcode());
5139 case Instruction::PHI:
5140 //TODO: IF-converted IFs become selects.
5142 case Instruction::Add:
5143 case Instruction::FAdd:
5144 case Instruction::Sub:
5145 case Instruction::FSub:
5146 case Instruction::Mul:
5147 case Instruction::FMul:
5148 case Instruction::UDiv:
5149 case Instruction::SDiv:
5150 case Instruction::FDiv:
5151 case Instruction::URem:
5152 case Instruction::SRem:
5153 case Instruction::FRem:
5154 case Instruction::Shl:
5155 case Instruction::LShr:
5156 case Instruction::AShr:
5157 case Instruction::And:
5158 case Instruction::Or:
5159 case Instruction::Xor: {
5160 // Since we will replace the stride by 1 the multiplication should go away.
5161 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5163 // Certain instructions can be cheaper to vectorize if they have a constant
5164 // second vector operand. One example of this are shifts on x86.
5165 TargetTransformInfo::OperandValueKind Op1VK =
5166 TargetTransformInfo::OK_AnyValue;
5167 TargetTransformInfo::OperandValueKind Op2VK =
5168 TargetTransformInfo::OK_AnyValue;
5169 TargetTransformInfo::OperandValueProperties Op1VP =
5170 TargetTransformInfo::OP_None;
5171 TargetTransformInfo::OperandValueProperties Op2VP =
5172 TargetTransformInfo::OP_None;
5173 Value *Op2 = I->getOperand(1);
5175 // Check for a splat of a constant or for a non uniform vector of constants.
5176 if (isa<ConstantInt>(Op2)) {
5177 ConstantInt *CInt = cast<ConstantInt>(Op2);
5178 if (CInt && CInt->getValue().isPowerOf2())
5179 Op2VP = TargetTransformInfo::OP_PowerOf2;
5180 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5181 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5182 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5183 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5185 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5186 if (CInt && CInt->getValue().isPowerOf2())
5187 Op2VP = TargetTransformInfo::OP_PowerOf2;
5188 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5192 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5195 case Instruction::Select: {
5196 SelectInst *SI = cast<SelectInst>(I);
5197 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5198 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5199 Type *CondTy = SI->getCondition()->getType();
5201 CondTy = VectorType::get(CondTy, VF);
5203 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5205 case Instruction::ICmp:
5206 case Instruction::FCmp: {
5207 Type *ValTy = I->getOperand(0)->getType();
5208 VectorTy = ToVectorTy(ValTy, VF);
5209 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5211 case Instruction::Store:
5212 case Instruction::Load: {
5213 StoreInst *SI = dyn_cast<StoreInst>(I);
5214 LoadInst *LI = dyn_cast<LoadInst>(I);
5215 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5217 VectorTy = ToVectorTy(ValTy, VF);
5219 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5220 unsigned AS = SI ? SI->getPointerAddressSpace() :
5221 LI->getPointerAddressSpace();
5222 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5223 // We add the cost of address computation here instead of with the gep
5224 // instruction because only here we know whether the operation is
5227 return TTI.getAddressComputationCost(VectorTy) +
5228 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5230 // For an interleaved access, calculate the total cost of the whole
5231 // interleave group.
5232 if (Legal->isAccessInterleaved(I)) {
5233 auto Group = Legal->getInterleavedAccessGroup(I);
5234 assert(Group && "Fail to get an interleaved access group.");
5236 // Only calculate the cost once at the insert position.
5237 if (Group->getInsertPos() != I)
5240 unsigned InterleaveFactor = Group->getFactor();
5242 VectorType::get(VectorTy->getVectorElementType(),
5243 VectorTy->getVectorNumElements() * InterleaveFactor);
5245 // Holds the indices of existing members in an interleaved load group.
5246 // An interleaved store group doesn't need this as it dones't allow gaps.
5247 SmallVector<unsigned, 4> Indices;
5249 for (unsigned i = 0; i < InterleaveFactor; i++)
5250 if (Group->getMember(i))
5251 Indices.push_back(i);
5254 // Calculate the cost of the whole interleaved group.
5255 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5256 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5257 Group->getAlignment(), AS);
5259 if (Group->isReverse())
5261 Group->getNumMembers() *
5262 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5264 // FIXME: The interleaved load group with a huge gap could be even more
5265 // expensive than scalar operations. Then we could ignore such group and
5266 // use scalar operations instead.
5270 // Scalarized loads/stores.
5271 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5272 bool Reverse = ConsecutiveStride < 0;
5273 const DataLayout &DL = I->getModule()->getDataLayout();
5274 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5275 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5276 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5277 bool IsComplexComputation =
5278 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5280 // The cost of extracting from the value vector and pointer vector.
5281 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5282 for (unsigned i = 0; i < VF; ++i) {
5283 // The cost of extracting the pointer operand.
5284 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5285 // In case of STORE, the cost of ExtractElement from the vector.
5286 // In case of LOAD, the cost of InsertElement into the returned
5288 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5289 Instruction::InsertElement,
5293 // The cost of the scalar loads/stores.
5294 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5295 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5300 // Wide load/stores.
5301 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5302 if (Legal->isMaskRequired(I))
5303 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5306 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5309 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5313 case Instruction::ZExt:
5314 case Instruction::SExt:
5315 case Instruction::FPToUI:
5316 case Instruction::FPToSI:
5317 case Instruction::FPExt:
5318 case Instruction::PtrToInt:
5319 case Instruction::IntToPtr:
5320 case Instruction::SIToFP:
5321 case Instruction::UIToFP:
5322 case Instruction::Trunc:
5323 case Instruction::FPTrunc:
5324 case Instruction::BitCast: {
5325 // We optimize the truncation of induction variable.
5326 // The cost of these is the same as the scalar operation.
5327 if (I->getOpcode() == Instruction::Trunc &&
5328 Legal->isInductionVariable(I->getOperand(0)))
5329 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5330 I->getOperand(0)->getType());
5332 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5333 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5335 case Instruction::Call: {
5336 bool NeedToScalarize;
5337 CallInst *CI = cast<CallInst>(I);
5338 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5339 if (getIntrinsicIDForCall(CI, TLI))
5340 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5344 // We are scalarizing the instruction. Return the cost of the scalar
5345 // instruction, plus the cost of insert and extract into vector
5346 // elements, times the vector width.
5349 if (!RetTy->isVoidTy() && VF != 1) {
5350 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5352 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5355 // The cost of inserting the results plus extracting each one of the
5357 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5360 // The cost of executing VF copies of the scalar instruction. This opcode
5361 // is unknown. Assume that it is the same as 'mul'.
5362 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5368 char LoopVectorize::ID = 0;
5369 static const char lv_name[] = "Loop Vectorization";
5370 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5371 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5372 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5373 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5374 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5375 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5376 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5377 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5378 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5379 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5380 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5381 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5384 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5385 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5389 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5390 // Check for a store.
5391 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5392 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5394 // Check for a load.
5395 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5396 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5402 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5403 bool IfPredicateStore) {
5404 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5405 // Holds vector parameters or scalars, in case of uniform vals.
5406 SmallVector<VectorParts, 4> Params;
5408 setDebugLocFromInst(Builder, Instr);
5410 // Find all of the vectorized parameters.
5411 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5412 Value *SrcOp = Instr->getOperand(op);
5414 // If we are accessing the old induction variable, use the new one.
5415 if (SrcOp == OldInduction) {
5416 Params.push_back(getVectorValue(SrcOp));
5420 // Try using previously calculated values.
5421 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5423 // If the src is an instruction that appeared earlier in the basic block
5424 // then it should already be vectorized.
5425 if (SrcInst && OrigLoop->contains(SrcInst)) {
5426 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5427 // The parameter is a vector value from earlier.
5428 Params.push_back(WidenMap.get(SrcInst));
5430 // The parameter is a scalar from outside the loop. Maybe even a constant.
5431 VectorParts Scalars;
5432 Scalars.append(UF, SrcOp);
5433 Params.push_back(Scalars);
5437 assert(Params.size() == Instr->getNumOperands() &&
5438 "Invalid number of operands");
5440 // Does this instruction return a value ?
5441 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5443 Value *UndefVec = IsVoidRetTy ? nullptr :
5444 UndefValue::get(Instr->getType());
5445 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5446 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5448 Instruction *InsertPt = Builder.GetInsertPoint();
5449 BasicBlock *IfBlock = Builder.GetInsertBlock();
5450 BasicBlock *CondBlock = nullptr;
5453 Loop *VectorLp = nullptr;
5454 if (IfPredicateStore) {
5455 assert(Instr->getParent()->getSinglePredecessor() &&
5456 "Only support single predecessor blocks");
5457 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5458 Instr->getParent());
5459 VectorLp = LI->getLoopFor(IfBlock);
5460 assert(VectorLp && "Must have a loop for this block");
5463 // For each vector unroll 'part':
5464 for (unsigned Part = 0; Part < UF; ++Part) {
5465 // For each scalar that we create:
5467 // Start an "if (pred) a[i] = ..." block.
5468 Value *Cmp = nullptr;
5469 if (IfPredicateStore) {
5470 if (Cond[Part]->getType()->isVectorTy())
5472 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5473 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5474 ConstantInt::get(Cond[Part]->getType(), 1));
5475 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5476 LoopVectorBody.push_back(CondBlock);
5477 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5478 // Update Builder with newly created basic block.
5479 Builder.SetInsertPoint(InsertPt);
5482 Instruction *Cloned = Instr->clone();
5484 Cloned->setName(Instr->getName() + ".cloned");
5485 // Replace the operands of the cloned instructions with extracted scalars.
5486 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5487 Value *Op = Params[op][Part];
5488 Cloned->setOperand(op, Op);
5491 // Place the cloned scalar in the new loop.
5492 Builder.Insert(Cloned);
5494 // If the original scalar returns a value we need to place it in a vector
5495 // so that future users will be able to use it.
5497 VecResults[Part] = Cloned;
5500 if (IfPredicateStore) {
5501 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5502 LoopVectorBody.push_back(NewIfBlock);
5503 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5504 Builder.SetInsertPoint(InsertPt);
5505 ReplaceInstWithInst(IfBlock->getTerminator(),
5506 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
5507 IfBlock = NewIfBlock;
5512 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5513 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5514 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5516 return scalarizeInstruction(Instr, IfPredicateStore);
5519 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5523 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5527 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5528 // When unrolling and the VF is 1, we only need to add a simple scalar.
5529 Type *ITy = Val->getType();
5530 assert(!ITy->isVectorTy() && "Val must be a scalar");
5531 Constant *C = ConstantInt::get(ITy, StartIdx);
5532 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");