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."));
219 // Forward declarations.
220 class LoopVectorizationLegality;
221 class LoopVectorizationCostModel;
222 class LoopVectorizeHints;
224 /// \brief This modifies LoopAccessReport to initialize message with
225 /// loop-vectorizer-specific part.
226 class VectorizationReport : public LoopAccessReport {
228 VectorizationReport(Instruction *I = nullptr)
229 : LoopAccessReport("loop not vectorized: ", I) {}
231 /// \brief This allows promotion of the loop-access analysis report into the
232 /// loop-vectorizer report. It modifies the message to add the
233 /// loop-vectorizer-specific part of the message.
234 explicit VectorizationReport(const LoopAccessReport &R)
235 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
239 /// A helper function for converting Scalar types to vector types.
240 /// If the incoming type is void, we return void. If the VF is 1, we return
242 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
243 if (Scalar->isVoidTy() || VF == 1)
245 return VectorType::get(Scalar, VF);
248 /// InnerLoopVectorizer vectorizes loops which contain only one basic
249 /// block to a specified vectorization factor (VF).
250 /// This class performs the widening of scalars into vectors, or multiple
251 /// scalars. This class also implements the following features:
252 /// * It inserts an epilogue loop for handling loops that don't have iteration
253 /// counts that are known to be a multiple of the vectorization factor.
254 /// * It handles the code generation for reduction variables.
255 /// * Scalarization (implementation using scalars) of un-vectorizable
257 /// InnerLoopVectorizer does not perform any vectorization-legality
258 /// checks, and relies on the caller to check for the different legality
259 /// aspects. The InnerLoopVectorizer relies on the
260 /// LoopVectorizationLegality class to provide information about the induction
261 /// and reduction variables that were found to a given vectorization factor.
262 class InnerLoopVectorizer {
264 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
265 DominatorTree *DT, const TargetLibraryInfo *TLI,
266 const TargetTransformInfo *TTI, unsigned VecWidth,
267 unsigned UnrollFactor)
268 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
269 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
270 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
271 Legal(nullptr), AddedSafetyChecks(false) {}
273 // Perform the actual loop widening (vectorization).
274 void vectorize(LoopVectorizationLegality *L) {
276 // Create a new empty loop. Unlink the old loop and connect the new one.
278 // Widen each instruction in the old loop to a new one in the new loop.
279 // Use the Legality module to find the induction and reduction variables.
281 // Register the new loop and update the analysis passes.
285 // Return true if any runtime check is added.
286 bool IsSafetyChecksAdded() {
287 return AddedSafetyChecks;
290 virtual ~InnerLoopVectorizer() {}
293 /// A small list of PHINodes.
294 typedef SmallVector<PHINode*, 4> PhiVector;
295 /// When we unroll loops we have multiple vector values for each scalar.
296 /// This data structure holds the unrolled and vectorized values that
297 /// originated from one scalar instruction.
298 typedef SmallVector<Value*, 2> VectorParts;
300 // When we if-convert we need to create edge masks. We have to cache values
301 // so that we don't end up with exponential recursion/IR.
302 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
303 VectorParts> EdgeMaskCache;
305 /// \brief Add checks for strides that were assumed to be 1.
307 /// Returns the last check instruction and the first check instruction in the
308 /// pair as (first, last).
309 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
311 /// Create an empty loop, based on the loop ranges of the old loop.
312 void createEmptyLoop();
313 /// Copy and widen the instructions from the old loop.
314 virtual void vectorizeLoop();
316 /// \brief The Loop exit block may have single value PHI nodes where the
317 /// incoming value is 'Undef'. While vectorizing we only handled real values
318 /// that were defined inside the loop. Here we fix the 'undef case'.
322 /// A helper function that computes the predicate of the block BB, assuming
323 /// that the header block of the loop is set to True. It returns the *entry*
324 /// mask for the block BB.
325 VectorParts createBlockInMask(BasicBlock *BB);
326 /// A helper function that computes the predicate of the edge between SRC
328 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
330 /// A helper function to vectorize a single BB within the innermost loop.
331 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
333 /// Vectorize a single PHINode in a block. This method handles the induction
334 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
335 /// arbitrary length vectors.
336 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
337 unsigned UF, unsigned VF, PhiVector *PV);
339 /// Insert the new loop to the loop hierarchy and pass manager
340 /// and update the analysis passes.
341 void updateAnalysis();
343 /// This instruction is un-vectorizable. Implement it as a sequence
344 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
345 /// scalarized instruction behind an if block predicated on the control
346 /// dependence of the instruction.
347 virtual void scalarizeInstruction(Instruction *Instr,
348 bool IfPredicateStore=false);
350 /// Vectorize Load and Store instructions,
351 virtual void vectorizeMemoryInstruction(Instruction *Instr);
353 /// Create a broadcast instruction. This method generates a broadcast
354 /// instruction (shuffle) for loop invariant values and for the induction
355 /// value. If this is the induction variable then we extend it to N, N+1, ...
356 /// this is needed because each iteration in the loop corresponds to a SIMD
358 virtual Value *getBroadcastInstrs(Value *V);
360 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
361 /// to each vector element of Val. The sequence starts at StartIndex.
362 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
364 /// When we go over instructions in the basic block we rely on previous
365 /// values within the current basic block or on loop invariant values.
366 /// When we widen (vectorize) values we place them in the map. If the values
367 /// are not within the map, they have to be loop invariant, so we simply
368 /// broadcast them into a vector.
369 VectorParts &getVectorValue(Value *V);
371 /// Try to vectorize the interleaved access group that \p Instr belongs to.
372 void vectorizeInterleaveGroup(Instruction *Instr);
374 /// Generate a shuffle sequence that will reverse the vector Vec.
375 virtual Value *reverseVector(Value *Vec);
377 /// This is a helper class that holds the vectorizer state. It maps scalar
378 /// instructions to vector instructions. When the code is 'unrolled' then
379 /// then a single scalar value is mapped to multiple vector parts. The parts
380 /// are stored in the VectorPart type.
382 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
384 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
386 /// \return True if 'Key' is saved in the Value Map.
387 bool has(Value *Key) const { return MapStorage.count(Key); }
389 /// Initializes a new entry in the map. Sets all of the vector parts to the
390 /// save value in 'Val'.
391 /// \return A reference to a vector with splat values.
392 VectorParts &splat(Value *Key, Value *Val) {
393 VectorParts &Entry = MapStorage[Key];
394 Entry.assign(UF, Val);
398 ///\return A reference to the value that is stored at 'Key'.
399 VectorParts &get(Value *Key) {
400 VectorParts &Entry = MapStorage[Key];
403 assert(Entry.size() == UF);
408 /// The unroll factor. Each entry in the map stores this number of vector
412 /// Map storage. We use std::map and not DenseMap because insertions to a
413 /// dense map invalidates its iterators.
414 std::map<Value *, VectorParts> MapStorage;
417 /// The original loop.
419 /// Scev analysis to use.
427 /// Target Library Info.
428 const TargetLibraryInfo *TLI;
429 /// Target Transform Info.
430 const TargetTransformInfo *TTI;
432 /// The vectorization SIMD factor to use. Each vector will have this many
437 /// The vectorization unroll factor to use. Each scalar is vectorized to this
438 /// many different vector instructions.
441 /// The builder that we use
444 // --- Vectorization state ---
446 /// The vector-loop preheader.
447 BasicBlock *LoopVectorPreHeader;
448 /// The scalar-loop preheader.
449 BasicBlock *LoopScalarPreHeader;
450 /// Middle Block between the vector and the scalar.
451 BasicBlock *LoopMiddleBlock;
452 ///The ExitBlock of the scalar loop.
453 BasicBlock *LoopExitBlock;
454 ///The vector loop body.
455 SmallVector<BasicBlock *, 4> LoopVectorBody;
456 ///The scalar loop body.
457 BasicBlock *LoopScalarBody;
458 /// A list of all bypass blocks. The first block is the entry of the loop.
459 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
461 /// The new Induction variable which was added to the new block.
463 /// The induction variable of the old basic block.
464 PHINode *OldInduction;
465 /// Holds the extended (to the widest induction type) start index.
467 /// Maps scalars to widened vectors.
469 EdgeMaskCache MaskCache;
471 LoopVectorizationLegality *Legal;
473 // Record whether runtime check is added.
474 bool AddedSafetyChecks;
477 class InnerLoopUnroller : public InnerLoopVectorizer {
479 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
480 DominatorTree *DT, const TargetLibraryInfo *TLI,
481 const TargetTransformInfo *TTI, unsigned UnrollFactor)
482 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
485 void scalarizeInstruction(Instruction *Instr,
486 bool IfPredicateStore = false) override;
487 void vectorizeMemoryInstruction(Instruction *Instr) override;
488 Value *getBroadcastInstrs(Value *V) override;
489 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
490 Value *reverseVector(Value *Vec) override;
493 /// \brief Look for a meaningful debug location on the instruction or it's
495 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
500 if (I->getDebugLoc() != Empty)
503 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
504 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
505 if (OpInst->getDebugLoc() != Empty)
512 /// \brief Set the debug location in the builder using the debug location in the
514 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
515 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
516 B.SetCurrentDebugLocation(Inst->getDebugLoc());
518 B.SetCurrentDebugLocation(DebugLoc());
522 /// \return string containing a file name and a line # for the given loop.
523 static std::string getDebugLocString(const Loop *L) {
526 raw_string_ostream OS(Result);
527 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
528 LoopDbgLoc.print(OS);
530 // Just print the module name.
531 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
538 /// \brief Propagate known metadata from one instruction to another.
539 static void propagateMetadata(Instruction *To, const Instruction *From) {
540 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
541 From->getAllMetadataOtherThanDebugLoc(Metadata);
543 for (auto M : Metadata) {
544 unsigned Kind = M.first;
546 // These are safe to transfer (this is safe for TBAA, even when we
547 // if-convert, because should that metadata have had a control dependency
548 // on the condition, and thus actually aliased with some other
549 // non-speculated memory access when the condition was false, this would be
550 // caught by the runtime overlap checks).
551 if (Kind != LLVMContext::MD_tbaa &&
552 Kind != LLVMContext::MD_alias_scope &&
553 Kind != LLVMContext::MD_noalias &&
554 Kind != LLVMContext::MD_fpmath)
557 To->setMetadata(Kind, M.second);
561 /// \brief Propagate known metadata from one instruction to a vector of others.
562 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
564 if (Instruction *I = dyn_cast<Instruction>(V))
565 propagateMetadata(I, From);
568 /// \brief The group of interleaved loads/stores sharing the same stride and
569 /// close to each other.
571 /// Each member in this group has an index starting from 0, and the largest
572 /// index should be less than interleaved factor, which is equal to the absolute
573 /// value of the access's stride.
575 /// E.g. An interleaved load group of factor 4:
576 /// for (unsigned i = 0; i < 1024; i+=4) {
577 /// a = A[i]; // Member of index 0
578 /// b = A[i+1]; // Member of index 1
579 /// d = A[i+3]; // Member of index 3
583 /// An interleaved store group of factor 4:
584 /// for (unsigned i = 0; i < 1024; i+=4) {
586 /// A[i] = a; // Member of index 0
587 /// A[i+1] = b; // Member of index 1
588 /// A[i+2] = c; // Member of index 2
589 /// A[i+3] = d; // Member of index 3
592 /// Note: the interleaved load group could have gaps (missing members), but
593 /// the interleaved store group doesn't allow gaps.
594 class InterleaveGroup {
596 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
597 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
598 assert(Align && "The alignment should be non-zero");
600 Factor = std::abs(Stride);
601 assert(Factor > 1 && "Invalid interleave factor");
603 Reverse = Stride < 0;
607 bool isReverse() const { return Reverse; }
608 unsigned getFactor() const { return Factor; }
609 unsigned getAlignment() const { return Align; }
610 unsigned getNumMembers() const { return Members.size(); }
612 /// \brief Try to insert a new member \p Instr with index \p Index and
613 /// alignment \p NewAlign. The index is related to the leader and it could be
614 /// negative if it is the new leader.
616 /// \returns false if the instruction doesn't belong to the group.
617 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
618 assert(NewAlign && "The new member's alignment should be non-zero");
620 int Key = Index + SmallestKey;
622 // Skip if there is already a member with the same index.
623 if (Members.count(Key))
626 if (Key > LargestKey) {
627 // The largest index is always less than the interleave factor.
628 if (Index >= static_cast<int>(Factor))
632 } else if (Key < SmallestKey) {
633 // The largest index is always less than the interleave factor.
634 if (LargestKey - Key >= static_cast<int>(Factor))
640 // It's always safe to select the minimum alignment.
641 Align = std::min(Align, NewAlign);
642 Members[Key] = Instr;
646 /// \brief Get the member with the given index \p Index
648 /// \returns nullptr if contains no such member.
649 Instruction *getMember(unsigned Index) const {
650 int Key = SmallestKey + Index;
651 if (!Members.count(Key))
654 return Members.find(Key)->second;
657 /// \brief Get the index for the given member. Unlike the key in the member
658 /// map, the index starts from 0.
659 unsigned getIndex(Instruction *Instr) const {
660 for (auto I : Members)
661 if (I.second == Instr)
662 return I.first - SmallestKey;
664 llvm_unreachable("InterleaveGroup contains no such member");
667 Instruction *getInsertPos() const { return InsertPos; }
668 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
671 unsigned Factor; // Interleave Factor.
674 DenseMap<int, Instruction *> Members;
678 // To avoid breaking dependences, vectorized instructions of an interleave
679 // group should be inserted at either the first load or the last store in
682 // E.g. %even = load i32 // Insert Position
683 // %add = add i32 %even // Use of %even
687 // %odd = add i32 // Def of %odd
688 // store i32 %odd // Insert Position
689 Instruction *InsertPos;
692 /// \brief Drive the analysis of interleaved memory accesses in the loop.
694 /// Use this class to analyze interleaved accesses only when we can vectorize
695 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
696 /// on interleaved accesses is unsafe.
698 /// The analysis collects interleave groups and records the relationships
699 /// between the member and the group in a map.
700 class InterleavedAccessInfo {
702 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
703 : SE(SE), TheLoop(L), DT(DT) {}
705 ~InterleavedAccessInfo() {
706 SmallSet<InterleaveGroup *, 4> DelSet;
707 // Avoid releasing a pointer twice.
708 for (auto &I : InterleaveGroupMap)
709 DelSet.insert(I.second);
710 for (auto *Ptr : DelSet)
714 /// \brief Analyze the interleaved accesses and collect them in interleave
715 /// groups. Substitute symbolic strides using \p Strides.
716 void analyzeInterleaving(const ValueToValueMap &Strides);
718 /// \brief Check if \p Instr belongs to any interleave group.
719 bool isInterleaved(Instruction *Instr) const {
720 return InterleaveGroupMap.count(Instr);
723 /// \brief Get the interleave group that \p Instr belongs to.
725 /// \returns nullptr if doesn't have such group.
726 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
727 if (InterleaveGroupMap.count(Instr))
728 return InterleaveGroupMap.find(Instr)->second;
737 /// Holds the relationships between the members and the interleave group.
738 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
740 /// \brief The descriptor for a strided memory access.
741 struct StrideDescriptor {
742 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
744 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
746 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
748 int Stride; // The access's stride. It is negative for a reverse access.
749 const SCEV *Scev; // The scalar expression of this access
750 unsigned Size; // The size of the memory object.
751 unsigned Align; // The alignment of this access.
754 /// \brief Create a new interleave group with the given instruction \p Instr,
755 /// stride \p Stride and alignment \p Align.
757 /// \returns the newly created interleave group.
758 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
760 assert(!InterleaveGroupMap.count(Instr) &&
761 "Already in an interleaved access group");
762 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
763 return InterleaveGroupMap[Instr];
766 /// \brief Release the group and remove all the relationships.
767 void releaseGroup(InterleaveGroup *Group) {
768 for (unsigned i = 0; i < Group->getFactor(); i++)
769 if (Instruction *Member = Group->getMember(i))
770 InterleaveGroupMap.erase(Member);
775 /// \brief Collect all the accesses with a constant stride in program order.
776 void collectConstStridedAccesses(
777 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
778 const ValueToValueMap &Strides);
781 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
782 /// to what vectorization factor.
783 /// This class does not look at the profitability of vectorization, only the
784 /// legality. This class has two main kinds of checks:
785 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
786 /// will change the order of memory accesses in a way that will change the
787 /// correctness of the program.
788 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
789 /// checks for a number of different conditions, such as the availability of a
790 /// single induction variable, that all types are supported and vectorize-able,
791 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
792 /// This class is also used by InnerLoopVectorizer for identifying
793 /// induction variable and the different reduction variables.
794 class LoopVectorizationLegality {
796 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
797 TargetLibraryInfo *TLI, AliasAnalysis *AA,
798 Function *F, const TargetTransformInfo *TTI,
799 LoopAccessAnalysis *LAA)
800 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
801 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
802 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false) {}
804 /// This enum represents the kinds of inductions that we support.
806 IK_NoInduction, ///< Not an induction variable.
807 IK_IntInduction, ///< Integer induction variable. Step = C.
808 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
811 /// A struct for saving information about induction variables.
812 struct InductionInfo {
813 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
814 : StartValue(Start), IK(K), StepValue(Step) {
815 assert(IK != IK_NoInduction && "Not an induction");
816 assert(StartValue && "StartValue is null");
817 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
818 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
819 "StartValue is not a pointer for pointer induction");
820 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
821 "StartValue is not an integer for integer induction");
822 assert(StepValue->getType()->isIntegerTy() &&
823 "StepValue is not an integer");
826 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
828 /// Get the consecutive direction. Returns:
829 /// 0 - unknown or non-consecutive.
830 /// 1 - consecutive and increasing.
831 /// -1 - consecutive and decreasing.
832 int getConsecutiveDirection() const {
833 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
834 return StepValue->getSExtValue();
838 /// Compute the transformed value of Index at offset StartValue using step
840 /// For integer induction, returns StartValue + Index * StepValue.
841 /// For pointer induction, returns StartValue[Index * StepValue].
842 /// FIXME: The newly created binary instructions should contain nsw/nuw
843 /// flags, which can be found from the original scalar operations.
844 Value *transform(IRBuilder<> &B, Value *Index) const {
846 case IK_IntInduction:
847 assert(Index->getType() == StartValue->getType() &&
848 "Index type does not match StartValue type");
849 if (StepValue->isMinusOne())
850 return B.CreateSub(StartValue, Index);
851 if (!StepValue->isOne())
852 Index = B.CreateMul(Index, StepValue);
853 return B.CreateAdd(StartValue, Index);
855 case IK_PtrInduction:
856 assert(Index->getType() == StepValue->getType() &&
857 "Index type does not match StepValue type");
858 if (StepValue->isMinusOne())
859 Index = B.CreateNeg(Index);
860 else if (!StepValue->isOne())
861 Index = B.CreateMul(Index, StepValue);
862 return B.CreateGEP(nullptr, StartValue, Index);
867 llvm_unreachable("invalid enum");
871 TrackingVH<Value> StartValue;
875 ConstantInt *StepValue;
878 /// ReductionList contains the reduction descriptors for all
879 /// of the reductions that were found in the loop.
880 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
882 /// InductionList saves induction variables and maps them to the
883 /// induction descriptor.
884 typedef MapVector<PHINode*, InductionInfo> InductionList;
886 /// Returns true if it is legal to vectorize this loop.
887 /// This does not mean that it is profitable to vectorize this
888 /// loop, only that it is legal to do so.
891 /// Returns the Induction variable.
892 PHINode *getInduction() { return Induction; }
894 /// Returns the reduction variables found in the loop.
895 ReductionList *getReductionVars() { return &Reductions; }
897 /// Returns the induction variables found in the loop.
898 InductionList *getInductionVars() { return &Inductions; }
900 /// Returns the widest induction type.
901 Type *getWidestInductionType() { return WidestIndTy; }
903 /// Returns True if V is an induction variable in this loop.
904 bool isInductionVariable(const Value *V);
906 /// Return true if the block BB needs to be predicated in order for the loop
907 /// to be vectorized.
908 bool blockNeedsPredication(BasicBlock *BB);
910 /// Check if this pointer is consecutive when vectorizing. This happens
911 /// when the last index of the GEP is the induction variable, or that the
912 /// pointer itself is an induction variable.
913 /// This check allows us to vectorize A[idx] into a wide load/store.
915 /// 0 - Stride is unknown or non-consecutive.
916 /// 1 - Address is consecutive.
917 /// -1 - Address is consecutive, and decreasing.
918 int isConsecutivePtr(Value *Ptr);
920 /// Returns true if the value V is uniform within the loop.
921 bool isUniform(Value *V);
923 /// Returns true if this instruction will remain scalar after vectorization.
924 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
926 /// Returns the information that we collected about runtime memory check.
927 const RuntimePointerChecking *getRuntimePointerChecking() const {
928 return LAI->getRuntimePointerChecking();
931 const LoopAccessInfo *getLAI() const {
935 /// \brief Check if \p Instr belongs to any interleaved access group.
936 bool isAccessInterleaved(Instruction *Instr) {
937 return InterleaveInfo.isInterleaved(Instr);
940 /// \brief Get the interleaved access group that \p Instr belongs to.
941 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
942 return InterleaveInfo.getInterleaveGroup(Instr);
945 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
947 bool hasStride(Value *V) { return StrideSet.count(V); }
948 bool mustCheckStrides() { return !StrideSet.empty(); }
949 SmallPtrSet<Value *, 8>::iterator strides_begin() {
950 return StrideSet.begin();
952 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
954 /// Returns true if the target machine supports masked store operation
955 /// for the given \p DataType and kind of access to \p Ptr.
956 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
957 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
959 /// Returns true if the target machine supports masked load operation
960 /// for the given \p DataType and kind of access to \p Ptr.
961 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
962 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
964 /// Returns true if vector representation of the instruction \p I
966 bool isMaskRequired(const Instruction* I) {
967 return (MaskedOp.count(I) != 0);
969 unsigned getNumStores() const {
970 return LAI->getNumStores();
972 unsigned getNumLoads() const {
973 return LAI->getNumLoads();
975 unsigned getNumPredStores() const {
976 return NumPredStores;
979 /// Check if a single basic block loop is vectorizable.
980 /// At this point we know that this is a loop with a constant trip count
981 /// and we only need to check individual instructions.
982 bool canVectorizeInstrs();
984 /// When we vectorize loops we may change the order in which
985 /// we read and write from memory. This method checks if it is
986 /// legal to vectorize the code, considering only memory constrains.
987 /// Returns true if the loop is vectorizable
988 bool canVectorizeMemory();
990 /// Return true if we can vectorize this loop using the IF-conversion
992 bool canVectorizeWithIfConvert();
994 /// Collect the variables that need to stay uniform after vectorization.
995 void collectLoopUniforms();
997 /// Return true if all of the instructions in the block can be speculatively
998 /// executed. \p SafePtrs is a list of addresses that are known to be legal
999 /// and we know that we can read from them without segfault.
1000 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1002 /// Returns the induction kind of Phi and record the step. This function may
1003 /// return NoInduction if the PHI is not an induction variable.
1004 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
1006 /// \brief Collect memory access with loop invariant strides.
1008 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1010 void collectStridedAccess(Value *LoadOrStoreInst);
1012 /// Report an analysis message to assist the user in diagnosing loops that are
1013 /// not vectorized. These are handled as LoopAccessReport rather than
1014 /// VectorizationReport because the << operator of VectorizationReport returns
1015 /// LoopAccessReport.
1016 void emitAnalysis(const LoopAccessReport &Message) {
1017 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1020 unsigned NumPredStores;
1022 /// The loop that we evaluate.
1025 ScalarEvolution *SE;
1026 /// Target Library Info.
1027 TargetLibraryInfo *TLI;
1029 Function *TheFunction;
1030 /// Target Transform Info
1031 const TargetTransformInfo *TTI;
1034 // LoopAccess analysis.
1035 LoopAccessAnalysis *LAA;
1036 // And the loop-accesses info corresponding to this loop. This pointer is
1037 // null until canVectorizeMemory sets it up.
1038 const LoopAccessInfo *LAI;
1040 /// The interleave access information contains groups of interleaved accesses
1041 /// with the same stride and close to each other.
1042 InterleavedAccessInfo InterleaveInfo;
1044 // --- vectorization state --- //
1046 /// Holds the integer induction variable. This is the counter of the
1049 /// Holds the reduction variables.
1050 ReductionList Reductions;
1051 /// Holds all of the induction variables that we found in the loop.
1052 /// Notice that inductions don't need to start at zero and that induction
1053 /// variables can be pointers.
1054 InductionList Inductions;
1055 /// Holds the widest induction type encountered.
1058 /// Allowed outside users. This holds the reduction
1059 /// vars which can be accessed from outside the loop.
1060 SmallPtrSet<Value*, 4> AllowedExit;
1061 /// This set holds the variables which are known to be uniform after
1063 SmallPtrSet<Instruction*, 4> Uniforms;
1065 /// Can we assume the absence of NaNs.
1066 bool HasFunNoNaNAttr;
1068 ValueToValueMap Strides;
1069 SmallPtrSet<Value *, 8> StrideSet;
1071 /// While vectorizing these instructions we have to generate a
1072 /// call to the appropriate masked intrinsic
1073 SmallPtrSet<const Instruction*, 8> MaskedOp;
1076 /// LoopVectorizationCostModel - estimates the expected speedups due to
1078 /// In many cases vectorization is not profitable. This can happen because of
1079 /// a number of reasons. In this class we mainly attempt to predict the
1080 /// expected speedup/slowdowns due to the supported instruction set. We use the
1081 /// TargetTransformInfo to query the different backends for the cost of
1082 /// different operations.
1083 class LoopVectorizationCostModel {
1085 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1086 LoopVectorizationLegality *Legal,
1087 const TargetTransformInfo &TTI,
1088 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1089 const Function *F, const LoopVectorizeHints *Hints)
1090 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1091 TheFunction(F), Hints(Hints) {
1092 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
1095 /// Information about vectorization costs
1096 struct VectorizationFactor {
1097 unsigned Width; // Vector width with best cost
1098 unsigned Cost; // Cost of the loop with that width
1100 /// \return The most profitable vectorization factor and the cost of that VF.
1101 /// This method checks every power of two up to VF. If UserVF is not ZERO
1102 /// then this vectorization factor will be selected if vectorization is
1104 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1106 /// \return The size (in bits) of the widest type in the code that
1107 /// needs to be vectorized. We ignore values that remain scalar such as
1108 /// 64 bit loop indices.
1109 unsigned getWidestType();
1111 /// \return The desired interleave count.
1112 /// If interleave count has been specified by metadata it will be returned.
1113 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1114 /// are the selected vectorization factor and the cost of the selected VF.
1115 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1118 /// \return The most profitable unroll factor.
1119 /// This method finds the best unroll-factor based on register pressure and
1120 /// other parameters. VF and LoopCost are the selected vectorization factor
1121 /// and the cost of the selected VF.
1122 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1125 /// \brief A struct that represents some properties of the register usage
1127 struct RegisterUsage {
1128 /// Holds the number of loop invariant values that are used in the loop.
1129 unsigned LoopInvariantRegs;
1130 /// Holds the maximum number of concurrent live intervals in the loop.
1131 unsigned MaxLocalUsers;
1132 /// Holds the number of instructions in the loop.
1133 unsigned NumInstructions;
1136 /// \return information about the register usage of the loop.
1137 RegisterUsage calculateRegisterUsage();
1140 /// Returns the expected execution cost. The unit of the cost does
1141 /// not matter because we use the 'cost' units to compare different
1142 /// vector widths. The cost that is returned is *not* normalized by
1143 /// the factor width.
1144 unsigned expectedCost(unsigned VF);
1146 /// Returns the execution time cost of an instruction for a given vector
1147 /// width. Vector width of one means scalar.
1148 unsigned getInstructionCost(Instruction *I, unsigned VF);
1150 /// Returns whether the instruction is a load or store and will be a emitted
1151 /// as a vector operation.
1152 bool isConsecutiveLoadOrStore(Instruction *I);
1154 /// Report an analysis message to assist the user in diagnosing loops that are
1155 /// not vectorized. These are handled as LoopAccessReport rather than
1156 /// VectorizationReport because the << operator of VectorizationReport returns
1157 /// LoopAccessReport.
1158 void emitAnalysis(const LoopAccessReport &Message) {
1159 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1162 /// Values used only by @llvm.assume calls.
1163 SmallPtrSet<const Value *, 32> EphValues;
1165 /// The loop that we evaluate.
1168 ScalarEvolution *SE;
1169 /// Loop Info analysis.
1171 /// Vectorization legality.
1172 LoopVectorizationLegality *Legal;
1173 /// Vector target information.
1174 const TargetTransformInfo &TTI;
1175 /// Target Library Info.
1176 const TargetLibraryInfo *TLI;
1177 const Function *TheFunction;
1178 // Loop Vectorize Hint.
1179 const LoopVectorizeHints *Hints;
1182 /// Utility class for getting and setting loop vectorizer hints in the form
1183 /// of loop metadata.
1184 /// This class keeps a number of loop annotations locally (as member variables)
1185 /// and can, upon request, write them back as metadata on the loop. It will
1186 /// initially scan the loop for existing metadata, and will update the local
1187 /// values based on information in the loop.
1188 /// We cannot write all values to metadata, as the mere presence of some info,
1189 /// for example 'force', means a decision has been made. So, we need to be
1190 /// careful NOT to add them if the user hasn't specifically asked so.
1191 class LoopVectorizeHints {
1198 /// Hint - associates name and validation with the hint value.
1201 unsigned Value; // This may have to change for non-numeric values.
1204 Hint(const char * Name, unsigned Value, HintKind Kind)
1205 : Name(Name), Value(Value), Kind(Kind) { }
1207 bool validate(unsigned Val) {
1210 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1212 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1220 /// Vectorization width.
1222 /// Vectorization interleave factor.
1224 /// Vectorization forced
1227 /// Return the loop metadata prefix.
1228 static StringRef Prefix() { return "llvm.loop."; }
1232 FK_Undefined = -1, ///< Not selected.
1233 FK_Disabled = 0, ///< Forcing disabled.
1234 FK_Enabled = 1, ///< Forcing enabled.
1237 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1238 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1240 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1241 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1243 // Populate values with existing loop metadata.
1244 getHintsFromMetadata();
1246 // force-vector-interleave overrides DisableInterleaving.
1247 if (VectorizerParams::isInterleaveForced())
1248 Interleave.Value = VectorizerParams::VectorizationInterleave;
1250 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1251 << "LV: Interleaving disabled by the pass manager\n");
1254 /// Mark the loop L as already vectorized by setting the width to 1.
1255 void setAlreadyVectorized() {
1256 Width.Value = Interleave.Value = 1;
1257 Hint Hints[] = {Width, Interleave};
1258 writeHintsToMetadata(Hints);
1261 /// Dumps all the hint information.
1262 std::string emitRemark() const {
1263 VectorizationReport R;
1264 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1265 R << "vectorization is explicitly disabled";
1267 R << "use -Rpass-analysis=loop-vectorize for more info";
1268 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1269 R << " (Force=true";
1270 if (Width.Value != 0)
1271 R << ", Vector Width=" << Width.Value;
1272 if (Interleave.Value != 0)
1273 R << ", Interleave Count=" << Interleave.Value;
1281 unsigned getWidth() const { return Width.Value; }
1282 unsigned getInterleave() const { return Interleave.Value; }
1283 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1286 /// Find hints specified in the loop metadata and update local values.
1287 void getHintsFromMetadata() {
1288 MDNode *LoopID = TheLoop->getLoopID();
1292 // First operand should refer to the loop id itself.
1293 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1294 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1296 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1297 const MDString *S = nullptr;
1298 SmallVector<Metadata *, 4> Args;
1300 // The expected hint is either a MDString or a MDNode with the first
1301 // operand a MDString.
1302 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1303 if (!MD || MD->getNumOperands() == 0)
1305 S = dyn_cast<MDString>(MD->getOperand(0));
1306 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1307 Args.push_back(MD->getOperand(i));
1309 S = dyn_cast<MDString>(LoopID->getOperand(i));
1310 assert(Args.size() == 0 && "too many arguments for MDString");
1316 // Check if the hint starts with the loop metadata prefix.
1317 StringRef Name = S->getString();
1318 if (Args.size() == 1)
1319 setHint(Name, Args[0]);
1323 /// Checks string hint with one operand and set value if valid.
1324 void setHint(StringRef Name, Metadata *Arg) {
1325 if (!Name.startswith(Prefix()))
1327 Name = Name.substr(Prefix().size(), StringRef::npos);
1329 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1331 unsigned Val = C->getZExtValue();
1333 Hint *Hints[] = {&Width, &Interleave, &Force};
1334 for (auto H : Hints) {
1335 if (Name == H->Name) {
1336 if (H->validate(Val))
1339 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1345 /// Create a new hint from name / value pair.
1346 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1347 LLVMContext &Context = TheLoop->getHeader()->getContext();
1348 Metadata *MDs[] = {MDString::get(Context, Name),
1349 ConstantAsMetadata::get(
1350 ConstantInt::get(Type::getInt32Ty(Context), V))};
1351 return MDNode::get(Context, MDs);
1354 /// Matches metadata with hint name.
1355 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1356 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1360 for (auto H : HintTypes)
1361 if (Name->getString().endswith(H.Name))
1366 /// Sets current hints into loop metadata, keeping other values intact.
1367 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1368 if (HintTypes.size() == 0)
1371 // Reserve the first element to LoopID (see below).
1372 SmallVector<Metadata *, 4> MDs(1);
1373 // If the loop already has metadata, then ignore the existing operands.
1374 MDNode *LoopID = TheLoop->getLoopID();
1376 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1377 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1378 // If node in update list, ignore old value.
1379 if (!matchesHintMetadataName(Node, HintTypes))
1380 MDs.push_back(Node);
1384 // Now, add the missing hints.
1385 for (auto H : HintTypes)
1386 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1388 // Replace current metadata node with new one.
1389 LLVMContext &Context = TheLoop->getHeader()->getContext();
1390 MDNode *NewLoopID = MDNode::get(Context, MDs);
1391 // Set operand 0 to refer to the loop id itself.
1392 NewLoopID->replaceOperandWith(0, NewLoopID);
1394 TheLoop->setLoopID(NewLoopID);
1397 /// The loop these hints belong to.
1398 const Loop *TheLoop;
1401 static void emitMissedWarning(Function *F, Loop *L,
1402 const LoopVectorizeHints &LH) {
1403 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1404 L->getStartLoc(), LH.emitRemark());
1406 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1407 if (LH.getWidth() != 1)
1408 emitLoopVectorizeWarning(
1409 F->getContext(), *F, L->getStartLoc(),
1410 "failed explicitly specified loop vectorization");
1411 else if (LH.getInterleave() != 1)
1412 emitLoopInterleaveWarning(
1413 F->getContext(), *F, L->getStartLoc(),
1414 "failed explicitly specified loop interleaving");
1418 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1420 return V.push_back(&L);
1422 for (Loop *InnerL : L)
1423 addInnerLoop(*InnerL, V);
1426 /// The LoopVectorize Pass.
1427 struct LoopVectorize : public FunctionPass {
1428 /// Pass identification, replacement for typeid
1431 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1433 DisableUnrolling(NoUnrolling),
1434 AlwaysVectorize(AlwaysVectorize) {
1435 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1438 ScalarEvolution *SE;
1440 TargetTransformInfo *TTI;
1442 BlockFrequencyInfo *BFI;
1443 TargetLibraryInfo *TLI;
1445 AssumptionCache *AC;
1446 LoopAccessAnalysis *LAA;
1447 bool DisableUnrolling;
1448 bool AlwaysVectorize;
1450 BlockFrequency ColdEntryFreq;
1452 bool runOnFunction(Function &F) override {
1453 SE = &getAnalysis<ScalarEvolution>();
1454 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1455 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1456 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1457 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1458 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1459 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1460 AA = &getAnalysis<AliasAnalysis>();
1461 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1462 LAA = &getAnalysis<LoopAccessAnalysis>();
1464 // Compute some weights outside of the loop over the loops. Compute this
1465 // using a BranchProbability to re-use its scaling math.
1466 const BranchProbability ColdProb(1, 5); // 20%
1467 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1470 // 1. the target claims to have no vector registers, and
1471 // 2. interleaving won't help ILP.
1473 // The second condition is necessary because, even if the target has no
1474 // vector registers, loop vectorization may still enable scalar
1476 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1479 // Build up a worklist of inner-loops to vectorize. This is necessary as
1480 // the act of vectorizing or partially unrolling a loop creates new loops
1481 // and can invalidate iterators across the loops.
1482 SmallVector<Loop *, 8> Worklist;
1485 addInnerLoop(*L, Worklist);
1487 LoopsAnalyzed += Worklist.size();
1489 // Now walk the identified inner loops.
1490 bool Changed = false;
1491 while (!Worklist.empty())
1492 Changed |= processLoop(Worklist.pop_back_val());
1494 // Process each loop nest in the function.
1498 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1499 SmallVector<Metadata *, 4> MDs;
1500 // Reserve first location for self reference to the LoopID metadata node.
1501 MDs.push_back(nullptr);
1502 bool IsUnrollMetadata = false;
1503 MDNode *LoopID = L->getLoopID();
1505 // First find existing loop unrolling disable metadata.
1506 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1507 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1509 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1511 S && S->getString().startswith("llvm.loop.unroll.disable");
1513 MDs.push_back(LoopID->getOperand(i));
1517 if (!IsUnrollMetadata) {
1518 // Add runtime unroll disable metadata.
1519 LLVMContext &Context = L->getHeader()->getContext();
1520 SmallVector<Metadata *, 1> DisableOperands;
1521 DisableOperands.push_back(
1522 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1523 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1524 MDs.push_back(DisableNode);
1525 MDNode *NewLoopID = MDNode::get(Context, MDs);
1526 // Set operand 0 to refer to the loop id itself.
1527 NewLoopID->replaceOperandWith(0, NewLoopID);
1528 L->setLoopID(NewLoopID);
1532 bool processLoop(Loop *L) {
1533 assert(L->empty() && "Only process inner loops.");
1536 const std::string DebugLocStr = getDebugLocString(L);
1539 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1540 << L->getHeader()->getParent()->getName() << "\" from "
1541 << DebugLocStr << "\n");
1543 LoopVectorizeHints Hints(L, DisableUnrolling);
1545 DEBUG(dbgs() << "LV: Loop hints:"
1547 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1549 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1551 : "?")) << " width=" << Hints.getWidth()
1552 << " unroll=" << Hints.getInterleave() << "\n");
1554 // Function containing loop
1555 Function *F = L->getHeader()->getParent();
1557 // Looking at the diagnostic output is the only way to determine if a loop
1558 // was vectorized (other than looking at the IR or machine code), so it
1559 // is important to generate an optimization remark for each loop. Most of
1560 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1561 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1562 // less verbose reporting vectorized loops and unvectorized loops that may
1563 // benefit from vectorization, respectively.
1565 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1566 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1567 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1568 L->getStartLoc(), Hints.emitRemark());
1572 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1573 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1574 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1575 L->getStartLoc(), Hints.emitRemark());
1579 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1580 // FIXME: Add a separate metadata to indicate when the loop has already
1581 // been vectorized instead of setting width and count to 1.
1582 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1583 // FIXME: Add interleave.disable metadata. This will allow
1584 // vectorize.disable to be used without disabling the pass and errors
1585 // to differentiate between disabled vectorization and a width of 1.
1586 emitOptimizationRemarkAnalysis(
1587 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1588 "loop not vectorized: vectorization and interleaving are explicitly "
1589 "disabled, or vectorize width and interleave count are both set to "
1594 // Check the loop for a trip count threshold:
1595 // do not vectorize loops with a tiny trip count.
1596 const unsigned TC = SE->getSmallConstantTripCount(L);
1597 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1598 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1599 << "This loop is not worth vectorizing.");
1600 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1601 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1603 DEBUG(dbgs() << "\n");
1604 emitOptimizationRemarkAnalysis(
1605 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1606 "vectorization is not beneficial and is not explicitly forced");
1611 // Check if it is legal to vectorize the loop.
1612 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA);
1613 if (!LVL.canVectorize()) {
1614 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1615 emitMissedWarning(F, L, Hints);
1619 // Use the cost model.
1620 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints);
1622 // Check the function attributes to find out if this function should be
1623 // optimized for size.
1624 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1625 // FIXME: Use Function::optForSize().
1626 F->hasFnAttribute(Attribute::OptimizeForSize);
1628 // Compute the weighted frequency of this loop being executed and see if it
1629 // is less than 20% of the function entry baseline frequency. Note that we
1630 // always have a canonical loop here because we think we *can* vectoriez.
1631 // FIXME: This is hidden behind a flag due to pervasive problems with
1632 // exactly what block frequency models.
1633 if (LoopVectorizeWithBlockFrequency) {
1634 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1635 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1636 LoopEntryFreq < ColdEntryFreq)
1640 // Check the function attributes to see if implicit floats are allowed.a
1641 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1642 // an integer loop and the vector instructions selected are purely integer
1643 // vector instructions?
1644 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1645 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1646 "attribute is used.\n");
1647 emitOptimizationRemarkAnalysis(
1648 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1649 "loop not vectorized due to NoImplicitFloat attribute");
1650 emitMissedWarning(F, L, Hints);
1654 // Select the optimal vectorization factor.
1655 const LoopVectorizationCostModel::VectorizationFactor VF =
1656 CM.selectVectorizationFactor(OptForSize);
1658 // Select the interleave count.
1659 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1661 // Get user interleave count.
1662 unsigned UserIC = Hints.getInterleave();
1664 // Identify the diagnostic messages that should be produced.
1665 std::string VecDiagMsg, IntDiagMsg;
1666 bool VectorizeLoop = true, InterleaveLoop = true;
1668 if (VF.Width == 1) {
1669 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1671 "the cost-model indicates that vectorization is not beneficial";
1672 VectorizeLoop = false;
1675 if (IC == 1 && UserIC <= 1) {
1676 // Tell the user interleaving is not beneficial.
1677 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1679 "the cost-model indicates that interleaving is not beneficial";
1680 InterleaveLoop = false;
1683 " and is explicitly disabled or interleave count is set to 1";
1684 } else if (IC > 1 && UserIC == 1) {
1685 // Tell the user interleaving is beneficial, but it explicitly disabled.
1687 << "LV: Interleaving is beneficial but is explicitly disabled.");
1688 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1689 "but is explicitly disabled or interleave count is set to 1";
1690 InterleaveLoop = false;
1693 // Override IC if user provided an interleave count.
1694 IC = UserIC > 0 ? UserIC : IC;
1696 // Emit diagnostic messages, if any.
1697 if (!VectorizeLoop && !InterleaveLoop) {
1698 // Do not vectorize or interleaving the loop.
1699 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1700 L->getStartLoc(), VecDiagMsg);
1701 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1702 L->getStartLoc(), IntDiagMsg);
1704 } else if (!VectorizeLoop && InterleaveLoop) {
1705 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1706 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1707 L->getStartLoc(), VecDiagMsg);
1708 } else if (VectorizeLoop && !InterleaveLoop) {
1709 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1710 << DebugLocStr << '\n');
1711 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1712 L->getStartLoc(), IntDiagMsg);
1713 } else if (VectorizeLoop && InterleaveLoop) {
1714 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1715 << DebugLocStr << '\n');
1716 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1719 if (!VectorizeLoop) {
1720 assert(IC > 1 && "interleave count should not be 1 or 0");
1721 // If we decided that it is not legal to vectorize the loop then
1723 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC);
1724 Unroller.vectorize(&LVL);
1726 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1727 Twine("interleaved loop (interleaved count: ") +
1730 // If we decided that it is *legal* to vectorize the loop then do it.
1731 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC);
1735 // Add metadata to disable runtime unrolling scalar loop when there's no
1736 // runtime check about strides and memory. Because at this situation,
1737 // scalar loop is rarely used not worthy to be unrolled.
1738 if (!LB.IsSafetyChecksAdded())
1739 AddRuntimeUnrollDisableMetaData(L);
1741 // Report the vectorization decision.
1742 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1743 Twine("vectorized loop (vectorization width: ") +
1744 Twine(VF.Width) + ", interleaved count: " +
1748 // Mark the loop as already vectorized to avoid vectorizing again.
1749 Hints.setAlreadyVectorized();
1751 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1755 void getAnalysisUsage(AnalysisUsage &AU) const override {
1756 AU.addRequired<AssumptionCacheTracker>();
1757 AU.addRequiredID(LoopSimplifyID);
1758 AU.addRequiredID(LCSSAID);
1759 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1760 AU.addRequired<DominatorTreeWrapperPass>();
1761 AU.addRequired<LoopInfoWrapperPass>();
1762 AU.addRequired<ScalarEvolution>();
1763 AU.addRequired<TargetTransformInfoWrapperPass>();
1764 AU.addRequired<AliasAnalysis>();
1765 AU.addRequired<LoopAccessAnalysis>();
1766 AU.addPreserved<LoopInfoWrapperPass>();
1767 AU.addPreserved<DominatorTreeWrapperPass>();
1768 AU.addPreserved<AliasAnalysis>();
1773 } // end anonymous namespace
1775 //===----------------------------------------------------------------------===//
1776 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1777 // LoopVectorizationCostModel.
1778 //===----------------------------------------------------------------------===//
1780 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1781 // We need to place the broadcast of invariant variables outside the loop.
1782 Instruction *Instr = dyn_cast<Instruction>(V);
1784 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1785 Instr->getParent()) != LoopVectorBody.end());
1786 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1788 // Place the code for broadcasting invariant variables in the new preheader.
1789 IRBuilder<>::InsertPointGuard Guard(Builder);
1791 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1793 // Broadcast the scalar into all locations in the vector.
1794 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1799 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1801 assert(Val->getType()->isVectorTy() && "Must be a vector");
1802 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1803 "Elem must be an integer");
1804 assert(Step->getType() == Val->getType()->getScalarType() &&
1805 "Step has wrong type");
1806 // Create the types.
1807 Type *ITy = Val->getType()->getScalarType();
1808 VectorType *Ty = cast<VectorType>(Val->getType());
1809 int VLen = Ty->getNumElements();
1810 SmallVector<Constant*, 8> Indices;
1812 // Create a vector of consecutive numbers from zero to VF.
1813 for (int i = 0; i < VLen; ++i)
1814 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1816 // Add the consecutive indices to the vector value.
1817 Constant *Cv = ConstantVector::get(Indices);
1818 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1819 Step = Builder.CreateVectorSplat(VLen, Step);
1820 assert(Step->getType() == Val->getType() && "Invalid step vec");
1821 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1822 // which can be found from the original scalar operations.
1823 Step = Builder.CreateMul(Cv, Step);
1824 return Builder.CreateAdd(Val, Step, "induction");
1827 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1828 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1829 // Make sure that the pointer does not point to structs.
1830 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1833 // If this value is a pointer induction variable we know it is consecutive.
1834 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1835 if (Phi && Inductions.count(Phi)) {
1836 InductionInfo II = Inductions[Phi];
1837 return II.getConsecutiveDirection();
1840 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1844 unsigned NumOperands = Gep->getNumOperands();
1845 Value *GpPtr = Gep->getPointerOperand();
1846 // If this GEP value is a consecutive pointer induction variable and all of
1847 // the indices are constant then we know it is consecutive. We can
1848 Phi = dyn_cast<PHINode>(GpPtr);
1849 if (Phi && Inductions.count(Phi)) {
1851 // Make sure that the pointer does not point to structs.
1852 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1853 if (GepPtrType->getElementType()->isAggregateType())
1856 // Make sure that all of the index operands are loop invariant.
1857 for (unsigned i = 1; i < NumOperands; ++i)
1858 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1861 InductionInfo II = Inductions[Phi];
1862 return II.getConsecutiveDirection();
1865 unsigned InductionOperand = getGEPInductionOperand(Gep);
1867 // Check that all of the gep indices are uniform except for our induction
1869 for (unsigned i = 0; i != NumOperands; ++i)
1870 if (i != InductionOperand &&
1871 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1874 // We can emit wide load/stores only if the last non-zero index is the
1875 // induction variable.
1876 const SCEV *Last = nullptr;
1877 if (!Strides.count(Gep))
1878 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1880 // Because of the multiplication by a stride we can have a s/zext cast.
1881 // We are going to replace this stride by 1 so the cast is safe to ignore.
1883 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1884 // %0 = trunc i64 %indvars.iv to i32
1885 // %mul = mul i32 %0, %Stride1
1886 // %idxprom = zext i32 %mul to i64 << Safe cast.
1887 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1889 Last = replaceSymbolicStrideSCEV(SE, Strides,
1890 Gep->getOperand(InductionOperand), Gep);
1891 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1893 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1897 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1898 const SCEV *Step = AR->getStepRecurrence(*SE);
1900 // The memory is consecutive because the last index is consecutive
1901 // and all other indices are loop invariant.
1904 if (Step->isAllOnesValue())
1911 bool LoopVectorizationLegality::isUniform(Value *V) {
1912 return LAI->isUniform(V);
1915 InnerLoopVectorizer::VectorParts&
1916 InnerLoopVectorizer::getVectorValue(Value *V) {
1917 assert(V != Induction && "The new induction variable should not be used.");
1918 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1920 // If we have a stride that is replaced by one, do it here.
1921 if (Legal->hasStride(V))
1922 V = ConstantInt::get(V->getType(), 1);
1924 // If we have this scalar in the map, return it.
1925 if (WidenMap.has(V))
1926 return WidenMap.get(V);
1928 // If this scalar is unknown, assume that it is a constant or that it is
1929 // loop invariant. Broadcast V and save the value for future uses.
1930 Value *B = getBroadcastInstrs(V);
1931 return WidenMap.splat(V, B);
1934 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1935 assert(Vec->getType()->isVectorTy() && "Invalid type");
1936 SmallVector<Constant*, 8> ShuffleMask;
1937 for (unsigned i = 0; i < VF; ++i)
1938 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1940 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1941 ConstantVector::get(ShuffleMask),
1945 // Get a mask to interleave \p NumVec vectors into a wide vector.
1946 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
1947 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
1948 // <0, 4, 1, 5, 2, 6, 3, 7>
1949 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
1951 SmallVector<Constant *, 16> Mask;
1952 for (unsigned i = 0; i < VF; i++)
1953 for (unsigned j = 0; j < NumVec; j++)
1954 Mask.push_back(Builder.getInt32(j * VF + i));
1956 return ConstantVector::get(Mask);
1959 // Get the strided mask starting from index \p Start.
1960 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
1961 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
1962 unsigned Stride, unsigned VF) {
1963 SmallVector<Constant *, 16> Mask;
1964 for (unsigned i = 0; i < VF; i++)
1965 Mask.push_back(Builder.getInt32(Start + i * Stride));
1967 return ConstantVector::get(Mask);
1970 // Get a mask of two parts: The first part consists of sequential integers
1971 // starting from 0, The second part consists of UNDEFs.
1972 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
1973 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
1974 unsigned NumUndef) {
1975 SmallVector<Constant *, 16> Mask;
1976 for (unsigned i = 0; i < NumInt; i++)
1977 Mask.push_back(Builder.getInt32(i));
1979 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
1980 for (unsigned i = 0; i < NumUndef; i++)
1981 Mask.push_back(Undef);
1983 return ConstantVector::get(Mask);
1986 // Concatenate two vectors with the same element type. The 2nd vector should
1987 // not have more elements than the 1st vector. If the 2nd vector has less
1988 // elements, extend it with UNDEFs.
1989 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
1991 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
1992 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
1993 assert(VecTy1 && VecTy2 &&
1994 VecTy1->getScalarType() == VecTy2->getScalarType() &&
1995 "Expect two vectors with the same element type");
1997 unsigned NumElts1 = VecTy1->getNumElements();
1998 unsigned NumElts2 = VecTy2->getNumElements();
1999 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2001 if (NumElts1 > NumElts2) {
2002 // Extend with UNDEFs.
2004 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2005 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2008 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2009 return Builder.CreateShuffleVector(V1, V2, Mask);
2012 // Concatenate vectors in the given list. All vectors have the same type.
2013 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2014 ArrayRef<Value *> InputList) {
2015 unsigned NumVec = InputList.size();
2016 assert(NumVec > 1 && "Should be at least two vectors");
2018 SmallVector<Value *, 8> ResList;
2019 ResList.append(InputList.begin(), InputList.end());
2021 SmallVector<Value *, 8> TmpList;
2022 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2023 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2024 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2025 "Only the last vector may have a different type");
2027 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2030 // Push the last vector if the total number of vectors is odd.
2031 if (NumVec % 2 != 0)
2032 TmpList.push_back(ResList[NumVec - 1]);
2035 NumVec = ResList.size();
2036 } while (NumVec > 1);
2041 // Try to vectorize the interleave group that \p Instr belongs to.
2043 // E.g. Translate following interleaved load group (factor = 3):
2044 // for (i = 0; i < N; i+=3) {
2045 // R = Pic[i]; // Member of index 0
2046 // G = Pic[i+1]; // Member of index 1
2047 // B = Pic[i+2]; // Member of index 2
2048 // ... // do something to R, G, B
2051 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2052 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2053 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2054 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2056 // Or translate following interleaved store group (factor = 3):
2057 // for (i = 0; i < N; i+=3) {
2058 // ... do something to R, G, B
2059 // Pic[i] = R; // Member of index 0
2060 // Pic[i+1] = G; // Member of index 1
2061 // Pic[i+2] = B; // Member of index 2
2064 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2065 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2066 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2067 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2068 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2069 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2070 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2071 assert(Group && "Fail to get an interleaved access group.");
2073 // Skip if current instruction is not the insert position.
2074 if (Instr != Group->getInsertPos())
2077 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2078 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2079 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2081 // Prepare for the vector type of the interleaved load/store.
2082 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2083 unsigned InterleaveFactor = Group->getFactor();
2084 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2085 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2087 // Prepare for the new pointers.
2088 setDebugLocFromInst(Builder, Ptr);
2089 VectorParts &PtrParts = getVectorValue(Ptr);
2090 SmallVector<Value *, 2> NewPtrs;
2091 unsigned Index = Group->getIndex(Instr);
2092 for (unsigned Part = 0; Part < UF; Part++) {
2093 // Extract the pointer for current instruction from the pointer vector. A
2094 // reverse access uses the pointer in the last lane.
2095 Value *NewPtr = Builder.CreateExtractElement(
2097 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2099 // Notice current instruction could be any index. Need to adjust the address
2100 // to the member of index 0.
2102 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2103 // b = A[i]; // Member of index 0
2104 // Current pointer is pointed to A[i+1], adjust it to A[i].
2106 // E.g. A[i+1] = a; // Member of index 1
2107 // A[i] = b; // Member of index 0
2108 // A[i+2] = c; // Member of index 2 (Current instruction)
2109 // Current pointer is pointed to A[i+2], adjust it to A[i].
2110 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2112 // Cast to the vector pointer type.
2113 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2116 setDebugLocFromInst(Builder, Instr);
2117 Value *UndefVec = UndefValue::get(VecTy);
2119 // Vectorize the interleaved load group.
2121 for (unsigned Part = 0; Part < UF; Part++) {
2122 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2123 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2125 for (unsigned i = 0; i < InterleaveFactor; i++) {
2126 Instruction *Member = Group->getMember(i);
2128 // Skip the gaps in the group.
2132 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2133 Value *StridedVec = Builder.CreateShuffleVector(
2134 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2136 // If this member has different type, cast the result type.
2137 if (Member->getType() != ScalarTy) {
2138 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2139 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2142 VectorParts &Entry = WidenMap.get(Member);
2144 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2147 propagateMetadata(NewLoadInstr, Instr);
2152 // The sub vector type for current instruction.
2153 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2155 // Vectorize the interleaved store group.
2156 for (unsigned Part = 0; Part < UF; Part++) {
2157 // Collect the stored vector from each member.
2158 SmallVector<Value *, 4> StoredVecs;
2159 for (unsigned i = 0; i < InterleaveFactor; i++) {
2160 // Interleaved store group doesn't allow a gap, so each index has a member
2161 Instruction *Member = Group->getMember(i);
2162 assert(Member && "Fail to get a member from an interleaved store group");
2165 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2166 if (Group->isReverse())
2167 StoredVec = reverseVector(StoredVec);
2169 // If this member has different type, cast it to an unified type.
2170 if (StoredVec->getType() != SubVT)
2171 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2173 StoredVecs.push_back(StoredVec);
2176 // Concatenate all vectors into a wide vector.
2177 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2179 // Interleave the elements in the wide vector.
2180 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2181 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2184 Instruction *NewStoreInstr =
2185 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2186 propagateMetadata(NewStoreInstr, Instr);
2190 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2191 // Attempt to issue a wide load.
2192 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2193 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2195 assert((LI || SI) && "Invalid Load/Store instruction");
2197 // Try to vectorize the interleave group if this access is interleaved.
2198 if (Legal->isAccessInterleaved(Instr))
2199 return vectorizeInterleaveGroup(Instr);
2201 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2202 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2203 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2204 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2205 // An alignment of 0 means target abi alignment. We need to use the scalar's
2206 // target abi alignment in such a case.
2207 const DataLayout &DL = Instr->getModule()->getDataLayout();
2209 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2210 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2211 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2212 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2214 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2215 !Legal->isMaskRequired(SI))
2216 return scalarizeInstruction(Instr, true);
2218 if (ScalarAllocatedSize != VectorElementSize)
2219 return scalarizeInstruction(Instr);
2221 // If the pointer is loop invariant or if it is non-consecutive,
2222 // scalarize the load.
2223 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2224 bool Reverse = ConsecutiveStride < 0;
2225 bool UniformLoad = LI && Legal->isUniform(Ptr);
2226 if (!ConsecutiveStride || UniformLoad)
2227 return scalarizeInstruction(Instr);
2229 Constant *Zero = Builder.getInt32(0);
2230 VectorParts &Entry = WidenMap.get(Instr);
2232 // Handle consecutive loads/stores.
2233 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2234 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2235 setDebugLocFromInst(Builder, Gep);
2236 Value *PtrOperand = Gep->getPointerOperand();
2237 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2238 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2240 // Create the new GEP with the new induction variable.
2241 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2242 Gep2->setOperand(0, FirstBasePtr);
2243 Gep2->setName("gep.indvar.base");
2244 Ptr = Builder.Insert(Gep2);
2246 setDebugLocFromInst(Builder, Gep);
2247 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2248 OrigLoop) && "Base ptr must be invariant");
2250 // The last index does not have to be the induction. It can be
2251 // consecutive and be a function of the index. For example A[I+1];
2252 unsigned NumOperands = Gep->getNumOperands();
2253 unsigned InductionOperand = getGEPInductionOperand(Gep);
2254 // Create the new GEP with the new induction variable.
2255 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2257 for (unsigned i = 0; i < NumOperands; ++i) {
2258 Value *GepOperand = Gep->getOperand(i);
2259 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2261 // Update last index or loop invariant instruction anchored in loop.
2262 if (i == InductionOperand ||
2263 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2264 assert((i == InductionOperand ||
2265 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2266 "Must be last index or loop invariant");
2268 VectorParts &GEPParts = getVectorValue(GepOperand);
2269 Value *Index = GEPParts[0];
2270 Index = Builder.CreateExtractElement(Index, Zero);
2271 Gep2->setOperand(i, Index);
2272 Gep2->setName("gep.indvar.idx");
2275 Ptr = Builder.Insert(Gep2);
2277 // Use the induction element ptr.
2278 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2279 setDebugLocFromInst(Builder, Ptr);
2280 VectorParts &PtrVal = getVectorValue(Ptr);
2281 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2284 VectorParts Mask = createBlockInMask(Instr->getParent());
2287 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2288 "We do not allow storing to uniform addresses");
2289 setDebugLocFromInst(Builder, SI);
2290 // We don't want to update the value in the map as it might be used in
2291 // another expression. So don't use a reference type for "StoredVal".
2292 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2294 for (unsigned Part = 0; Part < UF; ++Part) {
2295 // Calculate the pointer for the specific unroll-part.
2297 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2300 // If we store to reverse consecutive memory locations then we need
2301 // to reverse the order of elements in the stored value.
2302 StoredVal[Part] = reverseVector(StoredVal[Part]);
2303 // If the address is consecutive but reversed, then the
2304 // wide store needs to start at the last vector element.
2305 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2306 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2307 Mask[Part] = reverseVector(Mask[Part]);
2310 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2311 DataTy->getPointerTo(AddressSpace));
2314 if (Legal->isMaskRequired(SI))
2315 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2318 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2319 propagateMetadata(NewSI, SI);
2325 assert(LI && "Must have a load instruction");
2326 setDebugLocFromInst(Builder, LI);
2327 for (unsigned Part = 0; Part < UF; ++Part) {
2328 // Calculate the pointer for the specific unroll-part.
2330 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2333 // If the address is consecutive but reversed, then the
2334 // wide load needs to start at the last vector element.
2335 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2336 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2337 Mask[Part] = reverseVector(Mask[Part]);
2341 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2342 DataTy->getPointerTo(AddressSpace));
2343 if (Legal->isMaskRequired(LI))
2344 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2345 UndefValue::get(DataTy),
2346 "wide.masked.load");
2348 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2349 propagateMetadata(NewLI, LI);
2350 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2354 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2355 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2356 // Holds vector parameters or scalars, in case of uniform vals.
2357 SmallVector<VectorParts, 4> Params;
2359 setDebugLocFromInst(Builder, Instr);
2361 // Find all of the vectorized parameters.
2362 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2363 Value *SrcOp = Instr->getOperand(op);
2365 // If we are accessing the old induction variable, use the new one.
2366 if (SrcOp == OldInduction) {
2367 Params.push_back(getVectorValue(SrcOp));
2371 // Try using previously calculated values.
2372 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2374 // If the src is an instruction that appeared earlier in the basic block
2375 // then it should already be vectorized.
2376 if (SrcInst && OrigLoop->contains(SrcInst)) {
2377 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2378 // The parameter is a vector value from earlier.
2379 Params.push_back(WidenMap.get(SrcInst));
2381 // The parameter is a scalar from outside the loop. Maybe even a constant.
2382 VectorParts Scalars;
2383 Scalars.append(UF, SrcOp);
2384 Params.push_back(Scalars);
2388 assert(Params.size() == Instr->getNumOperands() &&
2389 "Invalid number of operands");
2391 // Does this instruction return a value ?
2392 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2394 Value *UndefVec = IsVoidRetTy ? nullptr :
2395 UndefValue::get(VectorType::get(Instr->getType(), VF));
2396 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2397 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2399 Instruction *InsertPt = Builder.GetInsertPoint();
2400 BasicBlock *IfBlock = Builder.GetInsertBlock();
2401 BasicBlock *CondBlock = nullptr;
2404 Loop *VectorLp = nullptr;
2405 if (IfPredicateStore) {
2406 assert(Instr->getParent()->getSinglePredecessor() &&
2407 "Only support single predecessor blocks");
2408 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2409 Instr->getParent());
2410 VectorLp = LI->getLoopFor(IfBlock);
2411 assert(VectorLp && "Must have a loop for this block");
2414 // For each vector unroll 'part':
2415 for (unsigned Part = 0; Part < UF; ++Part) {
2416 // For each scalar that we create:
2417 for (unsigned Width = 0; Width < VF; ++Width) {
2420 Value *Cmp = nullptr;
2421 if (IfPredicateStore) {
2422 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2423 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2424 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2425 LoopVectorBody.push_back(CondBlock);
2426 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
2427 // Update Builder with newly created basic block.
2428 Builder.SetInsertPoint(InsertPt);
2431 Instruction *Cloned = Instr->clone();
2433 Cloned->setName(Instr->getName() + ".cloned");
2434 // Replace the operands of the cloned instructions with extracted scalars.
2435 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2436 Value *Op = Params[op][Part];
2437 // Param is a vector. Need to extract the right lane.
2438 if (Op->getType()->isVectorTy())
2439 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2440 Cloned->setOperand(op, Op);
2443 // Place the cloned scalar in the new loop.
2444 Builder.Insert(Cloned);
2446 // If the original scalar returns a value we need to place it in a vector
2447 // so that future users will be able to use it.
2449 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2450 Builder.getInt32(Width));
2452 if (IfPredicateStore) {
2453 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2454 LoopVectorBody.push_back(NewIfBlock);
2455 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
2456 Builder.SetInsertPoint(InsertPt);
2457 ReplaceInstWithInst(IfBlock->getTerminator(),
2458 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
2459 IfBlock = NewIfBlock;
2465 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2469 if (Instruction *I = dyn_cast<Instruction>(V))
2470 return I->getParent() == Loc->getParent() ? I : nullptr;
2474 std::pair<Instruction *, Instruction *>
2475 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2476 Instruction *tnullptr = nullptr;
2477 if (!Legal->mustCheckStrides())
2478 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2480 IRBuilder<> ChkBuilder(Loc);
2483 Value *Check = nullptr;
2484 Instruction *FirstInst = nullptr;
2485 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2486 SE = Legal->strides_end();
2488 Value *Ptr = stripIntegerCast(*SI);
2489 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2491 // Store the first instruction we create.
2492 FirstInst = getFirstInst(FirstInst, C, Loc);
2494 Check = ChkBuilder.CreateOr(Check, C);
2499 // We have to do this trickery because the IRBuilder might fold the check to a
2500 // constant expression in which case there is no Instruction anchored in a
2502 LLVMContext &Ctx = Loc->getContext();
2503 Instruction *TheCheck =
2504 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2505 ChkBuilder.Insert(TheCheck, "stride.not.one");
2506 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2508 return std::make_pair(FirstInst, TheCheck);
2511 void InnerLoopVectorizer::createEmptyLoop() {
2513 In this function we generate a new loop. The new loop will contain
2514 the vectorized instructions while the old loop will continue to run the
2517 [ ] <-- Back-edge taken count overflow check.
2520 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2523 || [ ] <-- vector pre header.
2527 || [ ]_| <-- vector loop.
2530 | >[ ] <--- middle-block.
2533 -|- >[ ] <--- new preheader.
2537 | [ ]_| <-- old scalar loop to handle remainder.
2540 >[ ] <-- exit block.
2544 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2545 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2546 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2547 assert(VectorPH && "Invalid loop structure");
2548 assert(ExitBlock && "Must have an exit block");
2550 // Some loops have a single integer induction variable, while other loops
2551 // don't. One example is c++ iterators that often have multiple pointer
2552 // induction variables. In the code below we also support a case where we
2553 // don't have a single induction variable.
2554 OldInduction = Legal->getInduction();
2555 Type *IdxTy = Legal->getWidestInductionType();
2557 // Find the loop boundaries.
2558 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2559 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2561 // The exit count might have the type of i64 while the phi is i32. This can
2562 // happen if we have an induction variable that is sign extended before the
2563 // compare. The only way that we get a backedge taken count is that the
2564 // induction variable was signed and as such will not overflow. In such a case
2565 // truncation is legal.
2566 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2567 IdxTy->getPrimitiveSizeInBits())
2568 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2570 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2571 // Get the total trip count from the count by adding 1.
2572 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2573 SE->getConstant(BackedgeTakeCount->getType(), 1));
2575 const DataLayout &DL = OldBasicBlock->getModule()->getDataLayout();
2577 // Expand the trip count and place the new instructions in the preheader.
2578 // Notice that the pre-header does not change, only the loop body.
2579 SCEVExpander Exp(*SE, DL, "induction");
2581 // We need to test whether the backedge-taken count is uint##_max. Adding one
2582 // to it will cause overflow and an incorrect loop trip count in the vector
2583 // body. In case of overflow we want to directly jump to the scalar remainder
2585 Value *BackedgeCount =
2586 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2587 VectorPH->getTerminator());
2588 if (BackedgeCount->getType()->isPointerTy())
2589 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2590 "backedge.ptrcnt.to.int",
2591 VectorPH->getTerminator());
2592 Instruction *CheckBCOverflow =
2593 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2594 Constant::getAllOnesValue(BackedgeCount->getType()),
2595 "backedge.overflow", VectorPH->getTerminator());
2597 // The loop index does not have to start at Zero. Find the original start
2598 // value from the induction PHI node. If we don't have an induction variable
2599 // then we know that it starts at zero.
2600 Builder.SetInsertPoint(VectorPH->getTerminator());
2601 Value *StartIdx = ExtendedIdx =
2603 ? Builder.CreateZExt(OldInduction->getIncomingValueForBlock(VectorPH),
2605 : ConstantInt::get(IdxTy, 0);
2607 // Count holds the overall loop count (N).
2608 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2609 VectorPH->getTerminator());
2611 LoopBypassBlocks.push_back(VectorPH);
2613 // Split the single block loop into the two loop structure described above.
2614 BasicBlock *VecBody =
2615 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2616 BasicBlock *MiddleBlock =
2617 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2618 BasicBlock *ScalarPH =
2619 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2621 // Create and register the new vector loop.
2622 Loop* Lp = new Loop();
2623 Loop *ParentLoop = OrigLoop->getParentLoop();
2625 // Insert the new loop into the loop nest and register the new basic blocks
2626 // before calling any utilities such as SCEV that require valid LoopInfo.
2628 ParentLoop->addChildLoop(Lp);
2629 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2630 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2632 LI->addTopLevelLoop(Lp);
2634 Lp->addBasicBlockToLoop(VecBody, *LI);
2636 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2638 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2640 // Generate the induction variable.
2641 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2642 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2643 // The loop step is equal to the vectorization factor (num of SIMD elements)
2644 // times the unroll factor (num of SIMD instructions).
2645 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2647 // Generate code to check that the loop's trip count that we computed by
2648 // adding one to the backedge-taken count will not overflow.
2649 BasicBlock *NewVectorPH =
2650 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "overflow.checked");
2652 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2653 ReplaceInstWithInst(
2654 VectorPH->getTerminator(),
2655 BranchInst::Create(ScalarPH, NewVectorPH, CheckBCOverflow));
2656 VectorPH = NewVectorPH;
2658 // This is the IR builder that we use to add all of the logic for bypassing
2659 // the new vector loop.
2660 IRBuilder<> BypassBuilder(VectorPH->getTerminator());
2661 setDebugLocFromInst(BypassBuilder,
2662 getDebugLocFromInstOrOperands(OldInduction));
2664 // We may need to extend the index in case there is a type mismatch.
2665 // We know that the count starts at zero and does not overflow.
2666 if (Count->getType() != IdxTy) {
2667 // The exit count can be of pointer type. Convert it to the correct
2669 if (ExitCount->getType()->isPointerTy())
2670 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2672 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2675 // Add the start index to the loop count to get the new end index.
2676 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2678 // Now we need to generate the expression for N - (N % VF), which is
2679 // the part that the vectorized body will execute.
2680 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2681 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2682 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2683 "end.idx.rnd.down");
2685 // Now, compare the new count to zero. If it is zero skip the vector loop and
2686 // jump to the scalar loop.
2688 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2690 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2692 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2693 LoopBypassBlocks.push_back(VectorPH);
2694 ReplaceInstWithInst(VectorPH->getTerminator(),
2695 BranchInst::Create(MiddleBlock, NewVectorPH, Cmp));
2696 VectorPH = NewVectorPH;
2698 // Generate the code to check that the strides we assumed to be one are really
2699 // one. We want the new basic block to start at the first instruction in a
2700 // sequence of instructions that form a check.
2701 Instruction *StrideCheck;
2702 Instruction *FirstCheckInst;
2703 std::tie(FirstCheckInst, StrideCheck) =
2704 addStrideCheck(VectorPH->getTerminator());
2706 AddedSafetyChecks = true;
2707 // Create a new block containing the stride check.
2708 VectorPH->setName("vector.stridecheck");
2710 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2712 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2713 LoopBypassBlocks.push_back(VectorPH);
2715 // Replace the branch into the memory check block with a conditional branch
2716 // for the "few elements case".
2717 ReplaceInstWithInst(
2718 VectorPH->getTerminator(),
2719 BranchInst::Create(MiddleBlock, NewVectorPH, StrideCheck));
2721 VectorPH = NewVectorPH;
2724 // Generate the code that checks in runtime if arrays overlap. We put the
2725 // checks into a separate block to make the more common case of few elements
2727 Instruction *MemRuntimeCheck;
2728 std::tie(FirstCheckInst, MemRuntimeCheck) =
2729 Legal->getLAI()->addRuntimeCheck(VectorPH->getTerminator());
2730 if (MemRuntimeCheck) {
2731 AddedSafetyChecks = true;
2732 // Create a new block containing the memory check.
2733 VectorPH->setName("vector.memcheck");
2735 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2737 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2738 LoopBypassBlocks.push_back(VectorPH);
2740 // Replace the branch into the memory check block with a conditional branch
2741 // for the "few elements case".
2742 ReplaceInstWithInst(
2743 VectorPH->getTerminator(),
2744 BranchInst::Create(MiddleBlock, NewVectorPH, MemRuntimeCheck));
2746 VectorPH = NewVectorPH;
2749 // We are going to resume the execution of the scalar loop.
2750 // Go over all of the induction variables that we found and fix the
2751 // PHIs that are left in the scalar version of the loop.
2752 // The starting values of PHI nodes depend on the counter of the last
2753 // iteration in the vectorized loop.
2754 // If we come from a bypass edge then we need to start from the original
2757 // This variable saves the new starting index for the scalar loop.
2758 PHINode *ResumeIndex = nullptr;
2759 LoopVectorizationLegality::InductionList::iterator I, E;
2760 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2761 // Set builder to point to last bypass block.
2762 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2763 for (I = List->begin(), E = List->end(); I != E; ++I) {
2764 PHINode *OrigPhi = I->first;
2765 LoopVectorizationLegality::InductionInfo II = I->second;
2767 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2768 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2769 MiddleBlock->getTerminator());
2770 // We might have extended the type of the induction variable but we need a
2771 // truncated version for the scalar loop.
2772 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2773 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2774 MiddleBlock->getTerminator()) : nullptr;
2776 // Create phi nodes to merge from the backedge-taken check block.
2777 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2778 ScalarPH->getTerminator());
2779 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2781 PHINode *BCTruncResumeVal = nullptr;
2782 if (OrigPhi == OldInduction) {
2784 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2785 ScalarPH->getTerminator());
2786 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2789 Value *EndValue = nullptr;
2791 case LoopVectorizationLegality::IK_NoInduction:
2792 llvm_unreachable("Unknown induction");
2793 case LoopVectorizationLegality::IK_IntInduction: {
2794 // Handle the integer induction counter.
2795 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2797 // We have the canonical induction variable.
2798 if (OrigPhi == OldInduction) {
2799 // Create a truncated version of the resume value for the scalar loop,
2800 // we might have promoted the type to a larger width.
2802 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2803 // The new PHI merges the original incoming value, in case of a bypass,
2804 // or the value at the end of the vectorized loop.
2805 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2806 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2807 TruncResumeVal->addIncoming(EndValue, VecBody);
2809 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2811 // We know what the end value is.
2812 EndValue = IdxEndRoundDown;
2813 // We also know which PHI node holds it.
2814 ResumeIndex = ResumeVal;
2818 // Not the canonical induction variable - add the vector loop count to the
2820 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2821 II.StartValue->getType(),
2823 EndValue = II.transform(BypassBuilder, CRD);
2824 EndValue->setName("ind.end");
2827 case LoopVectorizationLegality::IK_PtrInduction: {
2828 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2829 II.StepValue->getType(),
2831 EndValue = II.transform(BypassBuilder, CRD);
2832 EndValue->setName("ptr.ind.end");
2837 // The new PHI merges the original incoming value, in case of a bypass,
2838 // or the value at the end of the vectorized loop.
2839 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2840 if (OrigPhi == OldInduction)
2841 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2843 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2845 ResumeVal->addIncoming(EndValue, VecBody);
2847 // Fix the scalar body counter (PHI node).
2848 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2850 // The old induction's phi node in the scalar body needs the truncated
2852 if (OrigPhi == OldInduction) {
2853 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2854 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2856 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2857 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2861 // If we are generating a new induction variable then we also need to
2862 // generate the code that calculates the exit value. This value is not
2863 // simply the end of the counter because we may skip the vectorized body
2864 // in case of a runtime check.
2866 assert(!ResumeIndex && "Unexpected resume value found");
2867 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2868 MiddleBlock->getTerminator());
2869 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2870 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2871 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2874 // Make sure that we found the index where scalar loop needs to continue.
2875 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2876 "Invalid resume Index");
2878 // Add a check in the middle block to see if we have completed
2879 // all of the iterations in the first vector loop.
2880 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2881 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2882 ResumeIndex, "cmp.n",
2883 MiddleBlock->getTerminator());
2884 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2885 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2887 // Create i+1 and fill the PHINode.
2888 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2889 Induction->addIncoming(StartIdx, VectorPH);
2890 Induction->addIncoming(NextIdx, VecBody);
2891 // Create the compare.
2892 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2893 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2895 // Now we have two terminators. Remove the old one from the block.
2896 VecBody->getTerminator()->eraseFromParent();
2898 // Get ready to start creating new instructions into the vectorized body.
2899 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2902 LoopVectorPreHeader = VectorPH;
2903 LoopScalarPreHeader = ScalarPH;
2904 LoopMiddleBlock = MiddleBlock;
2905 LoopExitBlock = ExitBlock;
2906 LoopVectorBody.push_back(VecBody);
2907 LoopScalarBody = OldBasicBlock;
2909 LoopVectorizeHints Hints(Lp, true);
2910 Hints.setAlreadyVectorized();
2914 struct CSEDenseMapInfo {
2915 static bool canHandle(Instruction *I) {
2916 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2917 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2919 static inline Instruction *getEmptyKey() {
2920 return DenseMapInfo<Instruction *>::getEmptyKey();
2922 static inline Instruction *getTombstoneKey() {
2923 return DenseMapInfo<Instruction *>::getTombstoneKey();
2925 static unsigned getHashValue(Instruction *I) {
2926 assert(canHandle(I) && "Unknown instruction!");
2927 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2928 I->value_op_end()));
2930 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2931 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2932 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2934 return LHS->isIdenticalTo(RHS);
2939 /// \brief Check whether this block is a predicated block.
2940 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2941 /// = ...; " blocks. We start with one vectorized basic block. For every
2942 /// conditional block we split this vectorized block. Therefore, every second
2943 /// block will be a predicated one.
2944 static bool isPredicatedBlock(unsigned BlockNum) {
2945 return BlockNum % 2;
2948 ///\brief Perform cse of induction variable instructions.
2949 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2950 // Perform simple cse.
2951 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2952 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2953 BasicBlock *BB = BBs[i];
2954 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2955 Instruction *In = I++;
2957 if (!CSEDenseMapInfo::canHandle(In))
2960 // Check if we can replace this instruction with any of the
2961 // visited instructions.
2962 if (Instruction *V = CSEMap.lookup(In)) {
2963 In->replaceAllUsesWith(V);
2964 In->eraseFromParent();
2967 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2968 // ...;" blocks for predicated stores. Every second block is a predicated
2970 if (isPredicatedBlock(i))
2978 /// \brief Adds a 'fast' flag to floating point operations.
2979 static Value *addFastMathFlag(Value *V) {
2980 if (isa<FPMathOperator>(V)){
2981 FastMathFlags Flags;
2982 Flags.setUnsafeAlgebra();
2983 cast<Instruction>(V)->setFastMathFlags(Flags);
2988 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
2989 /// the result needs to be inserted and/or extracted from vectors.
2990 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
2991 const TargetTransformInfo &TTI) {
2995 assert(Ty->isVectorTy() && "Can only scalarize vectors");
2998 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3000 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3002 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3008 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3009 // Return the cost of the instruction, including scalarization overhead if it's
3010 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3011 // i.e. either vector version isn't available, or is too expensive.
3012 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3013 const TargetTransformInfo &TTI,
3014 const TargetLibraryInfo *TLI,
3015 bool &NeedToScalarize) {
3016 Function *F = CI->getCalledFunction();
3017 StringRef FnName = CI->getCalledFunction()->getName();
3018 Type *ScalarRetTy = CI->getType();
3019 SmallVector<Type *, 4> Tys, ScalarTys;
3020 for (auto &ArgOp : CI->arg_operands())
3021 ScalarTys.push_back(ArgOp->getType());
3023 // Estimate cost of scalarized vector call. The source operands are assumed
3024 // to be vectors, so we need to extract individual elements from there,
3025 // execute VF scalar calls, and then gather the result into the vector return
3027 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3029 return ScalarCallCost;
3031 // Compute corresponding vector type for return value and arguments.
3032 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3033 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3034 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3036 // Compute costs of unpacking argument values for the scalar calls and
3037 // packing the return values to a vector.
3038 unsigned ScalarizationCost =
3039 getScalarizationOverhead(RetTy, true, false, TTI);
3040 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3041 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3043 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3045 // If we can't emit a vector call for this function, then the currently found
3046 // cost is the cost we need to return.
3047 NeedToScalarize = true;
3048 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3051 // If the corresponding vector cost is cheaper, return its cost.
3052 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3053 if (VectorCallCost < Cost) {
3054 NeedToScalarize = false;
3055 return VectorCallCost;
3060 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3061 // factor VF. Return the cost of the instruction, including scalarization
3062 // overhead if it's needed.
3063 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3064 const TargetTransformInfo &TTI,
3065 const TargetLibraryInfo *TLI) {
3066 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3067 assert(ID && "Expected intrinsic call!");
3069 Type *RetTy = ToVectorTy(CI->getType(), VF);
3070 SmallVector<Type *, 4> Tys;
3071 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3072 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3074 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3077 void InnerLoopVectorizer::vectorizeLoop() {
3078 //===------------------------------------------------===//
3080 // Notice: any optimization or new instruction that go
3081 // into the code below should be also be implemented in
3084 //===------------------------------------------------===//
3085 Constant *Zero = Builder.getInt32(0);
3087 // In order to support reduction variables we need to be able to vectorize
3088 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3089 // stages. First, we create a new vector PHI node with no incoming edges.
3090 // We use this value when we vectorize all of the instructions that use the
3091 // PHI. Next, after all of the instructions in the block are complete we
3092 // add the new incoming edges to the PHI. At this point all of the
3093 // instructions in the basic block are vectorized, so we can use them to
3094 // construct the PHI.
3095 PhiVector RdxPHIsToFix;
3097 // Scan the loop in a topological order to ensure that defs are vectorized
3099 LoopBlocksDFS DFS(OrigLoop);
3102 // Vectorize all of the blocks in the original loop.
3103 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3104 be = DFS.endRPO(); bb != be; ++bb)
3105 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3107 // At this point every instruction in the original loop is widened to
3108 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3109 // that we vectorized. The PHI nodes are currently empty because we did
3110 // not want to introduce cycles. Notice that the remaining PHI nodes
3111 // that we need to fix are reduction variables.
3113 // Create the 'reduced' values for each of the induction vars.
3114 // The reduced values are the vector values that we scalarize and combine
3115 // after the loop is finished.
3116 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3118 PHINode *RdxPhi = *it;
3119 assert(RdxPhi && "Unable to recover vectorized PHI");
3121 // Find the reduction variable descriptor.
3122 assert(Legal->getReductionVars()->count(RdxPhi) &&
3123 "Unable to find the reduction variable");
3124 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3126 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3127 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3128 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3129 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3130 RdxDesc.getMinMaxRecurrenceKind();
3131 setDebugLocFromInst(Builder, ReductionStartValue);
3133 // We need to generate a reduction vector from the incoming scalar.
3134 // To do so, we need to generate the 'identity' vector and override
3135 // one of the elements with the incoming scalar reduction. We need
3136 // to do it in the vector-loop preheader.
3137 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3139 // This is the vector-clone of the value that leaves the loop.
3140 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3141 Type *VecTy = VectorExit[0]->getType();
3143 // Find the reduction identity variable. Zero for addition, or, xor,
3144 // one for multiplication, -1 for And.
3147 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3148 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3149 // MinMax reduction have the start value as their identify.
3151 VectorStart = Identity = ReductionStartValue;
3153 VectorStart = Identity =
3154 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3157 // Handle other reduction kinds:
3158 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3159 RK, VecTy->getScalarType());
3162 // This vector is the Identity vector where the first element is the
3163 // incoming scalar reduction.
3164 VectorStart = ReductionStartValue;
3166 Identity = ConstantVector::getSplat(VF, Iden);
3168 // This vector is the Identity vector where the first element is the
3169 // incoming scalar reduction.
3171 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3175 // Fix the vector-loop phi.
3177 // Reductions do not have to start at zero. They can start with
3178 // any loop invariant values.
3179 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3180 BasicBlock *Latch = OrigLoop->getLoopLatch();
3181 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3182 VectorParts &Val = getVectorValue(LoopVal);
3183 for (unsigned part = 0; part < UF; ++part) {
3184 // Make sure to add the reduction stat value only to the
3185 // first unroll part.
3186 Value *StartVal = (part == 0) ? VectorStart : Identity;
3187 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3188 LoopVectorPreHeader);
3189 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3190 LoopVectorBody.back());
3193 // Before each round, move the insertion point right between
3194 // the PHIs and the values we are going to write.
3195 // This allows us to write both PHINodes and the extractelement
3197 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3199 VectorParts RdxParts;
3200 setDebugLocFromInst(Builder, LoopExitInst);
3201 for (unsigned part = 0; part < UF; ++part) {
3202 // This PHINode contains the vectorized reduction variable, or
3203 // the initial value vector, if we bypass the vector loop.
3204 VectorParts &RdxExitVal = getVectorValue(LoopExitInst);
3205 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
3206 Value *StartVal = (part == 0) ? VectorStart : Identity;
3207 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3208 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
3209 NewPhi->addIncoming(RdxExitVal[part],
3210 LoopVectorBody.back());
3211 RdxParts.push_back(NewPhi);
3214 // Reduce all of the unrolled parts into a single vector.
3215 Value *ReducedPartRdx = RdxParts[0];
3216 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3217 setDebugLocFromInst(Builder, ReducedPartRdx);
3218 for (unsigned part = 1; part < UF; ++part) {
3219 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3220 // Floating point operations had to be 'fast' to enable the reduction.
3221 ReducedPartRdx = addFastMathFlag(
3222 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3223 ReducedPartRdx, "bin.rdx"));
3225 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3226 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3230 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3231 // and vector ops, reducing the set of values being computed by half each
3233 assert(isPowerOf2_32(VF) &&
3234 "Reduction emission only supported for pow2 vectors!");
3235 Value *TmpVec = ReducedPartRdx;
3236 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3237 for (unsigned i = VF; i != 1; i >>= 1) {
3238 // Move the upper half of the vector to the lower half.
3239 for (unsigned j = 0; j != i/2; ++j)
3240 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3242 // Fill the rest of the mask with undef.
3243 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3244 UndefValue::get(Builder.getInt32Ty()));
3247 Builder.CreateShuffleVector(TmpVec,
3248 UndefValue::get(TmpVec->getType()),
3249 ConstantVector::get(ShuffleMask),
3252 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3253 // Floating point operations had to be 'fast' to enable the reduction.
3254 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3255 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3257 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3261 // The result is in the first element of the vector.
3262 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3263 Builder.getInt32(0));
3266 // Create a phi node that merges control-flow from the backedge-taken check
3267 // block and the middle block.
3268 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3269 LoopScalarPreHeader->getTerminator());
3270 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[0]);
3271 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3273 // Now, we need to fix the users of the reduction variable
3274 // inside and outside of the scalar remainder loop.
3275 // We know that the loop is in LCSSA form. We need to update the
3276 // PHI nodes in the exit blocks.
3277 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3278 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3279 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3280 if (!LCSSAPhi) break;
3282 // All PHINodes need to have a single entry edge, or two if
3283 // we already fixed them.
3284 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3286 // We found our reduction value exit-PHI. Update it with the
3287 // incoming bypass edge.
3288 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3289 // Add an edge coming from the bypass.
3290 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3293 }// end of the LCSSA phi scan.
3295 // Fix the scalar loop reduction variable with the incoming reduction sum
3296 // from the vector body and from the backedge value.
3297 int IncomingEdgeBlockIdx =
3298 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3299 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3300 // Pick the other block.
3301 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3302 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3303 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3304 }// end of for each redux variable.
3308 // Remove redundant induction instructions.
3309 cse(LoopVectorBody);
3312 void InnerLoopVectorizer::fixLCSSAPHIs() {
3313 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3314 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3315 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3316 if (!LCSSAPhi) break;
3317 if (LCSSAPhi->getNumIncomingValues() == 1)
3318 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3323 InnerLoopVectorizer::VectorParts
3324 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3325 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3328 // Look for cached value.
3329 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3330 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3331 if (ECEntryIt != MaskCache.end())
3332 return ECEntryIt->second;
3334 VectorParts SrcMask = createBlockInMask(Src);
3336 // The terminator has to be a branch inst!
3337 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3338 assert(BI && "Unexpected terminator found");
3340 if (BI->isConditional()) {
3341 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3343 if (BI->getSuccessor(0) != Dst)
3344 for (unsigned part = 0; part < UF; ++part)
3345 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3347 for (unsigned part = 0; part < UF; ++part)
3348 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3350 MaskCache[Edge] = EdgeMask;
3354 MaskCache[Edge] = SrcMask;
3358 InnerLoopVectorizer::VectorParts
3359 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3360 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3362 // Loop incoming mask is all-one.
3363 if (OrigLoop->getHeader() == BB) {
3364 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3365 return getVectorValue(C);
3368 // This is the block mask. We OR all incoming edges, and with zero.
3369 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3370 VectorParts BlockMask = getVectorValue(Zero);
3373 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3374 VectorParts EM = createEdgeMask(*it, BB);
3375 for (unsigned part = 0; part < UF; ++part)
3376 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3382 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3383 InnerLoopVectorizer::VectorParts &Entry,
3384 unsigned UF, unsigned VF, PhiVector *PV) {
3385 PHINode* P = cast<PHINode>(PN);
3386 // Handle reduction variables:
3387 if (Legal->getReductionVars()->count(P)) {
3388 for (unsigned part = 0; part < UF; ++part) {
3389 // This is phase one of vectorizing PHIs.
3390 Type *VecTy = (VF == 1) ? PN->getType() :
3391 VectorType::get(PN->getType(), VF);
3392 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3393 LoopVectorBody.back()-> getFirstInsertionPt());
3399 setDebugLocFromInst(Builder, P);
3400 // Check for PHI nodes that are lowered to vector selects.
3401 if (P->getParent() != OrigLoop->getHeader()) {
3402 // We know that all PHIs in non-header blocks are converted into
3403 // selects, so we don't have to worry about the insertion order and we
3404 // can just use the builder.
3405 // At this point we generate the predication tree. There may be
3406 // duplications since this is a simple recursive scan, but future
3407 // optimizations will clean it up.
3409 unsigned NumIncoming = P->getNumIncomingValues();
3411 // Generate a sequence of selects of the form:
3412 // SELECT(Mask3, In3,
3413 // SELECT(Mask2, In2,
3415 for (unsigned In = 0; In < NumIncoming; In++) {
3416 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3418 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3420 for (unsigned part = 0; part < UF; ++part) {
3421 // We might have single edge PHIs (blocks) - use an identity
3422 // 'select' for the first PHI operand.
3424 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3427 // Select between the current value and the previous incoming edge
3428 // based on the incoming mask.
3429 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3430 Entry[part], "predphi");
3436 // This PHINode must be an induction variable.
3437 // Make sure that we know about it.
3438 assert(Legal->getInductionVars()->count(P) &&
3439 "Not an induction variable");
3441 LoopVectorizationLegality::InductionInfo II =
3442 Legal->getInductionVars()->lookup(P);
3444 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3445 // which can be found from the original scalar operations.
3447 case LoopVectorizationLegality::IK_NoInduction:
3448 llvm_unreachable("Unknown induction");
3449 case LoopVectorizationLegality::IK_IntInduction: {
3450 assert(P->getType() == II.StartValue->getType() && "Types must match");
3451 Type *PhiTy = P->getType();
3453 if (P == OldInduction) {
3454 // Handle the canonical induction variable. We might have had to
3456 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3458 // Handle other induction variables that are now based on the
3460 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3462 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3463 Broadcasted = II.transform(Builder, NormalizedIdx);
3464 Broadcasted->setName("offset.idx");
3466 Broadcasted = getBroadcastInstrs(Broadcasted);
3467 // After broadcasting the induction variable we need to make the vector
3468 // consecutive by adding 0, 1, 2, etc.
3469 for (unsigned part = 0; part < UF; ++part)
3470 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
3473 case LoopVectorizationLegality::IK_PtrInduction:
3474 // Handle the pointer induction variable case.
3475 assert(P->getType()->isPointerTy() && "Unexpected type.");
3476 // This is the normalized GEP that starts counting at zero.
3477 Value *NormalizedIdx =
3478 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
3480 Builder.CreateSExtOrTrunc(NormalizedIdx, II.StepValue->getType());
3481 // This is the vector of results. Notice that we don't generate
3482 // vector geps because scalar geps result in better code.
3483 for (unsigned part = 0; part < UF; ++part) {
3485 int EltIndex = part;
3486 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3487 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3488 Value *SclrGep = II.transform(Builder, GlobalIdx);
3489 SclrGep->setName("next.gep");
3490 Entry[part] = SclrGep;
3494 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3495 for (unsigned int i = 0; i < VF; ++i) {
3496 int EltIndex = i + part * VF;
3497 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3498 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3499 Value *SclrGep = II.transform(Builder, GlobalIdx);
3500 SclrGep->setName("next.gep");
3501 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3502 Builder.getInt32(i),
3505 Entry[part] = VecVal;
3511 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3512 // For each instruction in the old loop.
3513 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3514 VectorParts &Entry = WidenMap.get(it);
3515 switch (it->getOpcode()) {
3516 case Instruction::Br:
3517 // Nothing to do for PHIs and BR, since we already took care of the
3518 // loop control flow instructions.
3520 case Instruction::PHI: {
3521 // Vectorize PHINodes.
3522 widenPHIInstruction(it, Entry, UF, VF, PV);
3526 case Instruction::Add:
3527 case Instruction::FAdd:
3528 case Instruction::Sub:
3529 case Instruction::FSub:
3530 case Instruction::Mul:
3531 case Instruction::FMul:
3532 case Instruction::UDiv:
3533 case Instruction::SDiv:
3534 case Instruction::FDiv:
3535 case Instruction::URem:
3536 case Instruction::SRem:
3537 case Instruction::FRem:
3538 case Instruction::Shl:
3539 case Instruction::LShr:
3540 case Instruction::AShr:
3541 case Instruction::And:
3542 case Instruction::Or:
3543 case Instruction::Xor: {
3544 // Just widen binops.
3545 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3546 setDebugLocFromInst(Builder, BinOp);
3547 VectorParts &A = getVectorValue(it->getOperand(0));
3548 VectorParts &B = getVectorValue(it->getOperand(1));
3550 // Use this vector value for all users of the original instruction.
3551 for (unsigned Part = 0; Part < UF; ++Part) {
3552 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3554 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3555 VecOp->copyIRFlags(BinOp);
3560 propagateMetadata(Entry, it);
3563 case Instruction::Select: {
3565 // If the selector is loop invariant we can create a select
3566 // instruction with a scalar condition. Otherwise, use vector-select.
3567 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3569 setDebugLocFromInst(Builder, it);
3571 // The condition can be loop invariant but still defined inside the
3572 // loop. This means that we can't just use the original 'cond' value.
3573 // We have to take the 'vectorized' value and pick the first lane.
3574 // Instcombine will make this a no-op.
3575 VectorParts &Cond = getVectorValue(it->getOperand(0));
3576 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3577 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3579 Value *ScalarCond = (VF == 1) ? Cond[0] :
3580 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3582 for (unsigned Part = 0; Part < UF; ++Part) {
3583 Entry[Part] = Builder.CreateSelect(
3584 InvariantCond ? ScalarCond : Cond[Part],
3589 propagateMetadata(Entry, it);
3593 case Instruction::ICmp:
3594 case Instruction::FCmp: {
3595 // Widen compares. Generate vector compares.
3596 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3597 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3598 setDebugLocFromInst(Builder, it);
3599 VectorParts &A = getVectorValue(it->getOperand(0));
3600 VectorParts &B = getVectorValue(it->getOperand(1));
3601 for (unsigned Part = 0; Part < UF; ++Part) {
3604 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3606 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3610 propagateMetadata(Entry, it);
3614 case Instruction::Store:
3615 case Instruction::Load:
3616 vectorizeMemoryInstruction(it);
3618 case Instruction::ZExt:
3619 case Instruction::SExt:
3620 case Instruction::FPToUI:
3621 case Instruction::FPToSI:
3622 case Instruction::FPExt:
3623 case Instruction::PtrToInt:
3624 case Instruction::IntToPtr:
3625 case Instruction::SIToFP:
3626 case Instruction::UIToFP:
3627 case Instruction::Trunc:
3628 case Instruction::FPTrunc:
3629 case Instruction::BitCast: {
3630 CastInst *CI = dyn_cast<CastInst>(it);
3631 setDebugLocFromInst(Builder, it);
3632 /// Optimize the special case where the source is the induction
3633 /// variable. Notice that we can only optimize the 'trunc' case
3634 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3635 /// c. other casts depend on pointer size.
3636 if (CI->getOperand(0) == OldInduction &&
3637 it->getOpcode() == Instruction::Trunc) {
3638 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3640 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3641 LoopVectorizationLegality::InductionInfo II =
3642 Legal->getInductionVars()->lookup(OldInduction);
3644 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3645 for (unsigned Part = 0; Part < UF; ++Part)
3646 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3647 propagateMetadata(Entry, it);
3650 /// Vectorize casts.
3651 Type *DestTy = (VF == 1) ? CI->getType() :
3652 VectorType::get(CI->getType(), VF);
3654 VectorParts &A = getVectorValue(it->getOperand(0));
3655 for (unsigned Part = 0; Part < UF; ++Part)
3656 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3657 propagateMetadata(Entry, it);
3661 case Instruction::Call: {
3662 // Ignore dbg intrinsics.
3663 if (isa<DbgInfoIntrinsic>(it))
3665 setDebugLocFromInst(Builder, it);
3667 Module *M = BB->getParent()->getParent();
3668 CallInst *CI = cast<CallInst>(it);
3670 StringRef FnName = CI->getCalledFunction()->getName();
3671 Function *F = CI->getCalledFunction();
3672 Type *RetTy = ToVectorTy(CI->getType(), VF);
3673 SmallVector<Type *, 4> Tys;
3674 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3675 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3677 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3679 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3680 ID == Intrinsic::lifetime_start)) {
3681 scalarizeInstruction(it);
3684 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3685 // version of the instruction.
3686 // Is it beneficial to perform intrinsic call compared to lib call?
3687 bool NeedToScalarize;
3688 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3689 bool UseVectorIntrinsic =
3690 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3691 if (!UseVectorIntrinsic && NeedToScalarize) {
3692 scalarizeInstruction(it);
3696 for (unsigned Part = 0; Part < UF; ++Part) {
3697 SmallVector<Value *, 4> Args;
3698 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3699 Value *Arg = CI->getArgOperand(i);
3700 // Some intrinsics have a scalar argument - don't replace it with a
3702 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3703 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3704 Arg = VectorArg[Part];
3706 Args.push_back(Arg);
3710 if (UseVectorIntrinsic) {
3711 // Use vector version of the intrinsic.
3712 Type *TysForDecl[] = {CI->getType()};
3714 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3715 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3717 // Use vector version of the library call.
3718 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3719 assert(!VFnName.empty() && "Vector function name is empty.");
3720 VectorF = M->getFunction(VFnName);
3722 // Generate a declaration
3723 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3725 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3726 VectorF->copyAttributesFrom(F);
3729 assert(VectorF && "Can't create vector function.");
3730 Entry[Part] = Builder.CreateCall(VectorF, Args);
3733 propagateMetadata(Entry, it);
3738 // All other instructions are unsupported. Scalarize them.
3739 scalarizeInstruction(it);
3742 }// end of for_each instr.
3745 void InnerLoopVectorizer::updateAnalysis() {
3746 // Forget the original basic block.
3747 SE->forgetLoop(OrigLoop);
3749 // Update the dominator tree information.
3750 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3751 "Entry does not dominate exit.");
3753 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3754 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3755 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3757 // Due to if predication of stores we might create a sequence of "if(pred)
3758 // a[i] = ...; " blocks.
3759 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3761 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3762 else if (isPredicatedBlock(i)) {
3763 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3765 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3769 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3770 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3771 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3772 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3774 DEBUG(DT->verifyDomTree());
3777 /// \brief Check whether it is safe to if-convert this phi node.
3779 /// Phi nodes with constant expressions that can trap are not safe to if
3781 static bool canIfConvertPHINodes(BasicBlock *BB) {
3782 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3783 PHINode *Phi = dyn_cast<PHINode>(I);
3786 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3787 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3794 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3795 if (!EnableIfConversion) {
3796 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3800 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3802 // A list of pointers that we can safely read and write to.
3803 SmallPtrSet<Value *, 8> SafePointes;
3805 // Collect safe addresses.
3806 for (Loop::block_iterator BI = TheLoop->block_begin(),
3807 BE = TheLoop->block_end(); BI != BE; ++BI) {
3808 BasicBlock *BB = *BI;
3810 if (blockNeedsPredication(BB))
3813 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3814 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3815 SafePointes.insert(LI->getPointerOperand());
3816 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3817 SafePointes.insert(SI->getPointerOperand());
3821 // Collect the blocks that need predication.
3822 BasicBlock *Header = TheLoop->getHeader();
3823 for (Loop::block_iterator BI = TheLoop->block_begin(),
3824 BE = TheLoop->block_end(); BI != BE; ++BI) {
3825 BasicBlock *BB = *BI;
3827 // We don't support switch statements inside loops.
3828 if (!isa<BranchInst>(BB->getTerminator())) {
3829 emitAnalysis(VectorizationReport(BB->getTerminator())
3830 << "loop contains a switch statement");
3834 // We must be able to predicate all blocks that need to be predicated.
3835 if (blockNeedsPredication(BB)) {
3836 if (!blockCanBePredicated(BB, SafePointes)) {
3837 emitAnalysis(VectorizationReport(BB->getTerminator())
3838 << "control flow cannot be substituted for a select");
3841 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3842 emitAnalysis(VectorizationReport(BB->getTerminator())
3843 << "control flow cannot be substituted for a select");
3848 // We can if-convert this loop.
3852 bool LoopVectorizationLegality::canVectorize() {
3853 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3854 // be canonicalized.
3855 if (!TheLoop->getLoopPreheader()) {
3857 VectorizationReport() <<
3858 "loop control flow is not understood by vectorizer");
3862 // We can only vectorize innermost loops.
3863 if (!TheLoop->empty()) {
3864 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3868 // We must have a single backedge.
3869 if (TheLoop->getNumBackEdges() != 1) {
3871 VectorizationReport() <<
3872 "loop control flow is not understood by vectorizer");
3876 // We must have a single exiting block.
3877 if (!TheLoop->getExitingBlock()) {
3879 VectorizationReport() <<
3880 "loop control flow is not understood by vectorizer");
3884 // We only handle bottom-tested loops, i.e. loop in which the condition is
3885 // checked at the end of each iteration. With that we can assume that all
3886 // instructions in the loop are executed the same number of times.
3887 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3889 VectorizationReport() <<
3890 "loop control flow is not understood by vectorizer");
3894 // We need to have a loop header.
3895 DEBUG(dbgs() << "LV: Found a loop: " <<
3896 TheLoop->getHeader()->getName() << '\n');
3898 // Check if we can if-convert non-single-bb loops.
3899 unsigned NumBlocks = TheLoop->getNumBlocks();
3900 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3901 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3905 // ScalarEvolution needs to be able to find the exit count.
3906 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3907 if (ExitCount == SE->getCouldNotCompute()) {
3908 emitAnalysis(VectorizationReport() <<
3909 "could not determine number of loop iterations");
3910 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3914 // Check if we can vectorize the instructions and CFG in this loop.
3915 if (!canVectorizeInstrs()) {
3916 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3920 // Go over each instruction and look at memory deps.
3921 if (!canVectorizeMemory()) {
3922 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3926 // Collect all of the variables that remain uniform after vectorization.
3927 collectLoopUniforms();
3929 DEBUG(dbgs() << "LV: We can vectorize this loop"
3930 << (LAI->getRuntimePointerChecking()->Need
3931 ? " (with a runtime bound check)"
3935 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
3937 // If an override option has been passed in for interleaved accesses, use it.
3938 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
3939 UseInterleaved = EnableInterleavedMemAccesses;
3941 // Analyze interleaved memory accesses.
3943 InterleaveInfo.analyzeInterleaving(Strides);
3945 // Okay! We can vectorize. At this point we don't have any other mem analysis
3946 // which may limit our maximum vectorization factor, so just return true with
3951 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3952 if (Ty->isPointerTy())
3953 return DL.getIntPtrType(Ty);
3955 // It is possible that char's or short's overflow when we ask for the loop's
3956 // trip count, work around this by changing the type size.
3957 if (Ty->getScalarSizeInBits() < 32)
3958 return Type::getInt32Ty(Ty->getContext());
3963 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3964 Ty0 = convertPointerToIntegerType(DL, Ty0);
3965 Ty1 = convertPointerToIntegerType(DL, Ty1);
3966 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3971 /// \brief Check that the instruction has outside loop users and is not an
3972 /// identified reduction variable.
3973 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3974 SmallPtrSetImpl<Value *> &Reductions) {
3975 // Reduction instructions are allowed to have exit users. All other
3976 // instructions must not have external users.
3977 if (!Reductions.count(Inst))
3978 //Check that all of the users of the loop are inside the BB.
3979 for (User *U : Inst->users()) {
3980 Instruction *UI = cast<Instruction>(U);
3981 // This user may be a reduction exit value.
3982 if (!TheLoop->contains(UI)) {
3983 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3990 bool LoopVectorizationLegality::canVectorizeInstrs() {
3991 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3992 BasicBlock *Header = TheLoop->getHeader();
3994 // Look for the attribute signaling the absence of NaNs.
3995 Function &F = *Header->getParent();
3996 const DataLayout &DL = F.getParent()->getDataLayout();
3997 if (F.hasFnAttribute("no-nans-fp-math"))
3999 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4001 // For each block in the loop.
4002 for (Loop::block_iterator bb = TheLoop->block_begin(),
4003 be = TheLoop->block_end(); bb != be; ++bb) {
4005 // Scan the instructions in the block and look for hazards.
4006 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4009 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4010 Type *PhiTy = Phi->getType();
4011 // Check that this PHI type is allowed.
4012 if (!PhiTy->isIntegerTy() &&
4013 !PhiTy->isFloatingPointTy() &&
4014 !PhiTy->isPointerTy()) {
4015 emitAnalysis(VectorizationReport(it)
4016 << "loop control flow is not understood by vectorizer");
4017 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4021 // If this PHINode is not in the header block, then we know that we
4022 // can convert it to select during if-conversion. No need to check if
4023 // the PHIs in this block are induction or reduction variables.
4024 if (*bb != Header) {
4025 // Check that this instruction has no outside users or is an
4026 // identified reduction value with an outside user.
4027 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
4029 emitAnalysis(VectorizationReport(it) <<
4030 "value could not be identified as "
4031 "an induction or reduction variable");
4035 // We only allow if-converted PHIs with exactly two incoming values.
4036 if (Phi->getNumIncomingValues() != 2) {
4037 emitAnalysis(VectorizationReport(it)
4038 << "control flow not understood by vectorizer");
4039 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4043 // This is the value coming from the preheader.
4044 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
4045 ConstantInt *StepValue = nullptr;
4046 // Check if this is an induction variable.
4047 InductionKind IK = isInductionVariable(Phi, StepValue);
4049 if (IK_NoInduction != IK) {
4050 // Get the widest type.
4052 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4054 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4056 // Int inductions are special because we only allow one IV.
4057 if (IK == IK_IntInduction && StepValue->isOne()) {
4058 // Use the phi node with the widest type as induction. Use the last
4059 // one if there are multiple (no good reason for doing this other
4060 // than it is expedient).
4061 if (!Induction || PhiTy == WidestIndTy)
4065 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4066 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
4068 // Until we explicitly handle the case of an induction variable with
4069 // an outside loop user we have to give up vectorizing this loop.
4070 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4071 emitAnalysis(VectorizationReport(it) <<
4072 "use of induction value outside of the "
4073 "loop is not handled by vectorizer");
4080 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4082 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4086 emitAnalysis(VectorizationReport(it) <<
4087 "value that could not be identified as "
4088 "reduction is used outside the loop");
4089 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4091 }// end of PHI handling
4093 // We handle calls that:
4094 // * Are debug info intrinsics.
4095 // * Have a mapping to an IR intrinsic.
4096 // * Have a vector version available.
4097 CallInst *CI = dyn_cast<CallInst>(it);
4098 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4099 !(CI->getCalledFunction() && TLI &&
4100 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4101 emitAnalysis(VectorizationReport(it) <<
4102 "call instruction cannot be vectorized");
4103 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4107 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4108 // second argument is the same (i.e. loop invariant)
4110 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4111 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4112 emitAnalysis(VectorizationReport(it)
4113 << "intrinsic instruction cannot be vectorized");
4114 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4119 // Check that the instruction return type is vectorizable.
4120 // Also, we can't vectorize extractelement instructions.
4121 if ((!VectorType::isValidElementType(it->getType()) &&
4122 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4123 emitAnalysis(VectorizationReport(it)
4124 << "instruction return type cannot be vectorized");
4125 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4129 // Check that the stored type is vectorizable.
4130 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4131 Type *T = ST->getValueOperand()->getType();
4132 if (!VectorType::isValidElementType(T)) {
4133 emitAnalysis(VectorizationReport(ST) <<
4134 "store instruction cannot be vectorized");
4137 if (EnableMemAccessVersioning)
4138 collectStridedAccess(ST);
4141 if (EnableMemAccessVersioning)
4142 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4143 collectStridedAccess(LI);
4145 // Reduction instructions are allowed to have exit users.
4146 // All other instructions must not have external users.
4147 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4148 emitAnalysis(VectorizationReport(it) <<
4149 "value cannot be used outside the loop");
4158 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4159 if (Inductions.empty()) {
4160 emitAnalysis(VectorizationReport()
4161 << "loop induction variable could not be identified");
4169 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4170 Value *Ptr = nullptr;
4171 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4172 Ptr = LI->getPointerOperand();
4173 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4174 Ptr = SI->getPointerOperand();
4178 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4182 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4183 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4184 Strides[Ptr] = Stride;
4185 StrideSet.insert(Stride);
4188 void LoopVectorizationLegality::collectLoopUniforms() {
4189 // We now know that the loop is vectorizable!
4190 // Collect variables that will remain uniform after vectorization.
4191 std::vector<Value*> Worklist;
4192 BasicBlock *Latch = TheLoop->getLoopLatch();
4194 // Start with the conditional branch and walk up the block.
4195 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4197 // Also add all consecutive pointer values; these values will be uniform
4198 // after vectorization (and subsequent cleanup) and, until revectorization is
4199 // supported, all dependencies must also be uniform.
4200 for (Loop::block_iterator B = TheLoop->block_begin(),
4201 BE = TheLoop->block_end(); B != BE; ++B)
4202 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4204 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4205 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4207 while (!Worklist.empty()) {
4208 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4209 Worklist.pop_back();
4211 // Look at instructions inside this loop.
4212 // Stop when reaching PHI nodes.
4213 // TODO: we need to follow values all over the loop, not only in this block.
4214 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4217 // This is a known uniform.
4220 // Insert all operands.
4221 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4225 bool LoopVectorizationLegality::canVectorizeMemory() {
4226 LAI = &LAA->getInfo(TheLoop, Strides);
4227 auto &OptionalReport = LAI->getReport();
4229 emitAnalysis(VectorizationReport(*OptionalReport));
4230 if (!LAI->canVectorizeMemory())
4233 if (LAI->hasStoreToLoopInvariantAddress()) {
4235 VectorizationReport()
4236 << "write to a loop invariant address could not be vectorized");
4237 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4241 if (LAI->getNumRuntimePointerChecks() >
4242 VectorizerParams::RuntimeMemoryCheckThreshold) {
4243 emitAnalysis(VectorizationReport()
4244 << LAI->getNumRuntimePointerChecks() << " exceeds limit of "
4245 << VectorizerParams::RuntimeMemoryCheckThreshold
4246 << " dependent memory operations checked at runtime");
4247 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
4253 LoopVectorizationLegality::InductionKind
4254 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4255 ConstantInt *&StepValue) {
4256 if (!isInductionPHI(Phi, SE, StepValue))
4257 return IK_NoInduction;
4259 Type *PhiTy = Phi->getType();
4260 // Found an Integer induction variable.
4261 if (PhiTy->isIntegerTy())
4262 return IK_IntInduction;
4263 // Found an Pointer induction variable.
4264 return IK_PtrInduction;
4267 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4268 Value *In0 = const_cast<Value*>(V);
4269 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4273 return Inductions.count(PN);
4276 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4277 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4280 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4281 SmallPtrSetImpl<Value *> &SafePtrs) {
4283 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4284 // Check that we don't have a constant expression that can trap as operand.
4285 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4287 if (Constant *C = dyn_cast<Constant>(*OI))
4291 // We might be able to hoist the load.
4292 if (it->mayReadFromMemory()) {
4293 LoadInst *LI = dyn_cast<LoadInst>(it);
4296 if (!SafePtrs.count(LI->getPointerOperand())) {
4297 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4298 MaskedOp.insert(LI);
4305 // We don't predicate stores at the moment.
4306 if (it->mayWriteToMemory()) {
4307 StoreInst *SI = dyn_cast<StoreInst>(it);
4308 // We only support predication of stores in basic blocks with one
4313 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4314 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4316 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4317 !isSinglePredecessor) {
4318 // Build a masked store if it is legal for the target, otherwise scalarize
4320 bool isLegalMaskedOp =
4321 isLegalMaskedStore(SI->getValueOperand()->getType(),
4322 SI->getPointerOperand());
4323 if (isLegalMaskedOp) {
4325 MaskedOp.insert(SI);
4334 // The instructions below can trap.
4335 switch (it->getOpcode()) {
4337 case Instruction::UDiv:
4338 case Instruction::SDiv:
4339 case Instruction::URem:
4340 case Instruction::SRem:
4348 void InterleavedAccessInfo::collectConstStridedAccesses(
4349 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4350 const ValueToValueMap &Strides) {
4351 // Holds load/store instructions in program order.
4352 SmallVector<Instruction *, 16> AccessList;
4354 for (auto *BB : TheLoop->getBlocks()) {
4355 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4357 for (auto &I : *BB) {
4358 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4360 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4364 AccessList.push_back(&I);
4368 if (AccessList.empty())
4371 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4372 for (auto I : AccessList) {
4373 LoadInst *LI = dyn_cast<LoadInst>(I);
4374 StoreInst *SI = dyn_cast<StoreInst>(I);
4376 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4377 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4379 // The factor of the corresponding interleave group.
4380 unsigned Factor = std::abs(Stride);
4382 // Ignore the access if the factor is too small or too large.
4383 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4386 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4387 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4388 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4390 // An alignment of 0 means target ABI alignment.
4391 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4393 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4395 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4399 // Analyze interleaved accesses and collect them into interleave groups.
4401 // Notice that the vectorization on interleaved groups will change instruction
4402 // orders and may break dependences. But the memory dependence check guarantees
4403 // that there is no overlap between two pointers of different strides, element
4404 // sizes or underlying bases.
4406 // For pointers sharing the same stride, element size and underlying base, no
4407 // need to worry about Read-After-Write dependences and Write-After-Read
4410 // E.g. The RAW dependence: A[i] = a;
4412 // This won't exist as it is a store-load forwarding conflict, which has
4413 // already been checked and forbidden in the dependence check.
4415 // E.g. The WAR dependence: a = A[i]; // (1)
4417 // The store group of (2) is always inserted at or below (2), and the load group
4418 // of (1) is always inserted at or above (1). The dependence is safe.
4419 void InterleavedAccessInfo::analyzeInterleaving(
4420 const ValueToValueMap &Strides) {
4421 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4423 // Holds all the stride accesses.
4424 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4425 collectConstStridedAccesses(StrideAccesses, Strides);
4427 if (StrideAccesses.empty())
4430 // Holds all interleaved store groups temporarily.
4431 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4433 // Search the load-load/write-write pair B-A in bottom-up order and try to
4434 // insert B into the interleave group of A according to 3 rules:
4435 // 1. A and B have the same stride.
4436 // 2. A and B have the same memory object size.
4437 // 3. B belongs to the group according to the distance.
4439 // The bottom-up order can avoid breaking the Write-After-Write dependences
4440 // between two pointers of the same base.
4441 // E.g. A[i] = a; (1)
4444 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4445 // above (1), which guarantees that (1) is always above (2).
4446 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4448 Instruction *A = I->first;
4449 StrideDescriptor DesA = I->second;
4451 InterleaveGroup *Group = getInterleaveGroup(A);
4453 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4454 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4457 if (A->mayWriteToMemory())
4458 StoreGroups.insert(Group);
4460 for (auto II = std::next(I); II != E; ++II) {
4461 Instruction *B = II->first;
4462 StrideDescriptor DesB = II->second;
4464 // Ignore if B is already in a group or B is a different memory operation.
4465 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4468 // Check the rule 1 and 2.
4469 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4472 // Calculate the distance and prepare for the rule 3.
4473 const SCEVConstant *DistToA =
4474 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4478 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4480 // Skip if the distance is not multiple of size as they are not in the
4482 if (DistanceToA % static_cast<int>(DesA.Size))
4485 // The index of B is the index of A plus the related index to A.
4487 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4489 // Try to insert B into the group.
4490 if (Group->insertMember(B, IndexB, DesB.Align)) {
4491 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4492 << " into the interleave group with" << *A << '\n');
4493 InterleaveGroupMap[B] = Group;
4495 // Set the first load in program order as the insert position.
4496 if (B->mayReadFromMemory())
4497 Group->setInsertPos(B);
4499 } // Iteration on instruction B
4500 } // Iteration on instruction A
4502 // Remove interleaved store groups with gaps.
4503 for (InterleaveGroup *Group : StoreGroups)
4504 if (Group->getNumMembers() != Group->getFactor())
4505 releaseGroup(Group);
4508 LoopVectorizationCostModel::VectorizationFactor
4509 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4510 // Width 1 means no vectorize
4511 VectorizationFactor Factor = { 1U, 0U };
4512 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4513 emitAnalysis(VectorizationReport() <<
4514 "runtime pointer checks needed. Enable vectorization of this "
4515 "loop with '#pragma clang loop vectorize(enable)' when "
4516 "compiling with -Os");
4517 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4521 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4522 emitAnalysis(VectorizationReport() <<
4523 "store that is conditionally executed prevents vectorization");
4524 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4528 // Find the trip count.
4529 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4530 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4532 unsigned WidestType = getWidestType();
4533 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4534 unsigned MaxSafeDepDist = -1U;
4535 if (Legal->getMaxSafeDepDistBytes() != -1U)
4536 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4537 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4538 WidestRegister : MaxSafeDepDist);
4539 unsigned MaxVectorSize = WidestRegister / WidestType;
4540 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4541 DEBUG(dbgs() << "LV: The Widest register is: "
4542 << WidestRegister << " bits.\n");
4544 if (MaxVectorSize == 0) {
4545 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4549 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4550 " into one vector!");
4552 unsigned VF = MaxVectorSize;
4554 // If we optimize the program for size, avoid creating the tail loop.
4556 // If we are unable to calculate the trip count then don't try to vectorize.
4559 (VectorizationReport() <<
4560 "unable to calculate the loop count due to complex control flow");
4561 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4565 // Find the maximum SIMD width that can fit within the trip count.
4566 VF = TC % MaxVectorSize;
4571 // If the trip count that we found modulo the vectorization factor is not
4572 // zero then we require a tail.
4573 emitAnalysis(VectorizationReport() <<
4574 "cannot optimize for size and vectorize at the "
4575 "same time. Enable vectorization of this loop "
4576 "with '#pragma clang loop vectorize(enable)' "
4577 "when compiling with -Os");
4578 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4583 int UserVF = Hints->getWidth();
4585 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4586 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4588 Factor.Width = UserVF;
4592 float Cost = expectedCost(1);
4594 const float ScalarCost = Cost;
4597 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4599 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4600 // Ignore scalar width, because the user explicitly wants vectorization.
4601 if (ForceVectorization && VF > 1) {
4603 Cost = expectedCost(Width) / (float)Width;
4606 for (unsigned i=2; i <= VF; i*=2) {
4607 // Notice that the vector loop needs to be executed less times, so
4608 // we need to divide the cost of the vector loops by the width of
4609 // the vector elements.
4610 float VectorCost = expectedCost(i) / (float)i;
4611 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4612 (int)VectorCost << ".\n");
4613 if (VectorCost < Cost) {
4619 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4620 << "LV: Vectorization seems to be not beneficial, "
4621 << "but was forced by a user.\n");
4622 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4623 Factor.Width = Width;
4624 Factor.Cost = Width * Cost;
4628 unsigned LoopVectorizationCostModel::getWidestType() {
4629 unsigned MaxWidth = 8;
4630 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4633 for (Loop::block_iterator bb = TheLoop->block_begin(),
4634 be = TheLoop->block_end(); bb != be; ++bb) {
4635 BasicBlock *BB = *bb;
4637 // For each instruction in the loop.
4638 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4639 Type *T = it->getType();
4641 // Ignore ephemeral values.
4642 if (EphValues.count(it))
4645 // Only examine Loads, Stores and PHINodes.
4646 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4649 // Examine PHI nodes that are reduction variables.
4650 if (PHINode *PN = dyn_cast<PHINode>(it))
4651 if (!Legal->getReductionVars()->count(PN))
4654 // Examine the stored values.
4655 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4656 T = ST->getValueOperand()->getType();
4658 // Ignore loaded pointer types and stored pointer types that are not
4659 // consecutive. However, we do want to take consecutive stores/loads of
4660 // pointer vectors into account.
4661 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4664 MaxWidth = std::max(MaxWidth,
4665 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4672 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4674 unsigned LoopCost) {
4676 // -- The interleave heuristics --
4677 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4678 // There are many micro-architectural considerations that we can't predict
4679 // at this level. For example, frontend pressure (on decode or fetch) due to
4680 // code size, or the number and capabilities of the execution ports.
4682 // We use the following heuristics to select the interleave count:
4683 // 1. If the code has reductions, then we interleave to break the cross
4684 // iteration dependency.
4685 // 2. If the loop is really small, then we interleave to reduce the loop
4687 // 3. We don't interleave if we think that we will spill registers to memory
4688 // due to the increased register pressure.
4690 // When we optimize for size, we don't interleave.
4694 // We used the distance for the interleave count.
4695 if (Legal->getMaxSafeDepDistBytes() != -1U)
4698 // Do not interleave loops with a relatively small trip count.
4699 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4700 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4703 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4704 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4708 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4709 TargetNumRegisters = ForceTargetNumScalarRegs;
4711 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4712 TargetNumRegisters = ForceTargetNumVectorRegs;
4715 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4716 // We divide by these constants so assume that we have at least one
4717 // instruction that uses at least one register.
4718 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4719 R.NumInstructions = std::max(R.NumInstructions, 1U);
4721 // We calculate the interleave count using the following formula.
4722 // Subtract the number of loop invariants from the number of available
4723 // registers. These registers are used by all of the interleaved instances.
4724 // Next, divide the remaining registers by the number of registers that is
4725 // required by the loop, in order to estimate how many parallel instances
4726 // fit without causing spills. All of this is rounded down if necessary to be
4727 // a power of two. We want power of two interleave count to simplify any
4728 // addressing operations or alignment considerations.
4729 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4732 // Don't count the induction variable as interleaved.
4733 if (EnableIndVarRegisterHeur)
4734 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4735 std::max(1U, (R.MaxLocalUsers - 1)));
4737 // Clamp the interleave ranges to reasonable counts.
4738 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4740 // Check if the user has overridden the max.
4742 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4743 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4745 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4746 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4749 // If we did not calculate the cost for VF (because the user selected the VF)
4750 // then we calculate the cost of VF here.
4752 LoopCost = expectedCost(VF);
4754 // Clamp the calculated IC to be between the 1 and the max interleave count
4755 // that the target allows.
4756 if (IC > MaxInterleaveCount)
4757 IC = MaxInterleaveCount;
4761 // Interleave if we vectorized this loop and there is a reduction that could
4762 // benefit from interleaving.
4763 if (VF > 1 && Legal->getReductionVars()->size()) {
4764 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4768 // Note that if we've already vectorized the loop we will have done the
4769 // runtime check and so interleaving won't require further checks.
4770 bool InterleavingRequiresRuntimePointerCheck =
4771 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4773 // We want to interleave small loops in order to reduce the loop overhead and
4774 // potentially expose ILP opportunities.
4775 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4776 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4777 // We assume that the cost overhead is 1 and we use the cost model
4778 // to estimate the cost of the loop and interleave until the cost of the
4779 // loop overhead is about 5% of the cost of the loop.
4781 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4783 // Interleave until store/load ports (estimated by max interleave count) are
4785 unsigned NumStores = Legal->getNumStores();
4786 unsigned NumLoads = Legal->getNumLoads();
4787 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4788 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4790 // If we have a scalar reduction (vector reductions are already dealt with
4791 // by this point), we can increase the critical path length if the loop
4792 // we're interleaving is inside another loop. Limit, by default to 2, so the
4793 // critical path only gets increased by one reduction operation.
4794 if (Legal->getReductionVars()->size() &&
4795 TheLoop->getLoopDepth() > 1) {
4796 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4797 SmallIC = std::min(SmallIC, F);
4798 StoresIC = std::min(StoresIC, F);
4799 LoadsIC = std::min(LoadsIC, F);
4802 if (EnableLoadStoreRuntimeInterleave &&
4803 std::max(StoresIC, LoadsIC) > SmallIC) {
4804 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4805 return std::max(StoresIC, LoadsIC);
4808 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4812 // Interleave if this is a large loop (small loops are already dealt with by
4814 // point) that could benefit from interleaving.
4815 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4816 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4817 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4821 DEBUG(dbgs() << "LV: Not Interleaving.\n");
4825 LoopVectorizationCostModel::RegisterUsage
4826 LoopVectorizationCostModel::calculateRegisterUsage() {
4827 // This function calculates the register usage by measuring the highest number
4828 // of values that are alive at a single location. Obviously, this is a very
4829 // rough estimation. We scan the loop in a topological order in order and
4830 // assign a number to each instruction. We use RPO to ensure that defs are
4831 // met before their users. We assume that each instruction that has in-loop
4832 // users starts an interval. We record every time that an in-loop value is
4833 // used, so we have a list of the first and last occurrences of each
4834 // instruction. Next, we transpose this data structure into a multi map that
4835 // holds the list of intervals that *end* at a specific location. This multi
4836 // map allows us to perform a linear search. We scan the instructions linearly
4837 // and record each time that a new interval starts, by placing it in a set.
4838 // If we find this value in the multi-map then we remove it from the set.
4839 // The max register usage is the maximum size of the set.
4840 // We also search for instructions that are defined outside the loop, but are
4841 // used inside the loop. We need this number separately from the max-interval
4842 // usage number because when we unroll, loop-invariant values do not take
4844 LoopBlocksDFS DFS(TheLoop);
4848 R.NumInstructions = 0;
4850 // Each 'key' in the map opens a new interval. The values
4851 // of the map are the index of the 'last seen' usage of the
4852 // instruction that is the key.
4853 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4854 // Maps instruction to its index.
4855 DenseMap<unsigned, Instruction*> IdxToInstr;
4856 // Marks the end of each interval.
4857 IntervalMap EndPoint;
4858 // Saves the list of instruction indices that are used in the loop.
4859 SmallSet<Instruction*, 8> Ends;
4860 // Saves the list of values that are used in the loop but are
4861 // defined outside the loop, such as arguments and constants.
4862 SmallPtrSet<Value*, 8> LoopInvariants;
4865 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4866 be = DFS.endRPO(); bb != be; ++bb) {
4867 R.NumInstructions += (*bb)->size();
4868 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4870 Instruction *I = it;
4871 IdxToInstr[Index++] = I;
4873 // Save the end location of each USE.
4874 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4875 Value *U = I->getOperand(i);
4876 Instruction *Instr = dyn_cast<Instruction>(U);
4878 // Ignore non-instruction values such as arguments, constants, etc.
4879 if (!Instr) continue;
4881 // If this instruction is outside the loop then record it and continue.
4882 if (!TheLoop->contains(Instr)) {
4883 LoopInvariants.insert(Instr);
4887 // Overwrite previous end points.
4888 EndPoint[Instr] = Index;
4894 // Saves the list of intervals that end with the index in 'key'.
4895 typedef SmallVector<Instruction*, 2> InstrList;
4896 DenseMap<unsigned, InstrList> TransposeEnds;
4898 // Transpose the EndPoints to a list of values that end at each index.
4899 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4901 TransposeEnds[it->second].push_back(it->first);
4903 SmallSet<Instruction*, 8> OpenIntervals;
4904 unsigned MaxUsage = 0;
4907 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4908 for (unsigned int i = 0; i < Index; ++i) {
4909 Instruction *I = IdxToInstr[i];
4910 // Ignore instructions that are never used within the loop.
4911 if (!Ends.count(I)) continue;
4913 // Ignore ephemeral values.
4914 if (EphValues.count(I))
4917 // Remove all of the instructions that end at this location.
4918 InstrList &List = TransposeEnds[i];
4919 for (unsigned int j=0, e = List.size(); j < e; ++j)
4920 OpenIntervals.erase(List[j]);
4922 // Count the number of live interals.
4923 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4925 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4926 OpenIntervals.size() << '\n');
4928 // Add the current instruction to the list of open intervals.
4929 OpenIntervals.insert(I);
4932 unsigned Invariant = LoopInvariants.size();
4933 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4934 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4935 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4937 R.LoopInvariantRegs = Invariant;
4938 R.MaxLocalUsers = MaxUsage;
4942 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4946 for (Loop::block_iterator bb = TheLoop->block_begin(),
4947 be = TheLoop->block_end(); bb != be; ++bb) {
4948 unsigned BlockCost = 0;
4949 BasicBlock *BB = *bb;
4951 // For each instruction in the old loop.
4952 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4953 // Skip dbg intrinsics.
4954 if (isa<DbgInfoIntrinsic>(it))
4957 // Ignore ephemeral values.
4958 if (EphValues.count(it))
4961 unsigned C = getInstructionCost(it, VF);
4963 // Check if we should override the cost.
4964 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4965 C = ForceTargetInstructionCost;
4968 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
4969 VF << " For instruction: " << *it << '\n');
4972 // We assume that if-converted blocks have a 50% chance of being executed.
4973 // When the code is scalar then some of the blocks are avoided due to CF.
4974 // When the code is vectorized we execute all code paths.
4975 if (VF == 1 && Legal->blockNeedsPredication(*bb))
4984 /// \brief Check whether the address computation for a non-consecutive memory
4985 /// access looks like an unlikely candidate for being merged into the indexing
4988 /// We look for a GEP which has one index that is an induction variable and all
4989 /// other indices are loop invariant. If the stride of this access is also
4990 /// within a small bound we decide that this address computation can likely be
4991 /// merged into the addressing mode.
4992 /// In all other cases, we identify the address computation as complex.
4993 static bool isLikelyComplexAddressComputation(Value *Ptr,
4994 LoopVectorizationLegality *Legal,
4995 ScalarEvolution *SE,
4996 const Loop *TheLoop) {
4997 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5001 // We are looking for a gep with all loop invariant indices except for one
5002 // which should be an induction variable.
5003 unsigned NumOperands = Gep->getNumOperands();
5004 for (unsigned i = 1; i < NumOperands; ++i) {
5005 Value *Opd = Gep->getOperand(i);
5006 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5007 !Legal->isInductionVariable(Opd))
5011 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5012 // can likely be merged into the address computation.
5013 unsigned MaxMergeDistance = 64;
5015 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5019 // Check the step is constant.
5020 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5021 // Calculate the pointer stride and check if it is consecutive.
5022 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5026 const APInt &APStepVal = C->getValue()->getValue();
5028 // Huge step value - give up.
5029 if (APStepVal.getBitWidth() > 64)
5032 int64_t StepVal = APStepVal.getSExtValue();
5034 return StepVal > MaxMergeDistance;
5037 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5038 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5044 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5045 // If we know that this instruction will remain uniform, check the cost of
5046 // the scalar version.
5047 if (Legal->isUniformAfterVectorization(I))
5050 Type *RetTy = I->getType();
5051 Type *VectorTy = ToVectorTy(RetTy, VF);
5053 // TODO: We need to estimate the cost of intrinsic calls.
5054 switch (I->getOpcode()) {
5055 case Instruction::GetElementPtr:
5056 // We mark this instruction as zero-cost because the cost of GEPs in
5057 // vectorized code depends on whether the corresponding memory instruction
5058 // is scalarized or not. Therefore, we handle GEPs with the memory
5059 // instruction cost.
5061 case Instruction::Br: {
5062 return TTI.getCFInstrCost(I->getOpcode());
5064 case Instruction::PHI:
5065 //TODO: IF-converted IFs become selects.
5067 case Instruction::Add:
5068 case Instruction::FAdd:
5069 case Instruction::Sub:
5070 case Instruction::FSub:
5071 case Instruction::Mul:
5072 case Instruction::FMul:
5073 case Instruction::UDiv:
5074 case Instruction::SDiv:
5075 case Instruction::FDiv:
5076 case Instruction::URem:
5077 case Instruction::SRem:
5078 case Instruction::FRem:
5079 case Instruction::Shl:
5080 case Instruction::LShr:
5081 case Instruction::AShr:
5082 case Instruction::And:
5083 case Instruction::Or:
5084 case Instruction::Xor: {
5085 // Since we will replace the stride by 1 the multiplication should go away.
5086 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5088 // Certain instructions can be cheaper to vectorize if they have a constant
5089 // second vector operand. One example of this are shifts on x86.
5090 TargetTransformInfo::OperandValueKind Op1VK =
5091 TargetTransformInfo::OK_AnyValue;
5092 TargetTransformInfo::OperandValueKind Op2VK =
5093 TargetTransformInfo::OK_AnyValue;
5094 TargetTransformInfo::OperandValueProperties Op1VP =
5095 TargetTransformInfo::OP_None;
5096 TargetTransformInfo::OperandValueProperties Op2VP =
5097 TargetTransformInfo::OP_None;
5098 Value *Op2 = I->getOperand(1);
5100 // Check for a splat of a constant or for a non uniform vector of constants.
5101 if (isa<ConstantInt>(Op2)) {
5102 ConstantInt *CInt = cast<ConstantInt>(Op2);
5103 if (CInt && CInt->getValue().isPowerOf2())
5104 Op2VP = TargetTransformInfo::OP_PowerOf2;
5105 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5106 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5107 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5108 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5110 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5111 if (CInt && CInt->getValue().isPowerOf2())
5112 Op2VP = TargetTransformInfo::OP_PowerOf2;
5113 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5117 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5120 case Instruction::Select: {
5121 SelectInst *SI = cast<SelectInst>(I);
5122 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5123 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5124 Type *CondTy = SI->getCondition()->getType();
5126 CondTy = VectorType::get(CondTy, VF);
5128 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5130 case Instruction::ICmp:
5131 case Instruction::FCmp: {
5132 Type *ValTy = I->getOperand(0)->getType();
5133 VectorTy = ToVectorTy(ValTy, VF);
5134 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5136 case Instruction::Store:
5137 case Instruction::Load: {
5138 StoreInst *SI = dyn_cast<StoreInst>(I);
5139 LoadInst *LI = dyn_cast<LoadInst>(I);
5140 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5142 VectorTy = ToVectorTy(ValTy, VF);
5144 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5145 unsigned AS = SI ? SI->getPointerAddressSpace() :
5146 LI->getPointerAddressSpace();
5147 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5148 // We add the cost of address computation here instead of with the gep
5149 // instruction because only here we know whether the operation is
5152 return TTI.getAddressComputationCost(VectorTy) +
5153 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5155 // For an interleaved access, calculate the total cost of the whole
5156 // interleave group.
5157 if (Legal->isAccessInterleaved(I)) {
5158 auto Group = Legal->getInterleavedAccessGroup(I);
5159 assert(Group && "Fail to get an interleaved access group.");
5161 // Only calculate the cost once at the insert position.
5162 if (Group->getInsertPos() != I)
5165 unsigned InterleaveFactor = Group->getFactor();
5167 VectorType::get(VectorTy->getVectorElementType(),
5168 VectorTy->getVectorNumElements() * InterleaveFactor);
5170 // Holds the indices of existing members in an interleaved load group.
5171 // An interleaved store group doesn't need this as it dones't allow gaps.
5172 SmallVector<unsigned, 4> Indices;
5174 for (unsigned i = 0; i < InterleaveFactor; i++)
5175 if (Group->getMember(i))
5176 Indices.push_back(i);
5179 // Calculate the cost of the whole interleaved group.
5180 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5181 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5182 Group->getAlignment(), AS);
5184 if (Group->isReverse())
5186 Group->getNumMembers() *
5187 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5189 // FIXME: The interleaved load group with a huge gap could be even more
5190 // expensive than scalar operations. Then we could ignore such group and
5191 // use scalar operations instead.
5195 // Scalarized loads/stores.
5196 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5197 bool Reverse = ConsecutiveStride < 0;
5198 const DataLayout &DL = I->getModule()->getDataLayout();
5199 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5200 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5201 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5202 bool IsComplexComputation =
5203 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5205 // The cost of extracting from the value vector and pointer vector.
5206 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5207 for (unsigned i = 0; i < VF; ++i) {
5208 // The cost of extracting the pointer operand.
5209 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5210 // In case of STORE, the cost of ExtractElement from the vector.
5211 // In case of LOAD, the cost of InsertElement into the returned
5213 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5214 Instruction::InsertElement,
5218 // The cost of the scalar loads/stores.
5219 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5220 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5225 // Wide load/stores.
5226 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5227 if (Legal->isMaskRequired(I))
5228 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5231 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5234 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5238 case Instruction::ZExt:
5239 case Instruction::SExt:
5240 case Instruction::FPToUI:
5241 case Instruction::FPToSI:
5242 case Instruction::FPExt:
5243 case Instruction::PtrToInt:
5244 case Instruction::IntToPtr:
5245 case Instruction::SIToFP:
5246 case Instruction::UIToFP:
5247 case Instruction::Trunc:
5248 case Instruction::FPTrunc:
5249 case Instruction::BitCast: {
5250 // We optimize the truncation of induction variable.
5251 // The cost of these is the same as the scalar operation.
5252 if (I->getOpcode() == Instruction::Trunc &&
5253 Legal->isInductionVariable(I->getOperand(0)))
5254 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5255 I->getOperand(0)->getType());
5257 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5258 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5260 case Instruction::Call: {
5261 bool NeedToScalarize;
5262 CallInst *CI = cast<CallInst>(I);
5263 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5264 if (getIntrinsicIDForCall(CI, TLI))
5265 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5269 // We are scalarizing the instruction. Return the cost of the scalar
5270 // instruction, plus the cost of insert and extract into vector
5271 // elements, times the vector width.
5274 if (!RetTy->isVoidTy() && VF != 1) {
5275 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5277 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5280 // The cost of inserting the results plus extracting each one of the
5282 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5285 // The cost of executing VF copies of the scalar instruction. This opcode
5286 // is unknown. Assume that it is the same as 'mul'.
5287 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5293 char LoopVectorize::ID = 0;
5294 static const char lv_name[] = "Loop Vectorization";
5295 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5296 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5297 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5298 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5299 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5300 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5301 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5302 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5303 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5304 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5305 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5306 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5309 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5310 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5314 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5315 // Check for a store.
5316 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5317 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5319 // Check for a load.
5320 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5321 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5327 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5328 bool IfPredicateStore) {
5329 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5330 // Holds vector parameters or scalars, in case of uniform vals.
5331 SmallVector<VectorParts, 4> Params;
5333 setDebugLocFromInst(Builder, Instr);
5335 // Find all of the vectorized parameters.
5336 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5337 Value *SrcOp = Instr->getOperand(op);
5339 // If we are accessing the old induction variable, use the new one.
5340 if (SrcOp == OldInduction) {
5341 Params.push_back(getVectorValue(SrcOp));
5345 // Try using previously calculated values.
5346 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5348 // If the src is an instruction that appeared earlier in the basic block
5349 // then it should already be vectorized.
5350 if (SrcInst && OrigLoop->contains(SrcInst)) {
5351 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5352 // The parameter is a vector value from earlier.
5353 Params.push_back(WidenMap.get(SrcInst));
5355 // The parameter is a scalar from outside the loop. Maybe even a constant.
5356 VectorParts Scalars;
5357 Scalars.append(UF, SrcOp);
5358 Params.push_back(Scalars);
5362 assert(Params.size() == Instr->getNumOperands() &&
5363 "Invalid number of operands");
5365 // Does this instruction return a value ?
5366 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5368 Value *UndefVec = IsVoidRetTy ? nullptr :
5369 UndefValue::get(Instr->getType());
5370 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5371 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5373 Instruction *InsertPt = Builder.GetInsertPoint();
5374 BasicBlock *IfBlock = Builder.GetInsertBlock();
5375 BasicBlock *CondBlock = nullptr;
5378 Loop *VectorLp = nullptr;
5379 if (IfPredicateStore) {
5380 assert(Instr->getParent()->getSinglePredecessor() &&
5381 "Only support single predecessor blocks");
5382 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5383 Instr->getParent());
5384 VectorLp = LI->getLoopFor(IfBlock);
5385 assert(VectorLp && "Must have a loop for this block");
5388 // For each vector unroll 'part':
5389 for (unsigned Part = 0; Part < UF; ++Part) {
5390 // For each scalar that we create:
5392 // Start an "if (pred) a[i] = ..." block.
5393 Value *Cmp = nullptr;
5394 if (IfPredicateStore) {
5395 if (Cond[Part]->getType()->isVectorTy())
5397 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5398 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5399 ConstantInt::get(Cond[Part]->getType(), 1));
5400 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5401 LoopVectorBody.push_back(CondBlock);
5402 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5403 // Update Builder with newly created basic block.
5404 Builder.SetInsertPoint(InsertPt);
5407 Instruction *Cloned = Instr->clone();
5409 Cloned->setName(Instr->getName() + ".cloned");
5410 // Replace the operands of the cloned instructions with extracted scalars.
5411 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5412 Value *Op = Params[op][Part];
5413 Cloned->setOperand(op, Op);
5416 // Place the cloned scalar in the new loop.
5417 Builder.Insert(Cloned);
5419 // If the original scalar returns a value we need to place it in a vector
5420 // so that future users will be able to use it.
5422 VecResults[Part] = Cloned;
5425 if (IfPredicateStore) {
5426 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5427 LoopVectorBody.push_back(NewIfBlock);
5428 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5429 Builder.SetInsertPoint(InsertPt);
5430 ReplaceInstWithInst(IfBlock->getTerminator(),
5431 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
5432 IfBlock = NewIfBlock;
5437 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5438 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5439 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5441 return scalarizeInstruction(Instr, IfPredicateStore);
5444 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5448 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5452 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5453 // When unrolling and the VF is 1, we only need to add a simple scalar.
5454 Type *ITy = Val->getType();
5455 assert(!ITy->isVectorTy() && "Val must be a scalar");
5456 Constant *C = ConstantInt::get(ITy, StartIdx);
5457 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");