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 interleave loops with a known constant trip count below this
153 static const unsigned TinyTripCountInterleaveThreshold = 128;
155 static cl::opt<unsigned> ForceTargetNumScalarRegs(
156 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's number of scalar registers."));
159 static cl::opt<unsigned> ForceTargetNumVectorRegs(
160 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
161 cl::desc("A flag that overrides the target's number of vector registers."));
163 /// Maximum vectorization interleave count.
164 static const unsigned MaxInterleaveFactor = 16;
166 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
167 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
168 cl::desc("A flag that overrides the target's max interleave factor for "
171 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
172 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
173 cl::desc("A flag that overrides the target's max interleave factor for "
174 "vectorized loops."));
176 static cl::opt<unsigned> ForceTargetInstructionCost(
177 "force-target-instruction-cost", cl::init(0), cl::Hidden,
178 cl::desc("A flag that overrides the target's expected cost for "
179 "an instruction to a single constant value. Mostly "
180 "useful for getting consistent testing."));
182 static cl::opt<unsigned> SmallLoopCost(
183 "small-loop-cost", cl::init(20), cl::Hidden,
185 "The cost of a loop that is considered 'small' by the interleaver."));
187 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
188 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
189 cl::desc("Enable the use of the block frequency analysis to access PGO "
190 "heuristics minimizing code growth in cold regions and being more "
191 "aggressive in hot regions."));
193 // Runtime interleave loops for load/store throughput.
194 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
195 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
197 "Enable runtime interleaving until load/store ports are saturated"));
199 /// The number of stores in a loop that are allowed to need predication.
200 static cl::opt<unsigned> NumberOfStoresToPredicate(
201 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
202 cl::desc("Max number of stores to be predicated behind an if."));
204 static cl::opt<bool> EnableIndVarRegisterHeur(
205 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
206 cl::desc("Count the induction variable only once when interleaving"));
208 static cl::opt<bool> EnableCondStoresVectorization(
209 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
210 cl::desc("Enable if predication of stores during vectorization."));
212 static cl::opt<unsigned> MaxNestedScalarReductionIC(
213 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
214 cl::desc("The maximum interleave count to use when interleaving a scalar "
215 "reduction in a nested loop."));
217 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
218 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
219 cl::desc("The maximum allowed number of runtime memory checks with a "
220 "vectorize(enable) pragma."));
224 // Forward declarations.
225 class LoopVectorizeHints;
226 class LoopVectorizationLegality;
227 class LoopVectorizationCostModel;
228 class LoopVectorizationRequirements;
230 /// \brief This modifies LoopAccessReport to initialize message with
231 /// loop-vectorizer-specific part.
232 class VectorizationReport : public LoopAccessReport {
234 VectorizationReport(Instruction *I = nullptr)
235 : LoopAccessReport("loop not vectorized: ", I) {}
237 /// \brief This allows promotion of the loop-access analysis report into the
238 /// loop-vectorizer report. It modifies the message to add the
239 /// loop-vectorizer-specific part of the message.
240 explicit VectorizationReport(const LoopAccessReport &R)
241 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
245 /// A helper function for converting Scalar types to vector types.
246 /// If the incoming type is void, we return void. If the VF is 1, we return
248 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
249 if (Scalar->isVoidTy() || VF == 1)
251 return VectorType::get(Scalar, VF);
254 /// InnerLoopVectorizer vectorizes loops which contain only one basic
255 /// block to a specified vectorization factor (VF).
256 /// This class performs the widening of scalars into vectors, or multiple
257 /// scalars. This class also implements the following features:
258 /// * It inserts an epilogue loop for handling loops that don't have iteration
259 /// counts that are known to be a multiple of the vectorization factor.
260 /// * It handles the code generation for reduction variables.
261 /// * Scalarization (implementation using scalars) of un-vectorizable
263 /// InnerLoopVectorizer does not perform any vectorization-legality
264 /// checks, and relies on the caller to check for the different legality
265 /// aspects. The InnerLoopVectorizer relies on the
266 /// LoopVectorizationLegality class to provide information about the induction
267 /// and reduction variables that were found to a given vectorization factor.
268 class InnerLoopVectorizer {
270 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
271 DominatorTree *DT, const TargetLibraryInfo *TLI,
272 const TargetTransformInfo *TTI, unsigned VecWidth,
273 unsigned UnrollFactor)
274 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
275 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
276 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
277 TripCount(nullptr), VectorTripCount(nullptr), Legal(nullptr),
278 AddedSafetyChecks(false) {}
280 // Perform the actual loop widening (vectorization).
281 void vectorize(LoopVectorizationLegality *L) {
283 // Create a new empty loop. Unlink the old loop and connect the new one.
285 // Widen each instruction in the old loop to a new one in the new loop.
286 // Use the Legality module to find the induction and reduction variables.
290 // Return true if any runtime check is added.
291 bool IsSafetyChecksAdded() {
292 return AddedSafetyChecks;
295 virtual ~InnerLoopVectorizer() {}
298 /// A small list of PHINodes.
299 typedef SmallVector<PHINode*, 4> PhiVector;
300 /// When we unroll loops we have multiple vector values for each scalar.
301 /// This data structure holds the unrolled and vectorized values that
302 /// originated from one scalar instruction.
303 typedef SmallVector<Value*, 2> VectorParts;
305 // When we if-convert we need to create edge masks. We have to cache values
306 // so that we don't end up with exponential recursion/IR.
307 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
308 VectorParts> EdgeMaskCache;
310 /// \brief Add checks for strides that were assumed to be 1.
312 /// Returns the last check instruction and the first check instruction in the
313 /// pair as (first, last).
314 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
316 /// Create an empty loop, based on the loop ranges of the old loop.
317 void createEmptyLoop();
318 /// Create a new induction variable inside L.
319 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
320 Value *Step, Instruction *DL);
321 /// Copy and widen the instructions from the old loop.
322 virtual void vectorizeLoop();
324 /// \brief The Loop exit block may have single value PHI nodes where the
325 /// incoming value is 'Undef'. While vectorizing we only handled real values
326 /// that were defined inside the loop. Here we fix the 'undef case'.
330 /// A helper function that computes the predicate of the block BB, assuming
331 /// that the header block of the loop is set to True. It returns the *entry*
332 /// mask for the block BB.
333 VectorParts createBlockInMask(BasicBlock *BB);
334 /// A helper function that computes the predicate of the edge between SRC
336 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
338 /// A helper function to vectorize a single BB within the innermost loop.
339 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
341 /// Vectorize a single PHINode in a block. This method handles the induction
342 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
343 /// arbitrary length vectors.
344 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
345 unsigned UF, unsigned VF, PhiVector *PV);
347 /// Insert the new loop to the loop hierarchy and pass manager
348 /// and update the analysis passes.
349 void updateAnalysis();
351 /// This instruction is un-vectorizable. Implement it as a sequence
352 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
353 /// scalarized instruction behind an if block predicated on the control
354 /// dependence of the instruction.
355 virtual void scalarizeInstruction(Instruction *Instr,
356 bool IfPredicateStore=false);
358 /// Vectorize Load and Store instructions,
359 virtual void vectorizeMemoryInstruction(Instruction *Instr);
361 /// Create a broadcast instruction. This method generates a broadcast
362 /// instruction (shuffle) for loop invariant values and for the induction
363 /// value. If this is the induction variable then we extend it to N, N+1, ...
364 /// this is needed because each iteration in the loop corresponds to a SIMD
366 virtual Value *getBroadcastInstrs(Value *V);
368 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
369 /// to each vector element of Val. The sequence starts at StartIndex.
370 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
372 /// When we go over instructions in the basic block we rely on previous
373 /// values within the current basic block or on loop invariant values.
374 /// When we widen (vectorize) values we place them in the map. If the values
375 /// are not within the map, they have to be loop invariant, so we simply
376 /// broadcast them into a vector.
377 VectorParts &getVectorValue(Value *V);
379 /// Try to vectorize the interleaved access group that \p Instr belongs to.
380 void vectorizeInterleaveGroup(Instruction *Instr);
382 /// Generate a shuffle sequence that will reverse the vector Vec.
383 virtual Value *reverseVector(Value *Vec);
385 /// Returns (and creates if needed) the original loop trip count.
386 Value *getOrCreateTripCount(Loop *NewLoop);
388 /// Returns (and creates if needed) the trip count of the widened loop.
389 Value *getOrCreateVectorTripCount(Loop *NewLoop);
391 /// Emit a bypass check to see if the trip count would overflow, or we
392 /// wouldn't have enough iterations to execute one vector loop.
393 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
394 /// Emit a bypass check to see if the vector trip count is nonzero.
395 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
396 /// Emit bypass checks to check if strides we've assumed to be one really are.
397 void emitStrideChecks(Loop *L, BasicBlock *Bypass);
398 /// Emit bypass checks to check any memory assumptions we may have made.
399 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
401 /// This is a helper class that holds the vectorizer state. It maps scalar
402 /// instructions to vector instructions. When the code is 'unrolled' then
403 /// then a single scalar value is mapped to multiple vector parts. The parts
404 /// are stored in the VectorPart type.
406 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
408 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
410 /// \return True if 'Key' is saved in the Value Map.
411 bool has(Value *Key) const { return MapStorage.count(Key); }
413 /// Initializes a new entry in the map. Sets all of the vector parts to the
414 /// save value in 'Val'.
415 /// \return A reference to a vector with splat values.
416 VectorParts &splat(Value *Key, Value *Val) {
417 VectorParts &Entry = MapStorage[Key];
418 Entry.assign(UF, Val);
422 ///\return A reference to the value that is stored at 'Key'.
423 VectorParts &get(Value *Key) {
424 VectorParts &Entry = MapStorage[Key];
427 assert(Entry.size() == UF);
432 /// The unroll factor. Each entry in the map stores this number of vector
436 /// Map storage. We use std::map and not DenseMap because insertions to a
437 /// dense map invalidates its iterators.
438 std::map<Value *, VectorParts> MapStorage;
441 /// The original loop.
443 /// Scev analysis to use.
451 /// Target Library Info.
452 const TargetLibraryInfo *TLI;
453 /// Target Transform Info.
454 const TargetTransformInfo *TTI;
456 /// The vectorization SIMD factor to use. Each vector will have this many
461 /// The vectorization unroll factor to use. Each scalar is vectorized to this
462 /// many different vector instructions.
465 /// The builder that we use
468 // --- Vectorization state ---
470 /// The vector-loop preheader.
471 BasicBlock *LoopVectorPreHeader;
472 /// The scalar-loop preheader.
473 BasicBlock *LoopScalarPreHeader;
474 /// Middle Block between the vector and the scalar.
475 BasicBlock *LoopMiddleBlock;
476 ///The ExitBlock of the scalar loop.
477 BasicBlock *LoopExitBlock;
478 ///The vector loop body.
479 SmallVector<BasicBlock *, 4> LoopVectorBody;
480 ///The scalar loop body.
481 BasicBlock *LoopScalarBody;
482 /// A list of all bypass blocks. The first block is the entry of the loop.
483 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
485 /// The new Induction variable which was added to the new block.
487 /// The induction variable of the old basic block.
488 PHINode *OldInduction;
489 /// Maps scalars to widened vectors.
491 /// Store instructions that should be predicated, as a pair
492 /// <StoreInst, Predicate>
493 SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
494 EdgeMaskCache MaskCache;
495 /// Trip count of the original loop.
497 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
498 Value *VectorTripCount;
500 LoopVectorizationLegality *Legal;
502 // Record whether runtime check is added.
503 bool AddedSafetyChecks;
506 class InnerLoopUnroller : public InnerLoopVectorizer {
508 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
509 DominatorTree *DT, const TargetLibraryInfo *TLI,
510 const TargetTransformInfo *TTI, unsigned UnrollFactor)
511 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
514 void scalarizeInstruction(Instruction *Instr,
515 bool IfPredicateStore = false) override;
516 void vectorizeMemoryInstruction(Instruction *Instr) override;
517 Value *getBroadcastInstrs(Value *V) override;
518 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
519 Value *reverseVector(Value *Vec) override;
522 /// \brief Look for a meaningful debug location on the instruction or it's
524 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
529 if (I->getDebugLoc() != Empty)
532 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
533 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
534 if (OpInst->getDebugLoc() != Empty)
541 /// \brief Set the debug location in the builder using the debug location in the
543 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
544 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
545 B.SetCurrentDebugLocation(Inst->getDebugLoc());
547 B.SetCurrentDebugLocation(DebugLoc());
551 /// \return string containing a file name and a line # for the given loop.
552 static std::string getDebugLocString(const Loop *L) {
555 raw_string_ostream OS(Result);
556 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
557 LoopDbgLoc.print(OS);
559 // Just print the module name.
560 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
567 /// \brief Propagate known metadata from one instruction to another.
568 static void propagateMetadata(Instruction *To, const Instruction *From) {
569 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
570 From->getAllMetadataOtherThanDebugLoc(Metadata);
572 for (auto M : Metadata) {
573 unsigned Kind = M.first;
575 // These are safe to transfer (this is safe for TBAA, even when we
576 // if-convert, because should that metadata have had a control dependency
577 // on the condition, and thus actually aliased with some other
578 // non-speculated memory access when the condition was false, this would be
579 // caught by the runtime overlap checks).
580 if (Kind != LLVMContext::MD_tbaa &&
581 Kind != LLVMContext::MD_alias_scope &&
582 Kind != LLVMContext::MD_noalias &&
583 Kind != LLVMContext::MD_fpmath &&
584 Kind != LLVMContext::MD_nontemporal)
587 To->setMetadata(Kind, M.second);
591 /// \brief Propagate known metadata from one instruction to a vector of others.
592 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
594 if (Instruction *I = dyn_cast<Instruction>(V))
595 propagateMetadata(I, From);
598 /// \brief The group of interleaved loads/stores sharing the same stride and
599 /// close to each other.
601 /// Each member in this group has an index starting from 0, and the largest
602 /// index should be less than interleaved factor, which is equal to the absolute
603 /// value of the access's stride.
605 /// E.g. An interleaved load group of factor 4:
606 /// for (unsigned i = 0; i < 1024; i+=4) {
607 /// a = A[i]; // Member of index 0
608 /// b = A[i+1]; // Member of index 1
609 /// d = A[i+3]; // Member of index 3
613 /// An interleaved store group of factor 4:
614 /// for (unsigned i = 0; i < 1024; i+=4) {
616 /// A[i] = a; // Member of index 0
617 /// A[i+1] = b; // Member of index 1
618 /// A[i+2] = c; // Member of index 2
619 /// A[i+3] = d; // Member of index 3
622 /// Note: the interleaved load group could have gaps (missing members), but
623 /// the interleaved store group doesn't allow gaps.
624 class InterleaveGroup {
626 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
627 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
628 assert(Align && "The alignment should be non-zero");
630 Factor = std::abs(Stride);
631 assert(Factor > 1 && "Invalid interleave factor");
633 Reverse = Stride < 0;
637 bool isReverse() const { return Reverse; }
638 unsigned getFactor() const { return Factor; }
639 unsigned getAlignment() const { return Align; }
640 unsigned getNumMembers() const { return Members.size(); }
642 /// \brief Try to insert a new member \p Instr with index \p Index and
643 /// alignment \p NewAlign. The index is related to the leader and it could be
644 /// negative if it is the new leader.
646 /// \returns false if the instruction doesn't belong to the group.
647 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
648 assert(NewAlign && "The new member's alignment should be non-zero");
650 int Key = Index + SmallestKey;
652 // Skip if there is already a member with the same index.
653 if (Members.count(Key))
656 if (Key > LargestKey) {
657 // The largest index is always less than the interleave factor.
658 if (Index >= static_cast<int>(Factor))
662 } else if (Key < SmallestKey) {
663 // The largest index is always less than the interleave factor.
664 if (LargestKey - Key >= static_cast<int>(Factor))
670 // It's always safe to select the minimum alignment.
671 Align = std::min(Align, NewAlign);
672 Members[Key] = Instr;
676 /// \brief Get the member with the given index \p Index
678 /// \returns nullptr if contains no such member.
679 Instruction *getMember(unsigned Index) const {
680 int Key = SmallestKey + Index;
681 if (!Members.count(Key))
684 return Members.find(Key)->second;
687 /// \brief Get the index for the given member. Unlike the key in the member
688 /// map, the index starts from 0.
689 unsigned getIndex(Instruction *Instr) const {
690 for (auto I : Members)
691 if (I.second == Instr)
692 return I.first - SmallestKey;
694 llvm_unreachable("InterleaveGroup contains no such member");
697 Instruction *getInsertPos() const { return InsertPos; }
698 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
701 unsigned Factor; // Interleave Factor.
704 DenseMap<int, Instruction *> Members;
708 // To avoid breaking dependences, vectorized instructions of an interleave
709 // group should be inserted at either the first load or the last store in
712 // E.g. %even = load i32 // Insert Position
713 // %add = add i32 %even // Use of %even
717 // %odd = add i32 // Def of %odd
718 // store i32 %odd // Insert Position
719 Instruction *InsertPos;
722 /// \brief Drive the analysis of interleaved memory accesses in the loop.
724 /// Use this class to analyze interleaved accesses only when we can vectorize
725 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
726 /// on interleaved accesses is unsafe.
728 /// The analysis collects interleave groups and records the relationships
729 /// between the member and the group in a map.
730 class InterleavedAccessInfo {
732 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
733 : SE(SE), TheLoop(L), DT(DT) {}
735 ~InterleavedAccessInfo() {
736 SmallSet<InterleaveGroup *, 4> DelSet;
737 // Avoid releasing a pointer twice.
738 for (auto &I : InterleaveGroupMap)
739 DelSet.insert(I.second);
740 for (auto *Ptr : DelSet)
744 /// \brief Analyze the interleaved accesses and collect them in interleave
745 /// groups. Substitute symbolic strides using \p Strides.
746 void analyzeInterleaving(const ValueToValueMap &Strides);
748 /// \brief Check if \p Instr belongs to any interleave group.
749 bool isInterleaved(Instruction *Instr) const {
750 return InterleaveGroupMap.count(Instr);
753 /// \brief Get the interleave group that \p Instr belongs to.
755 /// \returns nullptr if doesn't have such group.
756 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
757 if (InterleaveGroupMap.count(Instr))
758 return InterleaveGroupMap.find(Instr)->second;
767 /// Holds the relationships between the members and the interleave group.
768 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
770 /// \brief The descriptor for a strided memory access.
771 struct StrideDescriptor {
772 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
774 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
776 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
778 int Stride; // The access's stride. It is negative for a reverse access.
779 const SCEV *Scev; // The scalar expression of this access
780 unsigned Size; // The size of the memory object.
781 unsigned Align; // The alignment of this access.
784 /// \brief Create a new interleave group with the given instruction \p Instr,
785 /// stride \p Stride and alignment \p Align.
787 /// \returns the newly created interleave group.
788 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
790 assert(!InterleaveGroupMap.count(Instr) &&
791 "Already in an interleaved access group");
792 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
793 return InterleaveGroupMap[Instr];
796 /// \brief Release the group and remove all the relationships.
797 void releaseGroup(InterleaveGroup *Group) {
798 for (unsigned i = 0; i < Group->getFactor(); i++)
799 if (Instruction *Member = Group->getMember(i))
800 InterleaveGroupMap.erase(Member);
805 /// \brief Collect all the accesses with a constant stride in program order.
806 void collectConstStridedAccesses(
807 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
808 const ValueToValueMap &Strides);
811 /// Utility class for getting and setting loop vectorizer hints in the form
812 /// of loop metadata.
813 /// This class keeps a number of loop annotations locally (as member variables)
814 /// and can, upon request, write them back as metadata on the loop. It will
815 /// initially scan the loop for existing metadata, and will update the local
816 /// values based on information in the loop.
817 /// We cannot write all values to metadata, as the mere presence of some info,
818 /// for example 'force', means a decision has been made. So, we need to be
819 /// careful NOT to add them if the user hasn't specifically asked so.
820 class LoopVectorizeHints {
827 /// Hint - associates name and validation with the hint value.
830 unsigned Value; // This may have to change for non-numeric values.
833 Hint(const char * Name, unsigned Value, HintKind Kind)
834 : Name(Name), Value(Value), Kind(Kind) { }
836 bool validate(unsigned Val) {
839 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
841 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
849 /// Vectorization width.
851 /// Vectorization interleave factor.
853 /// Vectorization forced
856 /// Return the loop metadata prefix.
857 static StringRef Prefix() { return "llvm.loop."; }
861 FK_Undefined = -1, ///< Not selected.
862 FK_Disabled = 0, ///< Forcing disabled.
863 FK_Enabled = 1, ///< Forcing enabled.
866 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
867 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
869 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
870 Force("vectorize.enable", FK_Undefined, HK_FORCE),
872 // Populate values with existing loop metadata.
873 getHintsFromMetadata();
875 // force-vector-interleave overrides DisableInterleaving.
876 if (VectorizerParams::isInterleaveForced())
877 Interleave.Value = VectorizerParams::VectorizationInterleave;
879 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
880 << "LV: Interleaving disabled by the pass manager\n");
883 /// Mark the loop L as already vectorized by setting the width to 1.
884 void setAlreadyVectorized() {
885 Width.Value = Interleave.Value = 1;
886 Hint Hints[] = {Width, Interleave};
887 writeHintsToMetadata(Hints);
890 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
891 if (getForce() == LoopVectorizeHints::FK_Disabled) {
892 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
893 emitOptimizationRemarkAnalysis(F->getContext(),
894 vectorizeAnalysisPassName(), *F,
895 L->getStartLoc(), emitRemark());
899 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
900 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
901 emitOptimizationRemarkAnalysis(F->getContext(),
902 vectorizeAnalysisPassName(), *F,
903 L->getStartLoc(), emitRemark());
907 if (getWidth() == 1 && getInterleave() == 1) {
908 // FIXME: Add a separate metadata to indicate when the loop has already
909 // been vectorized instead of setting width and count to 1.
910 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
911 // FIXME: Add interleave.disable metadata. This will allow
912 // vectorize.disable to be used without disabling the pass and errors
913 // to differentiate between disabled vectorization and a width of 1.
914 emitOptimizationRemarkAnalysis(
915 F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
916 "loop not vectorized: vectorization and interleaving are explicitly "
917 "disabled, or vectorize width and interleave count are both set to "
925 /// Dumps all the hint information.
926 std::string emitRemark() const {
927 VectorizationReport R;
928 if (Force.Value == LoopVectorizeHints::FK_Disabled)
929 R << "vectorization is explicitly disabled";
931 R << "use -Rpass-analysis=loop-vectorize for more info";
932 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
934 if (Width.Value != 0)
935 R << ", Vector Width=" << Width.Value;
936 if (Interleave.Value != 0)
937 R << ", Interleave Count=" << Interleave.Value;
945 unsigned getWidth() const { return Width.Value; }
946 unsigned getInterleave() const { return Interleave.Value; }
947 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
948 const char *vectorizeAnalysisPassName() const {
949 // If hints are provided that don't disable vectorization use the
950 // AlwaysPrint pass name to force the frontend to print the diagnostic.
953 if (getForce() == LoopVectorizeHints::FK_Disabled)
955 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
957 return DiagnosticInfo::AlwaysPrint;
960 bool allowReordering() const {
961 // When enabling loop hints are provided we allow the vectorizer to change
962 // the order of operations that is given by the scalar loop. This is not
963 // enabled by default because can be unsafe or inefficient. For example,
964 // reordering floating-point operations will change the way round-off
965 // error accumulates in the loop.
966 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
970 /// Find hints specified in the loop metadata and update local values.
971 void getHintsFromMetadata() {
972 MDNode *LoopID = TheLoop->getLoopID();
976 // First operand should refer to the loop id itself.
977 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
978 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
980 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
981 const MDString *S = nullptr;
982 SmallVector<Metadata *, 4> Args;
984 // The expected hint is either a MDString or a MDNode with the first
985 // operand a MDString.
986 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
987 if (!MD || MD->getNumOperands() == 0)
989 S = dyn_cast<MDString>(MD->getOperand(0));
990 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
991 Args.push_back(MD->getOperand(i));
993 S = dyn_cast<MDString>(LoopID->getOperand(i));
994 assert(Args.size() == 0 && "too many arguments for MDString");
1000 // Check if the hint starts with the loop metadata prefix.
1001 StringRef Name = S->getString();
1002 if (Args.size() == 1)
1003 setHint(Name, Args[0]);
1007 /// Checks string hint with one operand and set value if valid.
1008 void setHint(StringRef Name, Metadata *Arg) {
1009 if (!Name.startswith(Prefix()))
1011 Name = Name.substr(Prefix().size(), StringRef::npos);
1013 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1015 unsigned Val = C->getZExtValue();
1017 Hint *Hints[] = {&Width, &Interleave, &Force};
1018 for (auto H : Hints) {
1019 if (Name == H->Name) {
1020 if (H->validate(Val))
1023 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1029 /// Create a new hint from name / value pair.
1030 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1031 LLVMContext &Context = TheLoop->getHeader()->getContext();
1032 Metadata *MDs[] = {MDString::get(Context, Name),
1033 ConstantAsMetadata::get(
1034 ConstantInt::get(Type::getInt32Ty(Context), V))};
1035 return MDNode::get(Context, MDs);
1038 /// Matches metadata with hint name.
1039 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1040 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1044 for (auto H : HintTypes)
1045 if (Name->getString().endswith(H.Name))
1050 /// Sets current hints into loop metadata, keeping other values intact.
1051 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1052 if (HintTypes.size() == 0)
1055 // Reserve the first element to LoopID (see below).
1056 SmallVector<Metadata *, 4> MDs(1);
1057 // If the loop already has metadata, then ignore the existing operands.
1058 MDNode *LoopID = TheLoop->getLoopID();
1060 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1061 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1062 // If node in update list, ignore old value.
1063 if (!matchesHintMetadataName(Node, HintTypes))
1064 MDs.push_back(Node);
1068 // Now, add the missing hints.
1069 for (auto H : HintTypes)
1070 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1072 // Replace current metadata node with new one.
1073 LLVMContext &Context = TheLoop->getHeader()->getContext();
1074 MDNode *NewLoopID = MDNode::get(Context, MDs);
1075 // Set operand 0 to refer to the loop id itself.
1076 NewLoopID->replaceOperandWith(0, NewLoopID);
1078 TheLoop->setLoopID(NewLoopID);
1081 /// The loop these hints belong to.
1082 const Loop *TheLoop;
1085 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1086 const LoopVectorizeHints &Hints,
1087 const LoopAccessReport &Message) {
1088 const char *Name = Hints.vectorizeAnalysisPassName();
1089 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1092 static void emitMissedWarning(Function *F, Loop *L,
1093 const LoopVectorizeHints &LH) {
1094 emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1097 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1098 if (LH.getWidth() != 1)
1099 emitLoopVectorizeWarning(
1100 F->getContext(), *F, L->getStartLoc(),
1101 "failed explicitly specified loop vectorization");
1102 else if (LH.getInterleave() != 1)
1103 emitLoopInterleaveWarning(
1104 F->getContext(), *F, L->getStartLoc(),
1105 "failed explicitly specified loop interleaving");
1109 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1110 /// to what vectorization factor.
1111 /// This class does not look at the profitability of vectorization, only the
1112 /// legality. This class has two main kinds of checks:
1113 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1114 /// will change the order of memory accesses in a way that will change the
1115 /// correctness of the program.
1116 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1117 /// checks for a number of different conditions, such as the availability of a
1118 /// single induction variable, that all types are supported and vectorize-able,
1119 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1120 /// This class is also used by InnerLoopVectorizer for identifying
1121 /// induction variable and the different reduction variables.
1122 class LoopVectorizationLegality {
1124 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1125 TargetLibraryInfo *TLI, AliasAnalysis *AA,
1126 Function *F, const TargetTransformInfo *TTI,
1127 LoopAccessAnalysis *LAA,
1128 LoopVectorizationRequirements *R,
1129 const LoopVectorizeHints *H)
1130 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
1131 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
1132 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
1133 Requirements(R), Hints(H) {}
1135 /// ReductionList contains the reduction descriptors for all
1136 /// of the reductions that were found in the loop.
1137 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1139 /// InductionList saves induction variables and maps them to the
1140 /// induction descriptor.
1141 typedef MapVector<PHINode*, InductionDescriptor> InductionList;
1143 /// Returns true if it is legal to vectorize this loop.
1144 /// This does not mean that it is profitable to vectorize this
1145 /// loop, only that it is legal to do so.
1146 bool canVectorize();
1148 /// Returns the Induction variable.
1149 PHINode *getInduction() { return Induction; }
1151 /// Returns the reduction variables found in the loop.
1152 ReductionList *getReductionVars() { return &Reductions; }
1154 /// Returns the induction variables found in the loop.
1155 InductionList *getInductionVars() { return &Inductions; }
1157 /// Returns the widest induction type.
1158 Type *getWidestInductionType() { return WidestIndTy; }
1160 /// Returns True if V is an induction variable in this loop.
1161 bool isInductionVariable(const Value *V);
1163 /// Return true if the block BB needs to be predicated in order for the loop
1164 /// to be vectorized.
1165 bool blockNeedsPredication(BasicBlock *BB);
1167 /// Check if this pointer is consecutive when vectorizing. This happens
1168 /// when the last index of the GEP is the induction variable, or that the
1169 /// pointer itself is an induction variable.
1170 /// This check allows us to vectorize A[idx] into a wide load/store.
1172 /// 0 - Stride is unknown or non-consecutive.
1173 /// 1 - Address is consecutive.
1174 /// -1 - Address is consecutive, and decreasing.
1175 int isConsecutivePtr(Value *Ptr);
1177 /// Returns true if the value V is uniform within the loop.
1178 bool isUniform(Value *V);
1180 /// Returns true if this instruction will remain scalar after vectorization.
1181 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
1183 /// Returns the information that we collected about runtime memory check.
1184 const RuntimePointerChecking *getRuntimePointerChecking() const {
1185 return LAI->getRuntimePointerChecking();
1188 const LoopAccessInfo *getLAI() const {
1192 /// \brief Check if \p Instr belongs to any interleaved access group.
1193 bool isAccessInterleaved(Instruction *Instr) {
1194 return InterleaveInfo.isInterleaved(Instr);
1197 /// \brief Get the interleaved access group that \p Instr belongs to.
1198 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1199 return InterleaveInfo.getInterleaveGroup(Instr);
1202 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1204 bool hasStride(Value *V) { return StrideSet.count(V); }
1205 bool mustCheckStrides() { return !StrideSet.empty(); }
1206 SmallPtrSet<Value *, 8>::iterator strides_begin() {
1207 return StrideSet.begin();
1209 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
1211 /// Returns true if the target machine supports masked store operation
1212 /// for the given \p DataType and kind of access to \p Ptr.
1213 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1214 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
1216 /// Returns true if the target machine supports masked load operation
1217 /// for the given \p DataType and kind of access to \p Ptr.
1218 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1219 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
1221 /// Returns true if vector representation of the instruction \p I
1223 bool isMaskRequired(const Instruction* I) {
1224 return (MaskedOp.count(I) != 0);
1226 unsigned getNumStores() const {
1227 return LAI->getNumStores();
1229 unsigned getNumLoads() const {
1230 return LAI->getNumLoads();
1232 unsigned getNumPredStores() const {
1233 return NumPredStores;
1236 /// Check if a single basic block loop is vectorizable.
1237 /// At this point we know that this is a loop with a constant trip count
1238 /// and we only need to check individual instructions.
1239 bool canVectorizeInstrs();
1241 /// When we vectorize loops we may change the order in which
1242 /// we read and write from memory. This method checks if it is
1243 /// legal to vectorize the code, considering only memory constrains.
1244 /// Returns true if the loop is vectorizable
1245 bool canVectorizeMemory();
1247 /// Return true if we can vectorize this loop using the IF-conversion
1249 bool canVectorizeWithIfConvert();
1251 /// Collect the variables that need to stay uniform after vectorization.
1252 void collectLoopUniforms();
1254 /// Return true if all of the instructions in the block can be speculatively
1255 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1256 /// and we know that we can read from them without segfault.
1257 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1259 /// \brief Collect memory access with loop invariant strides.
1261 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1263 void collectStridedAccess(Value *LoadOrStoreInst);
1265 /// Report an analysis message to assist the user in diagnosing loops that are
1266 /// not vectorized. These are handled as LoopAccessReport rather than
1267 /// VectorizationReport because the << operator of VectorizationReport returns
1268 /// LoopAccessReport.
1269 void emitAnalysis(const LoopAccessReport &Message) const {
1270 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1273 unsigned NumPredStores;
1275 /// The loop that we evaluate.
1278 ScalarEvolution *SE;
1279 /// Target Library Info.
1280 TargetLibraryInfo *TLI;
1282 Function *TheFunction;
1283 /// Target Transform Info
1284 const TargetTransformInfo *TTI;
1287 // LoopAccess analysis.
1288 LoopAccessAnalysis *LAA;
1289 // And the loop-accesses info corresponding to this loop. This pointer is
1290 // null until canVectorizeMemory sets it up.
1291 const LoopAccessInfo *LAI;
1293 /// The interleave access information contains groups of interleaved accesses
1294 /// with the same stride and close to each other.
1295 InterleavedAccessInfo InterleaveInfo;
1297 // --- vectorization state --- //
1299 /// Holds the integer induction variable. This is the counter of the
1302 /// Holds the reduction variables.
1303 ReductionList Reductions;
1304 /// Holds all of the induction variables that we found in the loop.
1305 /// Notice that inductions don't need to start at zero and that induction
1306 /// variables can be pointers.
1307 InductionList Inductions;
1308 /// Holds the widest induction type encountered.
1311 /// Allowed outside users. This holds the reduction
1312 /// vars which can be accessed from outside the loop.
1313 SmallPtrSet<Value*, 4> AllowedExit;
1314 /// This set holds the variables which are known to be uniform after
1316 SmallPtrSet<Instruction*, 4> Uniforms;
1318 /// Can we assume the absence of NaNs.
1319 bool HasFunNoNaNAttr;
1321 /// Vectorization requirements that will go through late-evaluation.
1322 LoopVectorizationRequirements *Requirements;
1324 /// Used to emit an analysis of any legality issues.
1325 const LoopVectorizeHints *Hints;
1327 ValueToValueMap Strides;
1328 SmallPtrSet<Value *, 8> StrideSet;
1330 /// While vectorizing these instructions we have to generate a
1331 /// call to the appropriate masked intrinsic
1332 SmallPtrSet<const Instruction*, 8> MaskedOp;
1335 /// LoopVectorizationCostModel - estimates the expected speedups due to
1337 /// In many cases vectorization is not profitable. This can happen because of
1338 /// a number of reasons. In this class we mainly attempt to predict the
1339 /// expected speedup/slowdowns due to the supported instruction set. We use the
1340 /// TargetTransformInfo to query the different backends for the cost of
1341 /// different operations.
1342 class LoopVectorizationCostModel {
1344 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1345 LoopVectorizationLegality *Legal,
1346 const TargetTransformInfo &TTI,
1347 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1348 const Function *F, const LoopVectorizeHints *Hints,
1349 SmallPtrSetImpl<const Value *> &ValuesToIgnore)
1350 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1351 TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
1353 /// Information about vectorization costs
1354 struct VectorizationFactor {
1355 unsigned Width; // Vector width with best cost
1356 unsigned Cost; // Cost of the loop with that width
1358 /// \return The most profitable vectorization factor and the cost of that VF.
1359 /// This method checks every power of two up to VF. If UserVF is not ZERO
1360 /// then this vectorization factor will be selected if vectorization is
1362 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1364 /// \return The size (in bits) of the widest type in the code that
1365 /// needs to be vectorized. We ignore values that remain scalar such as
1366 /// 64 bit loop indices.
1367 unsigned getWidestType();
1369 /// \return The desired interleave count.
1370 /// If interleave count has been specified by metadata it will be returned.
1371 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1372 /// are the selected vectorization factor and the cost of the selected VF.
1373 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1376 /// \return The most profitable unroll factor.
1377 /// This method finds the best unroll-factor based on register pressure and
1378 /// other parameters. VF and LoopCost are the selected vectorization factor
1379 /// and the cost of the selected VF.
1380 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1383 /// \brief A struct that represents some properties of the register usage
1385 struct RegisterUsage {
1386 /// Holds the number of loop invariant values that are used in the loop.
1387 unsigned LoopInvariantRegs;
1388 /// Holds the maximum number of concurrent live intervals in the loop.
1389 unsigned MaxLocalUsers;
1390 /// Holds the number of instructions in the loop.
1391 unsigned NumInstructions;
1394 /// \return information about the register usage of the loop.
1395 RegisterUsage calculateRegisterUsage();
1398 /// Returns the expected execution cost. The unit of the cost does
1399 /// not matter because we use the 'cost' units to compare different
1400 /// vector widths. The cost that is returned is *not* normalized by
1401 /// the factor width.
1402 unsigned expectedCost(unsigned VF);
1404 /// Returns the execution time cost of an instruction for a given vector
1405 /// width. Vector width of one means scalar.
1406 unsigned getInstructionCost(Instruction *I, unsigned VF);
1408 /// Returns whether the instruction is a load or store and will be a emitted
1409 /// as a vector operation.
1410 bool isConsecutiveLoadOrStore(Instruction *I);
1412 /// Report an analysis message to assist the user in diagnosing loops that are
1413 /// not vectorized. These are handled as LoopAccessReport rather than
1414 /// VectorizationReport because the << operator of VectorizationReport returns
1415 /// LoopAccessReport.
1416 void emitAnalysis(const LoopAccessReport &Message) const {
1417 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1420 /// The loop that we evaluate.
1423 ScalarEvolution *SE;
1424 /// Loop Info analysis.
1426 /// Vectorization legality.
1427 LoopVectorizationLegality *Legal;
1428 /// Vector target information.
1429 const TargetTransformInfo &TTI;
1430 /// Target Library Info.
1431 const TargetLibraryInfo *TLI;
1432 const Function *TheFunction;
1433 // Loop Vectorize Hint.
1434 const LoopVectorizeHints *Hints;
1435 // Values to ignore in the cost model.
1436 const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
1439 /// \brief This holds vectorization requirements that must be verified late in
1440 /// the process. The requirements are set by legalize and costmodel. Once
1441 /// vectorization has been determined to be possible and profitable the
1442 /// requirements can be verified by looking for metadata or compiler options.
1443 /// For example, some loops require FP commutativity which is only allowed if
1444 /// vectorization is explicitly specified or if the fast-math compiler option
1445 /// has been provided.
1446 /// Late evaluation of these requirements allows helpful diagnostics to be
1447 /// composed that tells the user what need to be done to vectorize the loop. For
1448 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1449 /// evaluation should be used only when diagnostics can generated that can be
1450 /// followed by a non-expert user.
1451 class LoopVectorizationRequirements {
1453 LoopVectorizationRequirements()
1454 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1456 void addUnsafeAlgebraInst(Instruction *I) {
1457 // First unsafe algebra instruction.
1458 if (!UnsafeAlgebraInst)
1459 UnsafeAlgebraInst = I;
1462 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1464 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1465 const char *Name = Hints.vectorizeAnalysisPassName();
1466 bool Failed = false;
1467 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1468 emitOptimizationRemarkAnalysisFPCommute(
1469 F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1470 VectorizationReport() << "cannot prove it is safe to reorder "
1471 "floating-point operations");
1475 // Test if runtime memcheck thresholds are exceeded.
1476 bool PragmaThresholdReached =
1477 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1478 bool ThresholdReached =
1479 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1480 if ((ThresholdReached && !Hints.allowReordering()) ||
1481 PragmaThresholdReached) {
1482 emitOptimizationRemarkAnalysisAliasing(
1483 F->getContext(), Name, *F, L->getStartLoc(),
1484 VectorizationReport()
1485 << "cannot prove it is safe to reorder memory operations");
1486 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1494 unsigned NumRuntimePointerChecks;
1495 Instruction *UnsafeAlgebraInst;
1498 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1500 return V.push_back(&L);
1502 for (Loop *InnerL : L)
1503 addInnerLoop(*InnerL, V);
1506 /// The LoopVectorize Pass.
1507 struct LoopVectorize : public FunctionPass {
1508 /// Pass identification, replacement for typeid
1511 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1513 DisableUnrolling(NoUnrolling),
1514 AlwaysVectorize(AlwaysVectorize) {
1515 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1518 ScalarEvolution *SE;
1520 TargetTransformInfo *TTI;
1522 BlockFrequencyInfo *BFI;
1523 TargetLibraryInfo *TLI;
1525 AssumptionCache *AC;
1526 LoopAccessAnalysis *LAA;
1527 bool DisableUnrolling;
1528 bool AlwaysVectorize;
1530 BlockFrequency ColdEntryFreq;
1532 bool runOnFunction(Function &F) override {
1533 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1534 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1535 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1536 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1537 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1538 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1539 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1540 AA = &getAnalysis<AliasAnalysis>();
1541 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1542 LAA = &getAnalysis<LoopAccessAnalysis>();
1544 // Compute some weights outside of the loop over the loops. Compute this
1545 // using a BranchProbability to re-use its scaling math.
1546 const BranchProbability ColdProb(1, 5); // 20%
1547 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1550 // 1. the target claims to have no vector registers, and
1551 // 2. interleaving won't help ILP.
1553 // The second condition is necessary because, even if the target has no
1554 // vector registers, loop vectorization may still enable scalar
1556 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1559 // Build up a worklist of inner-loops to vectorize. This is necessary as
1560 // the act of vectorizing or partially unrolling a loop creates new loops
1561 // and can invalidate iterators across the loops.
1562 SmallVector<Loop *, 8> Worklist;
1565 addInnerLoop(*L, Worklist);
1567 LoopsAnalyzed += Worklist.size();
1569 // Now walk the identified inner loops.
1570 bool Changed = false;
1571 while (!Worklist.empty())
1572 Changed |= processLoop(Worklist.pop_back_val());
1574 // Process each loop nest in the function.
1578 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1579 SmallVector<Metadata *, 4> MDs;
1580 // Reserve first location for self reference to the LoopID metadata node.
1581 MDs.push_back(nullptr);
1582 bool IsUnrollMetadata = false;
1583 MDNode *LoopID = L->getLoopID();
1585 // First find existing loop unrolling disable metadata.
1586 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1587 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1589 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1591 S && S->getString().startswith("llvm.loop.unroll.disable");
1593 MDs.push_back(LoopID->getOperand(i));
1597 if (!IsUnrollMetadata) {
1598 // Add runtime unroll disable metadata.
1599 LLVMContext &Context = L->getHeader()->getContext();
1600 SmallVector<Metadata *, 1> DisableOperands;
1601 DisableOperands.push_back(
1602 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1603 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1604 MDs.push_back(DisableNode);
1605 MDNode *NewLoopID = MDNode::get(Context, MDs);
1606 // Set operand 0 to refer to the loop id itself.
1607 NewLoopID->replaceOperandWith(0, NewLoopID);
1608 L->setLoopID(NewLoopID);
1612 bool processLoop(Loop *L) {
1613 assert(L->empty() && "Only process inner loops.");
1616 const std::string DebugLocStr = getDebugLocString(L);
1619 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1620 << L->getHeader()->getParent()->getName() << "\" from "
1621 << DebugLocStr << "\n");
1623 LoopVectorizeHints Hints(L, DisableUnrolling);
1625 DEBUG(dbgs() << "LV: Loop hints:"
1627 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1629 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1631 : "?")) << " width=" << Hints.getWidth()
1632 << " unroll=" << Hints.getInterleave() << "\n");
1634 // Function containing loop
1635 Function *F = L->getHeader()->getParent();
1637 // Looking at the diagnostic output is the only way to determine if a loop
1638 // was vectorized (other than looking at the IR or machine code), so it
1639 // is important to generate an optimization remark for each loop. Most of
1640 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1641 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1642 // less verbose reporting vectorized loops and unvectorized loops that may
1643 // benefit from vectorization, respectively.
1645 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1646 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1650 // Check the loop for a trip count threshold:
1651 // do not vectorize loops with a tiny trip count.
1652 const unsigned TC = SE->getSmallConstantTripCount(L);
1653 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1654 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1655 << "This loop is not worth vectorizing.");
1656 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1657 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1659 DEBUG(dbgs() << "\n");
1660 emitAnalysisDiag(F, L, Hints, VectorizationReport()
1661 << "vectorization is not beneficial "
1662 "and is not explicitly forced");
1667 // Check if it is legal to vectorize the loop.
1668 LoopVectorizationRequirements Requirements;
1669 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1670 &Requirements, &Hints);
1671 if (!LVL.canVectorize()) {
1672 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1673 emitMissedWarning(F, L, Hints);
1677 // Collect values we want to ignore in the cost model. This includes
1678 // type-promoting instructions we identified during reduction detection.
1679 SmallPtrSet<const Value *, 32> ValuesToIgnore;
1680 CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
1681 for (auto &Reduction : *LVL.getReductionVars()) {
1682 RecurrenceDescriptor &RedDes = Reduction.second;
1683 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
1684 ValuesToIgnore.insert(Casts.begin(), Casts.end());
1687 // Use the cost model.
1688 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints,
1691 // Check the function attributes to find out if this function should be
1692 // optimized for size.
1693 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1696 // Compute the weighted frequency of this loop being executed and see if it
1697 // is less than 20% of the function entry baseline frequency. Note that we
1698 // always have a canonical loop here because we think we *can* vectorize.
1699 // FIXME: This is hidden behind a flag due to pervasive problems with
1700 // exactly what block frequency models.
1701 if (LoopVectorizeWithBlockFrequency) {
1702 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1703 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1704 LoopEntryFreq < ColdEntryFreq)
1708 // Check the function attributes to see if implicit floats are allowed.
1709 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1710 // an integer loop and the vector instructions selected are purely integer
1711 // vector instructions?
1712 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1713 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1714 "attribute is used.\n");
1717 VectorizationReport()
1718 << "loop not vectorized due to NoImplicitFloat attribute");
1719 emitMissedWarning(F, L, Hints);
1723 // Select the optimal vectorization factor.
1724 const LoopVectorizationCostModel::VectorizationFactor VF =
1725 CM.selectVectorizationFactor(OptForSize);
1727 // Select the interleave count.
1728 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1730 // Get user interleave count.
1731 unsigned UserIC = Hints.getInterleave();
1733 // Identify the diagnostic messages that should be produced.
1734 std::string VecDiagMsg, IntDiagMsg;
1735 bool VectorizeLoop = true, InterleaveLoop = true;
1737 if (Requirements.doesNotMeet(F, L, Hints)) {
1738 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1740 emitMissedWarning(F, L, Hints);
1744 if (VF.Width == 1) {
1745 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1747 "the cost-model indicates that vectorization is not beneficial";
1748 VectorizeLoop = false;
1751 if (IC == 1 && UserIC <= 1) {
1752 // Tell the user interleaving is not beneficial.
1753 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1755 "the cost-model indicates that interleaving is not beneficial";
1756 InterleaveLoop = false;
1759 " and is explicitly disabled or interleave count is set to 1";
1760 } else if (IC > 1 && UserIC == 1) {
1761 // Tell the user interleaving is beneficial, but it explicitly disabled.
1763 << "LV: Interleaving is beneficial but is explicitly disabled.");
1764 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1765 "but is explicitly disabled or interleave count is set to 1";
1766 InterleaveLoop = false;
1769 // Override IC if user provided an interleave count.
1770 IC = UserIC > 0 ? UserIC : IC;
1772 // Emit diagnostic messages, if any.
1773 const char *VAPassName = Hints.vectorizeAnalysisPassName();
1774 if (!VectorizeLoop && !InterleaveLoop) {
1775 // Do not vectorize or interleaving the loop.
1776 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1777 L->getStartLoc(), VecDiagMsg);
1778 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1779 L->getStartLoc(), IntDiagMsg);
1781 } else if (!VectorizeLoop && InterleaveLoop) {
1782 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1783 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1784 L->getStartLoc(), VecDiagMsg);
1785 } else if (VectorizeLoop && !InterleaveLoop) {
1786 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1787 << DebugLocStr << '\n');
1788 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1789 L->getStartLoc(), IntDiagMsg);
1790 } else if (VectorizeLoop && InterleaveLoop) {
1791 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1792 << DebugLocStr << '\n');
1793 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1796 if (!VectorizeLoop) {
1797 assert(IC > 1 && "interleave count should not be 1 or 0");
1798 // If we decided that it is not legal to vectorize the loop then
1800 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC);
1801 Unroller.vectorize(&LVL);
1803 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1804 Twine("interleaved loop (interleaved count: ") +
1807 // If we decided that it is *legal* to vectorize the loop then do it.
1808 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC);
1812 // Add metadata to disable runtime unrolling scalar loop when there's no
1813 // runtime check about strides and memory. Because at this situation,
1814 // scalar loop is rarely used not worthy to be unrolled.
1815 if (!LB.IsSafetyChecksAdded())
1816 AddRuntimeUnrollDisableMetaData(L);
1818 // Report the vectorization decision.
1819 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1820 Twine("vectorized loop (vectorization width: ") +
1821 Twine(VF.Width) + ", interleaved count: " +
1825 // Mark the loop as already vectorized to avoid vectorizing again.
1826 Hints.setAlreadyVectorized();
1828 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1832 void getAnalysisUsage(AnalysisUsage &AU) const override {
1833 AU.addRequired<AssumptionCacheTracker>();
1834 AU.addRequiredID(LoopSimplifyID);
1835 AU.addRequiredID(LCSSAID);
1836 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1837 AU.addRequired<DominatorTreeWrapperPass>();
1838 AU.addRequired<LoopInfoWrapperPass>();
1839 AU.addRequired<ScalarEvolutionWrapperPass>();
1840 AU.addRequired<TargetTransformInfoWrapperPass>();
1841 AU.addRequired<AliasAnalysis>();
1842 AU.addRequired<LoopAccessAnalysis>();
1843 AU.addPreserved<LoopInfoWrapperPass>();
1844 AU.addPreserved<DominatorTreeWrapperPass>();
1845 AU.addPreserved<AliasAnalysis>();
1850 } // end anonymous namespace
1852 //===----------------------------------------------------------------------===//
1853 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1854 // LoopVectorizationCostModel.
1855 //===----------------------------------------------------------------------===//
1857 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1858 // We need to place the broadcast of invariant variables outside the loop.
1859 Instruction *Instr = dyn_cast<Instruction>(V);
1861 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1862 Instr->getParent()) != LoopVectorBody.end());
1863 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1865 // Place the code for broadcasting invariant variables in the new preheader.
1866 IRBuilder<>::InsertPointGuard Guard(Builder);
1868 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1870 // Broadcast the scalar into all locations in the vector.
1871 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1876 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1878 assert(Val->getType()->isVectorTy() && "Must be a vector");
1879 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1880 "Elem must be an integer");
1881 assert(Step->getType() == Val->getType()->getScalarType() &&
1882 "Step has wrong type");
1883 // Create the types.
1884 Type *ITy = Val->getType()->getScalarType();
1885 VectorType *Ty = cast<VectorType>(Val->getType());
1886 int VLen = Ty->getNumElements();
1887 SmallVector<Constant*, 8> Indices;
1889 // Create a vector of consecutive numbers from zero to VF.
1890 for (int i = 0; i < VLen; ++i)
1891 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1893 // Add the consecutive indices to the vector value.
1894 Constant *Cv = ConstantVector::get(Indices);
1895 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1896 Step = Builder.CreateVectorSplat(VLen, Step);
1897 assert(Step->getType() == Val->getType() && "Invalid step vec");
1898 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1899 // which can be found from the original scalar operations.
1900 Step = Builder.CreateMul(Cv, Step);
1901 return Builder.CreateAdd(Val, Step, "induction");
1904 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1905 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1906 // Make sure that the pointer does not point to structs.
1907 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1910 // If this value is a pointer induction variable we know it is consecutive.
1911 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1912 if (Phi && Inductions.count(Phi)) {
1913 InductionDescriptor II = Inductions[Phi];
1914 return II.getConsecutiveDirection();
1917 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1921 unsigned NumOperands = Gep->getNumOperands();
1922 Value *GpPtr = Gep->getPointerOperand();
1923 // If this GEP value is a consecutive pointer induction variable and all of
1924 // the indices are constant then we know it is consecutive. We can
1925 Phi = dyn_cast<PHINode>(GpPtr);
1926 if (Phi && Inductions.count(Phi)) {
1928 // Make sure that the pointer does not point to structs.
1929 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1930 if (GepPtrType->getElementType()->isAggregateType())
1933 // Make sure that all of the index operands are loop invariant.
1934 for (unsigned i = 1; i < NumOperands; ++i)
1935 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1938 InductionDescriptor II = Inductions[Phi];
1939 return II.getConsecutiveDirection();
1942 unsigned InductionOperand = getGEPInductionOperand(Gep);
1944 // Check that all of the gep indices are uniform except for our induction
1946 for (unsigned i = 0; i != NumOperands; ++i)
1947 if (i != InductionOperand &&
1948 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1951 // We can emit wide load/stores only if the last non-zero index is the
1952 // induction variable.
1953 const SCEV *Last = nullptr;
1954 if (!Strides.count(Gep))
1955 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1957 // Because of the multiplication by a stride we can have a s/zext cast.
1958 // We are going to replace this stride by 1 so the cast is safe to ignore.
1960 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1961 // %0 = trunc i64 %indvars.iv to i32
1962 // %mul = mul i32 %0, %Stride1
1963 // %idxprom = zext i32 %mul to i64 << Safe cast.
1964 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1966 Last = replaceSymbolicStrideSCEV(SE, Strides,
1967 Gep->getOperand(InductionOperand), Gep);
1968 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1970 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1974 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1975 const SCEV *Step = AR->getStepRecurrence(*SE);
1977 // The memory is consecutive because the last index is consecutive
1978 // and all other indices are loop invariant.
1981 if (Step->isAllOnesValue())
1988 bool LoopVectorizationLegality::isUniform(Value *V) {
1989 return LAI->isUniform(V);
1992 InnerLoopVectorizer::VectorParts&
1993 InnerLoopVectorizer::getVectorValue(Value *V) {
1994 assert(V != Induction && "The new induction variable should not be used.");
1995 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1997 // If we have a stride that is replaced by one, do it here.
1998 if (Legal->hasStride(V))
1999 V = ConstantInt::get(V->getType(), 1);
2001 // If we have this scalar in the map, return it.
2002 if (WidenMap.has(V))
2003 return WidenMap.get(V);
2005 // If this scalar is unknown, assume that it is a constant or that it is
2006 // loop invariant. Broadcast V and save the value for future uses.
2007 Value *B = getBroadcastInstrs(V);
2008 return WidenMap.splat(V, B);
2011 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2012 assert(Vec->getType()->isVectorTy() && "Invalid type");
2013 SmallVector<Constant*, 8> ShuffleMask;
2014 for (unsigned i = 0; i < VF; ++i)
2015 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2017 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2018 ConstantVector::get(ShuffleMask),
2022 // Get a mask to interleave \p NumVec vectors into a wide vector.
2023 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2024 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2025 // <0, 4, 1, 5, 2, 6, 3, 7>
2026 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2028 SmallVector<Constant *, 16> Mask;
2029 for (unsigned i = 0; i < VF; i++)
2030 for (unsigned j = 0; j < NumVec; j++)
2031 Mask.push_back(Builder.getInt32(j * VF + i));
2033 return ConstantVector::get(Mask);
2036 // Get the strided mask starting from index \p Start.
2037 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2038 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2039 unsigned Stride, unsigned VF) {
2040 SmallVector<Constant *, 16> Mask;
2041 for (unsigned i = 0; i < VF; i++)
2042 Mask.push_back(Builder.getInt32(Start + i * Stride));
2044 return ConstantVector::get(Mask);
2047 // Get a mask of two parts: The first part consists of sequential integers
2048 // starting from 0, The second part consists of UNDEFs.
2049 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2050 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2051 unsigned NumUndef) {
2052 SmallVector<Constant *, 16> Mask;
2053 for (unsigned i = 0; i < NumInt; i++)
2054 Mask.push_back(Builder.getInt32(i));
2056 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2057 for (unsigned i = 0; i < NumUndef; i++)
2058 Mask.push_back(Undef);
2060 return ConstantVector::get(Mask);
2063 // Concatenate two vectors with the same element type. The 2nd vector should
2064 // not have more elements than the 1st vector. If the 2nd vector has less
2065 // elements, extend it with UNDEFs.
2066 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2068 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2069 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2070 assert(VecTy1 && VecTy2 &&
2071 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2072 "Expect two vectors with the same element type");
2074 unsigned NumElts1 = VecTy1->getNumElements();
2075 unsigned NumElts2 = VecTy2->getNumElements();
2076 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2078 if (NumElts1 > NumElts2) {
2079 // Extend with UNDEFs.
2081 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2082 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2085 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2086 return Builder.CreateShuffleVector(V1, V2, Mask);
2089 // Concatenate vectors in the given list. All vectors have the same type.
2090 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2091 ArrayRef<Value *> InputList) {
2092 unsigned NumVec = InputList.size();
2093 assert(NumVec > 1 && "Should be at least two vectors");
2095 SmallVector<Value *, 8> ResList;
2096 ResList.append(InputList.begin(), InputList.end());
2098 SmallVector<Value *, 8> TmpList;
2099 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2100 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2101 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2102 "Only the last vector may have a different type");
2104 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2107 // Push the last vector if the total number of vectors is odd.
2108 if (NumVec % 2 != 0)
2109 TmpList.push_back(ResList[NumVec - 1]);
2112 NumVec = ResList.size();
2113 } while (NumVec > 1);
2118 // Try to vectorize the interleave group that \p Instr belongs to.
2120 // E.g. Translate following interleaved load group (factor = 3):
2121 // for (i = 0; i < N; i+=3) {
2122 // R = Pic[i]; // Member of index 0
2123 // G = Pic[i+1]; // Member of index 1
2124 // B = Pic[i+2]; // Member of index 2
2125 // ... // do something to R, G, B
2128 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2129 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2130 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2131 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2133 // Or translate following interleaved store group (factor = 3):
2134 // for (i = 0; i < N; i+=3) {
2135 // ... do something to R, G, B
2136 // Pic[i] = R; // Member of index 0
2137 // Pic[i+1] = G; // Member of index 1
2138 // Pic[i+2] = B; // Member of index 2
2141 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2142 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2143 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2144 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2145 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2146 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2147 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2148 assert(Group && "Fail to get an interleaved access group.");
2150 // Skip if current instruction is not the insert position.
2151 if (Instr != Group->getInsertPos())
2154 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2155 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2156 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2158 // Prepare for the vector type of the interleaved load/store.
2159 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2160 unsigned InterleaveFactor = Group->getFactor();
2161 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2162 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2164 // Prepare for the new pointers.
2165 setDebugLocFromInst(Builder, Ptr);
2166 VectorParts &PtrParts = getVectorValue(Ptr);
2167 SmallVector<Value *, 2> NewPtrs;
2168 unsigned Index = Group->getIndex(Instr);
2169 for (unsigned Part = 0; Part < UF; Part++) {
2170 // Extract the pointer for current instruction from the pointer vector. A
2171 // reverse access uses the pointer in the last lane.
2172 Value *NewPtr = Builder.CreateExtractElement(
2174 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2176 // Notice current instruction could be any index. Need to adjust the address
2177 // to the member of index 0.
2179 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2180 // b = A[i]; // Member of index 0
2181 // Current pointer is pointed to A[i+1], adjust it to A[i].
2183 // E.g. A[i+1] = a; // Member of index 1
2184 // A[i] = b; // Member of index 0
2185 // A[i+2] = c; // Member of index 2 (Current instruction)
2186 // Current pointer is pointed to A[i+2], adjust it to A[i].
2187 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2189 // Cast to the vector pointer type.
2190 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2193 setDebugLocFromInst(Builder, Instr);
2194 Value *UndefVec = UndefValue::get(VecTy);
2196 // Vectorize the interleaved load group.
2198 for (unsigned Part = 0; Part < UF; Part++) {
2199 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2200 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2202 for (unsigned i = 0; i < InterleaveFactor; i++) {
2203 Instruction *Member = Group->getMember(i);
2205 // Skip the gaps in the group.
2209 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2210 Value *StridedVec = Builder.CreateShuffleVector(
2211 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2213 // If this member has different type, cast the result type.
2214 if (Member->getType() != ScalarTy) {
2215 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2216 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2219 VectorParts &Entry = WidenMap.get(Member);
2221 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2224 propagateMetadata(NewLoadInstr, Instr);
2229 // The sub vector type for current instruction.
2230 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2232 // Vectorize the interleaved store group.
2233 for (unsigned Part = 0; Part < UF; Part++) {
2234 // Collect the stored vector from each member.
2235 SmallVector<Value *, 4> StoredVecs;
2236 for (unsigned i = 0; i < InterleaveFactor; i++) {
2237 // Interleaved store group doesn't allow a gap, so each index has a member
2238 Instruction *Member = Group->getMember(i);
2239 assert(Member && "Fail to get a member from an interleaved store group");
2242 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2243 if (Group->isReverse())
2244 StoredVec = reverseVector(StoredVec);
2246 // If this member has different type, cast it to an unified type.
2247 if (StoredVec->getType() != SubVT)
2248 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2250 StoredVecs.push_back(StoredVec);
2253 // Concatenate all vectors into a wide vector.
2254 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2256 // Interleave the elements in the wide vector.
2257 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2258 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2261 Instruction *NewStoreInstr =
2262 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2263 propagateMetadata(NewStoreInstr, Instr);
2267 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2268 // Attempt to issue a wide load.
2269 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2270 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2272 assert((LI || SI) && "Invalid Load/Store instruction");
2274 // Try to vectorize the interleave group if this access is interleaved.
2275 if (Legal->isAccessInterleaved(Instr))
2276 return vectorizeInterleaveGroup(Instr);
2278 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2279 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2280 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2281 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2282 // An alignment of 0 means target abi alignment. We need to use the scalar's
2283 // target abi alignment in such a case.
2284 const DataLayout &DL = Instr->getModule()->getDataLayout();
2286 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2287 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2288 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2289 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2291 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2292 !Legal->isMaskRequired(SI))
2293 return scalarizeInstruction(Instr, true);
2295 if (ScalarAllocatedSize != VectorElementSize)
2296 return scalarizeInstruction(Instr);
2298 // If the pointer is loop invariant or if it is non-consecutive,
2299 // scalarize the load.
2300 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2301 bool Reverse = ConsecutiveStride < 0;
2302 bool UniformLoad = LI && Legal->isUniform(Ptr);
2303 if (!ConsecutiveStride || UniformLoad)
2304 return scalarizeInstruction(Instr);
2306 Constant *Zero = Builder.getInt32(0);
2307 VectorParts &Entry = WidenMap.get(Instr);
2309 // Handle consecutive loads/stores.
2310 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2311 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2312 setDebugLocFromInst(Builder, Gep);
2313 Value *PtrOperand = Gep->getPointerOperand();
2314 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2315 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2317 // Create the new GEP with the new induction variable.
2318 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2319 Gep2->setOperand(0, FirstBasePtr);
2320 Gep2->setName("gep.indvar.base");
2321 Ptr = Builder.Insert(Gep2);
2323 setDebugLocFromInst(Builder, Gep);
2324 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2325 OrigLoop) && "Base ptr must be invariant");
2327 // The last index does not have to be the induction. It can be
2328 // consecutive and be a function of the index. For example A[I+1];
2329 unsigned NumOperands = Gep->getNumOperands();
2330 unsigned InductionOperand = getGEPInductionOperand(Gep);
2331 // Create the new GEP with the new induction variable.
2332 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2334 for (unsigned i = 0; i < NumOperands; ++i) {
2335 Value *GepOperand = Gep->getOperand(i);
2336 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2338 // Update last index or loop invariant instruction anchored in loop.
2339 if (i == InductionOperand ||
2340 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2341 assert((i == InductionOperand ||
2342 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2343 "Must be last index or loop invariant");
2345 VectorParts &GEPParts = getVectorValue(GepOperand);
2346 Value *Index = GEPParts[0];
2347 Index = Builder.CreateExtractElement(Index, Zero);
2348 Gep2->setOperand(i, Index);
2349 Gep2->setName("gep.indvar.idx");
2352 Ptr = Builder.Insert(Gep2);
2354 // Use the induction element ptr.
2355 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2356 setDebugLocFromInst(Builder, Ptr);
2357 VectorParts &PtrVal = getVectorValue(Ptr);
2358 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2361 VectorParts Mask = createBlockInMask(Instr->getParent());
2364 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2365 "We do not allow storing to uniform addresses");
2366 setDebugLocFromInst(Builder, SI);
2367 // We don't want to update the value in the map as it might be used in
2368 // another expression. So don't use a reference type for "StoredVal".
2369 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2371 for (unsigned Part = 0; Part < UF; ++Part) {
2372 // Calculate the pointer for the specific unroll-part.
2374 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2377 // If we store to reverse consecutive memory locations, then we need
2378 // to reverse the order of elements in the stored value.
2379 StoredVal[Part] = reverseVector(StoredVal[Part]);
2380 // If the address is consecutive but reversed, then the
2381 // wide store needs to start at the last vector element.
2382 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2383 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2384 Mask[Part] = reverseVector(Mask[Part]);
2387 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2388 DataTy->getPointerTo(AddressSpace));
2391 if (Legal->isMaskRequired(SI))
2392 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2395 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2396 propagateMetadata(NewSI, SI);
2402 assert(LI && "Must have a load instruction");
2403 setDebugLocFromInst(Builder, LI);
2404 for (unsigned Part = 0; Part < UF; ++Part) {
2405 // Calculate the pointer for the specific unroll-part.
2407 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2410 // If the address is consecutive but reversed, then the
2411 // wide load needs to start at the last vector element.
2412 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2413 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2414 Mask[Part] = reverseVector(Mask[Part]);
2418 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2419 DataTy->getPointerTo(AddressSpace));
2420 if (Legal->isMaskRequired(LI))
2421 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2422 UndefValue::get(DataTy),
2423 "wide.masked.load");
2425 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2426 propagateMetadata(NewLI, LI);
2427 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2431 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2432 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2433 // Holds vector parameters or scalars, in case of uniform vals.
2434 SmallVector<VectorParts, 4> Params;
2436 setDebugLocFromInst(Builder, Instr);
2438 // Find all of the vectorized parameters.
2439 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2440 Value *SrcOp = Instr->getOperand(op);
2442 // If we are accessing the old induction variable, use the new one.
2443 if (SrcOp == OldInduction) {
2444 Params.push_back(getVectorValue(SrcOp));
2448 // Try using previously calculated values.
2449 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2451 // If the src is an instruction that appeared earlier in the basic block,
2452 // then it should already be vectorized.
2453 if (SrcInst && OrigLoop->contains(SrcInst)) {
2454 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2455 // The parameter is a vector value from earlier.
2456 Params.push_back(WidenMap.get(SrcInst));
2458 // The parameter is a scalar from outside the loop. Maybe even a constant.
2459 VectorParts Scalars;
2460 Scalars.append(UF, SrcOp);
2461 Params.push_back(Scalars);
2465 assert(Params.size() == Instr->getNumOperands() &&
2466 "Invalid number of operands");
2468 // Does this instruction return a value ?
2469 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2471 Value *UndefVec = IsVoidRetTy ? nullptr :
2472 UndefValue::get(VectorType::get(Instr->getType(), VF));
2473 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2474 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2477 if (IfPredicateStore) {
2478 assert(Instr->getParent()->getSinglePredecessor() &&
2479 "Only support single predecessor blocks");
2480 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2481 Instr->getParent());
2484 // For each vector unroll 'part':
2485 for (unsigned Part = 0; Part < UF; ++Part) {
2486 // For each scalar that we create:
2487 for (unsigned Width = 0; Width < VF; ++Width) {
2490 Value *Cmp = nullptr;
2491 if (IfPredicateStore) {
2492 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2493 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2496 Instruction *Cloned = Instr->clone();
2498 Cloned->setName(Instr->getName() + ".cloned");
2499 // Replace the operands of the cloned instructions with extracted scalars.
2500 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2501 Value *Op = Params[op][Part];
2502 // Param is a vector. Need to extract the right lane.
2503 if (Op->getType()->isVectorTy())
2504 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2505 Cloned->setOperand(op, Op);
2508 // Place the cloned scalar in the new loop.
2509 Builder.Insert(Cloned);
2511 // If the original scalar returns a value we need to place it in a vector
2512 // so that future users will be able to use it.
2514 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2515 Builder.getInt32(Width));
2517 if (IfPredicateStore)
2518 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
2524 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2528 if (Instruction *I = dyn_cast<Instruction>(V))
2529 return I->getParent() == Loc->getParent() ? I : nullptr;
2533 std::pair<Instruction *, Instruction *>
2534 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2535 Instruction *tnullptr = nullptr;
2536 if (!Legal->mustCheckStrides())
2537 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2539 IRBuilder<> ChkBuilder(Loc);
2542 Value *Check = nullptr;
2543 Instruction *FirstInst = nullptr;
2544 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2545 SE = Legal->strides_end();
2547 Value *Ptr = stripIntegerCast(*SI);
2548 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2550 // Store the first instruction we create.
2551 FirstInst = getFirstInst(FirstInst, C, Loc);
2553 Check = ChkBuilder.CreateOr(Check, C);
2558 // We have to do this trickery because the IRBuilder might fold the check to a
2559 // constant expression in which case there is no Instruction anchored in a
2561 LLVMContext &Ctx = Loc->getContext();
2562 Instruction *TheCheck =
2563 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2564 ChkBuilder.Insert(TheCheck, "stride.not.one");
2565 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2567 return std::make_pair(FirstInst, TheCheck);
2570 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L,
2575 BasicBlock *Header = L->getHeader();
2576 BasicBlock *Latch = L->getLoopLatch();
2577 // As we're just creating this loop, it's possible no latch exists
2578 // yet. If so, use the header as this will be a single block loop.
2582 IRBuilder<> Builder(Header->getFirstInsertionPt());
2583 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2584 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2586 Builder.SetInsertPoint(Latch->getTerminator());
2588 // Create i+1 and fill the PHINode.
2589 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2590 Induction->addIncoming(Start, L->getLoopPreheader());
2591 Induction->addIncoming(Next, Latch);
2592 // Create the compare.
2593 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2594 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2596 // Now we have two terminators. Remove the old one from the block.
2597 Latch->getTerminator()->eraseFromParent();
2602 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2606 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2607 // Find the loop boundaries.
2608 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(OrigLoop);
2609 assert(BackedgeTakenCount != SE->getCouldNotCompute() && "Invalid loop count");
2611 Type *IdxTy = Legal->getWidestInductionType();
2613 // The exit count might have the type of i64 while the phi is i32. This can
2614 // happen if we have an induction variable that is sign extended before the
2615 // compare. The only way that we get a backedge taken count is that the
2616 // induction variable was signed and as such will not overflow. In such a case
2617 // truncation is legal.
2618 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2619 IdxTy->getPrimitiveSizeInBits())
2620 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2621 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2623 // Get the total trip count from the count by adding 1.
2624 const SCEV *ExitCount =
2625 SE->getAddExpr(BackedgeTakenCount,
2626 SE->getConstant(BackedgeTakenCount->getType(), 1));
2628 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2630 // Expand the trip count and place the new instructions in the preheader.
2631 // Notice that the pre-header does not change, only the loop body.
2632 SCEVExpander Exp(*SE, DL, "induction");
2634 // Count holds the overall loop count (N).
2635 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2636 L->getLoopPreheader()->getTerminator());
2638 if (TripCount->getType()->isPointerTy())
2640 CastInst::CreatePointerCast(TripCount, IdxTy,
2641 "exitcount.ptrcnt.to.int",
2642 L->getLoopPreheader()->getTerminator());
2647 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2648 if (VectorTripCount)
2649 return VectorTripCount;
2651 Value *TC = getOrCreateTripCount(L);
2652 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2654 // Now we need to generate the expression for N - (N % VF), which is
2655 // the part that the vectorized body will execute.
2656 // The loop step is equal to the vectorization factor (num of SIMD elements)
2657 // times the unroll factor (num of SIMD instructions).
2658 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2659 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2660 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2662 return VectorTripCount;
2665 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2666 BasicBlock *Bypass) {
2667 Value *Count = getOrCreateTripCount(L);
2668 BasicBlock *BB = L->getLoopPreheader();
2669 IRBuilder<> Builder(BB->getTerminator());
2671 // Generate code to check that the loop's trip count that we computed by
2672 // adding one to the backedge-taken count will not overflow.
2673 Value *CheckMinIters =
2674 Builder.CreateICmpULT(Count,
2675 ConstantInt::get(Count->getType(), VF * UF),
2678 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2679 "min.iters.checked");
2680 if (L->getParentLoop())
2681 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2682 ReplaceInstWithInst(BB->getTerminator(),
2683 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2684 LoopBypassBlocks.push_back(BB);
2687 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2688 BasicBlock *Bypass) {
2689 Value *TC = getOrCreateVectorTripCount(L);
2690 BasicBlock *BB = L->getLoopPreheader();
2691 IRBuilder<> Builder(BB->getTerminator());
2693 // Now, compare the new count to zero. If it is zero skip the vector loop and
2694 // jump to the scalar loop.
2695 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2698 // Generate code to check that the loop's trip count that we computed by
2699 // adding one to the backedge-taken count will not overflow.
2700 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2702 if (L->getParentLoop())
2703 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2704 ReplaceInstWithInst(BB->getTerminator(),
2705 BranchInst::Create(Bypass, NewBB, Cmp));
2706 LoopBypassBlocks.push_back(BB);
2709 void InnerLoopVectorizer::emitStrideChecks(Loop *L,
2710 BasicBlock *Bypass) {
2711 BasicBlock *BB = L->getLoopPreheader();
2713 // Generate the code to check that the strides we assumed to be one are really
2714 // one. We want the new basic block to start at the first instruction in a
2715 // sequence of instructions that form a check.
2716 Instruction *StrideCheck;
2717 Instruction *FirstCheckInst;
2718 std::tie(FirstCheckInst, StrideCheck) = addStrideCheck(BB->getTerminator());
2722 // Create a new block containing the stride check.
2723 BB->setName("vector.stridecheck");
2724 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2725 if (L->getParentLoop())
2726 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2727 ReplaceInstWithInst(BB->getTerminator(),
2728 BranchInst::Create(Bypass, NewBB, StrideCheck));
2729 LoopBypassBlocks.push_back(BB);
2730 AddedSafetyChecks = true;
2733 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
2734 BasicBlock *Bypass) {
2735 BasicBlock *BB = L->getLoopPreheader();
2737 // Generate the code that checks in runtime if arrays overlap. We put the
2738 // checks into a separate block to make the more common case of few elements
2740 Instruction *FirstCheckInst;
2741 Instruction *MemRuntimeCheck;
2742 std::tie(FirstCheckInst, MemRuntimeCheck) =
2743 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2744 if (!MemRuntimeCheck)
2747 // Create a new block containing the memory check.
2748 BB->setName("vector.memcheck");
2749 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2750 if (L->getParentLoop())
2751 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2752 ReplaceInstWithInst(BB->getTerminator(),
2753 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2754 LoopBypassBlocks.push_back(BB);
2755 AddedSafetyChecks = true;
2759 void InnerLoopVectorizer::createEmptyLoop() {
2761 In this function we generate a new loop. The new loop will contain
2762 the vectorized instructions while the old loop will continue to run the
2765 [ ] <-- loop iteration number check.
2768 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2771 || [ ] <-- vector pre header.
2775 | [ ]_| <-- vector loop.
2778 | -[ ] <--- middle-block.
2781 -|- >[ ] <--- new preheader.
2785 | [ ]_| <-- old scalar loop to handle remainder.
2788 >[ ] <-- exit block.
2792 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2793 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2794 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2795 assert(VectorPH && "Invalid loop structure");
2796 assert(ExitBlock && "Must have an exit block");
2798 // Some loops have a single integer induction variable, while other loops
2799 // don't. One example is c++ iterators that often have multiple pointer
2800 // induction variables. In the code below we also support a case where we
2801 // don't have a single induction variable.
2803 // We try to obtain an induction variable from the original loop as hard
2804 // as possible. However if we don't find one that:
2806 // - counts from zero, stepping by one
2807 // - is the size of the widest induction variable type
2808 // then we create a new one.
2809 OldInduction = Legal->getInduction();
2810 Type *IdxTy = Legal->getWidestInductionType();
2812 // Split the single block loop into the two loop structure described above.
2813 BasicBlock *VecBody =
2814 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2815 BasicBlock *MiddleBlock =
2816 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2817 BasicBlock *ScalarPH =
2818 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2820 // Create and register the new vector loop.
2821 Loop* Lp = new Loop();
2822 Loop *ParentLoop = OrigLoop->getParentLoop();
2824 // Insert the new loop into the loop nest and register the new basic blocks
2825 // before calling any utilities such as SCEV that require valid LoopInfo.
2827 ParentLoop->addChildLoop(Lp);
2828 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2829 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2831 LI->addTopLevelLoop(Lp);
2833 Lp->addBasicBlockToLoop(VecBody, *LI);
2835 // Find the loop boundaries.
2836 Value *Count = getOrCreateTripCount(Lp);
2838 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2840 // We need to test whether the backedge-taken count is uint##_max. Adding one
2841 // to it will cause overflow and an incorrect loop trip count in the vector
2842 // body. In case of overflow we want to directly jump to the scalar remainder
2844 emitMinimumIterationCountCheck(Lp, ScalarPH);
2845 // Now, compare the new count to zero. If it is zero skip the vector loop and
2846 // jump to the scalar loop.
2847 emitVectorLoopEnteredCheck(Lp, ScalarPH);
2848 // Generate the code to check that the strides we assumed to be one are really
2849 // one. We want the new basic block to start at the first instruction in a
2850 // sequence of instructions that form a check.
2851 emitStrideChecks(Lp, ScalarPH);
2852 // Generate the code that checks in runtime if arrays overlap. We put the
2853 // checks into a separate block to make the more common case of few elements
2855 emitMemRuntimeChecks(Lp, ScalarPH);
2857 // Generate the induction variable.
2858 // The loop step is equal to the vectorization factor (num of SIMD elements)
2859 // times the unroll factor (num of SIMD instructions).
2860 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2861 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2863 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2864 getDebugLocFromInstOrOperands(OldInduction));
2866 // We are going to resume the execution of the scalar loop.
2867 // Go over all of the induction variables that we found and fix the
2868 // PHIs that are left in the scalar version of the loop.
2869 // The starting values of PHI nodes depend on the counter of the last
2870 // iteration in the vectorized loop.
2871 // If we come from a bypass edge then we need to start from the original
2874 // This variable saves the new starting index for the scalar loop. It is used
2875 // to test if there are any tail iterations left once the vector loop has
2877 LoopVectorizationLegality::InductionList::iterator I, E;
2878 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2879 for (I = List->begin(), E = List->end(); I != E; ++I) {
2880 PHINode *OrigPhi = I->first;
2881 InductionDescriptor II = I->second;
2883 // Create phi nodes to merge from the backedge-taken check block.
2884 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
2886 ScalarPH->getTerminator());
2888 if (OrigPhi == OldInduction) {
2889 // We know what the end value is.
2890 EndValue = CountRoundDown;
2892 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
2893 Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
2894 II.getStepValue()->getType(),
2896 EndValue = II.transform(B, CRD);
2897 EndValue->setName("ind.end");
2900 // The new PHI merges the original incoming value, in case of a bypass,
2901 // or the value at the end of the vectorized loop.
2902 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2904 // Fix the scalar body counter (PHI node).
2905 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2907 // The old induction's phi node in the scalar body needs the truncated
2909 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2910 BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
2911 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2914 // Add a check in the middle block to see if we have completed
2915 // all of the iterations in the first vector loop.
2916 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2917 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2918 CountRoundDown, "cmp.n",
2919 MiddleBlock->getTerminator());
2920 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2921 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2923 // Get ready to start creating new instructions into the vectorized body.
2924 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2927 LoopVectorPreHeader = Lp->getLoopPreheader();
2928 LoopScalarPreHeader = ScalarPH;
2929 LoopMiddleBlock = MiddleBlock;
2930 LoopExitBlock = ExitBlock;
2931 LoopVectorBody.push_back(VecBody);
2932 LoopScalarBody = OldBasicBlock;
2934 LoopVectorizeHints Hints(Lp, true);
2935 Hints.setAlreadyVectorized();
2939 struct CSEDenseMapInfo {
2940 static bool canHandle(Instruction *I) {
2941 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2942 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2944 static inline Instruction *getEmptyKey() {
2945 return DenseMapInfo<Instruction *>::getEmptyKey();
2947 static inline Instruction *getTombstoneKey() {
2948 return DenseMapInfo<Instruction *>::getTombstoneKey();
2950 static unsigned getHashValue(Instruction *I) {
2951 assert(canHandle(I) && "Unknown instruction!");
2952 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2953 I->value_op_end()));
2955 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2956 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2957 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2959 return LHS->isIdenticalTo(RHS);
2964 /// \brief Check whether this block is a predicated block.
2965 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2966 /// = ...; " blocks. We start with one vectorized basic block. For every
2967 /// conditional block we split this vectorized block. Therefore, every second
2968 /// block will be a predicated one.
2969 static bool isPredicatedBlock(unsigned BlockNum) {
2970 return BlockNum % 2;
2973 ///\brief Perform cse of induction variable instructions.
2974 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2975 // Perform simple cse.
2976 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2977 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2978 BasicBlock *BB = BBs[i];
2979 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2980 Instruction *In = I++;
2982 if (!CSEDenseMapInfo::canHandle(In))
2985 // Check if we can replace this instruction with any of the
2986 // visited instructions.
2987 if (Instruction *V = CSEMap.lookup(In)) {
2988 In->replaceAllUsesWith(V);
2989 In->eraseFromParent();
2992 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2993 // ...;" blocks for predicated stores. Every second block is a predicated
2995 if (isPredicatedBlock(i))
3003 /// \brief Adds a 'fast' flag to floating point operations.
3004 static Value *addFastMathFlag(Value *V) {
3005 if (isa<FPMathOperator>(V)){
3006 FastMathFlags Flags;
3007 Flags.setUnsafeAlgebra();
3008 cast<Instruction>(V)->setFastMathFlags(Flags);
3013 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3014 /// the result needs to be inserted and/or extracted from vectors.
3015 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3016 const TargetTransformInfo &TTI) {
3020 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3023 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3025 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3027 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3033 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3034 // Return the cost of the instruction, including scalarization overhead if it's
3035 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3036 // i.e. either vector version isn't available, or is too expensive.
3037 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3038 const TargetTransformInfo &TTI,
3039 const TargetLibraryInfo *TLI,
3040 bool &NeedToScalarize) {
3041 Function *F = CI->getCalledFunction();
3042 StringRef FnName = CI->getCalledFunction()->getName();
3043 Type *ScalarRetTy = CI->getType();
3044 SmallVector<Type *, 4> Tys, ScalarTys;
3045 for (auto &ArgOp : CI->arg_operands())
3046 ScalarTys.push_back(ArgOp->getType());
3048 // Estimate cost of scalarized vector call. The source operands are assumed
3049 // to be vectors, so we need to extract individual elements from there,
3050 // execute VF scalar calls, and then gather the result into the vector return
3052 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3054 return ScalarCallCost;
3056 // Compute corresponding vector type for return value and arguments.
3057 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3058 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3059 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3061 // Compute costs of unpacking argument values for the scalar calls and
3062 // packing the return values to a vector.
3063 unsigned ScalarizationCost =
3064 getScalarizationOverhead(RetTy, true, false, TTI);
3065 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3066 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3068 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3070 // If we can't emit a vector call for this function, then the currently found
3071 // cost is the cost we need to return.
3072 NeedToScalarize = true;
3073 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3076 // If the corresponding vector cost is cheaper, return its cost.
3077 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3078 if (VectorCallCost < Cost) {
3079 NeedToScalarize = false;
3080 return VectorCallCost;
3085 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3086 // factor VF. Return the cost of the instruction, including scalarization
3087 // overhead if it's needed.
3088 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3089 const TargetTransformInfo &TTI,
3090 const TargetLibraryInfo *TLI) {
3091 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3092 assert(ID && "Expected intrinsic call!");
3094 Type *RetTy = ToVectorTy(CI->getType(), VF);
3095 SmallVector<Type *, 4> Tys;
3096 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3097 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3099 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3102 void InnerLoopVectorizer::vectorizeLoop() {
3103 //===------------------------------------------------===//
3105 // Notice: any optimization or new instruction that go
3106 // into the code below should be also be implemented in
3109 //===------------------------------------------------===//
3110 Constant *Zero = Builder.getInt32(0);
3112 // In order to support reduction variables we need to be able to vectorize
3113 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3114 // stages. First, we create a new vector PHI node with no incoming edges.
3115 // We use this value when we vectorize all of the instructions that use the
3116 // PHI. Next, after all of the instructions in the block are complete we
3117 // add the new incoming edges to the PHI. At this point all of the
3118 // instructions in the basic block are vectorized, so we can use them to
3119 // construct the PHI.
3120 PhiVector RdxPHIsToFix;
3122 // Scan the loop in a topological order to ensure that defs are vectorized
3124 LoopBlocksDFS DFS(OrigLoop);
3127 // Vectorize all of the blocks in the original loop.
3128 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3129 be = DFS.endRPO(); bb != be; ++bb)
3130 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3132 // At this point every instruction in the original loop is widened to
3133 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3134 // that we vectorized. The PHI nodes are currently empty because we did
3135 // not want to introduce cycles. Notice that the remaining PHI nodes
3136 // that we need to fix are reduction variables.
3138 // Create the 'reduced' values for each of the induction vars.
3139 // The reduced values are the vector values that we scalarize and combine
3140 // after the loop is finished.
3141 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3143 PHINode *RdxPhi = *it;
3144 assert(RdxPhi && "Unable to recover vectorized PHI");
3146 // Find the reduction variable descriptor.
3147 assert(Legal->getReductionVars()->count(RdxPhi) &&
3148 "Unable to find the reduction variable");
3149 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3151 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3152 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3153 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3154 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3155 RdxDesc.getMinMaxRecurrenceKind();
3156 setDebugLocFromInst(Builder, ReductionStartValue);
3158 // We need to generate a reduction vector from the incoming scalar.
3159 // To do so, we need to generate the 'identity' vector and override
3160 // one of the elements with the incoming scalar reduction. We need
3161 // to do it in the vector-loop preheader.
3162 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3164 // This is the vector-clone of the value that leaves the loop.
3165 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3166 Type *VecTy = VectorExit[0]->getType();
3168 // Find the reduction identity variable. Zero for addition, or, xor,
3169 // one for multiplication, -1 for And.
3172 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3173 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3174 // MinMax reduction have the start value as their identify.
3176 VectorStart = Identity = ReductionStartValue;
3178 VectorStart = Identity =
3179 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3182 // Handle other reduction kinds:
3183 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3184 RK, VecTy->getScalarType());
3187 // This vector is the Identity vector where the first element is the
3188 // incoming scalar reduction.
3189 VectorStart = ReductionStartValue;
3191 Identity = ConstantVector::getSplat(VF, Iden);
3193 // This vector is the Identity vector where the first element is the
3194 // incoming scalar reduction.
3196 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3200 // Fix the vector-loop phi.
3202 // Reductions do not have to start at zero. They can start with
3203 // any loop invariant values.
3204 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3205 BasicBlock *Latch = OrigLoop->getLoopLatch();
3206 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3207 VectorParts &Val = getVectorValue(LoopVal);
3208 for (unsigned part = 0; part < UF; ++part) {
3209 // Make sure to add the reduction stat value only to the
3210 // first unroll part.
3211 Value *StartVal = (part == 0) ? VectorStart : Identity;
3212 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3213 LoopVectorPreHeader);
3214 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3215 LoopVectorBody.back());
3218 // Before each round, move the insertion point right between
3219 // the PHIs and the values we are going to write.
3220 // This allows us to write both PHINodes and the extractelement
3222 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3224 VectorParts RdxParts = getVectorValue(LoopExitInst);
3225 setDebugLocFromInst(Builder, LoopExitInst);
3227 // If the vector reduction can be performed in a smaller type, we truncate
3228 // then extend the loop exit value to enable InstCombine to evaluate the
3229 // entire expression in the smaller type.
3230 if (VF > 1 && RdxPhi->getType() != RdxDesc.getRecurrenceType()) {
3231 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3232 Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
3233 for (unsigned part = 0; part < UF; ++part) {
3234 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3235 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3236 : Builder.CreateZExt(Trunc, VecTy);
3237 for (Value::user_iterator UI = RdxParts[part]->user_begin();
3238 UI != RdxParts[part]->user_end();)
3240 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3241 RdxParts[part] = Extnd;
3246 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3247 for (unsigned part = 0; part < UF; ++part)
3248 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3251 // Reduce all of the unrolled parts into a single vector.
3252 Value *ReducedPartRdx = RdxParts[0];
3253 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3254 setDebugLocFromInst(Builder, ReducedPartRdx);
3255 for (unsigned part = 1; part < UF; ++part) {
3256 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3257 // Floating point operations had to be 'fast' to enable the reduction.
3258 ReducedPartRdx = addFastMathFlag(
3259 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3260 ReducedPartRdx, "bin.rdx"));
3262 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3263 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3267 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3268 // and vector ops, reducing the set of values being computed by half each
3270 assert(isPowerOf2_32(VF) &&
3271 "Reduction emission only supported for pow2 vectors!");
3272 Value *TmpVec = ReducedPartRdx;
3273 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3274 for (unsigned i = VF; i != 1; i >>= 1) {
3275 // Move the upper half of the vector to the lower half.
3276 for (unsigned j = 0; j != i/2; ++j)
3277 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3279 // Fill the rest of the mask with undef.
3280 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3281 UndefValue::get(Builder.getInt32Ty()));
3284 Builder.CreateShuffleVector(TmpVec,
3285 UndefValue::get(TmpVec->getType()),
3286 ConstantVector::get(ShuffleMask),
3289 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3290 // Floating point operations had to be 'fast' to enable the reduction.
3291 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3292 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3294 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3298 // The result is in the first element of the vector.
3299 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3300 Builder.getInt32(0));
3302 // If the reduction can be performed in a smaller type, we need to extend
3303 // the reduction to the wider type before we branch to the original loop.
3304 if (RdxPhi->getType() != RdxDesc.getRecurrenceType())
3307 ? Builder.CreateSExt(ReducedPartRdx, RdxPhi->getType())
3308 : Builder.CreateZExt(ReducedPartRdx, RdxPhi->getType());
3311 // Create a phi node that merges control-flow from the backedge-taken check
3312 // block and the middle block.
3313 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3314 LoopScalarPreHeader->getTerminator());
3315 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3316 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3317 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3319 // Now, we need to fix the users of the reduction variable
3320 // inside and outside of the scalar remainder loop.
3321 // We know that the loop is in LCSSA form. We need to update the
3322 // PHI nodes in the exit blocks.
3323 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3324 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3325 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3326 if (!LCSSAPhi) break;
3328 // All PHINodes need to have a single entry edge, or two if
3329 // we already fixed them.
3330 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3332 // We found our reduction value exit-PHI. Update it with the
3333 // incoming bypass edge.
3334 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3335 // Add an edge coming from the bypass.
3336 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3339 }// end of the LCSSA phi scan.
3341 // Fix the scalar loop reduction variable with the incoming reduction sum
3342 // from the vector body and from the backedge value.
3343 int IncomingEdgeBlockIdx =
3344 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3345 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3346 // Pick the other block.
3347 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3348 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3349 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3350 }// end of for each redux variable.
3354 // Make sure DomTree is updated.
3357 // Predicate any stores.
3358 for (auto KV : PredicatedStores) {
3359 BasicBlock::iterator I(KV.first);
3360 auto *BB = SplitBlock(I->getParent(), std::next(I), DT, LI);
3361 auto *T = SplitBlockAndInsertIfThen(KV.second, I, /*Unreachable=*/false,
3362 /*BranchWeights=*/nullptr, DT);
3364 I->getParent()->setName("pred.store.if");
3365 BB->setName("pred.store.continue");
3367 DEBUG(DT->verifyDomTree());
3368 // Remove redundant induction instructions.
3369 cse(LoopVectorBody);
3372 void InnerLoopVectorizer::fixLCSSAPHIs() {
3373 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3374 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3375 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3376 if (!LCSSAPhi) break;
3377 if (LCSSAPhi->getNumIncomingValues() == 1)
3378 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3383 InnerLoopVectorizer::VectorParts
3384 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3385 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3388 // Look for cached value.
3389 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3390 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3391 if (ECEntryIt != MaskCache.end())
3392 return ECEntryIt->second;
3394 VectorParts SrcMask = createBlockInMask(Src);
3396 // The terminator has to be a branch inst!
3397 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3398 assert(BI && "Unexpected terminator found");
3400 if (BI->isConditional()) {
3401 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3403 if (BI->getSuccessor(0) != Dst)
3404 for (unsigned part = 0; part < UF; ++part)
3405 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3407 for (unsigned part = 0; part < UF; ++part)
3408 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3410 MaskCache[Edge] = EdgeMask;
3414 MaskCache[Edge] = SrcMask;
3418 InnerLoopVectorizer::VectorParts
3419 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3420 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3422 // Loop incoming mask is all-one.
3423 if (OrigLoop->getHeader() == BB) {
3424 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3425 return getVectorValue(C);
3428 // This is the block mask. We OR all incoming edges, and with zero.
3429 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3430 VectorParts BlockMask = getVectorValue(Zero);
3433 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3434 VectorParts EM = createEdgeMask(*it, BB);
3435 for (unsigned part = 0; part < UF; ++part)
3436 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3442 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3443 InnerLoopVectorizer::VectorParts &Entry,
3444 unsigned UF, unsigned VF, PhiVector *PV) {
3445 PHINode* P = cast<PHINode>(PN);
3446 // Handle reduction variables:
3447 if (Legal->getReductionVars()->count(P)) {
3448 for (unsigned part = 0; part < UF; ++part) {
3449 // This is phase one of vectorizing PHIs.
3450 Type *VecTy = (VF == 1) ? PN->getType() :
3451 VectorType::get(PN->getType(), VF);
3452 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3453 LoopVectorBody.back()-> getFirstInsertionPt());
3459 setDebugLocFromInst(Builder, P);
3460 // Check for PHI nodes that are lowered to vector selects.
3461 if (P->getParent() != OrigLoop->getHeader()) {
3462 // We know that all PHIs in non-header blocks are converted into
3463 // selects, so we don't have to worry about the insertion order and we
3464 // can just use the builder.
3465 // At this point we generate the predication tree. There may be
3466 // duplications since this is a simple recursive scan, but future
3467 // optimizations will clean it up.
3469 unsigned NumIncoming = P->getNumIncomingValues();
3471 // Generate a sequence of selects of the form:
3472 // SELECT(Mask3, In3,
3473 // SELECT(Mask2, In2,
3475 for (unsigned In = 0; In < NumIncoming; In++) {
3476 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3478 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3480 for (unsigned part = 0; part < UF; ++part) {
3481 // We might have single edge PHIs (blocks) - use an identity
3482 // 'select' for the first PHI operand.
3484 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3487 // Select between the current value and the previous incoming edge
3488 // based on the incoming mask.
3489 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3490 Entry[part], "predphi");
3496 // This PHINode must be an induction variable.
3497 // Make sure that we know about it.
3498 assert(Legal->getInductionVars()->count(P) &&
3499 "Not an induction variable");
3501 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3503 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3504 // which can be found from the original scalar operations.
3505 switch (II.getKind()) {
3506 case InductionDescriptor::IK_NoInduction:
3507 llvm_unreachable("Unknown induction");
3508 case InductionDescriptor::IK_IntInduction: {
3509 assert(P->getType() == II.getStartValue()->getType() && "Types must match");
3510 // Handle other induction variables that are now based on the
3512 Value *V = Induction;
3513 if (P != OldInduction) {
3514 V = Builder.CreateSExtOrTrunc(Induction, P->getType());
3515 V = II.transform(Builder, V);
3516 V->setName("offset.idx");
3518 Value *Broadcasted = getBroadcastInstrs(V);
3519 // After broadcasting the induction variable we need to make the vector
3520 // consecutive by adding 0, 1, 2, etc.
3521 for (unsigned part = 0; part < UF; ++part)
3522 Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
3525 case InductionDescriptor::IK_PtrInduction:
3526 // Handle the pointer induction variable case.
3527 assert(P->getType()->isPointerTy() && "Unexpected type.");
3528 // This is the normalized GEP that starts counting at zero.
3529 Value *PtrInd = Induction;
3530 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
3531 // This is the vector of results. Notice that we don't generate
3532 // vector geps because scalar geps result in better code.
3533 for (unsigned part = 0; part < UF; ++part) {
3535 int EltIndex = part;
3536 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3537 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3538 Value *SclrGep = II.transform(Builder, GlobalIdx);
3539 SclrGep->setName("next.gep");
3540 Entry[part] = SclrGep;
3544 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3545 for (unsigned int i = 0; i < VF; ++i) {
3546 int EltIndex = i + part * VF;
3547 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3548 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3549 Value *SclrGep = II.transform(Builder, GlobalIdx);
3550 SclrGep->setName("next.gep");
3551 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3552 Builder.getInt32(i),
3555 Entry[part] = VecVal;
3561 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3562 // For each instruction in the old loop.
3563 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3564 VectorParts &Entry = WidenMap.get(it);
3565 switch (it->getOpcode()) {
3566 case Instruction::Br:
3567 // Nothing to do for PHIs and BR, since we already took care of the
3568 // loop control flow instructions.
3570 case Instruction::PHI: {
3571 // Vectorize PHINodes.
3572 widenPHIInstruction(it, Entry, UF, VF, PV);
3576 case Instruction::Add:
3577 case Instruction::FAdd:
3578 case Instruction::Sub:
3579 case Instruction::FSub:
3580 case Instruction::Mul:
3581 case Instruction::FMul:
3582 case Instruction::UDiv:
3583 case Instruction::SDiv:
3584 case Instruction::FDiv:
3585 case Instruction::URem:
3586 case Instruction::SRem:
3587 case Instruction::FRem:
3588 case Instruction::Shl:
3589 case Instruction::LShr:
3590 case Instruction::AShr:
3591 case Instruction::And:
3592 case Instruction::Or:
3593 case Instruction::Xor: {
3594 // Just widen binops.
3595 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3596 setDebugLocFromInst(Builder, BinOp);
3597 VectorParts &A = getVectorValue(it->getOperand(0));
3598 VectorParts &B = getVectorValue(it->getOperand(1));
3600 // Use this vector value for all users of the original instruction.
3601 for (unsigned Part = 0; Part < UF; ++Part) {
3602 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3604 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3605 VecOp->copyIRFlags(BinOp);
3610 propagateMetadata(Entry, it);
3613 case Instruction::Select: {
3615 // If the selector is loop invariant we can create a select
3616 // instruction with a scalar condition. Otherwise, use vector-select.
3617 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3619 setDebugLocFromInst(Builder, it);
3621 // The condition can be loop invariant but still defined inside the
3622 // loop. This means that we can't just use the original 'cond' value.
3623 // We have to take the 'vectorized' value and pick the first lane.
3624 // Instcombine will make this a no-op.
3625 VectorParts &Cond = getVectorValue(it->getOperand(0));
3626 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3627 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3629 Value *ScalarCond = (VF == 1) ? Cond[0] :
3630 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3632 for (unsigned Part = 0; Part < UF; ++Part) {
3633 Entry[Part] = Builder.CreateSelect(
3634 InvariantCond ? ScalarCond : Cond[Part],
3639 propagateMetadata(Entry, it);
3643 case Instruction::ICmp:
3644 case Instruction::FCmp: {
3645 // Widen compares. Generate vector compares.
3646 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3647 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3648 setDebugLocFromInst(Builder, it);
3649 VectorParts &A = getVectorValue(it->getOperand(0));
3650 VectorParts &B = getVectorValue(it->getOperand(1));
3651 for (unsigned Part = 0; Part < UF; ++Part) {
3654 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3656 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3660 propagateMetadata(Entry, it);
3664 case Instruction::Store:
3665 case Instruction::Load:
3666 vectorizeMemoryInstruction(it);
3668 case Instruction::ZExt:
3669 case Instruction::SExt:
3670 case Instruction::FPToUI:
3671 case Instruction::FPToSI:
3672 case Instruction::FPExt:
3673 case Instruction::PtrToInt:
3674 case Instruction::IntToPtr:
3675 case Instruction::SIToFP:
3676 case Instruction::UIToFP:
3677 case Instruction::Trunc:
3678 case Instruction::FPTrunc:
3679 case Instruction::BitCast: {
3680 CastInst *CI = dyn_cast<CastInst>(it);
3681 setDebugLocFromInst(Builder, it);
3682 /// Optimize the special case where the source is the induction
3683 /// variable. Notice that we can only optimize the 'trunc' case
3684 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3685 /// c. other casts depend on pointer size.
3686 if (CI->getOperand(0) == OldInduction &&
3687 it->getOpcode() == Instruction::Trunc) {
3688 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3690 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3691 InductionDescriptor II = Legal->getInductionVars()->lookup(OldInduction);
3693 ConstantInt::getSigned(CI->getType(), II.getStepValue()->getSExtValue());
3694 for (unsigned Part = 0; Part < UF; ++Part)
3695 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3696 propagateMetadata(Entry, it);
3699 /// Vectorize casts.
3700 Type *DestTy = (VF == 1) ? CI->getType() :
3701 VectorType::get(CI->getType(), VF);
3703 VectorParts &A = getVectorValue(it->getOperand(0));
3704 for (unsigned Part = 0; Part < UF; ++Part)
3705 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3706 propagateMetadata(Entry, it);
3710 case Instruction::Call: {
3711 // Ignore dbg intrinsics.
3712 if (isa<DbgInfoIntrinsic>(it))
3714 setDebugLocFromInst(Builder, it);
3716 Module *M = BB->getParent()->getParent();
3717 CallInst *CI = cast<CallInst>(it);
3719 StringRef FnName = CI->getCalledFunction()->getName();
3720 Function *F = CI->getCalledFunction();
3721 Type *RetTy = ToVectorTy(CI->getType(), VF);
3722 SmallVector<Type *, 4> Tys;
3723 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3724 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3726 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3728 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3729 ID == Intrinsic::lifetime_start)) {
3730 scalarizeInstruction(it);
3733 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3734 // version of the instruction.
3735 // Is it beneficial to perform intrinsic call compared to lib call?
3736 bool NeedToScalarize;
3737 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3738 bool UseVectorIntrinsic =
3739 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3740 if (!UseVectorIntrinsic && NeedToScalarize) {
3741 scalarizeInstruction(it);
3745 for (unsigned Part = 0; Part < UF; ++Part) {
3746 SmallVector<Value *, 4> Args;
3747 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3748 Value *Arg = CI->getArgOperand(i);
3749 // Some intrinsics have a scalar argument - don't replace it with a
3751 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3752 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3753 Arg = VectorArg[Part];
3755 Args.push_back(Arg);
3759 if (UseVectorIntrinsic) {
3760 // Use vector version of the intrinsic.
3761 Type *TysForDecl[] = {CI->getType()};
3763 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3764 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3766 // Use vector version of the library call.
3767 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3768 assert(!VFnName.empty() && "Vector function name is empty.");
3769 VectorF = M->getFunction(VFnName);
3771 // Generate a declaration
3772 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3774 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3775 VectorF->copyAttributesFrom(F);
3778 assert(VectorF && "Can't create vector function.");
3779 Entry[Part] = Builder.CreateCall(VectorF, Args);
3782 propagateMetadata(Entry, it);
3787 // All other instructions are unsupported. Scalarize them.
3788 scalarizeInstruction(it);
3791 }// end of for_each instr.
3794 void InnerLoopVectorizer::updateAnalysis() {
3795 // Forget the original basic block.
3796 SE->forgetLoop(OrigLoop);
3798 // Update the dominator tree information.
3799 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3800 "Entry does not dominate exit.");
3802 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3803 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3804 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3806 // We don't predicate stores by this point, so the vector body should be a
3808 assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
3809 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3811 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
3812 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3813 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3814 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3816 DEBUG(DT->verifyDomTree());
3819 /// \brief Check whether it is safe to if-convert this phi node.
3821 /// Phi nodes with constant expressions that can trap are not safe to if
3823 static bool canIfConvertPHINodes(BasicBlock *BB) {
3824 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3825 PHINode *Phi = dyn_cast<PHINode>(I);
3828 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3829 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3836 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3837 if (!EnableIfConversion) {
3838 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3842 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3844 // A list of pointers that we can safely read and write to.
3845 SmallPtrSet<Value *, 8> SafePointes;
3847 // Collect safe addresses.
3848 for (Loop::block_iterator BI = TheLoop->block_begin(),
3849 BE = TheLoop->block_end(); BI != BE; ++BI) {
3850 BasicBlock *BB = *BI;
3852 if (blockNeedsPredication(BB))
3855 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3856 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3857 SafePointes.insert(LI->getPointerOperand());
3858 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3859 SafePointes.insert(SI->getPointerOperand());
3863 // Collect the blocks that need predication.
3864 BasicBlock *Header = TheLoop->getHeader();
3865 for (Loop::block_iterator BI = TheLoop->block_begin(),
3866 BE = TheLoop->block_end(); BI != BE; ++BI) {
3867 BasicBlock *BB = *BI;
3869 // We don't support switch statements inside loops.
3870 if (!isa<BranchInst>(BB->getTerminator())) {
3871 emitAnalysis(VectorizationReport(BB->getTerminator())
3872 << "loop contains a switch statement");
3876 // We must be able to predicate all blocks that need to be predicated.
3877 if (blockNeedsPredication(BB)) {
3878 if (!blockCanBePredicated(BB, SafePointes)) {
3879 emitAnalysis(VectorizationReport(BB->getTerminator())
3880 << "control flow cannot be substituted for a select");
3883 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3884 emitAnalysis(VectorizationReport(BB->getTerminator())
3885 << "control flow cannot be substituted for a select");
3890 // We can if-convert this loop.
3894 bool LoopVectorizationLegality::canVectorize() {
3895 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3896 // be canonicalized.
3897 if (!TheLoop->getLoopPreheader()) {
3899 VectorizationReport() <<
3900 "loop control flow is not understood by vectorizer");
3904 // We can only vectorize innermost loops.
3905 if (!TheLoop->empty()) {
3906 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3910 // We must have a single backedge.
3911 if (TheLoop->getNumBackEdges() != 1) {
3913 VectorizationReport() <<
3914 "loop control flow is not understood by vectorizer");
3918 // We must have a single exiting block.
3919 if (!TheLoop->getExitingBlock()) {
3921 VectorizationReport() <<
3922 "loop control flow is not understood by vectorizer");
3926 // We only handle bottom-tested loops, i.e. loop in which the condition is
3927 // checked at the end of each iteration. With that we can assume that all
3928 // instructions in the loop are executed the same number of times.
3929 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3931 VectorizationReport() <<
3932 "loop control flow is not understood by vectorizer");
3936 // We need to have a loop header.
3937 DEBUG(dbgs() << "LV: Found a loop: " <<
3938 TheLoop->getHeader()->getName() << '\n');
3940 // Check if we can if-convert non-single-bb loops.
3941 unsigned NumBlocks = TheLoop->getNumBlocks();
3942 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3943 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3947 // ScalarEvolution needs to be able to find the exit count.
3948 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3949 if (ExitCount == SE->getCouldNotCompute()) {
3950 emitAnalysis(VectorizationReport() <<
3951 "could not determine number of loop iterations");
3952 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3956 // Check if we can vectorize the instructions and CFG in this loop.
3957 if (!canVectorizeInstrs()) {
3958 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3962 // Go over each instruction and look at memory deps.
3963 if (!canVectorizeMemory()) {
3964 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3968 // Collect all of the variables that remain uniform after vectorization.
3969 collectLoopUniforms();
3971 DEBUG(dbgs() << "LV: We can vectorize this loop"
3972 << (LAI->getRuntimePointerChecking()->Need
3973 ? " (with a runtime bound check)"
3977 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
3979 // If an override option has been passed in for interleaved accesses, use it.
3980 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
3981 UseInterleaved = EnableInterleavedMemAccesses;
3983 // Analyze interleaved memory accesses.
3985 InterleaveInfo.analyzeInterleaving(Strides);
3987 // Okay! We can vectorize. At this point we don't have any other mem analysis
3988 // which may limit our maximum vectorization factor, so just return true with
3993 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3994 if (Ty->isPointerTy())
3995 return DL.getIntPtrType(Ty);
3997 // It is possible that char's or short's overflow when we ask for the loop's
3998 // trip count, work around this by changing the type size.
3999 if (Ty->getScalarSizeInBits() < 32)
4000 return Type::getInt32Ty(Ty->getContext());
4005 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4006 Ty0 = convertPointerToIntegerType(DL, Ty0);
4007 Ty1 = convertPointerToIntegerType(DL, Ty1);
4008 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4013 /// \brief Check that the instruction has outside loop users and is not an
4014 /// identified reduction variable.
4015 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4016 SmallPtrSetImpl<Value *> &Reductions) {
4017 // Reduction instructions are allowed to have exit users. All other
4018 // instructions must not have external users.
4019 if (!Reductions.count(Inst))
4020 //Check that all of the users of the loop are inside the BB.
4021 for (User *U : Inst->users()) {
4022 Instruction *UI = cast<Instruction>(U);
4023 // This user may be a reduction exit value.
4024 if (!TheLoop->contains(UI)) {
4025 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4032 bool LoopVectorizationLegality::canVectorizeInstrs() {
4033 BasicBlock *Header = TheLoop->getHeader();
4035 // Look for the attribute signaling the absence of NaNs.
4036 Function &F = *Header->getParent();
4037 const DataLayout &DL = F.getParent()->getDataLayout();
4038 if (F.hasFnAttribute("no-nans-fp-math"))
4040 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4042 // For each block in the loop.
4043 for (Loop::block_iterator bb = TheLoop->block_begin(),
4044 be = TheLoop->block_end(); bb != be; ++bb) {
4046 // Scan the instructions in the block and look for hazards.
4047 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4050 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4051 Type *PhiTy = Phi->getType();
4052 // Check that this PHI type is allowed.
4053 if (!PhiTy->isIntegerTy() &&
4054 !PhiTy->isFloatingPointTy() &&
4055 !PhiTy->isPointerTy()) {
4056 emitAnalysis(VectorizationReport(it)
4057 << "loop control flow is not understood by vectorizer");
4058 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4062 // If this PHINode is not in the header block, then we know that we
4063 // can convert it to select during if-conversion. No need to check if
4064 // the PHIs in this block are induction or reduction variables.
4065 if (*bb != Header) {
4066 // Check that this instruction has no outside users or is an
4067 // identified reduction value with an outside user.
4068 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
4070 emitAnalysis(VectorizationReport(it) <<
4071 "value could not be identified as "
4072 "an induction or reduction variable");
4076 // We only allow if-converted PHIs with exactly two incoming values.
4077 if (Phi->getNumIncomingValues() != 2) {
4078 emitAnalysis(VectorizationReport(it)
4079 << "control flow not understood by vectorizer");
4080 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4084 InductionDescriptor ID;
4085 if (InductionDescriptor::isInductionPHI(Phi, SE, ID)) {
4086 Inductions[Phi] = ID;
4087 // Get the widest type.
4089 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4091 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4093 // Int inductions are special because we only allow one IV.
4094 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4095 ID.getStepValue()->isOne() &&
4096 isa<Constant>(ID.getStartValue()) &&
4097 cast<Constant>(ID.getStartValue())->isNullValue()) {
4098 // Use the phi node with the widest type as induction. Use the last
4099 // one if there are multiple (no good reason for doing this other
4100 // than it is expedient). We've checked that it begins at zero and
4101 // steps by one, so this is a canonical induction variable.
4102 if (!Induction || PhiTy == WidestIndTy)
4106 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4108 // Until we explicitly handle the case of an induction variable with
4109 // an outside loop user we have to give up vectorizing this loop.
4110 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4111 emitAnalysis(VectorizationReport(it) <<
4112 "use of induction value outside of the "
4113 "loop is not handled by vectorizer");
4120 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4122 if (Reductions[Phi].hasUnsafeAlgebra())
4123 Requirements->addUnsafeAlgebraInst(
4124 Reductions[Phi].getUnsafeAlgebraInst());
4125 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4129 emitAnalysis(VectorizationReport(it) <<
4130 "value that could not be identified as "
4131 "reduction is used outside the loop");
4132 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4134 }// end of PHI handling
4136 // We handle calls that:
4137 // * Are debug info intrinsics.
4138 // * Have a mapping to an IR intrinsic.
4139 // * Have a vector version available.
4140 CallInst *CI = dyn_cast<CallInst>(it);
4141 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4142 !(CI->getCalledFunction() && TLI &&
4143 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4144 emitAnalysis(VectorizationReport(it) <<
4145 "call instruction cannot be vectorized");
4146 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4150 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4151 // second argument is the same (i.e. loop invariant)
4153 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4154 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4155 emitAnalysis(VectorizationReport(it)
4156 << "intrinsic instruction cannot be vectorized");
4157 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4162 // Check that the instruction return type is vectorizable.
4163 // Also, we can't vectorize extractelement instructions.
4164 if ((!VectorType::isValidElementType(it->getType()) &&
4165 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4166 emitAnalysis(VectorizationReport(it)
4167 << "instruction return type cannot be vectorized");
4168 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4172 // Check that the stored type is vectorizable.
4173 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4174 Type *T = ST->getValueOperand()->getType();
4175 if (!VectorType::isValidElementType(T)) {
4176 emitAnalysis(VectorizationReport(ST) <<
4177 "store instruction cannot be vectorized");
4180 if (EnableMemAccessVersioning)
4181 collectStridedAccess(ST);
4184 if (EnableMemAccessVersioning)
4185 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4186 collectStridedAccess(LI);
4188 // Reduction instructions are allowed to have exit users.
4189 // All other instructions must not have external users.
4190 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4191 emitAnalysis(VectorizationReport(it) <<
4192 "value cannot be used outside the loop");
4201 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4202 if (Inductions.empty()) {
4203 emitAnalysis(VectorizationReport()
4204 << "loop induction variable could not be identified");
4209 // Now we know the widest induction type, check if our found induction
4210 // is the same size. If it's not, unset it here and InnerLoopVectorizer
4211 // will create another.
4212 if (Induction && WidestIndTy != Induction->getType())
4213 Induction = nullptr;
4218 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4219 Value *Ptr = nullptr;
4220 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4221 Ptr = LI->getPointerOperand();
4222 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4223 Ptr = SI->getPointerOperand();
4227 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4231 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4232 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4233 Strides[Ptr] = Stride;
4234 StrideSet.insert(Stride);
4237 void LoopVectorizationLegality::collectLoopUniforms() {
4238 // We now know that the loop is vectorizable!
4239 // Collect variables that will remain uniform after vectorization.
4240 std::vector<Value*> Worklist;
4241 BasicBlock *Latch = TheLoop->getLoopLatch();
4243 // Start with the conditional branch and walk up the block.
4244 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4246 // Also add all consecutive pointer values; these values will be uniform
4247 // after vectorization (and subsequent cleanup) and, until revectorization is
4248 // supported, all dependencies must also be uniform.
4249 for (Loop::block_iterator B = TheLoop->block_begin(),
4250 BE = TheLoop->block_end(); B != BE; ++B)
4251 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4253 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4254 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4256 while (!Worklist.empty()) {
4257 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4258 Worklist.pop_back();
4260 // Look at instructions inside this loop.
4261 // Stop when reaching PHI nodes.
4262 // TODO: we need to follow values all over the loop, not only in this block.
4263 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4266 // This is a known uniform.
4269 // Insert all operands.
4270 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4274 bool LoopVectorizationLegality::canVectorizeMemory() {
4275 LAI = &LAA->getInfo(TheLoop, Strides);
4276 auto &OptionalReport = LAI->getReport();
4278 emitAnalysis(VectorizationReport(*OptionalReport));
4279 if (!LAI->canVectorizeMemory())
4282 if (LAI->hasStoreToLoopInvariantAddress()) {
4284 VectorizationReport()
4285 << "write to a loop invariant address could not be vectorized");
4286 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4290 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4295 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4296 Value *In0 = const_cast<Value*>(V);
4297 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4301 return Inductions.count(PN);
4304 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4305 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4308 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4309 SmallPtrSetImpl<Value *> &SafePtrs) {
4311 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4312 // Check that we don't have a constant expression that can trap as operand.
4313 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4315 if (Constant *C = dyn_cast<Constant>(*OI))
4319 // We might be able to hoist the load.
4320 if (it->mayReadFromMemory()) {
4321 LoadInst *LI = dyn_cast<LoadInst>(it);
4324 if (!SafePtrs.count(LI->getPointerOperand())) {
4325 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4326 MaskedOp.insert(LI);
4333 // We don't predicate stores at the moment.
4334 if (it->mayWriteToMemory()) {
4335 StoreInst *SI = dyn_cast<StoreInst>(it);
4336 // We only support predication of stores in basic blocks with one
4341 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4342 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4344 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4345 !isSinglePredecessor) {
4346 // Build a masked store if it is legal for the target, otherwise scalarize
4348 bool isLegalMaskedOp =
4349 isLegalMaskedStore(SI->getValueOperand()->getType(),
4350 SI->getPointerOperand());
4351 if (isLegalMaskedOp) {
4353 MaskedOp.insert(SI);
4362 // The instructions below can trap.
4363 switch (it->getOpcode()) {
4365 case Instruction::UDiv:
4366 case Instruction::SDiv:
4367 case Instruction::URem:
4368 case Instruction::SRem:
4376 void InterleavedAccessInfo::collectConstStridedAccesses(
4377 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4378 const ValueToValueMap &Strides) {
4379 // Holds load/store instructions in program order.
4380 SmallVector<Instruction *, 16> AccessList;
4382 for (auto *BB : TheLoop->getBlocks()) {
4383 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4385 for (auto &I : *BB) {
4386 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4388 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4392 AccessList.push_back(&I);
4396 if (AccessList.empty())
4399 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4400 for (auto I : AccessList) {
4401 LoadInst *LI = dyn_cast<LoadInst>(I);
4402 StoreInst *SI = dyn_cast<StoreInst>(I);
4404 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4405 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4407 // The factor of the corresponding interleave group.
4408 unsigned Factor = std::abs(Stride);
4410 // Ignore the access if the factor is too small or too large.
4411 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4414 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4415 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4416 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4418 // An alignment of 0 means target ABI alignment.
4419 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4421 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4423 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4427 // Analyze interleaved accesses and collect them into interleave groups.
4429 // Notice that the vectorization on interleaved groups will change instruction
4430 // orders and may break dependences. But the memory dependence check guarantees
4431 // that there is no overlap between two pointers of different strides, element
4432 // sizes or underlying bases.
4434 // For pointers sharing the same stride, element size and underlying base, no
4435 // need to worry about Read-After-Write dependences and Write-After-Read
4438 // E.g. The RAW dependence: A[i] = a;
4440 // This won't exist as it is a store-load forwarding conflict, which has
4441 // already been checked and forbidden in the dependence check.
4443 // E.g. The WAR dependence: a = A[i]; // (1)
4445 // The store group of (2) is always inserted at or below (2), and the load group
4446 // of (1) is always inserted at or above (1). The dependence is safe.
4447 void InterleavedAccessInfo::analyzeInterleaving(
4448 const ValueToValueMap &Strides) {
4449 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4451 // Holds all the stride accesses.
4452 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4453 collectConstStridedAccesses(StrideAccesses, Strides);
4455 if (StrideAccesses.empty())
4458 // Holds all interleaved store groups temporarily.
4459 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4461 // Search the load-load/write-write pair B-A in bottom-up order and try to
4462 // insert B into the interleave group of A according to 3 rules:
4463 // 1. A and B have the same stride.
4464 // 2. A and B have the same memory object size.
4465 // 3. B belongs to the group according to the distance.
4467 // The bottom-up order can avoid breaking the Write-After-Write dependences
4468 // between two pointers of the same base.
4469 // E.g. A[i] = a; (1)
4472 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4473 // above (1), which guarantees that (1) is always above (2).
4474 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4476 Instruction *A = I->first;
4477 StrideDescriptor DesA = I->second;
4479 InterleaveGroup *Group = getInterleaveGroup(A);
4481 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4482 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4485 if (A->mayWriteToMemory())
4486 StoreGroups.insert(Group);
4488 for (auto II = std::next(I); II != E; ++II) {
4489 Instruction *B = II->first;
4490 StrideDescriptor DesB = II->second;
4492 // Ignore if B is already in a group or B is a different memory operation.
4493 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4496 // Check the rule 1 and 2.
4497 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4500 // Calculate the distance and prepare for the rule 3.
4501 const SCEVConstant *DistToA =
4502 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4506 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4508 // Skip if the distance is not multiple of size as they are not in the
4510 if (DistanceToA % static_cast<int>(DesA.Size))
4513 // The index of B is the index of A plus the related index to A.
4515 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4517 // Try to insert B into the group.
4518 if (Group->insertMember(B, IndexB, DesB.Align)) {
4519 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4520 << " into the interleave group with" << *A << '\n');
4521 InterleaveGroupMap[B] = Group;
4523 // Set the first load in program order as the insert position.
4524 if (B->mayReadFromMemory())
4525 Group->setInsertPos(B);
4527 } // Iteration on instruction B
4528 } // Iteration on instruction A
4530 // Remove interleaved store groups with gaps.
4531 for (InterleaveGroup *Group : StoreGroups)
4532 if (Group->getNumMembers() != Group->getFactor())
4533 releaseGroup(Group);
4536 LoopVectorizationCostModel::VectorizationFactor
4537 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4538 // Width 1 means no vectorize
4539 VectorizationFactor Factor = { 1U, 0U };
4540 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4541 emitAnalysis(VectorizationReport() <<
4542 "runtime pointer checks needed. Enable vectorization of this "
4543 "loop with '#pragma clang loop vectorize(enable)' when "
4544 "compiling with -Os/-Oz");
4546 "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4550 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4551 emitAnalysis(VectorizationReport() <<
4552 "store that is conditionally executed prevents vectorization");
4553 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4557 // Find the trip count.
4558 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4559 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4561 unsigned WidestType = getWidestType();
4562 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4563 unsigned MaxSafeDepDist = -1U;
4564 if (Legal->getMaxSafeDepDistBytes() != -1U)
4565 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4566 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4567 WidestRegister : MaxSafeDepDist);
4568 unsigned MaxVectorSize = WidestRegister / WidestType;
4569 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4570 DEBUG(dbgs() << "LV: The Widest register is: "
4571 << WidestRegister << " bits.\n");
4573 if (MaxVectorSize == 0) {
4574 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4578 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4579 " into one vector!");
4581 unsigned VF = MaxVectorSize;
4583 // If we optimize the program for size, avoid creating the tail loop.
4585 // If we are unable to calculate the trip count then don't try to vectorize.
4588 (VectorizationReport() <<
4589 "unable to calculate the loop count due to complex control flow");
4590 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4594 // Find the maximum SIMD width that can fit within the trip count.
4595 VF = TC % MaxVectorSize;
4600 // If the trip count that we found modulo the vectorization factor is not
4601 // zero then we require a tail.
4602 emitAnalysis(VectorizationReport() <<
4603 "cannot optimize for size and vectorize at the "
4604 "same time. Enable vectorization of this loop "
4605 "with '#pragma clang loop vectorize(enable)' "
4606 "when compiling with -Os/-Oz");
4607 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4612 int UserVF = Hints->getWidth();
4614 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4615 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4617 Factor.Width = UserVF;
4621 float Cost = expectedCost(1);
4623 const float ScalarCost = Cost;
4626 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4628 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4629 // Ignore scalar width, because the user explicitly wants vectorization.
4630 if (ForceVectorization && VF > 1) {
4632 Cost = expectedCost(Width) / (float)Width;
4635 for (unsigned i=2; i <= VF; i*=2) {
4636 // Notice that the vector loop needs to be executed less times, so
4637 // we need to divide the cost of the vector loops by the width of
4638 // the vector elements.
4639 float VectorCost = expectedCost(i) / (float)i;
4640 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4641 (int)VectorCost << ".\n");
4642 if (VectorCost < Cost) {
4648 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4649 << "LV: Vectorization seems to be not beneficial, "
4650 << "but was forced by a user.\n");
4651 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4652 Factor.Width = Width;
4653 Factor.Cost = Width * Cost;
4657 unsigned LoopVectorizationCostModel::getWidestType() {
4658 unsigned MaxWidth = 8;
4659 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4662 for (Loop::block_iterator bb = TheLoop->block_begin(),
4663 be = TheLoop->block_end(); bb != be; ++bb) {
4664 BasicBlock *BB = *bb;
4666 // For each instruction in the loop.
4667 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4668 Type *T = it->getType();
4670 // Skip ignored values.
4671 if (ValuesToIgnore.count(it))
4674 // Only examine Loads, Stores and PHINodes.
4675 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4678 // Examine PHI nodes that are reduction variables. Update the type to
4679 // account for the recurrence type.
4680 if (PHINode *PN = dyn_cast<PHINode>(it)) {
4681 if (!Legal->getReductionVars()->count(PN))
4683 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4684 T = RdxDesc.getRecurrenceType();
4687 // Examine the stored values.
4688 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4689 T = ST->getValueOperand()->getType();
4691 // Ignore loaded pointer types and stored pointer types that are not
4692 // consecutive. However, we do want to take consecutive stores/loads of
4693 // pointer vectors into account.
4694 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4697 MaxWidth = std::max(MaxWidth,
4698 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4705 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4707 unsigned LoopCost) {
4709 // -- The interleave heuristics --
4710 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4711 // There are many micro-architectural considerations that we can't predict
4712 // at this level. For example, frontend pressure (on decode or fetch) due to
4713 // code size, or the number and capabilities of the execution ports.
4715 // We use the following heuristics to select the interleave count:
4716 // 1. If the code has reductions, then we interleave to break the cross
4717 // iteration dependency.
4718 // 2. If the loop is really small, then we interleave to reduce the loop
4720 // 3. We don't interleave if we think that we will spill registers to memory
4721 // due to the increased register pressure.
4723 // When we optimize for size, we don't interleave.
4727 // We used the distance for the interleave count.
4728 if (Legal->getMaxSafeDepDistBytes() != -1U)
4731 // Do not interleave loops with a relatively small trip count.
4732 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4733 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4736 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4737 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4741 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4742 TargetNumRegisters = ForceTargetNumScalarRegs;
4744 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4745 TargetNumRegisters = ForceTargetNumVectorRegs;
4748 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4749 // We divide by these constants so assume that we have at least one
4750 // instruction that uses at least one register.
4751 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4752 R.NumInstructions = std::max(R.NumInstructions, 1U);
4754 // We calculate the interleave count using the following formula.
4755 // Subtract the number of loop invariants from the number of available
4756 // registers. These registers are used by all of the interleaved instances.
4757 // Next, divide the remaining registers by the number of registers that is
4758 // required by the loop, in order to estimate how many parallel instances
4759 // fit without causing spills. All of this is rounded down if necessary to be
4760 // a power of two. We want power of two interleave count to simplify any
4761 // addressing operations or alignment considerations.
4762 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4765 // Don't count the induction variable as interleaved.
4766 if (EnableIndVarRegisterHeur)
4767 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4768 std::max(1U, (R.MaxLocalUsers - 1)));
4770 // Clamp the interleave ranges to reasonable counts.
4771 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4773 // Check if the user has overridden the max.
4775 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4776 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4778 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4779 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4782 // If we did not calculate the cost for VF (because the user selected the VF)
4783 // then we calculate the cost of VF here.
4785 LoopCost = expectedCost(VF);
4787 // Clamp the calculated IC to be between the 1 and the max interleave count
4788 // that the target allows.
4789 if (IC > MaxInterleaveCount)
4790 IC = MaxInterleaveCount;
4794 // Interleave if we vectorized this loop and there is a reduction that could
4795 // benefit from interleaving.
4796 if (VF > 1 && Legal->getReductionVars()->size()) {
4797 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4801 // Note that if we've already vectorized the loop we will have done the
4802 // runtime check and so interleaving won't require further checks.
4803 bool InterleavingRequiresRuntimePointerCheck =
4804 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4806 // We want to interleave small loops in order to reduce the loop overhead and
4807 // potentially expose ILP opportunities.
4808 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4809 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4810 // We assume that the cost overhead is 1 and we use the cost model
4811 // to estimate the cost of the loop and interleave until the cost of the
4812 // loop overhead is about 5% of the cost of the loop.
4814 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4816 // Interleave until store/load ports (estimated by max interleave count) are
4818 unsigned NumStores = Legal->getNumStores();
4819 unsigned NumLoads = Legal->getNumLoads();
4820 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4821 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4823 // If we have a scalar reduction (vector reductions are already dealt with
4824 // by this point), we can increase the critical path length if the loop
4825 // we're interleaving is inside another loop. Limit, by default to 2, so the
4826 // critical path only gets increased by one reduction operation.
4827 if (Legal->getReductionVars()->size() &&
4828 TheLoop->getLoopDepth() > 1) {
4829 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4830 SmallIC = std::min(SmallIC, F);
4831 StoresIC = std::min(StoresIC, F);
4832 LoadsIC = std::min(LoadsIC, F);
4835 if (EnableLoadStoreRuntimeInterleave &&
4836 std::max(StoresIC, LoadsIC) > SmallIC) {
4837 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4838 return std::max(StoresIC, LoadsIC);
4841 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4845 // Interleave if this is a large loop (small loops are already dealt with by
4847 // point) that could benefit from interleaving.
4848 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4849 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4850 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4854 DEBUG(dbgs() << "LV: Not Interleaving.\n");
4858 LoopVectorizationCostModel::RegisterUsage
4859 LoopVectorizationCostModel::calculateRegisterUsage() {
4860 // This function calculates the register usage by measuring the highest number
4861 // of values that are alive at a single location. Obviously, this is a very
4862 // rough estimation. We scan the loop in a topological order in order and
4863 // assign a number to each instruction. We use RPO to ensure that defs are
4864 // met before their users. We assume that each instruction that has in-loop
4865 // users starts an interval. We record every time that an in-loop value is
4866 // used, so we have a list of the first and last occurrences of each
4867 // instruction. Next, we transpose this data structure into a multi map that
4868 // holds the list of intervals that *end* at a specific location. This multi
4869 // map allows us to perform a linear search. We scan the instructions linearly
4870 // and record each time that a new interval starts, by placing it in a set.
4871 // If we find this value in the multi-map then we remove it from the set.
4872 // The max register usage is the maximum size of the set.
4873 // We also search for instructions that are defined outside the loop, but are
4874 // used inside the loop. We need this number separately from the max-interval
4875 // usage number because when we unroll, loop-invariant values do not take
4877 LoopBlocksDFS DFS(TheLoop);
4881 R.NumInstructions = 0;
4883 // Each 'key' in the map opens a new interval. The values
4884 // of the map are the index of the 'last seen' usage of the
4885 // instruction that is the key.
4886 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4887 // Maps instruction to its index.
4888 DenseMap<unsigned, Instruction*> IdxToInstr;
4889 // Marks the end of each interval.
4890 IntervalMap EndPoint;
4891 // Saves the list of instruction indices that are used in the loop.
4892 SmallSet<Instruction*, 8> Ends;
4893 // Saves the list of values that are used in the loop but are
4894 // defined outside the loop, such as arguments and constants.
4895 SmallPtrSet<Value*, 8> LoopInvariants;
4898 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4899 be = DFS.endRPO(); bb != be; ++bb) {
4900 R.NumInstructions += (*bb)->size();
4901 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4903 Instruction *I = it;
4904 IdxToInstr[Index++] = I;
4906 // Save the end location of each USE.
4907 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4908 Value *U = I->getOperand(i);
4909 Instruction *Instr = dyn_cast<Instruction>(U);
4911 // Ignore non-instruction values such as arguments, constants, etc.
4912 if (!Instr) continue;
4914 // If this instruction is outside the loop then record it and continue.
4915 if (!TheLoop->contains(Instr)) {
4916 LoopInvariants.insert(Instr);
4920 // Overwrite previous end points.
4921 EndPoint[Instr] = Index;
4927 // Saves the list of intervals that end with the index in 'key'.
4928 typedef SmallVector<Instruction*, 2> InstrList;
4929 DenseMap<unsigned, InstrList> TransposeEnds;
4931 // Transpose the EndPoints to a list of values that end at each index.
4932 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4934 TransposeEnds[it->second].push_back(it->first);
4936 SmallSet<Instruction*, 8> OpenIntervals;
4937 unsigned MaxUsage = 0;
4940 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4941 for (unsigned int i = 0; i < Index; ++i) {
4942 Instruction *I = IdxToInstr[i];
4943 // Ignore instructions that are never used within the loop.
4944 if (!Ends.count(I)) continue;
4946 // Skip ignored values.
4947 if (ValuesToIgnore.count(I))
4950 // Remove all of the instructions that end at this location.
4951 InstrList &List = TransposeEnds[i];
4952 for (unsigned int j=0, e = List.size(); j < e; ++j)
4953 OpenIntervals.erase(List[j]);
4955 // Count the number of live interals.
4956 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4958 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4959 OpenIntervals.size() << '\n');
4961 // Add the current instruction to the list of open intervals.
4962 OpenIntervals.insert(I);
4965 unsigned Invariant = LoopInvariants.size();
4966 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4967 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4968 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4970 R.LoopInvariantRegs = Invariant;
4971 R.MaxLocalUsers = MaxUsage;
4975 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4979 for (Loop::block_iterator bb = TheLoop->block_begin(),
4980 be = TheLoop->block_end(); bb != be; ++bb) {
4981 unsigned BlockCost = 0;
4982 BasicBlock *BB = *bb;
4984 // For each instruction in the old loop.
4985 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4986 // Skip dbg intrinsics.
4987 if (isa<DbgInfoIntrinsic>(it))
4990 // Skip ignored values.
4991 if (ValuesToIgnore.count(it))
4994 unsigned C = getInstructionCost(it, VF);
4996 // Check if we should override the cost.
4997 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4998 C = ForceTargetInstructionCost;
5001 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5002 VF << " For instruction: " << *it << '\n');
5005 // We assume that if-converted blocks have a 50% chance of being executed.
5006 // When the code is scalar then some of the blocks are avoided due to CF.
5007 // When the code is vectorized we execute all code paths.
5008 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5017 /// \brief Check whether the address computation for a non-consecutive memory
5018 /// access looks like an unlikely candidate for being merged into the indexing
5021 /// We look for a GEP which has one index that is an induction variable and all
5022 /// other indices are loop invariant. If the stride of this access is also
5023 /// within a small bound we decide that this address computation can likely be
5024 /// merged into the addressing mode.
5025 /// In all other cases, we identify the address computation as complex.
5026 static bool isLikelyComplexAddressComputation(Value *Ptr,
5027 LoopVectorizationLegality *Legal,
5028 ScalarEvolution *SE,
5029 const Loop *TheLoop) {
5030 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5034 // We are looking for a gep with all loop invariant indices except for one
5035 // which should be an induction variable.
5036 unsigned NumOperands = Gep->getNumOperands();
5037 for (unsigned i = 1; i < NumOperands; ++i) {
5038 Value *Opd = Gep->getOperand(i);
5039 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5040 !Legal->isInductionVariable(Opd))
5044 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5045 // can likely be merged into the address computation.
5046 unsigned MaxMergeDistance = 64;
5048 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5052 // Check the step is constant.
5053 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5054 // Calculate the pointer stride and check if it is consecutive.
5055 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5059 const APInt &APStepVal = C->getValue()->getValue();
5061 // Huge step value - give up.
5062 if (APStepVal.getBitWidth() > 64)
5065 int64_t StepVal = APStepVal.getSExtValue();
5067 return StepVal > MaxMergeDistance;
5070 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5071 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5077 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5078 // If we know that this instruction will remain uniform, check the cost of
5079 // the scalar version.
5080 if (Legal->isUniformAfterVectorization(I))
5083 Type *RetTy = I->getType();
5084 Type *VectorTy = ToVectorTy(RetTy, VF);
5086 // TODO: We need to estimate the cost of intrinsic calls.
5087 switch (I->getOpcode()) {
5088 case Instruction::GetElementPtr:
5089 // We mark this instruction as zero-cost because the cost of GEPs in
5090 // vectorized code depends on whether the corresponding memory instruction
5091 // is scalarized or not. Therefore, we handle GEPs with the memory
5092 // instruction cost.
5094 case Instruction::Br: {
5095 return TTI.getCFInstrCost(I->getOpcode());
5097 case Instruction::PHI:
5098 //TODO: IF-converted IFs become selects.
5100 case Instruction::Add:
5101 case Instruction::FAdd:
5102 case Instruction::Sub:
5103 case Instruction::FSub:
5104 case Instruction::Mul:
5105 case Instruction::FMul:
5106 case Instruction::UDiv:
5107 case Instruction::SDiv:
5108 case Instruction::FDiv:
5109 case Instruction::URem:
5110 case Instruction::SRem:
5111 case Instruction::FRem:
5112 case Instruction::Shl:
5113 case Instruction::LShr:
5114 case Instruction::AShr:
5115 case Instruction::And:
5116 case Instruction::Or:
5117 case Instruction::Xor: {
5118 // Since we will replace the stride by 1 the multiplication should go away.
5119 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5121 // Certain instructions can be cheaper to vectorize if they have a constant
5122 // second vector operand. One example of this are shifts on x86.
5123 TargetTransformInfo::OperandValueKind Op1VK =
5124 TargetTransformInfo::OK_AnyValue;
5125 TargetTransformInfo::OperandValueKind Op2VK =
5126 TargetTransformInfo::OK_AnyValue;
5127 TargetTransformInfo::OperandValueProperties Op1VP =
5128 TargetTransformInfo::OP_None;
5129 TargetTransformInfo::OperandValueProperties Op2VP =
5130 TargetTransformInfo::OP_None;
5131 Value *Op2 = I->getOperand(1);
5133 // Check for a splat of a constant or for a non uniform vector of constants.
5134 if (isa<ConstantInt>(Op2)) {
5135 ConstantInt *CInt = cast<ConstantInt>(Op2);
5136 if (CInt && CInt->getValue().isPowerOf2())
5137 Op2VP = TargetTransformInfo::OP_PowerOf2;
5138 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5139 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5140 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5141 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5143 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5144 if (CInt && CInt->getValue().isPowerOf2())
5145 Op2VP = TargetTransformInfo::OP_PowerOf2;
5146 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5150 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5153 case Instruction::Select: {
5154 SelectInst *SI = cast<SelectInst>(I);
5155 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5156 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5157 Type *CondTy = SI->getCondition()->getType();
5159 CondTy = VectorType::get(CondTy, VF);
5161 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5163 case Instruction::ICmp:
5164 case Instruction::FCmp: {
5165 Type *ValTy = I->getOperand(0)->getType();
5166 VectorTy = ToVectorTy(ValTy, VF);
5167 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5169 case Instruction::Store:
5170 case Instruction::Load: {
5171 StoreInst *SI = dyn_cast<StoreInst>(I);
5172 LoadInst *LI = dyn_cast<LoadInst>(I);
5173 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5175 VectorTy = ToVectorTy(ValTy, VF);
5177 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5178 unsigned AS = SI ? SI->getPointerAddressSpace() :
5179 LI->getPointerAddressSpace();
5180 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5181 // We add the cost of address computation here instead of with the gep
5182 // instruction because only here we know whether the operation is
5185 return TTI.getAddressComputationCost(VectorTy) +
5186 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5188 // For an interleaved access, calculate the total cost of the whole
5189 // interleave group.
5190 if (Legal->isAccessInterleaved(I)) {
5191 auto Group = Legal->getInterleavedAccessGroup(I);
5192 assert(Group && "Fail to get an interleaved access group.");
5194 // Only calculate the cost once at the insert position.
5195 if (Group->getInsertPos() != I)
5198 unsigned InterleaveFactor = Group->getFactor();
5200 VectorType::get(VectorTy->getVectorElementType(),
5201 VectorTy->getVectorNumElements() * InterleaveFactor);
5203 // Holds the indices of existing members in an interleaved load group.
5204 // An interleaved store group doesn't need this as it dones't allow gaps.
5205 SmallVector<unsigned, 4> Indices;
5207 for (unsigned i = 0; i < InterleaveFactor; i++)
5208 if (Group->getMember(i))
5209 Indices.push_back(i);
5212 // Calculate the cost of the whole interleaved group.
5213 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5214 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5215 Group->getAlignment(), AS);
5217 if (Group->isReverse())
5219 Group->getNumMembers() *
5220 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5222 // FIXME: The interleaved load group with a huge gap could be even more
5223 // expensive than scalar operations. Then we could ignore such group and
5224 // use scalar operations instead.
5228 // Scalarized loads/stores.
5229 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5230 bool Reverse = ConsecutiveStride < 0;
5231 const DataLayout &DL = I->getModule()->getDataLayout();
5232 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5233 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5234 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5235 bool IsComplexComputation =
5236 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5238 // The cost of extracting from the value vector and pointer vector.
5239 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5240 for (unsigned i = 0; i < VF; ++i) {
5241 // The cost of extracting the pointer operand.
5242 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5243 // In case of STORE, the cost of ExtractElement from the vector.
5244 // In case of LOAD, the cost of InsertElement into the returned
5246 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5247 Instruction::InsertElement,
5251 // The cost of the scalar loads/stores.
5252 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5253 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5258 // Wide load/stores.
5259 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5260 if (Legal->isMaskRequired(I))
5261 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5264 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5267 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5271 case Instruction::ZExt:
5272 case Instruction::SExt:
5273 case Instruction::FPToUI:
5274 case Instruction::FPToSI:
5275 case Instruction::FPExt:
5276 case Instruction::PtrToInt:
5277 case Instruction::IntToPtr:
5278 case Instruction::SIToFP:
5279 case Instruction::UIToFP:
5280 case Instruction::Trunc:
5281 case Instruction::FPTrunc:
5282 case Instruction::BitCast: {
5283 // We optimize the truncation of induction variable.
5284 // The cost of these is the same as the scalar operation.
5285 if (I->getOpcode() == Instruction::Trunc &&
5286 Legal->isInductionVariable(I->getOperand(0)))
5287 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5288 I->getOperand(0)->getType());
5290 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5291 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5293 case Instruction::Call: {
5294 bool NeedToScalarize;
5295 CallInst *CI = cast<CallInst>(I);
5296 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5297 if (getIntrinsicIDForCall(CI, TLI))
5298 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5302 // We are scalarizing the instruction. Return the cost of the scalar
5303 // instruction, plus the cost of insert and extract into vector
5304 // elements, times the vector width.
5307 if (!RetTy->isVoidTy() && VF != 1) {
5308 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5310 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5313 // The cost of inserting the results plus extracting each one of the
5315 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5318 // The cost of executing VF copies of the scalar instruction. This opcode
5319 // is unknown. Assume that it is the same as 'mul'.
5320 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5326 char LoopVectorize::ID = 0;
5327 static const char lv_name[] = "Loop Vectorization";
5328 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5329 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5330 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5331 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5332 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5333 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5334 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5335 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5336 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5337 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5338 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5339 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5342 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5343 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5347 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5348 // Check for a store.
5349 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5350 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5352 // Check for a load.
5353 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5354 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5360 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5361 bool IfPredicateStore) {
5362 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5363 // Holds vector parameters or scalars, in case of uniform vals.
5364 SmallVector<VectorParts, 4> Params;
5366 setDebugLocFromInst(Builder, Instr);
5368 // Find all of the vectorized parameters.
5369 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5370 Value *SrcOp = Instr->getOperand(op);
5372 // If we are accessing the old induction variable, use the new one.
5373 if (SrcOp == OldInduction) {
5374 Params.push_back(getVectorValue(SrcOp));
5378 // Try using previously calculated values.
5379 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5381 // If the src is an instruction that appeared earlier in the basic block
5382 // then it should already be vectorized.
5383 if (SrcInst && OrigLoop->contains(SrcInst)) {
5384 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5385 // The parameter is a vector value from earlier.
5386 Params.push_back(WidenMap.get(SrcInst));
5388 // The parameter is a scalar from outside the loop. Maybe even a constant.
5389 VectorParts Scalars;
5390 Scalars.append(UF, SrcOp);
5391 Params.push_back(Scalars);
5395 assert(Params.size() == Instr->getNumOperands() &&
5396 "Invalid number of operands");
5398 // Does this instruction return a value ?
5399 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5401 Value *UndefVec = IsVoidRetTy ? nullptr :
5402 UndefValue::get(Instr->getType());
5403 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5404 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5407 if (IfPredicateStore) {
5408 assert(Instr->getParent()->getSinglePredecessor() &&
5409 "Only support single predecessor blocks");
5410 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5411 Instr->getParent());
5414 // For each vector unroll 'part':
5415 for (unsigned Part = 0; Part < UF; ++Part) {
5416 // For each scalar that we create:
5418 // Start an "if (pred) a[i] = ..." block.
5419 Value *Cmp = nullptr;
5420 if (IfPredicateStore) {
5421 if (Cond[Part]->getType()->isVectorTy())
5423 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5424 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5425 ConstantInt::get(Cond[Part]->getType(), 1));
5428 Instruction *Cloned = Instr->clone();
5430 Cloned->setName(Instr->getName() + ".cloned");
5431 // Replace the operands of the cloned instructions with extracted scalars.
5432 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5433 Value *Op = Params[op][Part];
5434 Cloned->setOperand(op, Op);
5437 // Place the cloned scalar in the new loop.
5438 Builder.Insert(Cloned);
5440 // If the original scalar returns a value we need to place it in a vector
5441 // so that future users will be able to use it.
5443 VecResults[Part] = Cloned;
5446 if (IfPredicateStore)
5447 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
5452 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5453 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5454 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5456 return scalarizeInstruction(Instr, IfPredicateStore);
5459 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5463 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5467 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5468 // When unrolling and the VF is 1, we only need to add a simple scalar.
5469 Type *ITy = Val->getType();
5470 assert(!ITy->isVectorTy() && "Val must be a scalar");
5471 Constant *C = ConstantInt::get(ITy, StartIdx);
5472 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");