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;
223 class LoopVectorizationRequirements;
225 /// \brief This modifies LoopAccessReport to initialize message with
226 /// loop-vectorizer-specific part.
227 class VectorizationReport : public LoopAccessReport {
229 VectorizationReport(Instruction *I = nullptr)
230 : LoopAccessReport("loop not vectorized: ", I) {}
232 /// \brief This allows promotion of the loop-access analysis report into the
233 /// loop-vectorizer report. It modifies the message to add the
234 /// loop-vectorizer-specific part of the message.
235 explicit VectorizationReport(const LoopAccessReport &R)
236 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
240 /// A helper function for converting Scalar types to vector types.
241 /// If the incoming type is void, we return void. If the VF is 1, we return
243 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
244 if (Scalar->isVoidTy() || VF == 1)
246 return VectorType::get(Scalar, VF);
249 /// InnerLoopVectorizer vectorizes loops which contain only one basic
250 /// block to a specified vectorization factor (VF).
251 /// This class performs the widening of scalars into vectors, or multiple
252 /// scalars. This class also implements the following features:
253 /// * It inserts an epilogue loop for handling loops that don't have iteration
254 /// counts that are known to be a multiple of the vectorization factor.
255 /// * It handles the code generation for reduction variables.
256 /// * Scalarization (implementation using scalars) of un-vectorizable
258 /// InnerLoopVectorizer does not perform any vectorization-legality
259 /// checks, and relies on the caller to check for the different legality
260 /// aspects. The InnerLoopVectorizer relies on the
261 /// LoopVectorizationLegality class to provide information about the induction
262 /// and reduction variables that were found to a given vectorization factor.
263 class InnerLoopVectorizer {
265 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
266 DominatorTree *DT, const TargetLibraryInfo *TLI,
267 const TargetTransformInfo *TTI, unsigned VecWidth,
268 unsigned UnrollFactor)
269 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
270 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
271 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
272 Legal(nullptr), AddedSafetyChecks(false) {}
274 // Perform the actual loop widening (vectorization).
275 void vectorize(LoopVectorizationLegality *L) {
277 // Create a new empty loop. Unlink the old loop and connect the new one.
279 // Widen each instruction in the old loop to a new one in the new loop.
280 // Use the Legality module to find the induction and reduction variables.
282 // Register the new loop and update the analysis passes.
286 // Return true if any runtime check is added.
287 bool IsSafetyChecksAdded() {
288 return AddedSafetyChecks;
291 virtual ~InnerLoopVectorizer() {}
294 /// A small list of PHINodes.
295 typedef SmallVector<PHINode*, 4> PhiVector;
296 /// When we unroll loops we have multiple vector values for each scalar.
297 /// This data structure holds the unrolled and vectorized values that
298 /// originated from one scalar instruction.
299 typedef SmallVector<Value*, 2> VectorParts;
301 // When we if-convert we need to create edge masks. We have to cache values
302 // so that we don't end up with exponential recursion/IR.
303 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
304 VectorParts> EdgeMaskCache;
306 /// \brief Add checks for strides that were assumed to be 1.
308 /// Returns the last check instruction and the first check instruction in the
309 /// pair as (first, last).
310 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
312 /// Create an empty loop, based on the loop ranges of the old loop.
313 void createEmptyLoop();
314 /// Copy and widen the instructions from the old loop.
315 virtual void vectorizeLoop();
317 /// \brief The Loop exit block may have single value PHI nodes where the
318 /// incoming value is 'Undef'. While vectorizing we only handled real values
319 /// that were defined inside the loop. Here we fix the 'undef case'.
323 /// A helper function that computes the predicate of the block BB, assuming
324 /// that the header block of the loop is set to True. It returns the *entry*
325 /// mask for the block BB.
326 VectorParts createBlockInMask(BasicBlock *BB);
327 /// A helper function that computes the predicate of the edge between SRC
329 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
331 /// A helper function to vectorize a single BB within the innermost loop.
332 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
334 /// Vectorize a single PHINode in a block. This method handles the induction
335 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
336 /// arbitrary length vectors.
337 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
338 unsigned UF, unsigned VF, PhiVector *PV);
340 /// Insert the new loop to the loop hierarchy and pass manager
341 /// and update the analysis passes.
342 void updateAnalysis();
344 /// This instruction is un-vectorizable. Implement it as a sequence
345 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
346 /// scalarized instruction behind an if block predicated on the control
347 /// dependence of the instruction.
348 virtual void scalarizeInstruction(Instruction *Instr,
349 bool IfPredicateStore=false);
351 /// Vectorize Load and Store instructions,
352 virtual void vectorizeMemoryInstruction(Instruction *Instr);
354 /// Create a broadcast instruction. This method generates a broadcast
355 /// instruction (shuffle) for loop invariant values and for the induction
356 /// value. If this is the induction variable then we extend it to N, N+1, ...
357 /// this is needed because each iteration in the loop corresponds to a SIMD
359 virtual Value *getBroadcastInstrs(Value *V);
361 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
362 /// to each vector element of Val. The sequence starts at StartIndex.
363 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
365 /// When we go over instructions in the basic block we rely on previous
366 /// values within the current basic block or on loop invariant values.
367 /// When we widen (vectorize) values we place them in the map. If the values
368 /// are not within the map, they have to be loop invariant, so we simply
369 /// broadcast them into a vector.
370 VectorParts &getVectorValue(Value *V);
372 /// Try to vectorize the interleaved access group that \p Instr belongs to.
373 void vectorizeInterleaveGroup(Instruction *Instr);
375 /// Generate a shuffle sequence that will reverse the vector Vec.
376 virtual Value *reverseVector(Value *Vec);
378 /// This is a helper class that holds the vectorizer state. It maps scalar
379 /// instructions to vector instructions. When the code is 'unrolled' then
380 /// then a single scalar value is mapped to multiple vector parts. The parts
381 /// are stored in the VectorPart type.
383 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
385 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
387 /// \return True if 'Key' is saved in the Value Map.
388 bool has(Value *Key) const { return MapStorage.count(Key); }
390 /// Initializes a new entry in the map. Sets all of the vector parts to the
391 /// save value in 'Val'.
392 /// \return A reference to a vector with splat values.
393 VectorParts &splat(Value *Key, Value *Val) {
394 VectorParts &Entry = MapStorage[Key];
395 Entry.assign(UF, Val);
399 ///\return A reference to the value that is stored at 'Key'.
400 VectorParts &get(Value *Key) {
401 VectorParts &Entry = MapStorage[Key];
404 assert(Entry.size() == UF);
409 /// The unroll factor. Each entry in the map stores this number of vector
413 /// Map storage. We use std::map and not DenseMap because insertions to a
414 /// dense map invalidates its iterators.
415 std::map<Value *, VectorParts> MapStorage;
418 /// The original loop.
420 /// Scev analysis to use.
428 /// Target Library Info.
429 const TargetLibraryInfo *TLI;
430 /// Target Transform Info.
431 const TargetTransformInfo *TTI;
433 /// The vectorization SIMD factor to use. Each vector will have this many
438 /// The vectorization unroll factor to use. Each scalar is vectorized to this
439 /// many different vector instructions.
442 /// The builder that we use
445 // --- Vectorization state ---
447 /// The vector-loop preheader.
448 BasicBlock *LoopVectorPreHeader;
449 /// The scalar-loop preheader.
450 BasicBlock *LoopScalarPreHeader;
451 /// Middle Block between the vector and the scalar.
452 BasicBlock *LoopMiddleBlock;
453 ///The ExitBlock of the scalar loop.
454 BasicBlock *LoopExitBlock;
455 ///The vector loop body.
456 SmallVector<BasicBlock *, 4> LoopVectorBody;
457 ///The scalar loop body.
458 BasicBlock *LoopScalarBody;
459 /// A list of all bypass blocks. The first block is the entry of the loop.
460 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
462 /// The new Induction variable which was added to the new block.
464 /// The induction variable of the old basic block.
465 PHINode *OldInduction;
466 /// Holds the extended (to the widest induction type) start index.
468 /// Maps scalars to widened vectors.
470 EdgeMaskCache MaskCache;
472 LoopVectorizationLegality *Legal;
474 // Record whether runtime check is added.
475 bool AddedSafetyChecks;
478 class InnerLoopUnroller : public InnerLoopVectorizer {
480 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
481 DominatorTree *DT, const TargetLibraryInfo *TLI,
482 const TargetTransformInfo *TTI, unsigned UnrollFactor)
483 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
486 void scalarizeInstruction(Instruction *Instr,
487 bool IfPredicateStore = false) override;
488 void vectorizeMemoryInstruction(Instruction *Instr) override;
489 Value *getBroadcastInstrs(Value *V) override;
490 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
491 Value *reverseVector(Value *Vec) override;
494 /// \brief Look for a meaningful debug location on the instruction or it's
496 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
501 if (I->getDebugLoc() != Empty)
504 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
505 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
506 if (OpInst->getDebugLoc() != Empty)
513 /// \brief Set the debug location in the builder using the debug location in the
515 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
516 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
517 B.SetCurrentDebugLocation(Inst->getDebugLoc());
519 B.SetCurrentDebugLocation(DebugLoc());
523 /// \return string containing a file name and a line # for the given loop.
524 static std::string getDebugLocString(const Loop *L) {
527 raw_string_ostream OS(Result);
528 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
529 LoopDbgLoc.print(OS);
531 // Just print the module name.
532 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
539 /// \brief Propagate known metadata from one instruction to another.
540 static void propagateMetadata(Instruction *To, const Instruction *From) {
541 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
542 From->getAllMetadataOtherThanDebugLoc(Metadata);
544 for (auto M : Metadata) {
545 unsigned Kind = M.first;
547 // These are safe to transfer (this is safe for TBAA, even when we
548 // if-convert, because should that metadata have had a control dependency
549 // on the condition, and thus actually aliased with some other
550 // non-speculated memory access when the condition was false, this would be
551 // caught by the runtime overlap checks).
552 if (Kind != LLVMContext::MD_tbaa &&
553 Kind != LLVMContext::MD_alias_scope &&
554 Kind != LLVMContext::MD_noalias &&
555 Kind != LLVMContext::MD_fpmath)
558 To->setMetadata(Kind, M.second);
562 /// \brief Propagate known metadata from one instruction to a vector of others.
563 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
565 if (Instruction *I = dyn_cast<Instruction>(V))
566 propagateMetadata(I, From);
569 /// \brief The group of interleaved loads/stores sharing the same stride and
570 /// close to each other.
572 /// Each member in this group has an index starting from 0, and the largest
573 /// index should be less than interleaved factor, which is equal to the absolute
574 /// value of the access's stride.
576 /// E.g. An interleaved load group of factor 4:
577 /// for (unsigned i = 0; i < 1024; i+=4) {
578 /// a = A[i]; // Member of index 0
579 /// b = A[i+1]; // Member of index 1
580 /// d = A[i+3]; // Member of index 3
584 /// An interleaved store group of factor 4:
585 /// for (unsigned i = 0; i < 1024; i+=4) {
587 /// A[i] = a; // Member of index 0
588 /// A[i+1] = b; // Member of index 1
589 /// A[i+2] = c; // Member of index 2
590 /// A[i+3] = d; // Member of index 3
593 /// Note: the interleaved load group could have gaps (missing members), but
594 /// the interleaved store group doesn't allow gaps.
595 class InterleaveGroup {
597 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
598 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
599 assert(Align && "The alignment should be non-zero");
601 Factor = std::abs(Stride);
602 assert(Factor > 1 && "Invalid interleave factor");
604 Reverse = Stride < 0;
608 bool isReverse() const { return Reverse; }
609 unsigned getFactor() const { return Factor; }
610 unsigned getAlignment() const { return Align; }
611 unsigned getNumMembers() const { return Members.size(); }
613 /// \brief Try to insert a new member \p Instr with index \p Index and
614 /// alignment \p NewAlign. The index is related to the leader and it could be
615 /// negative if it is the new leader.
617 /// \returns false if the instruction doesn't belong to the group.
618 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
619 assert(NewAlign && "The new member's alignment should be non-zero");
621 int Key = Index + SmallestKey;
623 // Skip if there is already a member with the same index.
624 if (Members.count(Key))
627 if (Key > LargestKey) {
628 // The largest index is always less than the interleave factor.
629 if (Index >= static_cast<int>(Factor))
633 } else if (Key < SmallestKey) {
634 // The largest index is always less than the interleave factor.
635 if (LargestKey - Key >= static_cast<int>(Factor))
641 // It's always safe to select the minimum alignment.
642 Align = std::min(Align, NewAlign);
643 Members[Key] = Instr;
647 /// \brief Get the member with the given index \p Index
649 /// \returns nullptr if contains no such member.
650 Instruction *getMember(unsigned Index) const {
651 int Key = SmallestKey + Index;
652 if (!Members.count(Key))
655 return Members.find(Key)->second;
658 /// \brief Get the index for the given member. Unlike the key in the member
659 /// map, the index starts from 0.
660 unsigned getIndex(Instruction *Instr) const {
661 for (auto I : Members)
662 if (I.second == Instr)
663 return I.first - SmallestKey;
665 llvm_unreachable("InterleaveGroup contains no such member");
668 Instruction *getInsertPos() const { return InsertPos; }
669 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
672 unsigned Factor; // Interleave Factor.
675 DenseMap<int, Instruction *> Members;
679 // To avoid breaking dependences, vectorized instructions of an interleave
680 // group should be inserted at either the first load or the last store in
683 // E.g. %even = load i32 // Insert Position
684 // %add = add i32 %even // Use of %even
688 // %odd = add i32 // Def of %odd
689 // store i32 %odd // Insert Position
690 Instruction *InsertPos;
693 /// \brief Drive the analysis of interleaved memory accesses in the loop.
695 /// Use this class to analyze interleaved accesses only when we can vectorize
696 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
697 /// on interleaved accesses is unsafe.
699 /// The analysis collects interleave groups and records the relationships
700 /// between the member and the group in a map.
701 class InterleavedAccessInfo {
703 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
704 : SE(SE), TheLoop(L), DT(DT) {}
706 ~InterleavedAccessInfo() {
707 SmallSet<InterleaveGroup *, 4> DelSet;
708 // Avoid releasing a pointer twice.
709 for (auto &I : InterleaveGroupMap)
710 DelSet.insert(I.second);
711 for (auto *Ptr : DelSet)
715 /// \brief Analyze the interleaved accesses and collect them in interleave
716 /// groups. Substitute symbolic strides using \p Strides.
717 void analyzeInterleaving(const ValueToValueMap &Strides);
719 /// \brief Check if \p Instr belongs to any interleave group.
720 bool isInterleaved(Instruction *Instr) const {
721 return InterleaveGroupMap.count(Instr);
724 /// \brief Get the interleave group that \p Instr belongs to.
726 /// \returns nullptr if doesn't have such group.
727 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
728 if (InterleaveGroupMap.count(Instr))
729 return InterleaveGroupMap.find(Instr)->second;
738 /// Holds the relationships between the members and the interleave group.
739 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
741 /// \brief The descriptor for a strided memory access.
742 struct StrideDescriptor {
743 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
745 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
747 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
749 int Stride; // The access's stride. It is negative for a reverse access.
750 const SCEV *Scev; // The scalar expression of this access
751 unsigned Size; // The size of the memory object.
752 unsigned Align; // The alignment of this access.
755 /// \brief Create a new interleave group with the given instruction \p Instr,
756 /// stride \p Stride and alignment \p Align.
758 /// \returns the newly created interleave group.
759 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
761 assert(!InterleaveGroupMap.count(Instr) &&
762 "Already in an interleaved access group");
763 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
764 return InterleaveGroupMap[Instr];
767 /// \brief Release the group and remove all the relationships.
768 void releaseGroup(InterleaveGroup *Group) {
769 for (unsigned i = 0; i < Group->getFactor(); i++)
770 if (Instruction *Member = Group->getMember(i))
771 InterleaveGroupMap.erase(Member);
776 /// \brief Collect all the accesses with a constant stride in program order.
777 void collectConstStridedAccesses(
778 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
779 const ValueToValueMap &Strides);
782 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
783 /// to what vectorization factor.
784 /// This class does not look at the profitability of vectorization, only the
785 /// legality. This class has two main kinds of checks:
786 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
787 /// will change the order of memory accesses in a way that will change the
788 /// correctness of the program.
789 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
790 /// checks for a number of different conditions, such as the availability of a
791 /// single induction variable, that all types are supported and vectorize-able,
792 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
793 /// This class is also used by InnerLoopVectorizer for identifying
794 /// induction variable and the different reduction variables.
795 class LoopVectorizationLegality {
797 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
798 TargetLibraryInfo *TLI, AliasAnalysis *AA,
799 Function *F, const TargetTransformInfo *TTI,
800 LoopAccessAnalysis *LAA,
801 LoopVectorizationRequirements *R)
802 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
803 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
804 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
807 /// This enum represents the kinds of inductions that we support.
809 IK_NoInduction, ///< Not an induction variable.
810 IK_IntInduction, ///< Integer induction variable. Step = C.
811 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
814 /// A struct for saving information about induction variables.
815 struct InductionInfo {
816 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
817 : StartValue(Start), IK(K), StepValue(Step) {
818 assert(IK != IK_NoInduction && "Not an induction");
819 assert(StartValue && "StartValue is null");
820 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
821 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
822 "StartValue is not a pointer for pointer induction");
823 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
824 "StartValue is not an integer for integer induction");
825 assert(StepValue->getType()->isIntegerTy() &&
826 "StepValue is not an integer");
829 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
831 /// Get the consecutive direction. Returns:
832 /// 0 - unknown or non-consecutive.
833 /// 1 - consecutive and increasing.
834 /// -1 - consecutive and decreasing.
835 int getConsecutiveDirection() const {
836 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
837 return StepValue->getSExtValue();
841 /// Compute the transformed value of Index at offset StartValue using step
843 /// For integer induction, returns StartValue + Index * StepValue.
844 /// For pointer induction, returns StartValue[Index * StepValue].
845 /// FIXME: The newly created binary instructions should contain nsw/nuw
846 /// flags, which can be found from the original scalar operations.
847 Value *transform(IRBuilder<> &B, Value *Index) const {
849 case IK_IntInduction:
850 assert(Index->getType() == StartValue->getType() &&
851 "Index type does not match StartValue type");
852 if (StepValue->isMinusOne())
853 return B.CreateSub(StartValue, Index);
854 if (!StepValue->isOne())
855 Index = B.CreateMul(Index, StepValue);
856 return B.CreateAdd(StartValue, Index);
858 case IK_PtrInduction:
859 assert(Index->getType() == StepValue->getType() &&
860 "Index type does not match StepValue type");
861 if (StepValue->isMinusOne())
862 Index = B.CreateNeg(Index);
863 else if (!StepValue->isOne())
864 Index = B.CreateMul(Index, StepValue);
865 return B.CreateGEP(nullptr, StartValue, Index);
870 llvm_unreachable("invalid enum");
874 TrackingVH<Value> StartValue;
878 ConstantInt *StepValue;
881 /// ReductionList contains the reduction descriptors for all
882 /// of the reductions that were found in the loop.
883 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
885 /// InductionList saves induction variables and maps them to the
886 /// induction descriptor.
887 typedef MapVector<PHINode*, InductionInfo> InductionList;
889 /// Returns true if it is legal to vectorize this loop.
890 /// This does not mean that it is profitable to vectorize this
891 /// loop, only that it is legal to do so.
894 /// Returns the Induction variable.
895 PHINode *getInduction() { return Induction; }
897 /// Returns the reduction variables found in the loop.
898 ReductionList *getReductionVars() { return &Reductions; }
900 /// Returns the induction variables found in the loop.
901 InductionList *getInductionVars() { return &Inductions; }
903 /// Returns the widest induction type.
904 Type *getWidestInductionType() { return WidestIndTy; }
906 /// Returns True if V is an induction variable in this loop.
907 bool isInductionVariable(const Value *V);
909 /// Return true if the block BB needs to be predicated in order for the loop
910 /// to be vectorized.
911 bool blockNeedsPredication(BasicBlock *BB);
913 /// Check if this pointer is consecutive when vectorizing. This happens
914 /// when the last index of the GEP is the induction variable, or that the
915 /// pointer itself is an induction variable.
916 /// This check allows us to vectorize A[idx] into a wide load/store.
918 /// 0 - Stride is unknown or non-consecutive.
919 /// 1 - Address is consecutive.
920 /// -1 - Address is consecutive, and decreasing.
921 int isConsecutivePtr(Value *Ptr);
923 /// Returns true if the value V is uniform within the loop.
924 bool isUniform(Value *V);
926 /// Returns true if this instruction will remain scalar after vectorization.
927 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
929 /// Returns the information that we collected about runtime memory check.
930 const RuntimePointerChecking *getRuntimePointerChecking() const {
931 return LAI->getRuntimePointerChecking();
934 const LoopAccessInfo *getLAI() const {
938 /// \brief Check if \p Instr belongs to any interleaved access group.
939 bool isAccessInterleaved(Instruction *Instr) {
940 return InterleaveInfo.isInterleaved(Instr);
943 /// \brief Get the interleaved access group that \p Instr belongs to.
944 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
945 return InterleaveInfo.getInterleaveGroup(Instr);
948 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
950 bool hasStride(Value *V) { return StrideSet.count(V); }
951 bool mustCheckStrides() { return !StrideSet.empty(); }
952 SmallPtrSet<Value *, 8>::iterator strides_begin() {
953 return StrideSet.begin();
955 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
957 /// Returns true if the target machine supports masked store operation
958 /// for the given \p DataType and kind of access to \p Ptr.
959 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
960 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
962 /// Returns true if the target machine supports masked load operation
963 /// for the given \p DataType and kind of access to \p Ptr.
964 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
965 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
967 /// Returns true if vector representation of the instruction \p I
969 bool isMaskRequired(const Instruction* I) {
970 return (MaskedOp.count(I) != 0);
972 unsigned getNumStores() const {
973 return LAI->getNumStores();
975 unsigned getNumLoads() const {
976 return LAI->getNumLoads();
978 unsigned getNumPredStores() const {
979 return NumPredStores;
982 /// Check if a single basic block loop is vectorizable.
983 /// At this point we know that this is a loop with a constant trip count
984 /// and we only need to check individual instructions.
985 bool canVectorizeInstrs();
987 /// When we vectorize loops we may change the order in which
988 /// we read and write from memory. This method checks if it is
989 /// legal to vectorize the code, considering only memory constrains.
990 /// Returns true if the loop is vectorizable
991 bool canVectorizeMemory();
993 /// Return true if we can vectorize this loop using the IF-conversion
995 bool canVectorizeWithIfConvert();
997 /// Collect the variables that need to stay uniform after vectorization.
998 void collectLoopUniforms();
1000 /// Return true if all of the instructions in the block can be speculatively
1001 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1002 /// and we know that we can read from them without segfault.
1003 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1005 /// Returns the induction kind of Phi and record the step. This function may
1006 /// return NoInduction if the PHI is not an induction variable.
1007 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
1009 /// \brief Collect memory access with loop invariant strides.
1011 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1013 void collectStridedAccess(Value *LoadOrStoreInst);
1015 /// Report an analysis message to assist the user in diagnosing loops that are
1016 /// not vectorized. These are handled as LoopAccessReport rather than
1017 /// VectorizationReport because the << operator of VectorizationReport returns
1018 /// LoopAccessReport.
1019 void emitAnalysis(const LoopAccessReport &Message) {
1020 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1023 unsigned NumPredStores;
1025 /// The loop that we evaluate.
1028 ScalarEvolution *SE;
1029 /// Target Library Info.
1030 TargetLibraryInfo *TLI;
1032 Function *TheFunction;
1033 /// Target Transform Info
1034 const TargetTransformInfo *TTI;
1037 // LoopAccess analysis.
1038 LoopAccessAnalysis *LAA;
1039 // And the loop-accesses info corresponding to this loop. This pointer is
1040 // null until canVectorizeMemory sets it up.
1041 const LoopAccessInfo *LAI;
1043 /// The interleave access information contains groups of interleaved accesses
1044 /// with the same stride and close to each other.
1045 InterleavedAccessInfo InterleaveInfo;
1047 // --- vectorization state --- //
1049 /// Holds the integer induction variable. This is the counter of the
1052 /// Holds the reduction variables.
1053 ReductionList Reductions;
1054 /// Holds all of the induction variables that we found in the loop.
1055 /// Notice that inductions don't need to start at zero and that induction
1056 /// variables can be pointers.
1057 InductionList Inductions;
1058 /// Holds the widest induction type encountered.
1061 /// Allowed outside users. This holds the reduction
1062 /// vars which can be accessed from outside the loop.
1063 SmallPtrSet<Value*, 4> AllowedExit;
1064 /// This set holds the variables which are known to be uniform after
1066 SmallPtrSet<Instruction*, 4> Uniforms;
1068 /// Can we assume the absence of NaNs.
1069 bool HasFunNoNaNAttr;
1071 /// Vectorization requirements that will go through late-evaluation.
1072 LoopVectorizationRequirements *Requirements;
1074 ValueToValueMap Strides;
1075 SmallPtrSet<Value *, 8> StrideSet;
1077 /// While vectorizing these instructions we have to generate a
1078 /// call to the appropriate masked intrinsic
1079 SmallPtrSet<const Instruction*, 8> MaskedOp;
1082 /// LoopVectorizationCostModel - estimates the expected speedups due to
1084 /// In many cases vectorization is not profitable. This can happen because of
1085 /// a number of reasons. In this class we mainly attempt to predict the
1086 /// expected speedup/slowdowns due to the supported instruction set. We use the
1087 /// TargetTransformInfo to query the different backends for the cost of
1088 /// different operations.
1089 class LoopVectorizationCostModel {
1091 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1092 LoopVectorizationLegality *Legal,
1093 const TargetTransformInfo &TTI,
1094 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1095 const Function *F, const LoopVectorizeHints *Hints)
1096 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1097 TheFunction(F), Hints(Hints) {
1098 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
1101 /// Information about vectorization costs
1102 struct VectorizationFactor {
1103 unsigned Width; // Vector width with best cost
1104 unsigned Cost; // Cost of the loop with that width
1106 /// \return The most profitable vectorization factor and the cost of that VF.
1107 /// This method checks every power of two up to VF. If UserVF is not ZERO
1108 /// then this vectorization factor will be selected if vectorization is
1110 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1112 /// \return The size (in bits) of the widest type in the code that
1113 /// needs to be vectorized. We ignore values that remain scalar such as
1114 /// 64 bit loop indices.
1115 unsigned getWidestType();
1117 /// \return The desired interleave count.
1118 /// If interleave count has been specified by metadata it will be returned.
1119 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1120 /// are the selected vectorization factor and the cost of the selected VF.
1121 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1124 /// \return The most profitable unroll factor.
1125 /// This method finds the best unroll-factor based on register pressure and
1126 /// other parameters. VF and LoopCost are the selected vectorization factor
1127 /// and the cost of the selected VF.
1128 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1131 /// \brief A struct that represents some properties of the register usage
1133 struct RegisterUsage {
1134 /// Holds the number of loop invariant values that are used in the loop.
1135 unsigned LoopInvariantRegs;
1136 /// Holds the maximum number of concurrent live intervals in the loop.
1137 unsigned MaxLocalUsers;
1138 /// Holds the number of instructions in the loop.
1139 unsigned NumInstructions;
1142 /// \return information about the register usage of the loop.
1143 RegisterUsage calculateRegisterUsage();
1146 /// Returns the expected execution cost. The unit of the cost does
1147 /// not matter because we use the 'cost' units to compare different
1148 /// vector widths. The cost that is returned is *not* normalized by
1149 /// the factor width.
1150 unsigned expectedCost(unsigned VF);
1152 /// Returns the execution time cost of an instruction for a given vector
1153 /// width. Vector width of one means scalar.
1154 unsigned getInstructionCost(Instruction *I, unsigned VF);
1156 /// Returns whether the instruction is a load or store and will be a emitted
1157 /// as a vector operation.
1158 bool isConsecutiveLoadOrStore(Instruction *I);
1160 /// Report an analysis message to assist the user in diagnosing loops that are
1161 /// not vectorized. These are handled as LoopAccessReport rather than
1162 /// VectorizationReport because the << operator of VectorizationReport returns
1163 /// LoopAccessReport.
1164 void emitAnalysis(const LoopAccessReport &Message) {
1165 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1168 /// Values used only by @llvm.assume calls.
1169 SmallPtrSet<const Value *, 32> EphValues;
1171 /// The loop that we evaluate.
1174 ScalarEvolution *SE;
1175 /// Loop Info analysis.
1177 /// Vectorization legality.
1178 LoopVectorizationLegality *Legal;
1179 /// Vector target information.
1180 const TargetTransformInfo &TTI;
1181 /// Target Library Info.
1182 const TargetLibraryInfo *TLI;
1183 const Function *TheFunction;
1184 // Loop Vectorize Hint.
1185 const LoopVectorizeHints *Hints;
1188 /// Utility class for getting and setting loop vectorizer hints in the form
1189 /// of loop metadata.
1190 /// This class keeps a number of loop annotations locally (as member variables)
1191 /// and can, upon request, write them back as metadata on the loop. It will
1192 /// initially scan the loop for existing metadata, and will update the local
1193 /// values based on information in the loop.
1194 /// We cannot write all values to metadata, as the mere presence of some info,
1195 /// for example 'force', means a decision has been made. So, we need to be
1196 /// careful NOT to add them if the user hasn't specifically asked so.
1197 class LoopVectorizeHints {
1204 /// Hint - associates name and validation with the hint value.
1207 unsigned Value; // This may have to change for non-numeric values.
1210 Hint(const char * Name, unsigned Value, HintKind Kind)
1211 : Name(Name), Value(Value), Kind(Kind) { }
1213 bool validate(unsigned Val) {
1216 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1218 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1226 /// Vectorization width.
1228 /// Vectorization interleave factor.
1230 /// Vectorization forced
1233 /// Return the loop metadata prefix.
1234 static StringRef Prefix() { return "llvm.loop."; }
1238 FK_Undefined = -1, ///< Not selected.
1239 FK_Disabled = 0, ///< Forcing disabled.
1240 FK_Enabled = 1, ///< Forcing enabled.
1243 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1244 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1246 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1247 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1249 // Populate values with existing loop metadata.
1250 getHintsFromMetadata();
1252 // force-vector-interleave overrides DisableInterleaving.
1253 if (VectorizerParams::isInterleaveForced())
1254 Interleave.Value = VectorizerParams::VectorizationInterleave;
1256 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1257 << "LV: Interleaving disabled by the pass manager\n");
1260 /// Mark the loop L as already vectorized by setting the width to 1.
1261 void setAlreadyVectorized() {
1262 Width.Value = Interleave.Value = 1;
1263 Hint Hints[] = {Width, Interleave};
1264 writeHintsToMetadata(Hints);
1267 /// Dumps all the hint information.
1268 std::string emitRemark() const {
1269 VectorizationReport R;
1270 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1271 R << "vectorization is explicitly disabled";
1273 R << "use -Rpass-analysis=loop-vectorize for more info";
1274 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1275 R << " (Force=true";
1276 if (Width.Value != 0)
1277 R << ", Vector Width=" << Width.Value;
1278 if (Interleave.Value != 0)
1279 R << ", Interleave Count=" << Interleave.Value;
1287 unsigned getWidth() const { return Width.Value; }
1288 unsigned getInterleave() const { return Interleave.Value; }
1289 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1292 /// Find hints specified in the loop metadata and update local values.
1293 void getHintsFromMetadata() {
1294 MDNode *LoopID = TheLoop->getLoopID();
1298 // First operand should refer to the loop id itself.
1299 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1300 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1302 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1303 const MDString *S = nullptr;
1304 SmallVector<Metadata *, 4> Args;
1306 // The expected hint is either a MDString or a MDNode with the first
1307 // operand a MDString.
1308 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1309 if (!MD || MD->getNumOperands() == 0)
1311 S = dyn_cast<MDString>(MD->getOperand(0));
1312 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1313 Args.push_back(MD->getOperand(i));
1315 S = dyn_cast<MDString>(LoopID->getOperand(i));
1316 assert(Args.size() == 0 && "too many arguments for MDString");
1322 // Check if the hint starts with the loop metadata prefix.
1323 StringRef Name = S->getString();
1324 if (Args.size() == 1)
1325 setHint(Name, Args[0]);
1329 /// Checks string hint with one operand and set value if valid.
1330 void setHint(StringRef Name, Metadata *Arg) {
1331 if (!Name.startswith(Prefix()))
1333 Name = Name.substr(Prefix().size(), StringRef::npos);
1335 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1337 unsigned Val = C->getZExtValue();
1339 Hint *Hints[] = {&Width, &Interleave, &Force};
1340 for (auto H : Hints) {
1341 if (Name == H->Name) {
1342 if (H->validate(Val))
1345 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1351 /// Create a new hint from name / value pair.
1352 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1353 LLVMContext &Context = TheLoop->getHeader()->getContext();
1354 Metadata *MDs[] = {MDString::get(Context, Name),
1355 ConstantAsMetadata::get(
1356 ConstantInt::get(Type::getInt32Ty(Context), V))};
1357 return MDNode::get(Context, MDs);
1360 /// Matches metadata with hint name.
1361 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1362 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1366 for (auto H : HintTypes)
1367 if (Name->getString().endswith(H.Name))
1372 /// Sets current hints into loop metadata, keeping other values intact.
1373 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1374 if (HintTypes.size() == 0)
1377 // Reserve the first element to LoopID (see below).
1378 SmallVector<Metadata *, 4> MDs(1);
1379 // If the loop already has metadata, then ignore the existing operands.
1380 MDNode *LoopID = TheLoop->getLoopID();
1382 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1383 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1384 // If node in update list, ignore old value.
1385 if (!matchesHintMetadataName(Node, HintTypes))
1386 MDs.push_back(Node);
1390 // Now, add the missing hints.
1391 for (auto H : HintTypes)
1392 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1394 // Replace current metadata node with new one.
1395 LLVMContext &Context = TheLoop->getHeader()->getContext();
1396 MDNode *NewLoopID = MDNode::get(Context, MDs);
1397 // Set operand 0 to refer to the loop id itself.
1398 NewLoopID->replaceOperandWith(0, NewLoopID);
1400 TheLoop->setLoopID(NewLoopID);
1403 /// The loop these hints belong to.
1404 const Loop *TheLoop;
1407 static void emitMissedWarning(Function *F, Loop *L,
1408 const LoopVectorizeHints &LH) {
1409 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1410 L->getStartLoc(), LH.emitRemark());
1412 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1413 if (LH.getWidth() != 1)
1414 emitLoopVectorizeWarning(
1415 F->getContext(), *F, L->getStartLoc(),
1416 "failed explicitly specified loop vectorization");
1417 else if (LH.getInterleave() != 1)
1418 emitLoopInterleaveWarning(
1419 F->getContext(), *F, L->getStartLoc(),
1420 "failed explicitly specified loop interleaving");
1424 /// \brief This holds vectorization requirements that must be verified late in
1425 /// the process. The requirements are set by legalize and costmodel. Once
1426 /// vectorization has been determined to be possible and profitable the
1427 /// requirements can be verified by looking for metadata or compiler options.
1428 /// For example, some loops require FP commutativity which is only allowed if
1429 /// vectorization is explicitly specified or if the fast-math compiler option
1430 /// has been provided.
1431 /// Late evaluation of these requirements allows helpful diagnostics to be
1432 /// composed that tells the user what need to be done to vectorize the loop. For
1433 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1434 /// evaluation should be used only when diagnostics can generated that can be
1435 /// followed by a non-expert user.
1436 class LoopVectorizationRequirements {
1438 LoopVectorizationRequirements()
1439 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1441 void addUnsafeAlgebraInst(Instruction *I) {
1442 // First unsafe algebra instruction.
1443 if (!UnsafeAlgebraInst)
1444 UnsafeAlgebraInst = I;
1447 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1449 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1450 bool failed = false;
1452 if (UnsafeAlgebraInst &&
1453 Hints.getForce() == LoopVectorizeHints::FK_Undefined &&
1454 Hints.getWidth() == 0) {
1455 emitOptimizationRemarkAnalysisFPCommute(
1456 F->getContext(), DEBUG_TYPE, *F, UnsafeAlgebraInst->getDebugLoc(),
1457 VectorizationReport() << "vectorization requires changes in the "
1458 "order of operations, however IEEE 754 "
1459 "floating-point operations are not "
1464 if (NumRuntimePointerChecks >
1465 VectorizerParams::RuntimeMemoryCheckThreshold) {
1466 emitOptimizationRemarkAnalysisAliasing(
1467 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1468 VectorizationReport()
1469 << "cannot prove pointers refer to independent arrays in memory. "
1470 "The loop requires "
1471 << NumRuntimePointerChecks
1472 << " runtime independence checks to vectorize the loop, but that "
1473 "would exceed the limit of "
1474 << VectorizerParams::RuntimeMemoryCheckThreshold << " checks");
1475 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1483 unsigned NumRuntimePointerChecks;
1484 Instruction *UnsafeAlgebraInst;
1487 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1489 return V.push_back(&L);
1491 for (Loop *InnerL : L)
1492 addInnerLoop(*InnerL, V);
1495 /// The LoopVectorize Pass.
1496 struct LoopVectorize : public FunctionPass {
1497 /// Pass identification, replacement for typeid
1500 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1502 DisableUnrolling(NoUnrolling),
1503 AlwaysVectorize(AlwaysVectorize) {
1504 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1507 ScalarEvolution *SE;
1509 TargetTransformInfo *TTI;
1511 BlockFrequencyInfo *BFI;
1512 TargetLibraryInfo *TLI;
1514 AssumptionCache *AC;
1515 LoopAccessAnalysis *LAA;
1516 bool DisableUnrolling;
1517 bool AlwaysVectorize;
1519 BlockFrequency ColdEntryFreq;
1521 bool runOnFunction(Function &F) override {
1522 SE = &getAnalysis<ScalarEvolution>();
1523 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1524 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1525 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1526 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1527 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1528 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1529 AA = &getAnalysis<AliasAnalysis>();
1530 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1531 LAA = &getAnalysis<LoopAccessAnalysis>();
1533 // Compute some weights outside of the loop over the loops. Compute this
1534 // using a BranchProbability to re-use its scaling math.
1535 const BranchProbability ColdProb(1, 5); // 20%
1536 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1539 // 1. the target claims to have no vector registers, and
1540 // 2. interleaving won't help ILP.
1542 // The second condition is necessary because, even if the target has no
1543 // vector registers, loop vectorization may still enable scalar
1545 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1548 // Build up a worklist of inner-loops to vectorize. This is necessary as
1549 // the act of vectorizing or partially unrolling a loop creates new loops
1550 // and can invalidate iterators across the loops.
1551 SmallVector<Loop *, 8> Worklist;
1554 addInnerLoop(*L, Worklist);
1556 LoopsAnalyzed += Worklist.size();
1558 // Now walk the identified inner loops.
1559 bool Changed = false;
1560 while (!Worklist.empty())
1561 Changed |= processLoop(Worklist.pop_back_val());
1563 // Process each loop nest in the function.
1567 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1568 SmallVector<Metadata *, 4> MDs;
1569 // Reserve first location for self reference to the LoopID metadata node.
1570 MDs.push_back(nullptr);
1571 bool IsUnrollMetadata = false;
1572 MDNode *LoopID = L->getLoopID();
1574 // First find existing loop unrolling disable metadata.
1575 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1576 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1578 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1580 S && S->getString().startswith("llvm.loop.unroll.disable");
1582 MDs.push_back(LoopID->getOperand(i));
1586 if (!IsUnrollMetadata) {
1587 // Add runtime unroll disable metadata.
1588 LLVMContext &Context = L->getHeader()->getContext();
1589 SmallVector<Metadata *, 1> DisableOperands;
1590 DisableOperands.push_back(
1591 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1592 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1593 MDs.push_back(DisableNode);
1594 MDNode *NewLoopID = MDNode::get(Context, MDs);
1595 // Set operand 0 to refer to the loop id itself.
1596 NewLoopID->replaceOperandWith(0, NewLoopID);
1597 L->setLoopID(NewLoopID);
1601 bool processLoop(Loop *L) {
1602 assert(L->empty() && "Only process inner loops.");
1605 const std::string DebugLocStr = getDebugLocString(L);
1608 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1609 << L->getHeader()->getParent()->getName() << "\" from "
1610 << DebugLocStr << "\n");
1612 LoopVectorizeHints Hints(L, DisableUnrolling);
1614 DEBUG(dbgs() << "LV: Loop hints:"
1616 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1618 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1620 : "?")) << " width=" << Hints.getWidth()
1621 << " unroll=" << Hints.getInterleave() << "\n");
1623 // Function containing loop
1624 Function *F = L->getHeader()->getParent();
1626 // Looking at the diagnostic output is the only way to determine if a loop
1627 // was vectorized (other than looking at the IR or machine code), so it
1628 // is important to generate an optimization remark for each loop. Most of
1629 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1630 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1631 // less verbose reporting vectorized loops and unvectorized loops that may
1632 // benefit from vectorization, respectively.
1634 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1635 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1636 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1637 L->getStartLoc(), Hints.emitRemark());
1641 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1642 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1643 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1644 L->getStartLoc(), Hints.emitRemark());
1648 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1649 // FIXME: Add a separate metadata to indicate when the loop has already
1650 // been vectorized instead of setting width and count to 1.
1651 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1652 // FIXME: Add interleave.disable metadata. This will allow
1653 // vectorize.disable to be used without disabling the pass and errors
1654 // to differentiate between disabled vectorization and a width of 1.
1655 emitOptimizationRemarkAnalysis(
1656 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1657 "loop not vectorized: vectorization and interleaving are explicitly "
1658 "disabled, or vectorize width and interleave count are both set to "
1663 // Check the loop for a trip count threshold:
1664 // do not vectorize loops with a tiny trip count.
1665 const unsigned TC = SE->getSmallConstantTripCount(L);
1666 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1667 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1668 << "This loop is not worth vectorizing.");
1669 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1670 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1672 DEBUG(dbgs() << "\n");
1673 emitOptimizationRemarkAnalysis(
1674 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1675 "vectorization is not beneficial and is not explicitly forced");
1680 // Check if it is legal to vectorize the loop.
1681 LoopVectorizationRequirements Requirements;
1682 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1684 if (!LVL.canVectorize()) {
1685 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1686 emitMissedWarning(F, L, Hints);
1690 // Use the cost model.
1691 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints);
1693 // Check the function attributes to find out if this function should be
1694 // optimized for size.
1695 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1696 // FIXME: Use Function::optForSize().
1697 F->hasFnAttribute(Attribute::OptimizeForSize);
1699 // Compute the weighted frequency of this loop being executed and see if it
1700 // is less than 20% of the function entry baseline frequency. Note that we
1701 // always have a canonical loop here because we think we *can* vectoriez.
1702 // FIXME: This is hidden behind a flag due to pervasive problems with
1703 // exactly what block frequency models.
1704 if (LoopVectorizeWithBlockFrequency) {
1705 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1706 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1707 LoopEntryFreq < ColdEntryFreq)
1711 // Check the function attributes to see if implicit floats are allowed.a
1712 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1713 // an integer loop and the vector instructions selected are purely integer
1714 // vector instructions?
1715 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1716 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1717 "attribute is used.\n");
1718 emitOptimizationRemarkAnalysis(
1719 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1720 "loop not vectorized due to NoImplicitFloat attribute");
1721 emitMissedWarning(F, L, Hints);
1725 // Select the optimal vectorization factor.
1726 const LoopVectorizationCostModel::VectorizationFactor VF =
1727 CM.selectVectorizationFactor(OptForSize);
1729 // Select the interleave count.
1730 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1732 // Get user interleave count.
1733 unsigned UserIC = Hints.getInterleave();
1735 // Identify the diagnostic messages that should be produced.
1736 std::string VecDiagMsg, IntDiagMsg;
1737 bool VectorizeLoop = true, InterleaveLoop = true;
1739 if (Requirements.doesNotMeet(F, L, Hints)) {
1740 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1742 emitMissedWarning(F, L, Hints);
1746 if (VF.Width == 1) {
1747 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1749 "the cost-model indicates that vectorization is not beneficial";
1750 VectorizeLoop = false;
1753 if (IC == 1 && UserIC <= 1) {
1754 // Tell the user interleaving is not beneficial.
1755 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1757 "the cost-model indicates that interleaving is not beneficial";
1758 InterleaveLoop = false;
1761 " and is explicitly disabled or interleave count is set to 1";
1762 } else if (IC > 1 && UserIC == 1) {
1763 // Tell the user interleaving is beneficial, but it explicitly disabled.
1765 << "LV: Interleaving is beneficial but is explicitly disabled.");
1766 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1767 "but is explicitly disabled or interleave count is set to 1";
1768 InterleaveLoop = false;
1771 // Override IC if user provided an interleave count.
1772 IC = UserIC > 0 ? UserIC : IC;
1774 // Emit diagnostic messages, if any.
1775 if (!VectorizeLoop && !InterleaveLoop) {
1776 // Do not vectorize or interleaving the loop.
1777 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1778 L->getStartLoc(), VecDiagMsg);
1779 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1780 L->getStartLoc(), IntDiagMsg);
1782 } else if (!VectorizeLoop && InterleaveLoop) {
1783 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1784 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1785 L->getStartLoc(), VecDiagMsg);
1786 } else if (VectorizeLoop && !InterleaveLoop) {
1787 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1788 << DebugLocStr << '\n');
1789 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1790 L->getStartLoc(), IntDiagMsg);
1791 } else if (VectorizeLoop && InterleaveLoop) {
1792 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1793 << DebugLocStr << '\n');
1794 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1797 if (!VectorizeLoop) {
1798 assert(IC > 1 && "interleave count should not be 1 or 0");
1799 // If we decided that it is not legal to vectorize the loop then
1801 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC);
1802 Unroller.vectorize(&LVL);
1804 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1805 Twine("interleaved loop (interleaved count: ") +
1808 // If we decided that it is *legal* to vectorize the loop then do it.
1809 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC);
1813 // Add metadata to disable runtime unrolling scalar loop when there's no
1814 // runtime check about strides and memory. Because at this situation,
1815 // scalar loop is rarely used not worthy to be unrolled.
1816 if (!LB.IsSafetyChecksAdded())
1817 AddRuntimeUnrollDisableMetaData(L);
1819 // Report the vectorization decision.
1820 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1821 Twine("vectorized loop (vectorization width: ") +
1822 Twine(VF.Width) + ", interleaved count: " +
1826 // Mark the loop as already vectorized to avoid vectorizing again.
1827 Hints.setAlreadyVectorized();
1829 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1833 void getAnalysisUsage(AnalysisUsage &AU) const override {
1834 AU.addRequired<AssumptionCacheTracker>();
1835 AU.addRequiredID(LoopSimplifyID);
1836 AU.addRequiredID(LCSSAID);
1837 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1838 AU.addRequired<DominatorTreeWrapperPass>();
1839 AU.addRequired<LoopInfoWrapperPass>();
1840 AU.addRequired<ScalarEvolution>();
1841 AU.addRequired<TargetTransformInfoWrapperPass>();
1842 AU.addRequired<AliasAnalysis>();
1843 AU.addRequired<LoopAccessAnalysis>();
1844 AU.addPreserved<LoopInfoWrapperPass>();
1845 AU.addPreserved<DominatorTreeWrapperPass>();
1846 AU.addPreserved<AliasAnalysis>();
1851 } // end anonymous namespace
1853 //===----------------------------------------------------------------------===//
1854 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1855 // LoopVectorizationCostModel.
1856 //===----------------------------------------------------------------------===//
1858 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1859 // We need to place the broadcast of invariant variables outside the loop.
1860 Instruction *Instr = dyn_cast<Instruction>(V);
1862 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1863 Instr->getParent()) != LoopVectorBody.end());
1864 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1866 // Place the code for broadcasting invariant variables in the new preheader.
1867 IRBuilder<>::InsertPointGuard Guard(Builder);
1869 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1871 // Broadcast the scalar into all locations in the vector.
1872 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1877 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1879 assert(Val->getType()->isVectorTy() && "Must be a vector");
1880 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1881 "Elem must be an integer");
1882 assert(Step->getType() == Val->getType()->getScalarType() &&
1883 "Step has wrong type");
1884 // Create the types.
1885 Type *ITy = Val->getType()->getScalarType();
1886 VectorType *Ty = cast<VectorType>(Val->getType());
1887 int VLen = Ty->getNumElements();
1888 SmallVector<Constant*, 8> Indices;
1890 // Create a vector of consecutive numbers from zero to VF.
1891 for (int i = 0; i < VLen; ++i)
1892 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1894 // Add the consecutive indices to the vector value.
1895 Constant *Cv = ConstantVector::get(Indices);
1896 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1897 Step = Builder.CreateVectorSplat(VLen, Step);
1898 assert(Step->getType() == Val->getType() && "Invalid step vec");
1899 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1900 // which can be found from the original scalar operations.
1901 Step = Builder.CreateMul(Cv, Step);
1902 return Builder.CreateAdd(Val, Step, "induction");
1905 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1906 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1907 // Make sure that the pointer does not point to structs.
1908 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1911 // If this value is a pointer induction variable we know it is consecutive.
1912 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1913 if (Phi && Inductions.count(Phi)) {
1914 InductionInfo II = Inductions[Phi];
1915 return II.getConsecutiveDirection();
1918 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1922 unsigned NumOperands = Gep->getNumOperands();
1923 Value *GpPtr = Gep->getPointerOperand();
1924 // If this GEP value is a consecutive pointer induction variable and all of
1925 // the indices are constant then we know it is consecutive. We can
1926 Phi = dyn_cast<PHINode>(GpPtr);
1927 if (Phi && Inductions.count(Phi)) {
1929 // Make sure that the pointer does not point to structs.
1930 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1931 if (GepPtrType->getElementType()->isAggregateType())
1934 // Make sure that all of the index operands are loop invariant.
1935 for (unsigned i = 1; i < NumOperands; ++i)
1936 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1939 InductionInfo II = Inductions[Phi];
1940 return II.getConsecutiveDirection();
1943 unsigned InductionOperand = getGEPInductionOperand(Gep);
1945 // Check that all of the gep indices are uniform except for our induction
1947 for (unsigned i = 0; i != NumOperands; ++i)
1948 if (i != InductionOperand &&
1949 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1952 // We can emit wide load/stores only if the last non-zero index is the
1953 // induction variable.
1954 const SCEV *Last = nullptr;
1955 if (!Strides.count(Gep))
1956 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1958 // Because of the multiplication by a stride we can have a s/zext cast.
1959 // We are going to replace this stride by 1 so the cast is safe to ignore.
1961 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1962 // %0 = trunc i64 %indvars.iv to i32
1963 // %mul = mul i32 %0, %Stride1
1964 // %idxprom = zext i32 %mul to i64 << Safe cast.
1965 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1967 Last = replaceSymbolicStrideSCEV(SE, Strides,
1968 Gep->getOperand(InductionOperand), Gep);
1969 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1971 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1975 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1976 const SCEV *Step = AR->getStepRecurrence(*SE);
1978 // The memory is consecutive because the last index is consecutive
1979 // and all other indices are loop invariant.
1982 if (Step->isAllOnesValue())
1989 bool LoopVectorizationLegality::isUniform(Value *V) {
1990 return LAI->isUniform(V);
1993 InnerLoopVectorizer::VectorParts&
1994 InnerLoopVectorizer::getVectorValue(Value *V) {
1995 assert(V != Induction && "The new induction variable should not be used.");
1996 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1998 // If we have a stride that is replaced by one, do it here.
1999 if (Legal->hasStride(V))
2000 V = ConstantInt::get(V->getType(), 1);
2002 // If we have this scalar in the map, return it.
2003 if (WidenMap.has(V))
2004 return WidenMap.get(V);
2006 // If this scalar is unknown, assume that it is a constant or that it is
2007 // loop invariant. Broadcast V and save the value for future uses.
2008 Value *B = getBroadcastInstrs(V);
2009 return WidenMap.splat(V, B);
2012 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2013 assert(Vec->getType()->isVectorTy() && "Invalid type");
2014 SmallVector<Constant*, 8> ShuffleMask;
2015 for (unsigned i = 0; i < VF; ++i)
2016 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2018 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2019 ConstantVector::get(ShuffleMask),
2023 // Get a mask to interleave \p NumVec vectors into a wide vector.
2024 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2025 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2026 // <0, 4, 1, 5, 2, 6, 3, 7>
2027 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2029 SmallVector<Constant *, 16> Mask;
2030 for (unsigned i = 0; i < VF; i++)
2031 for (unsigned j = 0; j < NumVec; j++)
2032 Mask.push_back(Builder.getInt32(j * VF + i));
2034 return ConstantVector::get(Mask);
2037 // Get the strided mask starting from index \p Start.
2038 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2039 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2040 unsigned Stride, unsigned VF) {
2041 SmallVector<Constant *, 16> Mask;
2042 for (unsigned i = 0; i < VF; i++)
2043 Mask.push_back(Builder.getInt32(Start + i * Stride));
2045 return ConstantVector::get(Mask);
2048 // Get a mask of two parts: The first part consists of sequential integers
2049 // starting from 0, The second part consists of UNDEFs.
2050 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2051 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2052 unsigned NumUndef) {
2053 SmallVector<Constant *, 16> Mask;
2054 for (unsigned i = 0; i < NumInt; i++)
2055 Mask.push_back(Builder.getInt32(i));
2057 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2058 for (unsigned i = 0; i < NumUndef; i++)
2059 Mask.push_back(Undef);
2061 return ConstantVector::get(Mask);
2064 // Concatenate two vectors with the same element type. The 2nd vector should
2065 // not have more elements than the 1st vector. If the 2nd vector has less
2066 // elements, extend it with UNDEFs.
2067 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2069 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2070 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2071 assert(VecTy1 && VecTy2 &&
2072 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2073 "Expect two vectors with the same element type");
2075 unsigned NumElts1 = VecTy1->getNumElements();
2076 unsigned NumElts2 = VecTy2->getNumElements();
2077 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2079 if (NumElts1 > NumElts2) {
2080 // Extend with UNDEFs.
2082 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2083 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2086 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2087 return Builder.CreateShuffleVector(V1, V2, Mask);
2090 // Concatenate vectors in the given list. All vectors have the same type.
2091 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2092 ArrayRef<Value *> InputList) {
2093 unsigned NumVec = InputList.size();
2094 assert(NumVec > 1 && "Should be at least two vectors");
2096 SmallVector<Value *, 8> ResList;
2097 ResList.append(InputList.begin(), InputList.end());
2099 SmallVector<Value *, 8> TmpList;
2100 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2101 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2102 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2103 "Only the last vector may have a different type");
2105 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2108 // Push the last vector if the total number of vectors is odd.
2109 if (NumVec % 2 != 0)
2110 TmpList.push_back(ResList[NumVec - 1]);
2113 NumVec = ResList.size();
2114 } while (NumVec > 1);
2119 // Try to vectorize the interleave group that \p Instr belongs to.
2121 // E.g. Translate following interleaved load group (factor = 3):
2122 // for (i = 0; i < N; i+=3) {
2123 // R = Pic[i]; // Member of index 0
2124 // G = Pic[i+1]; // Member of index 1
2125 // B = Pic[i+2]; // Member of index 2
2126 // ... // do something to R, G, B
2129 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2130 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2131 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2132 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2134 // Or translate following interleaved store group (factor = 3):
2135 // for (i = 0; i < N; i+=3) {
2136 // ... do something to R, G, B
2137 // Pic[i] = R; // Member of index 0
2138 // Pic[i+1] = G; // Member of index 1
2139 // Pic[i+2] = B; // Member of index 2
2142 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2143 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2144 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2145 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2146 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2147 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2148 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2149 assert(Group && "Fail to get an interleaved access group.");
2151 // Skip if current instruction is not the insert position.
2152 if (Instr != Group->getInsertPos())
2155 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2156 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2157 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2159 // Prepare for the vector type of the interleaved load/store.
2160 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2161 unsigned InterleaveFactor = Group->getFactor();
2162 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2163 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2165 // Prepare for the new pointers.
2166 setDebugLocFromInst(Builder, Ptr);
2167 VectorParts &PtrParts = getVectorValue(Ptr);
2168 SmallVector<Value *, 2> NewPtrs;
2169 unsigned Index = Group->getIndex(Instr);
2170 for (unsigned Part = 0; Part < UF; Part++) {
2171 // Extract the pointer for current instruction from the pointer vector. A
2172 // reverse access uses the pointer in the last lane.
2173 Value *NewPtr = Builder.CreateExtractElement(
2175 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2177 // Notice current instruction could be any index. Need to adjust the address
2178 // to the member of index 0.
2180 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2181 // b = A[i]; // Member of index 0
2182 // Current pointer is pointed to A[i+1], adjust it to A[i].
2184 // E.g. A[i+1] = a; // Member of index 1
2185 // A[i] = b; // Member of index 0
2186 // A[i+2] = c; // Member of index 2 (Current instruction)
2187 // Current pointer is pointed to A[i+2], adjust it to A[i].
2188 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2190 // Cast to the vector pointer type.
2191 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2194 setDebugLocFromInst(Builder, Instr);
2195 Value *UndefVec = UndefValue::get(VecTy);
2197 // Vectorize the interleaved load group.
2199 for (unsigned Part = 0; Part < UF; Part++) {
2200 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2201 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2203 for (unsigned i = 0; i < InterleaveFactor; i++) {
2204 Instruction *Member = Group->getMember(i);
2206 // Skip the gaps in the group.
2210 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2211 Value *StridedVec = Builder.CreateShuffleVector(
2212 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2214 // If this member has different type, cast the result type.
2215 if (Member->getType() != ScalarTy) {
2216 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2217 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2220 VectorParts &Entry = WidenMap.get(Member);
2222 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2225 propagateMetadata(NewLoadInstr, Instr);
2230 // The sub vector type for current instruction.
2231 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2233 // Vectorize the interleaved store group.
2234 for (unsigned Part = 0; Part < UF; Part++) {
2235 // Collect the stored vector from each member.
2236 SmallVector<Value *, 4> StoredVecs;
2237 for (unsigned i = 0; i < InterleaveFactor; i++) {
2238 // Interleaved store group doesn't allow a gap, so each index has a member
2239 Instruction *Member = Group->getMember(i);
2240 assert(Member && "Fail to get a member from an interleaved store group");
2243 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2244 if (Group->isReverse())
2245 StoredVec = reverseVector(StoredVec);
2247 // If this member has different type, cast it to an unified type.
2248 if (StoredVec->getType() != SubVT)
2249 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2251 StoredVecs.push_back(StoredVec);
2254 // Concatenate all vectors into a wide vector.
2255 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2257 // Interleave the elements in the wide vector.
2258 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2259 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2262 Instruction *NewStoreInstr =
2263 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2264 propagateMetadata(NewStoreInstr, Instr);
2268 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2269 // Attempt to issue a wide load.
2270 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2271 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2273 assert((LI || SI) && "Invalid Load/Store instruction");
2275 // Try to vectorize the interleave group if this access is interleaved.
2276 if (Legal->isAccessInterleaved(Instr))
2277 return vectorizeInterleaveGroup(Instr);
2279 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2280 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2281 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2282 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2283 // An alignment of 0 means target abi alignment. We need to use the scalar's
2284 // target abi alignment in such a case.
2285 const DataLayout &DL = Instr->getModule()->getDataLayout();
2287 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2288 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2289 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2290 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2292 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2293 !Legal->isMaskRequired(SI))
2294 return scalarizeInstruction(Instr, true);
2296 if (ScalarAllocatedSize != VectorElementSize)
2297 return scalarizeInstruction(Instr);
2299 // If the pointer is loop invariant or if it is non-consecutive,
2300 // scalarize the load.
2301 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2302 bool Reverse = ConsecutiveStride < 0;
2303 bool UniformLoad = LI && Legal->isUniform(Ptr);
2304 if (!ConsecutiveStride || UniformLoad)
2305 return scalarizeInstruction(Instr);
2307 Constant *Zero = Builder.getInt32(0);
2308 VectorParts &Entry = WidenMap.get(Instr);
2310 // Handle consecutive loads/stores.
2311 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2312 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2313 setDebugLocFromInst(Builder, Gep);
2314 Value *PtrOperand = Gep->getPointerOperand();
2315 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2316 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2318 // Create the new GEP with the new induction variable.
2319 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2320 Gep2->setOperand(0, FirstBasePtr);
2321 Gep2->setName("gep.indvar.base");
2322 Ptr = Builder.Insert(Gep2);
2324 setDebugLocFromInst(Builder, Gep);
2325 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2326 OrigLoop) && "Base ptr must be invariant");
2328 // The last index does not have to be the induction. It can be
2329 // consecutive and be a function of the index. For example A[I+1];
2330 unsigned NumOperands = Gep->getNumOperands();
2331 unsigned InductionOperand = getGEPInductionOperand(Gep);
2332 // Create the new GEP with the new induction variable.
2333 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2335 for (unsigned i = 0; i < NumOperands; ++i) {
2336 Value *GepOperand = Gep->getOperand(i);
2337 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2339 // Update last index or loop invariant instruction anchored in loop.
2340 if (i == InductionOperand ||
2341 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2342 assert((i == InductionOperand ||
2343 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2344 "Must be last index or loop invariant");
2346 VectorParts &GEPParts = getVectorValue(GepOperand);
2347 Value *Index = GEPParts[0];
2348 Index = Builder.CreateExtractElement(Index, Zero);
2349 Gep2->setOperand(i, Index);
2350 Gep2->setName("gep.indvar.idx");
2353 Ptr = Builder.Insert(Gep2);
2355 // Use the induction element ptr.
2356 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2357 setDebugLocFromInst(Builder, Ptr);
2358 VectorParts &PtrVal = getVectorValue(Ptr);
2359 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2362 VectorParts Mask = createBlockInMask(Instr->getParent());
2365 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2366 "We do not allow storing to uniform addresses");
2367 setDebugLocFromInst(Builder, SI);
2368 // We don't want to update the value in the map as it might be used in
2369 // another expression. So don't use a reference type for "StoredVal".
2370 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2372 for (unsigned Part = 0; Part < UF; ++Part) {
2373 // Calculate the pointer for the specific unroll-part.
2375 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2378 // If we store to reverse consecutive memory locations then we need
2379 // to reverse the order of elements in the stored value.
2380 StoredVal[Part] = reverseVector(StoredVal[Part]);
2381 // If the address is consecutive but reversed, then the
2382 // wide store needs to start at the last vector element.
2383 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2384 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2385 Mask[Part] = reverseVector(Mask[Part]);
2388 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2389 DataTy->getPointerTo(AddressSpace));
2392 if (Legal->isMaskRequired(SI))
2393 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2396 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2397 propagateMetadata(NewSI, SI);
2403 assert(LI && "Must have a load instruction");
2404 setDebugLocFromInst(Builder, LI);
2405 for (unsigned Part = 0; Part < UF; ++Part) {
2406 // Calculate the pointer for the specific unroll-part.
2408 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2411 // If the address is consecutive but reversed, then the
2412 // wide load needs to start at the last vector element.
2413 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2414 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2415 Mask[Part] = reverseVector(Mask[Part]);
2419 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2420 DataTy->getPointerTo(AddressSpace));
2421 if (Legal->isMaskRequired(LI))
2422 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2423 UndefValue::get(DataTy),
2424 "wide.masked.load");
2426 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2427 propagateMetadata(NewLI, LI);
2428 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2432 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2433 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2434 // Holds vector parameters or scalars, in case of uniform vals.
2435 SmallVector<VectorParts, 4> Params;
2437 setDebugLocFromInst(Builder, Instr);
2439 // Find all of the vectorized parameters.
2440 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2441 Value *SrcOp = Instr->getOperand(op);
2443 // If we are accessing the old induction variable, use the new one.
2444 if (SrcOp == OldInduction) {
2445 Params.push_back(getVectorValue(SrcOp));
2449 // Try using previously calculated values.
2450 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2452 // If the src is an instruction that appeared earlier in the basic block
2453 // then it should already be vectorized.
2454 if (SrcInst && OrigLoop->contains(SrcInst)) {
2455 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2456 // The parameter is a vector value from earlier.
2457 Params.push_back(WidenMap.get(SrcInst));
2459 // The parameter is a scalar from outside the loop. Maybe even a constant.
2460 VectorParts Scalars;
2461 Scalars.append(UF, SrcOp);
2462 Params.push_back(Scalars);
2466 assert(Params.size() == Instr->getNumOperands() &&
2467 "Invalid number of operands");
2469 // Does this instruction return a value ?
2470 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2472 Value *UndefVec = IsVoidRetTy ? nullptr :
2473 UndefValue::get(VectorType::get(Instr->getType(), VF));
2474 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2475 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2477 Instruction *InsertPt = Builder.GetInsertPoint();
2478 BasicBlock *IfBlock = Builder.GetInsertBlock();
2479 BasicBlock *CondBlock = nullptr;
2482 Loop *VectorLp = nullptr;
2483 if (IfPredicateStore) {
2484 assert(Instr->getParent()->getSinglePredecessor() &&
2485 "Only support single predecessor blocks");
2486 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2487 Instr->getParent());
2488 VectorLp = LI->getLoopFor(IfBlock);
2489 assert(VectorLp && "Must have a loop for this block");
2492 // For each vector unroll 'part':
2493 for (unsigned Part = 0; Part < UF; ++Part) {
2494 // For each scalar that we create:
2495 for (unsigned Width = 0; Width < VF; ++Width) {
2498 Value *Cmp = nullptr;
2499 if (IfPredicateStore) {
2500 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2501 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2502 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2503 LoopVectorBody.push_back(CondBlock);
2504 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
2505 // Update Builder with newly created basic block.
2506 Builder.SetInsertPoint(InsertPt);
2509 Instruction *Cloned = Instr->clone();
2511 Cloned->setName(Instr->getName() + ".cloned");
2512 // Replace the operands of the cloned instructions with extracted scalars.
2513 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2514 Value *Op = Params[op][Part];
2515 // Param is a vector. Need to extract the right lane.
2516 if (Op->getType()->isVectorTy())
2517 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2518 Cloned->setOperand(op, Op);
2521 // Place the cloned scalar in the new loop.
2522 Builder.Insert(Cloned);
2524 // If the original scalar returns a value we need to place it in a vector
2525 // so that future users will be able to use it.
2527 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2528 Builder.getInt32(Width));
2530 if (IfPredicateStore) {
2531 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2532 LoopVectorBody.push_back(NewIfBlock);
2533 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
2534 Builder.SetInsertPoint(InsertPt);
2535 ReplaceInstWithInst(IfBlock->getTerminator(),
2536 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
2537 IfBlock = NewIfBlock;
2543 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2547 if (Instruction *I = dyn_cast<Instruction>(V))
2548 return I->getParent() == Loc->getParent() ? I : nullptr;
2552 std::pair<Instruction *, Instruction *>
2553 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2554 Instruction *tnullptr = nullptr;
2555 if (!Legal->mustCheckStrides())
2556 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2558 IRBuilder<> ChkBuilder(Loc);
2561 Value *Check = nullptr;
2562 Instruction *FirstInst = nullptr;
2563 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2564 SE = Legal->strides_end();
2566 Value *Ptr = stripIntegerCast(*SI);
2567 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2569 // Store the first instruction we create.
2570 FirstInst = getFirstInst(FirstInst, C, Loc);
2572 Check = ChkBuilder.CreateOr(Check, C);
2577 // We have to do this trickery because the IRBuilder might fold the check to a
2578 // constant expression in which case there is no Instruction anchored in a
2580 LLVMContext &Ctx = Loc->getContext();
2581 Instruction *TheCheck =
2582 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2583 ChkBuilder.Insert(TheCheck, "stride.not.one");
2584 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2586 return std::make_pair(FirstInst, TheCheck);
2589 void InnerLoopVectorizer::createEmptyLoop() {
2591 In this function we generate a new loop. The new loop will contain
2592 the vectorized instructions while the old loop will continue to run the
2595 [ ] <-- Back-edge taken count overflow check.
2598 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2601 || [ ] <-- vector pre header.
2605 || [ ]_| <-- vector loop.
2608 | >[ ] <--- middle-block.
2611 -|- >[ ] <--- new preheader.
2615 | [ ]_| <-- old scalar loop to handle remainder.
2618 >[ ] <-- exit block.
2622 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2623 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2624 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2625 assert(VectorPH && "Invalid loop structure");
2626 assert(ExitBlock && "Must have an exit block");
2628 // Some loops have a single integer induction variable, while other loops
2629 // don't. One example is c++ iterators that often have multiple pointer
2630 // induction variables. In the code below we also support a case where we
2631 // don't have a single induction variable.
2632 OldInduction = Legal->getInduction();
2633 Type *IdxTy = Legal->getWidestInductionType();
2635 // Find the loop boundaries.
2636 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2637 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2639 // The exit count might have the type of i64 while the phi is i32. This can
2640 // happen if we have an induction variable that is sign extended before the
2641 // compare. The only way that we get a backedge taken count is that the
2642 // induction variable was signed and as such will not overflow. In such a case
2643 // truncation is legal.
2644 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2645 IdxTy->getPrimitiveSizeInBits())
2646 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2648 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2649 // Get the total trip count from the count by adding 1.
2650 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2651 SE->getConstant(BackedgeTakeCount->getType(), 1));
2653 const DataLayout &DL = OldBasicBlock->getModule()->getDataLayout();
2655 // Expand the trip count and place the new instructions in the preheader.
2656 // Notice that the pre-header does not change, only the loop body.
2657 SCEVExpander Exp(*SE, DL, "induction");
2659 // We need to test whether the backedge-taken count is uint##_max. Adding one
2660 // to it will cause overflow and an incorrect loop trip count in the vector
2661 // body. In case of overflow we want to directly jump to the scalar remainder
2663 Value *BackedgeCount =
2664 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2665 VectorPH->getTerminator());
2666 if (BackedgeCount->getType()->isPointerTy())
2667 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2668 "backedge.ptrcnt.to.int",
2669 VectorPH->getTerminator());
2670 Instruction *CheckBCOverflow =
2671 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2672 Constant::getAllOnesValue(BackedgeCount->getType()),
2673 "backedge.overflow", VectorPH->getTerminator());
2675 // The loop index does not have to start at Zero. Find the original start
2676 // value from the induction PHI node. If we don't have an induction variable
2677 // then we know that it starts at zero.
2678 Builder.SetInsertPoint(VectorPH->getTerminator());
2679 Value *StartIdx = ExtendedIdx =
2681 ? Builder.CreateZExt(OldInduction->getIncomingValueForBlock(VectorPH),
2683 : ConstantInt::get(IdxTy, 0);
2685 // Count holds the overall loop count (N).
2686 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2687 VectorPH->getTerminator());
2689 LoopBypassBlocks.push_back(VectorPH);
2691 // Split the single block loop into the two loop structure described above.
2692 BasicBlock *VecBody =
2693 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2694 BasicBlock *MiddleBlock =
2695 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2696 BasicBlock *ScalarPH =
2697 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2699 // Create and register the new vector loop.
2700 Loop* Lp = new Loop();
2701 Loop *ParentLoop = OrigLoop->getParentLoop();
2703 // Insert the new loop into the loop nest and register the new basic blocks
2704 // before calling any utilities such as SCEV that require valid LoopInfo.
2706 ParentLoop->addChildLoop(Lp);
2707 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2708 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2710 LI->addTopLevelLoop(Lp);
2712 Lp->addBasicBlockToLoop(VecBody, *LI);
2714 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2716 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2718 // Generate the induction variable.
2719 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2720 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2721 // The loop step is equal to the vectorization factor (num of SIMD elements)
2722 // times the unroll factor (num of SIMD instructions).
2723 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2725 // Generate code to check that the loop's trip count that we computed by
2726 // adding one to the backedge-taken count will not overflow.
2727 BasicBlock *NewVectorPH =
2728 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "overflow.checked");
2730 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2731 ReplaceInstWithInst(
2732 VectorPH->getTerminator(),
2733 BranchInst::Create(ScalarPH, NewVectorPH, CheckBCOverflow));
2734 VectorPH = NewVectorPH;
2736 // This is the IR builder that we use to add all of the logic for bypassing
2737 // the new vector loop.
2738 IRBuilder<> BypassBuilder(VectorPH->getTerminator());
2739 setDebugLocFromInst(BypassBuilder,
2740 getDebugLocFromInstOrOperands(OldInduction));
2742 // We may need to extend the index in case there is a type mismatch.
2743 // We know that the count starts at zero and does not overflow.
2744 if (Count->getType() != IdxTy) {
2745 // The exit count can be of pointer type. Convert it to the correct
2747 if (ExitCount->getType()->isPointerTy())
2748 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2750 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2753 // Add the start index to the loop count to get the new end index.
2754 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2756 // Now we need to generate the expression for N - (N % VF), which is
2757 // the part that the vectorized body will execute.
2758 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2759 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2760 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2761 "end.idx.rnd.down");
2763 // Now, compare the new count to zero. If it is zero skip the vector loop and
2764 // jump to the scalar loop.
2766 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2768 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2770 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2771 LoopBypassBlocks.push_back(VectorPH);
2772 ReplaceInstWithInst(VectorPH->getTerminator(),
2773 BranchInst::Create(MiddleBlock, NewVectorPH, Cmp));
2774 VectorPH = NewVectorPH;
2776 // Generate the code to check that the strides we assumed to be one are really
2777 // one. We want the new basic block to start at the first instruction in a
2778 // sequence of instructions that form a check.
2779 Instruction *StrideCheck;
2780 Instruction *FirstCheckInst;
2781 std::tie(FirstCheckInst, StrideCheck) =
2782 addStrideCheck(VectorPH->getTerminator());
2784 AddedSafetyChecks = true;
2785 // Create a new block containing the stride check.
2786 VectorPH->setName("vector.stridecheck");
2788 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2790 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2791 LoopBypassBlocks.push_back(VectorPH);
2793 // Replace the branch into the memory check block with a conditional branch
2794 // for the "few elements case".
2795 ReplaceInstWithInst(
2796 VectorPH->getTerminator(),
2797 BranchInst::Create(MiddleBlock, NewVectorPH, StrideCheck));
2799 VectorPH = NewVectorPH;
2802 // Generate the code that checks in runtime if arrays overlap. We put the
2803 // checks into a separate block to make the more common case of few elements
2805 Instruction *MemRuntimeCheck;
2806 std::tie(FirstCheckInst, MemRuntimeCheck) =
2807 Legal->getLAI()->addRuntimeCheck(VectorPH->getTerminator());
2808 if (MemRuntimeCheck) {
2809 AddedSafetyChecks = true;
2810 // Create a new block containing the memory check.
2811 VectorPH->setName("vector.memcheck");
2813 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2815 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2816 LoopBypassBlocks.push_back(VectorPH);
2818 // Replace the branch into the memory check block with a conditional branch
2819 // for the "few elements case".
2820 ReplaceInstWithInst(
2821 VectorPH->getTerminator(),
2822 BranchInst::Create(MiddleBlock, NewVectorPH, MemRuntimeCheck));
2824 VectorPH = NewVectorPH;
2827 // We are going to resume the execution of the scalar loop.
2828 // Go over all of the induction variables that we found and fix the
2829 // PHIs that are left in the scalar version of the loop.
2830 // The starting values of PHI nodes depend on the counter of the last
2831 // iteration in the vectorized loop.
2832 // If we come from a bypass edge then we need to start from the original
2835 // This variable saves the new starting index for the scalar loop.
2836 PHINode *ResumeIndex = nullptr;
2837 LoopVectorizationLegality::InductionList::iterator I, E;
2838 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2839 // Set builder to point to last bypass block.
2840 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2841 for (I = List->begin(), E = List->end(); I != E; ++I) {
2842 PHINode *OrigPhi = I->first;
2843 LoopVectorizationLegality::InductionInfo II = I->second;
2845 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2846 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2847 MiddleBlock->getTerminator());
2848 // We might have extended the type of the induction variable but we need a
2849 // truncated version for the scalar loop.
2850 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2851 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2852 MiddleBlock->getTerminator()) : nullptr;
2854 // Create phi nodes to merge from the backedge-taken check block.
2855 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2856 ScalarPH->getTerminator());
2857 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2859 PHINode *BCTruncResumeVal = nullptr;
2860 if (OrigPhi == OldInduction) {
2862 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2863 ScalarPH->getTerminator());
2864 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2867 Value *EndValue = nullptr;
2869 case LoopVectorizationLegality::IK_NoInduction:
2870 llvm_unreachable("Unknown induction");
2871 case LoopVectorizationLegality::IK_IntInduction: {
2872 // Handle the integer induction counter.
2873 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2875 // We have the canonical induction variable.
2876 if (OrigPhi == OldInduction) {
2877 // Create a truncated version of the resume value for the scalar loop,
2878 // we might have promoted the type to a larger width.
2880 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2881 // The new PHI merges the original incoming value, in case of a bypass,
2882 // or the value at the end of the vectorized loop.
2883 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2884 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2885 TruncResumeVal->addIncoming(EndValue, VecBody);
2887 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2889 // We know what the end value is.
2890 EndValue = IdxEndRoundDown;
2891 // We also know which PHI node holds it.
2892 ResumeIndex = ResumeVal;
2896 // Not the canonical induction variable - add the vector loop count to the
2898 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2899 II.StartValue->getType(),
2901 EndValue = II.transform(BypassBuilder, CRD);
2902 EndValue->setName("ind.end");
2905 case LoopVectorizationLegality::IK_PtrInduction: {
2906 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2907 II.StepValue->getType(),
2909 EndValue = II.transform(BypassBuilder, CRD);
2910 EndValue->setName("ptr.ind.end");
2915 // The new PHI merges the original incoming value, in case of a bypass,
2916 // or the value at the end of the vectorized loop.
2917 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2918 if (OrigPhi == OldInduction)
2919 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2921 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2923 ResumeVal->addIncoming(EndValue, VecBody);
2925 // Fix the scalar body counter (PHI node).
2926 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2928 // The old induction's phi node in the scalar body needs the truncated
2930 if (OrigPhi == OldInduction) {
2931 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2932 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2934 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2935 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2939 // If we are generating a new induction variable then we also need to
2940 // generate the code that calculates the exit value. This value is not
2941 // simply the end of the counter because we may skip the vectorized body
2942 // in case of a runtime check.
2944 assert(!ResumeIndex && "Unexpected resume value found");
2945 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2946 MiddleBlock->getTerminator());
2947 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2948 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2949 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2952 // Make sure that we found the index where scalar loop needs to continue.
2953 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2954 "Invalid resume Index");
2956 // Add a check in the middle block to see if we have completed
2957 // all of the iterations in the first vector loop.
2958 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2959 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2960 ResumeIndex, "cmp.n",
2961 MiddleBlock->getTerminator());
2962 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2963 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2965 // Create i+1 and fill the PHINode.
2966 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2967 Induction->addIncoming(StartIdx, VectorPH);
2968 Induction->addIncoming(NextIdx, VecBody);
2969 // Create the compare.
2970 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2971 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2973 // Now we have two terminators. Remove the old one from the block.
2974 VecBody->getTerminator()->eraseFromParent();
2976 // Get ready to start creating new instructions into the vectorized body.
2977 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2980 LoopVectorPreHeader = VectorPH;
2981 LoopScalarPreHeader = ScalarPH;
2982 LoopMiddleBlock = MiddleBlock;
2983 LoopExitBlock = ExitBlock;
2984 LoopVectorBody.push_back(VecBody);
2985 LoopScalarBody = OldBasicBlock;
2987 LoopVectorizeHints Hints(Lp, true);
2988 Hints.setAlreadyVectorized();
2992 struct CSEDenseMapInfo {
2993 static bool canHandle(Instruction *I) {
2994 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2995 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2997 static inline Instruction *getEmptyKey() {
2998 return DenseMapInfo<Instruction *>::getEmptyKey();
3000 static inline Instruction *getTombstoneKey() {
3001 return DenseMapInfo<Instruction *>::getTombstoneKey();
3003 static unsigned getHashValue(Instruction *I) {
3004 assert(canHandle(I) && "Unknown instruction!");
3005 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3006 I->value_op_end()));
3008 static bool isEqual(Instruction *LHS, Instruction *RHS) {
3009 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3010 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3012 return LHS->isIdenticalTo(RHS);
3017 /// \brief Check whether this block is a predicated block.
3018 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
3019 /// = ...; " blocks. We start with one vectorized basic block. For every
3020 /// conditional block we split this vectorized block. Therefore, every second
3021 /// block will be a predicated one.
3022 static bool isPredicatedBlock(unsigned BlockNum) {
3023 return BlockNum % 2;
3026 ///\brief Perform cse of induction variable instructions.
3027 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
3028 // Perform simple cse.
3029 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3030 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
3031 BasicBlock *BB = BBs[i];
3032 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3033 Instruction *In = I++;
3035 if (!CSEDenseMapInfo::canHandle(In))
3038 // Check if we can replace this instruction with any of the
3039 // visited instructions.
3040 if (Instruction *V = CSEMap.lookup(In)) {
3041 In->replaceAllUsesWith(V);
3042 In->eraseFromParent();
3045 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
3046 // ...;" blocks for predicated stores. Every second block is a predicated
3048 if (isPredicatedBlock(i))
3056 /// \brief Adds a 'fast' flag to floating point operations.
3057 static Value *addFastMathFlag(Value *V) {
3058 if (isa<FPMathOperator>(V)){
3059 FastMathFlags Flags;
3060 Flags.setUnsafeAlgebra();
3061 cast<Instruction>(V)->setFastMathFlags(Flags);
3066 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3067 /// the result needs to be inserted and/or extracted from vectors.
3068 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3069 const TargetTransformInfo &TTI) {
3073 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3076 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3078 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3080 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3086 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3087 // Return the cost of the instruction, including scalarization overhead if it's
3088 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3089 // i.e. either vector version isn't available, or is too expensive.
3090 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3091 const TargetTransformInfo &TTI,
3092 const TargetLibraryInfo *TLI,
3093 bool &NeedToScalarize) {
3094 Function *F = CI->getCalledFunction();
3095 StringRef FnName = CI->getCalledFunction()->getName();
3096 Type *ScalarRetTy = CI->getType();
3097 SmallVector<Type *, 4> Tys, ScalarTys;
3098 for (auto &ArgOp : CI->arg_operands())
3099 ScalarTys.push_back(ArgOp->getType());
3101 // Estimate cost of scalarized vector call. The source operands are assumed
3102 // to be vectors, so we need to extract individual elements from there,
3103 // execute VF scalar calls, and then gather the result into the vector return
3105 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3107 return ScalarCallCost;
3109 // Compute corresponding vector type for return value and arguments.
3110 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3111 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3112 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3114 // Compute costs of unpacking argument values for the scalar calls and
3115 // packing the return values to a vector.
3116 unsigned ScalarizationCost =
3117 getScalarizationOverhead(RetTy, true, false, TTI);
3118 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3119 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3121 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3123 // If we can't emit a vector call for this function, then the currently found
3124 // cost is the cost we need to return.
3125 NeedToScalarize = true;
3126 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3129 // If the corresponding vector cost is cheaper, return its cost.
3130 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3131 if (VectorCallCost < Cost) {
3132 NeedToScalarize = false;
3133 return VectorCallCost;
3138 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3139 // factor VF. Return the cost of the instruction, including scalarization
3140 // overhead if it's needed.
3141 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3142 const TargetTransformInfo &TTI,
3143 const TargetLibraryInfo *TLI) {
3144 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3145 assert(ID && "Expected intrinsic call!");
3147 Type *RetTy = ToVectorTy(CI->getType(), VF);
3148 SmallVector<Type *, 4> Tys;
3149 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3150 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3152 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3155 void InnerLoopVectorizer::vectorizeLoop() {
3156 //===------------------------------------------------===//
3158 // Notice: any optimization or new instruction that go
3159 // into the code below should be also be implemented in
3162 //===------------------------------------------------===//
3163 Constant *Zero = Builder.getInt32(0);
3165 // In order to support reduction variables we need to be able to vectorize
3166 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3167 // stages. First, we create a new vector PHI node with no incoming edges.
3168 // We use this value when we vectorize all of the instructions that use the
3169 // PHI. Next, after all of the instructions in the block are complete we
3170 // add the new incoming edges to the PHI. At this point all of the
3171 // instructions in the basic block are vectorized, so we can use them to
3172 // construct the PHI.
3173 PhiVector RdxPHIsToFix;
3175 // Scan the loop in a topological order to ensure that defs are vectorized
3177 LoopBlocksDFS DFS(OrigLoop);
3180 // Vectorize all of the blocks in the original loop.
3181 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3182 be = DFS.endRPO(); bb != be; ++bb)
3183 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3185 // At this point every instruction in the original loop is widened to
3186 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3187 // that we vectorized. The PHI nodes are currently empty because we did
3188 // not want to introduce cycles. Notice that the remaining PHI nodes
3189 // that we need to fix are reduction variables.
3191 // Create the 'reduced' values for each of the induction vars.
3192 // The reduced values are the vector values that we scalarize and combine
3193 // after the loop is finished.
3194 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3196 PHINode *RdxPhi = *it;
3197 assert(RdxPhi && "Unable to recover vectorized PHI");
3199 // Find the reduction variable descriptor.
3200 assert(Legal->getReductionVars()->count(RdxPhi) &&
3201 "Unable to find the reduction variable");
3202 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3204 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3205 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3206 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3207 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3208 RdxDesc.getMinMaxRecurrenceKind();
3209 setDebugLocFromInst(Builder, ReductionStartValue);
3211 // We need to generate a reduction vector from the incoming scalar.
3212 // To do so, we need to generate the 'identity' vector and override
3213 // one of the elements with the incoming scalar reduction. We need
3214 // to do it in the vector-loop preheader.
3215 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3217 // This is the vector-clone of the value that leaves the loop.
3218 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3219 Type *VecTy = VectorExit[0]->getType();
3221 // Find the reduction identity variable. Zero for addition, or, xor,
3222 // one for multiplication, -1 for And.
3225 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3226 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3227 // MinMax reduction have the start value as their identify.
3229 VectorStart = Identity = ReductionStartValue;
3231 VectorStart = Identity =
3232 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3235 // Handle other reduction kinds:
3236 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3237 RK, VecTy->getScalarType());
3240 // This vector is the Identity vector where the first element is the
3241 // incoming scalar reduction.
3242 VectorStart = ReductionStartValue;
3244 Identity = ConstantVector::getSplat(VF, Iden);
3246 // This vector is the Identity vector where the first element is the
3247 // incoming scalar reduction.
3249 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3253 // Fix the vector-loop phi.
3255 // Reductions do not have to start at zero. They can start with
3256 // any loop invariant values.
3257 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3258 BasicBlock *Latch = OrigLoop->getLoopLatch();
3259 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3260 VectorParts &Val = getVectorValue(LoopVal);
3261 for (unsigned part = 0; part < UF; ++part) {
3262 // Make sure to add the reduction stat value only to the
3263 // first unroll part.
3264 Value *StartVal = (part == 0) ? VectorStart : Identity;
3265 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3266 LoopVectorPreHeader);
3267 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3268 LoopVectorBody.back());
3271 // Before each round, move the insertion point right between
3272 // the PHIs and the values we are going to write.
3273 // This allows us to write both PHINodes and the extractelement
3275 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3277 VectorParts RdxParts;
3278 setDebugLocFromInst(Builder, LoopExitInst);
3279 for (unsigned part = 0; part < UF; ++part) {
3280 // This PHINode contains the vectorized reduction variable, or
3281 // the initial value vector, if we bypass the vector loop.
3282 VectorParts &RdxExitVal = getVectorValue(LoopExitInst);
3283 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
3284 Value *StartVal = (part == 0) ? VectorStart : Identity;
3285 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3286 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
3287 NewPhi->addIncoming(RdxExitVal[part],
3288 LoopVectorBody.back());
3289 RdxParts.push_back(NewPhi);
3292 // Reduce all of the unrolled parts into a single vector.
3293 Value *ReducedPartRdx = RdxParts[0];
3294 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3295 setDebugLocFromInst(Builder, ReducedPartRdx);
3296 for (unsigned part = 1; part < UF; ++part) {
3297 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3298 // Floating point operations had to be 'fast' to enable the reduction.
3299 ReducedPartRdx = addFastMathFlag(
3300 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3301 ReducedPartRdx, "bin.rdx"));
3303 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3304 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3308 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3309 // and vector ops, reducing the set of values being computed by half each
3311 assert(isPowerOf2_32(VF) &&
3312 "Reduction emission only supported for pow2 vectors!");
3313 Value *TmpVec = ReducedPartRdx;
3314 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3315 for (unsigned i = VF; i != 1; i >>= 1) {
3316 // Move the upper half of the vector to the lower half.
3317 for (unsigned j = 0; j != i/2; ++j)
3318 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3320 // Fill the rest of the mask with undef.
3321 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3322 UndefValue::get(Builder.getInt32Ty()));
3325 Builder.CreateShuffleVector(TmpVec,
3326 UndefValue::get(TmpVec->getType()),
3327 ConstantVector::get(ShuffleMask),
3330 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3331 // Floating point operations had to be 'fast' to enable the reduction.
3332 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3333 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3335 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3339 // The result is in the first element of the vector.
3340 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3341 Builder.getInt32(0));
3344 // Create a phi node that merges control-flow from the backedge-taken check
3345 // block and the middle block.
3346 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3347 LoopScalarPreHeader->getTerminator());
3348 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[0]);
3349 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3351 // Now, we need to fix the users of the reduction variable
3352 // inside and outside of the scalar remainder loop.
3353 // We know that the loop is in LCSSA form. We need to update the
3354 // PHI nodes in the exit blocks.
3355 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3356 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3357 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3358 if (!LCSSAPhi) break;
3360 // All PHINodes need to have a single entry edge, or two if
3361 // we already fixed them.
3362 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3364 // We found our reduction value exit-PHI. Update it with the
3365 // incoming bypass edge.
3366 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3367 // Add an edge coming from the bypass.
3368 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3371 }// end of the LCSSA phi scan.
3373 // Fix the scalar loop reduction variable with the incoming reduction sum
3374 // from the vector body and from the backedge value.
3375 int IncomingEdgeBlockIdx =
3376 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3377 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3378 // Pick the other block.
3379 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3380 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3381 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3382 }// end of for each redux variable.
3386 // Remove redundant induction instructions.
3387 cse(LoopVectorBody);
3390 void InnerLoopVectorizer::fixLCSSAPHIs() {
3391 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3392 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3393 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3394 if (!LCSSAPhi) break;
3395 if (LCSSAPhi->getNumIncomingValues() == 1)
3396 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3401 InnerLoopVectorizer::VectorParts
3402 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3403 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3406 // Look for cached value.
3407 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3408 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3409 if (ECEntryIt != MaskCache.end())
3410 return ECEntryIt->second;
3412 VectorParts SrcMask = createBlockInMask(Src);
3414 // The terminator has to be a branch inst!
3415 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3416 assert(BI && "Unexpected terminator found");
3418 if (BI->isConditional()) {
3419 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3421 if (BI->getSuccessor(0) != Dst)
3422 for (unsigned part = 0; part < UF; ++part)
3423 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3425 for (unsigned part = 0; part < UF; ++part)
3426 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3428 MaskCache[Edge] = EdgeMask;
3432 MaskCache[Edge] = SrcMask;
3436 InnerLoopVectorizer::VectorParts
3437 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3438 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3440 // Loop incoming mask is all-one.
3441 if (OrigLoop->getHeader() == BB) {
3442 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3443 return getVectorValue(C);
3446 // This is the block mask. We OR all incoming edges, and with zero.
3447 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3448 VectorParts BlockMask = getVectorValue(Zero);
3451 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3452 VectorParts EM = createEdgeMask(*it, BB);
3453 for (unsigned part = 0; part < UF; ++part)
3454 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3460 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3461 InnerLoopVectorizer::VectorParts &Entry,
3462 unsigned UF, unsigned VF, PhiVector *PV) {
3463 PHINode* P = cast<PHINode>(PN);
3464 // Handle reduction variables:
3465 if (Legal->getReductionVars()->count(P)) {
3466 for (unsigned part = 0; part < UF; ++part) {
3467 // This is phase one of vectorizing PHIs.
3468 Type *VecTy = (VF == 1) ? PN->getType() :
3469 VectorType::get(PN->getType(), VF);
3470 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3471 LoopVectorBody.back()-> getFirstInsertionPt());
3477 setDebugLocFromInst(Builder, P);
3478 // Check for PHI nodes that are lowered to vector selects.
3479 if (P->getParent() != OrigLoop->getHeader()) {
3480 // We know that all PHIs in non-header blocks are converted into
3481 // selects, so we don't have to worry about the insertion order and we
3482 // can just use the builder.
3483 // At this point we generate the predication tree. There may be
3484 // duplications since this is a simple recursive scan, but future
3485 // optimizations will clean it up.
3487 unsigned NumIncoming = P->getNumIncomingValues();
3489 // Generate a sequence of selects of the form:
3490 // SELECT(Mask3, In3,
3491 // SELECT(Mask2, In2,
3493 for (unsigned In = 0; In < NumIncoming; In++) {
3494 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3496 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3498 for (unsigned part = 0; part < UF; ++part) {
3499 // We might have single edge PHIs (blocks) - use an identity
3500 // 'select' for the first PHI operand.
3502 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3505 // Select between the current value and the previous incoming edge
3506 // based on the incoming mask.
3507 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3508 Entry[part], "predphi");
3514 // This PHINode must be an induction variable.
3515 // Make sure that we know about it.
3516 assert(Legal->getInductionVars()->count(P) &&
3517 "Not an induction variable");
3519 LoopVectorizationLegality::InductionInfo II =
3520 Legal->getInductionVars()->lookup(P);
3522 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3523 // which can be found from the original scalar operations.
3525 case LoopVectorizationLegality::IK_NoInduction:
3526 llvm_unreachable("Unknown induction");
3527 case LoopVectorizationLegality::IK_IntInduction: {
3528 assert(P->getType() == II.StartValue->getType() && "Types must match");
3529 Type *PhiTy = P->getType();
3531 if (P == OldInduction) {
3532 // Handle the canonical induction variable. We might have had to
3534 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3536 // Handle other induction variables that are now based on the
3538 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3540 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3541 Broadcasted = II.transform(Builder, NormalizedIdx);
3542 Broadcasted->setName("offset.idx");
3544 Broadcasted = getBroadcastInstrs(Broadcasted);
3545 // After broadcasting the induction variable we need to make the vector
3546 // consecutive by adding 0, 1, 2, etc.
3547 for (unsigned part = 0; part < UF; ++part)
3548 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
3551 case LoopVectorizationLegality::IK_PtrInduction:
3552 // Handle the pointer induction variable case.
3553 assert(P->getType()->isPointerTy() && "Unexpected type.");
3554 // This is the normalized GEP that starts counting at zero.
3555 Value *NormalizedIdx =
3556 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
3558 Builder.CreateSExtOrTrunc(NormalizedIdx, II.StepValue->getType());
3559 // This is the vector of results. Notice that we don't generate
3560 // vector geps because scalar geps result in better code.
3561 for (unsigned part = 0; part < UF; ++part) {
3563 int EltIndex = part;
3564 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3565 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3566 Value *SclrGep = II.transform(Builder, GlobalIdx);
3567 SclrGep->setName("next.gep");
3568 Entry[part] = SclrGep;
3572 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3573 for (unsigned int i = 0; i < VF; ++i) {
3574 int EltIndex = i + part * VF;
3575 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3576 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3577 Value *SclrGep = II.transform(Builder, GlobalIdx);
3578 SclrGep->setName("next.gep");
3579 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3580 Builder.getInt32(i),
3583 Entry[part] = VecVal;
3589 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3590 // For each instruction in the old loop.
3591 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3592 VectorParts &Entry = WidenMap.get(it);
3593 switch (it->getOpcode()) {
3594 case Instruction::Br:
3595 // Nothing to do for PHIs and BR, since we already took care of the
3596 // loop control flow instructions.
3598 case Instruction::PHI: {
3599 // Vectorize PHINodes.
3600 widenPHIInstruction(it, Entry, UF, VF, PV);
3604 case Instruction::Add:
3605 case Instruction::FAdd:
3606 case Instruction::Sub:
3607 case Instruction::FSub:
3608 case Instruction::Mul:
3609 case Instruction::FMul:
3610 case Instruction::UDiv:
3611 case Instruction::SDiv:
3612 case Instruction::FDiv:
3613 case Instruction::URem:
3614 case Instruction::SRem:
3615 case Instruction::FRem:
3616 case Instruction::Shl:
3617 case Instruction::LShr:
3618 case Instruction::AShr:
3619 case Instruction::And:
3620 case Instruction::Or:
3621 case Instruction::Xor: {
3622 // Just widen binops.
3623 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3624 setDebugLocFromInst(Builder, BinOp);
3625 VectorParts &A = getVectorValue(it->getOperand(0));
3626 VectorParts &B = getVectorValue(it->getOperand(1));
3628 // Use this vector value for all users of the original instruction.
3629 for (unsigned Part = 0; Part < UF; ++Part) {
3630 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3632 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3633 VecOp->copyIRFlags(BinOp);
3638 propagateMetadata(Entry, it);
3641 case Instruction::Select: {
3643 // If the selector is loop invariant we can create a select
3644 // instruction with a scalar condition. Otherwise, use vector-select.
3645 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3647 setDebugLocFromInst(Builder, it);
3649 // The condition can be loop invariant but still defined inside the
3650 // loop. This means that we can't just use the original 'cond' value.
3651 // We have to take the 'vectorized' value and pick the first lane.
3652 // Instcombine will make this a no-op.
3653 VectorParts &Cond = getVectorValue(it->getOperand(0));
3654 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3655 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3657 Value *ScalarCond = (VF == 1) ? Cond[0] :
3658 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3660 for (unsigned Part = 0; Part < UF; ++Part) {
3661 Entry[Part] = Builder.CreateSelect(
3662 InvariantCond ? ScalarCond : Cond[Part],
3667 propagateMetadata(Entry, it);
3671 case Instruction::ICmp:
3672 case Instruction::FCmp: {
3673 // Widen compares. Generate vector compares.
3674 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3675 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3676 setDebugLocFromInst(Builder, it);
3677 VectorParts &A = getVectorValue(it->getOperand(0));
3678 VectorParts &B = getVectorValue(it->getOperand(1));
3679 for (unsigned Part = 0; Part < UF; ++Part) {
3682 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3684 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3688 propagateMetadata(Entry, it);
3692 case Instruction::Store:
3693 case Instruction::Load:
3694 vectorizeMemoryInstruction(it);
3696 case Instruction::ZExt:
3697 case Instruction::SExt:
3698 case Instruction::FPToUI:
3699 case Instruction::FPToSI:
3700 case Instruction::FPExt:
3701 case Instruction::PtrToInt:
3702 case Instruction::IntToPtr:
3703 case Instruction::SIToFP:
3704 case Instruction::UIToFP:
3705 case Instruction::Trunc:
3706 case Instruction::FPTrunc:
3707 case Instruction::BitCast: {
3708 CastInst *CI = dyn_cast<CastInst>(it);
3709 setDebugLocFromInst(Builder, it);
3710 /// Optimize the special case where the source is the induction
3711 /// variable. Notice that we can only optimize the 'trunc' case
3712 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3713 /// c. other casts depend on pointer size.
3714 if (CI->getOperand(0) == OldInduction &&
3715 it->getOpcode() == Instruction::Trunc) {
3716 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3718 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3719 LoopVectorizationLegality::InductionInfo II =
3720 Legal->getInductionVars()->lookup(OldInduction);
3722 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3723 for (unsigned Part = 0; Part < UF; ++Part)
3724 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3725 propagateMetadata(Entry, it);
3728 /// Vectorize casts.
3729 Type *DestTy = (VF == 1) ? CI->getType() :
3730 VectorType::get(CI->getType(), VF);
3732 VectorParts &A = getVectorValue(it->getOperand(0));
3733 for (unsigned Part = 0; Part < UF; ++Part)
3734 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3735 propagateMetadata(Entry, it);
3739 case Instruction::Call: {
3740 // Ignore dbg intrinsics.
3741 if (isa<DbgInfoIntrinsic>(it))
3743 setDebugLocFromInst(Builder, it);
3745 Module *M = BB->getParent()->getParent();
3746 CallInst *CI = cast<CallInst>(it);
3748 StringRef FnName = CI->getCalledFunction()->getName();
3749 Function *F = CI->getCalledFunction();
3750 Type *RetTy = ToVectorTy(CI->getType(), VF);
3751 SmallVector<Type *, 4> Tys;
3752 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3753 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3755 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3757 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3758 ID == Intrinsic::lifetime_start)) {
3759 scalarizeInstruction(it);
3762 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3763 // version of the instruction.
3764 // Is it beneficial to perform intrinsic call compared to lib call?
3765 bool NeedToScalarize;
3766 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3767 bool UseVectorIntrinsic =
3768 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3769 if (!UseVectorIntrinsic && NeedToScalarize) {
3770 scalarizeInstruction(it);
3774 for (unsigned Part = 0; Part < UF; ++Part) {
3775 SmallVector<Value *, 4> Args;
3776 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3777 Value *Arg = CI->getArgOperand(i);
3778 // Some intrinsics have a scalar argument - don't replace it with a
3780 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3781 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3782 Arg = VectorArg[Part];
3784 Args.push_back(Arg);
3788 if (UseVectorIntrinsic) {
3789 // Use vector version of the intrinsic.
3790 Type *TysForDecl[] = {CI->getType()};
3792 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3793 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3795 // Use vector version of the library call.
3796 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3797 assert(!VFnName.empty() && "Vector function name is empty.");
3798 VectorF = M->getFunction(VFnName);
3800 // Generate a declaration
3801 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3803 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3804 VectorF->copyAttributesFrom(F);
3807 assert(VectorF && "Can't create vector function.");
3808 Entry[Part] = Builder.CreateCall(VectorF, Args);
3811 propagateMetadata(Entry, it);
3816 // All other instructions are unsupported. Scalarize them.
3817 scalarizeInstruction(it);
3820 }// end of for_each instr.
3823 void InnerLoopVectorizer::updateAnalysis() {
3824 // Forget the original basic block.
3825 SE->forgetLoop(OrigLoop);
3827 // Update the dominator tree information.
3828 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3829 "Entry does not dominate exit.");
3831 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3832 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3833 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3835 // Due to if predication of stores we might create a sequence of "if(pred)
3836 // a[i] = ...; " blocks.
3837 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3839 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3840 else if (isPredicatedBlock(i)) {
3841 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3843 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3847 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3848 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3849 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3850 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3852 DEBUG(DT->verifyDomTree());
3855 /// \brief Check whether it is safe to if-convert this phi node.
3857 /// Phi nodes with constant expressions that can trap are not safe to if
3859 static bool canIfConvertPHINodes(BasicBlock *BB) {
3860 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3861 PHINode *Phi = dyn_cast<PHINode>(I);
3864 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3865 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3872 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3873 if (!EnableIfConversion) {
3874 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3878 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3880 // A list of pointers that we can safely read and write to.
3881 SmallPtrSet<Value *, 8> SafePointes;
3883 // Collect safe addresses.
3884 for (Loop::block_iterator BI = TheLoop->block_begin(),
3885 BE = TheLoop->block_end(); BI != BE; ++BI) {
3886 BasicBlock *BB = *BI;
3888 if (blockNeedsPredication(BB))
3891 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3892 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3893 SafePointes.insert(LI->getPointerOperand());
3894 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3895 SafePointes.insert(SI->getPointerOperand());
3899 // Collect the blocks that need predication.
3900 BasicBlock *Header = TheLoop->getHeader();
3901 for (Loop::block_iterator BI = TheLoop->block_begin(),
3902 BE = TheLoop->block_end(); BI != BE; ++BI) {
3903 BasicBlock *BB = *BI;
3905 // We don't support switch statements inside loops.
3906 if (!isa<BranchInst>(BB->getTerminator())) {
3907 emitAnalysis(VectorizationReport(BB->getTerminator())
3908 << "loop contains a switch statement");
3912 // We must be able to predicate all blocks that need to be predicated.
3913 if (blockNeedsPredication(BB)) {
3914 if (!blockCanBePredicated(BB, SafePointes)) {
3915 emitAnalysis(VectorizationReport(BB->getTerminator())
3916 << "control flow cannot be substituted for a select");
3919 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3920 emitAnalysis(VectorizationReport(BB->getTerminator())
3921 << "control flow cannot be substituted for a select");
3926 // We can if-convert this loop.
3930 bool LoopVectorizationLegality::canVectorize() {
3931 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3932 // be canonicalized.
3933 if (!TheLoop->getLoopPreheader()) {
3935 VectorizationReport() <<
3936 "loop control flow is not understood by vectorizer");
3940 // We can only vectorize innermost loops.
3941 if (!TheLoop->empty()) {
3942 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3946 // We must have a single backedge.
3947 if (TheLoop->getNumBackEdges() != 1) {
3949 VectorizationReport() <<
3950 "loop control flow is not understood by vectorizer");
3954 // We must have a single exiting block.
3955 if (!TheLoop->getExitingBlock()) {
3957 VectorizationReport() <<
3958 "loop control flow is not understood by vectorizer");
3962 // We only handle bottom-tested loops, i.e. loop in which the condition is
3963 // checked at the end of each iteration. With that we can assume that all
3964 // instructions in the loop are executed the same number of times.
3965 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3967 VectorizationReport() <<
3968 "loop control flow is not understood by vectorizer");
3972 // We need to have a loop header.
3973 DEBUG(dbgs() << "LV: Found a loop: " <<
3974 TheLoop->getHeader()->getName() << '\n');
3976 // Check if we can if-convert non-single-bb loops.
3977 unsigned NumBlocks = TheLoop->getNumBlocks();
3978 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3979 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3983 // ScalarEvolution needs to be able to find the exit count.
3984 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3985 if (ExitCount == SE->getCouldNotCompute()) {
3986 emitAnalysis(VectorizationReport() <<
3987 "could not determine number of loop iterations");
3988 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3992 // Check if we can vectorize the instructions and CFG in this loop.
3993 if (!canVectorizeInstrs()) {
3994 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3998 // Go over each instruction and look at memory deps.
3999 if (!canVectorizeMemory()) {
4000 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4004 // Collect all of the variables that remain uniform after vectorization.
4005 collectLoopUniforms();
4007 DEBUG(dbgs() << "LV: We can vectorize this loop"
4008 << (LAI->getRuntimePointerChecking()->Need
4009 ? " (with a runtime bound check)"
4013 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4015 // If an override option has been passed in for interleaved accesses, use it.
4016 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4017 UseInterleaved = EnableInterleavedMemAccesses;
4019 // Analyze interleaved memory accesses.
4021 InterleaveInfo.analyzeInterleaving(Strides);
4023 // Okay! We can vectorize. At this point we don't have any other mem analysis
4024 // which may limit our maximum vectorization factor, so just return true with
4029 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4030 if (Ty->isPointerTy())
4031 return DL.getIntPtrType(Ty);
4033 // It is possible that char's or short's overflow when we ask for the loop's
4034 // trip count, work around this by changing the type size.
4035 if (Ty->getScalarSizeInBits() < 32)
4036 return Type::getInt32Ty(Ty->getContext());
4041 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4042 Ty0 = convertPointerToIntegerType(DL, Ty0);
4043 Ty1 = convertPointerToIntegerType(DL, Ty1);
4044 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4049 /// \brief Check that the instruction has outside loop users and is not an
4050 /// identified reduction variable.
4051 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4052 SmallPtrSetImpl<Value *> &Reductions) {
4053 // Reduction instructions are allowed to have exit users. All other
4054 // instructions must not have external users.
4055 if (!Reductions.count(Inst))
4056 //Check that all of the users of the loop are inside the BB.
4057 for (User *U : Inst->users()) {
4058 Instruction *UI = cast<Instruction>(U);
4059 // This user may be a reduction exit value.
4060 if (!TheLoop->contains(UI)) {
4061 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4068 bool LoopVectorizationLegality::canVectorizeInstrs() {
4069 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
4070 BasicBlock *Header = TheLoop->getHeader();
4072 // Look for the attribute signaling the absence of NaNs.
4073 Function &F = *Header->getParent();
4074 const DataLayout &DL = F.getParent()->getDataLayout();
4075 if (F.hasFnAttribute("no-nans-fp-math"))
4077 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4079 // For each block in the loop.
4080 for (Loop::block_iterator bb = TheLoop->block_begin(),
4081 be = TheLoop->block_end(); bb != be; ++bb) {
4083 // Scan the instructions in the block and look for hazards.
4084 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4087 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4088 Type *PhiTy = Phi->getType();
4089 // Check that this PHI type is allowed.
4090 if (!PhiTy->isIntegerTy() &&
4091 !PhiTy->isFloatingPointTy() &&
4092 !PhiTy->isPointerTy()) {
4093 emitAnalysis(VectorizationReport(it)
4094 << "loop control flow is not understood by vectorizer");
4095 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4099 // If this PHINode is not in the header block, then we know that we
4100 // can convert it to select during if-conversion. No need to check if
4101 // the PHIs in this block are induction or reduction variables.
4102 if (*bb != Header) {
4103 // Check that this instruction has no outside users or is an
4104 // identified reduction value with an outside user.
4105 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
4107 emitAnalysis(VectorizationReport(it) <<
4108 "value could not be identified as "
4109 "an induction or reduction variable");
4113 // We only allow if-converted PHIs with exactly two incoming values.
4114 if (Phi->getNumIncomingValues() != 2) {
4115 emitAnalysis(VectorizationReport(it)
4116 << "control flow not understood by vectorizer");
4117 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4121 // This is the value coming from the preheader.
4122 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
4123 ConstantInt *StepValue = nullptr;
4124 // Check if this is an induction variable.
4125 InductionKind IK = isInductionVariable(Phi, StepValue);
4127 if (IK_NoInduction != IK) {
4128 // Get the widest type.
4130 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4132 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4134 // Int inductions are special because we only allow one IV.
4135 if (IK == IK_IntInduction && StepValue->isOne()) {
4136 // Use the phi node with the widest type as induction. Use the last
4137 // one if there are multiple (no good reason for doing this other
4138 // than it is expedient).
4139 if (!Induction || PhiTy == WidestIndTy)
4143 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4144 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
4146 // Until we explicitly handle the case of an induction variable with
4147 // an outside loop user we have to give up vectorizing this loop.
4148 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4149 emitAnalysis(VectorizationReport(it) <<
4150 "use of induction value outside of the "
4151 "loop is not handled by vectorizer");
4158 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4160 if (Reductions[Phi].hasUnsafeAlgebra())
4161 Requirements->addUnsafeAlgebraInst(
4162 Reductions[Phi].getUnsafeAlgebraInst());
4163 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4167 emitAnalysis(VectorizationReport(it) <<
4168 "value that could not be identified as "
4169 "reduction is used outside the loop");
4170 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4172 }// end of PHI handling
4174 // We handle calls that:
4175 // * Are debug info intrinsics.
4176 // * Have a mapping to an IR intrinsic.
4177 // * Have a vector version available.
4178 CallInst *CI = dyn_cast<CallInst>(it);
4179 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4180 !(CI->getCalledFunction() && TLI &&
4181 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4182 emitAnalysis(VectorizationReport(it) <<
4183 "call instruction cannot be vectorized");
4184 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4188 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4189 // second argument is the same (i.e. loop invariant)
4191 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4192 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4193 emitAnalysis(VectorizationReport(it)
4194 << "intrinsic instruction cannot be vectorized");
4195 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4200 // Check that the instruction return type is vectorizable.
4201 // Also, we can't vectorize extractelement instructions.
4202 if ((!VectorType::isValidElementType(it->getType()) &&
4203 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4204 emitAnalysis(VectorizationReport(it)
4205 << "instruction return type cannot be vectorized");
4206 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4210 // Check that the stored type is vectorizable.
4211 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4212 Type *T = ST->getValueOperand()->getType();
4213 if (!VectorType::isValidElementType(T)) {
4214 emitAnalysis(VectorizationReport(ST) <<
4215 "store instruction cannot be vectorized");
4218 if (EnableMemAccessVersioning)
4219 collectStridedAccess(ST);
4222 if (EnableMemAccessVersioning)
4223 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4224 collectStridedAccess(LI);
4226 // Reduction instructions are allowed to have exit users.
4227 // All other instructions must not have external users.
4228 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4229 emitAnalysis(VectorizationReport(it) <<
4230 "value cannot be used outside the loop");
4239 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4240 if (Inductions.empty()) {
4241 emitAnalysis(VectorizationReport()
4242 << "loop induction variable could not be identified");
4250 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4251 Value *Ptr = nullptr;
4252 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4253 Ptr = LI->getPointerOperand();
4254 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4255 Ptr = SI->getPointerOperand();
4259 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4263 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4264 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4265 Strides[Ptr] = Stride;
4266 StrideSet.insert(Stride);
4269 void LoopVectorizationLegality::collectLoopUniforms() {
4270 // We now know that the loop is vectorizable!
4271 // Collect variables that will remain uniform after vectorization.
4272 std::vector<Value*> Worklist;
4273 BasicBlock *Latch = TheLoop->getLoopLatch();
4275 // Start with the conditional branch and walk up the block.
4276 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4278 // Also add all consecutive pointer values; these values will be uniform
4279 // after vectorization (and subsequent cleanup) and, until revectorization is
4280 // supported, all dependencies must also be uniform.
4281 for (Loop::block_iterator B = TheLoop->block_begin(),
4282 BE = TheLoop->block_end(); B != BE; ++B)
4283 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4285 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4286 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4288 while (!Worklist.empty()) {
4289 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4290 Worklist.pop_back();
4292 // Look at instructions inside this loop.
4293 // Stop when reaching PHI nodes.
4294 // TODO: we need to follow values all over the loop, not only in this block.
4295 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4298 // This is a known uniform.
4301 // Insert all operands.
4302 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4306 bool LoopVectorizationLegality::canVectorizeMemory() {
4307 LAI = &LAA->getInfo(TheLoop, Strides);
4308 auto &OptionalReport = LAI->getReport();
4310 emitAnalysis(VectorizationReport(*OptionalReport));
4311 if (!LAI->canVectorizeMemory())
4314 if (LAI->hasStoreToLoopInvariantAddress()) {
4316 VectorizationReport()
4317 << "write to a loop invariant address could not be vectorized");
4318 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4322 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4327 LoopVectorizationLegality::InductionKind
4328 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4329 ConstantInt *&StepValue) {
4330 if (!isInductionPHI(Phi, SE, StepValue))
4331 return IK_NoInduction;
4333 Type *PhiTy = Phi->getType();
4334 // Found an Integer induction variable.
4335 if (PhiTy->isIntegerTy())
4336 return IK_IntInduction;
4337 // Found an Pointer induction variable.
4338 return IK_PtrInduction;
4341 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4342 Value *In0 = const_cast<Value*>(V);
4343 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4347 return Inductions.count(PN);
4350 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4351 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4354 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4355 SmallPtrSetImpl<Value *> &SafePtrs) {
4357 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4358 // Check that we don't have a constant expression that can trap as operand.
4359 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4361 if (Constant *C = dyn_cast<Constant>(*OI))
4365 // We might be able to hoist the load.
4366 if (it->mayReadFromMemory()) {
4367 LoadInst *LI = dyn_cast<LoadInst>(it);
4370 if (!SafePtrs.count(LI->getPointerOperand())) {
4371 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4372 MaskedOp.insert(LI);
4379 // We don't predicate stores at the moment.
4380 if (it->mayWriteToMemory()) {
4381 StoreInst *SI = dyn_cast<StoreInst>(it);
4382 // We only support predication of stores in basic blocks with one
4387 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4388 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4390 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4391 !isSinglePredecessor) {
4392 // Build a masked store if it is legal for the target, otherwise scalarize
4394 bool isLegalMaskedOp =
4395 isLegalMaskedStore(SI->getValueOperand()->getType(),
4396 SI->getPointerOperand());
4397 if (isLegalMaskedOp) {
4399 MaskedOp.insert(SI);
4408 // The instructions below can trap.
4409 switch (it->getOpcode()) {
4411 case Instruction::UDiv:
4412 case Instruction::SDiv:
4413 case Instruction::URem:
4414 case Instruction::SRem:
4422 void InterleavedAccessInfo::collectConstStridedAccesses(
4423 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4424 const ValueToValueMap &Strides) {
4425 // Holds load/store instructions in program order.
4426 SmallVector<Instruction *, 16> AccessList;
4428 for (auto *BB : TheLoop->getBlocks()) {
4429 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4431 for (auto &I : *BB) {
4432 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4434 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4438 AccessList.push_back(&I);
4442 if (AccessList.empty())
4445 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4446 for (auto I : AccessList) {
4447 LoadInst *LI = dyn_cast<LoadInst>(I);
4448 StoreInst *SI = dyn_cast<StoreInst>(I);
4450 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4451 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4453 // The factor of the corresponding interleave group.
4454 unsigned Factor = std::abs(Stride);
4456 // Ignore the access if the factor is too small or too large.
4457 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4460 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4461 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4462 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4464 // An alignment of 0 means target ABI alignment.
4465 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4467 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4469 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4473 // Analyze interleaved accesses and collect them into interleave groups.
4475 // Notice that the vectorization on interleaved groups will change instruction
4476 // orders and may break dependences. But the memory dependence check guarantees
4477 // that there is no overlap between two pointers of different strides, element
4478 // sizes or underlying bases.
4480 // For pointers sharing the same stride, element size and underlying base, no
4481 // need to worry about Read-After-Write dependences and Write-After-Read
4484 // E.g. The RAW dependence: A[i] = a;
4486 // This won't exist as it is a store-load forwarding conflict, which has
4487 // already been checked and forbidden in the dependence check.
4489 // E.g. The WAR dependence: a = A[i]; // (1)
4491 // The store group of (2) is always inserted at or below (2), and the load group
4492 // of (1) is always inserted at or above (1). The dependence is safe.
4493 void InterleavedAccessInfo::analyzeInterleaving(
4494 const ValueToValueMap &Strides) {
4495 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4497 // Holds all the stride accesses.
4498 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4499 collectConstStridedAccesses(StrideAccesses, Strides);
4501 if (StrideAccesses.empty())
4504 // Holds all interleaved store groups temporarily.
4505 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4507 // Search the load-load/write-write pair B-A in bottom-up order and try to
4508 // insert B into the interleave group of A according to 3 rules:
4509 // 1. A and B have the same stride.
4510 // 2. A and B have the same memory object size.
4511 // 3. B belongs to the group according to the distance.
4513 // The bottom-up order can avoid breaking the Write-After-Write dependences
4514 // between two pointers of the same base.
4515 // E.g. A[i] = a; (1)
4518 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4519 // above (1), which guarantees that (1) is always above (2).
4520 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4522 Instruction *A = I->first;
4523 StrideDescriptor DesA = I->second;
4525 InterleaveGroup *Group = getInterleaveGroup(A);
4527 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4528 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4531 if (A->mayWriteToMemory())
4532 StoreGroups.insert(Group);
4534 for (auto II = std::next(I); II != E; ++II) {
4535 Instruction *B = II->first;
4536 StrideDescriptor DesB = II->second;
4538 // Ignore if B is already in a group or B is a different memory operation.
4539 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4542 // Check the rule 1 and 2.
4543 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4546 // Calculate the distance and prepare for the rule 3.
4547 const SCEVConstant *DistToA =
4548 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4552 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4554 // Skip if the distance is not multiple of size as they are not in the
4556 if (DistanceToA % static_cast<int>(DesA.Size))
4559 // The index of B is the index of A plus the related index to A.
4561 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4563 // Try to insert B into the group.
4564 if (Group->insertMember(B, IndexB, DesB.Align)) {
4565 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4566 << " into the interleave group with" << *A << '\n');
4567 InterleaveGroupMap[B] = Group;
4569 // Set the first load in program order as the insert position.
4570 if (B->mayReadFromMemory())
4571 Group->setInsertPos(B);
4573 } // Iteration on instruction B
4574 } // Iteration on instruction A
4576 // Remove interleaved store groups with gaps.
4577 for (InterleaveGroup *Group : StoreGroups)
4578 if (Group->getNumMembers() != Group->getFactor())
4579 releaseGroup(Group);
4582 LoopVectorizationCostModel::VectorizationFactor
4583 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4584 // Width 1 means no vectorize
4585 VectorizationFactor Factor = { 1U, 0U };
4586 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4587 emitAnalysis(VectorizationReport() <<
4588 "runtime pointer checks needed. Enable vectorization of this "
4589 "loop with '#pragma clang loop vectorize(enable)' when "
4590 "compiling with -Os");
4591 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4595 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4596 emitAnalysis(VectorizationReport() <<
4597 "store that is conditionally executed prevents vectorization");
4598 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4602 // Find the trip count.
4603 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4604 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4606 unsigned WidestType = getWidestType();
4607 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4608 unsigned MaxSafeDepDist = -1U;
4609 if (Legal->getMaxSafeDepDistBytes() != -1U)
4610 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4611 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4612 WidestRegister : MaxSafeDepDist);
4613 unsigned MaxVectorSize = WidestRegister / WidestType;
4614 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4615 DEBUG(dbgs() << "LV: The Widest register is: "
4616 << WidestRegister << " bits.\n");
4618 if (MaxVectorSize == 0) {
4619 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4623 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4624 " into one vector!");
4626 unsigned VF = MaxVectorSize;
4628 // If we optimize the program for size, avoid creating the tail loop.
4630 // If we are unable to calculate the trip count then don't try to vectorize.
4633 (VectorizationReport() <<
4634 "unable to calculate the loop count due to complex control flow");
4635 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4639 // Find the maximum SIMD width that can fit within the trip count.
4640 VF = TC % MaxVectorSize;
4645 // If the trip count that we found modulo the vectorization factor is not
4646 // zero then we require a tail.
4647 emitAnalysis(VectorizationReport() <<
4648 "cannot optimize for size and vectorize at the "
4649 "same time. Enable vectorization of this loop "
4650 "with '#pragma clang loop vectorize(enable)' "
4651 "when compiling with -Os");
4652 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4657 int UserVF = Hints->getWidth();
4659 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4660 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4662 Factor.Width = UserVF;
4666 float Cost = expectedCost(1);
4668 const float ScalarCost = Cost;
4671 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4673 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4674 // Ignore scalar width, because the user explicitly wants vectorization.
4675 if (ForceVectorization && VF > 1) {
4677 Cost = expectedCost(Width) / (float)Width;
4680 for (unsigned i=2; i <= VF; i*=2) {
4681 // Notice that the vector loop needs to be executed less times, so
4682 // we need to divide the cost of the vector loops by the width of
4683 // the vector elements.
4684 float VectorCost = expectedCost(i) / (float)i;
4685 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4686 (int)VectorCost << ".\n");
4687 if (VectorCost < Cost) {
4693 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4694 << "LV: Vectorization seems to be not beneficial, "
4695 << "but was forced by a user.\n");
4696 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4697 Factor.Width = Width;
4698 Factor.Cost = Width * Cost;
4702 unsigned LoopVectorizationCostModel::getWidestType() {
4703 unsigned MaxWidth = 8;
4704 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4707 for (Loop::block_iterator bb = TheLoop->block_begin(),
4708 be = TheLoop->block_end(); bb != be; ++bb) {
4709 BasicBlock *BB = *bb;
4711 // For each instruction in the loop.
4712 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4713 Type *T = it->getType();
4715 // Ignore ephemeral values.
4716 if (EphValues.count(it))
4719 // Only examine Loads, Stores and PHINodes.
4720 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4723 // Examine PHI nodes that are reduction variables.
4724 if (PHINode *PN = dyn_cast<PHINode>(it))
4725 if (!Legal->getReductionVars()->count(PN))
4728 // Examine the stored values.
4729 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4730 T = ST->getValueOperand()->getType();
4732 // Ignore loaded pointer types and stored pointer types that are not
4733 // consecutive. However, we do want to take consecutive stores/loads of
4734 // pointer vectors into account.
4735 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4738 MaxWidth = std::max(MaxWidth,
4739 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4746 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4748 unsigned LoopCost) {
4750 // -- The interleave heuristics --
4751 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4752 // There are many micro-architectural considerations that we can't predict
4753 // at this level. For example, frontend pressure (on decode or fetch) due to
4754 // code size, or the number and capabilities of the execution ports.
4756 // We use the following heuristics to select the interleave count:
4757 // 1. If the code has reductions, then we interleave to break the cross
4758 // iteration dependency.
4759 // 2. If the loop is really small, then we interleave to reduce the loop
4761 // 3. We don't interleave if we think that we will spill registers to memory
4762 // due to the increased register pressure.
4764 // When we optimize for size, we don't interleave.
4768 // We used the distance for the interleave count.
4769 if (Legal->getMaxSafeDepDistBytes() != -1U)
4772 // Do not interleave loops with a relatively small trip count.
4773 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4774 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4777 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4778 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4782 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4783 TargetNumRegisters = ForceTargetNumScalarRegs;
4785 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4786 TargetNumRegisters = ForceTargetNumVectorRegs;
4789 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4790 // We divide by these constants so assume that we have at least one
4791 // instruction that uses at least one register.
4792 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4793 R.NumInstructions = std::max(R.NumInstructions, 1U);
4795 // We calculate the interleave count using the following formula.
4796 // Subtract the number of loop invariants from the number of available
4797 // registers. These registers are used by all of the interleaved instances.
4798 // Next, divide the remaining registers by the number of registers that is
4799 // required by the loop, in order to estimate how many parallel instances
4800 // fit without causing spills. All of this is rounded down if necessary to be
4801 // a power of two. We want power of two interleave count to simplify any
4802 // addressing operations or alignment considerations.
4803 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4806 // Don't count the induction variable as interleaved.
4807 if (EnableIndVarRegisterHeur)
4808 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4809 std::max(1U, (R.MaxLocalUsers - 1)));
4811 // Clamp the interleave ranges to reasonable counts.
4812 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4814 // Check if the user has overridden the max.
4816 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4817 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4819 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4820 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4823 // If we did not calculate the cost for VF (because the user selected the VF)
4824 // then we calculate the cost of VF here.
4826 LoopCost = expectedCost(VF);
4828 // Clamp the calculated IC to be between the 1 and the max interleave count
4829 // that the target allows.
4830 if (IC > MaxInterleaveCount)
4831 IC = MaxInterleaveCount;
4835 // Interleave if we vectorized this loop and there is a reduction that could
4836 // benefit from interleaving.
4837 if (VF > 1 && Legal->getReductionVars()->size()) {
4838 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4842 // Note that if we've already vectorized the loop we will have done the
4843 // runtime check and so interleaving won't require further checks.
4844 bool InterleavingRequiresRuntimePointerCheck =
4845 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4847 // We want to interleave small loops in order to reduce the loop overhead and
4848 // potentially expose ILP opportunities.
4849 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4850 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4851 // We assume that the cost overhead is 1 and we use the cost model
4852 // to estimate the cost of the loop and interleave until the cost of the
4853 // loop overhead is about 5% of the cost of the loop.
4855 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4857 // Interleave until store/load ports (estimated by max interleave count) are
4859 unsigned NumStores = Legal->getNumStores();
4860 unsigned NumLoads = Legal->getNumLoads();
4861 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4862 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4864 // If we have a scalar reduction (vector reductions are already dealt with
4865 // by this point), we can increase the critical path length if the loop
4866 // we're interleaving is inside another loop. Limit, by default to 2, so the
4867 // critical path only gets increased by one reduction operation.
4868 if (Legal->getReductionVars()->size() &&
4869 TheLoop->getLoopDepth() > 1) {
4870 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4871 SmallIC = std::min(SmallIC, F);
4872 StoresIC = std::min(StoresIC, F);
4873 LoadsIC = std::min(LoadsIC, F);
4876 if (EnableLoadStoreRuntimeInterleave &&
4877 std::max(StoresIC, LoadsIC) > SmallIC) {
4878 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4879 return std::max(StoresIC, LoadsIC);
4882 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4886 // Interleave if this is a large loop (small loops are already dealt with by
4888 // point) that could benefit from interleaving.
4889 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4890 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4891 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4895 DEBUG(dbgs() << "LV: Not Interleaving.\n");
4899 LoopVectorizationCostModel::RegisterUsage
4900 LoopVectorizationCostModel::calculateRegisterUsage() {
4901 // This function calculates the register usage by measuring the highest number
4902 // of values that are alive at a single location. Obviously, this is a very
4903 // rough estimation. We scan the loop in a topological order in order and
4904 // assign a number to each instruction. We use RPO to ensure that defs are
4905 // met before their users. We assume that each instruction that has in-loop
4906 // users starts an interval. We record every time that an in-loop value is
4907 // used, so we have a list of the first and last occurrences of each
4908 // instruction. Next, we transpose this data structure into a multi map that
4909 // holds the list of intervals that *end* at a specific location. This multi
4910 // map allows us to perform a linear search. We scan the instructions linearly
4911 // and record each time that a new interval starts, by placing it in a set.
4912 // If we find this value in the multi-map then we remove it from the set.
4913 // The max register usage is the maximum size of the set.
4914 // We also search for instructions that are defined outside the loop, but are
4915 // used inside the loop. We need this number separately from the max-interval
4916 // usage number because when we unroll, loop-invariant values do not take
4918 LoopBlocksDFS DFS(TheLoop);
4922 R.NumInstructions = 0;
4924 // Each 'key' in the map opens a new interval. The values
4925 // of the map are the index of the 'last seen' usage of the
4926 // instruction that is the key.
4927 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4928 // Maps instruction to its index.
4929 DenseMap<unsigned, Instruction*> IdxToInstr;
4930 // Marks the end of each interval.
4931 IntervalMap EndPoint;
4932 // Saves the list of instruction indices that are used in the loop.
4933 SmallSet<Instruction*, 8> Ends;
4934 // Saves the list of values that are used in the loop but are
4935 // defined outside the loop, such as arguments and constants.
4936 SmallPtrSet<Value*, 8> LoopInvariants;
4939 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4940 be = DFS.endRPO(); bb != be; ++bb) {
4941 R.NumInstructions += (*bb)->size();
4942 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4944 Instruction *I = it;
4945 IdxToInstr[Index++] = I;
4947 // Save the end location of each USE.
4948 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4949 Value *U = I->getOperand(i);
4950 Instruction *Instr = dyn_cast<Instruction>(U);
4952 // Ignore non-instruction values such as arguments, constants, etc.
4953 if (!Instr) continue;
4955 // If this instruction is outside the loop then record it and continue.
4956 if (!TheLoop->contains(Instr)) {
4957 LoopInvariants.insert(Instr);
4961 // Overwrite previous end points.
4962 EndPoint[Instr] = Index;
4968 // Saves the list of intervals that end with the index in 'key'.
4969 typedef SmallVector<Instruction*, 2> InstrList;
4970 DenseMap<unsigned, InstrList> TransposeEnds;
4972 // Transpose the EndPoints to a list of values that end at each index.
4973 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4975 TransposeEnds[it->second].push_back(it->first);
4977 SmallSet<Instruction*, 8> OpenIntervals;
4978 unsigned MaxUsage = 0;
4981 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4982 for (unsigned int i = 0; i < Index; ++i) {
4983 Instruction *I = IdxToInstr[i];
4984 // Ignore instructions that are never used within the loop.
4985 if (!Ends.count(I)) continue;
4987 // Ignore ephemeral values.
4988 if (EphValues.count(I))
4991 // Remove all of the instructions that end at this location.
4992 InstrList &List = TransposeEnds[i];
4993 for (unsigned int j=0, e = List.size(); j < e; ++j)
4994 OpenIntervals.erase(List[j]);
4996 // Count the number of live interals.
4997 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4999 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5000 OpenIntervals.size() << '\n');
5002 // Add the current instruction to the list of open intervals.
5003 OpenIntervals.insert(I);
5006 unsigned Invariant = LoopInvariants.size();
5007 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5008 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5009 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5011 R.LoopInvariantRegs = Invariant;
5012 R.MaxLocalUsers = MaxUsage;
5016 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5020 for (Loop::block_iterator bb = TheLoop->block_begin(),
5021 be = TheLoop->block_end(); bb != be; ++bb) {
5022 unsigned BlockCost = 0;
5023 BasicBlock *BB = *bb;
5025 // For each instruction in the old loop.
5026 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5027 // Skip dbg intrinsics.
5028 if (isa<DbgInfoIntrinsic>(it))
5031 // Ignore ephemeral values.
5032 if (EphValues.count(it))
5035 unsigned C = getInstructionCost(it, VF);
5037 // Check if we should override the cost.
5038 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5039 C = ForceTargetInstructionCost;
5042 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5043 VF << " For instruction: " << *it << '\n');
5046 // We assume that if-converted blocks have a 50% chance of being executed.
5047 // When the code is scalar then some of the blocks are avoided due to CF.
5048 // When the code is vectorized we execute all code paths.
5049 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5058 /// \brief Check whether the address computation for a non-consecutive memory
5059 /// access looks like an unlikely candidate for being merged into the indexing
5062 /// We look for a GEP which has one index that is an induction variable and all
5063 /// other indices are loop invariant. If the stride of this access is also
5064 /// within a small bound we decide that this address computation can likely be
5065 /// merged into the addressing mode.
5066 /// In all other cases, we identify the address computation as complex.
5067 static bool isLikelyComplexAddressComputation(Value *Ptr,
5068 LoopVectorizationLegality *Legal,
5069 ScalarEvolution *SE,
5070 const Loop *TheLoop) {
5071 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5075 // We are looking for a gep with all loop invariant indices except for one
5076 // which should be an induction variable.
5077 unsigned NumOperands = Gep->getNumOperands();
5078 for (unsigned i = 1; i < NumOperands; ++i) {
5079 Value *Opd = Gep->getOperand(i);
5080 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5081 !Legal->isInductionVariable(Opd))
5085 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5086 // can likely be merged into the address computation.
5087 unsigned MaxMergeDistance = 64;
5089 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5093 // Check the step is constant.
5094 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5095 // Calculate the pointer stride and check if it is consecutive.
5096 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5100 const APInt &APStepVal = C->getValue()->getValue();
5102 // Huge step value - give up.
5103 if (APStepVal.getBitWidth() > 64)
5106 int64_t StepVal = APStepVal.getSExtValue();
5108 return StepVal > MaxMergeDistance;
5111 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5112 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5118 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5119 // If we know that this instruction will remain uniform, check the cost of
5120 // the scalar version.
5121 if (Legal->isUniformAfterVectorization(I))
5124 Type *RetTy = I->getType();
5125 Type *VectorTy = ToVectorTy(RetTy, VF);
5127 // TODO: We need to estimate the cost of intrinsic calls.
5128 switch (I->getOpcode()) {
5129 case Instruction::GetElementPtr:
5130 // We mark this instruction as zero-cost because the cost of GEPs in
5131 // vectorized code depends on whether the corresponding memory instruction
5132 // is scalarized or not. Therefore, we handle GEPs with the memory
5133 // instruction cost.
5135 case Instruction::Br: {
5136 return TTI.getCFInstrCost(I->getOpcode());
5138 case Instruction::PHI:
5139 //TODO: IF-converted IFs become selects.
5141 case Instruction::Add:
5142 case Instruction::FAdd:
5143 case Instruction::Sub:
5144 case Instruction::FSub:
5145 case Instruction::Mul:
5146 case Instruction::FMul:
5147 case Instruction::UDiv:
5148 case Instruction::SDiv:
5149 case Instruction::FDiv:
5150 case Instruction::URem:
5151 case Instruction::SRem:
5152 case Instruction::FRem:
5153 case Instruction::Shl:
5154 case Instruction::LShr:
5155 case Instruction::AShr:
5156 case Instruction::And:
5157 case Instruction::Or:
5158 case Instruction::Xor: {
5159 // Since we will replace the stride by 1 the multiplication should go away.
5160 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5162 // Certain instructions can be cheaper to vectorize if they have a constant
5163 // second vector operand. One example of this are shifts on x86.
5164 TargetTransformInfo::OperandValueKind Op1VK =
5165 TargetTransformInfo::OK_AnyValue;
5166 TargetTransformInfo::OperandValueKind Op2VK =
5167 TargetTransformInfo::OK_AnyValue;
5168 TargetTransformInfo::OperandValueProperties Op1VP =
5169 TargetTransformInfo::OP_None;
5170 TargetTransformInfo::OperandValueProperties Op2VP =
5171 TargetTransformInfo::OP_None;
5172 Value *Op2 = I->getOperand(1);
5174 // Check for a splat of a constant or for a non uniform vector of constants.
5175 if (isa<ConstantInt>(Op2)) {
5176 ConstantInt *CInt = cast<ConstantInt>(Op2);
5177 if (CInt && CInt->getValue().isPowerOf2())
5178 Op2VP = TargetTransformInfo::OP_PowerOf2;
5179 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5180 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5181 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5182 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5184 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5185 if (CInt && CInt->getValue().isPowerOf2())
5186 Op2VP = TargetTransformInfo::OP_PowerOf2;
5187 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5191 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5194 case Instruction::Select: {
5195 SelectInst *SI = cast<SelectInst>(I);
5196 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5197 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5198 Type *CondTy = SI->getCondition()->getType();
5200 CondTy = VectorType::get(CondTy, VF);
5202 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5204 case Instruction::ICmp:
5205 case Instruction::FCmp: {
5206 Type *ValTy = I->getOperand(0)->getType();
5207 VectorTy = ToVectorTy(ValTy, VF);
5208 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5210 case Instruction::Store:
5211 case Instruction::Load: {
5212 StoreInst *SI = dyn_cast<StoreInst>(I);
5213 LoadInst *LI = dyn_cast<LoadInst>(I);
5214 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5216 VectorTy = ToVectorTy(ValTy, VF);
5218 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5219 unsigned AS = SI ? SI->getPointerAddressSpace() :
5220 LI->getPointerAddressSpace();
5221 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5222 // We add the cost of address computation here instead of with the gep
5223 // instruction because only here we know whether the operation is
5226 return TTI.getAddressComputationCost(VectorTy) +
5227 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5229 // For an interleaved access, calculate the total cost of the whole
5230 // interleave group.
5231 if (Legal->isAccessInterleaved(I)) {
5232 auto Group = Legal->getInterleavedAccessGroup(I);
5233 assert(Group && "Fail to get an interleaved access group.");
5235 // Only calculate the cost once at the insert position.
5236 if (Group->getInsertPos() != I)
5239 unsigned InterleaveFactor = Group->getFactor();
5241 VectorType::get(VectorTy->getVectorElementType(),
5242 VectorTy->getVectorNumElements() * InterleaveFactor);
5244 // Holds the indices of existing members in an interleaved load group.
5245 // An interleaved store group doesn't need this as it dones't allow gaps.
5246 SmallVector<unsigned, 4> Indices;
5248 for (unsigned i = 0; i < InterleaveFactor; i++)
5249 if (Group->getMember(i))
5250 Indices.push_back(i);
5253 // Calculate the cost of the whole interleaved group.
5254 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5255 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5256 Group->getAlignment(), AS);
5258 if (Group->isReverse())
5260 Group->getNumMembers() *
5261 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5263 // FIXME: The interleaved load group with a huge gap could be even more
5264 // expensive than scalar operations. Then we could ignore such group and
5265 // use scalar operations instead.
5269 // Scalarized loads/stores.
5270 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5271 bool Reverse = ConsecutiveStride < 0;
5272 const DataLayout &DL = I->getModule()->getDataLayout();
5273 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5274 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5275 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5276 bool IsComplexComputation =
5277 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5279 // The cost of extracting from the value vector and pointer vector.
5280 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5281 for (unsigned i = 0; i < VF; ++i) {
5282 // The cost of extracting the pointer operand.
5283 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5284 // In case of STORE, the cost of ExtractElement from the vector.
5285 // In case of LOAD, the cost of InsertElement into the returned
5287 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5288 Instruction::InsertElement,
5292 // The cost of the scalar loads/stores.
5293 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5294 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5299 // Wide load/stores.
5300 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5301 if (Legal->isMaskRequired(I))
5302 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5305 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5308 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5312 case Instruction::ZExt:
5313 case Instruction::SExt:
5314 case Instruction::FPToUI:
5315 case Instruction::FPToSI:
5316 case Instruction::FPExt:
5317 case Instruction::PtrToInt:
5318 case Instruction::IntToPtr:
5319 case Instruction::SIToFP:
5320 case Instruction::UIToFP:
5321 case Instruction::Trunc:
5322 case Instruction::FPTrunc:
5323 case Instruction::BitCast: {
5324 // We optimize the truncation of induction variable.
5325 // The cost of these is the same as the scalar operation.
5326 if (I->getOpcode() == Instruction::Trunc &&
5327 Legal->isInductionVariable(I->getOperand(0)))
5328 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5329 I->getOperand(0)->getType());
5331 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5332 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5334 case Instruction::Call: {
5335 bool NeedToScalarize;
5336 CallInst *CI = cast<CallInst>(I);
5337 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5338 if (getIntrinsicIDForCall(CI, TLI))
5339 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5343 // We are scalarizing the instruction. Return the cost of the scalar
5344 // instruction, plus the cost of insert and extract into vector
5345 // elements, times the vector width.
5348 if (!RetTy->isVoidTy() && VF != 1) {
5349 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5351 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5354 // The cost of inserting the results plus extracting each one of the
5356 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5359 // The cost of executing VF copies of the scalar instruction. This opcode
5360 // is unknown. Assume that it is the same as 'mul'.
5361 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5367 char LoopVectorize::ID = 0;
5368 static const char lv_name[] = "Loop Vectorization";
5369 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5370 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5371 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5372 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5373 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5374 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5375 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5376 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5377 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5378 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5379 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5380 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5383 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5384 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5388 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5389 // Check for a store.
5390 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5391 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5393 // Check for a load.
5394 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5395 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5401 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5402 bool IfPredicateStore) {
5403 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5404 // Holds vector parameters or scalars, in case of uniform vals.
5405 SmallVector<VectorParts, 4> Params;
5407 setDebugLocFromInst(Builder, Instr);
5409 // Find all of the vectorized parameters.
5410 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5411 Value *SrcOp = Instr->getOperand(op);
5413 // If we are accessing the old induction variable, use the new one.
5414 if (SrcOp == OldInduction) {
5415 Params.push_back(getVectorValue(SrcOp));
5419 // Try using previously calculated values.
5420 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5422 // If the src is an instruction that appeared earlier in the basic block
5423 // then it should already be vectorized.
5424 if (SrcInst && OrigLoop->contains(SrcInst)) {
5425 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5426 // The parameter is a vector value from earlier.
5427 Params.push_back(WidenMap.get(SrcInst));
5429 // The parameter is a scalar from outside the loop. Maybe even a constant.
5430 VectorParts Scalars;
5431 Scalars.append(UF, SrcOp);
5432 Params.push_back(Scalars);
5436 assert(Params.size() == Instr->getNumOperands() &&
5437 "Invalid number of operands");
5439 // Does this instruction return a value ?
5440 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5442 Value *UndefVec = IsVoidRetTy ? nullptr :
5443 UndefValue::get(Instr->getType());
5444 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5445 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5447 Instruction *InsertPt = Builder.GetInsertPoint();
5448 BasicBlock *IfBlock = Builder.GetInsertBlock();
5449 BasicBlock *CondBlock = nullptr;
5452 Loop *VectorLp = nullptr;
5453 if (IfPredicateStore) {
5454 assert(Instr->getParent()->getSinglePredecessor() &&
5455 "Only support single predecessor blocks");
5456 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5457 Instr->getParent());
5458 VectorLp = LI->getLoopFor(IfBlock);
5459 assert(VectorLp && "Must have a loop for this block");
5462 // For each vector unroll 'part':
5463 for (unsigned Part = 0; Part < UF; ++Part) {
5464 // For each scalar that we create:
5466 // Start an "if (pred) a[i] = ..." block.
5467 Value *Cmp = nullptr;
5468 if (IfPredicateStore) {
5469 if (Cond[Part]->getType()->isVectorTy())
5471 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5472 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5473 ConstantInt::get(Cond[Part]->getType(), 1));
5474 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5475 LoopVectorBody.push_back(CondBlock);
5476 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5477 // Update Builder with newly created basic block.
5478 Builder.SetInsertPoint(InsertPt);
5481 Instruction *Cloned = Instr->clone();
5483 Cloned->setName(Instr->getName() + ".cloned");
5484 // Replace the operands of the cloned instructions with extracted scalars.
5485 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5486 Value *Op = Params[op][Part];
5487 Cloned->setOperand(op, Op);
5490 // Place the cloned scalar in the new loop.
5491 Builder.Insert(Cloned);
5493 // If the original scalar returns a value we need to place it in a vector
5494 // so that future users will be able to use it.
5496 VecResults[Part] = Cloned;
5499 if (IfPredicateStore) {
5500 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5501 LoopVectorBody.push_back(NewIfBlock);
5502 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5503 Builder.SetInsertPoint(InsertPt);
5504 ReplaceInstWithInst(IfBlock->getTerminator(),
5505 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
5506 IfBlock = NewIfBlock;
5511 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5512 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5513 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5515 return scalarizeInstruction(Instr, IfPredicateStore);
5518 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5522 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5526 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5527 // When unrolling and the VF is 1, we only need to add a simple scalar.
5528 Type *ITy = Val->getType();
5529 assert(!ITy->isVectorTy() && "Val must be a scalar");
5530 Constant *C = ConstantInt::get(ITy, StartIdx);
5531 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");