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/Hashing.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/Analysis/AliasAnalysis.h"
60 #include "llvm/Analysis/BasicAliasAnalysis.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/DemandedBits.h"
66 #include "llvm/Analysis/GlobalsModRef.h"
67 #include "llvm/Analysis/LoopAccessAnalysis.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Analysis/LoopIterator.h"
70 #include "llvm/Analysis/LoopPass.h"
71 #include "llvm/Analysis/ScalarEvolution.h"
72 #include "llvm/Analysis/ScalarEvolutionExpander.h"
73 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
74 #include "llvm/Analysis/TargetTransformInfo.h"
75 #include "llvm/Analysis/ValueTracking.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfo.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/DiagnosticInfo.h"
81 #include "llvm/IR/Dominators.h"
82 #include "llvm/IR/Function.h"
83 #include "llvm/IR/IRBuilder.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Module.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/IR/ValueHandle.h"
92 #include "llvm/IR/Verifier.h"
93 #include "llvm/Pass.h"
94 #include "llvm/Support/BranchProbability.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/raw_ostream.h"
98 #include "llvm/Transforms/Scalar.h"
99 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
100 #include "llvm/Transforms/Utils/Local.h"
101 #include "llvm/Analysis/VectorUtils.h"
102 #include "llvm/Transforms/Utils/LoopUtils.h"
104 #include <functional>
108 using namespace llvm;
109 using namespace llvm::PatternMatch;
111 #define LV_NAME "loop-vectorize"
112 #define DEBUG_TYPE LV_NAME
114 STATISTIC(LoopsVectorized, "Number of loops vectorized");
115 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
118 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
119 cl::desc("Enable if-conversion during vectorization."));
121 /// We don't vectorize loops with a known constant trip count below this number.
122 static cl::opt<unsigned>
123 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
125 cl::desc("Don't vectorize loops with a constant "
126 "trip count that is smaller than this "
129 /// This enables versioning on the strides of symbolically striding memory
130 /// accesses in code like the following.
131 /// for (i = 0; i < N; ++i)
132 /// A[i * Stride1] += B[i * Stride2] ...
134 /// Will be roughly translated to
135 /// if (Stride1 == 1 && Stride2 == 1) {
136 /// for (i = 0; i < N; i+=4)
140 static cl::opt<bool> EnableMemAccessVersioning(
141 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
142 cl::desc("Enable symblic stride memory access versioning"));
144 static cl::opt<bool> EnableInterleavedMemAccesses(
145 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
146 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
148 /// Maximum factor for an interleaved memory access.
149 static cl::opt<unsigned> MaxInterleaveGroupFactor(
150 "max-interleave-group-factor", cl::Hidden,
151 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
154 /// We don't interleave loops with a known constant trip count below this
156 static const unsigned TinyTripCountInterleaveThreshold = 128;
158 static cl::opt<unsigned> ForceTargetNumScalarRegs(
159 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
160 cl::desc("A flag that overrides the target's number of scalar registers."));
162 static cl::opt<unsigned> ForceTargetNumVectorRegs(
163 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
164 cl::desc("A flag that overrides the target's number of vector registers."));
166 /// Maximum vectorization interleave count.
167 static const unsigned MaxInterleaveFactor = 16;
169 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
170 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
171 cl::desc("A flag that overrides the target's max interleave factor for "
174 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
175 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
176 cl::desc("A flag that overrides the target's max interleave factor for "
177 "vectorized loops."));
179 static cl::opt<unsigned> ForceTargetInstructionCost(
180 "force-target-instruction-cost", cl::init(0), cl::Hidden,
181 cl::desc("A flag that overrides the target's expected cost for "
182 "an instruction to a single constant value. Mostly "
183 "useful for getting consistent testing."));
185 static cl::opt<unsigned> SmallLoopCost(
186 "small-loop-cost", cl::init(20), cl::Hidden,
188 "The cost of a loop that is considered 'small' by the interleaver."));
190 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
191 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
192 cl::desc("Enable the use of the block frequency analysis to access PGO "
193 "heuristics minimizing code growth in cold regions and being more "
194 "aggressive in hot regions."));
196 // Runtime interleave loops for load/store throughput.
197 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
198 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
200 "Enable runtime interleaving until load/store ports are saturated"));
202 /// The number of stores in a loop that are allowed to need predication.
203 static cl::opt<unsigned> NumberOfStoresToPredicate(
204 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
205 cl::desc("Max number of stores to be predicated behind an if."));
207 static cl::opt<bool> EnableIndVarRegisterHeur(
208 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
209 cl::desc("Count the induction variable only once when interleaving"));
211 static cl::opt<bool> EnableCondStoresVectorization(
212 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
213 cl::desc("Enable if predication of stores during vectorization."));
215 static cl::opt<unsigned> MaxNestedScalarReductionIC(
216 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
217 cl::desc("The maximum interleave count to use when interleaving a scalar "
218 "reduction in a nested loop."));
220 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
221 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
222 cl::desc("The maximum allowed number of runtime memory checks with a "
223 "vectorize(enable) pragma."));
225 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
226 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
227 cl::desc("The maximum number of SCEV checks allowed."));
229 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
230 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
231 cl::desc("The maximum number of SCEV checks allowed with a "
232 "vectorize(enable) pragma"));
236 // Forward declarations.
237 class LoopVectorizeHints;
238 class LoopVectorizationLegality;
239 class LoopVectorizationCostModel;
240 class LoopVectorizationRequirements;
242 /// \brief This modifies LoopAccessReport to initialize message with
243 /// loop-vectorizer-specific part.
244 class VectorizationReport : public LoopAccessReport {
246 VectorizationReport(Instruction *I = nullptr)
247 : LoopAccessReport("loop not vectorized: ", I) {}
249 /// \brief This allows promotion of the loop-access analysis report into the
250 /// loop-vectorizer report. It modifies the message to add the
251 /// loop-vectorizer-specific part of the message.
252 explicit VectorizationReport(const LoopAccessReport &R)
253 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
257 /// A helper function for converting Scalar types to vector types.
258 /// If the incoming type is void, we return void. If the VF is 1, we return
260 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
261 if (Scalar->isVoidTy() || VF == 1)
263 return VectorType::get(Scalar, VF);
266 /// InnerLoopVectorizer vectorizes loops which contain only one basic
267 /// block to a specified vectorization factor (VF).
268 /// This class performs the widening of scalars into vectors, or multiple
269 /// scalars. This class also implements the following features:
270 /// * It inserts an epilogue loop for handling loops that don't have iteration
271 /// counts that are known to be a multiple of the vectorization factor.
272 /// * It handles the code generation for reduction variables.
273 /// * Scalarization (implementation using scalars) of un-vectorizable
275 /// InnerLoopVectorizer does not perform any vectorization-legality
276 /// checks, and relies on the caller to check for the different legality
277 /// aspects. The InnerLoopVectorizer relies on the
278 /// LoopVectorizationLegality class to provide information about the induction
279 /// and reduction variables that were found to a given vectorization factor.
280 class InnerLoopVectorizer {
282 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
283 DominatorTree *DT, const TargetLibraryInfo *TLI,
284 const TargetTransformInfo *TTI, unsigned VecWidth,
285 unsigned UnrollFactor, SCEVUnionPredicate &Preds)
286 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
287 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
288 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
289 TripCount(nullptr), VectorTripCount(nullptr), Legal(nullptr),
290 AddedSafetyChecks(false), Preds(Preds) {}
292 // Perform the actual loop widening (vectorization).
293 // MinimumBitWidths maps scalar integer values to the smallest bitwidth they
294 // can be validly truncated to. The cost model has assumed this truncation
295 // will happen when vectorizing.
296 void vectorize(LoopVectorizationLegality *L,
297 DenseMap<Instruction*,uint64_t> MinimumBitWidths) {
298 MinBWs = MinimumBitWidths;
300 // Create a new empty loop. Unlink the old loop and connect the new one.
302 // Widen each instruction in the old loop to a new one in the new loop.
303 // Use the Legality module to find the induction and reduction variables.
307 // Return true if any runtime check is added.
308 bool IsSafetyChecksAdded() {
309 return AddedSafetyChecks;
312 virtual ~InnerLoopVectorizer() {}
315 /// A small list of PHINodes.
316 typedef SmallVector<PHINode*, 4> PhiVector;
317 /// When we unroll loops we have multiple vector values for each scalar.
318 /// This data structure holds the unrolled and vectorized values that
319 /// originated from one scalar instruction.
320 typedef SmallVector<Value*, 2> VectorParts;
322 // When we if-convert we need to create edge masks. We have to cache values
323 // so that we don't end up with exponential recursion/IR.
324 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
325 VectorParts> EdgeMaskCache;
327 /// Create an empty loop, based on the loop ranges of the old loop.
328 void createEmptyLoop();
329 /// Create a new induction variable inside L.
330 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
331 Value *Step, Instruction *DL);
332 /// Copy and widen the instructions from the old loop.
333 virtual void vectorizeLoop();
335 /// \brief The Loop exit block may have single value PHI nodes where the
336 /// incoming value is 'Undef'. While vectorizing we only handled real values
337 /// that were defined inside the loop. Here we fix the 'undef case'.
341 /// Shrinks vector element sizes based on information in "MinBWs".
342 void truncateToMinimalBitwidths();
344 /// A helper function that computes the predicate of the block BB, assuming
345 /// that the header block of the loop is set to True. It returns the *entry*
346 /// mask for the block BB.
347 VectorParts createBlockInMask(BasicBlock *BB);
348 /// A helper function that computes the predicate of the edge between SRC
350 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
352 /// A helper function to vectorize a single BB within the innermost loop.
353 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
355 /// Vectorize a single PHINode in a block. This method handles the induction
356 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
357 /// arbitrary length vectors.
358 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
359 unsigned UF, unsigned VF, PhiVector *PV);
361 /// Insert the new loop to the loop hierarchy and pass manager
362 /// and update the analysis passes.
363 void updateAnalysis();
365 /// This instruction is un-vectorizable. Implement it as a sequence
366 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
367 /// scalarized instruction behind an if block predicated on the control
368 /// dependence of the instruction.
369 virtual void scalarizeInstruction(Instruction *Instr,
370 bool IfPredicateStore=false);
372 /// Vectorize Load and Store instructions,
373 virtual void vectorizeMemoryInstruction(Instruction *Instr);
375 /// Create a broadcast instruction. This method generates a broadcast
376 /// instruction (shuffle) for loop invariant values and for the induction
377 /// value. If this is the induction variable then we extend it to N, N+1, ...
378 /// this is needed because each iteration in the loop corresponds to a SIMD
380 virtual Value *getBroadcastInstrs(Value *V);
382 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
383 /// to each vector element of Val. The sequence starts at StartIndex.
384 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
386 /// When we go over instructions in the basic block we rely on previous
387 /// values within the current basic block or on loop invariant values.
388 /// When we widen (vectorize) values we place them in the map. If the values
389 /// are not within the map, they have to be loop invariant, so we simply
390 /// broadcast them into a vector.
391 VectorParts &getVectorValue(Value *V);
393 /// Try to vectorize the interleaved access group that \p Instr belongs to.
394 void vectorizeInterleaveGroup(Instruction *Instr);
396 /// Generate a shuffle sequence that will reverse the vector Vec.
397 virtual Value *reverseVector(Value *Vec);
399 /// Returns (and creates if needed) the original loop trip count.
400 Value *getOrCreateTripCount(Loop *NewLoop);
402 /// Returns (and creates if needed) the trip count of the widened loop.
403 Value *getOrCreateVectorTripCount(Loop *NewLoop);
405 /// Emit a bypass check to see if the trip count would overflow, or we
406 /// wouldn't have enough iterations to execute one vector loop.
407 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
408 /// Emit a bypass check to see if the vector trip count is nonzero.
409 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
410 /// Emit a bypass check to see if all of the SCEV assumptions we've
411 /// had to make are correct.
412 void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
413 /// Emit bypass checks to check any memory assumptions we may have made.
414 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
416 /// This is a helper class that holds the vectorizer state. It maps scalar
417 /// instructions to vector instructions. When the code is 'unrolled' then
418 /// then a single scalar value is mapped to multiple vector parts. The parts
419 /// are stored in the VectorPart type.
421 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
423 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
425 /// \return True if 'Key' is saved in the Value Map.
426 bool has(Value *Key) const { return MapStorage.count(Key); }
428 /// Initializes a new entry in the map. Sets all of the vector parts to the
429 /// save value in 'Val'.
430 /// \return A reference to a vector with splat values.
431 VectorParts &splat(Value *Key, Value *Val) {
432 VectorParts &Entry = MapStorage[Key];
433 Entry.assign(UF, Val);
437 ///\return A reference to the value that is stored at 'Key'.
438 VectorParts &get(Value *Key) {
439 VectorParts &Entry = MapStorage[Key];
442 assert(Entry.size() == UF);
447 /// The unroll factor. Each entry in the map stores this number of vector
451 /// Map storage. We use std::map and not DenseMap because insertions to a
452 /// dense map invalidates its iterators.
453 std::map<Value *, VectorParts> MapStorage;
456 /// The original loop.
458 /// Scev analysis to use.
466 /// Target Library Info.
467 const TargetLibraryInfo *TLI;
468 /// Target Transform Info.
469 const TargetTransformInfo *TTI;
471 /// The vectorization SIMD factor to use. Each vector will have this many
476 /// The vectorization unroll factor to use. Each scalar is vectorized to this
477 /// many different vector instructions.
480 /// The builder that we use
483 // --- Vectorization state ---
485 /// The vector-loop preheader.
486 BasicBlock *LoopVectorPreHeader;
487 /// The scalar-loop preheader.
488 BasicBlock *LoopScalarPreHeader;
489 /// Middle Block between the vector and the scalar.
490 BasicBlock *LoopMiddleBlock;
491 ///The ExitBlock of the scalar loop.
492 BasicBlock *LoopExitBlock;
493 ///The vector loop body.
494 SmallVector<BasicBlock *, 4> LoopVectorBody;
495 ///The scalar loop body.
496 BasicBlock *LoopScalarBody;
497 /// A list of all bypass blocks. The first block is the entry of the loop.
498 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
500 /// The new Induction variable which was added to the new block.
502 /// The induction variable of the old basic block.
503 PHINode *OldInduction;
504 /// Maps scalars to widened vectors.
506 /// Store instructions that should be predicated, as a pair
507 /// <StoreInst, Predicate>
508 SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
509 EdgeMaskCache MaskCache;
510 /// Trip count of the original loop.
512 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
513 Value *VectorTripCount;
515 /// Map of scalar integer values to the smallest bitwidth they can be legally
516 /// represented as. The vector equivalents of these values should be truncated
518 DenseMap<Instruction*,uint64_t> MinBWs;
519 LoopVectorizationLegality *Legal;
521 // Record whether runtime check is added.
522 bool AddedSafetyChecks;
524 /// The SCEV predicate containing all the SCEV-related assumptions.
525 /// The predicate is used to simplify existing expressions in the
526 /// context of existing SCEV assumptions. Since legality checking is
527 /// not done here, we don't need to use this predicate to record
528 /// further assumptions.
529 SCEVUnionPredicate &Preds;
532 class InnerLoopUnroller : public InnerLoopVectorizer {
534 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
535 DominatorTree *DT, const TargetLibraryInfo *TLI,
536 const TargetTransformInfo *TTI, unsigned UnrollFactor,
537 SCEVUnionPredicate &Preds)
538 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor,
542 void scalarizeInstruction(Instruction *Instr,
543 bool IfPredicateStore = false) override;
544 void vectorizeMemoryInstruction(Instruction *Instr) override;
545 Value *getBroadcastInstrs(Value *V) override;
546 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
547 Value *reverseVector(Value *Vec) override;
550 /// \brief Look for a meaningful debug location on the instruction or it's
552 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
557 if (I->getDebugLoc() != Empty)
560 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
561 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
562 if (OpInst->getDebugLoc() != Empty)
569 /// \brief Set the debug location in the builder using the debug location in the
571 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
572 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
573 B.SetCurrentDebugLocation(Inst->getDebugLoc());
575 B.SetCurrentDebugLocation(DebugLoc());
579 /// \return string containing a file name and a line # for the given loop.
580 static std::string getDebugLocString(const Loop *L) {
583 raw_string_ostream OS(Result);
584 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
585 LoopDbgLoc.print(OS);
587 // Just print the module name.
588 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
595 /// \brief Propagate known metadata from one instruction to another.
596 static void propagateMetadata(Instruction *To, const Instruction *From) {
597 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
598 From->getAllMetadataOtherThanDebugLoc(Metadata);
600 for (auto M : Metadata) {
601 unsigned Kind = M.first;
603 // These are safe to transfer (this is safe for TBAA, even when we
604 // if-convert, because should that metadata have had a control dependency
605 // on the condition, and thus actually aliased with some other
606 // non-speculated memory access when the condition was false, this would be
607 // caught by the runtime overlap checks).
608 if (Kind != LLVMContext::MD_tbaa &&
609 Kind != LLVMContext::MD_alias_scope &&
610 Kind != LLVMContext::MD_noalias &&
611 Kind != LLVMContext::MD_fpmath &&
612 Kind != LLVMContext::MD_nontemporal)
615 To->setMetadata(Kind, M.second);
619 /// \brief Propagate known metadata from one instruction to a vector of others.
620 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
622 if (Instruction *I = dyn_cast<Instruction>(V))
623 propagateMetadata(I, From);
626 /// \brief The group of interleaved loads/stores sharing the same stride and
627 /// close to each other.
629 /// Each member in this group has an index starting from 0, and the largest
630 /// index should be less than interleaved factor, which is equal to the absolute
631 /// value of the access's stride.
633 /// E.g. An interleaved load group of factor 4:
634 /// for (unsigned i = 0; i < 1024; i+=4) {
635 /// a = A[i]; // Member of index 0
636 /// b = A[i+1]; // Member of index 1
637 /// d = A[i+3]; // Member of index 3
641 /// An interleaved store group of factor 4:
642 /// for (unsigned i = 0; i < 1024; i+=4) {
644 /// A[i] = a; // Member of index 0
645 /// A[i+1] = b; // Member of index 1
646 /// A[i+2] = c; // Member of index 2
647 /// A[i+3] = d; // Member of index 3
650 /// Note: the interleaved load group could have gaps (missing members), but
651 /// the interleaved store group doesn't allow gaps.
652 class InterleaveGroup {
654 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
655 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
656 assert(Align && "The alignment should be non-zero");
658 Factor = std::abs(Stride);
659 assert(Factor > 1 && "Invalid interleave factor");
661 Reverse = Stride < 0;
665 bool isReverse() const { return Reverse; }
666 unsigned getFactor() const { return Factor; }
667 unsigned getAlignment() const { return Align; }
668 unsigned getNumMembers() const { return Members.size(); }
670 /// \brief Try to insert a new member \p Instr with index \p Index and
671 /// alignment \p NewAlign. The index is related to the leader and it could be
672 /// negative if it is the new leader.
674 /// \returns false if the instruction doesn't belong to the group.
675 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
676 assert(NewAlign && "The new member's alignment should be non-zero");
678 int Key = Index + SmallestKey;
680 // Skip if there is already a member with the same index.
681 if (Members.count(Key))
684 if (Key > LargestKey) {
685 // The largest index is always less than the interleave factor.
686 if (Index >= static_cast<int>(Factor))
690 } else if (Key < SmallestKey) {
691 // The largest index is always less than the interleave factor.
692 if (LargestKey - Key >= static_cast<int>(Factor))
698 // It's always safe to select the minimum alignment.
699 Align = std::min(Align, NewAlign);
700 Members[Key] = Instr;
704 /// \brief Get the member with the given index \p Index
706 /// \returns nullptr if contains no such member.
707 Instruction *getMember(unsigned Index) const {
708 int Key = SmallestKey + Index;
709 if (!Members.count(Key))
712 return Members.find(Key)->second;
715 /// \brief Get the index for the given member. Unlike the key in the member
716 /// map, the index starts from 0.
717 unsigned getIndex(Instruction *Instr) const {
718 for (auto I : Members)
719 if (I.second == Instr)
720 return I.first - SmallestKey;
722 llvm_unreachable("InterleaveGroup contains no such member");
725 Instruction *getInsertPos() const { return InsertPos; }
726 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
729 unsigned Factor; // Interleave Factor.
732 DenseMap<int, Instruction *> Members;
736 // To avoid breaking dependences, vectorized instructions of an interleave
737 // group should be inserted at either the first load or the last store in
740 // E.g. %even = load i32 // Insert Position
741 // %add = add i32 %even // Use of %even
745 // %odd = add i32 // Def of %odd
746 // store i32 %odd // Insert Position
747 Instruction *InsertPos;
750 /// \brief Drive the analysis of interleaved memory accesses in the loop.
752 /// Use this class to analyze interleaved accesses only when we can vectorize
753 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
754 /// on interleaved accesses is unsafe.
756 /// The analysis collects interleave groups and records the relationships
757 /// between the member and the group in a map.
758 class InterleavedAccessInfo {
760 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT,
761 SCEVUnionPredicate &Preds)
762 : SE(SE), TheLoop(L), DT(DT), Preds(Preds) {}
764 ~InterleavedAccessInfo() {
765 SmallSet<InterleaveGroup *, 4> DelSet;
766 // Avoid releasing a pointer twice.
767 for (auto &I : InterleaveGroupMap)
768 DelSet.insert(I.second);
769 for (auto *Ptr : DelSet)
773 /// \brief Analyze the interleaved accesses and collect them in interleave
774 /// groups. Substitute symbolic strides using \p Strides.
775 void analyzeInterleaving(const ValueToValueMap &Strides);
777 /// \brief Check if \p Instr belongs to any interleave group.
778 bool isInterleaved(Instruction *Instr) const {
779 return InterleaveGroupMap.count(Instr);
782 /// \brief Get the interleave group that \p Instr belongs to.
784 /// \returns nullptr if doesn't have such group.
785 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
786 if (InterleaveGroupMap.count(Instr))
787 return InterleaveGroupMap.find(Instr)->second;
796 /// The SCEV predicate containing all the SCEV-related assumptions.
797 /// The predicate is used to simplify SCEV expressions in the
798 /// context of existing SCEV assumptions. The interleaved access
799 /// analysis can also add new predicates (for example by versioning
800 /// strides of pointers).
801 SCEVUnionPredicate &Preds;
803 /// Holds the relationships between the members and the interleave group.
804 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
806 /// \brief The descriptor for a strided memory access.
807 struct StrideDescriptor {
808 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
810 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
812 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
814 int Stride; // The access's stride. It is negative for a reverse access.
815 const SCEV *Scev; // The scalar expression of this access
816 unsigned Size; // The size of the memory object.
817 unsigned Align; // The alignment of this access.
820 /// \brief Create a new interleave group with the given instruction \p Instr,
821 /// stride \p Stride and alignment \p Align.
823 /// \returns the newly created interleave group.
824 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
826 assert(!InterleaveGroupMap.count(Instr) &&
827 "Already in an interleaved access group");
828 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
829 return InterleaveGroupMap[Instr];
832 /// \brief Release the group and remove all the relationships.
833 void releaseGroup(InterleaveGroup *Group) {
834 for (unsigned i = 0; i < Group->getFactor(); i++)
835 if (Instruction *Member = Group->getMember(i))
836 InterleaveGroupMap.erase(Member);
841 /// \brief Collect all the accesses with a constant stride in program order.
842 void collectConstStridedAccesses(
843 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
844 const ValueToValueMap &Strides);
847 /// Utility class for getting and setting loop vectorizer hints in the form
848 /// of loop metadata.
849 /// This class keeps a number of loop annotations locally (as member variables)
850 /// and can, upon request, write them back as metadata on the loop. It will
851 /// initially scan the loop for existing metadata, and will update the local
852 /// values based on information in the loop.
853 /// We cannot write all values to metadata, as the mere presence of some info,
854 /// for example 'force', means a decision has been made. So, we need to be
855 /// careful NOT to add them if the user hasn't specifically asked so.
856 class LoopVectorizeHints {
863 /// Hint - associates name and validation with the hint value.
866 unsigned Value; // This may have to change for non-numeric values.
869 Hint(const char * Name, unsigned Value, HintKind Kind)
870 : Name(Name), Value(Value), Kind(Kind) { }
872 bool validate(unsigned Val) {
875 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
877 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
885 /// Vectorization width.
887 /// Vectorization interleave factor.
889 /// Vectorization forced
892 /// Return the loop metadata prefix.
893 static StringRef Prefix() { return "llvm.loop."; }
897 FK_Undefined = -1, ///< Not selected.
898 FK_Disabled = 0, ///< Forcing disabled.
899 FK_Enabled = 1, ///< Forcing enabled.
902 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
903 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
905 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
906 Force("vectorize.enable", FK_Undefined, HK_FORCE),
908 // Populate values with existing loop metadata.
909 getHintsFromMetadata();
911 // force-vector-interleave overrides DisableInterleaving.
912 if (VectorizerParams::isInterleaveForced())
913 Interleave.Value = VectorizerParams::VectorizationInterleave;
915 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
916 << "LV: Interleaving disabled by the pass manager\n");
919 /// Mark the loop L as already vectorized by setting the width to 1.
920 void setAlreadyVectorized() {
921 Width.Value = Interleave.Value = 1;
922 Hint Hints[] = {Width, Interleave};
923 writeHintsToMetadata(Hints);
926 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
927 if (getForce() == LoopVectorizeHints::FK_Disabled) {
928 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
929 emitOptimizationRemarkAnalysis(F->getContext(),
930 vectorizeAnalysisPassName(), *F,
931 L->getStartLoc(), emitRemark());
935 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
936 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
937 emitOptimizationRemarkAnalysis(F->getContext(),
938 vectorizeAnalysisPassName(), *F,
939 L->getStartLoc(), emitRemark());
943 if (getWidth() == 1 && getInterleave() == 1) {
944 // FIXME: Add a separate metadata to indicate when the loop has already
945 // been vectorized instead of setting width and count to 1.
946 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
947 // FIXME: Add interleave.disable metadata. This will allow
948 // vectorize.disable to be used without disabling the pass and errors
949 // to differentiate between disabled vectorization and a width of 1.
950 emitOptimizationRemarkAnalysis(
951 F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
952 "loop not vectorized: vectorization and interleaving are explicitly "
953 "disabled, or vectorize width and interleave count are both set to "
961 /// Dumps all the hint information.
962 std::string emitRemark() const {
963 VectorizationReport R;
964 if (Force.Value == LoopVectorizeHints::FK_Disabled)
965 R << "vectorization is explicitly disabled";
967 R << "use -Rpass-analysis=loop-vectorize for more info";
968 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
970 if (Width.Value != 0)
971 R << ", Vector Width=" << Width.Value;
972 if (Interleave.Value != 0)
973 R << ", Interleave Count=" << Interleave.Value;
981 unsigned getWidth() const { return Width.Value; }
982 unsigned getInterleave() const { return Interleave.Value; }
983 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
984 const char *vectorizeAnalysisPassName() const {
985 // If hints are provided that don't disable vectorization use the
986 // AlwaysPrint pass name to force the frontend to print the diagnostic.
989 if (getForce() == LoopVectorizeHints::FK_Disabled)
991 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
993 return DiagnosticInfo::AlwaysPrint;
996 bool allowReordering() const {
997 // When enabling loop hints are provided we allow the vectorizer to change
998 // the order of operations that is given by the scalar loop. This is not
999 // enabled by default because can be unsafe or inefficient. For example,
1000 // reordering floating-point operations will change the way round-off
1001 // error accumulates in the loop.
1002 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1006 /// Find hints specified in the loop metadata and update local values.
1007 void getHintsFromMetadata() {
1008 MDNode *LoopID = TheLoop->getLoopID();
1012 // First operand should refer to the loop id itself.
1013 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1014 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1016 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1017 const MDString *S = nullptr;
1018 SmallVector<Metadata *, 4> Args;
1020 // The expected hint is either a MDString or a MDNode with the first
1021 // operand a MDString.
1022 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1023 if (!MD || MD->getNumOperands() == 0)
1025 S = dyn_cast<MDString>(MD->getOperand(0));
1026 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1027 Args.push_back(MD->getOperand(i));
1029 S = dyn_cast<MDString>(LoopID->getOperand(i));
1030 assert(Args.size() == 0 && "too many arguments for MDString");
1036 // Check if the hint starts with the loop metadata prefix.
1037 StringRef Name = S->getString();
1038 if (Args.size() == 1)
1039 setHint(Name, Args[0]);
1043 /// Checks string hint with one operand and set value if valid.
1044 void setHint(StringRef Name, Metadata *Arg) {
1045 if (!Name.startswith(Prefix()))
1047 Name = Name.substr(Prefix().size(), StringRef::npos);
1049 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1051 unsigned Val = C->getZExtValue();
1053 Hint *Hints[] = {&Width, &Interleave, &Force};
1054 for (auto H : Hints) {
1055 if (Name == H->Name) {
1056 if (H->validate(Val))
1059 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1065 /// Create a new hint from name / value pair.
1066 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1067 LLVMContext &Context = TheLoop->getHeader()->getContext();
1068 Metadata *MDs[] = {MDString::get(Context, Name),
1069 ConstantAsMetadata::get(
1070 ConstantInt::get(Type::getInt32Ty(Context), V))};
1071 return MDNode::get(Context, MDs);
1074 /// Matches metadata with hint name.
1075 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1076 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1080 for (auto H : HintTypes)
1081 if (Name->getString().endswith(H.Name))
1086 /// Sets current hints into loop metadata, keeping other values intact.
1087 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1088 if (HintTypes.size() == 0)
1091 // Reserve the first element to LoopID (see below).
1092 SmallVector<Metadata *, 4> MDs(1);
1093 // If the loop already has metadata, then ignore the existing operands.
1094 MDNode *LoopID = TheLoop->getLoopID();
1096 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1097 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1098 // If node in update list, ignore old value.
1099 if (!matchesHintMetadataName(Node, HintTypes))
1100 MDs.push_back(Node);
1104 // Now, add the missing hints.
1105 for (auto H : HintTypes)
1106 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1108 // Replace current metadata node with new one.
1109 LLVMContext &Context = TheLoop->getHeader()->getContext();
1110 MDNode *NewLoopID = MDNode::get(Context, MDs);
1111 // Set operand 0 to refer to the loop id itself.
1112 NewLoopID->replaceOperandWith(0, NewLoopID);
1114 TheLoop->setLoopID(NewLoopID);
1117 /// The loop these hints belong to.
1118 const Loop *TheLoop;
1121 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1122 const LoopVectorizeHints &Hints,
1123 const LoopAccessReport &Message) {
1124 const char *Name = Hints.vectorizeAnalysisPassName();
1125 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1128 static void emitMissedWarning(Function *F, Loop *L,
1129 const LoopVectorizeHints &LH) {
1130 emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1133 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1134 if (LH.getWidth() != 1)
1135 emitLoopVectorizeWarning(
1136 F->getContext(), *F, L->getStartLoc(),
1137 "failed explicitly specified loop vectorization");
1138 else if (LH.getInterleave() != 1)
1139 emitLoopInterleaveWarning(
1140 F->getContext(), *F, L->getStartLoc(),
1141 "failed explicitly specified loop interleaving");
1145 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1146 /// to what vectorization factor.
1147 /// This class does not look at the profitability of vectorization, only the
1148 /// legality. This class has two main kinds of checks:
1149 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1150 /// will change the order of memory accesses in a way that will change the
1151 /// correctness of the program.
1152 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1153 /// checks for a number of different conditions, such as the availability of a
1154 /// single induction variable, that all types are supported and vectorize-able,
1155 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1156 /// This class is also used by InnerLoopVectorizer for identifying
1157 /// induction variable and the different reduction variables.
1158 class LoopVectorizationLegality {
1160 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1161 TargetLibraryInfo *TLI, AliasAnalysis *AA,
1162 Function *F, const TargetTransformInfo *TTI,
1163 LoopAccessAnalysis *LAA,
1164 LoopVectorizationRequirements *R,
1165 const LoopVectorizeHints *H,
1166 SCEVUnionPredicate &Preds)
1167 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
1168 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr),
1169 InterleaveInfo(SE, L, DT, Preds), Induction(nullptr),
1170 WidestIndTy(nullptr), HasFunNoNaNAttr(false), Requirements(R), Hints(H),
1173 /// ReductionList contains the reduction descriptors for all
1174 /// of the reductions that were found in the loop.
1175 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1177 /// InductionList saves induction variables and maps them to the
1178 /// induction descriptor.
1179 typedef MapVector<PHINode*, InductionDescriptor> InductionList;
1181 /// Returns true if it is legal to vectorize this loop.
1182 /// This does not mean that it is profitable to vectorize this
1183 /// loop, only that it is legal to do so.
1184 bool canVectorize();
1186 /// Returns the Induction variable.
1187 PHINode *getInduction() { return Induction; }
1189 /// Returns the reduction variables found in the loop.
1190 ReductionList *getReductionVars() { return &Reductions; }
1192 /// Returns the induction variables found in the loop.
1193 InductionList *getInductionVars() { return &Inductions; }
1195 /// Returns the widest induction type.
1196 Type *getWidestInductionType() { return WidestIndTy; }
1198 /// Returns True if V is an induction variable in this loop.
1199 bool isInductionVariable(const Value *V);
1201 /// Return true if the block BB needs to be predicated in order for the loop
1202 /// to be vectorized.
1203 bool blockNeedsPredication(BasicBlock *BB);
1205 /// Check if this pointer is consecutive when vectorizing. This happens
1206 /// when the last index of the GEP is the induction variable, or that the
1207 /// pointer itself is an induction variable.
1208 /// This check allows us to vectorize A[idx] into a wide load/store.
1210 /// 0 - Stride is unknown or non-consecutive.
1211 /// 1 - Address is consecutive.
1212 /// -1 - Address is consecutive, and decreasing.
1213 int isConsecutivePtr(Value *Ptr);
1215 /// Returns true if the value V is uniform within the loop.
1216 bool isUniform(Value *V);
1218 /// Returns true if this instruction will remain scalar after vectorization.
1219 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
1221 /// Returns the information that we collected about runtime memory check.
1222 const RuntimePointerChecking *getRuntimePointerChecking() const {
1223 return LAI->getRuntimePointerChecking();
1226 const LoopAccessInfo *getLAI() const {
1230 /// \brief Check if \p Instr belongs to any interleaved access group.
1231 bool isAccessInterleaved(Instruction *Instr) {
1232 return InterleaveInfo.isInterleaved(Instr);
1235 /// \brief Get the interleaved access group that \p Instr belongs to.
1236 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1237 return InterleaveInfo.getInterleaveGroup(Instr);
1240 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1242 bool hasStride(Value *V) { return StrideSet.count(V); }
1243 bool mustCheckStrides() { return !StrideSet.empty(); }
1244 SmallPtrSet<Value *, 8>::iterator strides_begin() {
1245 return StrideSet.begin();
1247 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
1249 /// Returns true if the target machine supports masked store operation
1250 /// for the given \p DataType and kind of access to \p Ptr.
1251 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1252 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1254 /// Returns true if the target machine supports masked load operation
1255 /// for the given \p DataType and kind of access to \p Ptr.
1256 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1257 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1259 /// Returns true if vector representation of the instruction \p I
1261 bool isMaskRequired(const Instruction* I) {
1262 return (MaskedOp.count(I) != 0);
1264 unsigned getNumStores() const {
1265 return LAI->getNumStores();
1267 unsigned getNumLoads() const {
1268 return LAI->getNumLoads();
1270 unsigned getNumPredStores() const {
1271 return NumPredStores;
1274 /// Check if a single basic block loop is vectorizable.
1275 /// At this point we know that this is a loop with a constant trip count
1276 /// and we only need to check individual instructions.
1277 bool canVectorizeInstrs();
1279 /// When we vectorize loops we may change the order in which
1280 /// we read and write from memory. This method checks if it is
1281 /// legal to vectorize the code, considering only memory constrains.
1282 /// Returns true if the loop is vectorizable
1283 bool canVectorizeMemory();
1285 /// Return true if we can vectorize this loop using the IF-conversion
1287 bool canVectorizeWithIfConvert();
1289 /// Collect the variables that need to stay uniform after vectorization.
1290 void collectLoopUniforms();
1292 /// Return true if all of the instructions in the block can be speculatively
1293 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1294 /// and we know that we can read from them without segfault.
1295 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1297 /// \brief Collect memory access with loop invariant strides.
1299 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1301 void collectStridedAccess(Value *LoadOrStoreInst);
1303 /// Report an analysis message to assist the user in diagnosing loops that are
1304 /// not vectorized. These are handled as LoopAccessReport rather than
1305 /// VectorizationReport because the << operator of VectorizationReport returns
1306 /// LoopAccessReport.
1307 void emitAnalysis(const LoopAccessReport &Message) const {
1308 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1311 unsigned NumPredStores;
1313 /// The loop that we evaluate.
1316 ScalarEvolution *SE;
1317 /// Target Library Info.
1318 TargetLibraryInfo *TLI;
1320 Function *TheFunction;
1321 /// Target Transform Info
1322 const TargetTransformInfo *TTI;
1325 // LoopAccess analysis.
1326 LoopAccessAnalysis *LAA;
1327 // And the loop-accesses info corresponding to this loop. This pointer is
1328 // null until canVectorizeMemory sets it up.
1329 const LoopAccessInfo *LAI;
1331 /// The interleave access information contains groups of interleaved accesses
1332 /// with the same stride and close to each other.
1333 InterleavedAccessInfo InterleaveInfo;
1335 // --- vectorization state --- //
1337 /// Holds the integer induction variable. This is the counter of the
1340 /// Holds the reduction variables.
1341 ReductionList Reductions;
1342 /// Holds all of the induction variables that we found in the loop.
1343 /// Notice that inductions don't need to start at zero and that induction
1344 /// variables can be pointers.
1345 InductionList Inductions;
1346 /// Holds the widest induction type encountered.
1349 /// Allowed outside users. This holds the reduction
1350 /// vars which can be accessed from outside the loop.
1351 SmallPtrSet<Value*, 4> AllowedExit;
1352 /// This set holds the variables which are known to be uniform after
1354 SmallPtrSet<Instruction*, 4> Uniforms;
1356 /// Can we assume the absence of NaNs.
1357 bool HasFunNoNaNAttr;
1359 /// Vectorization requirements that will go through late-evaluation.
1360 LoopVectorizationRequirements *Requirements;
1362 /// Used to emit an analysis of any legality issues.
1363 const LoopVectorizeHints *Hints;
1365 ValueToValueMap Strides;
1366 SmallPtrSet<Value *, 8> StrideSet;
1368 /// While vectorizing these instructions we have to generate a
1369 /// call to the appropriate masked intrinsic
1370 SmallPtrSet<const Instruction *, 8> MaskedOp;
1372 /// The SCEV predicate containing all the SCEV-related assumptions.
1373 /// The predicate is used to simplify SCEV expressions in the
1374 /// context of existing SCEV assumptions. The analysis will also
1375 /// add a minimal set of new predicates if this is required to
1376 /// enable vectorization/unrolling.
1377 SCEVUnionPredicate &Preds;
1380 /// LoopVectorizationCostModel - estimates the expected speedups due to
1382 /// In many cases vectorization is not profitable. This can happen because of
1383 /// a number of reasons. In this class we mainly attempt to predict the
1384 /// expected speedup/slowdowns due to the supported instruction set. We use the
1385 /// TargetTransformInfo to query the different backends for the cost of
1386 /// different operations.
1387 class LoopVectorizationCostModel {
1389 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1390 LoopVectorizationLegality *Legal,
1391 const TargetTransformInfo &TTI,
1392 const TargetLibraryInfo *TLI, DemandedBits *DB,
1393 AssumptionCache *AC, const Function *F,
1394 const LoopVectorizeHints *Hints,
1395 SmallPtrSetImpl<const Value *> &ValuesToIgnore,
1396 SCEVUnionPredicate &Preds)
1397 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1398 TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
1400 /// Information about vectorization costs
1401 struct VectorizationFactor {
1402 unsigned Width; // Vector width with best cost
1403 unsigned Cost; // Cost of the loop with that width
1405 /// \return The most profitable vectorization factor and the cost of that VF.
1406 /// This method checks every power of two up to VF. If UserVF is not ZERO
1407 /// then this vectorization factor will be selected if vectorization is
1409 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1411 /// \return The size (in bits) of the widest type in the code that
1412 /// needs to be vectorized. We ignore values that remain scalar such as
1413 /// 64 bit loop indices.
1414 unsigned getWidestType();
1416 /// \return The desired interleave count.
1417 /// If interleave count has been specified by metadata it will be returned.
1418 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1419 /// are the selected vectorization factor and the cost of the selected VF.
1420 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1423 /// \return The most profitable unroll factor.
1424 /// This method finds the best unroll-factor based on register pressure and
1425 /// other parameters. VF and LoopCost are the selected vectorization factor
1426 /// and the cost of the selected VF.
1427 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1430 /// \brief A struct that represents some properties of the register usage
1432 struct RegisterUsage {
1433 /// Holds the number of loop invariant values that are used in the loop.
1434 unsigned LoopInvariantRegs;
1435 /// Holds the maximum number of concurrent live intervals in the loop.
1436 unsigned MaxLocalUsers;
1437 /// Holds the number of instructions in the loop.
1438 unsigned NumInstructions;
1441 /// \return information about the register usage of the loop.
1442 RegisterUsage calculateRegisterUsage();
1445 /// Returns the expected execution cost. The unit of the cost does
1446 /// not matter because we use the 'cost' units to compare different
1447 /// vector widths. The cost that is returned is *not* normalized by
1448 /// the factor width.
1449 unsigned expectedCost(unsigned VF);
1451 /// Returns the execution time cost of an instruction for a given vector
1452 /// width. Vector width of one means scalar.
1453 unsigned getInstructionCost(Instruction *I, unsigned VF);
1455 /// Returns whether the instruction is a load or store and will be a emitted
1456 /// as a vector operation.
1457 bool isConsecutiveLoadOrStore(Instruction *I);
1459 /// Report an analysis message to assist the user in diagnosing loops that are
1460 /// not vectorized. These are handled as LoopAccessReport rather than
1461 /// VectorizationReport because the << operator of VectorizationReport returns
1462 /// LoopAccessReport.
1463 void emitAnalysis(const LoopAccessReport &Message) const {
1464 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1468 /// Map of scalar integer values to the smallest bitwidth they can be legally
1469 /// represented as. The vector equivalents of these values should be truncated
1471 DenseMap<Instruction*,uint64_t> MinBWs;
1473 /// The loop that we evaluate.
1476 ScalarEvolution *SE;
1477 /// Loop Info analysis.
1479 /// Vectorization legality.
1480 LoopVectorizationLegality *Legal;
1481 /// Vector target information.
1482 const TargetTransformInfo &TTI;
1483 /// Target Library Info.
1484 const TargetLibraryInfo *TLI;
1485 /// Demanded bits analysis
1487 const Function *TheFunction;
1488 // Loop Vectorize Hint.
1489 const LoopVectorizeHints *Hints;
1490 // Values to ignore in the cost model.
1491 const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
1494 /// \brief This holds vectorization requirements that must be verified late in
1495 /// the process. The requirements are set by legalize and costmodel. Once
1496 /// vectorization has been determined to be possible and profitable the
1497 /// requirements can be verified by looking for metadata or compiler options.
1498 /// For example, some loops require FP commutativity which is only allowed if
1499 /// vectorization is explicitly specified or if the fast-math compiler option
1500 /// has been provided.
1501 /// Late evaluation of these requirements allows helpful diagnostics to be
1502 /// composed that tells the user what need to be done to vectorize the loop. For
1503 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1504 /// evaluation should be used only when diagnostics can generated that can be
1505 /// followed by a non-expert user.
1506 class LoopVectorizationRequirements {
1508 LoopVectorizationRequirements()
1509 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1511 void addUnsafeAlgebraInst(Instruction *I) {
1512 // First unsafe algebra instruction.
1513 if (!UnsafeAlgebraInst)
1514 UnsafeAlgebraInst = I;
1517 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1519 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1520 const char *Name = Hints.vectorizeAnalysisPassName();
1521 bool Failed = false;
1522 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1523 emitOptimizationRemarkAnalysisFPCommute(
1524 F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1525 VectorizationReport() << "cannot prove it is safe to reorder "
1526 "floating-point operations");
1530 // Test if runtime memcheck thresholds are exceeded.
1531 bool PragmaThresholdReached =
1532 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1533 bool ThresholdReached =
1534 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1535 if ((ThresholdReached && !Hints.allowReordering()) ||
1536 PragmaThresholdReached) {
1537 emitOptimizationRemarkAnalysisAliasing(
1538 F->getContext(), Name, *F, L->getStartLoc(),
1539 VectorizationReport()
1540 << "cannot prove it is safe to reorder memory operations");
1541 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1549 unsigned NumRuntimePointerChecks;
1550 Instruction *UnsafeAlgebraInst;
1553 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1555 return V.push_back(&L);
1557 for (Loop *InnerL : L)
1558 addInnerLoop(*InnerL, V);
1561 /// The LoopVectorize Pass.
1562 struct LoopVectorize : public FunctionPass {
1563 /// Pass identification, replacement for typeid
1566 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1568 DisableUnrolling(NoUnrolling),
1569 AlwaysVectorize(AlwaysVectorize) {
1570 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1573 ScalarEvolution *SE;
1575 TargetTransformInfo *TTI;
1577 BlockFrequencyInfo *BFI;
1578 TargetLibraryInfo *TLI;
1581 AssumptionCache *AC;
1582 LoopAccessAnalysis *LAA;
1583 bool DisableUnrolling;
1584 bool AlwaysVectorize;
1586 BlockFrequency ColdEntryFreq;
1588 bool runOnFunction(Function &F) override {
1589 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1590 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1591 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1592 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1593 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1594 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1595 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1596 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1597 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1598 LAA = &getAnalysis<LoopAccessAnalysis>();
1599 DB = &getAnalysis<DemandedBits>();
1601 // Compute some weights outside of the loop over the loops. Compute this
1602 // using a BranchProbability to re-use its scaling math.
1603 const BranchProbability ColdProb(1, 5); // 20%
1604 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1607 // 1. the target claims to have no vector registers, and
1608 // 2. interleaving won't help ILP.
1610 // The second condition is necessary because, even if the target has no
1611 // vector registers, loop vectorization may still enable scalar
1613 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1616 // Build up a worklist of inner-loops to vectorize. This is necessary as
1617 // the act of vectorizing or partially unrolling a loop creates new loops
1618 // and can invalidate iterators across the loops.
1619 SmallVector<Loop *, 8> Worklist;
1622 addInnerLoop(*L, Worklist);
1624 LoopsAnalyzed += Worklist.size();
1626 // Now walk the identified inner loops.
1627 bool Changed = false;
1628 while (!Worklist.empty())
1629 Changed |= processLoop(Worklist.pop_back_val());
1631 // Process each loop nest in the function.
1635 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1636 SmallVector<Metadata *, 4> MDs;
1637 // Reserve first location for self reference to the LoopID metadata node.
1638 MDs.push_back(nullptr);
1639 bool IsUnrollMetadata = false;
1640 MDNode *LoopID = L->getLoopID();
1642 // First find existing loop unrolling disable metadata.
1643 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1644 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1646 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1648 S && S->getString().startswith("llvm.loop.unroll.disable");
1650 MDs.push_back(LoopID->getOperand(i));
1654 if (!IsUnrollMetadata) {
1655 // Add runtime unroll disable metadata.
1656 LLVMContext &Context = L->getHeader()->getContext();
1657 SmallVector<Metadata *, 1> DisableOperands;
1658 DisableOperands.push_back(
1659 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1660 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1661 MDs.push_back(DisableNode);
1662 MDNode *NewLoopID = MDNode::get(Context, MDs);
1663 // Set operand 0 to refer to the loop id itself.
1664 NewLoopID->replaceOperandWith(0, NewLoopID);
1665 L->setLoopID(NewLoopID);
1669 bool processLoop(Loop *L) {
1670 assert(L->empty() && "Only process inner loops.");
1673 const std::string DebugLocStr = getDebugLocString(L);
1676 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1677 << L->getHeader()->getParent()->getName() << "\" from "
1678 << DebugLocStr << "\n");
1680 LoopVectorizeHints Hints(L, DisableUnrolling);
1682 DEBUG(dbgs() << "LV: Loop hints:"
1684 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1686 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1688 : "?")) << " width=" << Hints.getWidth()
1689 << " unroll=" << Hints.getInterleave() << "\n");
1691 // Function containing loop
1692 Function *F = L->getHeader()->getParent();
1694 // Looking at the diagnostic output is the only way to determine if a loop
1695 // was vectorized (other than looking at the IR or machine code), so it
1696 // is important to generate an optimization remark for each loop. Most of
1697 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1698 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1699 // less verbose reporting vectorized loops and unvectorized loops that may
1700 // benefit from vectorization, respectively.
1702 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1703 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1707 // Check the loop for a trip count threshold:
1708 // do not vectorize loops with a tiny trip count.
1709 const unsigned TC = SE->getSmallConstantTripCount(L);
1710 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1711 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1712 << "This loop is not worth vectorizing.");
1713 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1714 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1716 DEBUG(dbgs() << "\n");
1717 emitAnalysisDiag(F, L, Hints, VectorizationReport()
1718 << "vectorization is not beneficial "
1719 "and is not explicitly forced");
1724 SCEVUnionPredicate Preds;
1726 // Check if it is legal to vectorize the loop.
1727 LoopVectorizationRequirements Requirements;
1728 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1729 &Requirements, &Hints, Preds);
1730 if (!LVL.canVectorize()) {
1731 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1732 emitMissedWarning(F, L, Hints);
1736 // Collect values we want to ignore in the cost model. This includes
1737 // type-promoting instructions we identified during reduction detection.
1738 SmallPtrSet<const Value *, 32> ValuesToIgnore;
1739 CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
1740 for (auto &Reduction : *LVL.getReductionVars()) {
1741 RecurrenceDescriptor &RedDes = Reduction.second;
1742 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
1743 ValuesToIgnore.insert(Casts.begin(), Casts.end());
1746 // Use the cost model.
1747 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, DB, AC, F, &Hints,
1748 ValuesToIgnore, Preds);
1750 // Check the function attributes to find out if this function should be
1751 // optimized for size.
1752 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1755 // Compute the weighted frequency of this loop being executed and see if it
1756 // is less than 20% of the function entry baseline frequency. Note that we
1757 // always have a canonical loop here because we think we *can* vectorize.
1758 // FIXME: This is hidden behind a flag due to pervasive problems with
1759 // exactly what block frequency models.
1760 if (LoopVectorizeWithBlockFrequency) {
1761 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1762 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1763 LoopEntryFreq < ColdEntryFreq)
1767 // Check the function attributes to see if implicit floats are allowed.
1768 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1769 // an integer loop and the vector instructions selected are purely integer
1770 // vector instructions?
1771 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1772 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1773 "attribute is used.\n");
1776 VectorizationReport()
1777 << "loop not vectorized due to NoImplicitFloat attribute");
1778 emitMissedWarning(F, L, Hints);
1782 // Select the optimal vectorization factor.
1783 const LoopVectorizationCostModel::VectorizationFactor VF =
1784 CM.selectVectorizationFactor(OptForSize);
1786 // Select the interleave count.
1787 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1789 // Get user interleave count.
1790 unsigned UserIC = Hints.getInterleave();
1792 // Identify the diagnostic messages that should be produced.
1793 std::string VecDiagMsg, IntDiagMsg;
1794 bool VectorizeLoop = true, InterleaveLoop = true;
1796 if (Requirements.doesNotMeet(F, L, Hints)) {
1797 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1799 emitMissedWarning(F, L, Hints);
1803 if (VF.Width == 1) {
1804 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1806 "the cost-model indicates that vectorization is not beneficial";
1807 VectorizeLoop = false;
1810 if (IC == 1 && UserIC <= 1) {
1811 // Tell the user interleaving is not beneficial.
1812 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1814 "the cost-model indicates that interleaving is not beneficial";
1815 InterleaveLoop = false;
1818 " and is explicitly disabled or interleave count is set to 1";
1819 } else if (IC > 1 && UserIC == 1) {
1820 // Tell the user interleaving is beneficial, but it explicitly disabled.
1822 << "LV: Interleaving is beneficial but is explicitly disabled.");
1823 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1824 "but is explicitly disabled or interleave count is set to 1";
1825 InterleaveLoop = false;
1828 // Override IC if user provided an interleave count.
1829 IC = UserIC > 0 ? UserIC : IC;
1831 // Emit diagnostic messages, if any.
1832 const char *VAPassName = Hints.vectorizeAnalysisPassName();
1833 if (!VectorizeLoop && !InterleaveLoop) {
1834 // Do not vectorize or interleaving the loop.
1835 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1836 L->getStartLoc(), VecDiagMsg);
1837 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1838 L->getStartLoc(), IntDiagMsg);
1840 } else if (!VectorizeLoop && InterleaveLoop) {
1841 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1842 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1843 L->getStartLoc(), VecDiagMsg);
1844 } else if (VectorizeLoop && !InterleaveLoop) {
1845 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1846 << DebugLocStr << '\n');
1847 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1848 L->getStartLoc(), IntDiagMsg);
1849 } else if (VectorizeLoop && InterleaveLoop) {
1850 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1851 << DebugLocStr << '\n');
1852 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1855 if (!VectorizeLoop) {
1856 assert(IC > 1 && "interleave count should not be 1 or 0");
1857 // If we decided that it is not legal to vectorize the loop then
1859 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC, Preds);
1860 Unroller.vectorize(&LVL, CM.MinBWs);
1862 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1863 Twine("interleaved loop (interleaved count: ") +
1866 // If we decided that it is *legal* to vectorize the loop then do it.
1867 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC, Preds);
1868 LB.vectorize(&LVL, CM.MinBWs);
1871 // Add metadata to disable runtime unrolling scalar loop when there's no
1872 // runtime check about strides and memory. Because at this situation,
1873 // scalar loop is rarely used not worthy to be unrolled.
1874 if (!LB.IsSafetyChecksAdded())
1875 AddRuntimeUnrollDisableMetaData(L);
1877 // Report the vectorization decision.
1878 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1879 Twine("vectorized loop (vectorization width: ") +
1880 Twine(VF.Width) + ", interleaved count: " +
1884 // Mark the loop as already vectorized to avoid vectorizing again.
1885 Hints.setAlreadyVectorized();
1887 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1891 void getAnalysisUsage(AnalysisUsage &AU) const override {
1892 AU.addRequired<AssumptionCacheTracker>();
1893 AU.addRequiredID(LoopSimplifyID);
1894 AU.addRequiredID(LCSSAID);
1895 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1896 AU.addRequired<DominatorTreeWrapperPass>();
1897 AU.addRequired<LoopInfoWrapperPass>();
1898 AU.addRequired<ScalarEvolutionWrapperPass>();
1899 AU.addRequired<TargetTransformInfoWrapperPass>();
1900 AU.addRequired<AAResultsWrapperPass>();
1901 AU.addRequired<LoopAccessAnalysis>();
1902 AU.addRequired<DemandedBits>();
1903 AU.addPreserved<LoopInfoWrapperPass>();
1904 AU.addPreserved<DominatorTreeWrapperPass>();
1905 AU.addPreserved<BasicAAWrapperPass>();
1906 AU.addPreserved<AAResultsWrapperPass>();
1907 AU.addPreserved<GlobalsAAWrapperPass>();
1912 } // end anonymous namespace
1914 //===----------------------------------------------------------------------===//
1915 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1916 // LoopVectorizationCostModel.
1917 //===----------------------------------------------------------------------===//
1919 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1920 // We need to place the broadcast of invariant variables outside the loop.
1921 Instruction *Instr = dyn_cast<Instruction>(V);
1923 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1924 Instr->getParent()) != LoopVectorBody.end());
1925 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1927 // Place the code for broadcasting invariant variables in the new preheader.
1928 IRBuilder<>::InsertPointGuard Guard(Builder);
1930 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1932 // Broadcast the scalar into all locations in the vector.
1933 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1938 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1940 assert(Val->getType()->isVectorTy() && "Must be a vector");
1941 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1942 "Elem must be an integer");
1943 assert(Step->getType() == Val->getType()->getScalarType() &&
1944 "Step has wrong type");
1945 // Create the types.
1946 Type *ITy = Val->getType()->getScalarType();
1947 VectorType *Ty = cast<VectorType>(Val->getType());
1948 int VLen = Ty->getNumElements();
1949 SmallVector<Constant*, 8> Indices;
1951 // Create a vector of consecutive numbers from zero to VF.
1952 for (int i = 0; i < VLen; ++i)
1953 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1955 // Add the consecutive indices to the vector value.
1956 Constant *Cv = ConstantVector::get(Indices);
1957 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1958 Step = Builder.CreateVectorSplat(VLen, Step);
1959 assert(Step->getType() == Val->getType() && "Invalid step vec");
1960 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1961 // which can be found from the original scalar operations.
1962 Step = Builder.CreateMul(Cv, Step);
1963 return Builder.CreateAdd(Val, Step, "induction");
1966 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1967 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1968 // Make sure that the pointer does not point to structs.
1969 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1972 // If this value is a pointer induction variable we know it is consecutive.
1973 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1974 if (Phi && Inductions.count(Phi)) {
1975 InductionDescriptor II = Inductions[Phi];
1976 return II.getConsecutiveDirection();
1979 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1983 unsigned NumOperands = Gep->getNumOperands();
1984 Value *GpPtr = Gep->getPointerOperand();
1985 // If this GEP value is a consecutive pointer induction variable and all of
1986 // the indices are constant then we know it is consecutive. We can
1987 Phi = dyn_cast<PHINode>(GpPtr);
1988 if (Phi && Inductions.count(Phi)) {
1990 // Make sure that the pointer does not point to structs.
1991 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1992 if (GepPtrType->getElementType()->isAggregateType())
1995 // Make sure that all of the index operands are loop invariant.
1996 for (unsigned i = 1; i < NumOperands; ++i)
1997 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
2000 InductionDescriptor II = Inductions[Phi];
2001 return II.getConsecutiveDirection();
2004 unsigned InductionOperand = getGEPInductionOperand(Gep);
2006 // Check that all of the gep indices are uniform except for our induction
2008 for (unsigned i = 0; i != NumOperands; ++i)
2009 if (i != InductionOperand &&
2010 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
2013 // We can emit wide load/stores only if the last non-zero index is the
2014 // induction variable.
2015 const SCEV *Last = nullptr;
2016 if (!Strides.count(Gep))
2017 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
2019 // Because of the multiplication by a stride we can have a s/zext cast.
2020 // We are going to replace this stride by 1 so the cast is safe to ignore.
2022 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
2023 // %0 = trunc i64 %indvars.iv to i32
2024 // %mul = mul i32 %0, %Stride1
2025 // %idxprom = zext i32 %mul to i64 << Safe cast.
2026 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
2028 Last = replaceSymbolicStrideSCEV(SE, Strides, Preds,
2029 Gep->getOperand(InductionOperand), Gep);
2030 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
2032 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
2036 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
2037 const SCEV *Step = AR->getStepRecurrence(*SE);
2039 // The memory is consecutive because the last index is consecutive
2040 // and all other indices are loop invariant.
2043 if (Step->isAllOnesValue())
2050 bool LoopVectorizationLegality::isUniform(Value *V) {
2051 return LAI->isUniform(V);
2054 InnerLoopVectorizer::VectorParts&
2055 InnerLoopVectorizer::getVectorValue(Value *V) {
2056 assert(V != Induction && "The new induction variable should not be used.");
2057 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2059 // If we have a stride that is replaced by one, do it here.
2060 if (Legal->hasStride(V))
2061 V = ConstantInt::get(V->getType(), 1);
2063 // If we have this scalar in the map, return it.
2064 if (WidenMap.has(V))
2065 return WidenMap.get(V);
2067 // If this scalar is unknown, assume that it is a constant or that it is
2068 // loop invariant. Broadcast V and save the value for future uses.
2069 Value *B = getBroadcastInstrs(V);
2071 return WidenMap.splat(V, B);
2074 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2075 assert(Vec->getType()->isVectorTy() && "Invalid type");
2076 SmallVector<Constant*, 8> ShuffleMask;
2077 for (unsigned i = 0; i < VF; ++i)
2078 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2080 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2081 ConstantVector::get(ShuffleMask),
2085 // Get a mask to interleave \p NumVec vectors into a wide vector.
2086 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2087 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2088 // <0, 4, 1, 5, 2, 6, 3, 7>
2089 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2091 SmallVector<Constant *, 16> Mask;
2092 for (unsigned i = 0; i < VF; i++)
2093 for (unsigned j = 0; j < NumVec; j++)
2094 Mask.push_back(Builder.getInt32(j * VF + i));
2096 return ConstantVector::get(Mask);
2099 // Get the strided mask starting from index \p Start.
2100 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2101 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2102 unsigned Stride, unsigned VF) {
2103 SmallVector<Constant *, 16> Mask;
2104 for (unsigned i = 0; i < VF; i++)
2105 Mask.push_back(Builder.getInt32(Start + i * Stride));
2107 return ConstantVector::get(Mask);
2110 // Get a mask of two parts: The first part consists of sequential integers
2111 // starting from 0, The second part consists of UNDEFs.
2112 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2113 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2114 unsigned NumUndef) {
2115 SmallVector<Constant *, 16> Mask;
2116 for (unsigned i = 0; i < NumInt; i++)
2117 Mask.push_back(Builder.getInt32(i));
2119 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2120 for (unsigned i = 0; i < NumUndef; i++)
2121 Mask.push_back(Undef);
2123 return ConstantVector::get(Mask);
2126 // Concatenate two vectors with the same element type. The 2nd vector should
2127 // not have more elements than the 1st vector. If the 2nd vector has less
2128 // elements, extend it with UNDEFs.
2129 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2131 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2132 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2133 assert(VecTy1 && VecTy2 &&
2134 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2135 "Expect two vectors with the same element type");
2137 unsigned NumElts1 = VecTy1->getNumElements();
2138 unsigned NumElts2 = VecTy2->getNumElements();
2139 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2141 if (NumElts1 > NumElts2) {
2142 // Extend with UNDEFs.
2144 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2145 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2148 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2149 return Builder.CreateShuffleVector(V1, V2, Mask);
2152 // Concatenate vectors in the given list. All vectors have the same type.
2153 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2154 ArrayRef<Value *> InputList) {
2155 unsigned NumVec = InputList.size();
2156 assert(NumVec > 1 && "Should be at least two vectors");
2158 SmallVector<Value *, 8> ResList;
2159 ResList.append(InputList.begin(), InputList.end());
2161 SmallVector<Value *, 8> TmpList;
2162 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2163 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2164 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2165 "Only the last vector may have a different type");
2167 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2170 // Push the last vector if the total number of vectors is odd.
2171 if (NumVec % 2 != 0)
2172 TmpList.push_back(ResList[NumVec - 1]);
2175 NumVec = ResList.size();
2176 } while (NumVec > 1);
2181 // Try to vectorize the interleave group that \p Instr belongs to.
2183 // E.g. Translate following interleaved load group (factor = 3):
2184 // for (i = 0; i < N; i+=3) {
2185 // R = Pic[i]; // Member of index 0
2186 // G = Pic[i+1]; // Member of index 1
2187 // B = Pic[i+2]; // Member of index 2
2188 // ... // do something to R, G, B
2191 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2192 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2193 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2194 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2196 // Or translate following interleaved store group (factor = 3):
2197 // for (i = 0; i < N; i+=3) {
2198 // ... do something to R, G, B
2199 // Pic[i] = R; // Member of index 0
2200 // Pic[i+1] = G; // Member of index 1
2201 // Pic[i+2] = B; // Member of index 2
2204 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2205 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2206 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2207 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2208 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2209 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2210 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2211 assert(Group && "Fail to get an interleaved access group.");
2213 // Skip if current instruction is not the insert position.
2214 if (Instr != Group->getInsertPos())
2217 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2218 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2219 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2221 // Prepare for the vector type of the interleaved load/store.
2222 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2223 unsigned InterleaveFactor = Group->getFactor();
2224 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2225 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2227 // Prepare for the new pointers.
2228 setDebugLocFromInst(Builder, Ptr);
2229 VectorParts &PtrParts = getVectorValue(Ptr);
2230 SmallVector<Value *, 2> NewPtrs;
2231 unsigned Index = Group->getIndex(Instr);
2232 for (unsigned Part = 0; Part < UF; Part++) {
2233 // Extract the pointer for current instruction from the pointer vector. A
2234 // reverse access uses the pointer in the last lane.
2235 Value *NewPtr = Builder.CreateExtractElement(
2237 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2239 // Notice current instruction could be any index. Need to adjust the address
2240 // to the member of index 0.
2242 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2243 // b = A[i]; // Member of index 0
2244 // Current pointer is pointed to A[i+1], adjust it to A[i].
2246 // E.g. A[i+1] = a; // Member of index 1
2247 // A[i] = b; // Member of index 0
2248 // A[i+2] = c; // Member of index 2 (Current instruction)
2249 // Current pointer is pointed to A[i+2], adjust it to A[i].
2250 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2252 // Cast to the vector pointer type.
2253 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2256 setDebugLocFromInst(Builder, Instr);
2257 Value *UndefVec = UndefValue::get(VecTy);
2259 // Vectorize the interleaved load group.
2261 for (unsigned Part = 0; Part < UF; Part++) {
2262 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2263 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2265 for (unsigned i = 0; i < InterleaveFactor; i++) {
2266 Instruction *Member = Group->getMember(i);
2268 // Skip the gaps in the group.
2272 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2273 Value *StridedVec = Builder.CreateShuffleVector(
2274 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2276 // If this member has different type, cast the result type.
2277 if (Member->getType() != ScalarTy) {
2278 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2279 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2282 VectorParts &Entry = WidenMap.get(Member);
2284 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2287 propagateMetadata(NewLoadInstr, Instr);
2292 // The sub vector type for current instruction.
2293 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2295 // Vectorize the interleaved store group.
2296 for (unsigned Part = 0; Part < UF; Part++) {
2297 // Collect the stored vector from each member.
2298 SmallVector<Value *, 4> StoredVecs;
2299 for (unsigned i = 0; i < InterleaveFactor; i++) {
2300 // Interleaved store group doesn't allow a gap, so each index has a member
2301 Instruction *Member = Group->getMember(i);
2302 assert(Member && "Fail to get a member from an interleaved store group");
2305 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2306 if (Group->isReverse())
2307 StoredVec = reverseVector(StoredVec);
2309 // If this member has different type, cast it to an unified type.
2310 if (StoredVec->getType() != SubVT)
2311 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2313 StoredVecs.push_back(StoredVec);
2316 // Concatenate all vectors into a wide vector.
2317 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2319 // Interleave the elements in the wide vector.
2320 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2321 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2324 Instruction *NewStoreInstr =
2325 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2326 propagateMetadata(NewStoreInstr, Instr);
2330 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2331 // Attempt to issue a wide load.
2332 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2333 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2335 assert((LI || SI) && "Invalid Load/Store instruction");
2337 // Try to vectorize the interleave group if this access is interleaved.
2338 if (Legal->isAccessInterleaved(Instr))
2339 return vectorizeInterleaveGroup(Instr);
2341 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2342 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2343 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2344 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2345 // An alignment of 0 means target abi alignment. We need to use the scalar's
2346 // target abi alignment in such a case.
2347 const DataLayout &DL = Instr->getModule()->getDataLayout();
2349 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2350 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2351 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2352 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2354 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2355 !Legal->isMaskRequired(SI))
2356 return scalarizeInstruction(Instr, true);
2358 if (ScalarAllocatedSize != VectorElementSize)
2359 return scalarizeInstruction(Instr);
2361 // If the pointer is loop invariant or if it is non-consecutive,
2362 // scalarize the load.
2363 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2364 bool Reverse = ConsecutiveStride < 0;
2365 bool UniformLoad = LI && Legal->isUniform(Ptr);
2366 if (!ConsecutiveStride || UniformLoad)
2367 return scalarizeInstruction(Instr);
2369 Constant *Zero = Builder.getInt32(0);
2370 VectorParts &Entry = WidenMap.get(Instr);
2372 // Handle consecutive loads/stores.
2373 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2374 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2375 setDebugLocFromInst(Builder, Gep);
2376 Value *PtrOperand = Gep->getPointerOperand();
2377 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2378 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2380 // Create the new GEP with the new induction variable.
2381 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2382 Gep2->setOperand(0, FirstBasePtr);
2383 Gep2->setName("gep.indvar.base");
2384 Ptr = Builder.Insert(Gep2);
2386 setDebugLocFromInst(Builder, Gep);
2387 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2388 OrigLoop) && "Base ptr must be invariant");
2390 // The last index does not have to be the induction. It can be
2391 // consecutive and be a function of the index. For example A[I+1];
2392 unsigned NumOperands = Gep->getNumOperands();
2393 unsigned InductionOperand = getGEPInductionOperand(Gep);
2394 // Create the new GEP with the new induction variable.
2395 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2397 for (unsigned i = 0; i < NumOperands; ++i) {
2398 Value *GepOperand = Gep->getOperand(i);
2399 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2401 // Update last index or loop invariant instruction anchored in loop.
2402 if (i == InductionOperand ||
2403 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2404 assert((i == InductionOperand ||
2405 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2406 "Must be last index or loop invariant");
2408 VectorParts &GEPParts = getVectorValue(GepOperand);
2409 Value *Index = GEPParts[0];
2410 Index = Builder.CreateExtractElement(Index, Zero);
2411 Gep2->setOperand(i, Index);
2412 Gep2->setName("gep.indvar.idx");
2415 Ptr = Builder.Insert(Gep2);
2417 // Use the induction element ptr.
2418 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2419 setDebugLocFromInst(Builder, Ptr);
2420 VectorParts &PtrVal = getVectorValue(Ptr);
2421 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2424 VectorParts Mask = createBlockInMask(Instr->getParent());
2427 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2428 "We do not allow storing to uniform addresses");
2429 setDebugLocFromInst(Builder, SI);
2430 // We don't want to update the value in the map as it might be used in
2431 // another expression. So don't use a reference type for "StoredVal".
2432 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2434 for (unsigned Part = 0; Part < UF; ++Part) {
2435 // Calculate the pointer for the specific unroll-part.
2437 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2440 // If we store to reverse consecutive memory locations, then we need
2441 // to reverse the order of elements in the stored value.
2442 StoredVal[Part] = reverseVector(StoredVal[Part]);
2443 // If the address is consecutive but reversed, then the
2444 // wide store needs to start at the last vector element.
2445 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2446 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2447 Mask[Part] = reverseVector(Mask[Part]);
2450 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2451 DataTy->getPointerTo(AddressSpace));
2454 if (Legal->isMaskRequired(SI))
2455 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2458 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2459 propagateMetadata(NewSI, SI);
2465 assert(LI && "Must have a load instruction");
2466 setDebugLocFromInst(Builder, LI);
2467 for (unsigned Part = 0; Part < UF; ++Part) {
2468 // Calculate the pointer for the specific unroll-part.
2470 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2473 // If the address is consecutive but reversed, then the
2474 // wide load needs to start at the last vector element.
2475 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2476 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2477 Mask[Part] = reverseVector(Mask[Part]);
2481 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2482 DataTy->getPointerTo(AddressSpace));
2483 if (Legal->isMaskRequired(LI))
2484 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2485 UndefValue::get(DataTy),
2486 "wide.masked.load");
2488 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2489 propagateMetadata(NewLI, LI);
2490 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2494 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2495 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2496 // Holds vector parameters or scalars, in case of uniform vals.
2497 SmallVector<VectorParts, 4> Params;
2499 setDebugLocFromInst(Builder, Instr);
2501 // Find all of the vectorized parameters.
2502 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2503 Value *SrcOp = Instr->getOperand(op);
2505 // If we are accessing the old induction variable, use the new one.
2506 if (SrcOp == OldInduction) {
2507 Params.push_back(getVectorValue(SrcOp));
2511 // Try using previously calculated values.
2512 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2514 // If the src is an instruction that appeared earlier in the basic block,
2515 // then it should already be vectorized.
2516 if (SrcInst && OrigLoop->contains(SrcInst)) {
2517 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2518 // The parameter is a vector value from earlier.
2519 Params.push_back(WidenMap.get(SrcInst));
2521 // The parameter is a scalar from outside the loop. Maybe even a constant.
2522 VectorParts Scalars;
2523 Scalars.append(UF, SrcOp);
2524 Params.push_back(Scalars);
2528 assert(Params.size() == Instr->getNumOperands() &&
2529 "Invalid number of operands");
2531 // Does this instruction return a value ?
2532 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2534 Value *UndefVec = IsVoidRetTy ? nullptr :
2535 UndefValue::get(VectorType::get(Instr->getType(), VF));
2536 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2537 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2540 if (IfPredicateStore) {
2541 assert(Instr->getParent()->getSinglePredecessor() &&
2542 "Only support single predecessor blocks");
2543 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2544 Instr->getParent());
2547 // For each vector unroll 'part':
2548 for (unsigned Part = 0; Part < UF; ++Part) {
2549 // For each scalar that we create:
2550 for (unsigned Width = 0; Width < VF; ++Width) {
2553 Value *Cmp = nullptr;
2554 if (IfPredicateStore) {
2555 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2556 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2559 Instruction *Cloned = Instr->clone();
2561 Cloned->setName(Instr->getName() + ".cloned");
2562 // Replace the operands of the cloned instructions with extracted scalars.
2563 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2564 Value *Op = Params[op][Part];
2565 // Param is a vector. Need to extract the right lane.
2566 if (Op->getType()->isVectorTy())
2567 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2568 Cloned->setOperand(op, Op);
2571 // Place the cloned scalar in the new loop.
2572 Builder.Insert(Cloned);
2574 // If the original scalar returns a value we need to place it in a vector
2575 // so that future users will be able to use it.
2577 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2578 Builder.getInt32(Width));
2580 if (IfPredicateStore)
2581 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
2587 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2588 Value *End, Value *Step,
2590 BasicBlock *Header = L->getHeader();
2591 BasicBlock *Latch = L->getLoopLatch();
2592 // As we're just creating this loop, it's possible no latch exists
2593 // yet. If so, use the header as this will be a single block loop.
2597 IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2598 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2599 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2601 Builder.SetInsertPoint(Latch->getTerminator());
2603 // Create i+1 and fill the PHINode.
2604 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2605 Induction->addIncoming(Start, L->getLoopPreheader());
2606 Induction->addIncoming(Next, Latch);
2607 // Create the compare.
2608 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2609 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2611 // Now we have two terminators. Remove the old one from the block.
2612 Latch->getTerminator()->eraseFromParent();
2617 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2621 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2622 // Find the loop boundaries.
2623 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(OrigLoop);
2624 assert(BackedgeTakenCount != SE->getCouldNotCompute() && "Invalid loop count");
2626 Type *IdxTy = Legal->getWidestInductionType();
2628 // The exit count might have the type of i64 while the phi is i32. This can
2629 // happen if we have an induction variable that is sign extended before the
2630 // compare. The only way that we get a backedge taken count is that the
2631 // induction variable was signed and as such will not overflow. In such a case
2632 // truncation is legal.
2633 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2634 IdxTy->getPrimitiveSizeInBits())
2635 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2636 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2638 // Get the total trip count from the count by adding 1.
2639 const SCEV *ExitCount = SE->getAddExpr(
2640 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2642 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2644 // Expand the trip count and place the new instructions in the preheader.
2645 // Notice that the pre-header does not change, only the loop body.
2646 SCEVExpander Exp(*SE, DL, "induction");
2648 // Count holds the overall loop count (N).
2649 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2650 L->getLoopPreheader()->getTerminator());
2652 if (TripCount->getType()->isPointerTy())
2654 CastInst::CreatePointerCast(TripCount, IdxTy,
2655 "exitcount.ptrcnt.to.int",
2656 L->getLoopPreheader()->getTerminator());
2661 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2662 if (VectorTripCount)
2663 return VectorTripCount;
2665 Value *TC = getOrCreateTripCount(L);
2666 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2668 // Now we need to generate the expression for N - (N % VF), which is
2669 // the part that the vectorized body will execute.
2670 // The loop step is equal to the vectorization factor (num of SIMD elements)
2671 // times the unroll factor (num of SIMD instructions).
2672 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2673 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2674 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2676 return VectorTripCount;
2679 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2680 BasicBlock *Bypass) {
2681 Value *Count = getOrCreateTripCount(L);
2682 BasicBlock *BB = L->getLoopPreheader();
2683 IRBuilder<> Builder(BB->getTerminator());
2685 // Generate code to check that the loop's trip count that we computed by
2686 // adding one to the backedge-taken count will not overflow.
2687 Value *CheckMinIters =
2688 Builder.CreateICmpULT(Count,
2689 ConstantInt::get(Count->getType(), VF * UF),
2692 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2693 "min.iters.checked");
2694 if (L->getParentLoop())
2695 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2696 ReplaceInstWithInst(BB->getTerminator(),
2697 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2698 LoopBypassBlocks.push_back(BB);
2701 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2702 BasicBlock *Bypass) {
2703 Value *TC = getOrCreateVectorTripCount(L);
2704 BasicBlock *BB = L->getLoopPreheader();
2705 IRBuilder<> Builder(BB->getTerminator());
2707 // Now, compare the new count to zero. If it is zero skip the vector loop and
2708 // jump to the scalar loop.
2709 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2712 // Generate code to check that the loop's trip count that we computed by
2713 // adding one to the backedge-taken count will not overflow.
2714 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2716 if (L->getParentLoop())
2717 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2718 ReplaceInstWithInst(BB->getTerminator(),
2719 BranchInst::Create(Bypass, NewBB, Cmp));
2720 LoopBypassBlocks.push_back(BB);
2723 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
2724 BasicBlock *BB = L->getLoopPreheader();
2726 // Generate the code to check that the SCEV assumptions that we made.
2727 // We want the new basic block to start at the first instruction in a
2728 // sequence of instructions that form a check.
2729 SCEVExpander Exp(*SE, Bypass->getModule()->getDataLayout(), "scev.check");
2730 Value *SCEVCheck = Exp.expandCodeForPredicate(&Preds, BB->getTerminator());
2732 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2736 // Create a new block containing the stride check.
2737 BB->setName("vector.scevcheck");
2738 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2739 if (L->getParentLoop())
2740 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2741 ReplaceInstWithInst(BB->getTerminator(),
2742 BranchInst::Create(Bypass, NewBB, SCEVCheck));
2743 LoopBypassBlocks.push_back(BB);
2744 AddedSafetyChecks = true;
2747 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
2748 BasicBlock *Bypass) {
2749 BasicBlock *BB = L->getLoopPreheader();
2751 // Generate the code that checks in runtime if arrays overlap. We put the
2752 // checks into a separate block to make the more common case of few elements
2754 Instruction *FirstCheckInst;
2755 Instruction *MemRuntimeCheck;
2756 std::tie(FirstCheckInst, MemRuntimeCheck) =
2757 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2758 if (!MemRuntimeCheck)
2761 // Create a new block containing the memory check.
2762 BB->setName("vector.memcheck");
2763 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2764 if (L->getParentLoop())
2765 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2766 ReplaceInstWithInst(BB->getTerminator(),
2767 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2768 LoopBypassBlocks.push_back(BB);
2769 AddedSafetyChecks = true;
2773 void InnerLoopVectorizer::createEmptyLoop() {
2775 In this function we generate a new loop. The new loop will contain
2776 the vectorized instructions while the old loop will continue to run the
2779 [ ] <-- loop iteration number check.
2782 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2785 || [ ] <-- vector pre header.
2789 | [ ]_| <-- vector loop.
2792 | -[ ] <--- middle-block.
2795 -|- >[ ] <--- new preheader.
2799 | [ ]_| <-- old scalar loop to handle remainder.
2802 >[ ] <-- exit block.
2806 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2807 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2808 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2809 assert(VectorPH && "Invalid loop structure");
2810 assert(ExitBlock && "Must have an exit block");
2812 // Some loops have a single integer induction variable, while other loops
2813 // don't. One example is c++ iterators that often have multiple pointer
2814 // induction variables. In the code below we also support a case where we
2815 // don't have a single induction variable.
2817 // We try to obtain an induction variable from the original loop as hard
2818 // as possible. However if we don't find one that:
2820 // - counts from zero, stepping by one
2821 // - is the size of the widest induction variable type
2822 // then we create a new one.
2823 OldInduction = Legal->getInduction();
2824 Type *IdxTy = Legal->getWidestInductionType();
2826 // Split the single block loop into the two loop structure described above.
2827 BasicBlock *VecBody =
2828 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2829 BasicBlock *MiddleBlock =
2830 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2831 BasicBlock *ScalarPH =
2832 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2834 // Create and register the new vector loop.
2835 Loop* Lp = new Loop();
2836 Loop *ParentLoop = OrigLoop->getParentLoop();
2838 // Insert the new loop into the loop nest and register the new basic blocks
2839 // before calling any utilities such as SCEV that require valid LoopInfo.
2841 ParentLoop->addChildLoop(Lp);
2842 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2843 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2845 LI->addTopLevelLoop(Lp);
2847 Lp->addBasicBlockToLoop(VecBody, *LI);
2849 // Find the loop boundaries.
2850 Value *Count = getOrCreateTripCount(Lp);
2852 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2854 // We need to test whether the backedge-taken count is uint##_max. Adding one
2855 // to it will cause overflow and an incorrect loop trip count in the vector
2856 // body. In case of overflow we want to directly jump to the scalar remainder
2858 emitMinimumIterationCountCheck(Lp, ScalarPH);
2859 // Now, compare the new count to zero. If it is zero skip the vector loop and
2860 // jump to the scalar loop.
2861 emitVectorLoopEnteredCheck(Lp, ScalarPH);
2862 // Generate the code to check any assumptions that we've made for SCEV
2864 emitSCEVChecks(Lp, ScalarPH);
2866 // Generate the code that checks in runtime if arrays overlap. We put the
2867 // checks into a separate block to make the more common case of few elements
2869 emitMemRuntimeChecks(Lp, ScalarPH);
2871 // Generate the induction variable.
2872 // The loop step is equal to the vectorization factor (num of SIMD elements)
2873 // times the unroll factor (num of SIMD instructions).
2874 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2875 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2877 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2878 getDebugLocFromInstOrOperands(OldInduction));
2880 // We are going to resume the execution of the scalar loop.
2881 // Go over all of the induction variables that we found and fix the
2882 // PHIs that are left in the scalar version of the loop.
2883 // The starting values of PHI nodes depend on the counter of the last
2884 // iteration in the vectorized loop.
2885 // If we come from a bypass edge then we need to start from the original
2888 // This variable saves the new starting index for the scalar loop. It is used
2889 // to test if there are any tail iterations left once the vector loop has
2891 LoopVectorizationLegality::InductionList::iterator I, E;
2892 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2893 for (I = List->begin(), E = List->end(); I != E; ++I) {
2894 PHINode *OrigPhi = I->first;
2895 InductionDescriptor II = I->second;
2897 // Create phi nodes to merge from the backedge-taken check block.
2898 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
2900 ScalarPH->getTerminator());
2902 if (OrigPhi == OldInduction) {
2903 // We know what the end value is.
2904 EndValue = CountRoundDown;
2906 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
2907 Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
2908 II.getStepValue()->getType(),
2910 EndValue = II.transform(B, CRD);
2911 EndValue->setName("ind.end");
2914 // The new PHI merges the original incoming value, in case of a bypass,
2915 // or the value at the end of the vectorized loop.
2916 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2918 // Fix the scalar body counter (PHI node).
2919 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2921 // The old induction's phi node in the scalar body needs the truncated
2923 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2924 BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
2925 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2928 // Add a check in the middle block to see if we have completed
2929 // all of the iterations in the first vector loop.
2930 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2931 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2932 CountRoundDown, "cmp.n",
2933 MiddleBlock->getTerminator());
2934 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2935 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2937 // Get ready to start creating new instructions into the vectorized body.
2938 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
2941 LoopVectorPreHeader = Lp->getLoopPreheader();
2942 LoopScalarPreHeader = ScalarPH;
2943 LoopMiddleBlock = MiddleBlock;
2944 LoopExitBlock = ExitBlock;
2945 LoopVectorBody.push_back(VecBody);
2946 LoopScalarBody = OldBasicBlock;
2948 LoopVectorizeHints Hints(Lp, true);
2949 Hints.setAlreadyVectorized();
2953 struct CSEDenseMapInfo {
2954 static bool canHandle(Instruction *I) {
2955 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2956 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2958 static inline Instruction *getEmptyKey() {
2959 return DenseMapInfo<Instruction *>::getEmptyKey();
2961 static inline Instruction *getTombstoneKey() {
2962 return DenseMapInfo<Instruction *>::getTombstoneKey();
2964 static unsigned getHashValue(Instruction *I) {
2965 assert(canHandle(I) && "Unknown instruction!");
2966 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2967 I->value_op_end()));
2969 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2970 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2971 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2973 return LHS->isIdenticalTo(RHS);
2978 /// \brief Check whether this block is a predicated block.
2979 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2980 /// = ...; " blocks. We start with one vectorized basic block. For every
2981 /// conditional block we split this vectorized block. Therefore, every second
2982 /// block will be a predicated one.
2983 static bool isPredicatedBlock(unsigned BlockNum) {
2984 return BlockNum % 2;
2987 ///\brief Perform cse of induction variable instructions.
2988 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2989 // Perform simple cse.
2990 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2991 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2992 BasicBlock *BB = BBs[i];
2993 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2994 Instruction *In = &*I++;
2996 if (!CSEDenseMapInfo::canHandle(In))
2999 // Check if we can replace this instruction with any of the
3000 // visited instructions.
3001 if (Instruction *V = CSEMap.lookup(In)) {
3002 In->replaceAllUsesWith(V);
3003 In->eraseFromParent();
3006 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
3007 // ...;" blocks for predicated stores. Every second block is a predicated
3009 if (isPredicatedBlock(i))
3017 /// \brief Adds a 'fast' flag to floating point operations.
3018 static Value *addFastMathFlag(Value *V) {
3019 if (isa<FPMathOperator>(V)){
3020 FastMathFlags Flags;
3021 Flags.setUnsafeAlgebra();
3022 cast<Instruction>(V)->setFastMathFlags(Flags);
3027 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3028 /// the result needs to be inserted and/or extracted from vectors.
3029 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3030 const TargetTransformInfo &TTI) {
3034 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3037 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3039 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3041 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3047 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3048 // Return the cost of the instruction, including scalarization overhead if it's
3049 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3050 // i.e. either vector version isn't available, or is too expensive.
3051 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3052 const TargetTransformInfo &TTI,
3053 const TargetLibraryInfo *TLI,
3054 bool &NeedToScalarize) {
3055 Function *F = CI->getCalledFunction();
3056 StringRef FnName = CI->getCalledFunction()->getName();
3057 Type *ScalarRetTy = CI->getType();
3058 SmallVector<Type *, 4> Tys, ScalarTys;
3059 for (auto &ArgOp : CI->arg_operands())
3060 ScalarTys.push_back(ArgOp->getType());
3062 // Estimate cost of scalarized vector call. The source operands are assumed
3063 // to be vectors, so we need to extract individual elements from there,
3064 // execute VF scalar calls, and then gather the result into the vector return
3066 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3068 return ScalarCallCost;
3070 // Compute corresponding vector type for return value and arguments.
3071 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3072 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3073 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3075 // Compute costs of unpacking argument values for the scalar calls and
3076 // packing the return values to a vector.
3077 unsigned ScalarizationCost =
3078 getScalarizationOverhead(RetTy, true, false, TTI);
3079 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3080 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3082 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3084 // If we can't emit a vector call for this function, then the currently found
3085 // cost is the cost we need to return.
3086 NeedToScalarize = true;
3087 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3090 // If the corresponding vector cost is cheaper, return its cost.
3091 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3092 if (VectorCallCost < Cost) {
3093 NeedToScalarize = false;
3094 return VectorCallCost;
3099 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3100 // factor VF. Return the cost of the instruction, including scalarization
3101 // overhead if it's needed.
3102 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3103 const TargetTransformInfo &TTI,
3104 const TargetLibraryInfo *TLI) {
3105 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3106 assert(ID && "Expected intrinsic call!");
3108 Type *RetTy = ToVectorTy(CI->getType(), VF);
3109 SmallVector<Type *, 4> Tys;
3110 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3111 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3113 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3116 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3117 IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3118 IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3119 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3121 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3122 IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3123 IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3124 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3127 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3128 // For every instruction `I` in MinBWs, truncate the operands, create a
3129 // truncated version of `I` and reextend its result. InstCombine runs
3130 // later and will remove any ext/trunc pairs.
3132 for (auto &KV : MinBWs) {
3133 VectorParts &Parts = WidenMap.get(KV.first);
3134 for (Value *&I : Parts) {
3137 Type *OriginalTy = I->getType();
3138 Type *ScalarTruncatedTy = IntegerType::get(OriginalTy->getContext(),
3140 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3141 OriginalTy->getVectorNumElements());
3142 if (TruncatedTy == OriginalTy)
3145 IRBuilder<> B(cast<Instruction>(I));
3146 auto ShrinkOperand = [&](Value *V) -> Value* {
3147 if (auto *ZI = dyn_cast<ZExtInst>(V))
3148 if (ZI->getSrcTy() == TruncatedTy)
3149 return ZI->getOperand(0);
3150 return B.CreateZExtOrTrunc(V, TruncatedTy);
3153 // The actual instruction modification depends on the instruction type,
3155 Value *NewI = nullptr;
3156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
3157 NewI = B.CreateBinOp(BO->getOpcode(),
3158 ShrinkOperand(BO->getOperand(0)),
3159 ShrinkOperand(BO->getOperand(1)));
3160 cast<BinaryOperator>(NewI)->copyIRFlags(I);
3161 } else if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) {
3162 NewI = B.CreateICmp(CI->getPredicate(),
3163 ShrinkOperand(CI->getOperand(0)),
3164 ShrinkOperand(CI->getOperand(1)));
3165 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
3166 NewI = B.CreateSelect(SI->getCondition(),
3167 ShrinkOperand(SI->getTrueValue()),
3168 ShrinkOperand(SI->getFalseValue()));
3169 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3170 switch (CI->getOpcode()) {
3171 default: llvm_unreachable("Unhandled cast!");
3172 case Instruction::Trunc:
3173 NewI = ShrinkOperand(CI->getOperand(0));
3175 case Instruction::SExt:
3176 NewI = B.CreateSExtOrTrunc(CI->getOperand(0),
3177 smallestIntegerVectorType(OriginalTy,
3180 case Instruction::ZExt:
3181 NewI = B.CreateZExtOrTrunc(CI->getOperand(0),
3182 smallestIntegerVectorType(OriginalTy,
3186 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
3187 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3189 B.CreateZExtOrTrunc(SI->getOperand(0),
3190 VectorType::get(ScalarTruncatedTy, Elements0));
3191 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3193 B.CreateZExtOrTrunc(SI->getOperand(1),
3194 VectorType::get(ScalarTruncatedTy, Elements1));
3196 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3197 } else if (isa<LoadInst>(I)) {
3198 // Don't do anything with the operands, just extend the result.
3201 llvm_unreachable("Unhandled instruction type!");
3204 // Lastly, extend the result.
3205 NewI->takeName(cast<Instruction>(I));
3206 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3207 I->replaceAllUsesWith(Res);
3208 cast<Instruction>(I)->eraseFromParent();
3213 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3214 for (auto &KV : MinBWs) {
3215 VectorParts &Parts = WidenMap.get(KV.first);
3216 for (Value *&I : Parts) {
3217 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3218 if (Inst && Inst->use_empty()) {
3219 Value *NewI = Inst->getOperand(0);
3220 Inst->eraseFromParent();
3227 void InnerLoopVectorizer::vectorizeLoop() {
3228 //===------------------------------------------------===//
3230 // Notice: any optimization or new instruction that go
3231 // into the code below should be also be implemented in
3234 //===------------------------------------------------===//
3235 Constant *Zero = Builder.getInt32(0);
3237 // In order to support reduction variables we need to be able to vectorize
3238 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3239 // stages. First, we create a new vector PHI node with no incoming edges.
3240 // We use this value when we vectorize all of the instructions that use the
3241 // PHI. Next, after all of the instructions in the block are complete we
3242 // add the new incoming edges to the PHI. At this point all of the
3243 // instructions in the basic block are vectorized, so we can use them to
3244 // construct the PHI.
3245 PhiVector RdxPHIsToFix;
3247 // Scan the loop in a topological order to ensure that defs are vectorized
3249 LoopBlocksDFS DFS(OrigLoop);
3252 // Vectorize all of the blocks in the original loop.
3253 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3254 be = DFS.endRPO(); bb != be; ++bb)
3255 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3257 // Insert truncates and extends for any truncated instructions as hints to
3260 truncateToMinimalBitwidths();
3262 // At this point every instruction in the original loop is widened to
3263 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3264 // that we vectorized. The PHI nodes are currently empty because we did
3265 // not want to introduce cycles. Notice that the remaining PHI nodes
3266 // that we need to fix are reduction variables.
3268 // Create the 'reduced' values for each of the induction vars.
3269 // The reduced values are the vector values that we scalarize and combine
3270 // after the loop is finished.
3271 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3273 PHINode *RdxPhi = *it;
3274 assert(RdxPhi && "Unable to recover vectorized PHI");
3276 // Find the reduction variable descriptor.
3277 assert(Legal->getReductionVars()->count(RdxPhi) &&
3278 "Unable to find the reduction variable");
3279 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3281 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3282 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3283 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3284 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3285 RdxDesc.getMinMaxRecurrenceKind();
3286 setDebugLocFromInst(Builder, ReductionStartValue);
3288 // We need to generate a reduction vector from the incoming scalar.
3289 // To do so, we need to generate the 'identity' vector and override
3290 // one of the elements with the incoming scalar reduction. We need
3291 // to do it in the vector-loop preheader.
3292 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3294 // This is the vector-clone of the value that leaves the loop.
3295 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3296 Type *VecTy = VectorExit[0]->getType();
3298 // Find the reduction identity variable. Zero for addition, or, xor,
3299 // one for multiplication, -1 for And.
3302 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3303 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3304 // MinMax reduction have the start value as their identify.
3306 VectorStart = Identity = ReductionStartValue;
3308 VectorStart = Identity =
3309 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3312 // Handle other reduction kinds:
3313 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3314 RK, VecTy->getScalarType());
3317 // This vector is the Identity vector where the first element is the
3318 // incoming scalar reduction.
3319 VectorStart = ReductionStartValue;
3321 Identity = ConstantVector::getSplat(VF, Iden);
3323 // This vector is the Identity vector where the first element is the
3324 // incoming scalar reduction.
3326 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3330 // Fix the vector-loop phi.
3332 // Reductions do not have to start at zero. They can start with
3333 // any loop invariant values.
3334 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3335 BasicBlock *Latch = OrigLoop->getLoopLatch();
3336 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3337 VectorParts &Val = getVectorValue(LoopVal);
3338 for (unsigned part = 0; part < UF; ++part) {
3339 // Make sure to add the reduction stat value only to the
3340 // first unroll part.
3341 Value *StartVal = (part == 0) ? VectorStart : Identity;
3342 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3343 LoopVectorPreHeader);
3344 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3345 LoopVectorBody.back());
3348 // Before each round, move the insertion point right between
3349 // the PHIs and the values we are going to write.
3350 // This allows us to write both PHINodes and the extractelement
3352 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3354 VectorParts RdxParts = getVectorValue(LoopExitInst);
3355 setDebugLocFromInst(Builder, LoopExitInst);
3357 // If the vector reduction can be performed in a smaller type, we truncate
3358 // then extend the loop exit value to enable InstCombine to evaluate the
3359 // entire expression in the smaller type.
3360 if (VF > 1 && RdxPhi->getType() != RdxDesc.getRecurrenceType()) {
3361 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3362 Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
3363 for (unsigned part = 0; part < UF; ++part) {
3364 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3365 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3366 : Builder.CreateZExt(Trunc, VecTy);
3367 for (Value::user_iterator UI = RdxParts[part]->user_begin();
3368 UI != RdxParts[part]->user_end();)
3370 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3371 RdxParts[part] = Extnd;
3376 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3377 for (unsigned part = 0; part < UF; ++part)
3378 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3381 // Reduce all of the unrolled parts into a single vector.
3382 Value *ReducedPartRdx = RdxParts[0];
3383 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3384 setDebugLocFromInst(Builder, ReducedPartRdx);
3385 for (unsigned part = 1; part < UF; ++part) {
3386 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3387 // Floating point operations had to be 'fast' to enable the reduction.
3388 ReducedPartRdx = addFastMathFlag(
3389 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3390 ReducedPartRdx, "bin.rdx"));
3392 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3393 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3397 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3398 // and vector ops, reducing the set of values being computed by half each
3400 assert(isPowerOf2_32(VF) &&
3401 "Reduction emission only supported for pow2 vectors!");
3402 Value *TmpVec = ReducedPartRdx;
3403 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3404 for (unsigned i = VF; i != 1; i >>= 1) {
3405 // Move the upper half of the vector to the lower half.
3406 for (unsigned j = 0; j != i/2; ++j)
3407 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3409 // Fill the rest of the mask with undef.
3410 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3411 UndefValue::get(Builder.getInt32Ty()));
3414 Builder.CreateShuffleVector(TmpVec,
3415 UndefValue::get(TmpVec->getType()),
3416 ConstantVector::get(ShuffleMask),
3419 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3420 // Floating point operations had to be 'fast' to enable the reduction.
3421 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3422 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3424 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3428 // The result is in the first element of the vector.
3429 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3430 Builder.getInt32(0));
3432 // If the reduction can be performed in a smaller type, we need to extend
3433 // the reduction to the wider type before we branch to the original loop.
3434 if (RdxPhi->getType() != RdxDesc.getRecurrenceType())
3437 ? Builder.CreateSExt(ReducedPartRdx, RdxPhi->getType())
3438 : Builder.CreateZExt(ReducedPartRdx, RdxPhi->getType());
3441 // Create a phi node that merges control-flow from the backedge-taken check
3442 // block and the middle block.
3443 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3444 LoopScalarPreHeader->getTerminator());
3445 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3446 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3447 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3449 // Now, we need to fix the users of the reduction variable
3450 // inside and outside of the scalar remainder loop.
3451 // We know that the loop is in LCSSA form. We need to update the
3452 // PHI nodes in the exit blocks.
3453 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3454 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3455 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3456 if (!LCSSAPhi) break;
3458 // All PHINodes need to have a single entry edge, or two if
3459 // we already fixed them.
3460 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3462 // We found our reduction value exit-PHI. Update it with the
3463 // incoming bypass edge.
3464 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3465 // Add an edge coming from the bypass.
3466 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3469 }// end of the LCSSA phi scan.
3471 // Fix the scalar loop reduction variable with the incoming reduction sum
3472 // from the vector body and from the backedge value.
3473 int IncomingEdgeBlockIdx =
3474 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3475 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3476 // Pick the other block.
3477 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3478 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3479 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3480 }// end of for each redux variable.
3484 // Make sure DomTree is updated.
3487 // Predicate any stores.
3488 for (auto KV : PredicatedStores) {
3489 BasicBlock::iterator I(KV.first);
3490 auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI);
3491 auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
3492 /*BranchWeights=*/nullptr, DT);
3494 I->getParent()->setName("pred.store.if");
3495 BB->setName("pred.store.continue");
3497 DEBUG(DT->verifyDomTree());
3498 // Remove redundant induction instructions.
3499 cse(LoopVectorBody);
3502 void InnerLoopVectorizer::fixLCSSAPHIs() {
3503 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3504 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3505 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3506 if (!LCSSAPhi) break;
3507 if (LCSSAPhi->getNumIncomingValues() == 1)
3508 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3513 InnerLoopVectorizer::VectorParts
3514 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3515 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3518 // Look for cached value.
3519 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3520 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3521 if (ECEntryIt != MaskCache.end())
3522 return ECEntryIt->second;
3524 VectorParts SrcMask = createBlockInMask(Src);
3526 // The terminator has to be a branch inst!
3527 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3528 assert(BI && "Unexpected terminator found");
3530 if (BI->isConditional()) {
3531 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3533 if (BI->getSuccessor(0) != Dst)
3534 for (unsigned part = 0; part < UF; ++part)
3535 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3537 for (unsigned part = 0; part < UF; ++part)
3538 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3540 MaskCache[Edge] = EdgeMask;
3544 MaskCache[Edge] = SrcMask;
3548 InnerLoopVectorizer::VectorParts
3549 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3550 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3552 // Loop incoming mask is all-one.
3553 if (OrigLoop->getHeader() == BB) {
3554 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3555 return getVectorValue(C);
3558 // This is the block mask. We OR all incoming edges, and with zero.
3559 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3560 VectorParts BlockMask = getVectorValue(Zero);
3563 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3564 VectorParts EM = createEdgeMask(*it, BB);
3565 for (unsigned part = 0; part < UF; ++part)
3566 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3572 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3573 InnerLoopVectorizer::VectorParts &Entry,
3574 unsigned UF, unsigned VF, PhiVector *PV) {
3575 PHINode* P = cast<PHINode>(PN);
3576 // Handle reduction variables:
3577 if (Legal->getReductionVars()->count(P)) {
3578 for (unsigned part = 0; part < UF; ++part) {
3579 // This is phase one of vectorizing PHIs.
3580 Type *VecTy = (VF == 1) ? PN->getType() :
3581 VectorType::get(PN->getType(), VF);
3582 Entry[part] = PHINode::Create(
3583 VecTy, 2, "vec.phi", &*LoopVectorBody.back()->getFirstInsertionPt());
3589 setDebugLocFromInst(Builder, P);
3590 // Check for PHI nodes that are lowered to vector selects.
3591 if (P->getParent() != OrigLoop->getHeader()) {
3592 // We know that all PHIs in non-header blocks are converted into
3593 // selects, so we don't have to worry about the insertion order and we
3594 // can just use the builder.
3595 // At this point we generate the predication tree. There may be
3596 // duplications since this is a simple recursive scan, but future
3597 // optimizations will clean it up.
3599 unsigned NumIncoming = P->getNumIncomingValues();
3601 // Generate a sequence of selects of the form:
3602 // SELECT(Mask3, In3,
3603 // SELECT(Mask2, In2,
3605 for (unsigned In = 0; In < NumIncoming; In++) {
3606 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3608 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3610 for (unsigned part = 0; part < UF; ++part) {
3611 // We might have single edge PHIs (blocks) - use an identity
3612 // 'select' for the first PHI operand.
3614 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3617 // Select between the current value and the previous incoming edge
3618 // based on the incoming mask.
3619 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3620 Entry[part], "predphi");
3626 // This PHINode must be an induction variable.
3627 // Make sure that we know about it.
3628 assert(Legal->getInductionVars()->count(P) &&
3629 "Not an induction variable");
3631 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3633 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3634 // which can be found from the original scalar operations.
3635 switch (II.getKind()) {
3636 case InductionDescriptor::IK_NoInduction:
3637 llvm_unreachable("Unknown induction");
3638 case InductionDescriptor::IK_IntInduction: {
3639 assert(P->getType() == II.getStartValue()->getType() && "Types must match");
3640 // Handle other induction variables that are now based on the
3642 Value *V = Induction;
3643 if (P != OldInduction) {
3644 V = Builder.CreateSExtOrTrunc(Induction, P->getType());
3645 V = II.transform(Builder, V);
3646 V->setName("offset.idx");
3648 Value *Broadcasted = getBroadcastInstrs(V);
3649 // After broadcasting the induction variable we need to make the vector
3650 // consecutive by adding 0, 1, 2, etc.
3651 for (unsigned part = 0; part < UF; ++part)
3652 Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
3655 case InductionDescriptor::IK_PtrInduction:
3656 // Handle the pointer induction variable case.
3657 assert(P->getType()->isPointerTy() && "Unexpected type.");
3658 // This is the normalized GEP that starts counting at zero.
3659 Value *PtrInd = Induction;
3660 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
3661 // This is the vector of results. Notice that we don't generate
3662 // vector geps because scalar geps result in better code.
3663 for (unsigned part = 0; part < UF; ++part) {
3665 int EltIndex = part;
3666 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3667 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3668 Value *SclrGep = II.transform(Builder, GlobalIdx);
3669 SclrGep->setName("next.gep");
3670 Entry[part] = SclrGep;
3674 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3675 for (unsigned int i = 0; i < VF; ++i) {
3676 int EltIndex = i + part * VF;
3677 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3678 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3679 Value *SclrGep = II.transform(Builder, GlobalIdx);
3680 SclrGep->setName("next.gep");
3681 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3682 Builder.getInt32(i),
3685 Entry[part] = VecVal;
3691 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3692 // For each instruction in the old loop.
3693 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3694 VectorParts &Entry = WidenMap.get(&*it);
3696 switch (it->getOpcode()) {
3697 case Instruction::Br:
3698 // Nothing to do for PHIs and BR, since we already took care of the
3699 // loop control flow instructions.
3701 case Instruction::PHI: {
3702 // Vectorize PHINodes.
3703 widenPHIInstruction(&*it, Entry, UF, VF, PV);
3707 case Instruction::Add:
3708 case Instruction::FAdd:
3709 case Instruction::Sub:
3710 case Instruction::FSub:
3711 case Instruction::Mul:
3712 case Instruction::FMul:
3713 case Instruction::UDiv:
3714 case Instruction::SDiv:
3715 case Instruction::FDiv:
3716 case Instruction::URem:
3717 case Instruction::SRem:
3718 case Instruction::FRem:
3719 case Instruction::Shl:
3720 case Instruction::LShr:
3721 case Instruction::AShr:
3722 case Instruction::And:
3723 case Instruction::Or:
3724 case Instruction::Xor: {
3725 // Just widen binops.
3726 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3727 setDebugLocFromInst(Builder, BinOp);
3728 VectorParts &A = getVectorValue(it->getOperand(0));
3729 VectorParts &B = getVectorValue(it->getOperand(1));
3731 // Use this vector value for all users of the original instruction.
3732 for (unsigned Part = 0; Part < UF; ++Part) {
3733 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3735 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3736 VecOp->copyIRFlags(BinOp);
3741 propagateMetadata(Entry, &*it);
3744 case Instruction::Select: {
3746 // If the selector is loop invariant we can create a select
3747 // instruction with a scalar condition. Otherwise, use vector-select.
3748 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3750 setDebugLocFromInst(Builder, &*it);
3752 // The condition can be loop invariant but still defined inside the
3753 // loop. This means that we can't just use the original 'cond' value.
3754 // We have to take the 'vectorized' value and pick the first lane.
3755 // Instcombine will make this a no-op.
3756 VectorParts &Cond = getVectorValue(it->getOperand(0));
3757 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3758 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3760 Value *ScalarCond = (VF == 1) ? Cond[0] :
3761 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3763 for (unsigned Part = 0; Part < UF; ++Part) {
3764 Entry[Part] = Builder.CreateSelect(
3765 InvariantCond ? ScalarCond : Cond[Part],
3770 propagateMetadata(Entry, &*it);
3774 case Instruction::ICmp:
3775 case Instruction::FCmp: {
3776 // Widen compares. Generate vector compares.
3777 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3778 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3779 setDebugLocFromInst(Builder, &*it);
3780 VectorParts &A = getVectorValue(it->getOperand(0));
3781 VectorParts &B = getVectorValue(it->getOperand(1));
3782 for (unsigned Part = 0; Part < UF; ++Part) {
3785 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3786 cast<FCmpInst>(C)->copyFastMathFlags(&*it);
3788 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3793 propagateMetadata(Entry, &*it);
3797 case Instruction::Store:
3798 case Instruction::Load:
3799 vectorizeMemoryInstruction(&*it);
3801 case Instruction::ZExt:
3802 case Instruction::SExt:
3803 case Instruction::FPToUI:
3804 case Instruction::FPToSI:
3805 case Instruction::FPExt:
3806 case Instruction::PtrToInt:
3807 case Instruction::IntToPtr:
3808 case Instruction::SIToFP:
3809 case Instruction::UIToFP:
3810 case Instruction::Trunc:
3811 case Instruction::FPTrunc:
3812 case Instruction::BitCast: {
3813 CastInst *CI = dyn_cast<CastInst>(it);
3814 setDebugLocFromInst(Builder, &*it);
3815 /// Optimize the special case where the source is the induction
3816 /// variable. Notice that we can only optimize the 'trunc' case
3817 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3818 /// c. other casts depend on pointer size.
3819 if (CI->getOperand(0) == OldInduction &&
3820 it->getOpcode() == Instruction::Trunc) {
3821 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3823 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3824 InductionDescriptor II = Legal->getInductionVars()->lookup(OldInduction);
3826 ConstantInt::getSigned(CI->getType(), II.getStepValue()->getSExtValue());
3827 for (unsigned Part = 0; Part < UF; ++Part)
3828 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3829 propagateMetadata(Entry, &*it);
3832 /// Vectorize casts.
3833 Type *DestTy = (VF == 1) ? CI->getType() :
3834 VectorType::get(CI->getType(), VF);
3836 VectorParts &A = getVectorValue(it->getOperand(0));
3837 for (unsigned Part = 0; Part < UF; ++Part)
3838 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3839 propagateMetadata(Entry, &*it);
3843 case Instruction::Call: {
3844 // Ignore dbg intrinsics.
3845 if (isa<DbgInfoIntrinsic>(it))
3847 setDebugLocFromInst(Builder, &*it);
3849 Module *M = BB->getParent()->getParent();
3850 CallInst *CI = cast<CallInst>(it);
3852 StringRef FnName = CI->getCalledFunction()->getName();
3853 Function *F = CI->getCalledFunction();
3854 Type *RetTy = ToVectorTy(CI->getType(), VF);
3855 SmallVector<Type *, 4> Tys;
3856 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3857 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3859 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3861 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3862 ID == Intrinsic::lifetime_start)) {
3863 scalarizeInstruction(&*it);
3866 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3867 // version of the instruction.
3868 // Is it beneficial to perform intrinsic call compared to lib call?
3869 bool NeedToScalarize;
3870 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3871 bool UseVectorIntrinsic =
3872 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3873 if (!UseVectorIntrinsic && NeedToScalarize) {
3874 scalarizeInstruction(&*it);
3878 for (unsigned Part = 0; Part < UF; ++Part) {
3879 SmallVector<Value *, 4> Args;
3880 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3881 Value *Arg = CI->getArgOperand(i);
3882 // Some intrinsics have a scalar argument - don't replace it with a
3884 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3885 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3886 Arg = VectorArg[Part];
3888 Args.push_back(Arg);
3892 if (UseVectorIntrinsic) {
3893 // Use vector version of the intrinsic.
3894 Type *TysForDecl[] = {CI->getType()};
3896 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3897 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3899 // Use vector version of the library call.
3900 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3901 assert(!VFnName.empty() && "Vector function name is empty.");
3902 VectorF = M->getFunction(VFnName);
3904 // Generate a declaration
3905 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3907 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3908 VectorF->copyAttributesFrom(F);
3911 assert(VectorF && "Can't create vector function.");
3912 Entry[Part] = Builder.CreateCall(VectorF, Args);
3915 propagateMetadata(Entry, &*it);
3920 // All other instructions are unsupported. Scalarize them.
3921 scalarizeInstruction(&*it);
3924 }// end of for_each instr.
3927 void InnerLoopVectorizer::updateAnalysis() {
3928 // Forget the original basic block.
3929 SE->forgetLoop(OrigLoop);
3931 // Update the dominator tree information.
3932 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3933 "Entry does not dominate exit.");
3935 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3936 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3937 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3939 // We don't predicate stores by this point, so the vector body should be a
3941 assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
3942 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3944 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
3945 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3946 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3947 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3949 DEBUG(DT->verifyDomTree());
3952 /// \brief Check whether it is safe to if-convert this phi node.
3954 /// Phi nodes with constant expressions that can trap are not safe to if
3956 static bool canIfConvertPHINodes(BasicBlock *BB) {
3957 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3958 PHINode *Phi = dyn_cast<PHINode>(I);
3961 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3962 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3969 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3970 if (!EnableIfConversion) {
3971 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3975 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3977 // A list of pointers that we can safely read and write to.
3978 SmallPtrSet<Value *, 8> SafePointes;
3980 // Collect safe addresses.
3981 for (Loop::block_iterator BI = TheLoop->block_begin(),
3982 BE = TheLoop->block_end(); BI != BE; ++BI) {
3983 BasicBlock *BB = *BI;
3985 if (blockNeedsPredication(BB))
3988 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3989 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3990 SafePointes.insert(LI->getPointerOperand());
3991 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3992 SafePointes.insert(SI->getPointerOperand());
3996 // Collect the blocks that need predication.
3997 BasicBlock *Header = TheLoop->getHeader();
3998 for (Loop::block_iterator BI = TheLoop->block_begin(),
3999 BE = TheLoop->block_end(); BI != BE; ++BI) {
4000 BasicBlock *BB = *BI;
4002 // We don't support switch statements inside loops.
4003 if (!isa<BranchInst>(BB->getTerminator())) {
4004 emitAnalysis(VectorizationReport(BB->getTerminator())
4005 << "loop contains a switch statement");
4009 // We must be able to predicate all blocks that need to be predicated.
4010 if (blockNeedsPredication(BB)) {
4011 if (!blockCanBePredicated(BB, SafePointes)) {
4012 emitAnalysis(VectorizationReport(BB->getTerminator())
4013 << "control flow cannot be substituted for a select");
4016 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4017 emitAnalysis(VectorizationReport(BB->getTerminator())
4018 << "control flow cannot be substituted for a select");
4023 // We can if-convert this loop.
4027 bool LoopVectorizationLegality::canVectorize() {
4028 // We must have a loop in canonical form. Loops with indirectbr in them cannot
4029 // be canonicalized.
4030 if (!TheLoop->getLoopPreheader()) {
4032 VectorizationReport() <<
4033 "loop control flow is not understood by vectorizer");
4037 // We can only vectorize innermost loops.
4038 if (!TheLoop->empty()) {
4039 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
4043 // We must have a single backedge.
4044 if (TheLoop->getNumBackEdges() != 1) {
4046 VectorizationReport() <<
4047 "loop control flow is not understood by vectorizer");
4051 // We must have a single exiting block.
4052 if (!TheLoop->getExitingBlock()) {
4054 VectorizationReport() <<
4055 "loop control flow is not understood by vectorizer");
4059 // We only handle bottom-tested loops, i.e. loop in which the condition is
4060 // checked at the end of each iteration. With that we can assume that all
4061 // instructions in the loop are executed the same number of times.
4062 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4064 VectorizationReport() <<
4065 "loop control flow is not understood by vectorizer");
4069 // We need to have a loop header.
4070 DEBUG(dbgs() << "LV: Found a loop: " <<
4071 TheLoop->getHeader()->getName() << '\n');
4073 // Check if we can if-convert non-single-bb loops.
4074 unsigned NumBlocks = TheLoop->getNumBlocks();
4075 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4076 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
4080 // ScalarEvolution needs to be able to find the exit count.
4081 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
4082 if (ExitCount == SE->getCouldNotCompute()) {
4083 emitAnalysis(VectorizationReport() <<
4084 "could not determine number of loop iterations");
4085 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
4089 // Check if we can vectorize the instructions and CFG in this loop.
4090 if (!canVectorizeInstrs()) {
4091 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
4095 // Go over each instruction and look at memory deps.
4096 if (!canVectorizeMemory()) {
4097 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4101 // Collect all of the variables that remain uniform after vectorization.
4102 collectLoopUniforms();
4104 DEBUG(dbgs() << "LV: We can vectorize this loop"
4105 << (LAI->getRuntimePointerChecking()->Need
4106 ? " (with a runtime bound check)"
4110 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4112 // If an override option has been passed in for interleaved accesses, use it.
4113 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4114 UseInterleaved = EnableInterleavedMemAccesses;
4116 // Analyze interleaved memory accesses.
4118 InterleaveInfo.analyzeInterleaving(Strides);
4120 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4121 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4122 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4124 if (Preds.getComplexity() > SCEVThreshold) {
4125 emitAnalysis(VectorizationReport()
4126 << "Too many SCEV assumptions need to be made and checked "
4128 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
4132 // Okay! We can vectorize. At this point we don't have any other mem analysis
4133 // which may limit our maximum vectorization factor, so just return true with
4138 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4139 if (Ty->isPointerTy())
4140 return DL.getIntPtrType(Ty);
4142 // It is possible that char's or short's overflow when we ask for the loop's
4143 // trip count, work around this by changing the type size.
4144 if (Ty->getScalarSizeInBits() < 32)
4145 return Type::getInt32Ty(Ty->getContext());
4150 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4151 Ty0 = convertPointerToIntegerType(DL, Ty0);
4152 Ty1 = convertPointerToIntegerType(DL, Ty1);
4153 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4158 /// \brief Check that the instruction has outside loop users and is not an
4159 /// identified reduction variable.
4160 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4161 SmallPtrSetImpl<Value *> &Reductions) {
4162 // Reduction instructions are allowed to have exit users. All other
4163 // instructions must not have external users.
4164 if (!Reductions.count(Inst))
4165 //Check that all of the users of the loop are inside the BB.
4166 for (User *U : Inst->users()) {
4167 Instruction *UI = cast<Instruction>(U);
4168 // This user may be a reduction exit value.
4169 if (!TheLoop->contains(UI)) {
4170 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4177 bool LoopVectorizationLegality::canVectorizeInstrs() {
4178 BasicBlock *Header = TheLoop->getHeader();
4180 // Look for the attribute signaling the absence of NaNs.
4181 Function &F = *Header->getParent();
4182 const DataLayout &DL = F.getParent()->getDataLayout();
4183 if (F.hasFnAttribute("no-nans-fp-math"))
4185 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4187 // For each block in the loop.
4188 for (Loop::block_iterator bb = TheLoop->block_begin(),
4189 be = TheLoop->block_end(); bb != be; ++bb) {
4191 // Scan the instructions in the block and look for hazards.
4192 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4195 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4196 Type *PhiTy = Phi->getType();
4197 // Check that this PHI type is allowed.
4198 if (!PhiTy->isIntegerTy() &&
4199 !PhiTy->isFloatingPointTy() &&
4200 !PhiTy->isPointerTy()) {
4201 emitAnalysis(VectorizationReport(&*it)
4202 << "loop control flow is not understood by vectorizer");
4203 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4207 // If this PHINode is not in the header block, then we know that we
4208 // can convert it to select during if-conversion. No need to check if
4209 // the PHIs in this block are induction or reduction variables.
4210 if (*bb != Header) {
4211 // Check that this instruction has no outside users or is an
4212 // identified reduction value with an outside user.
4213 if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
4215 emitAnalysis(VectorizationReport(&*it) <<
4216 "value could not be identified as "
4217 "an induction or reduction variable");
4221 // We only allow if-converted PHIs with exactly two incoming values.
4222 if (Phi->getNumIncomingValues() != 2) {
4223 emitAnalysis(VectorizationReport(&*it)
4224 << "control flow not understood by vectorizer");
4225 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4229 InductionDescriptor ID;
4230 if (InductionDescriptor::isInductionPHI(Phi, SE, ID)) {
4231 Inductions[Phi] = ID;
4232 // Get the widest type.
4234 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4236 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4238 // Int inductions are special because we only allow one IV.
4239 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4240 ID.getStepValue()->isOne() &&
4241 isa<Constant>(ID.getStartValue()) &&
4242 cast<Constant>(ID.getStartValue())->isNullValue()) {
4243 // Use the phi node with the widest type as induction. Use the last
4244 // one if there are multiple (no good reason for doing this other
4245 // than it is expedient). We've checked that it begins at zero and
4246 // steps by one, so this is a canonical induction variable.
4247 if (!Induction || PhiTy == WidestIndTy)
4251 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4253 // Until we explicitly handle the case of an induction variable with
4254 // an outside loop user we have to give up vectorizing this loop.
4255 if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
4256 emitAnalysis(VectorizationReport(&*it) <<
4257 "use of induction value outside of the "
4258 "loop is not handled by vectorizer");
4265 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4267 if (Reductions[Phi].hasUnsafeAlgebra())
4268 Requirements->addUnsafeAlgebraInst(
4269 Reductions[Phi].getUnsafeAlgebraInst());
4270 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4274 emitAnalysis(VectorizationReport(&*it) <<
4275 "value that could not be identified as "
4276 "reduction is used outside the loop");
4277 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4279 }// end of PHI handling
4281 // We handle calls that:
4282 // * Are debug info intrinsics.
4283 // * Have a mapping to an IR intrinsic.
4284 // * Have a vector version available.
4285 CallInst *CI = dyn_cast<CallInst>(it);
4286 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4287 !(CI->getCalledFunction() && TLI &&
4288 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4289 emitAnalysis(VectorizationReport(&*it)
4290 << "call instruction cannot be vectorized");
4291 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4295 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4296 // second argument is the same (i.e. loop invariant)
4298 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4299 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4300 emitAnalysis(VectorizationReport(&*it)
4301 << "intrinsic instruction cannot be vectorized");
4302 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4307 // Check that the instruction return type is vectorizable.
4308 // Also, we can't vectorize extractelement instructions.
4309 if ((!VectorType::isValidElementType(it->getType()) &&
4310 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4311 emitAnalysis(VectorizationReport(&*it)
4312 << "instruction return type cannot be vectorized");
4313 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4317 // Check that the stored type is vectorizable.
4318 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4319 Type *T = ST->getValueOperand()->getType();
4320 if (!VectorType::isValidElementType(T)) {
4321 emitAnalysis(VectorizationReport(ST) <<
4322 "store instruction cannot be vectorized");
4325 if (EnableMemAccessVersioning)
4326 collectStridedAccess(ST);
4329 if (EnableMemAccessVersioning)
4330 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4331 collectStridedAccess(LI);
4333 // Reduction instructions are allowed to have exit users.
4334 // All other instructions must not have external users.
4335 if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
4336 emitAnalysis(VectorizationReport(&*it) <<
4337 "value cannot be used outside the loop");
4346 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4347 if (Inductions.empty()) {
4348 emitAnalysis(VectorizationReport()
4349 << "loop induction variable could not be identified");
4354 // Now we know the widest induction type, check if our found induction
4355 // is the same size. If it's not, unset it here and InnerLoopVectorizer
4356 // will create another.
4357 if (Induction && WidestIndTy != Induction->getType())
4358 Induction = nullptr;
4363 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4364 Value *Ptr = nullptr;
4365 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4366 Ptr = LI->getPointerOperand();
4367 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4368 Ptr = SI->getPointerOperand();
4372 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4376 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4377 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4378 Strides[Ptr] = Stride;
4379 StrideSet.insert(Stride);
4382 void LoopVectorizationLegality::collectLoopUniforms() {
4383 // We now know that the loop is vectorizable!
4384 // Collect variables that will remain uniform after vectorization.
4385 std::vector<Value*> Worklist;
4386 BasicBlock *Latch = TheLoop->getLoopLatch();
4388 // Start with the conditional branch and walk up the block.
4389 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4391 // Also add all consecutive pointer values; these values will be uniform
4392 // after vectorization (and subsequent cleanup) and, until revectorization is
4393 // supported, all dependencies must also be uniform.
4394 for (Loop::block_iterator B = TheLoop->block_begin(),
4395 BE = TheLoop->block_end(); B != BE; ++B)
4396 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4398 if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
4399 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4401 while (!Worklist.empty()) {
4402 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4403 Worklist.pop_back();
4405 // Look at instructions inside this loop.
4406 // Stop when reaching PHI nodes.
4407 // TODO: we need to follow values all over the loop, not only in this block.
4408 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4411 // This is a known uniform.
4414 // Insert all operands.
4415 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4419 bool LoopVectorizationLegality::canVectorizeMemory() {
4420 LAI = &LAA->getInfo(TheLoop, Strides);
4421 auto &OptionalReport = LAI->getReport();
4423 emitAnalysis(VectorizationReport(*OptionalReport));
4424 if (!LAI->canVectorizeMemory())
4427 if (LAI->hasStoreToLoopInvariantAddress()) {
4429 VectorizationReport()
4430 << "write to a loop invariant address could not be vectorized");
4431 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4435 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4436 Preds.add(&LAI->Preds);
4441 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4442 Value *In0 = const_cast<Value*>(V);
4443 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4447 return Inductions.count(PN);
4450 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4451 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4454 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4455 SmallPtrSetImpl<Value *> &SafePtrs) {
4457 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4458 // Check that we don't have a constant expression that can trap as operand.
4459 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4461 if (Constant *C = dyn_cast<Constant>(*OI))
4465 // We might be able to hoist the load.
4466 if (it->mayReadFromMemory()) {
4467 LoadInst *LI = dyn_cast<LoadInst>(it);
4470 if (!SafePtrs.count(LI->getPointerOperand())) {
4471 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4472 MaskedOp.insert(LI);
4479 // We don't predicate stores at the moment.
4480 if (it->mayWriteToMemory()) {
4481 StoreInst *SI = dyn_cast<StoreInst>(it);
4482 // We only support predication of stores in basic blocks with one
4487 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4488 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4490 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4491 !isSinglePredecessor) {
4492 // Build a masked store if it is legal for the target, otherwise scalarize
4494 bool isLegalMaskedOp =
4495 isLegalMaskedStore(SI->getValueOperand()->getType(),
4496 SI->getPointerOperand());
4497 if (isLegalMaskedOp) {
4499 MaskedOp.insert(SI);
4508 // The instructions below can trap.
4509 switch (it->getOpcode()) {
4511 case Instruction::UDiv:
4512 case Instruction::SDiv:
4513 case Instruction::URem:
4514 case Instruction::SRem:
4522 void InterleavedAccessInfo::collectConstStridedAccesses(
4523 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4524 const ValueToValueMap &Strides) {
4525 // Holds load/store instructions in program order.
4526 SmallVector<Instruction *, 16> AccessList;
4528 for (auto *BB : TheLoop->getBlocks()) {
4529 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4531 for (auto &I : *BB) {
4532 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4534 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4538 AccessList.push_back(&I);
4542 if (AccessList.empty())
4545 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4546 for (auto I : AccessList) {
4547 LoadInst *LI = dyn_cast<LoadInst>(I);
4548 StoreInst *SI = dyn_cast<StoreInst>(I);
4550 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4551 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides, Preds);
4553 // The factor of the corresponding interleave group.
4554 unsigned Factor = std::abs(Stride);
4556 // Ignore the access if the factor is too small or too large.
4557 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4560 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Preds, Ptr);
4561 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4562 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4564 // An alignment of 0 means target ABI alignment.
4565 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4567 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4569 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4573 // Analyze interleaved accesses and collect them into interleave groups.
4575 // Notice that the vectorization on interleaved groups will change instruction
4576 // orders and may break dependences. But the memory dependence check guarantees
4577 // that there is no overlap between two pointers of different strides, element
4578 // sizes or underlying bases.
4580 // For pointers sharing the same stride, element size and underlying base, no
4581 // need to worry about Read-After-Write dependences and Write-After-Read
4584 // E.g. The RAW dependence: A[i] = a;
4586 // This won't exist as it is a store-load forwarding conflict, which has
4587 // already been checked and forbidden in the dependence check.
4589 // E.g. The WAR dependence: a = A[i]; // (1)
4591 // The store group of (2) is always inserted at or below (2), and the load group
4592 // of (1) is always inserted at or above (1). The dependence is safe.
4593 void InterleavedAccessInfo::analyzeInterleaving(
4594 const ValueToValueMap &Strides) {
4595 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4597 // Holds all the stride accesses.
4598 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4599 collectConstStridedAccesses(StrideAccesses, Strides);
4601 if (StrideAccesses.empty())
4604 // Holds all interleaved store groups temporarily.
4605 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4607 // Search the load-load/write-write pair B-A in bottom-up order and try to
4608 // insert B into the interleave group of A according to 3 rules:
4609 // 1. A and B have the same stride.
4610 // 2. A and B have the same memory object size.
4611 // 3. B belongs to the group according to the distance.
4613 // The bottom-up order can avoid breaking the Write-After-Write dependences
4614 // between two pointers of the same base.
4615 // E.g. A[i] = a; (1)
4618 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4619 // above (1), which guarantees that (1) is always above (2).
4620 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4622 Instruction *A = I->first;
4623 StrideDescriptor DesA = I->second;
4625 InterleaveGroup *Group = getInterleaveGroup(A);
4627 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4628 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4631 if (A->mayWriteToMemory())
4632 StoreGroups.insert(Group);
4634 for (auto II = std::next(I); II != E; ++II) {
4635 Instruction *B = II->first;
4636 StrideDescriptor DesB = II->second;
4638 // Ignore if B is already in a group or B is a different memory operation.
4639 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4642 // Check the rule 1 and 2.
4643 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4646 // Calculate the distance and prepare for the rule 3.
4647 const SCEVConstant *DistToA =
4648 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4652 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4654 // Skip if the distance is not multiple of size as they are not in the
4656 if (DistanceToA % static_cast<int>(DesA.Size))
4659 // The index of B is the index of A plus the related index to A.
4661 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4663 // Try to insert B into the group.
4664 if (Group->insertMember(B, IndexB, DesB.Align)) {
4665 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4666 << " into the interleave group with" << *A << '\n');
4667 InterleaveGroupMap[B] = Group;
4669 // Set the first load in program order as the insert position.
4670 if (B->mayReadFromMemory())
4671 Group->setInsertPos(B);
4673 } // Iteration on instruction B
4674 } // Iteration on instruction A
4676 // Remove interleaved store groups with gaps.
4677 for (InterleaveGroup *Group : StoreGroups)
4678 if (Group->getNumMembers() != Group->getFactor())
4679 releaseGroup(Group);
4682 LoopVectorizationCostModel::VectorizationFactor
4683 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4684 // Width 1 means no vectorize
4685 VectorizationFactor Factor = { 1U, 0U };
4686 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4687 emitAnalysis(VectorizationReport() <<
4688 "runtime pointer checks needed. Enable vectorization of this "
4689 "loop with '#pragma clang loop vectorize(enable)' when "
4690 "compiling with -Os/-Oz");
4692 "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4696 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4697 emitAnalysis(VectorizationReport() <<
4698 "store that is conditionally executed prevents vectorization");
4699 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4703 // Find the trip count.
4704 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4705 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4707 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4708 unsigned WidestType = getWidestType();
4709 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4710 unsigned MaxSafeDepDist = -1U;
4711 if (Legal->getMaxSafeDepDistBytes() != -1U)
4712 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4713 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4714 WidestRegister : MaxSafeDepDist);
4715 unsigned MaxVectorSize = WidestRegister / WidestType;
4716 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4717 DEBUG(dbgs() << "LV: The Widest register is: "
4718 << WidestRegister << " bits.\n");
4720 if (MaxVectorSize == 0) {
4721 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4725 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4726 " into one vector!");
4728 unsigned VF = MaxVectorSize;
4730 // If we optimize the program for size, avoid creating the tail loop.
4732 // If we are unable to calculate the trip count then don't try to vectorize.
4735 (VectorizationReport() <<
4736 "unable to calculate the loop count due to complex control flow");
4737 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4741 // Find the maximum SIMD width that can fit within the trip count.
4742 VF = TC % MaxVectorSize;
4747 // If the trip count that we found modulo the vectorization factor is not
4748 // zero then we require a tail.
4749 emitAnalysis(VectorizationReport() <<
4750 "cannot optimize for size and vectorize at the "
4751 "same time. Enable vectorization of this loop "
4752 "with '#pragma clang loop vectorize(enable)' "
4753 "when compiling with -Os/-Oz");
4754 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4759 int UserVF = Hints->getWidth();
4761 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4762 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4764 Factor.Width = UserVF;
4768 float Cost = expectedCost(1);
4770 const float ScalarCost = Cost;
4773 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4775 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4776 // Ignore scalar width, because the user explicitly wants vectorization.
4777 if (ForceVectorization && VF > 1) {
4779 Cost = expectedCost(Width) / (float)Width;
4782 for (unsigned i=2; i <= VF; i*=2) {
4783 // Notice that the vector loop needs to be executed less times, so
4784 // we need to divide the cost of the vector loops by the width of
4785 // the vector elements.
4786 float VectorCost = expectedCost(i) / (float)i;
4787 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4788 (int)VectorCost << ".\n");
4789 if (VectorCost < Cost) {
4795 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4796 << "LV: Vectorization seems to be not beneficial, "
4797 << "but was forced by a user.\n");
4798 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4799 Factor.Width = Width;
4800 Factor.Cost = Width * Cost;
4804 unsigned LoopVectorizationCostModel::getWidestType() {
4805 unsigned MaxWidth = 8;
4806 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4809 for (Loop::block_iterator bb = TheLoop->block_begin(),
4810 be = TheLoop->block_end(); bb != be; ++bb) {
4811 BasicBlock *BB = *bb;
4813 // For each instruction in the loop.
4814 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4815 Type *T = it->getType();
4817 // Skip ignored values.
4818 if (ValuesToIgnore.count(&*it))
4821 // Only examine Loads, Stores and PHINodes.
4822 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4825 // Examine PHI nodes that are reduction variables. Update the type to
4826 // account for the recurrence type.
4827 if (PHINode *PN = dyn_cast<PHINode>(it)) {
4828 if (!Legal->getReductionVars()->count(PN))
4830 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4831 T = RdxDesc.getRecurrenceType();
4834 // Examine the stored values.
4835 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4836 T = ST->getValueOperand()->getType();
4838 // Ignore loaded pointer types and stored pointer types that are not
4839 // consecutive. However, we do want to take consecutive stores/loads of
4840 // pointer vectors into account.
4841 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
4844 MaxWidth = std::max(MaxWidth,
4845 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4852 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4854 unsigned LoopCost) {
4856 // -- The interleave heuristics --
4857 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4858 // There are many micro-architectural considerations that we can't predict
4859 // at this level. For example, frontend pressure (on decode or fetch) due to
4860 // code size, or the number and capabilities of the execution ports.
4862 // We use the following heuristics to select the interleave count:
4863 // 1. If the code has reductions, then we interleave to break the cross
4864 // iteration dependency.
4865 // 2. If the loop is really small, then we interleave to reduce the loop
4867 // 3. We don't interleave if we think that we will spill registers to memory
4868 // due to the increased register pressure.
4870 // When we optimize for size, we don't interleave.
4874 // We used the distance for the interleave count.
4875 if (Legal->getMaxSafeDepDistBytes() != -1U)
4878 // Do not interleave loops with a relatively small trip count.
4879 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4880 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4883 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4884 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4888 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4889 TargetNumRegisters = ForceTargetNumScalarRegs;
4891 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4892 TargetNumRegisters = ForceTargetNumVectorRegs;
4895 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4896 // We divide by these constants so assume that we have at least one
4897 // instruction that uses at least one register.
4898 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4899 R.NumInstructions = std::max(R.NumInstructions, 1U);
4901 // We calculate the interleave count using the following formula.
4902 // Subtract the number of loop invariants from the number of available
4903 // registers. These registers are used by all of the interleaved instances.
4904 // Next, divide the remaining registers by the number of registers that is
4905 // required by the loop, in order to estimate how many parallel instances
4906 // fit without causing spills. All of this is rounded down if necessary to be
4907 // a power of two. We want power of two interleave count to simplify any
4908 // addressing operations or alignment considerations.
4909 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4912 // Don't count the induction variable as interleaved.
4913 if (EnableIndVarRegisterHeur)
4914 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4915 std::max(1U, (R.MaxLocalUsers - 1)));
4917 // Clamp the interleave ranges to reasonable counts.
4918 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4920 // Check if the user has overridden the max.
4922 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4923 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4925 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4926 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4929 // If we did not calculate the cost for VF (because the user selected the VF)
4930 // then we calculate the cost of VF here.
4932 LoopCost = expectedCost(VF);
4934 // Clamp the calculated IC to be between the 1 and the max interleave count
4935 // that the target allows.
4936 if (IC > MaxInterleaveCount)
4937 IC = MaxInterleaveCount;
4941 // Interleave if we vectorized this loop and there is a reduction that could
4942 // benefit from interleaving.
4943 if (VF > 1 && Legal->getReductionVars()->size()) {
4944 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4948 // Note that if we've already vectorized the loop we will have done the
4949 // runtime check and so interleaving won't require further checks.
4950 bool InterleavingRequiresRuntimePointerCheck =
4951 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4953 // We want to interleave small loops in order to reduce the loop overhead and
4954 // potentially expose ILP opportunities.
4955 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4956 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4957 // We assume that the cost overhead is 1 and we use the cost model
4958 // to estimate the cost of the loop and interleave until the cost of the
4959 // loop overhead is about 5% of the cost of the loop.
4961 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4963 // Interleave until store/load ports (estimated by max interleave count) are
4965 unsigned NumStores = Legal->getNumStores();
4966 unsigned NumLoads = Legal->getNumLoads();
4967 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4968 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4970 // If we have a scalar reduction (vector reductions are already dealt with
4971 // by this point), we can increase the critical path length if the loop
4972 // we're interleaving is inside another loop. Limit, by default to 2, so the
4973 // critical path only gets increased by one reduction operation.
4974 if (Legal->getReductionVars()->size() &&
4975 TheLoop->getLoopDepth() > 1) {
4976 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4977 SmallIC = std::min(SmallIC, F);
4978 StoresIC = std::min(StoresIC, F);
4979 LoadsIC = std::min(LoadsIC, F);
4982 if (EnableLoadStoreRuntimeInterleave &&
4983 std::max(StoresIC, LoadsIC) > SmallIC) {
4984 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4985 return std::max(StoresIC, LoadsIC);
4988 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4992 // Interleave if this is a large loop (small loops are already dealt with by
4994 // point) that could benefit from interleaving.
4995 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4996 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4997 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5001 DEBUG(dbgs() << "LV: Not Interleaving.\n");
5005 LoopVectorizationCostModel::RegisterUsage
5006 LoopVectorizationCostModel::calculateRegisterUsage() {
5007 // This function calculates the register usage by measuring the highest number
5008 // of values that are alive at a single location. Obviously, this is a very
5009 // rough estimation. We scan the loop in a topological order in order and
5010 // assign a number to each instruction. We use RPO to ensure that defs are
5011 // met before their users. We assume that each instruction that has in-loop
5012 // users starts an interval. We record every time that an in-loop value is
5013 // used, so we have a list of the first and last occurrences of each
5014 // instruction. Next, we transpose this data structure into a multi map that
5015 // holds the list of intervals that *end* at a specific location. This multi
5016 // map allows us to perform a linear search. We scan the instructions linearly
5017 // and record each time that a new interval starts, by placing it in a set.
5018 // If we find this value in the multi-map then we remove it from the set.
5019 // The max register usage is the maximum size of the set.
5020 // We also search for instructions that are defined outside the loop, but are
5021 // used inside the loop. We need this number separately from the max-interval
5022 // usage number because when we unroll, loop-invariant values do not take
5024 LoopBlocksDFS DFS(TheLoop);
5028 R.NumInstructions = 0;
5030 // Each 'key' in the map opens a new interval. The values
5031 // of the map are the index of the 'last seen' usage of the
5032 // instruction that is the key.
5033 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5034 // Maps instruction to its index.
5035 DenseMap<unsigned, Instruction*> IdxToInstr;
5036 // Marks the end of each interval.
5037 IntervalMap EndPoint;
5038 // Saves the list of instruction indices that are used in the loop.
5039 SmallSet<Instruction*, 8> Ends;
5040 // Saves the list of values that are used in the loop but are
5041 // defined outside the loop, such as arguments and constants.
5042 SmallPtrSet<Value*, 8> LoopInvariants;
5045 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5046 be = DFS.endRPO(); bb != be; ++bb) {
5047 R.NumInstructions += (*bb)->size();
5048 for (Instruction &I : **bb) {
5049 IdxToInstr[Index++] = &I;
5051 // Save the end location of each USE.
5052 for (unsigned i = 0; i < I.getNumOperands(); ++i) {
5053 Value *U = I.getOperand(i);
5054 Instruction *Instr = dyn_cast<Instruction>(U);
5056 // Ignore non-instruction values such as arguments, constants, etc.
5057 if (!Instr) continue;
5059 // If this instruction is outside the loop then record it and continue.
5060 if (!TheLoop->contains(Instr)) {
5061 LoopInvariants.insert(Instr);
5065 // Overwrite previous end points.
5066 EndPoint[Instr] = Index;
5072 // Saves the list of intervals that end with the index in 'key'.
5073 typedef SmallVector<Instruction*, 2> InstrList;
5074 DenseMap<unsigned, InstrList> TransposeEnds;
5076 // Transpose the EndPoints to a list of values that end at each index.
5077 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5079 TransposeEnds[it->second].push_back(it->first);
5081 SmallSet<Instruction*, 8> OpenIntervals;
5082 unsigned MaxUsage = 0;
5085 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5086 for (unsigned int i = 0; i < Index; ++i) {
5087 Instruction *I = IdxToInstr[i];
5088 // Ignore instructions that are never used within the loop.
5089 if (!Ends.count(I)) continue;
5091 // Skip ignored values.
5092 if (ValuesToIgnore.count(I))
5095 // Remove all of the instructions that end at this location.
5096 InstrList &List = TransposeEnds[i];
5097 for (unsigned int j=0, e = List.size(); j < e; ++j)
5098 OpenIntervals.erase(List[j]);
5100 // Count the number of live interals.
5101 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5103 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5104 OpenIntervals.size() << '\n');
5106 // Add the current instruction to the list of open intervals.
5107 OpenIntervals.insert(I);
5110 unsigned Invariant = LoopInvariants.size();
5111 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5112 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5113 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5115 R.LoopInvariantRegs = Invariant;
5116 R.MaxLocalUsers = MaxUsage;
5120 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5124 for (Loop::block_iterator bb = TheLoop->block_begin(),
5125 be = TheLoop->block_end(); bb != be; ++bb) {
5126 unsigned BlockCost = 0;
5127 BasicBlock *BB = *bb;
5129 // For each instruction in the old loop.
5130 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5131 // Skip dbg intrinsics.
5132 if (isa<DbgInfoIntrinsic>(it))
5135 // Skip ignored values.
5136 if (ValuesToIgnore.count(&*it))
5139 unsigned C = getInstructionCost(&*it, VF);
5141 // Check if we should override the cost.
5142 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5143 C = ForceTargetInstructionCost;
5146 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5147 VF << " For instruction: " << *it << '\n');
5150 // We assume that if-converted blocks have a 50% chance of being executed.
5151 // When the code is scalar then some of the blocks are avoided due to CF.
5152 // When the code is vectorized we execute all code paths.
5153 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5162 /// \brief Check whether the address computation for a non-consecutive memory
5163 /// access looks like an unlikely candidate for being merged into the indexing
5166 /// We look for a GEP which has one index that is an induction variable and all
5167 /// other indices are loop invariant. If the stride of this access is also
5168 /// within a small bound we decide that this address computation can likely be
5169 /// merged into the addressing mode.
5170 /// In all other cases, we identify the address computation as complex.
5171 static bool isLikelyComplexAddressComputation(Value *Ptr,
5172 LoopVectorizationLegality *Legal,
5173 ScalarEvolution *SE,
5174 const Loop *TheLoop) {
5175 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5179 // We are looking for a gep with all loop invariant indices except for one
5180 // which should be an induction variable.
5181 unsigned NumOperands = Gep->getNumOperands();
5182 for (unsigned i = 1; i < NumOperands; ++i) {
5183 Value *Opd = Gep->getOperand(i);
5184 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5185 !Legal->isInductionVariable(Opd))
5189 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5190 // can likely be merged into the address computation.
5191 unsigned MaxMergeDistance = 64;
5193 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5197 // Check the step is constant.
5198 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5199 // Calculate the pointer stride and check if it is consecutive.
5200 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5204 const APInt &APStepVal = C->getValue()->getValue();
5206 // Huge step value - give up.
5207 if (APStepVal.getBitWidth() > 64)
5210 int64_t StepVal = APStepVal.getSExtValue();
5212 return StepVal > MaxMergeDistance;
5215 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5216 return Legal->hasStride(I->getOperand(0)) ||
5217 Legal->hasStride(I->getOperand(1));
5221 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5222 // If we know that this instruction will remain uniform, check the cost of
5223 // the scalar version.
5224 if (Legal->isUniformAfterVectorization(I))
5227 Type *RetTy = I->getType();
5228 if (VF > 1 && MinBWs.count(I))
5229 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
5230 Type *VectorTy = ToVectorTy(RetTy, VF);
5232 // TODO: We need to estimate the cost of intrinsic calls.
5233 switch (I->getOpcode()) {
5234 case Instruction::GetElementPtr:
5235 // We mark this instruction as zero-cost because the cost of GEPs in
5236 // vectorized code depends on whether the corresponding memory instruction
5237 // is scalarized or not. Therefore, we handle GEPs with the memory
5238 // instruction cost.
5240 case Instruction::Br: {
5241 return TTI.getCFInstrCost(I->getOpcode());
5243 case Instruction::PHI:
5244 //TODO: IF-converted IFs become selects.
5246 case Instruction::Add:
5247 case Instruction::FAdd:
5248 case Instruction::Sub:
5249 case Instruction::FSub:
5250 case Instruction::Mul:
5251 case Instruction::FMul:
5252 case Instruction::UDiv:
5253 case Instruction::SDiv:
5254 case Instruction::FDiv:
5255 case Instruction::URem:
5256 case Instruction::SRem:
5257 case Instruction::FRem:
5258 case Instruction::Shl:
5259 case Instruction::LShr:
5260 case Instruction::AShr:
5261 case Instruction::And:
5262 case Instruction::Or:
5263 case Instruction::Xor: {
5264 // Since we will replace the stride by 1 the multiplication should go away.
5265 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5267 // Certain instructions can be cheaper to vectorize if they have a constant
5268 // second vector operand. One example of this are shifts on x86.
5269 TargetTransformInfo::OperandValueKind Op1VK =
5270 TargetTransformInfo::OK_AnyValue;
5271 TargetTransformInfo::OperandValueKind Op2VK =
5272 TargetTransformInfo::OK_AnyValue;
5273 TargetTransformInfo::OperandValueProperties Op1VP =
5274 TargetTransformInfo::OP_None;
5275 TargetTransformInfo::OperandValueProperties Op2VP =
5276 TargetTransformInfo::OP_None;
5277 Value *Op2 = I->getOperand(1);
5279 // Check for a splat of a constant or for a non uniform vector of constants.
5280 if (isa<ConstantInt>(Op2)) {
5281 ConstantInt *CInt = cast<ConstantInt>(Op2);
5282 if (CInt && CInt->getValue().isPowerOf2())
5283 Op2VP = TargetTransformInfo::OP_PowerOf2;
5284 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5285 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5286 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5287 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5289 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5290 if (CInt && CInt->getValue().isPowerOf2())
5291 Op2VP = TargetTransformInfo::OP_PowerOf2;
5292 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5296 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5299 case Instruction::Select: {
5300 SelectInst *SI = cast<SelectInst>(I);
5301 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5302 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5303 Type *CondTy = SI->getCondition()->getType();
5305 CondTy = VectorType::get(CondTy, VF);
5307 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5309 case Instruction::ICmp:
5310 case Instruction::FCmp: {
5311 Type *ValTy = I->getOperand(0)->getType();
5312 if (VF > 1 && MinBWs.count(dyn_cast<Instruction>(I->getOperand(0))))
5313 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[I]);
5314 VectorTy = ToVectorTy(ValTy, VF);
5315 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5317 case Instruction::Store:
5318 case Instruction::Load: {
5319 StoreInst *SI = dyn_cast<StoreInst>(I);
5320 LoadInst *LI = dyn_cast<LoadInst>(I);
5321 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5323 VectorTy = ToVectorTy(ValTy, VF);
5325 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5326 unsigned AS = SI ? SI->getPointerAddressSpace() :
5327 LI->getPointerAddressSpace();
5328 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5329 // We add the cost of address computation here instead of with the gep
5330 // instruction because only here we know whether the operation is
5333 return TTI.getAddressComputationCost(VectorTy) +
5334 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5336 // For an interleaved access, calculate the total cost of the whole
5337 // interleave group.
5338 if (Legal->isAccessInterleaved(I)) {
5339 auto Group = Legal->getInterleavedAccessGroup(I);
5340 assert(Group && "Fail to get an interleaved access group.");
5342 // Only calculate the cost once at the insert position.
5343 if (Group->getInsertPos() != I)
5346 unsigned InterleaveFactor = Group->getFactor();
5348 VectorType::get(VectorTy->getVectorElementType(),
5349 VectorTy->getVectorNumElements() * InterleaveFactor);
5351 // Holds the indices of existing members in an interleaved load group.
5352 // An interleaved store group doesn't need this as it dones't allow gaps.
5353 SmallVector<unsigned, 4> Indices;
5355 for (unsigned i = 0; i < InterleaveFactor; i++)
5356 if (Group->getMember(i))
5357 Indices.push_back(i);
5360 // Calculate the cost of the whole interleaved group.
5361 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5362 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5363 Group->getAlignment(), AS);
5365 if (Group->isReverse())
5367 Group->getNumMembers() *
5368 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5370 // FIXME: The interleaved load group with a huge gap could be even more
5371 // expensive than scalar operations. Then we could ignore such group and
5372 // use scalar operations instead.
5376 // Scalarized loads/stores.
5377 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5378 bool Reverse = ConsecutiveStride < 0;
5379 const DataLayout &DL = I->getModule()->getDataLayout();
5380 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5381 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5382 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5383 bool IsComplexComputation =
5384 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5386 // The cost of extracting from the value vector and pointer vector.
5387 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5388 for (unsigned i = 0; i < VF; ++i) {
5389 // The cost of extracting the pointer operand.
5390 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5391 // In case of STORE, the cost of ExtractElement from the vector.
5392 // In case of LOAD, the cost of InsertElement into the returned
5394 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5395 Instruction::InsertElement,
5399 // The cost of the scalar loads/stores.
5400 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5401 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5406 // Wide load/stores.
5407 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5408 if (Legal->isMaskRequired(I))
5409 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5412 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5415 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5419 case Instruction::ZExt:
5420 case Instruction::SExt:
5421 case Instruction::FPToUI:
5422 case Instruction::FPToSI:
5423 case Instruction::FPExt:
5424 case Instruction::PtrToInt:
5425 case Instruction::IntToPtr:
5426 case Instruction::SIToFP:
5427 case Instruction::UIToFP:
5428 case Instruction::Trunc:
5429 case Instruction::FPTrunc:
5430 case Instruction::BitCast: {
5431 // We optimize the truncation of induction variable.
5432 // The cost of these is the same as the scalar operation.
5433 if (I->getOpcode() == Instruction::Trunc &&
5434 Legal->isInductionVariable(I->getOperand(0)))
5435 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5436 I->getOperand(0)->getType());
5438 Type *SrcScalarTy = I->getOperand(0)->getType();
5439 Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
5440 if (VF > 1 && MinBWs.count(I)) {
5441 // This cast is going to be shrunk. This may remove the cast or it might
5442 // turn it into slightly different cast. For example, if MinBW == 16,
5443 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
5445 // Calculate the modified src and dest types.
5446 Type *MinVecTy = VectorTy;
5447 if (I->getOpcode() == Instruction::Trunc) {
5448 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
5449 VectorTy = largestIntegerVectorType(ToVectorTy(I->getType(), VF),
5451 } else if (I->getOpcode() == Instruction::ZExt ||
5452 I->getOpcode() == Instruction::SExt) {
5453 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
5454 VectorTy = smallestIntegerVectorType(ToVectorTy(I->getType(), VF),
5459 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5461 case Instruction::Call: {
5462 bool NeedToScalarize;
5463 CallInst *CI = cast<CallInst>(I);
5464 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5465 if (getIntrinsicIDForCall(CI, TLI))
5466 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5470 // We are scalarizing the instruction. Return the cost of the scalar
5471 // instruction, plus the cost of insert and extract into vector
5472 // elements, times the vector width.
5475 if (!RetTy->isVoidTy() && VF != 1) {
5476 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5478 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5481 // The cost of inserting the results plus extracting each one of the
5483 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5486 // The cost of executing VF copies of the scalar instruction. This opcode
5487 // is unknown. Assume that it is the same as 'mul'.
5488 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5494 char LoopVectorize::ID = 0;
5495 static const char lv_name[] = "Loop Vectorization";
5496 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5497 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5498 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
5499 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5500 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
5501 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5502 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5503 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5504 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5505 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5506 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5507 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5508 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5509 INITIALIZE_PASS_DEPENDENCY(DemandedBits)
5510 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5513 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5514 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5518 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5519 // Check for a store.
5520 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5521 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5523 // Check for a load.
5524 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5525 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5531 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5532 bool IfPredicateStore) {
5533 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5534 // Holds vector parameters or scalars, in case of uniform vals.
5535 SmallVector<VectorParts, 4> Params;
5537 setDebugLocFromInst(Builder, Instr);
5539 // Find all of the vectorized parameters.
5540 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5541 Value *SrcOp = Instr->getOperand(op);
5543 // If we are accessing the old induction variable, use the new one.
5544 if (SrcOp == OldInduction) {
5545 Params.push_back(getVectorValue(SrcOp));
5549 // Try using previously calculated values.
5550 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5552 // If the src is an instruction that appeared earlier in the basic block
5553 // then it should already be vectorized.
5554 if (SrcInst && OrigLoop->contains(SrcInst)) {
5555 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5556 // The parameter is a vector value from earlier.
5557 Params.push_back(WidenMap.get(SrcInst));
5559 // The parameter is a scalar from outside the loop. Maybe even a constant.
5560 VectorParts Scalars;
5561 Scalars.append(UF, SrcOp);
5562 Params.push_back(Scalars);
5566 assert(Params.size() == Instr->getNumOperands() &&
5567 "Invalid number of operands");
5569 // Does this instruction return a value ?
5570 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5572 Value *UndefVec = IsVoidRetTy ? nullptr :
5573 UndefValue::get(Instr->getType());
5574 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5575 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5578 if (IfPredicateStore) {
5579 assert(Instr->getParent()->getSinglePredecessor() &&
5580 "Only support single predecessor blocks");
5581 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5582 Instr->getParent());
5585 // For each vector unroll 'part':
5586 for (unsigned Part = 0; Part < UF; ++Part) {
5587 // For each scalar that we create:
5589 // Start an "if (pred) a[i] = ..." block.
5590 Value *Cmp = nullptr;
5591 if (IfPredicateStore) {
5592 if (Cond[Part]->getType()->isVectorTy())
5594 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5595 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5596 ConstantInt::get(Cond[Part]->getType(), 1));
5599 Instruction *Cloned = Instr->clone();
5601 Cloned->setName(Instr->getName() + ".cloned");
5602 // Replace the operands of the cloned instructions with extracted scalars.
5603 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5604 Value *Op = Params[op][Part];
5605 Cloned->setOperand(op, Op);
5608 // Place the cloned scalar in the new loop.
5609 Builder.Insert(Cloned);
5611 // If the original scalar returns a value we need to place it in a vector
5612 // so that future users will be able to use it.
5614 VecResults[Part] = Cloned;
5617 if (IfPredicateStore)
5618 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
5623 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5624 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5625 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5627 return scalarizeInstruction(Instr, IfPredicateStore);
5630 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5634 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5638 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5639 // When unrolling and the VF is 1, we only need to add a simple scalar.
5640 Type *ITy = Val->getType();
5641 assert(!ITy->isVectorTy() && "Val must be a scalar");
5642 Constant *C = ConstantInt::get(ITy, StartIdx);
5643 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");