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 static cl::opt<bool> MaximizeBandwidth(
130 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
131 cl::desc("Maximize bandwidth when selecting vectorization factor which "
132 "will be determined by the smallest type in loop."));
134 /// This enables versioning on the strides of symbolically striding memory
135 /// accesses in code like the following.
136 /// for (i = 0; i < N; ++i)
137 /// A[i * Stride1] += B[i * Stride2] ...
139 /// Will be roughly translated to
140 /// if (Stride1 == 1 && Stride2 == 1) {
141 /// for (i = 0; i < N; i+=4)
145 static cl::opt<bool> EnableMemAccessVersioning(
146 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
147 cl::desc("Enable symblic stride memory access versioning"));
149 static cl::opt<bool> EnableInterleavedMemAccesses(
150 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
151 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
153 /// Maximum factor for an interleaved memory access.
154 static cl::opt<unsigned> MaxInterleaveGroupFactor(
155 "max-interleave-group-factor", cl::Hidden,
156 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
159 /// We don't interleave loops with a known constant trip count below this
161 static const unsigned TinyTripCountInterleaveThreshold = 128;
163 static cl::opt<unsigned> ForceTargetNumScalarRegs(
164 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
165 cl::desc("A flag that overrides the target's number of scalar registers."));
167 static cl::opt<unsigned> ForceTargetNumVectorRegs(
168 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
169 cl::desc("A flag that overrides the target's number of vector registers."));
171 /// Maximum vectorization interleave count.
172 static const unsigned MaxInterleaveFactor = 16;
174 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
175 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
176 cl::desc("A flag that overrides the target's max interleave factor for "
179 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
180 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
181 cl::desc("A flag that overrides the target's max interleave factor for "
182 "vectorized loops."));
184 static cl::opt<unsigned> ForceTargetInstructionCost(
185 "force-target-instruction-cost", cl::init(0), cl::Hidden,
186 cl::desc("A flag that overrides the target's expected cost for "
187 "an instruction to a single constant value. Mostly "
188 "useful for getting consistent testing."));
190 static cl::opt<unsigned> SmallLoopCost(
191 "small-loop-cost", cl::init(20), cl::Hidden,
193 "The cost of a loop that is considered 'small' by the interleaver."));
195 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
196 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
197 cl::desc("Enable the use of the block frequency analysis to access PGO "
198 "heuristics minimizing code growth in cold regions and being more "
199 "aggressive in hot regions."));
201 // Runtime interleave loops for load/store throughput.
202 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
203 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
205 "Enable runtime interleaving until load/store ports are saturated"));
207 /// The number of stores in a loop that are allowed to need predication.
208 static cl::opt<unsigned> NumberOfStoresToPredicate(
209 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
210 cl::desc("Max number of stores to be predicated behind an if."));
212 static cl::opt<bool> EnableIndVarRegisterHeur(
213 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
214 cl::desc("Count the induction variable only once when interleaving"));
216 static cl::opt<bool> EnableCondStoresVectorization(
217 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
218 cl::desc("Enable if predication of stores during vectorization."));
220 static cl::opt<unsigned> MaxNestedScalarReductionIC(
221 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
222 cl::desc("The maximum interleave count to use when interleaving a scalar "
223 "reduction in a nested loop."));
225 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
226 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
227 cl::desc("The maximum allowed number of runtime memory checks with a "
228 "vectorize(enable) pragma."));
230 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
231 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
232 cl::desc("The maximum number of SCEV checks allowed."));
234 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
235 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
236 cl::desc("The maximum number of SCEV checks allowed with a "
237 "vectorize(enable) pragma"));
241 // Forward declarations.
242 class LoopVectorizeHints;
243 class LoopVectorizationLegality;
244 class LoopVectorizationCostModel;
245 class LoopVectorizationRequirements;
247 /// \brief This modifies LoopAccessReport to initialize message with
248 /// loop-vectorizer-specific part.
249 class VectorizationReport : public LoopAccessReport {
251 VectorizationReport(Instruction *I = nullptr)
252 : LoopAccessReport("loop not vectorized: ", I) {}
254 /// \brief This allows promotion of the loop-access analysis report into the
255 /// loop-vectorizer report. It modifies the message to add the
256 /// loop-vectorizer-specific part of the message.
257 explicit VectorizationReport(const LoopAccessReport &R)
258 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
262 /// A helper function for converting Scalar types to vector types.
263 /// If the incoming type is void, we return void. If the VF is 1, we return
265 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
266 if (Scalar->isVoidTy() || VF == 1)
268 return VectorType::get(Scalar, VF);
271 /// A helper function that returns GEP instruction and knows to skip a
272 /// 'bitcast'. The 'bitcast' may be skipped if the source and the destination
273 /// pointee types of the 'bitcast' have the same size.
275 /// bitcast double** %var to i64* - can be skipped
276 /// bitcast double** %var to i8* - can not
277 static GetElementPtrInst *getGEPInstruction(Value *Ptr) {
279 if (isa<GetElementPtrInst>(Ptr))
280 return cast<GetElementPtrInst>(Ptr);
282 if (isa<BitCastInst>(Ptr) &&
283 isa<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0))) {
284 Type *BitcastTy = Ptr->getType();
285 Type *GEPTy = cast<BitCastInst>(Ptr)->getSrcTy();
286 if (!isa<PointerType>(BitcastTy) || !isa<PointerType>(GEPTy))
288 Type *Pointee1Ty = cast<PointerType>(BitcastTy)->getPointerElementType();
289 Type *Pointee2Ty = cast<PointerType>(GEPTy)->getPointerElementType();
290 const DataLayout &DL = cast<BitCastInst>(Ptr)->getModule()->getDataLayout();
291 if (DL.getTypeSizeInBits(Pointee1Ty) == DL.getTypeSizeInBits(Pointee2Ty))
292 return cast<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0));
297 /// InnerLoopVectorizer vectorizes loops which contain only one basic
298 /// block to a specified vectorization factor (VF).
299 /// This class performs the widening of scalars into vectors, or multiple
300 /// scalars. This class also implements the following features:
301 /// * It inserts an epilogue loop for handling loops that don't have iteration
302 /// counts that are known to be a multiple of the vectorization factor.
303 /// * It handles the code generation for reduction variables.
304 /// * Scalarization (implementation using scalars) of un-vectorizable
306 /// InnerLoopVectorizer does not perform any vectorization-legality
307 /// checks, and relies on the caller to check for the different legality
308 /// aspects. The InnerLoopVectorizer relies on the
309 /// LoopVectorizationLegality class to provide information about the induction
310 /// and reduction variables that were found to a given vectorization factor.
311 class InnerLoopVectorizer {
313 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
314 DominatorTree *DT, const TargetLibraryInfo *TLI,
315 const TargetTransformInfo *TTI, unsigned VecWidth,
316 unsigned UnrollFactor, SCEVUnionPredicate &Preds)
317 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
318 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
319 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
320 TripCount(nullptr), VectorTripCount(nullptr), Legal(nullptr),
321 AddedSafetyChecks(false), Preds(Preds) {}
323 // Perform the actual loop widening (vectorization).
324 // MinimumBitWidths maps scalar integer values to the smallest bitwidth they
325 // can be validly truncated to. The cost model has assumed this truncation
326 // will happen when vectorizing.
327 void vectorize(LoopVectorizationLegality *L,
328 DenseMap<Instruction*,uint64_t> MinimumBitWidths) {
329 MinBWs = MinimumBitWidths;
331 // Create a new empty loop. Unlink the old loop and connect the new one.
333 // Widen each instruction in the old loop to a new one in the new loop.
334 // Use the Legality module to find the induction and reduction variables.
338 // Return true if any runtime check is added.
339 bool IsSafetyChecksAdded() {
340 return AddedSafetyChecks;
343 virtual ~InnerLoopVectorizer() {}
346 /// A small list of PHINodes.
347 typedef SmallVector<PHINode*, 4> PhiVector;
348 /// When we unroll loops we have multiple vector values for each scalar.
349 /// This data structure holds the unrolled and vectorized values that
350 /// originated from one scalar instruction.
351 typedef SmallVector<Value*, 2> VectorParts;
353 // When we if-convert we need to create edge masks. We have to cache values
354 // so that we don't end up with exponential recursion/IR.
355 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
356 VectorParts> EdgeMaskCache;
358 /// Create an empty loop, based on the loop ranges of the old loop.
359 void createEmptyLoop();
360 /// Create a new induction variable inside L.
361 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
362 Value *Step, Instruction *DL);
363 /// Copy and widen the instructions from the old loop.
364 virtual void vectorizeLoop();
366 /// \brief The Loop exit block may have single value PHI nodes where the
367 /// incoming value is 'Undef'. While vectorizing we only handled real values
368 /// that were defined inside the loop. Here we fix the 'undef case'.
372 /// Shrinks vector element sizes based on information in "MinBWs".
373 void truncateToMinimalBitwidths();
375 /// A helper function that computes the predicate of the block BB, assuming
376 /// that the header block of the loop is set to True. It returns the *entry*
377 /// mask for the block BB.
378 VectorParts createBlockInMask(BasicBlock *BB);
379 /// A helper function that computes the predicate of the edge between SRC
381 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
383 /// A helper function to vectorize a single BB within the innermost loop.
384 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
386 /// Vectorize a single PHINode in a block. This method handles the induction
387 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
388 /// arbitrary length vectors.
389 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
390 unsigned UF, unsigned VF, PhiVector *PV);
392 /// Insert the new loop to the loop hierarchy and pass manager
393 /// and update the analysis passes.
394 void updateAnalysis();
396 /// This instruction is un-vectorizable. Implement it as a sequence
397 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
398 /// scalarized instruction behind an if block predicated on the control
399 /// dependence of the instruction.
400 virtual void scalarizeInstruction(Instruction *Instr,
401 bool IfPredicateStore=false);
403 /// Vectorize Load and Store instructions,
404 virtual void vectorizeMemoryInstruction(Instruction *Instr);
406 /// Create a broadcast instruction. This method generates a broadcast
407 /// instruction (shuffle) for loop invariant values and for the induction
408 /// value. If this is the induction variable then we extend it to N, N+1, ...
409 /// this is needed because each iteration in the loop corresponds to a SIMD
411 virtual Value *getBroadcastInstrs(Value *V);
413 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
414 /// to each vector element of Val. The sequence starts at StartIndex.
415 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
417 /// When we go over instructions in the basic block we rely on previous
418 /// values within the current basic block or on loop invariant values.
419 /// When we widen (vectorize) values we place them in the map. If the values
420 /// are not within the map, they have to be loop invariant, so we simply
421 /// broadcast them into a vector.
422 VectorParts &getVectorValue(Value *V);
424 /// Try to vectorize the interleaved access group that \p Instr belongs to.
425 void vectorizeInterleaveGroup(Instruction *Instr);
427 /// Generate a shuffle sequence that will reverse the vector Vec.
428 virtual Value *reverseVector(Value *Vec);
430 /// Returns (and creates if needed) the original loop trip count.
431 Value *getOrCreateTripCount(Loop *NewLoop);
433 /// Returns (and creates if needed) the trip count of the widened loop.
434 Value *getOrCreateVectorTripCount(Loop *NewLoop);
436 /// Emit a bypass check to see if the trip count would overflow, or we
437 /// wouldn't have enough iterations to execute one vector loop.
438 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
439 /// Emit a bypass check to see if the vector trip count is nonzero.
440 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
441 /// Emit a bypass check to see if all of the SCEV assumptions we've
442 /// had to make are correct.
443 void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
444 /// Emit bypass checks to check any memory assumptions we may have made.
445 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
447 /// This is a helper class that holds the vectorizer state. It maps scalar
448 /// instructions to vector instructions. When the code is 'unrolled' then
449 /// then a single scalar value is mapped to multiple vector parts. The parts
450 /// are stored in the VectorPart type.
452 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
454 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
456 /// \return True if 'Key' is saved in the Value Map.
457 bool has(Value *Key) const { return MapStorage.count(Key); }
459 /// Initializes a new entry in the map. Sets all of the vector parts to the
460 /// save value in 'Val'.
461 /// \return A reference to a vector with splat values.
462 VectorParts &splat(Value *Key, Value *Val) {
463 VectorParts &Entry = MapStorage[Key];
464 Entry.assign(UF, Val);
468 ///\return A reference to the value that is stored at 'Key'.
469 VectorParts &get(Value *Key) {
470 VectorParts &Entry = MapStorage[Key];
473 assert(Entry.size() == UF);
478 /// The unroll factor. Each entry in the map stores this number of vector
482 /// Map storage. We use std::map and not DenseMap because insertions to a
483 /// dense map invalidates its iterators.
484 std::map<Value *, VectorParts> MapStorage;
487 /// The original loop.
489 /// Scev analysis to use.
497 /// Target Library Info.
498 const TargetLibraryInfo *TLI;
499 /// Target Transform Info.
500 const TargetTransformInfo *TTI;
502 /// The vectorization SIMD factor to use. Each vector will have this many
507 /// The vectorization unroll factor to use. Each scalar is vectorized to this
508 /// many different vector instructions.
511 /// The builder that we use
514 // --- Vectorization state ---
516 /// The vector-loop preheader.
517 BasicBlock *LoopVectorPreHeader;
518 /// The scalar-loop preheader.
519 BasicBlock *LoopScalarPreHeader;
520 /// Middle Block between the vector and the scalar.
521 BasicBlock *LoopMiddleBlock;
522 ///The ExitBlock of the scalar loop.
523 BasicBlock *LoopExitBlock;
524 ///The vector loop body.
525 SmallVector<BasicBlock *, 4> LoopVectorBody;
526 ///The scalar loop body.
527 BasicBlock *LoopScalarBody;
528 /// A list of all bypass blocks. The first block is the entry of the loop.
529 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
531 /// The new Induction variable which was added to the new block.
533 /// The induction variable of the old basic block.
534 PHINode *OldInduction;
535 /// Maps scalars to widened vectors.
537 /// Store instructions that should be predicated, as a pair
538 /// <StoreInst, Predicate>
539 SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
540 EdgeMaskCache MaskCache;
541 /// Trip count of the original loop.
543 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
544 Value *VectorTripCount;
546 /// Map of scalar integer values to the smallest bitwidth they can be legally
547 /// represented as. The vector equivalents of these values should be truncated
549 DenseMap<Instruction*,uint64_t> MinBWs;
550 LoopVectorizationLegality *Legal;
552 // Record whether runtime check is added.
553 bool AddedSafetyChecks;
555 /// The SCEV predicate containing all the SCEV-related assumptions.
556 /// The predicate is used to simplify existing expressions in the
557 /// context of existing SCEV assumptions. Since legality checking is
558 /// not done here, we don't need to use this predicate to record
559 /// further assumptions.
560 SCEVUnionPredicate &Preds;
563 class InnerLoopUnroller : public InnerLoopVectorizer {
565 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
566 DominatorTree *DT, const TargetLibraryInfo *TLI,
567 const TargetTransformInfo *TTI, unsigned UnrollFactor,
568 SCEVUnionPredicate &Preds)
569 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor,
573 void scalarizeInstruction(Instruction *Instr,
574 bool IfPredicateStore = false) override;
575 void vectorizeMemoryInstruction(Instruction *Instr) override;
576 Value *getBroadcastInstrs(Value *V) override;
577 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
578 Value *reverseVector(Value *Vec) override;
581 /// \brief Look for a meaningful debug location on the instruction or it's
583 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
588 if (I->getDebugLoc() != Empty)
591 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
592 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
593 if (OpInst->getDebugLoc() != Empty)
600 /// \brief Set the debug location in the builder using the debug location in the
602 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
603 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
604 B.SetCurrentDebugLocation(Inst->getDebugLoc());
606 B.SetCurrentDebugLocation(DebugLoc());
610 /// \return string containing a file name and a line # for the given loop.
611 static std::string getDebugLocString(const Loop *L) {
614 raw_string_ostream OS(Result);
615 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
616 LoopDbgLoc.print(OS);
618 // Just print the module name.
619 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
626 /// \brief Propagate known metadata from one instruction to another.
627 static void propagateMetadata(Instruction *To, const Instruction *From) {
628 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
629 From->getAllMetadataOtherThanDebugLoc(Metadata);
631 for (auto M : Metadata) {
632 unsigned Kind = M.first;
634 // These are safe to transfer (this is safe for TBAA, even when we
635 // if-convert, because should that metadata have had a control dependency
636 // on the condition, and thus actually aliased with some other
637 // non-speculated memory access when the condition was false, this would be
638 // caught by the runtime overlap checks).
639 if (Kind != LLVMContext::MD_tbaa &&
640 Kind != LLVMContext::MD_alias_scope &&
641 Kind != LLVMContext::MD_noalias &&
642 Kind != LLVMContext::MD_fpmath &&
643 Kind != LLVMContext::MD_nontemporal)
646 To->setMetadata(Kind, M.second);
650 /// \brief Propagate known metadata from one instruction to a vector of others.
651 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
653 if (Instruction *I = dyn_cast<Instruction>(V))
654 propagateMetadata(I, From);
657 /// \brief The group of interleaved loads/stores sharing the same stride and
658 /// close to each other.
660 /// Each member in this group has an index starting from 0, and the largest
661 /// index should be less than interleaved factor, which is equal to the absolute
662 /// value of the access's stride.
664 /// E.g. An interleaved load group of factor 4:
665 /// for (unsigned i = 0; i < 1024; i+=4) {
666 /// a = A[i]; // Member of index 0
667 /// b = A[i+1]; // Member of index 1
668 /// d = A[i+3]; // Member of index 3
672 /// An interleaved store group of factor 4:
673 /// for (unsigned i = 0; i < 1024; i+=4) {
675 /// A[i] = a; // Member of index 0
676 /// A[i+1] = b; // Member of index 1
677 /// A[i+2] = c; // Member of index 2
678 /// A[i+3] = d; // Member of index 3
681 /// Note: the interleaved load group could have gaps (missing members), but
682 /// the interleaved store group doesn't allow gaps.
683 class InterleaveGroup {
685 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
686 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
687 assert(Align && "The alignment should be non-zero");
689 Factor = std::abs(Stride);
690 assert(Factor > 1 && "Invalid interleave factor");
692 Reverse = Stride < 0;
696 bool isReverse() const { return Reverse; }
697 unsigned getFactor() const { return Factor; }
698 unsigned getAlignment() const { return Align; }
699 unsigned getNumMembers() const { return Members.size(); }
701 /// \brief Try to insert a new member \p Instr with index \p Index and
702 /// alignment \p NewAlign. The index is related to the leader and it could be
703 /// negative if it is the new leader.
705 /// \returns false if the instruction doesn't belong to the group.
706 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
707 assert(NewAlign && "The new member's alignment should be non-zero");
709 int Key = Index + SmallestKey;
711 // Skip if there is already a member with the same index.
712 if (Members.count(Key))
715 if (Key > LargestKey) {
716 // The largest index is always less than the interleave factor.
717 if (Index >= static_cast<int>(Factor))
721 } else if (Key < SmallestKey) {
722 // The largest index is always less than the interleave factor.
723 if (LargestKey - Key >= static_cast<int>(Factor))
729 // It's always safe to select the minimum alignment.
730 Align = std::min(Align, NewAlign);
731 Members[Key] = Instr;
735 /// \brief Get the member with the given index \p Index
737 /// \returns nullptr if contains no such member.
738 Instruction *getMember(unsigned Index) const {
739 int Key = SmallestKey + Index;
740 if (!Members.count(Key))
743 return Members.find(Key)->second;
746 /// \brief Get the index for the given member. Unlike the key in the member
747 /// map, the index starts from 0.
748 unsigned getIndex(Instruction *Instr) const {
749 for (auto I : Members)
750 if (I.second == Instr)
751 return I.first - SmallestKey;
753 llvm_unreachable("InterleaveGroup contains no such member");
756 Instruction *getInsertPos() const { return InsertPos; }
757 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
760 unsigned Factor; // Interleave Factor.
763 DenseMap<int, Instruction *> Members;
767 // To avoid breaking dependences, vectorized instructions of an interleave
768 // group should be inserted at either the first load or the last store in
771 // E.g. %even = load i32 // Insert Position
772 // %add = add i32 %even // Use of %even
776 // %odd = add i32 // Def of %odd
777 // store i32 %odd // Insert Position
778 Instruction *InsertPos;
781 /// \brief Drive the analysis of interleaved memory accesses in the loop.
783 /// Use this class to analyze interleaved accesses only when we can vectorize
784 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
785 /// on interleaved accesses is unsafe.
787 /// The analysis collects interleave groups and records the relationships
788 /// between the member and the group in a map.
789 class InterleavedAccessInfo {
791 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT,
792 SCEVUnionPredicate &Preds)
793 : SE(SE), TheLoop(L), DT(DT), Preds(Preds) {}
795 ~InterleavedAccessInfo() {
796 SmallSet<InterleaveGroup *, 4> DelSet;
797 // Avoid releasing a pointer twice.
798 for (auto &I : InterleaveGroupMap)
799 DelSet.insert(I.second);
800 for (auto *Ptr : DelSet)
804 /// \brief Analyze the interleaved accesses and collect them in interleave
805 /// groups. Substitute symbolic strides using \p Strides.
806 void analyzeInterleaving(const ValueToValueMap &Strides);
808 /// \brief Check if \p Instr belongs to any interleave group.
809 bool isInterleaved(Instruction *Instr) const {
810 return InterleaveGroupMap.count(Instr);
813 /// \brief Get the interleave group that \p Instr belongs to.
815 /// \returns nullptr if doesn't have such group.
816 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
817 if (InterleaveGroupMap.count(Instr))
818 return InterleaveGroupMap.find(Instr)->second;
827 /// The SCEV predicate containing all the SCEV-related assumptions.
828 /// The predicate is used to simplify SCEV expressions in the
829 /// context of existing SCEV assumptions. The interleaved access
830 /// analysis can also add new predicates (for example by versioning
831 /// strides of pointers).
832 SCEVUnionPredicate &Preds;
834 /// Holds the relationships between the members and the interleave group.
835 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
837 /// \brief The descriptor for a strided memory access.
838 struct StrideDescriptor {
839 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
841 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
843 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
845 int Stride; // The access's stride. It is negative for a reverse access.
846 const SCEV *Scev; // The scalar expression of this access
847 unsigned Size; // The size of the memory object.
848 unsigned Align; // The alignment of this access.
851 /// \brief Create a new interleave group with the given instruction \p Instr,
852 /// stride \p Stride and alignment \p Align.
854 /// \returns the newly created interleave group.
855 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
857 assert(!InterleaveGroupMap.count(Instr) &&
858 "Already in an interleaved access group");
859 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
860 return InterleaveGroupMap[Instr];
863 /// \brief Release the group and remove all the relationships.
864 void releaseGroup(InterleaveGroup *Group) {
865 for (unsigned i = 0; i < Group->getFactor(); i++)
866 if (Instruction *Member = Group->getMember(i))
867 InterleaveGroupMap.erase(Member);
872 /// \brief Collect all the accesses with a constant stride in program order.
873 void collectConstStridedAccesses(
874 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
875 const ValueToValueMap &Strides);
878 /// Utility class for getting and setting loop vectorizer hints in the form
879 /// of loop metadata.
880 /// This class keeps a number of loop annotations locally (as member variables)
881 /// and can, upon request, write them back as metadata on the loop. It will
882 /// initially scan the loop for existing metadata, and will update the local
883 /// values based on information in the loop.
884 /// We cannot write all values to metadata, as the mere presence of some info,
885 /// for example 'force', means a decision has been made. So, we need to be
886 /// careful NOT to add them if the user hasn't specifically asked so.
887 class LoopVectorizeHints {
894 /// Hint - associates name and validation with the hint value.
897 unsigned Value; // This may have to change for non-numeric values.
900 Hint(const char * Name, unsigned Value, HintKind Kind)
901 : Name(Name), Value(Value), Kind(Kind) { }
903 bool validate(unsigned Val) {
906 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
908 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
916 /// Vectorization width.
918 /// Vectorization interleave factor.
920 /// Vectorization forced
923 /// Return the loop metadata prefix.
924 static StringRef Prefix() { return "llvm.loop."; }
928 FK_Undefined = -1, ///< Not selected.
929 FK_Disabled = 0, ///< Forcing disabled.
930 FK_Enabled = 1, ///< Forcing enabled.
933 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
934 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
936 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
937 Force("vectorize.enable", FK_Undefined, HK_FORCE),
939 // Populate values with existing loop metadata.
940 getHintsFromMetadata();
942 // force-vector-interleave overrides DisableInterleaving.
943 if (VectorizerParams::isInterleaveForced())
944 Interleave.Value = VectorizerParams::VectorizationInterleave;
946 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
947 << "LV: Interleaving disabled by the pass manager\n");
950 /// Mark the loop L as already vectorized by setting the width to 1.
951 void setAlreadyVectorized() {
952 Width.Value = Interleave.Value = 1;
953 Hint Hints[] = {Width, Interleave};
954 writeHintsToMetadata(Hints);
957 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
958 if (getForce() == LoopVectorizeHints::FK_Disabled) {
959 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
960 emitOptimizationRemarkAnalysis(F->getContext(),
961 vectorizeAnalysisPassName(), *F,
962 L->getStartLoc(), emitRemark());
966 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
967 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
968 emitOptimizationRemarkAnalysis(F->getContext(),
969 vectorizeAnalysisPassName(), *F,
970 L->getStartLoc(), emitRemark());
974 if (getWidth() == 1 && getInterleave() == 1) {
975 // FIXME: Add a separate metadata to indicate when the loop has already
976 // been vectorized instead of setting width and count to 1.
977 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
978 // FIXME: Add interleave.disable metadata. This will allow
979 // vectorize.disable to be used without disabling the pass and errors
980 // to differentiate between disabled vectorization and a width of 1.
981 emitOptimizationRemarkAnalysis(
982 F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
983 "loop not vectorized: vectorization and interleaving are explicitly "
984 "disabled, or vectorize width and interleave count are both set to "
992 /// Dumps all the hint information.
993 std::string emitRemark() const {
994 VectorizationReport R;
995 if (Force.Value == LoopVectorizeHints::FK_Disabled)
996 R << "vectorization is explicitly disabled";
998 R << "use -Rpass-analysis=loop-vectorize for more info";
999 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1000 R << " (Force=true";
1001 if (Width.Value != 0)
1002 R << ", Vector Width=" << Width.Value;
1003 if (Interleave.Value != 0)
1004 R << ", Interleave Count=" << Interleave.Value;
1012 unsigned getWidth() const { return Width.Value; }
1013 unsigned getInterleave() const { return Interleave.Value; }
1014 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1015 const char *vectorizeAnalysisPassName() const {
1016 // If hints are provided that don't disable vectorization use the
1017 // AlwaysPrint pass name to force the frontend to print the diagnostic.
1018 if (getWidth() == 1)
1020 if (getForce() == LoopVectorizeHints::FK_Disabled)
1022 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1024 return DiagnosticInfo::AlwaysPrint;
1027 bool allowReordering() const {
1028 // When enabling loop hints are provided we allow the vectorizer to change
1029 // the order of operations that is given by the scalar loop. This is not
1030 // enabled by default because can be unsafe or inefficient. For example,
1031 // reordering floating-point operations will change the way round-off
1032 // error accumulates in the loop.
1033 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1037 /// Find hints specified in the loop metadata and update local values.
1038 void getHintsFromMetadata() {
1039 MDNode *LoopID = TheLoop->getLoopID();
1043 // First operand should refer to the loop id itself.
1044 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1045 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1047 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1048 const MDString *S = nullptr;
1049 SmallVector<Metadata *, 4> Args;
1051 // The expected hint is either a MDString or a MDNode with the first
1052 // operand a MDString.
1053 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1054 if (!MD || MD->getNumOperands() == 0)
1056 S = dyn_cast<MDString>(MD->getOperand(0));
1057 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1058 Args.push_back(MD->getOperand(i));
1060 S = dyn_cast<MDString>(LoopID->getOperand(i));
1061 assert(Args.size() == 0 && "too many arguments for MDString");
1067 // Check if the hint starts with the loop metadata prefix.
1068 StringRef Name = S->getString();
1069 if (Args.size() == 1)
1070 setHint(Name, Args[0]);
1074 /// Checks string hint with one operand and set value if valid.
1075 void setHint(StringRef Name, Metadata *Arg) {
1076 if (!Name.startswith(Prefix()))
1078 Name = Name.substr(Prefix().size(), StringRef::npos);
1080 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1082 unsigned Val = C->getZExtValue();
1084 Hint *Hints[] = {&Width, &Interleave, &Force};
1085 for (auto H : Hints) {
1086 if (Name == H->Name) {
1087 if (H->validate(Val))
1090 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1096 /// Create a new hint from name / value pair.
1097 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1098 LLVMContext &Context = TheLoop->getHeader()->getContext();
1099 Metadata *MDs[] = {MDString::get(Context, Name),
1100 ConstantAsMetadata::get(
1101 ConstantInt::get(Type::getInt32Ty(Context), V))};
1102 return MDNode::get(Context, MDs);
1105 /// Matches metadata with hint name.
1106 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1107 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1111 for (auto H : HintTypes)
1112 if (Name->getString().endswith(H.Name))
1117 /// Sets current hints into loop metadata, keeping other values intact.
1118 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1119 if (HintTypes.size() == 0)
1122 // Reserve the first element to LoopID (see below).
1123 SmallVector<Metadata *, 4> MDs(1);
1124 // If the loop already has metadata, then ignore the existing operands.
1125 MDNode *LoopID = TheLoop->getLoopID();
1127 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1128 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1129 // If node in update list, ignore old value.
1130 if (!matchesHintMetadataName(Node, HintTypes))
1131 MDs.push_back(Node);
1135 // Now, add the missing hints.
1136 for (auto H : HintTypes)
1137 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1139 // Replace current metadata node with new one.
1140 LLVMContext &Context = TheLoop->getHeader()->getContext();
1141 MDNode *NewLoopID = MDNode::get(Context, MDs);
1142 // Set operand 0 to refer to the loop id itself.
1143 NewLoopID->replaceOperandWith(0, NewLoopID);
1145 TheLoop->setLoopID(NewLoopID);
1148 /// The loop these hints belong to.
1149 const Loop *TheLoop;
1152 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1153 const LoopVectorizeHints &Hints,
1154 const LoopAccessReport &Message) {
1155 const char *Name = Hints.vectorizeAnalysisPassName();
1156 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1159 static void emitMissedWarning(Function *F, Loop *L,
1160 const LoopVectorizeHints &LH) {
1161 emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1164 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1165 if (LH.getWidth() != 1)
1166 emitLoopVectorizeWarning(
1167 F->getContext(), *F, L->getStartLoc(),
1168 "failed explicitly specified loop vectorization");
1169 else if (LH.getInterleave() != 1)
1170 emitLoopInterleaveWarning(
1171 F->getContext(), *F, L->getStartLoc(),
1172 "failed explicitly specified loop interleaving");
1176 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1177 /// to what vectorization factor.
1178 /// This class does not look at the profitability of vectorization, only the
1179 /// legality. This class has two main kinds of checks:
1180 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1181 /// will change the order of memory accesses in a way that will change the
1182 /// correctness of the program.
1183 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1184 /// checks for a number of different conditions, such as the availability of a
1185 /// single induction variable, that all types are supported and vectorize-able,
1186 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1187 /// This class is also used by InnerLoopVectorizer for identifying
1188 /// induction variable and the different reduction variables.
1189 class LoopVectorizationLegality {
1191 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1192 TargetLibraryInfo *TLI, AliasAnalysis *AA,
1193 Function *F, const TargetTransformInfo *TTI,
1194 LoopAccessAnalysis *LAA,
1195 LoopVectorizationRequirements *R,
1196 const LoopVectorizeHints *H,
1197 SCEVUnionPredicate &Preds)
1198 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
1199 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr),
1200 InterleaveInfo(SE, L, DT, Preds), Induction(nullptr),
1201 WidestIndTy(nullptr), HasFunNoNaNAttr(false), Requirements(R), Hints(H),
1204 /// ReductionList contains the reduction descriptors for all
1205 /// of the reductions that were found in the loop.
1206 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1208 /// InductionList saves induction variables and maps them to the
1209 /// induction descriptor.
1210 typedef MapVector<PHINode*, InductionDescriptor> InductionList;
1212 /// Returns true if it is legal to vectorize this loop.
1213 /// This does not mean that it is profitable to vectorize this
1214 /// loop, only that it is legal to do so.
1215 bool canVectorize();
1217 /// Returns the Induction variable.
1218 PHINode *getInduction() { return Induction; }
1220 /// Returns the reduction variables found in the loop.
1221 ReductionList *getReductionVars() { return &Reductions; }
1223 /// Returns the induction variables found in the loop.
1224 InductionList *getInductionVars() { return &Inductions; }
1226 /// Returns the widest induction type.
1227 Type *getWidestInductionType() { return WidestIndTy; }
1229 /// Returns True if V is an induction variable in this loop.
1230 bool isInductionVariable(const Value *V);
1232 /// Return true if the block BB needs to be predicated in order for the loop
1233 /// to be vectorized.
1234 bool blockNeedsPredication(BasicBlock *BB);
1236 /// Check if this pointer is consecutive when vectorizing. This happens
1237 /// when the last index of the GEP is the induction variable, or that the
1238 /// pointer itself is an induction variable.
1239 /// This check allows us to vectorize A[idx] into a wide load/store.
1241 /// 0 - Stride is unknown or non-consecutive.
1242 /// 1 - Address is consecutive.
1243 /// -1 - Address is consecutive, and decreasing.
1244 int isConsecutivePtr(Value *Ptr);
1246 /// Returns true if the value V is uniform within the loop.
1247 bool isUniform(Value *V);
1249 /// Returns true if this instruction will remain scalar after vectorization.
1250 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
1252 /// Returns the information that we collected about runtime memory check.
1253 const RuntimePointerChecking *getRuntimePointerChecking() const {
1254 return LAI->getRuntimePointerChecking();
1257 const LoopAccessInfo *getLAI() const {
1261 /// \brief Check if \p Instr belongs to any interleaved access group.
1262 bool isAccessInterleaved(Instruction *Instr) {
1263 return InterleaveInfo.isInterleaved(Instr);
1266 /// \brief Get the interleaved access group that \p Instr belongs to.
1267 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1268 return InterleaveInfo.getInterleaveGroup(Instr);
1271 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1273 bool hasStride(Value *V) { return StrideSet.count(V); }
1274 bool mustCheckStrides() { return !StrideSet.empty(); }
1275 SmallPtrSet<Value *, 8>::iterator strides_begin() {
1276 return StrideSet.begin();
1278 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
1280 /// Returns true if the target machine supports masked store operation
1281 /// for the given \p DataType and kind of access to \p Ptr.
1282 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1283 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1285 /// Returns true if the target machine supports masked load operation
1286 /// for the given \p DataType and kind of access to \p Ptr.
1287 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1288 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1290 /// Returns true if vector representation of the instruction \p I
1292 bool isMaskRequired(const Instruction* I) {
1293 return (MaskedOp.count(I) != 0);
1295 unsigned getNumStores() const {
1296 return LAI->getNumStores();
1298 unsigned getNumLoads() const {
1299 return LAI->getNumLoads();
1301 unsigned getNumPredStores() const {
1302 return NumPredStores;
1305 /// Check if a single basic block loop is vectorizable.
1306 /// At this point we know that this is a loop with a constant trip count
1307 /// and we only need to check individual instructions.
1308 bool canVectorizeInstrs();
1310 /// When we vectorize loops we may change the order in which
1311 /// we read and write from memory. This method checks if it is
1312 /// legal to vectorize the code, considering only memory constrains.
1313 /// Returns true if the loop is vectorizable
1314 bool canVectorizeMemory();
1316 /// Return true if we can vectorize this loop using the IF-conversion
1318 bool canVectorizeWithIfConvert();
1320 /// Collect the variables that need to stay uniform after vectorization.
1321 void collectLoopUniforms();
1323 /// Return true if all of the instructions in the block can be speculatively
1324 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1325 /// and we know that we can read from them without segfault.
1326 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1328 /// \brief Collect memory access with loop invariant strides.
1330 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1332 void collectStridedAccess(Value *LoadOrStoreInst);
1334 /// Report an analysis message to assist the user in diagnosing loops that are
1335 /// not vectorized. These are handled as LoopAccessReport rather than
1336 /// VectorizationReport because the << operator of VectorizationReport returns
1337 /// LoopAccessReport.
1338 void emitAnalysis(const LoopAccessReport &Message) const {
1339 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1342 unsigned NumPredStores;
1344 /// The loop that we evaluate.
1347 ScalarEvolution *SE;
1348 /// Target Library Info.
1349 TargetLibraryInfo *TLI;
1351 Function *TheFunction;
1352 /// Target Transform Info
1353 const TargetTransformInfo *TTI;
1356 // LoopAccess analysis.
1357 LoopAccessAnalysis *LAA;
1358 // And the loop-accesses info corresponding to this loop. This pointer is
1359 // null until canVectorizeMemory sets it up.
1360 const LoopAccessInfo *LAI;
1362 /// The interleave access information contains groups of interleaved accesses
1363 /// with the same stride and close to each other.
1364 InterleavedAccessInfo InterleaveInfo;
1366 // --- vectorization state --- //
1368 /// Holds the integer induction variable. This is the counter of the
1371 /// Holds the reduction variables.
1372 ReductionList Reductions;
1373 /// Holds all of the induction variables that we found in the loop.
1374 /// Notice that inductions don't need to start at zero and that induction
1375 /// variables can be pointers.
1376 InductionList Inductions;
1377 /// Holds the widest induction type encountered.
1380 /// Allowed outside users. This holds the reduction
1381 /// vars which can be accessed from outside the loop.
1382 SmallPtrSet<Value*, 4> AllowedExit;
1383 /// This set holds the variables which are known to be uniform after
1385 SmallPtrSet<Instruction*, 4> Uniforms;
1387 /// Can we assume the absence of NaNs.
1388 bool HasFunNoNaNAttr;
1390 /// Vectorization requirements that will go through late-evaluation.
1391 LoopVectorizationRequirements *Requirements;
1393 /// Used to emit an analysis of any legality issues.
1394 const LoopVectorizeHints *Hints;
1396 ValueToValueMap Strides;
1397 SmallPtrSet<Value *, 8> StrideSet;
1399 /// While vectorizing these instructions we have to generate a
1400 /// call to the appropriate masked intrinsic
1401 SmallPtrSet<const Instruction *, 8> MaskedOp;
1403 /// The SCEV predicate containing all the SCEV-related assumptions.
1404 /// The predicate is used to simplify SCEV expressions in the
1405 /// context of existing SCEV assumptions. The analysis will also
1406 /// add a minimal set of new predicates if this is required to
1407 /// enable vectorization/unrolling.
1408 SCEVUnionPredicate &Preds;
1411 /// LoopVectorizationCostModel - estimates the expected speedups due to
1413 /// In many cases vectorization is not profitable. This can happen because of
1414 /// a number of reasons. In this class we mainly attempt to predict the
1415 /// expected speedup/slowdowns due to the supported instruction set. We use the
1416 /// TargetTransformInfo to query the different backends for the cost of
1417 /// different operations.
1418 class LoopVectorizationCostModel {
1420 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1421 LoopVectorizationLegality *Legal,
1422 const TargetTransformInfo &TTI,
1423 const TargetLibraryInfo *TLI, DemandedBits *DB,
1424 AssumptionCache *AC, const Function *F,
1425 const LoopVectorizeHints *Hints,
1426 SmallPtrSetImpl<const Value *> &ValuesToIgnore,
1427 SCEVUnionPredicate &Preds)
1428 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1429 TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
1431 /// Information about vectorization costs
1432 struct VectorizationFactor {
1433 unsigned Width; // Vector width with best cost
1434 unsigned Cost; // Cost of the loop with that width
1436 /// \return The most profitable vectorization factor and the cost of that VF.
1437 /// This method checks every power of two up to VF. If UserVF is not ZERO
1438 /// then this vectorization factor will be selected if vectorization is
1440 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1442 /// \return The size (in bits) of the smallest and widest types in the code
1443 /// that needs to be vectorized. We ignore values that remain scalar such as
1444 /// 64 bit loop indices.
1445 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1447 /// \return The desired interleave count.
1448 /// If interleave count has been specified by metadata it will be returned.
1449 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1450 /// are the selected vectorization factor and the cost of the selected VF.
1451 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1454 /// \return The most profitable unroll factor.
1455 /// This method finds the best unroll-factor based on register pressure and
1456 /// other parameters. VF and LoopCost are the selected vectorization factor
1457 /// and the cost of the selected VF.
1458 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1461 /// \brief A struct that represents some properties of the register usage
1463 struct RegisterUsage {
1464 /// Holds the number of loop invariant values that are used in the loop.
1465 unsigned LoopInvariantRegs;
1466 /// Holds the maximum number of concurrent live intervals in the loop.
1467 unsigned MaxLocalUsers;
1468 /// Holds the number of instructions in the loop.
1469 unsigned NumInstructions;
1472 /// \return Returns information about the register usages of the loop for the
1473 /// given vectorization factors.
1474 SmallVector<RegisterUsage, 8>
1475 calculateRegisterUsage(const SmallVector<unsigned, 8> &VFs);
1478 /// Returns the expected execution cost. The unit of the cost does
1479 /// not matter because we use the 'cost' units to compare different
1480 /// vector widths. The cost that is returned is *not* normalized by
1481 /// the factor width.
1482 unsigned expectedCost(unsigned VF);
1484 /// Returns the execution time cost of an instruction for a given vector
1485 /// width. Vector width of one means scalar.
1486 unsigned getInstructionCost(Instruction *I, unsigned VF);
1488 /// Returns whether the instruction is a load or store and will be a emitted
1489 /// as a vector operation.
1490 bool isConsecutiveLoadOrStore(Instruction *I);
1492 /// Report an analysis message to assist the user in diagnosing loops that are
1493 /// not vectorized. These are handled as LoopAccessReport rather than
1494 /// VectorizationReport because the << operator of VectorizationReport returns
1495 /// LoopAccessReport.
1496 void emitAnalysis(const LoopAccessReport &Message) const {
1497 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1501 /// Map of scalar integer values to the smallest bitwidth they can be legally
1502 /// represented as. The vector equivalents of these values should be truncated
1504 DenseMap<Instruction*,uint64_t> MinBWs;
1506 /// The loop that we evaluate.
1509 ScalarEvolution *SE;
1510 /// Loop Info analysis.
1512 /// Vectorization legality.
1513 LoopVectorizationLegality *Legal;
1514 /// Vector target information.
1515 const TargetTransformInfo &TTI;
1516 /// Target Library Info.
1517 const TargetLibraryInfo *TLI;
1518 /// Demanded bits analysis
1520 const Function *TheFunction;
1521 // Loop Vectorize Hint.
1522 const LoopVectorizeHints *Hints;
1523 // Values to ignore in the cost model.
1524 const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
1527 /// \brief This holds vectorization requirements that must be verified late in
1528 /// the process. The requirements are set by legalize and costmodel. Once
1529 /// vectorization has been determined to be possible and profitable the
1530 /// requirements can be verified by looking for metadata or compiler options.
1531 /// For example, some loops require FP commutativity which is only allowed if
1532 /// vectorization is explicitly specified or if the fast-math compiler option
1533 /// has been provided.
1534 /// Late evaluation of these requirements allows helpful diagnostics to be
1535 /// composed that tells the user what need to be done to vectorize the loop. For
1536 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1537 /// evaluation should be used only when diagnostics can generated that can be
1538 /// followed by a non-expert user.
1539 class LoopVectorizationRequirements {
1541 LoopVectorizationRequirements()
1542 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1544 void addUnsafeAlgebraInst(Instruction *I) {
1545 // First unsafe algebra instruction.
1546 if (!UnsafeAlgebraInst)
1547 UnsafeAlgebraInst = I;
1550 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1552 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1553 const char *Name = Hints.vectorizeAnalysisPassName();
1554 bool Failed = false;
1555 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1556 emitOptimizationRemarkAnalysisFPCommute(
1557 F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1558 VectorizationReport() << "cannot prove it is safe to reorder "
1559 "floating-point operations");
1563 // Test if runtime memcheck thresholds are exceeded.
1564 bool PragmaThresholdReached =
1565 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1566 bool ThresholdReached =
1567 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1568 if ((ThresholdReached && !Hints.allowReordering()) ||
1569 PragmaThresholdReached) {
1570 emitOptimizationRemarkAnalysisAliasing(
1571 F->getContext(), Name, *F, L->getStartLoc(),
1572 VectorizationReport()
1573 << "cannot prove it is safe to reorder memory operations");
1574 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1582 unsigned NumRuntimePointerChecks;
1583 Instruction *UnsafeAlgebraInst;
1586 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1588 return V.push_back(&L);
1590 for (Loop *InnerL : L)
1591 addInnerLoop(*InnerL, V);
1594 /// The LoopVectorize Pass.
1595 struct LoopVectorize : public FunctionPass {
1596 /// Pass identification, replacement for typeid
1599 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1601 DisableUnrolling(NoUnrolling),
1602 AlwaysVectorize(AlwaysVectorize) {
1603 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1606 ScalarEvolution *SE;
1608 TargetTransformInfo *TTI;
1610 BlockFrequencyInfo *BFI;
1611 TargetLibraryInfo *TLI;
1614 AssumptionCache *AC;
1615 LoopAccessAnalysis *LAA;
1616 bool DisableUnrolling;
1617 bool AlwaysVectorize;
1619 BlockFrequency ColdEntryFreq;
1621 bool runOnFunction(Function &F) override {
1622 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1623 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1624 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1625 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1626 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1627 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1628 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1629 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1630 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1631 LAA = &getAnalysis<LoopAccessAnalysis>();
1632 DB = &getAnalysis<DemandedBits>();
1634 // Compute some weights outside of the loop over the loops. Compute this
1635 // using a BranchProbability to re-use its scaling math.
1636 const BranchProbability ColdProb(1, 5); // 20%
1637 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1640 // 1. the target claims to have no vector registers, and
1641 // 2. interleaving won't help ILP.
1643 // The second condition is necessary because, even if the target has no
1644 // vector registers, loop vectorization may still enable scalar
1646 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1649 // Build up a worklist of inner-loops to vectorize. This is necessary as
1650 // the act of vectorizing or partially unrolling a loop creates new loops
1651 // and can invalidate iterators across the loops.
1652 SmallVector<Loop *, 8> Worklist;
1655 addInnerLoop(*L, Worklist);
1657 LoopsAnalyzed += Worklist.size();
1659 // Now walk the identified inner loops.
1660 bool Changed = false;
1661 while (!Worklist.empty())
1662 Changed |= processLoop(Worklist.pop_back_val());
1664 // Process each loop nest in the function.
1668 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1669 SmallVector<Metadata *, 4> MDs;
1670 // Reserve first location for self reference to the LoopID metadata node.
1671 MDs.push_back(nullptr);
1672 bool IsUnrollMetadata = false;
1673 MDNode *LoopID = L->getLoopID();
1675 // First find existing loop unrolling disable metadata.
1676 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1677 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1679 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1681 S && S->getString().startswith("llvm.loop.unroll.disable");
1683 MDs.push_back(LoopID->getOperand(i));
1687 if (!IsUnrollMetadata) {
1688 // Add runtime unroll disable metadata.
1689 LLVMContext &Context = L->getHeader()->getContext();
1690 SmallVector<Metadata *, 1> DisableOperands;
1691 DisableOperands.push_back(
1692 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1693 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1694 MDs.push_back(DisableNode);
1695 MDNode *NewLoopID = MDNode::get(Context, MDs);
1696 // Set operand 0 to refer to the loop id itself.
1697 NewLoopID->replaceOperandWith(0, NewLoopID);
1698 L->setLoopID(NewLoopID);
1702 bool processLoop(Loop *L) {
1703 assert(L->empty() && "Only process inner loops.");
1706 const std::string DebugLocStr = getDebugLocString(L);
1709 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1710 << L->getHeader()->getParent()->getName() << "\" from "
1711 << DebugLocStr << "\n");
1713 LoopVectorizeHints Hints(L, DisableUnrolling);
1715 DEBUG(dbgs() << "LV: Loop hints:"
1717 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1719 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1721 : "?")) << " width=" << Hints.getWidth()
1722 << " unroll=" << Hints.getInterleave() << "\n");
1724 // Function containing loop
1725 Function *F = L->getHeader()->getParent();
1727 // Looking at the diagnostic output is the only way to determine if a loop
1728 // was vectorized (other than looking at the IR or machine code), so it
1729 // is important to generate an optimization remark for each loop. Most of
1730 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1731 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1732 // less verbose reporting vectorized loops and unvectorized loops that may
1733 // benefit from vectorization, respectively.
1735 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1736 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1740 // Check the loop for a trip count threshold:
1741 // do not vectorize loops with a tiny trip count.
1742 const unsigned TC = SE->getSmallConstantTripCount(L);
1743 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1744 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1745 << "This loop is not worth vectorizing.");
1746 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1747 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1749 DEBUG(dbgs() << "\n");
1750 emitAnalysisDiag(F, L, Hints, VectorizationReport()
1751 << "vectorization is not beneficial "
1752 "and is not explicitly forced");
1757 SCEVUnionPredicate Preds;
1759 // Check if it is legal to vectorize the loop.
1760 LoopVectorizationRequirements Requirements;
1761 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1762 &Requirements, &Hints, Preds);
1763 if (!LVL.canVectorize()) {
1764 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1765 emitMissedWarning(F, L, Hints);
1769 // Collect values we want to ignore in the cost model. This includes
1770 // type-promoting instructions we identified during reduction detection.
1771 SmallPtrSet<const Value *, 32> ValuesToIgnore;
1772 CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
1773 for (auto &Reduction : *LVL.getReductionVars()) {
1774 RecurrenceDescriptor &RedDes = Reduction.second;
1775 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
1776 ValuesToIgnore.insert(Casts.begin(), Casts.end());
1779 // Use the cost model.
1780 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, DB, AC, F, &Hints,
1781 ValuesToIgnore, Preds);
1783 // Check the function attributes to find out if this function should be
1784 // optimized for size.
1785 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1788 // Compute the weighted frequency of this loop being executed and see if it
1789 // is less than 20% of the function entry baseline frequency. Note that we
1790 // always have a canonical loop here because we think we *can* vectorize.
1791 // FIXME: This is hidden behind a flag due to pervasive problems with
1792 // exactly what block frequency models.
1793 if (LoopVectorizeWithBlockFrequency) {
1794 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1795 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1796 LoopEntryFreq < ColdEntryFreq)
1800 // Check the function attributes to see if implicit floats are allowed.
1801 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1802 // an integer loop and the vector instructions selected are purely integer
1803 // vector instructions?
1804 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1805 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1806 "attribute is used.\n");
1809 VectorizationReport()
1810 << "loop not vectorized due to NoImplicitFloat attribute");
1811 emitMissedWarning(F, L, Hints);
1815 // Select the optimal vectorization factor.
1816 const LoopVectorizationCostModel::VectorizationFactor VF =
1817 CM.selectVectorizationFactor(OptForSize);
1819 // Select the interleave count.
1820 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1822 // Get user interleave count.
1823 unsigned UserIC = Hints.getInterleave();
1825 // Identify the diagnostic messages that should be produced.
1826 std::string VecDiagMsg, IntDiagMsg;
1827 bool VectorizeLoop = true, InterleaveLoop = true;
1829 if (Requirements.doesNotMeet(F, L, Hints)) {
1830 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1832 emitMissedWarning(F, L, Hints);
1836 if (VF.Width == 1) {
1837 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1839 "the cost-model indicates that vectorization is not beneficial";
1840 VectorizeLoop = false;
1843 if (IC == 1 && UserIC <= 1) {
1844 // Tell the user interleaving is not beneficial.
1845 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1847 "the cost-model indicates that interleaving is not beneficial";
1848 InterleaveLoop = false;
1851 " and is explicitly disabled or interleave count is set to 1";
1852 } else if (IC > 1 && UserIC == 1) {
1853 // Tell the user interleaving is beneficial, but it explicitly disabled.
1855 << "LV: Interleaving is beneficial but is explicitly disabled.");
1856 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1857 "but is explicitly disabled or interleave count is set to 1";
1858 InterleaveLoop = false;
1861 // Override IC if user provided an interleave count.
1862 IC = UserIC > 0 ? UserIC : IC;
1864 // Emit diagnostic messages, if any.
1865 const char *VAPassName = Hints.vectorizeAnalysisPassName();
1866 if (!VectorizeLoop && !InterleaveLoop) {
1867 // Do not vectorize or interleaving the loop.
1868 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1869 L->getStartLoc(), VecDiagMsg);
1870 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1871 L->getStartLoc(), IntDiagMsg);
1873 } else if (!VectorizeLoop && InterleaveLoop) {
1874 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1875 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1876 L->getStartLoc(), VecDiagMsg);
1877 } else if (VectorizeLoop && !InterleaveLoop) {
1878 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1879 << DebugLocStr << '\n');
1880 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1881 L->getStartLoc(), IntDiagMsg);
1882 } else if (VectorizeLoop && InterleaveLoop) {
1883 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1884 << DebugLocStr << '\n');
1885 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1888 if (!VectorizeLoop) {
1889 assert(IC > 1 && "interleave count should not be 1 or 0");
1890 // If we decided that it is not legal to vectorize the loop then
1892 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC, Preds);
1893 Unroller.vectorize(&LVL, CM.MinBWs);
1895 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1896 Twine("interleaved loop (interleaved count: ") +
1899 // If we decided that it is *legal* to vectorize the loop then do it.
1900 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC, Preds);
1901 LB.vectorize(&LVL, CM.MinBWs);
1904 // Add metadata to disable runtime unrolling scalar loop when there's no
1905 // runtime check about strides and memory. Because at this situation,
1906 // scalar loop is rarely used not worthy to be unrolled.
1907 if (!LB.IsSafetyChecksAdded())
1908 AddRuntimeUnrollDisableMetaData(L);
1910 // Report the vectorization decision.
1911 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1912 Twine("vectorized loop (vectorization width: ") +
1913 Twine(VF.Width) + ", interleaved count: " +
1917 // Mark the loop as already vectorized to avoid vectorizing again.
1918 Hints.setAlreadyVectorized();
1920 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1924 void getAnalysisUsage(AnalysisUsage &AU) const override {
1925 AU.addRequired<AssumptionCacheTracker>();
1926 AU.addRequiredID(LoopSimplifyID);
1927 AU.addRequiredID(LCSSAID);
1928 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1929 AU.addRequired<DominatorTreeWrapperPass>();
1930 AU.addRequired<LoopInfoWrapperPass>();
1931 AU.addRequired<ScalarEvolutionWrapperPass>();
1932 AU.addRequired<TargetTransformInfoWrapperPass>();
1933 AU.addRequired<AAResultsWrapperPass>();
1934 AU.addRequired<LoopAccessAnalysis>();
1935 AU.addRequired<DemandedBits>();
1936 AU.addPreserved<LoopInfoWrapperPass>();
1937 AU.addPreserved<DominatorTreeWrapperPass>();
1938 AU.addPreserved<BasicAAWrapperPass>();
1939 AU.addPreserved<AAResultsWrapperPass>();
1940 AU.addPreserved<GlobalsAAWrapperPass>();
1945 } // end anonymous namespace
1947 //===----------------------------------------------------------------------===//
1948 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1949 // LoopVectorizationCostModel.
1950 //===----------------------------------------------------------------------===//
1952 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1953 // We need to place the broadcast of invariant variables outside the loop.
1954 Instruction *Instr = dyn_cast<Instruction>(V);
1956 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1957 Instr->getParent()) != LoopVectorBody.end());
1958 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1960 // Place the code for broadcasting invariant variables in the new preheader.
1961 IRBuilder<>::InsertPointGuard Guard(Builder);
1963 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1965 // Broadcast the scalar into all locations in the vector.
1966 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1971 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1973 assert(Val->getType()->isVectorTy() && "Must be a vector");
1974 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1975 "Elem must be an integer");
1976 assert(Step->getType() == Val->getType()->getScalarType() &&
1977 "Step has wrong type");
1978 // Create the types.
1979 Type *ITy = Val->getType()->getScalarType();
1980 VectorType *Ty = cast<VectorType>(Val->getType());
1981 int VLen = Ty->getNumElements();
1982 SmallVector<Constant*, 8> Indices;
1984 // Create a vector of consecutive numbers from zero to VF.
1985 for (int i = 0; i < VLen; ++i)
1986 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1988 // Add the consecutive indices to the vector value.
1989 Constant *Cv = ConstantVector::get(Indices);
1990 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1991 Step = Builder.CreateVectorSplat(VLen, Step);
1992 assert(Step->getType() == Val->getType() && "Invalid step vec");
1993 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1994 // which can be found from the original scalar operations.
1995 Step = Builder.CreateMul(Cv, Step);
1996 return Builder.CreateAdd(Val, Step, "induction");
1999 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2000 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
2001 // Make sure that the pointer does not point to structs.
2002 if (Ptr->getType()->getPointerElementType()->isAggregateType())
2005 // If this value is a pointer induction variable we know it is consecutive.
2006 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
2007 if (Phi && Inductions.count(Phi)) {
2008 InductionDescriptor II = Inductions[Phi];
2009 return II.getConsecutiveDirection();
2012 GetElementPtrInst *Gep = getGEPInstruction(Ptr);
2016 unsigned NumOperands = Gep->getNumOperands();
2017 Value *GpPtr = Gep->getPointerOperand();
2018 // If this GEP value is a consecutive pointer induction variable and all of
2019 // the indices are constant then we know it is consecutive. We can
2020 Phi = dyn_cast<PHINode>(GpPtr);
2021 if (Phi && Inductions.count(Phi)) {
2023 // Make sure that the pointer does not point to structs.
2024 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
2025 if (GepPtrType->getElementType()->isAggregateType())
2028 // Make sure that all of the index operands are loop invariant.
2029 for (unsigned i = 1; i < NumOperands; ++i)
2030 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
2033 InductionDescriptor II = Inductions[Phi];
2034 return II.getConsecutiveDirection();
2037 unsigned InductionOperand = getGEPInductionOperand(Gep);
2039 // Check that all of the gep indices are uniform except for our induction
2041 for (unsigned i = 0; i != NumOperands; ++i)
2042 if (i != InductionOperand &&
2043 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
2046 // We can emit wide load/stores only if the last non-zero index is the
2047 // induction variable.
2048 const SCEV *Last = nullptr;
2049 if (!Strides.count(Gep))
2050 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
2052 // Because of the multiplication by a stride we can have a s/zext cast.
2053 // We are going to replace this stride by 1 so the cast is safe to ignore.
2055 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
2056 // %0 = trunc i64 %indvars.iv to i32
2057 // %mul = mul i32 %0, %Stride1
2058 // %idxprom = zext i32 %mul to i64 << Safe cast.
2059 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
2061 Last = replaceSymbolicStrideSCEV(SE, Strides, Preds,
2062 Gep->getOperand(InductionOperand), Gep);
2063 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
2065 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
2069 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
2070 const SCEV *Step = AR->getStepRecurrence(*SE);
2072 // The memory is consecutive because the last index is consecutive
2073 // and all other indices are loop invariant.
2076 if (Step->isAllOnesValue())
2083 bool LoopVectorizationLegality::isUniform(Value *V) {
2084 return LAI->isUniform(V);
2087 InnerLoopVectorizer::VectorParts&
2088 InnerLoopVectorizer::getVectorValue(Value *V) {
2089 assert(V != Induction && "The new induction variable should not be used.");
2090 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2092 // If we have a stride that is replaced by one, do it here.
2093 if (Legal->hasStride(V))
2094 V = ConstantInt::get(V->getType(), 1);
2096 // If we have this scalar in the map, return it.
2097 if (WidenMap.has(V))
2098 return WidenMap.get(V);
2100 // If this scalar is unknown, assume that it is a constant or that it is
2101 // loop invariant. Broadcast V and save the value for future uses.
2102 Value *B = getBroadcastInstrs(V);
2103 return WidenMap.splat(V, B);
2106 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2107 assert(Vec->getType()->isVectorTy() && "Invalid type");
2108 SmallVector<Constant*, 8> ShuffleMask;
2109 for (unsigned i = 0; i < VF; ++i)
2110 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2112 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2113 ConstantVector::get(ShuffleMask),
2117 // Get a mask to interleave \p NumVec vectors into a wide vector.
2118 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2119 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2120 // <0, 4, 1, 5, 2, 6, 3, 7>
2121 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2123 SmallVector<Constant *, 16> Mask;
2124 for (unsigned i = 0; i < VF; i++)
2125 for (unsigned j = 0; j < NumVec; j++)
2126 Mask.push_back(Builder.getInt32(j * VF + i));
2128 return ConstantVector::get(Mask);
2131 // Get the strided mask starting from index \p Start.
2132 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2133 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2134 unsigned Stride, unsigned VF) {
2135 SmallVector<Constant *, 16> Mask;
2136 for (unsigned i = 0; i < VF; i++)
2137 Mask.push_back(Builder.getInt32(Start + i * Stride));
2139 return ConstantVector::get(Mask);
2142 // Get a mask of two parts: The first part consists of sequential integers
2143 // starting from 0, The second part consists of UNDEFs.
2144 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2145 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2146 unsigned NumUndef) {
2147 SmallVector<Constant *, 16> Mask;
2148 for (unsigned i = 0; i < NumInt; i++)
2149 Mask.push_back(Builder.getInt32(i));
2151 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2152 for (unsigned i = 0; i < NumUndef; i++)
2153 Mask.push_back(Undef);
2155 return ConstantVector::get(Mask);
2158 // Concatenate two vectors with the same element type. The 2nd vector should
2159 // not have more elements than the 1st vector. If the 2nd vector has less
2160 // elements, extend it with UNDEFs.
2161 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2163 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2164 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2165 assert(VecTy1 && VecTy2 &&
2166 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2167 "Expect two vectors with the same element type");
2169 unsigned NumElts1 = VecTy1->getNumElements();
2170 unsigned NumElts2 = VecTy2->getNumElements();
2171 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2173 if (NumElts1 > NumElts2) {
2174 // Extend with UNDEFs.
2176 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2177 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2180 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2181 return Builder.CreateShuffleVector(V1, V2, Mask);
2184 // Concatenate vectors in the given list. All vectors have the same type.
2185 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2186 ArrayRef<Value *> InputList) {
2187 unsigned NumVec = InputList.size();
2188 assert(NumVec > 1 && "Should be at least two vectors");
2190 SmallVector<Value *, 8> ResList;
2191 ResList.append(InputList.begin(), InputList.end());
2193 SmallVector<Value *, 8> TmpList;
2194 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2195 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2196 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2197 "Only the last vector may have a different type");
2199 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2202 // Push the last vector if the total number of vectors is odd.
2203 if (NumVec % 2 != 0)
2204 TmpList.push_back(ResList[NumVec - 1]);
2207 NumVec = ResList.size();
2208 } while (NumVec > 1);
2213 // Try to vectorize the interleave group that \p Instr belongs to.
2215 // E.g. Translate following interleaved load group (factor = 3):
2216 // for (i = 0; i < N; i+=3) {
2217 // R = Pic[i]; // Member of index 0
2218 // G = Pic[i+1]; // Member of index 1
2219 // B = Pic[i+2]; // Member of index 2
2220 // ... // do something to R, G, B
2223 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2224 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2225 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2226 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2228 // Or translate following interleaved store group (factor = 3):
2229 // for (i = 0; i < N; i+=3) {
2230 // ... do something to R, G, B
2231 // Pic[i] = R; // Member of index 0
2232 // Pic[i+1] = G; // Member of index 1
2233 // Pic[i+2] = B; // Member of index 2
2236 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2237 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2238 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2239 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2240 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2241 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2242 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2243 assert(Group && "Fail to get an interleaved access group.");
2245 // Skip if current instruction is not the insert position.
2246 if (Instr != Group->getInsertPos())
2249 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2250 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2251 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2253 // Prepare for the vector type of the interleaved load/store.
2254 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2255 unsigned InterleaveFactor = Group->getFactor();
2256 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2257 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2259 // Prepare for the new pointers.
2260 setDebugLocFromInst(Builder, Ptr);
2261 VectorParts &PtrParts = getVectorValue(Ptr);
2262 SmallVector<Value *, 2> NewPtrs;
2263 unsigned Index = Group->getIndex(Instr);
2264 for (unsigned Part = 0; Part < UF; Part++) {
2265 // Extract the pointer for current instruction from the pointer vector. A
2266 // reverse access uses the pointer in the last lane.
2267 Value *NewPtr = Builder.CreateExtractElement(
2269 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2271 // Notice current instruction could be any index. Need to adjust the address
2272 // to the member of index 0.
2274 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2275 // b = A[i]; // Member of index 0
2276 // Current pointer is pointed to A[i+1], adjust it to A[i].
2278 // E.g. A[i+1] = a; // Member of index 1
2279 // A[i] = b; // Member of index 0
2280 // A[i+2] = c; // Member of index 2 (Current instruction)
2281 // Current pointer is pointed to A[i+2], adjust it to A[i].
2282 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2284 // Cast to the vector pointer type.
2285 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2288 setDebugLocFromInst(Builder, Instr);
2289 Value *UndefVec = UndefValue::get(VecTy);
2291 // Vectorize the interleaved load group.
2293 for (unsigned Part = 0; Part < UF; Part++) {
2294 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2295 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2297 for (unsigned i = 0; i < InterleaveFactor; i++) {
2298 Instruction *Member = Group->getMember(i);
2300 // Skip the gaps in the group.
2304 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2305 Value *StridedVec = Builder.CreateShuffleVector(
2306 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2308 // If this member has different type, cast the result type.
2309 if (Member->getType() != ScalarTy) {
2310 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2311 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2314 VectorParts &Entry = WidenMap.get(Member);
2316 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2319 propagateMetadata(NewLoadInstr, Instr);
2324 // The sub vector type for current instruction.
2325 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2327 // Vectorize the interleaved store group.
2328 for (unsigned Part = 0; Part < UF; Part++) {
2329 // Collect the stored vector from each member.
2330 SmallVector<Value *, 4> StoredVecs;
2331 for (unsigned i = 0; i < InterleaveFactor; i++) {
2332 // Interleaved store group doesn't allow a gap, so each index has a member
2333 Instruction *Member = Group->getMember(i);
2334 assert(Member && "Fail to get a member from an interleaved store group");
2337 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2338 if (Group->isReverse())
2339 StoredVec = reverseVector(StoredVec);
2341 // If this member has different type, cast it to an unified type.
2342 if (StoredVec->getType() != SubVT)
2343 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2345 StoredVecs.push_back(StoredVec);
2348 // Concatenate all vectors into a wide vector.
2349 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2351 // Interleave the elements in the wide vector.
2352 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2353 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2356 Instruction *NewStoreInstr =
2357 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2358 propagateMetadata(NewStoreInstr, Instr);
2362 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2363 // Attempt to issue a wide load.
2364 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2365 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2367 assert((LI || SI) && "Invalid Load/Store instruction");
2369 // Try to vectorize the interleave group if this access is interleaved.
2370 if (Legal->isAccessInterleaved(Instr))
2371 return vectorizeInterleaveGroup(Instr);
2373 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2374 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2375 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2376 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2377 // An alignment of 0 means target abi alignment. We need to use the scalar's
2378 // target abi alignment in such a case.
2379 const DataLayout &DL = Instr->getModule()->getDataLayout();
2381 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2382 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2383 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2384 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2386 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2387 !Legal->isMaskRequired(SI))
2388 return scalarizeInstruction(Instr, true);
2390 if (ScalarAllocatedSize != VectorElementSize)
2391 return scalarizeInstruction(Instr);
2393 // If the pointer is loop invariant or if it is non-consecutive,
2394 // scalarize the load.
2395 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2396 bool Reverse = ConsecutiveStride < 0;
2397 bool UniformLoad = LI && Legal->isUniform(Ptr);
2398 if (!ConsecutiveStride || UniformLoad)
2399 return scalarizeInstruction(Instr);
2401 Constant *Zero = Builder.getInt32(0);
2402 VectorParts &Entry = WidenMap.get(Instr);
2404 // Handle consecutive loads/stores.
2405 GetElementPtrInst *Gep = getGEPInstruction(Ptr);
2406 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2407 setDebugLocFromInst(Builder, Gep);
2408 Value *PtrOperand = Gep->getPointerOperand();
2409 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2410 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2412 // Create the new GEP with the new induction variable.
2413 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2414 Gep2->setOperand(0, FirstBasePtr);
2415 Gep2->setName("gep.indvar.base");
2416 Ptr = Builder.Insert(Gep2);
2418 setDebugLocFromInst(Builder, Gep);
2419 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2420 OrigLoop) && "Base ptr must be invariant");
2422 // The last index does not have to be the induction. It can be
2423 // consecutive and be a function of the index. For example A[I+1];
2424 unsigned NumOperands = Gep->getNumOperands();
2425 unsigned InductionOperand = getGEPInductionOperand(Gep);
2426 // Create the new GEP with the new induction variable.
2427 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2429 for (unsigned i = 0; i < NumOperands; ++i) {
2430 Value *GepOperand = Gep->getOperand(i);
2431 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2433 // Update last index or loop invariant instruction anchored in loop.
2434 if (i == InductionOperand ||
2435 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2436 assert((i == InductionOperand ||
2437 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2438 "Must be last index or loop invariant");
2440 VectorParts &GEPParts = getVectorValue(GepOperand);
2441 Value *Index = GEPParts[0];
2442 Index = Builder.CreateExtractElement(Index, Zero);
2443 Gep2->setOperand(i, Index);
2444 Gep2->setName("gep.indvar.idx");
2447 Ptr = Builder.Insert(Gep2);
2449 // Use the induction element ptr.
2450 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2451 setDebugLocFromInst(Builder, Ptr);
2452 VectorParts &PtrVal = getVectorValue(Ptr);
2453 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2456 VectorParts Mask = createBlockInMask(Instr->getParent());
2459 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2460 "We do not allow storing to uniform addresses");
2461 setDebugLocFromInst(Builder, SI);
2462 // We don't want to update the value in the map as it might be used in
2463 // another expression. So don't use a reference type for "StoredVal".
2464 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2466 for (unsigned Part = 0; Part < UF; ++Part) {
2467 // Calculate the pointer for the specific unroll-part.
2469 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2472 // If we store to reverse consecutive memory locations, then we need
2473 // to reverse the order of elements in the stored value.
2474 StoredVal[Part] = reverseVector(StoredVal[Part]);
2475 // If the address is consecutive but reversed, then the
2476 // wide store needs to start at the last vector element.
2477 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2478 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2479 Mask[Part] = reverseVector(Mask[Part]);
2482 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2483 DataTy->getPointerTo(AddressSpace));
2486 if (Legal->isMaskRequired(SI))
2487 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2490 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2491 propagateMetadata(NewSI, SI);
2497 assert(LI && "Must have a load instruction");
2498 setDebugLocFromInst(Builder, LI);
2499 for (unsigned Part = 0; Part < UF; ++Part) {
2500 // Calculate the pointer for the specific unroll-part.
2502 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2505 // If the address is consecutive but reversed, then the
2506 // wide load needs to start at the last vector element.
2507 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2508 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2509 Mask[Part] = reverseVector(Mask[Part]);
2513 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2514 DataTy->getPointerTo(AddressSpace));
2515 if (Legal->isMaskRequired(LI))
2516 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2517 UndefValue::get(DataTy),
2518 "wide.masked.load");
2520 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2521 propagateMetadata(NewLI, LI);
2522 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2526 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2527 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2528 // Holds vector parameters or scalars, in case of uniform vals.
2529 SmallVector<VectorParts, 4> Params;
2531 setDebugLocFromInst(Builder, Instr);
2533 // Find all of the vectorized parameters.
2534 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2535 Value *SrcOp = Instr->getOperand(op);
2537 // If we are accessing the old induction variable, use the new one.
2538 if (SrcOp == OldInduction) {
2539 Params.push_back(getVectorValue(SrcOp));
2543 // Try using previously calculated values.
2544 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2546 // If the src is an instruction that appeared earlier in the basic block,
2547 // then it should already be vectorized.
2548 if (SrcInst && OrigLoop->contains(SrcInst)) {
2549 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2550 // The parameter is a vector value from earlier.
2551 Params.push_back(WidenMap.get(SrcInst));
2553 // The parameter is a scalar from outside the loop. Maybe even a constant.
2554 VectorParts Scalars;
2555 Scalars.append(UF, SrcOp);
2556 Params.push_back(Scalars);
2560 assert(Params.size() == Instr->getNumOperands() &&
2561 "Invalid number of operands");
2563 // Does this instruction return a value ?
2564 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2566 Value *UndefVec = IsVoidRetTy ? nullptr :
2567 UndefValue::get(VectorType::get(Instr->getType(), VF));
2568 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2569 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2572 if (IfPredicateStore) {
2573 assert(Instr->getParent()->getSinglePredecessor() &&
2574 "Only support single predecessor blocks");
2575 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2576 Instr->getParent());
2579 // For each vector unroll 'part':
2580 for (unsigned Part = 0; Part < UF; ++Part) {
2581 // For each scalar that we create:
2582 for (unsigned Width = 0; Width < VF; ++Width) {
2585 Value *Cmp = nullptr;
2586 if (IfPredicateStore) {
2587 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2588 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2591 Instruction *Cloned = Instr->clone();
2593 Cloned->setName(Instr->getName() + ".cloned");
2594 // Replace the operands of the cloned instructions with extracted scalars.
2595 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2596 Value *Op = Params[op][Part];
2597 // Param is a vector. Need to extract the right lane.
2598 if (Op->getType()->isVectorTy())
2599 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2600 Cloned->setOperand(op, Op);
2603 // Place the cloned scalar in the new loop.
2604 Builder.Insert(Cloned);
2606 // If the original scalar returns a value we need to place it in a vector
2607 // so that future users will be able to use it.
2609 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2610 Builder.getInt32(Width));
2612 if (IfPredicateStore)
2613 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
2619 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2620 Value *End, Value *Step,
2622 BasicBlock *Header = L->getHeader();
2623 BasicBlock *Latch = L->getLoopLatch();
2624 // As we're just creating this loop, it's possible no latch exists
2625 // yet. If so, use the header as this will be a single block loop.
2629 IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2630 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2631 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2633 Builder.SetInsertPoint(Latch->getTerminator());
2635 // Create i+1 and fill the PHINode.
2636 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2637 Induction->addIncoming(Start, L->getLoopPreheader());
2638 Induction->addIncoming(Next, Latch);
2639 // Create the compare.
2640 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2641 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2643 // Now we have two terminators. Remove the old one from the block.
2644 Latch->getTerminator()->eraseFromParent();
2649 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2653 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2654 // Find the loop boundaries.
2655 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(OrigLoop);
2656 assert(BackedgeTakenCount != SE->getCouldNotCompute() && "Invalid loop count");
2658 Type *IdxTy = Legal->getWidestInductionType();
2660 // The exit count might have the type of i64 while the phi is i32. This can
2661 // happen if we have an induction variable that is sign extended before the
2662 // compare. The only way that we get a backedge taken count is that the
2663 // induction variable was signed and as such will not overflow. In such a case
2664 // truncation is legal.
2665 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2666 IdxTy->getPrimitiveSizeInBits())
2667 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2668 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2670 // Get the total trip count from the count by adding 1.
2671 const SCEV *ExitCount = SE->getAddExpr(
2672 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2674 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2676 // Expand the trip count and place the new instructions in the preheader.
2677 // Notice that the pre-header does not change, only the loop body.
2678 SCEVExpander Exp(*SE, DL, "induction");
2680 // Count holds the overall loop count (N).
2681 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2682 L->getLoopPreheader()->getTerminator());
2684 if (TripCount->getType()->isPointerTy())
2686 CastInst::CreatePointerCast(TripCount, IdxTy,
2687 "exitcount.ptrcnt.to.int",
2688 L->getLoopPreheader()->getTerminator());
2693 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2694 if (VectorTripCount)
2695 return VectorTripCount;
2697 Value *TC = getOrCreateTripCount(L);
2698 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2700 // Now we need to generate the expression for N - (N % VF), which is
2701 // the part that the vectorized body will execute.
2702 // The loop step is equal to the vectorization factor (num of SIMD elements)
2703 // times the unroll factor (num of SIMD instructions).
2704 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2705 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2706 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2708 return VectorTripCount;
2711 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2712 BasicBlock *Bypass) {
2713 Value *Count = getOrCreateTripCount(L);
2714 BasicBlock *BB = L->getLoopPreheader();
2715 IRBuilder<> Builder(BB->getTerminator());
2717 // Generate code to check that the loop's trip count that we computed by
2718 // adding one to the backedge-taken count will not overflow.
2719 Value *CheckMinIters =
2720 Builder.CreateICmpULT(Count,
2721 ConstantInt::get(Count->getType(), VF * UF),
2724 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2725 "min.iters.checked");
2726 if (L->getParentLoop())
2727 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2728 ReplaceInstWithInst(BB->getTerminator(),
2729 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2730 LoopBypassBlocks.push_back(BB);
2733 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2734 BasicBlock *Bypass) {
2735 Value *TC = getOrCreateVectorTripCount(L);
2736 BasicBlock *BB = L->getLoopPreheader();
2737 IRBuilder<> Builder(BB->getTerminator());
2739 // Now, compare the new count to zero. If it is zero skip the vector loop and
2740 // jump to the scalar loop.
2741 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2744 // Generate code to check that the loop's trip count that we computed by
2745 // adding one to the backedge-taken count will not overflow.
2746 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2748 if (L->getParentLoop())
2749 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2750 ReplaceInstWithInst(BB->getTerminator(),
2751 BranchInst::Create(Bypass, NewBB, Cmp));
2752 LoopBypassBlocks.push_back(BB);
2755 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
2756 BasicBlock *BB = L->getLoopPreheader();
2758 // Generate the code to check that the SCEV assumptions that we made.
2759 // We want the new basic block to start at the first instruction in a
2760 // sequence of instructions that form a check.
2761 SCEVExpander Exp(*SE, Bypass->getModule()->getDataLayout(), "scev.check");
2762 Value *SCEVCheck = Exp.expandCodeForPredicate(&Preds, BB->getTerminator());
2764 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2768 // Create a new block containing the stride check.
2769 BB->setName("vector.scevcheck");
2770 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2771 if (L->getParentLoop())
2772 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2773 ReplaceInstWithInst(BB->getTerminator(),
2774 BranchInst::Create(Bypass, NewBB, SCEVCheck));
2775 LoopBypassBlocks.push_back(BB);
2776 AddedSafetyChecks = true;
2779 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
2780 BasicBlock *Bypass) {
2781 BasicBlock *BB = L->getLoopPreheader();
2783 // Generate the code that checks in runtime if arrays overlap. We put the
2784 // checks into a separate block to make the more common case of few elements
2786 Instruction *FirstCheckInst;
2787 Instruction *MemRuntimeCheck;
2788 std::tie(FirstCheckInst, MemRuntimeCheck) =
2789 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2790 if (!MemRuntimeCheck)
2793 // Create a new block containing the memory check.
2794 BB->setName("vector.memcheck");
2795 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2796 if (L->getParentLoop())
2797 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2798 ReplaceInstWithInst(BB->getTerminator(),
2799 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2800 LoopBypassBlocks.push_back(BB);
2801 AddedSafetyChecks = true;
2805 void InnerLoopVectorizer::createEmptyLoop() {
2807 In this function we generate a new loop. The new loop will contain
2808 the vectorized instructions while the old loop will continue to run the
2811 [ ] <-- loop iteration number check.
2814 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2817 || [ ] <-- vector pre header.
2821 | [ ]_| <-- vector loop.
2824 | -[ ] <--- middle-block.
2827 -|- >[ ] <--- new preheader.
2831 | [ ]_| <-- old scalar loop to handle remainder.
2834 >[ ] <-- exit block.
2838 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2839 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2840 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2841 assert(VectorPH && "Invalid loop structure");
2842 assert(ExitBlock && "Must have an exit block");
2844 // Some loops have a single integer induction variable, while other loops
2845 // don't. One example is c++ iterators that often have multiple pointer
2846 // induction variables. In the code below we also support a case where we
2847 // don't have a single induction variable.
2849 // We try to obtain an induction variable from the original loop as hard
2850 // as possible. However if we don't find one that:
2852 // - counts from zero, stepping by one
2853 // - is the size of the widest induction variable type
2854 // then we create a new one.
2855 OldInduction = Legal->getInduction();
2856 Type *IdxTy = Legal->getWidestInductionType();
2858 // Split the single block loop into the two loop structure described above.
2859 BasicBlock *VecBody =
2860 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2861 BasicBlock *MiddleBlock =
2862 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2863 BasicBlock *ScalarPH =
2864 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2866 // Create and register the new vector loop.
2867 Loop* Lp = new Loop();
2868 Loop *ParentLoop = OrigLoop->getParentLoop();
2870 // Insert the new loop into the loop nest and register the new basic blocks
2871 // before calling any utilities such as SCEV that require valid LoopInfo.
2873 ParentLoop->addChildLoop(Lp);
2874 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2875 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2877 LI->addTopLevelLoop(Lp);
2879 Lp->addBasicBlockToLoop(VecBody, *LI);
2881 // Find the loop boundaries.
2882 Value *Count = getOrCreateTripCount(Lp);
2884 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2886 // We need to test whether the backedge-taken count is uint##_max. Adding one
2887 // to it will cause overflow and an incorrect loop trip count in the vector
2888 // body. In case of overflow we want to directly jump to the scalar remainder
2890 emitMinimumIterationCountCheck(Lp, ScalarPH);
2891 // Now, compare the new count to zero. If it is zero skip the vector loop and
2892 // jump to the scalar loop.
2893 emitVectorLoopEnteredCheck(Lp, ScalarPH);
2894 // Generate the code to check any assumptions that we've made for SCEV
2896 emitSCEVChecks(Lp, ScalarPH);
2898 // Generate the code that checks in runtime if arrays overlap. We put the
2899 // checks into a separate block to make the more common case of few elements
2901 emitMemRuntimeChecks(Lp, ScalarPH);
2903 // Generate the induction variable.
2904 // The loop step is equal to the vectorization factor (num of SIMD elements)
2905 // times the unroll factor (num of SIMD instructions).
2906 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2907 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2909 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2910 getDebugLocFromInstOrOperands(OldInduction));
2912 // We are going to resume the execution of the scalar loop.
2913 // Go over all of the induction variables that we found and fix the
2914 // PHIs that are left in the scalar version of the loop.
2915 // The starting values of PHI nodes depend on the counter of the last
2916 // iteration in the vectorized loop.
2917 // If we come from a bypass edge then we need to start from the original
2920 // This variable saves the new starting index for the scalar loop. It is used
2921 // to test if there are any tail iterations left once the vector loop has
2923 LoopVectorizationLegality::InductionList::iterator I, E;
2924 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2925 for (I = List->begin(), E = List->end(); I != E; ++I) {
2926 PHINode *OrigPhi = I->first;
2927 InductionDescriptor II = I->second;
2929 // Create phi nodes to merge from the backedge-taken check block.
2930 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
2932 ScalarPH->getTerminator());
2934 if (OrigPhi == OldInduction) {
2935 // We know what the end value is.
2936 EndValue = CountRoundDown;
2938 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
2939 Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
2940 II.getStepValue()->getType(),
2942 EndValue = II.transform(B, CRD);
2943 EndValue->setName("ind.end");
2946 // The new PHI merges the original incoming value, in case of a bypass,
2947 // or the value at the end of the vectorized loop.
2948 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2950 // Fix the scalar body counter (PHI node).
2951 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2953 // The old induction's phi node in the scalar body needs the truncated
2955 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2956 BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
2957 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2960 // Add a check in the middle block to see if we have completed
2961 // all of the iterations in the first vector loop.
2962 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2963 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2964 CountRoundDown, "cmp.n",
2965 MiddleBlock->getTerminator());
2966 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2967 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2969 // Get ready to start creating new instructions into the vectorized body.
2970 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
2973 LoopVectorPreHeader = Lp->getLoopPreheader();
2974 LoopScalarPreHeader = ScalarPH;
2975 LoopMiddleBlock = MiddleBlock;
2976 LoopExitBlock = ExitBlock;
2977 LoopVectorBody.push_back(VecBody);
2978 LoopScalarBody = OldBasicBlock;
2980 LoopVectorizeHints Hints(Lp, true);
2981 Hints.setAlreadyVectorized();
2985 struct CSEDenseMapInfo {
2986 static bool canHandle(Instruction *I) {
2987 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2988 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2990 static inline Instruction *getEmptyKey() {
2991 return DenseMapInfo<Instruction *>::getEmptyKey();
2993 static inline Instruction *getTombstoneKey() {
2994 return DenseMapInfo<Instruction *>::getTombstoneKey();
2996 static unsigned getHashValue(Instruction *I) {
2997 assert(canHandle(I) && "Unknown instruction!");
2998 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2999 I->value_op_end()));
3001 static bool isEqual(Instruction *LHS, Instruction *RHS) {
3002 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3003 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3005 return LHS->isIdenticalTo(RHS);
3010 /// \brief Check whether this block is a predicated block.
3011 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
3012 /// = ...; " blocks. We start with one vectorized basic block. For every
3013 /// conditional block we split this vectorized block. Therefore, every second
3014 /// block will be a predicated one.
3015 static bool isPredicatedBlock(unsigned BlockNum) {
3016 return BlockNum % 2;
3019 ///\brief Perform cse of induction variable instructions.
3020 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
3021 // Perform simple cse.
3022 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3023 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
3024 BasicBlock *BB = BBs[i];
3025 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3026 Instruction *In = &*I++;
3028 if (!CSEDenseMapInfo::canHandle(In))
3031 // Check if we can replace this instruction with any of the
3032 // visited instructions.
3033 if (Instruction *V = CSEMap.lookup(In)) {
3034 In->replaceAllUsesWith(V);
3035 In->eraseFromParent();
3038 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
3039 // ...;" blocks for predicated stores. Every second block is a predicated
3041 if (isPredicatedBlock(i))
3049 /// \brief Adds a 'fast' flag to floating point operations.
3050 static Value *addFastMathFlag(Value *V) {
3051 if (isa<FPMathOperator>(V)){
3052 FastMathFlags Flags;
3053 Flags.setUnsafeAlgebra();
3054 cast<Instruction>(V)->setFastMathFlags(Flags);
3059 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3060 /// the result needs to be inserted and/or extracted from vectors.
3061 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3062 const TargetTransformInfo &TTI) {
3066 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3069 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3071 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3073 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3079 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3080 // Return the cost of the instruction, including scalarization overhead if it's
3081 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3082 // i.e. either vector version isn't available, or is too expensive.
3083 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3084 const TargetTransformInfo &TTI,
3085 const TargetLibraryInfo *TLI,
3086 bool &NeedToScalarize) {
3087 Function *F = CI->getCalledFunction();
3088 StringRef FnName = CI->getCalledFunction()->getName();
3089 Type *ScalarRetTy = CI->getType();
3090 SmallVector<Type *, 4> Tys, ScalarTys;
3091 for (auto &ArgOp : CI->arg_operands())
3092 ScalarTys.push_back(ArgOp->getType());
3094 // Estimate cost of scalarized vector call. The source operands are assumed
3095 // to be vectors, so we need to extract individual elements from there,
3096 // execute VF scalar calls, and then gather the result into the vector return
3098 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3100 return ScalarCallCost;
3102 // Compute corresponding vector type for return value and arguments.
3103 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3104 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3105 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3107 // Compute costs of unpacking argument values for the scalar calls and
3108 // packing the return values to a vector.
3109 unsigned ScalarizationCost =
3110 getScalarizationOverhead(RetTy, true, false, TTI);
3111 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3112 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3114 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3116 // If we can't emit a vector call for this function, then the currently found
3117 // cost is the cost we need to return.
3118 NeedToScalarize = true;
3119 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3122 // If the corresponding vector cost is cheaper, return its cost.
3123 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3124 if (VectorCallCost < Cost) {
3125 NeedToScalarize = false;
3126 return VectorCallCost;
3131 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3132 // factor VF. Return the cost of the instruction, including scalarization
3133 // overhead if it's needed.
3134 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3135 const TargetTransformInfo &TTI,
3136 const TargetLibraryInfo *TLI) {
3137 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3138 assert(ID && "Expected intrinsic call!");
3140 Type *RetTy = ToVectorTy(CI->getType(), VF);
3141 SmallVector<Type *, 4> Tys;
3142 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3143 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3145 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3148 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3149 IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3150 IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3151 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3153 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3154 IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3155 IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3156 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3159 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3160 // For every instruction `I` in MinBWs, truncate the operands, create a
3161 // truncated version of `I` and reextend its result. InstCombine runs
3162 // later and will remove any ext/trunc pairs.
3164 for (auto &KV : MinBWs) {
3165 VectorParts &Parts = WidenMap.get(KV.first);
3166 for (Value *&I : Parts) {
3169 Type *OriginalTy = I->getType();
3170 Type *ScalarTruncatedTy = IntegerType::get(OriginalTy->getContext(),
3172 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3173 OriginalTy->getVectorNumElements());
3174 if (TruncatedTy == OriginalTy)
3177 IRBuilder<> B(cast<Instruction>(I));
3178 auto ShrinkOperand = [&](Value *V) -> Value* {
3179 if (auto *ZI = dyn_cast<ZExtInst>(V))
3180 if (ZI->getSrcTy() == TruncatedTy)
3181 return ZI->getOperand(0);
3182 return B.CreateZExtOrTrunc(V, TruncatedTy);
3185 // The actual instruction modification depends on the instruction type,
3187 Value *NewI = nullptr;
3188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
3189 NewI = B.CreateBinOp(BO->getOpcode(),
3190 ShrinkOperand(BO->getOperand(0)),
3191 ShrinkOperand(BO->getOperand(1)));
3192 cast<BinaryOperator>(NewI)->copyIRFlags(I);
3193 } else if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) {
3194 NewI = B.CreateICmp(CI->getPredicate(),
3195 ShrinkOperand(CI->getOperand(0)),
3196 ShrinkOperand(CI->getOperand(1)));
3197 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
3198 NewI = B.CreateSelect(SI->getCondition(),
3199 ShrinkOperand(SI->getTrueValue()),
3200 ShrinkOperand(SI->getFalseValue()));
3201 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3202 switch (CI->getOpcode()) {
3203 default: llvm_unreachable("Unhandled cast!");
3204 case Instruction::Trunc:
3205 NewI = ShrinkOperand(CI->getOperand(0));
3207 case Instruction::SExt:
3208 NewI = B.CreateSExtOrTrunc(CI->getOperand(0),
3209 smallestIntegerVectorType(OriginalTy,
3212 case Instruction::ZExt:
3213 NewI = B.CreateZExtOrTrunc(CI->getOperand(0),
3214 smallestIntegerVectorType(OriginalTy,
3218 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
3219 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3221 B.CreateZExtOrTrunc(SI->getOperand(0),
3222 VectorType::get(ScalarTruncatedTy, Elements0));
3223 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3225 B.CreateZExtOrTrunc(SI->getOperand(1),
3226 VectorType::get(ScalarTruncatedTy, Elements1));
3228 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3229 } else if (isa<LoadInst>(I)) {
3230 // Don't do anything with the operands, just extend the result.
3233 llvm_unreachable("Unhandled instruction type!");
3236 // Lastly, extend the result.
3237 NewI->takeName(cast<Instruction>(I));
3238 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3239 I->replaceAllUsesWith(Res);
3240 cast<Instruction>(I)->eraseFromParent();
3245 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3246 for (auto &KV : MinBWs) {
3247 VectorParts &Parts = WidenMap.get(KV.first);
3248 for (Value *&I : Parts) {
3249 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3250 if (Inst && Inst->use_empty()) {
3251 Value *NewI = Inst->getOperand(0);
3252 Inst->eraseFromParent();
3259 void InnerLoopVectorizer::vectorizeLoop() {
3260 //===------------------------------------------------===//
3262 // Notice: any optimization or new instruction that go
3263 // into the code below should be also be implemented in
3266 //===------------------------------------------------===//
3267 Constant *Zero = Builder.getInt32(0);
3269 // In order to support reduction variables we need to be able to vectorize
3270 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3271 // stages. First, we create a new vector PHI node with no incoming edges.
3272 // We use this value when we vectorize all of the instructions that use the
3273 // PHI. Next, after all of the instructions in the block are complete we
3274 // add the new incoming edges to the PHI. At this point all of the
3275 // instructions in the basic block are vectorized, so we can use them to
3276 // construct the PHI.
3277 PhiVector RdxPHIsToFix;
3279 // Scan the loop in a topological order to ensure that defs are vectorized
3281 LoopBlocksDFS DFS(OrigLoop);
3284 // Vectorize all of the blocks in the original loop.
3285 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3286 be = DFS.endRPO(); bb != be; ++bb)
3287 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3289 // Insert truncates and extends for any truncated instructions as hints to
3292 truncateToMinimalBitwidths();
3294 // At this point every instruction in the original loop is widened to
3295 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3296 // that we vectorized. The PHI nodes are currently empty because we did
3297 // not want to introduce cycles. Notice that the remaining PHI nodes
3298 // that we need to fix are reduction variables.
3300 // Create the 'reduced' values for each of the induction vars.
3301 // The reduced values are the vector values that we scalarize and combine
3302 // after the loop is finished.
3303 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3305 PHINode *RdxPhi = *it;
3306 assert(RdxPhi && "Unable to recover vectorized PHI");
3308 // Find the reduction variable descriptor.
3309 assert(Legal->getReductionVars()->count(RdxPhi) &&
3310 "Unable to find the reduction variable");
3311 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3313 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3314 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3315 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3316 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3317 RdxDesc.getMinMaxRecurrenceKind();
3318 setDebugLocFromInst(Builder, ReductionStartValue);
3320 // We need to generate a reduction vector from the incoming scalar.
3321 // To do so, we need to generate the 'identity' vector and override
3322 // one of the elements with the incoming scalar reduction. We need
3323 // to do it in the vector-loop preheader.
3324 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3326 // This is the vector-clone of the value that leaves the loop.
3327 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3328 Type *VecTy = VectorExit[0]->getType();
3330 // Find the reduction identity variable. Zero for addition, or, xor,
3331 // one for multiplication, -1 for And.
3334 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3335 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3336 // MinMax reduction have the start value as their identify.
3338 VectorStart = Identity = ReductionStartValue;
3340 VectorStart = Identity =
3341 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3344 // Handle other reduction kinds:
3345 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3346 RK, VecTy->getScalarType());
3349 // This vector is the Identity vector where the first element is the
3350 // incoming scalar reduction.
3351 VectorStart = ReductionStartValue;
3353 Identity = ConstantVector::getSplat(VF, Iden);
3355 // This vector is the Identity vector where the first element is the
3356 // incoming scalar reduction.
3358 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3362 // Fix the vector-loop phi.
3364 // Reductions do not have to start at zero. They can start with
3365 // any loop invariant values.
3366 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3367 BasicBlock *Latch = OrigLoop->getLoopLatch();
3368 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3369 VectorParts &Val = getVectorValue(LoopVal);
3370 for (unsigned part = 0; part < UF; ++part) {
3371 // Make sure to add the reduction stat value only to the
3372 // first unroll part.
3373 Value *StartVal = (part == 0) ? VectorStart : Identity;
3374 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3375 LoopVectorPreHeader);
3376 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3377 LoopVectorBody.back());
3380 // Before each round, move the insertion point right between
3381 // the PHIs and the values we are going to write.
3382 // This allows us to write both PHINodes and the extractelement
3384 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3386 VectorParts RdxParts = getVectorValue(LoopExitInst);
3387 setDebugLocFromInst(Builder, LoopExitInst);
3389 // If the vector reduction can be performed in a smaller type, we truncate
3390 // then extend the loop exit value to enable InstCombine to evaluate the
3391 // entire expression in the smaller type.
3392 if (VF > 1 && RdxPhi->getType() != RdxDesc.getRecurrenceType()) {
3393 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3394 Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
3395 for (unsigned part = 0; part < UF; ++part) {
3396 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3397 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3398 : Builder.CreateZExt(Trunc, VecTy);
3399 for (Value::user_iterator UI = RdxParts[part]->user_begin();
3400 UI != RdxParts[part]->user_end();)
3402 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3403 RdxParts[part] = Extnd;
3408 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3409 for (unsigned part = 0; part < UF; ++part)
3410 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3413 // Reduce all of the unrolled parts into a single vector.
3414 Value *ReducedPartRdx = RdxParts[0];
3415 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3416 setDebugLocFromInst(Builder, ReducedPartRdx);
3417 for (unsigned part = 1; part < UF; ++part) {
3418 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3419 // Floating point operations had to be 'fast' to enable the reduction.
3420 ReducedPartRdx = addFastMathFlag(
3421 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3422 ReducedPartRdx, "bin.rdx"));
3424 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3425 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3429 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3430 // and vector ops, reducing the set of values being computed by half each
3432 assert(isPowerOf2_32(VF) &&
3433 "Reduction emission only supported for pow2 vectors!");
3434 Value *TmpVec = ReducedPartRdx;
3435 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3436 for (unsigned i = VF; i != 1; i >>= 1) {
3437 // Move the upper half of the vector to the lower half.
3438 for (unsigned j = 0; j != i/2; ++j)
3439 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3441 // Fill the rest of the mask with undef.
3442 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3443 UndefValue::get(Builder.getInt32Ty()));
3446 Builder.CreateShuffleVector(TmpVec,
3447 UndefValue::get(TmpVec->getType()),
3448 ConstantVector::get(ShuffleMask),
3451 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3452 // Floating point operations had to be 'fast' to enable the reduction.
3453 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3454 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3456 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3460 // The result is in the first element of the vector.
3461 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3462 Builder.getInt32(0));
3464 // If the reduction can be performed in a smaller type, we need to extend
3465 // the reduction to the wider type before we branch to the original loop.
3466 if (RdxPhi->getType() != RdxDesc.getRecurrenceType())
3469 ? Builder.CreateSExt(ReducedPartRdx, RdxPhi->getType())
3470 : Builder.CreateZExt(ReducedPartRdx, RdxPhi->getType());
3473 // Create a phi node that merges control-flow from the backedge-taken check
3474 // block and the middle block.
3475 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3476 LoopScalarPreHeader->getTerminator());
3477 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3478 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3479 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3481 // Now, we need to fix the users of the reduction variable
3482 // inside and outside of the scalar remainder loop.
3483 // We know that the loop is in LCSSA form. We need to update the
3484 // PHI nodes in the exit blocks.
3485 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3486 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3487 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3488 if (!LCSSAPhi) break;
3490 // All PHINodes need to have a single entry edge, or two if
3491 // we already fixed them.
3492 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3494 // We found our reduction value exit-PHI. Update it with the
3495 // incoming bypass edge.
3496 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3497 // Add an edge coming from the bypass.
3498 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3501 }// end of the LCSSA phi scan.
3503 // Fix the scalar loop reduction variable with the incoming reduction sum
3504 // from the vector body and from the backedge value.
3505 int IncomingEdgeBlockIdx =
3506 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3507 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3508 // Pick the other block.
3509 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3510 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3511 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3512 }// end of for each redux variable.
3516 // Make sure DomTree is updated.
3519 // Predicate any stores.
3520 for (auto KV : PredicatedStores) {
3521 BasicBlock::iterator I(KV.first);
3522 auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI);
3523 auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
3524 /*BranchWeights=*/nullptr, DT);
3526 I->getParent()->setName("pred.store.if");
3527 BB->setName("pred.store.continue");
3529 DEBUG(DT->verifyDomTree());
3530 // Remove redundant induction instructions.
3531 cse(LoopVectorBody);
3534 void InnerLoopVectorizer::fixLCSSAPHIs() {
3535 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3536 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3537 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3538 if (!LCSSAPhi) break;
3539 if (LCSSAPhi->getNumIncomingValues() == 1)
3540 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3545 InnerLoopVectorizer::VectorParts
3546 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3547 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3550 // Look for cached value.
3551 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3552 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3553 if (ECEntryIt != MaskCache.end())
3554 return ECEntryIt->second;
3556 VectorParts SrcMask = createBlockInMask(Src);
3558 // The terminator has to be a branch inst!
3559 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3560 assert(BI && "Unexpected terminator found");
3562 if (BI->isConditional()) {
3563 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3565 if (BI->getSuccessor(0) != Dst)
3566 for (unsigned part = 0; part < UF; ++part)
3567 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3569 for (unsigned part = 0; part < UF; ++part)
3570 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3572 MaskCache[Edge] = EdgeMask;
3576 MaskCache[Edge] = SrcMask;
3580 InnerLoopVectorizer::VectorParts
3581 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3582 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3584 // Loop incoming mask is all-one.
3585 if (OrigLoop->getHeader() == BB) {
3586 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3587 return getVectorValue(C);
3590 // This is the block mask. We OR all incoming edges, and with zero.
3591 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3592 VectorParts BlockMask = getVectorValue(Zero);
3595 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3596 VectorParts EM = createEdgeMask(*it, BB);
3597 for (unsigned part = 0; part < UF; ++part)
3598 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3604 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3605 InnerLoopVectorizer::VectorParts &Entry,
3606 unsigned UF, unsigned VF, PhiVector *PV) {
3607 PHINode* P = cast<PHINode>(PN);
3608 // Handle reduction variables:
3609 if (Legal->getReductionVars()->count(P)) {
3610 for (unsigned part = 0; part < UF; ++part) {
3611 // This is phase one of vectorizing PHIs.
3612 Type *VecTy = (VF == 1) ? PN->getType() :
3613 VectorType::get(PN->getType(), VF);
3614 Entry[part] = PHINode::Create(
3615 VecTy, 2, "vec.phi", &*LoopVectorBody.back()->getFirstInsertionPt());
3621 setDebugLocFromInst(Builder, P);
3622 // Check for PHI nodes that are lowered to vector selects.
3623 if (P->getParent() != OrigLoop->getHeader()) {
3624 // We know that all PHIs in non-header blocks are converted into
3625 // selects, so we don't have to worry about the insertion order and we
3626 // can just use the builder.
3627 // At this point we generate the predication tree. There may be
3628 // duplications since this is a simple recursive scan, but future
3629 // optimizations will clean it up.
3631 unsigned NumIncoming = P->getNumIncomingValues();
3633 // Generate a sequence of selects of the form:
3634 // SELECT(Mask3, In3,
3635 // SELECT(Mask2, In2,
3637 for (unsigned In = 0; In < NumIncoming; In++) {
3638 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3640 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3642 for (unsigned part = 0; part < UF; ++part) {
3643 // We might have single edge PHIs (blocks) - use an identity
3644 // 'select' for the first PHI operand.
3646 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3649 // Select between the current value and the previous incoming edge
3650 // based on the incoming mask.
3651 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3652 Entry[part], "predphi");
3658 // This PHINode must be an induction variable.
3659 // Make sure that we know about it.
3660 assert(Legal->getInductionVars()->count(P) &&
3661 "Not an induction variable");
3663 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3665 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3666 // which can be found from the original scalar operations.
3667 switch (II.getKind()) {
3668 case InductionDescriptor::IK_NoInduction:
3669 llvm_unreachable("Unknown induction");
3670 case InductionDescriptor::IK_IntInduction: {
3671 assert(P->getType() == II.getStartValue()->getType() && "Types must match");
3672 // Handle other induction variables that are now based on the
3674 Value *V = Induction;
3675 if (P != OldInduction) {
3676 V = Builder.CreateSExtOrTrunc(Induction, P->getType());
3677 V = II.transform(Builder, V);
3678 V->setName("offset.idx");
3680 Value *Broadcasted = getBroadcastInstrs(V);
3681 // After broadcasting the induction variable we need to make the vector
3682 // consecutive by adding 0, 1, 2, etc.
3683 for (unsigned part = 0; part < UF; ++part)
3684 Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
3687 case InductionDescriptor::IK_PtrInduction:
3688 // Handle the pointer induction variable case.
3689 assert(P->getType()->isPointerTy() && "Unexpected type.");
3690 // This is the normalized GEP that starts counting at zero.
3691 Value *PtrInd = Induction;
3692 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
3693 // This is the vector of results. Notice that we don't generate
3694 // vector geps because scalar geps result in better code.
3695 for (unsigned part = 0; part < UF; ++part) {
3697 int EltIndex = part;
3698 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3699 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3700 Value *SclrGep = II.transform(Builder, GlobalIdx);
3701 SclrGep->setName("next.gep");
3702 Entry[part] = SclrGep;
3706 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3707 for (unsigned int i = 0; i < VF; ++i) {
3708 int EltIndex = i + part * VF;
3709 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3710 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3711 Value *SclrGep = II.transform(Builder, GlobalIdx);
3712 SclrGep->setName("next.gep");
3713 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3714 Builder.getInt32(i),
3717 Entry[part] = VecVal;
3723 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3724 // For each instruction in the old loop.
3725 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3726 VectorParts &Entry = WidenMap.get(&*it);
3728 switch (it->getOpcode()) {
3729 case Instruction::Br:
3730 // Nothing to do for PHIs and BR, since we already took care of the
3731 // loop control flow instructions.
3733 case Instruction::PHI: {
3734 // Vectorize PHINodes.
3735 widenPHIInstruction(&*it, Entry, UF, VF, PV);
3739 case Instruction::Add:
3740 case Instruction::FAdd:
3741 case Instruction::Sub:
3742 case Instruction::FSub:
3743 case Instruction::Mul:
3744 case Instruction::FMul:
3745 case Instruction::UDiv:
3746 case Instruction::SDiv:
3747 case Instruction::FDiv:
3748 case Instruction::URem:
3749 case Instruction::SRem:
3750 case Instruction::FRem:
3751 case Instruction::Shl:
3752 case Instruction::LShr:
3753 case Instruction::AShr:
3754 case Instruction::And:
3755 case Instruction::Or:
3756 case Instruction::Xor: {
3757 // Just widen binops.
3758 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3759 setDebugLocFromInst(Builder, BinOp);
3760 VectorParts &A = getVectorValue(it->getOperand(0));
3761 VectorParts &B = getVectorValue(it->getOperand(1));
3763 // Use this vector value for all users of the original instruction.
3764 for (unsigned Part = 0; Part < UF; ++Part) {
3765 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3767 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3768 VecOp->copyIRFlags(BinOp);
3773 propagateMetadata(Entry, &*it);
3776 case Instruction::Select: {
3778 // If the selector is loop invariant we can create a select
3779 // instruction with a scalar condition. Otherwise, use vector-select.
3780 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3782 setDebugLocFromInst(Builder, &*it);
3784 // The condition can be loop invariant but still defined inside the
3785 // loop. This means that we can't just use the original 'cond' value.
3786 // We have to take the 'vectorized' value and pick the first lane.
3787 // Instcombine will make this a no-op.
3788 VectorParts &Cond = getVectorValue(it->getOperand(0));
3789 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3790 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3792 Value *ScalarCond = (VF == 1) ? Cond[0] :
3793 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3795 for (unsigned Part = 0; Part < UF; ++Part) {
3796 Entry[Part] = Builder.CreateSelect(
3797 InvariantCond ? ScalarCond : Cond[Part],
3802 propagateMetadata(Entry, &*it);
3806 case Instruction::ICmp:
3807 case Instruction::FCmp: {
3808 // Widen compares. Generate vector compares.
3809 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3810 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3811 setDebugLocFromInst(Builder, &*it);
3812 VectorParts &A = getVectorValue(it->getOperand(0));
3813 VectorParts &B = getVectorValue(it->getOperand(1));
3814 for (unsigned Part = 0; Part < UF; ++Part) {
3817 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3818 cast<FCmpInst>(C)->copyFastMathFlags(&*it);
3820 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3825 propagateMetadata(Entry, &*it);
3829 case Instruction::Store:
3830 case Instruction::Load:
3831 vectorizeMemoryInstruction(&*it);
3833 case Instruction::ZExt:
3834 case Instruction::SExt:
3835 case Instruction::FPToUI:
3836 case Instruction::FPToSI:
3837 case Instruction::FPExt:
3838 case Instruction::PtrToInt:
3839 case Instruction::IntToPtr:
3840 case Instruction::SIToFP:
3841 case Instruction::UIToFP:
3842 case Instruction::Trunc:
3843 case Instruction::FPTrunc:
3844 case Instruction::BitCast: {
3845 CastInst *CI = dyn_cast<CastInst>(it);
3846 setDebugLocFromInst(Builder, &*it);
3847 /// Optimize the special case where the source is the induction
3848 /// variable. Notice that we can only optimize the 'trunc' case
3849 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3850 /// c. other casts depend on pointer size.
3851 if (CI->getOperand(0) == OldInduction &&
3852 it->getOpcode() == Instruction::Trunc) {
3853 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3855 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3856 InductionDescriptor II = Legal->getInductionVars()->lookup(OldInduction);
3858 ConstantInt::getSigned(CI->getType(), II.getStepValue()->getSExtValue());
3859 for (unsigned Part = 0; Part < UF; ++Part)
3860 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3861 propagateMetadata(Entry, &*it);
3864 /// Vectorize casts.
3865 Type *DestTy = (VF == 1) ? CI->getType() :
3866 VectorType::get(CI->getType(), VF);
3868 VectorParts &A = getVectorValue(it->getOperand(0));
3869 for (unsigned Part = 0; Part < UF; ++Part)
3870 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3871 propagateMetadata(Entry, &*it);
3875 case Instruction::Call: {
3876 // Ignore dbg intrinsics.
3877 if (isa<DbgInfoIntrinsic>(it))
3879 setDebugLocFromInst(Builder, &*it);
3881 Module *M = BB->getParent()->getParent();
3882 CallInst *CI = cast<CallInst>(it);
3884 StringRef FnName = CI->getCalledFunction()->getName();
3885 Function *F = CI->getCalledFunction();
3886 Type *RetTy = ToVectorTy(CI->getType(), VF);
3887 SmallVector<Type *, 4> Tys;
3888 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3889 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3891 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3893 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3894 ID == Intrinsic::lifetime_start)) {
3895 scalarizeInstruction(&*it);
3898 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3899 // version of the instruction.
3900 // Is it beneficial to perform intrinsic call compared to lib call?
3901 bool NeedToScalarize;
3902 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3903 bool UseVectorIntrinsic =
3904 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3905 if (!UseVectorIntrinsic && NeedToScalarize) {
3906 scalarizeInstruction(&*it);
3910 for (unsigned Part = 0; Part < UF; ++Part) {
3911 SmallVector<Value *, 4> Args;
3912 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3913 Value *Arg = CI->getArgOperand(i);
3914 // Some intrinsics have a scalar argument - don't replace it with a
3916 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3917 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3918 Arg = VectorArg[Part];
3920 Args.push_back(Arg);
3924 if (UseVectorIntrinsic) {
3925 // Use vector version of the intrinsic.
3926 Type *TysForDecl[] = {CI->getType()};
3928 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3929 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3931 // Use vector version of the library call.
3932 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3933 assert(!VFnName.empty() && "Vector function name is empty.");
3934 VectorF = M->getFunction(VFnName);
3936 // Generate a declaration
3937 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3939 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3940 VectorF->copyAttributesFrom(F);
3943 assert(VectorF && "Can't create vector function.");
3944 Entry[Part] = Builder.CreateCall(VectorF, Args);
3947 propagateMetadata(Entry, &*it);
3952 // All other instructions are unsupported. Scalarize them.
3953 scalarizeInstruction(&*it);
3956 }// end of for_each instr.
3959 void InnerLoopVectorizer::updateAnalysis() {
3960 // Forget the original basic block.
3961 SE->forgetLoop(OrigLoop);
3963 // Update the dominator tree information.
3964 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3965 "Entry does not dominate exit.");
3967 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3968 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3969 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3971 // We don't predicate stores by this point, so the vector body should be a
3973 assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
3974 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3976 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
3977 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3978 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3979 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3981 DEBUG(DT->verifyDomTree());
3984 /// \brief Check whether it is safe to if-convert this phi node.
3986 /// Phi nodes with constant expressions that can trap are not safe to if
3988 static bool canIfConvertPHINodes(BasicBlock *BB) {
3989 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3990 PHINode *Phi = dyn_cast<PHINode>(I);
3993 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3994 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
4001 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4002 if (!EnableIfConversion) {
4003 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
4007 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
4009 // A list of pointers that we can safely read and write to.
4010 SmallPtrSet<Value *, 8> SafePointes;
4012 // Collect safe addresses.
4013 for (Loop::block_iterator BI = TheLoop->block_begin(),
4014 BE = TheLoop->block_end(); BI != BE; ++BI) {
4015 BasicBlock *BB = *BI;
4017 if (blockNeedsPredication(BB))
4020 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
4021 if (LoadInst *LI = dyn_cast<LoadInst>(I))
4022 SafePointes.insert(LI->getPointerOperand());
4023 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
4024 SafePointes.insert(SI->getPointerOperand());
4028 // Collect the blocks that need predication.
4029 BasicBlock *Header = TheLoop->getHeader();
4030 for (Loop::block_iterator BI = TheLoop->block_begin(),
4031 BE = TheLoop->block_end(); BI != BE; ++BI) {
4032 BasicBlock *BB = *BI;
4034 // We don't support switch statements inside loops.
4035 if (!isa<BranchInst>(BB->getTerminator())) {
4036 emitAnalysis(VectorizationReport(BB->getTerminator())
4037 << "loop contains a switch statement");
4041 // We must be able to predicate all blocks that need to be predicated.
4042 if (blockNeedsPredication(BB)) {
4043 if (!blockCanBePredicated(BB, SafePointes)) {
4044 emitAnalysis(VectorizationReport(BB->getTerminator())
4045 << "control flow cannot be substituted for a select");
4048 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4049 emitAnalysis(VectorizationReport(BB->getTerminator())
4050 << "control flow cannot be substituted for a select");
4055 // We can if-convert this loop.
4059 bool LoopVectorizationLegality::canVectorize() {
4060 // We must have a loop in canonical form. Loops with indirectbr in them cannot
4061 // be canonicalized.
4062 if (!TheLoop->getLoopPreheader()) {
4064 VectorizationReport() <<
4065 "loop control flow is not understood by vectorizer");
4069 // We can only vectorize innermost loops.
4070 if (!TheLoop->empty()) {
4071 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
4075 // We must have a single backedge.
4076 if (TheLoop->getNumBackEdges() != 1) {
4078 VectorizationReport() <<
4079 "loop control flow is not understood by vectorizer");
4083 // We must have a single exiting block.
4084 if (!TheLoop->getExitingBlock()) {
4086 VectorizationReport() <<
4087 "loop control flow is not understood by vectorizer");
4091 // We only handle bottom-tested loops, i.e. loop in which the condition is
4092 // checked at the end of each iteration. With that we can assume that all
4093 // instructions in the loop are executed the same number of times.
4094 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4096 VectorizationReport() <<
4097 "loop control flow is not understood by vectorizer");
4101 // We need to have a loop header.
4102 DEBUG(dbgs() << "LV: Found a loop: " <<
4103 TheLoop->getHeader()->getName() << '\n');
4105 // Check if we can if-convert non-single-bb loops.
4106 unsigned NumBlocks = TheLoop->getNumBlocks();
4107 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4108 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
4112 // ScalarEvolution needs to be able to find the exit count.
4113 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
4114 if (ExitCount == SE->getCouldNotCompute()) {
4115 emitAnalysis(VectorizationReport() <<
4116 "could not determine number of loop iterations");
4117 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
4121 // Check if we can vectorize the instructions and CFG in this loop.
4122 if (!canVectorizeInstrs()) {
4123 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
4127 // Go over each instruction and look at memory deps.
4128 if (!canVectorizeMemory()) {
4129 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4133 // Collect all of the variables that remain uniform after vectorization.
4134 collectLoopUniforms();
4136 DEBUG(dbgs() << "LV: We can vectorize this loop"
4137 << (LAI->getRuntimePointerChecking()->Need
4138 ? " (with a runtime bound check)"
4142 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4144 // If an override option has been passed in for interleaved accesses, use it.
4145 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4146 UseInterleaved = EnableInterleavedMemAccesses;
4148 // Analyze interleaved memory accesses.
4150 InterleaveInfo.analyzeInterleaving(Strides);
4152 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4153 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4154 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4156 if (Preds.getComplexity() > SCEVThreshold) {
4157 emitAnalysis(VectorizationReport()
4158 << "Too many SCEV assumptions need to be made and checked "
4160 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
4164 // Okay! We can vectorize. At this point we don't have any other mem analysis
4165 // which may limit our maximum vectorization factor, so just return true with
4170 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4171 if (Ty->isPointerTy())
4172 return DL.getIntPtrType(Ty);
4174 // It is possible that char's or short's overflow when we ask for the loop's
4175 // trip count, work around this by changing the type size.
4176 if (Ty->getScalarSizeInBits() < 32)
4177 return Type::getInt32Ty(Ty->getContext());
4182 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4183 Ty0 = convertPointerToIntegerType(DL, Ty0);
4184 Ty1 = convertPointerToIntegerType(DL, Ty1);
4185 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4190 /// \brief Check that the instruction has outside loop users and is not an
4191 /// identified reduction variable.
4192 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4193 SmallPtrSetImpl<Value *> &Reductions) {
4194 // Reduction instructions are allowed to have exit users. All other
4195 // instructions must not have external users.
4196 if (!Reductions.count(Inst))
4197 //Check that all of the users of the loop are inside the BB.
4198 for (User *U : Inst->users()) {
4199 Instruction *UI = cast<Instruction>(U);
4200 // This user may be a reduction exit value.
4201 if (!TheLoop->contains(UI)) {
4202 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4209 bool LoopVectorizationLegality::canVectorizeInstrs() {
4210 BasicBlock *Header = TheLoop->getHeader();
4212 // Look for the attribute signaling the absence of NaNs.
4213 Function &F = *Header->getParent();
4214 const DataLayout &DL = F.getParent()->getDataLayout();
4215 if (F.hasFnAttribute("no-nans-fp-math"))
4217 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4219 // For each block in the loop.
4220 for (Loop::block_iterator bb = TheLoop->block_begin(),
4221 be = TheLoop->block_end(); bb != be; ++bb) {
4223 // Scan the instructions in the block and look for hazards.
4224 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4227 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4228 Type *PhiTy = Phi->getType();
4229 // Check that this PHI type is allowed.
4230 if (!PhiTy->isIntegerTy() &&
4231 !PhiTy->isFloatingPointTy() &&
4232 !PhiTy->isPointerTy()) {
4233 emitAnalysis(VectorizationReport(&*it)
4234 << "loop control flow is not understood by vectorizer");
4235 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4239 // If this PHINode is not in the header block, then we know that we
4240 // can convert it to select during if-conversion. No need to check if
4241 // the PHIs in this block are induction or reduction variables.
4242 if (*bb != Header) {
4243 // Check that this instruction has no outside users or is an
4244 // identified reduction value with an outside user.
4245 if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
4247 emitAnalysis(VectorizationReport(&*it) <<
4248 "value could not be identified as "
4249 "an induction or reduction variable");
4253 // We only allow if-converted PHIs with exactly two incoming values.
4254 if (Phi->getNumIncomingValues() != 2) {
4255 emitAnalysis(VectorizationReport(&*it)
4256 << "control flow not understood by vectorizer");
4257 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4261 InductionDescriptor ID;
4262 if (InductionDescriptor::isInductionPHI(Phi, SE, ID)) {
4263 Inductions[Phi] = ID;
4264 // Get the widest type.
4266 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4268 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4270 // Int inductions are special because we only allow one IV.
4271 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4272 ID.getStepValue()->isOne() &&
4273 isa<Constant>(ID.getStartValue()) &&
4274 cast<Constant>(ID.getStartValue())->isNullValue()) {
4275 // Use the phi node with the widest type as induction. Use the last
4276 // one if there are multiple (no good reason for doing this other
4277 // than it is expedient). We've checked that it begins at zero and
4278 // steps by one, so this is a canonical induction variable.
4279 if (!Induction || PhiTy == WidestIndTy)
4283 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4285 // Until we explicitly handle the case of an induction variable with
4286 // an outside loop user we have to give up vectorizing this loop.
4287 if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
4288 emitAnalysis(VectorizationReport(&*it) <<
4289 "use of induction value outside of the "
4290 "loop is not handled by vectorizer");
4297 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4299 if (Reductions[Phi].hasUnsafeAlgebra())
4300 Requirements->addUnsafeAlgebraInst(
4301 Reductions[Phi].getUnsafeAlgebraInst());
4302 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4306 emitAnalysis(VectorizationReport(&*it) <<
4307 "value that could not be identified as "
4308 "reduction is used outside the loop");
4309 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4311 }// end of PHI handling
4313 // We handle calls that:
4314 // * Are debug info intrinsics.
4315 // * Have a mapping to an IR intrinsic.
4316 // * Have a vector version available.
4317 CallInst *CI = dyn_cast<CallInst>(it);
4318 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4319 !(CI->getCalledFunction() && TLI &&
4320 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4321 emitAnalysis(VectorizationReport(&*it)
4322 << "call instruction cannot be vectorized");
4323 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4327 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4328 // second argument is the same (i.e. loop invariant)
4330 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4331 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4332 emitAnalysis(VectorizationReport(&*it)
4333 << "intrinsic instruction cannot be vectorized");
4334 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4339 // Check that the instruction return type is vectorizable.
4340 // Also, we can't vectorize extractelement instructions.
4341 if ((!VectorType::isValidElementType(it->getType()) &&
4342 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4343 emitAnalysis(VectorizationReport(&*it)
4344 << "instruction return type cannot be vectorized");
4345 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4349 // Check that the stored type is vectorizable.
4350 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4351 Type *T = ST->getValueOperand()->getType();
4352 if (!VectorType::isValidElementType(T)) {
4353 emitAnalysis(VectorizationReport(ST) <<
4354 "store instruction cannot be vectorized");
4357 if (EnableMemAccessVersioning)
4358 collectStridedAccess(ST);
4361 if (EnableMemAccessVersioning)
4362 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4363 collectStridedAccess(LI);
4365 // Reduction instructions are allowed to have exit users.
4366 // All other instructions must not have external users.
4367 if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
4368 emitAnalysis(VectorizationReport(&*it) <<
4369 "value cannot be used outside the loop");
4378 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4379 if (Inductions.empty()) {
4380 emitAnalysis(VectorizationReport()
4381 << "loop induction variable could not be identified");
4386 // Now we know the widest induction type, check if our found induction
4387 // is the same size. If it's not, unset it here and InnerLoopVectorizer
4388 // will create another.
4389 if (Induction && WidestIndTy != Induction->getType())
4390 Induction = nullptr;
4395 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4396 Value *Ptr = nullptr;
4397 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4398 Ptr = LI->getPointerOperand();
4399 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4400 Ptr = SI->getPointerOperand();
4404 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4408 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4409 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4410 Strides[Ptr] = Stride;
4411 StrideSet.insert(Stride);
4414 void LoopVectorizationLegality::collectLoopUniforms() {
4415 // We now know that the loop is vectorizable!
4416 // Collect variables that will remain uniform after vectorization.
4417 std::vector<Value*> Worklist;
4418 BasicBlock *Latch = TheLoop->getLoopLatch();
4420 // Start with the conditional branch and walk up the block.
4421 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4423 // Also add all consecutive pointer values; these values will be uniform
4424 // after vectorization (and subsequent cleanup) and, until revectorization is
4425 // supported, all dependencies must also be uniform.
4426 for (Loop::block_iterator B = TheLoop->block_begin(),
4427 BE = TheLoop->block_end(); B != BE; ++B)
4428 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4430 if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
4431 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4433 while (!Worklist.empty()) {
4434 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4435 Worklist.pop_back();
4437 // Look at instructions inside this loop.
4438 // Stop when reaching PHI nodes.
4439 // TODO: we need to follow values all over the loop, not only in this block.
4440 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4443 // This is a known uniform.
4446 // Insert all operands.
4447 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4451 bool LoopVectorizationLegality::canVectorizeMemory() {
4452 LAI = &LAA->getInfo(TheLoop, Strides);
4453 auto &OptionalReport = LAI->getReport();
4455 emitAnalysis(VectorizationReport(*OptionalReport));
4456 if (!LAI->canVectorizeMemory())
4459 if (LAI->hasStoreToLoopInvariantAddress()) {
4461 VectorizationReport()
4462 << "write to a loop invariant address could not be vectorized");
4463 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4467 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4468 Preds.add(&LAI->Preds);
4473 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4474 Value *In0 = const_cast<Value*>(V);
4475 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4479 return Inductions.count(PN);
4482 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4483 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4486 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4487 SmallPtrSetImpl<Value *> &SafePtrs) {
4489 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4490 // Check that we don't have a constant expression that can trap as operand.
4491 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4493 if (Constant *C = dyn_cast<Constant>(*OI))
4497 // We might be able to hoist the load.
4498 if (it->mayReadFromMemory()) {
4499 LoadInst *LI = dyn_cast<LoadInst>(it);
4502 if (!SafePtrs.count(LI->getPointerOperand())) {
4503 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4504 MaskedOp.insert(LI);
4511 // We don't predicate stores at the moment.
4512 if (it->mayWriteToMemory()) {
4513 StoreInst *SI = dyn_cast<StoreInst>(it);
4514 // We only support predication of stores in basic blocks with one
4519 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4520 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4522 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4523 !isSinglePredecessor) {
4524 // Build a masked store if it is legal for the target, otherwise scalarize
4526 bool isLegalMaskedOp =
4527 isLegalMaskedStore(SI->getValueOperand()->getType(),
4528 SI->getPointerOperand());
4529 if (isLegalMaskedOp) {
4531 MaskedOp.insert(SI);
4540 // The instructions below can trap.
4541 switch (it->getOpcode()) {
4543 case Instruction::UDiv:
4544 case Instruction::SDiv:
4545 case Instruction::URem:
4546 case Instruction::SRem:
4554 void InterleavedAccessInfo::collectConstStridedAccesses(
4555 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4556 const ValueToValueMap &Strides) {
4557 // Holds load/store instructions in program order.
4558 SmallVector<Instruction *, 16> AccessList;
4560 for (auto *BB : TheLoop->getBlocks()) {
4561 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4563 for (auto &I : *BB) {
4564 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4566 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4570 AccessList.push_back(&I);
4574 if (AccessList.empty())
4577 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4578 for (auto I : AccessList) {
4579 LoadInst *LI = dyn_cast<LoadInst>(I);
4580 StoreInst *SI = dyn_cast<StoreInst>(I);
4582 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4583 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides, Preds);
4585 // The factor of the corresponding interleave group.
4586 unsigned Factor = std::abs(Stride);
4588 // Ignore the access if the factor is too small or too large.
4589 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4592 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Preds, Ptr);
4593 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4594 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4596 // An alignment of 0 means target ABI alignment.
4597 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4599 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4601 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4605 // Analyze interleaved accesses and collect them into interleave groups.
4607 // Notice that the vectorization on interleaved groups will change instruction
4608 // orders and may break dependences. But the memory dependence check guarantees
4609 // that there is no overlap between two pointers of different strides, element
4610 // sizes or underlying bases.
4612 // For pointers sharing the same stride, element size and underlying base, no
4613 // need to worry about Read-After-Write dependences and Write-After-Read
4616 // E.g. The RAW dependence: A[i] = a;
4618 // This won't exist as it is a store-load forwarding conflict, which has
4619 // already been checked and forbidden in the dependence check.
4621 // E.g. The WAR dependence: a = A[i]; // (1)
4623 // The store group of (2) is always inserted at or below (2), and the load group
4624 // of (1) is always inserted at or above (1). The dependence is safe.
4625 void InterleavedAccessInfo::analyzeInterleaving(
4626 const ValueToValueMap &Strides) {
4627 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4629 // Holds all the stride accesses.
4630 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4631 collectConstStridedAccesses(StrideAccesses, Strides);
4633 if (StrideAccesses.empty())
4636 // Holds all interleaved store groups temporarily.
4637 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4639 // Search the load-load/write-write pair B-A in bottom-up order and try to
4640 // insert B into the interleave group of A according to 3 rules:
4641 // 1. A and B have the same stride.
4642 // 2. A and B have the same memory object size.
4643 // 3. B belongs to the group according to the distance.
4645 // The bottom-up order can avoid breaking the Write-After-Write dependences
4646 // between two pointers of the same base.
4647 // E.g. A[i] = a; (1)
4650 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4651 // above (1), which guarantees that (1) is always above (2).
4652 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4654 Instruction *A = I->first;
4655 StrideDescriptor DesA = I->second;
4657 InterleaveGroup *Group = getInterleaveGroup(A);
4659 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4660 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4663 if (A->mayWriteToMemory())
4664 StoreGroups.insert(Group);
4666 for (auto II = std::next(I); II != E; ++II) {
4667 Instruction *B = II->first;
4668 StrideDescriptor DesB = II->second;
4670 // Ignore if B is already in a group or B is a different memory operation.
4671 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4674 // Check the rule 1 and 2.
4675 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4678 // Calculate the distance and prepare for the rule 3.
4679 const SCEVConstant *DistToA =
4680 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4684 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4686 // Skip if the distance is not multiple of size as they are not in the
4688 if (DistanceToA % static_cast<int>(DesA.Size))
4691 // The index of B is the index of A plus the related index to A.
4693 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4695 // Try to insert B into the group.
4696 if (Group->insertMember(B, IndexB, DesB.Align)) {
4697 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4698 << " into the interleave group with" << *A << '\n');
4699 InterleaveGroupMap[B] = Group;
4701 // Set the first load in program order as the insert position.
4702 if (B->mayReadFromMemory())
4703 Group->setInsertPos(B);
4705 } // Iteration on instruction B
4706 } // Iteration on instruction A
4708 // Remove interleaved store groups with gaps.
4709 for (InterleaveGroup *Group : StoreGroups)
4710 if (Group->getNumMembers() != Group->getFactor())
4711 releaseGroup(Group);
4714 LoopVectorizationCostModel::VectorizationFactor
4715 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4716 // Width 1 means no vectorize
4717 VectorizationFactor Factor = { 1U, 0U };
4718 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4719 emitAnalysis(VectorizationReport() <<
4720 "runtime pointer checks needed. Enable vectorization of this "
4721 "loop with '#pragma clang loop vectorize(enable)' when "
4722 "compiling with -Os/-Oz");
4724 "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4728 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4729 emitAnalysis(VectorizationReport() <<
4730 "store that is conditionally executed prevents vectorization");
4731 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4735 // Find the trip count.
4736 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4737 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4739 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4740 unsigned SmallestType, WidestType;
4741 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4742 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4743 unsigned MaxSafeDepDist = -1U;
4744 if (Legal->getMaxSafeDepDistBytes() != -1U)
4745 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4746 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4747 WidestRegister : MaxSafeDepDist);
4748 unsigned MaxVectorSize = WidestRegister / WidestType;
4750 DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
4751 << WidestType << " bits.\n");
4752 DEBUG(dbgs() << "LV: The Widest register is: "
4753 << WidestRegister << " bits.\n");
4755 if (MaxVectorSize == 0) {
4756 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4760 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4761 " into one vector!");
4763 unsigned VF = MaxVectorSize;
4764 if (MaximizeBandwidth && !OptForSize) {
4765 // Collect all viable vectorization factors.
4766 SmallVector<unsigned, 8> VFs;
4767 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
4768 for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
4771 // For each VF calculate its register usage.
4772 auto RUs = calculateRegisterUsage(VFs);
4774 // Select the largest VF which doesn't require more registers than existing
4776 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
4777 for (int i = RUs.size() - 1; i >= 0; --i) {
4778 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
4785 // If we optimize the program for size, avoid creating the tail loop.
4787 // If we are unable to calculate the trip count then don't try to vectorize.
4790 (VectorizationReport() <<
4791 "unable to calculate the loop count due to complex control flow");
4792 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4796 // Find the maximum SIMD width that can fit within the trip count.
4797 VF = TC % MaxVectorSize;
4802 // If the trip count that we found modulo the vectorization factor is not
4803 // zero then we require a tail.
4804 emitAnalysis(VectorizationReport() <<
4805 "cannot optimize for size and vectorize at the "
4806 "same time. Enable vectorization of this loop "
4807 "with '#pragma clang loop vectorize(enable)' "
4808 "when compiling with -Os/-Oz");
4809 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4814 int UserVF = Hints->getWidth();
4816 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4817 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4819 Factor.Width = UserVF;
4823 float Cost = expectedCost(1);
4825 const float ScalarCost = Cost;
4828 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4830 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4831 // Ignore scalar width, because the user explicitly wants vectorization.
4832 if (ForceVectorization && VF > 1) {
4834 Cost = expectedCost(Width) / (float)Width;
4837 for (unsigned i=2; i <= VF; i*=2) {
4838 // Notice that the vector loop needs to be executed less times, so
4839 // we need to divide the cost of the vector loops by the width of
4840 // the vector elements.
4841 float VectorCost = expectedCost(i) / (float)i;
4842 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4843 (int)VectorCost << ".\n");
4844 if (VectorCost < Cost) {
4850 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4851 << "LV: Vectorization seems to be not beneficial, "
4852 << "but was forced by a user.\n");
4853 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4854 Factor.Width = Width;
4855 Factor.Cost = Width * Cost;
4859 std::pair<unsigned, unsigned>
4860 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
4861 unsigned MinWidth = -1U;
4862 unsigned MaxWidth = 8;
4863 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4866 for (Loop::block_iterator bb = TheLoop->block_begin(),
4867 be = TheLoop->block_end(); bb != be; ++bb) {
4868 BasicBlock *BB = *bb;
4870 // For each instruction in the loop.
4871 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4872 Type *T = it->getType();
4874 // Skip ignored values.
4875 if (ValuesToIgnore.count(&*it))
4878 // Only examine Loads, Stores and PHINodes.
4879 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4882 // Examine PHI nodes that are reduction variables. Update the type to
4883 // account for the recurrence type.
4884 if (PHINode *PN = dyn_cast<PHINode>(it)) {
4885 if (!Legal->getReductionVars()->count(PN))
4887 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4888 T = RdxDesc.getRecurrenceType();
4891 // Examine the stored values.
4892 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4893 T = ST->getValueOperand()->getType();
4895 // Ignore loaded pointer types and stored pointer types that are not
4896 // consecutive. However, we do want to take consecutive stores/loads of
4897 // pointer vectors into account.
4898 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
4901 MinWidth = std::min(MinWidth,
4902 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4903 MaxWidth = std::max(MaxWidth,
4904 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4908 return {MinWidth, MaxWidth};
4911 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4913 unsigned LoopCost) {
4915 // -- The interleave heuristics --
4916 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4917 // There are many micro-architectural considerations that we can't predict
4918 // at this level. For example, frontend pressure (on decode or fetch) due to
4919 // code size, or the number and capabilities of the execution ports.
4921 // We use the following heuristics to select the interleave count:
4922 // 1. If the code has reductions, then we interleave to break the cross
4923 // iteration dependency.
4924 // 2. If the loop is really small, then we interleave to reduce the loop
4926 // 3. We don't interleave if we think that we will spill registers to memory
4927 // due to the increased register pressure.
4929 // When we optimize for size, we don't interleave.
4933 // We used the distance for the interleave count.
4934 if (Legal->getMaxSafeDepDistBytes() != -1U)
4937 // Do not interleave loops with a relatively small trip count.
4938 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4939 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4942 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4943 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4947 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4948 TargetNumRegisters = ForceTargetNumScalarRegs;
4950 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4951 TargetNumRegisters = ForceTargetNumVectorRegs;
4954 RegisterUsage R = calculateRegisterUsage({VF})[0];
4955 // We divide by these constants so assume that we have at least one
4956 // instruction that uses at least one register.
4957 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4958 R.NumInstructions = std::max(R.NumInstructions, 1U);
4960 // We calculate the interleave count using the following formula.
4961 // Subtract the number of loop invariants from the number of available
4962 // registers. These registers are used by all of the interleaved instances.
4963 // Next, divide the remaining registers by the number of registers that is
4964 // required by the loop, in order to estimate how many parallel instances
4965 // fit without causing spills. All of this is rounded down if necessary to be
4966 // a power of two. We want power of two interleave count to simplify any
4967 // addressing operations or alignment considerations.
4968 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4971 // Don't count the induction variable as interleaved.
4972 if (EnableIndVarRegisterHeur)
4973 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4974 std::max(1U, (R.MaxLocalUsers - 1)));
4976 // Clamp the interleave ranges to reasonable counts.
4977 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4979 // Check if the user has overridden the max.
4981 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4982 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4984 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4985 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4988 // If we did not calculate the cost for VF (because the user selected the VF)
4989 // then we calculate the cost of VF here.
4991 LoopCost = expectedCost(VF);
4993 // Clamp the calculated IC to be between the 1 and the max interleave count
4994 // that the target allows.
4995 if (IC > MaxInterleaveCount)
4996 IC = MaxInterleaveCount;
5000 // Interleave if we vectorized this loop and there is a reduction that could
5001 // benefit from interleaving.
5002 if (VF > 1 && Legal->getReductionVars()->size()) {
5003 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5007 // Note that if we've already vectorized the loop we will have done the
5008 // runtime check and so interleaving won't require further checks.
5009 bool InterleavingRequiresRuntimePointerCheck =
5010 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
5012 // We want to interleave small loops in order to reduce the loop overhead and
5013 // potentially expose ILP opportunities.
5014 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5015 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
5016 // We assume that the cost overhead is 1 and we use the cost model
5017 // to estimate the cost of the loop and interleave until the cost of the
5018 // loop overhead is about 5% of the cost of the loop.
5020 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5022 // Interleave until store/load ports (estimated by max interleave count) are
5024 unsigned NumStores = Legal->getNumStores();
5025 unsigned NumLoads = Legal->getNumLoads();
5026 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5027 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5029 // If we have a scalar reduction (vector reductions are already dealt with
5030 // by this point), we can increase the critical path length if the loop
5031 // we're interleaving is inside another loop. Limit, by default to 2, so the
5032 // critical path only gets increased by one reduction operation.
5033 if (Legal->getReductionVars()->size() &&
5034 TheLoop->getLoopDepth() > 1) {
5035 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5036 SmallIC = std::min(SmallIC, F);
5037 StoresIC = std::min(StoresIC, F);
5038 LoadsIC = std::min(LoadsIC, F);
5041 if (EnableLoadStoreRuntimeInterleave &&
5042 std::max(StoresIC, LoadsIC) > SmallIC) {
5043 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5044 return std::max(StoresIC, LoadsIC);
5047 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5051 // Interleave if this is a large loop (small loops are already dealt with by
5053 // point) that could benefit from interleaving.
5054 bool HasReductions = (Legal->getReductionVars()->size() > 0);
5055 if (TTI.enableAggressiveInterleaving(HasReductions)) {
5056 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5060 DEBUG(dbgs() << "LV: Not Interleaving.\n");
5064 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5065 LoopVectorizationCostModel::calculateRegisterUsage(
5066 const SmallVector<unsigned, 8> &VFs) {
5067 // This function calculates the register usage by measuring the highest number
5068 // of values that are alive at a single location. Obviously, this is a very
5069 // rough estimation. We scan the loop in a topological order in order and
5070 // assign a number to each instruction. We use RPO to ensure that defs are
5071 // met before their users. We assume that each instruction that has in-loop
5072 // users starts an interval. We record every time that an in-loop value is
5073 // used, so we have a list of the first and last occurrences of each
5074 // instruction. Next, we transpose this data structure into a multi map that
5075 // holds the list of intervals that *end* at a specific location. This multi
5076 // map allows us to perform a linear search. We scan the instructions linearly
5077 // and record each time that a new interval starts, by placing it in a set.
5078 // If we find this value in the multi-map then we remove it from the set.
5079 // The max register usage is the maximum size of the set.
5080 // We also search for instructions that are defined outside the loop, but are
5081 // used inside the loop. We need this number separately from the max-interval
5082 // usage number because when we unroll, loop-invariant values do not take
5084 LoopBlocksDFS DFS(TheLoop);
5088 RU.NumInstructions = 0;
5090 // Each 'key' in the map opens a new interval. The values
5091 // of the map are the index of the 'last seen' usage of the
5092 // instruction that is the key.
5093 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5094 // Maps instruction to its index.
5095 DenseMap<unsigned, Instruction*> IdxToInstr;
5096 // Marks the end of each interval.
5097 IntervalMap EndPoint;
5098 // Saves the list of instruction indices that are used in the loop.
5099 SmallSet<Instruction*, 8> Ends;
5100 // Saves the list of values that are used in the loop but are
5101 // defined outside the loop, such as arguments and constants.
5102 SmallPtrSet<Value*, 8> LoopInvariants;
5105 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5106 be = DFS.endRPO(); bb != be; ++bb) {
5107 RU.NumInstructions += (*bb)->size();
5108 for (Instruction &I : **bb) {
5109 IdxToInstr[Index++] = &I;
5111 // Save the end location of each USE.
5112 for (unsigned i = 0; i < I.getNumOperands(); ++i) {
5113 Value *U = I.getOperand(i);
5114 Instruction *Instr = dyn_cast<Instruction>(U);
5116 // Ignore non-instruction values such as arguments, constants, etc.
5117 if (!Instr) continue;
5119 // If this instruction is outside the loop then record it and continue.
5120 if (!TheLoop->contains(Instr)) {
5121 LoopInvariants.insert(Instr);
5125 // Overwrite previous end points.
5126 EndPoint[Instr] = Index;
5132 // Saves the list of intervals that end with the index in 'key'.
5133 typedef SmallVector<Instruction*, 2> InstrList;
5134 DenseMap<unsigned, InstrList> TransposeEnds;
5136 // Transpose the EndPoints to a list of values that end at each index.
5137 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5139 TransposeEnds[it->second].push_back(it->first);
5141 SmallSet<Instruction*, 8> OpenIntervals;
5143 // Get the size of the widest register.
5144 unsigned MaxSafeDepDist = -1U;
5145 if (Legal->getMaxSafeDepDistBytes() != -1U)
5146 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5147 unsigned WidestRegister =
5148 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
5149 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5151 SmallVector<RegisterUsage, 8> RUs(VFs.size());
5152 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
5154 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5156 // A lambda that gets the register usage for the given type and VF.
5157 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
5158 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5159 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5162 for (unsigned int i = 0; i < Index; ++i) {
5163 Instruction *I = IdxToInstr[i];
5164 // Ignore instructions that are never used within the loop.
5165 if (!Ends.count(I)) continue;
5167 // Skip ignored values.
5168 if (ValuesToIgnore.count(I))
5171 // Remove all of the instructions that end at this location.
5172 InstrList &List = TransposeEnds[i];
5173 for (unsigned int j = 0, e = List.size(); j < e; ++j)
5174 OpenIntervals.erase(List[j]);
5176 // For each VF find the maximum usage of registers.
5177 for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5179 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
5183 // Count the number of live interals.
5184 unsigned RegUsage = 0;
5185 for (auto Inst : OpenIntervals)
5186 RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
5187 MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
5190 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
5191 << OpenIntervals.size() << '\n');
5193 // Add the current instruction to the list of open intervals.
5194 OpenIntervals.insert(I);
5197 for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
5198 unsigned Invariant = 0;
5200 Invariant = LoopInvariants.size();
5202 for (auto Inst : LoopInvariants)
5203 Invariant += GetRegUsage(Inst->getType(), VFs[i]);
5206 DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
5207 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
5208 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5209 DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
5211 RU.LoopInvariantRegs = Invariant;
5212 RU.MaxLocalUsers = MaxUsages[i];
5219 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5223 for (Loop::block_iterator bb = TheLoop->block_begin(),
5224 be = TheLoop->block_end(); bb != be; ++bb) {
5225 unsigned BlockCost = 0;
5226 BasicBlock *BB = *bb;
5228 // For each instruction in the old loop.
5229 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5230 // Skip dbg intrinsics.
5231 if (isa<DbgInfoIntrinsic>(it))
5234 // Skip ignored values.
5235 if (ValuesToIgnore.count(&*it))
5238 unsigned C = getInstructionCost(&*it, VF);
5240 // Check if we should override the cost.
5241 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5242 C = ForceTargetInstructionCost;
5245 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5246 VF << " For instruction: " << *it << '\n');
5249 // We assume that if-converted blocks have a 50% chance of being executed.
5250 // When the code is scalar then some of the blocks are avoided due to CF.
5251 // When the code is vectorized we execute all code paths.
5252 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5261 /// \brief Check whether the address computation for a non-consecutive memory
5262 /// access looks like an unlikely candidate for being merged into the indexing
5265 /// We look for a GEP which has one index that is an induction variable and all
5266 /// other indices are loop invariant. If the stride of this access is also
5267 /// within a small bound we decide that this address computation can likely be
5268 /// merged into the addressing mode.
5269 /// In all other cases, we identify the address computation as complex.
5270 static bool isLikelyComplexAddressComputation(Value *Ptr,
5271 LoopVectorizationLegality *Legal,
5272 ScalarEvolution *SE,
5273 const Loop *TheLoop) {
5274 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5278 // We are looking for a gep with all loop invariant indices except for one
5279 // which should be an induction variable.
5280 unsigned NumOperands = Gep->getNumOperands();
5281 for (unsigned i = 1; i < NumOperands; ++i) {
5282 Value *Opd = Gep->getOperand(i);
5283 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5284 !Legal->isInductionVariable(Opd))
5288 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5289 // can likely be merged into the address computation.
5290 unsigned MaxMergeDistance = 64;
5292 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5296 // Check the step is constant.
5297 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5298 // Calculate the pointer stride and check if it is consecutive.
5299 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5303 const APInt &APStepVal = C->getValue()->getValue();
5305 // Huge step value - give up.
5306 if (APStepVal.getBitWidth() > 64)
5309 int64_t StepVal = APStepVal.getSExtValue();
5311 return StepVal > MaxMergeDistance;
5314 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5315 return Legal->hasStride(I->getOperand(0)) ||
5316 Legal->hasStride(I->getOperand(1));
5320 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5321 // If we know that this instruction will remain uniform, check the cost of
5322 // the scalar version.
5323 if (Legal->isUniformAfterVectorization(I))
5326 Type *RetTy = I->getType();
5327 if (VF > 1 && MinBWs.count(I))
5328 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
5329 Type *VectorTy = ToVectorTy(RetTy, VF);
5331 // TODO: We need to estimate the cost of intrinsic calls.
5332 switch (I->getOpcode()) {
5333 case Instruction::GetElementPtr:
5334 // We mark this instruction as zero-cost because the cost of GEPs in
5335 // vectorized code depends on whether the corresponding memory instruction
5336 // is scalarized or not. Therefore, we handle GEPs with the memory
5337 // instruction cost.
5339 case Instruction::Br: {
5340 return TTI.getCFInstrCost(I->getOpcode());
5342 case Instruction::PHI:
5343 //TODO: IF-converted IFs become selects.
5345 case Instruction::Add:
5346 case Instruction::FAdd:
5347 case Instruction::Sub:
5348 case Instruction::FSub:
5349 case Instruction::Mul:
5350 case Instruction::FMul:
5351 case Instruction::UDiv:
5352 case Instruction::SDiv:
5353 case Instruction::FDiv:
5354 case Instruction::URem:
5355 case Instruction::SRem:
5356 case Instruction::FRem:
5357 case Instruction::Shl:
5358 case Instruction::LShr:
5359 case Instruction::AShr:
5360 case Instruction::And:
5361 case Instruction::Or:
5362 case Instruction::Xor: {
5363 // Since we will replace the stride by 1 the multiplication should go away.
5364 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5366 // Certain instructions can be cheaper to vectorize if they have a constant
5367 // second vector operand. One example of this are shifts on x86.
5368 TargetTransformInfo::OperandValueKind Op1VK =
5369 TargetTransformInfo::OK_AnyValue;
5370 TargetTransformInfo::OperandValueKind Op2VK =
5371 TargetTransformInfo::OK_AnyValue;
5372 TargetTransformInfo::OperandValueProperties Op1VP =
5373 TargetTransformInfo::OP_None;
5374 TargetTransformInfo::OperandValueProperties Op2VP =
5375 TargetTransformInfo::OP_None;
5376 Value *Op2 = I->getOperand(1);
5378 // Check for a splat of a constant or for a non uniform vector of constants.
5379 if (isa<ConstantInt>(Op2)) {
5380 ConstantInt *CInt = cast<ConstantInt>(Op2);
5381 if (CInt && CInt->getValue().isPowerOf2())
5382 Op2VP = TargetTransformInfo::OP_PowerOf2;
5383 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5384 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5385 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5386 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5388 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5389 if (CInt && CInt->getValue().isPowerOf2())
5390 Op2VP = TargetTransformInfo::OP_PowerOf2;
5391 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5395 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5398 case Instruction::Select: {
5399 SelectInst *SI = cast<SelectInst>(I);
5400 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5401 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5402 Type *CondTy = SI->getCondition()->getType();
5404 CondTy = VectorType::get(CondTy, VF);
5406 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5408 case Instruction::ICmp:
5409 case Instruction::FCmp: {
5410 Type *ValTy = I->getOperand(0)->getType();
5411 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
5412 auto It = MinBWs.find(Op0AsInstruction);
5413 if (VF > 1 && It != MinBWs.end())
5414 ValTy = IntegerType::get(ValTy->getContext(), It->second);
5415 VectorTy = ToVectorTy(ValTy, VF);
5416 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5418 case Instruction::Store:
5419 case Instruction::Load: {
5420 StoreInst *SI = dyn_cast<StoreInst>(I);
5421 LoadInst *LI = dyn_cast<LoadInst>(I);
5422 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5424 VectorTy = ToVectorTy(ValTy, VF);
5426 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5427 unsigned AS = SI ? SI->getPointerAddressSpace() :
5428 LI->getPointerAddressSpace();
5429 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5430 // We add the cost of address computation here instead of with the gep
5431 // instruction because only here we know whether the operation is
5434 return TTI.getAddressComputationCost(VectorTy) +
5435 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5437 // For an interleaved access, calculate the total cost of the whole
5438 // interleave group.
5439 if (Legal->isAccessInterleaved(I)) {
5440 auto Group = Legal->getInterleavedAccessGroup(I);
5441 assert(Group && "Fail to get an interleaved access group.");
5443 // Only calculate the cost once at the insert position.
5444 if (Group->getInsertPos() != I)
5447 unsigned InterleaveFactor = Group->getFactor();
5449 VectorType::get(VectorTy->getVectorElementType(),
5450 VectorTy->getVectorNumElements() * InterleaveFactor);
5452 // Holds the indices of existing members in an interleaved load group.
5453 // An interleaved store group doesn't need this as it dones't allow gaps.
5454 SmallVector<unsigned, 4> Indices;
5456 for (unsigned i = 0; i < InterleaveFactor; i++)
5457 if (Group->getMember(i))
5458 Indices.push_back(i);
5461 // Calculate the cost of the whole interleaved group.
5462 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5463 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5464 Group->getAlignment(), AS);
5466 if (Group->isReverse())
5468 Group->getNumMembers() *
5469 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5471 // FIXME: The interleaved load group with a huge gap could be even more
5472 // expensive than scalar operations. Then we could ignore such group and
5473 // use scalar operations instead.
5477 // Scalarized loads/stores.
5478 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5479 bool Reverse = ConsecutiveStride < 0;
5480 const DataLayout &DL = I->getModule()->getDataLayout();
5481 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5482 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5483 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5484 bool IsComplexComputation =
5485 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5487 // The cost of extracting from the value vector and pointer vector.
5488 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5489 for (unsigned i = 0; i < VF; ++i) {
5490 // The cost of extracting the pointer operand.
5491 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5492 // In case of STORE, the cost of ExtractElement from the vector.
5493 // In case of LOAD, the cost of InsertElement into the returned
5495 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5496 Instruction::InsertElement,
5500 // The cost of the scalar loads/stores.
5501 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5502 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5507 // Wide load/stores.
5508 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5509 if (Legal->isMaskRequired(I))
5510 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5513 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5516 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5520 case Instruction::ZExt:
5521 case Instruction::SExt:
5522 case Instruction::FPToUI:
5523 case Instruction::FPToSI:
5524 case Instruction::FPExt:
5525 case Instruction::PtrToInt:
5526 case Instruction::IntToPtr:
5527 case Instruction::SIToFP:
5528 case Instruction::UIToFP:
5529 case Instruction::Trunc:
5530 case Instruction::FPTrunc:
5531 case Instruction::BitCast: {
5532 // We optimize the truncation of induction variable.
5533 // The cost of these is the same as the scalar operation.
5534 if (I->getOpcode() == Instruction::Trunc &&
5535 Legal->isInductionVariable(I->getOperand(0)))
5536 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5537 I->getOperand(0)->getType());
5539 Type *SrcScalarTy = I->getOperand(0)->getType();
5540 Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
5541 if (VF > 1 && MinBWs.count(I)) {
5542 // This cast is going to be shrunk. This may remove the cast or it might
5543 // turn it into slightly different cast. For example, if MinBW == 16,
5544 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
5546 // Calculate the modified src and dest types.
5547 Type *MinVecTy = VectorTy;
5548 if (I->getOpcode() == Instruction::Trunc) {
5549 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
5550 VectorTy = largestIntegerVectorType(ToVectorTy(I->getType(), VF),
5552 } else if (I->getOpcode() == Instruction::ZExt ||
5553 I->getOpcode() == Instruction::SExt) {
5554 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
5555 VectorTy = smallestIntegerVectorType(ToVectorTy(I->getType(), VF),
5560 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5562 case Instruction::Call: {
5563 bool NeedToScalarize;
5564 CallInst *CI = cast<CallInst>(I);
5565 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5566 if (getIntrinsicIDForCall(CI, TLI))
5567 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5571 // We are scalarizing the instruction. Return the cost of the scalar
5572 // instruction, plus the cost of insert and extract into vector
5573 // elements, times the vector width.
5576 if (!RetTy->isVoidTy() && VF != 1) {
5577 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5579 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5582 // The cost of inserting the results plus extracting each one of the
5584 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5587 // The cost of executing VF copies of the scalar instruction. This opcode
5588 // is unknown. Assume that it is the same as 'mul'.
5589 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5595 char LoopVectorize::ID = 0;
5596 static const char lv_name[] = "Loop Vectorization";
5597 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5598 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5599 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
5600 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5601 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
5602 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5603 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5604 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5605 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5606 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5607 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5608 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5609 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5610 INITIALIZE_PASS_DEPENDENCY(DemandedBits)
5611 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5614 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5615 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5619 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5620 // Check for a store.
5621 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5622 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5624 // Check for a load.
5625 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5626 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5632 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5633 bool IfPredicateStore) {
5634 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5635 // Holds vector parameters or scalars, in case of uniform vals.
5636 SmallVector<VectorParts, 4> Params;
5638 setDebugLocFromInst(Builder, Instr);
5640 // Find all of the vectorized parameters.
5641 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5642 Value *SrcOp = Instr->getOperand(op);
5644 // If we are accessing the old induction variable, use the new one.
5645 if (SrcOp == OldInduction) {
5646 Params.push_back(getVectorValue(SrcOp));
5650 // Try using previously calculated values.
5651 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5653 // If the src is an instruction that appeared earlier in the basic block
5654 // then it should already be vectorized.
5655 if (SrcInst && OrigLoop->contains(SrcInst)) {
5656 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5657 // The parameter is a vector value from earlier.
5658 Params.push_back(WidenMap.get(SrcInst));
5660 // The parameter is a scalar from outside the loop. Maybe even a constant.
5661 VectorParts Scalars;
5662 Scalars.append(UF, SrcOp);
5663 Params.push_back(Scalars);
5667 assert(Params.size() == Instr->getNumOperands() &&
5668 "Invalid number of operands");
5670 // Does this instruction return a value ?
5671 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5673 Value *UndefVec = IsVoidRetTy ? nullptr :
5674 UndefValue::get(Instr->getType());
5675 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5676 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5679 if (IfPredicateStore) {
5680 assert(Instr->getParent()->getSinglePredecessor() &&
5681 "Only support single predecessor blocks");
5682 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5683 Instr->getParent());
5686 // For each vector unroll 'part':
5687 for (unsigned Part = 0; Part < UF; ++Part) {
5688 // For each scalar that we create:
5690 // Start an "if (pred) a[i] = ..." block.
5691 Value *Cmp = nullptr;
5692 if (IfPredicateStore) {
5693 if (Cond[Part]->getType()->isVectorTy())
5695 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5696 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5697 ConstantInt::get(Cond[Part]->getType(), 1));
5700 Instruction *Cloned = Instr->clone();
5702 Cloned->setName(Instr->getName() + ".cloned");
5703 // Replace the operands of the cloned instructions with extracted scalars.
5704 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5705 Value *Op = Params[op][Part];
5706 Cloned->setOperand(op, Op);
5709 // Place the cloned scalar in the new loop.
5710 Builder.Insert(Cloned);
5712 // If the original scalar returns a value we need to place it in a vector
5713 // so that future users will be able to use it.
5715 VecResults[Part] = Cloned;
5718 if (IfPredicateStore)
5719 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
5724 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5725 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5726 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5728 return scalarizeInstruction(Instr, IfPredicateStore);
5731 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5735 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5739 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5740 // When unrolling and the VF is 1, we only need to add a simple scalar.
5741 Type *ITy = Val->getType();
5742 assert(!ITy->isVectorTy() && "Val must be a scalar");
5743 Constant *C = ConstantInt::get(ITy, StartIdx);
5744 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");