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/LoopVectorize.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/Hashing.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/Optional.h"
54 #include "llvm/ADT/SCCIterator.h"
55 #include "llvm/ADT/SetVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/SmallSet.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/Statistic.h"
60 #include "llvm/ADT/StringExtras.h"
61 #include "llvm/Analysis/CodeMetrics.h"
62 #include "llvm/Analysis/GlobalsModRef.h"
63 #include "llvm/Analysis/LoopInfo.h"
64 #include "llvm/Analysis/LoopIterator.h"
65 #include "llvm/Analysis/LoopPass.h"
66 #include "llvm/Analysis/ScalarEvolutionExpander.h"
67 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
68 #include "llvm/Analysis/ValueTracking.h"
69 #include "llvm/Analysis/VectorUtils.h"
70 #include "llvm/IR/Constants.h"
71 #include "llvm/IR/DataLayout.h"
72 #include "llvm/IR/DebugInfo.h"
73 #include "llvm/IR/DerivedTypes.h"
74 #include "llvm/IR/DiagnosticInfo.h"
75 #include "llvm/IR/Dominators.h"
76 #include "llvm/IR/Function.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/IR/ValueHandle.h"
87 #include "llvm/IR/Verifier.h"
88 #include "llvm/Pass.h"
89 #include "llvm/Support/BranchProbability.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Debug.h"
92 #include "llvm/Support/raw_ostream.h"
93 #include "llvm/Transforms/Scalar.h"
94 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
95 #include "llvm/Transforms/Utils/Local.h"
96 #include "llvm/Transforms/Utils/LoopSimplify.h"
97 #include "llvm/Transforms/Utils/LoopUtils.h"
98 #include "llvm/Transforms/Utils/LoopVersioning.h"
99 #include "llvm/Transforms/Vectorize.h"
104 using namespace llvm;
105 using namespace llvm::PatternMatch;
107 #define LV_NAME "loop-vectorize"
108 #define DEBUG_TYPE LV_NAME
110 STATISTIC(LoopsVectorized, "Number of loops vectorized");
111 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
114 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
115 cl::desc("Enable if-conversion during vectorization."));
117 /// We don't vectorize loops with a known constant trip count below this number.
118 static cl::opt<unsigned> TinyTripCountVectorThreshold(
119 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
120 cl::desc("Don't vectorize loops with a constant "
121 "trip count that is smaller than this "
124 static cl::opt<bool> MaximizeBandwidth(
125 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
126 cl::desc("Maximize bandwidth when selecting vectorization factor which "
127 "will be determined by the smallest type in loop."));
129 static cl::opt<bool> EnableInterleavedMemAccesses(
130 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
131 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
133 /// Maximum factor for an interleaved memory access.
134 static cl::opt<unsigned> MaxInterleaveGroupFactor(
135 "max-interleave-group-factor", cl::Hidden,
136 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
139 /// We don't interleave loops with a known constant trip count below this
141 static const unsigned TinyTripCountInterleaveThreshold = 128;
143 static cl::opt<unsigned> ForceTargetNumScalarRegs(
144 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
145 cl::desc("A flag that overrides the target's number of scalar registers."));
147 static cl::opt<unsigned> ForceTargetNumVectorRegs(
148 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
149 cl::desc("A flag that overrides the target's number of vector registers."));
151 /// Maximum vectorization interleave count.
152 static const unsigned MaxInterleaveFactor = 16;
154 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
155 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
156 cl::desc("A flag that overrides the target's max interleave factor for "
159 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
160 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
161 cl::desc("A flag that overrides the target's max interleave factor for "
162 "vectorized loops."));
164 static cl::opt<unsigned> ForceTargetInstructionCost(
165 "force-target-instruction-cost", cl::init(0), cl::Hidden,
166 cl::desc("A flag that overrides the target's expected cost for "
167 "an instruction to a single constant value. Mostly "
168 "useful for getting consistent testing."));
170 static cl::opt<unsigned> SmallLoopCost(
171 "small-loop-cost", cl::init(20), cl::Hidden,
173 "The cost of a loop that is considered 'small' by the interleaver."));
175 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
176 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
177 cl::desc("Enable the use of the block frequency analysis to access PGO "
178 "heuristics minimizing code growth in cold regions and being more "
179 "aggressive in hot regions."));
181 // Runtime interleave loops for load/store throughput.
182 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
183 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
185 "Enable runtime interleaving until load/store ports are saturated"));
187 /// The number of stores in a loop that are allowed to need predication.
188 static cl::opt<unsigned> NumberOfStoresToPredicate(
189 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
190 cl::desc("Max number of stores to be predicated behind an if."));
192 static cl::opt<bool> EnableIndVarRegisterHeur(
193 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
194 cl::desc("Count the induction variable only once when interleaving"));
196 static cl::opt<bool> EnableCondStoresVectorization(
197 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
198 cl::desc("Enable if predication of stores during vectorization."));
200 static cl::opt<unsigned> MaxNestedScalarReductionIC(
201 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
202 cl::desc("The maximum interleave count to use when interleaving a scalar "
203 "reduction in a nested loop."));
205 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
206 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
207 cl::desc("The maximum allowed number of runtime memory checks with a "
208 "vectorize(enable) pragma."));
210 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
211 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
212 cl::desc("The maximum number of SCEV checks allowed."));
214 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
215 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
216 cl::desc("The maximum number of SCEV checks allowed with a "
217 "vectorize(enable) pragma"));
219 /// Create an analysis remark that explains why vectorization failed
221 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
222 /// RemarkName is the identifier for the remark. If \p I is passed it is an
223 /// instruction that prevents vectorization. Otherwise \p TheLoop is used for
224 /// the location of the remark. \return the remark object that can be
226 static OptimizationRemarkAnalysis
227 createMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
228 Instruction *I = nullptr) {
229 Value *CodeRegion = TheLoop->getHeader();
230 DebugLoc DL = TheLoop->getStartLoc();
233 CodeRegion = I->getParent();
234 // If there is no debug location attached to the instruction, revert back to
236 if (I->getDebugLoc())
237 DL = I->getDebugLoc();
240 OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
241 R << "loop not vectorized: ";
247 // Forward declarations.
248 class LoopVectorizeHints;
249 class LoopVectorizationLegality;
250 class LoopVectorizationCostModel;
251 class LoopVectorizationRequirements;
253 /// Returns true if the given loop body has a cycle, excluding the loop
255 static bool hasCyclesInLoopBody(const Loop &L) {
259 for (const auto &SCC :
260 make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L),
261 scc_iterator<Loop, LoopBodyTraits>::end(L))) {
262 if (SCC.size() > 1) {
263 DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n");
271 /// A helper function for converting Scalar types to vector types.
272 /// If the incoming type is void, we return void. If the VF is 1, we return
274 static Type *ToVectorTy(Type *Scalar, unsigned VF) {
275 if (Scalar->isVoidTy() || VF == 1)
277 return VectorType::get(Scalar, VF);
280 // FIXME: The following helper functions have multiple implementations
281 // in the project. They can be effectively organized in a common Load/Store
284 /// A helper function that returns the pointer operand of a load or store
286 static Value *getPointerOperand(Value *I) {
287 if (auto *LI = dyn_cast<LoadInst>(I))
288 return LI->getPointerOperand();
289 if (auto *SI = dyn_cast<StoreInst>(I))
290 return SI->getPointerOperand();
294 /// A helper function that returns the type of loaded or stored value.
295 static Type *getMemInstValueType(Value *I) {
296 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
297 "Expected Load or Store instruction");
298 if (auto *LI = dyn_cast<LoadInst>(I))
299 return LI->getType();
300 return cast<StoreInst>(I)->getValueOperand()->getType();
303 /// A helper function that returns the alignment of load or store instruction.
304 static unsigned getMemInstAlignment(Value *I) {
305 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
306 "Expected Load or Store instruction");
307 if (auto *LI = dyn_cast<LoadInst>(I))
308 return LI->getAlignment();
309 return cast<StoreInst>(I)->getAlignment();
312 /// A helper function that returns the address space of the pointer operand of
313 /// load or store instruction.
314 static unsigned getMemInstAddressSpace(Value *I) {
315 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
316 "Expected Load or Store instruction");
317 if (auto *LI = dyn_cast<LoadInst>(I))
318 return LI->getPointerAddressSpace();
319 return cast<StoreInst>(I)->getPointerAddressSpace();
322 /// A helper function that returns true if the given type is irregular. The
323 /// type is irregular if its allocated size doesn't equal the store size of an
324 /// element of the corresponding vector type at the given vectorization factor.
325 static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
327 // Determine if an array of VF elements of type Ty is "bitcast compatible"
328 // with a <VF x Ty> vector.
330 auto *VectorTy = VectorType::get(Ty, VF);
331 return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
334 // If the vectorization factor is one, we just check if an array of type Ty
335 // requires padding between elements.
336 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
339 /// A helper function that returns the reciprocal of the block probability of
340 /// predicated blocks. If we return X, we are assuming the predicated block
341 /// will execute once for for every X iterations of the loop header.
343 /// TODO: We should use actual block probability here, if available. Currently,
344 /// we always assume predicated blocks have a 50% chance of executing.
345 static unsigned getReciprocalPredBlockProb() { return 2; }
347 /// A helper function that adds a 'fast' flag to floating-point operations.
348 static Value *addFastMathFlag(Value *V) {
349 if (isa<FPMathOperator>(V)) {
351 Flags.setUnsafeAlgebra();
352 cast<Instruction>(V)->setFastMathFlags(Flags);
357 /// A helper function that returns an integer or floating-point constant with
359 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
360 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
361 : ConstantFP::get(Ty, C);
364 /// InnerLoopVectorizer vectorizes loops which contain only one basic
365 /// block to a specified vectorization factor (VF).
366 /// This class performs the widening of scalars into vectors, or multiple
367 /// scalars. This class also implements the following features:
368 /// * It inserts an epilogue loop for handling loops that don't have iteration
369 /// counts that are known to be a multiple of the vectorization factor.
370 /// * It handles the code generation for reduction variables.
371 /// * Scalarization (implementation using scalars) of un-vectorizable
373 /// InnerLoopVectorizer does not perform any vectorization-legality
374 /// checks, and relies on the caller to check for the different legality
375 /// aspects. The InnerLoopVectorizer relies on the
376 /// LoopVectorizationLegality class to provide information about the induction
377 /// and reduction variables that were found to a given vectorization factor.
378 class InnerLoopVectorizer {
380 InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
381 LoopInfo *LI, DominatorTree *DT,
382 const TargetLibraryInfo *TLI,
383 const TargetTransformInfo *TTI, AssumptionCache *AC,
384 OptimizationRemarkEmitter *ORE, unsigned VecWidth,
385 unsigned UnrollFactor, LoopVectorizationLegality *LVL,
386 LoopVectorizationCostModel *CM)
387 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
388 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
389 Builder(PSE.getSE()->getContext()), Induction(nullptr),
390 OldInduction(nullptr), VectorLoopValueMap(UnrollFactor, VecWidth),
391 TripCount(nullptr), VectorTripCount(nullptr), Legal(LVL), Cost(CM),
392 AddedSafetyChecks(false) {}
394 // Perform the actual loop widening (vectorization).
396 // Create a new empty loop. Unlink the old loop and connect the new one.
398 // Widen each instruction in the old loop to a new one in the new loop.
402 // Return true if any runtime check is added.
403 bool areSafetyChecksAdded() { return AddedSafetyChecks; }
405 virtual ~InnerLoopVectorizer() {}
408 /// A small list of PHINodes.
409 typedef SmallVector<PHINode *, 4> PhiVector;
411 /// A type for vectorized values in the new loop. Each value from the
412 /// original loop, when vectorized, is represented by UF vector values in the
413 /// new unrolled loop, where UF is the unroll factor.
414 typedef SmallVector<Value *, 2> VectorParts;
416 /// A type for scalarized values in the new loop. Each value from the
417 /// original loop, when scalarized, is represented by UF x VF scalar values
418 /// in the new unrolled loop, where UF is the unroll factor and VF is the
419 /// vectorization factor.
420 typedef SmallVector<SmallVector<Value *, 4>, 2> ScalarParts;
422 // When we if-convert we need to create edge masks. We have to cache values
423 // so that we don't end up with exponential recursion/IR.
424 typedef DenseMap<std::pair<BasicBlock *, BasicBlock *>, VectorParts>
427 /// Create an empty loop, based on the loop ranges of the old loop.
428 void createEmptyLoop();
430 /// Set up the values of the IVs correctly when exiting the vector loop.
431 void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
432 Value *CountRoundDown, Value *EndValue,
433 BasicBlock *MiddleBlock);
435 /// Create a new induction variable inside L.
436 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
437 Value *Step, Instruction *DL);
438 /// Copy and widen the instructions from the old loop.
439 virtual void vectorizeLoop();
441 /// Handle all cross-iteration phis in the header.
442 void fixCrossIterationPHIs();
444 /// Fix a first-order recurrence. This is the second phase of vectorizing
446 void fixFirstOrderRecurrence(PHINode *Phi);
448 /// Fix a reduction cross-iteration phi. This is the second phase of
449 /// vectorizing this phi node.
450 void fixReduction(PHINode *Phi);
452 /// \brief The Loop exit block may have single value PHI nodes where the
453 /// incoming value is 'Undef'. While vectorizing we only handled real values
454 /// that were defined inside the loop. Here we fix the 'undef case'.
458 /// Iteratively sink the scalarized operands of a predicated instruction into
459 /// the block that was created for it.
460 void sinkScalarOperands(Instruction *PredInst);
462 /// Predicate conditional instructions that require predication on their
463 /// respective conditions.
464 void predicateInstructions();
466 /// Collect the instructions from the original loop that would be trivially
467 /// dead in the vectorized loop if generated.
468 void collectTriviallyDeadInstructions(
469 SmallPtrSetImpl<Instruction *> &DeadInstructions);
471 /// Shrinks vector element sizes to the smallest bitwidth they can be legally
473 void truncateToMinimalBitwidths();
475 /// A helper function that computes the predicate of the block BB, assuming
476 /// that the header block of the loop is set to True. It returns the *entry*
477 /// mask for the block BB.
478 VectorParts createBlockInMask(BasicBlock *BB);
479 /// A helper function that computes the predicate of the edge between SRC
481 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
483 /// A helper function to vectorize a single instruction within the innermost
485 void vectorizeInstruction(Instruction &I);
487 /// Vectorize a single PHINode in a block. This method handles the induction
488 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
489 /// arbitrary length vectors.
490 void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
492 /// Insert the new loop to the loop hierarchy and pass manager
493 /// and update the analysis passes.
494 void updateAnalysis();
496 /// This instruction is un-vectorizable. Implement it as a sequence
497 /// of scalars. If \p IfPredicateInstr is true we need to 'hide' each
498 /// scalarized instruction behind an if block predicated on the control
499 /// dependence of the instruction.
500 virtual void scalarizeInstruction(Instruction *Instr,
501 bool IfPredicateInstr = false);
503 /// Vectorize Load and Store instructions,
504 virtual void vectorizeMemoryInstruction(Instruction *Instr);
506 /// Create a broadcast instruction. This method generates a broadcast
507 /// instruction (shuffle) for loop invariant values and for the induction
508 /// value. If this is the induction variable then we extend it to N, N+1, ...
509 /// this is needed because each iteration in the loop corresponds to a SIMD
511 virtual Value *getBroadcastInstrs(Value *V);
513 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
514 /// to each vector element of Val. The sequence starts at StartIndex.
515 /// \p Opcode is relevant for FP induction variable.
516 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
517 Instruction::BinaryOps Opcode =
518 Instruction::BinaryOpsEnd);
520 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
521 /// variable on which to base the steps, \p Step is the size of the step, and
522 /// \p EntryVal is the value from the original loop that maps to the steps.
523 /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it
524 /// can be a truncate instruction).
525 void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal,
526 const InductionDescriptor &ID);
528 /// Create a vector induction phi node based on an existing scalar one. \p
529 /// EntryVal is the value from the original loop that maps to the vector phi
530 /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
531 /// truncate instruction, instead of widening the original IV, we widen a
532 /// version of the IV truncated to \p EntryVal's type.
533 void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
534 Value *Step, Instruction *EntryVal);
536 /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
537 /// is provided, the integer induction variable will first be truncated to
538 /// the corresponding type.
539 void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
541 /// Returns true if an instruction \p I should be scalarized instead of
542 /// vectorized for the chosen vectorization factor.
543 bool shouldScalarizeInstruction(Instruction *I) const;
545 /// Returns true if we should generate a scalar version of \p IV.
546 bool needsScalarInduction(Instruction *IV) const;
548 /// Return a constant reference to the VectorParts corresponding to \p V from
549 /// the original loop. If the value has already been vectorized, the
550 /// corresponding vector entry in VectorLoopValueMap is returned. If,
551 /// however, the value has a scalar entry in VectorLoopValueMap, we construct
552 /// new vector values on-demand by inserting the scalar values into vectors
553 /// with an insertelement sequence. If the value has been neither vectorized
554 /// nor scalarized, it must be loop invariant, so we simply broadcast the
555 /// value into vectors.
556 const VectorParts &getVectorValue(Value *V);
558 /// Return a value in the new loop corresponding to \p V from the original
559 /// loop at unroll index \p Part and vector index \p Lane. If the value has
560 /// been vectorized but not scalarized, the necessary extractelement
561 /// instruction will be generated.
562 Value *getScalarValue(Value *V, unsigned Part, unsigned Lane);
564 /// Try to vectorize the interleaved access group that \p Instr belongs to.
565 void vectorizeInterleaveGroup(Instruction *Instr);
567 /// Generate a shuffle sequence that will reverse the vector Vec.
568 virtual Value *reverseVector(Value *Vec);
570 /// Returns (and creates if needed) the original loop trip count.
571 Value *getOrCreateTripCount(Loop *NewLoop);
573 /// Returns (and creates if needed) the trip count of the widened loop.
574 Value *getOrCreateVectorTripCount(Loop *NewLoop);
576 /// Emit a bypass check to see if the trip count would overflow, or we
577 /// wouldn't have enough iterations to execute one vector loop.
578 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
579 /// Emit a bypass check to see if the vector trip count is nonzero.
580 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
581 /// Emit a bypass check to see if all of the SCEV assumptions we've
582 /// had to make are correct.
583 void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
584 /// Emit bypass checks to check any memory assumptions we may have made.
585 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
587 /// Add additional metadata to \p To that was not present on \p Orig.
589 /// Currently this is used to add the noalias annotations based on the
590 /// inserted memchecks. Use this for instructions that are *cloned* into the
592 void addNewMetadata(Instruction *To, const Instruction *Orig);
594 /// Add metadata from one instruction to another.
596 /// This includes both the original MDs from \p From and additional ones (\see
597 /// addNewMetadata). Use this for *newly created* instructions in the vector
599 void addMetadata(Instruction *To, Instruction *From);
601 /// \brief Similar to the previous function but it adds the metadata to a
602 /// vector of instructions.
603 void addMetadata(ArrayRef<Value *> To, Instruction *From);
605 /// \brief Set the debug location in the builder using the debug location in
607 void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
609 /// This is a helper class for maintaining vectorization state. It's used for
610 /// mapping values from the original loop to their corresponding values in
611 /// the new loop. Two mappings are maintained: one for vectorized values and
612 /// one for scalarized values. Vectorized values are represented with UF
613 /// vector values in the new loop, and scalarized values are represented with
614 /// UF x VF scalar values in the new loop. UF and VF are the unroll and
615 /// vectorization factors, respectively.
617 /// Entries can be added to either map with initVector and initScalar, which
618 /// initialize and return a constant reference to the new entry. If a
619 /// non-constant reference to a vector entry is required, getVector can be
620 /// used to retrieve a mutable entry. We currently directly modify the mapped
621 /// values during "fix-up" operations that occur once the first phase of
622 /// widening is complete. These operations include type truncation and the
623 /// second phase of recurrence widening.
625 /// Otherwise, entries from either map should be accessed using the
626 /// getVectorValue or getScalarValue functions from InnerLoopVectorizer.
627 /// getVectorValue and getScalarValue coordinate to generate a vector or
628 /// scalar value on-demand if one is not yet available. When vectorizing a
629 /// loop, we visit the definition of an instruction before its uses. When
630 /// visiting the definition, we either vectorize or scalarize the
631 /// instruction, creating an entry for it in the corresponding map. (In some
632 /// cases, such as induction variables, we will create both vector and scalar
633 /// entries.) Then, as we encounter uses of the definition, we derive values
634 /// for each scalar or vector use unless such a value is already available.
635 /// For example, if we scalarize a definition and one of its uses is vector,
636 /// we build the required vector on-demand with an insertelement sequence
637 /// when visiting the use. Otherwise, if the use is scalar, we can use the
638 /// existing scalar definition.
641 /// Construct an empty map with the given unroll and vectorization factors.
642 ValueMap(unsigned UnrollFactor, unsigned VecWidth)
643 : UF(UnrollFactor), VF(VecWidth) {
644 // The unroll and vectorization factors are only used in asserts builds
645 // to verify map entries are sized appropriately.
650 /// \return True if the map has a vector entry for \p Key.
651 bool hasVector(Value *Key) const { return VectorMapStorage.count(Key); }
653 /// \return True if the map has a scalar entry for \p Key.
654 bool hasScalar(Value *Key) const { return ScalarMapStorage.count(Key); }
656 /// \brief Map \p Key to the given VectorParts \p Entry, and return a
657 /// constant reference to the new vector map entry. The given key should
658 /// not already be in the map, and the given VectorParts should be
659 /// correctly sized for the current unroll factor.
660 const VectorParts &initVector(Value *Key, const VectorParts &Entry) {
661 assert(!hasVector(Key) && "Vector entry already initialized");
662 assert(Entry.size() == UF && "VectorParts has wrong dimensions");
663 VectorMapStorage[Key] = Entry;
664 return VectorMapStorage[Key];
667 /// \brief Map \p Key to the given ScalarParts \p Entry, and return a
668 /// constant reference to the new scalar map entry. The given key should
669 /// not already be in the map, and the given ScalarParts should be
670 /// correctly sized for the current unroll and vectorization factors.
671 const ScalarParts &initScalar(Value *Key, const ScalarParts &Entry) {
672 assert(!hasScalar(Key) && "Scalar entry already initialized");
673 assert(Entry.size() == UF &&
674 all_of(make_range(Entry.begin(), Entry.end()),
675 [&](const SmallVectorImpl<Value *> &Values) -> bool {
676 return Values.size() == VF;
678 "ScalarParts has wrong dimensions");
679 ScalarMapStorage[Key] = Entry;
680 return ScalarMapStorage[Key];
683 /// \return A reference to the vector map entry corresponding to \p Key.
684 /// The key should already be in the map. This function should only be used
685 /// when it's necessary to update values that have already been vectorized.
686 /// This is the case for "fix-up" operations including type truncation and
687 /// the second phase of recurrence vectorization. If a non-const reference
688 /// isn't required, getVectorValue should be used instead.
689 VectorParts &getVector(Value *Key) {
690 assert(hasVector(Key) && "Vector entry not initialized");
691 return VectorMapStorage.find(Key)->second;
694 /// Retrieve an entry from the vector or scalar maps. The preferred way to
695 /// access an existing mapped entry is with getVectorValue or
696 /// getScalarValue from InnerLoopVectorizer. Until those functions can be
697 /// moved inside ValueMap, we have to declare them as friends.
698 friend const VectorParts &InnerLoopVectorizer::getVectorValue(Value *V);
699 friend Value *InnerLoopVectorizer::getScalarValue(Value *V, unsigned Part,
703 /// The unroll factor. Each entry in the vector map contains UF vector
707 /// The vectorization factor. Each entry in the scalar map contains UF x VF
711 /// The vector and scalar map storage. We use std::map and not DenseMap
712 /// because insertions to DenseMap invalidate its iterators.
713 std::map<Value *, VectorParts> VectorMapStorage;
714 std::map<Value *, ScalarParts> ScalarMapStorage;
717 /// The original loop.
719 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
720 /// dynamic knowledge to simplify SCEV expressions and converts them to a
721 /// more usable form.
722 PredicatedScalarEvolution &PSE;
729 /// Target Library Info.
730 const TargetLibraryInfo *TLI;
731 /// Target Transform Info.
732 const TargetTransformInfo *TTI;
733 /// Assumption Cache.
735 /// Interface to emit optimization remarks.
736 OptimizationRemarkEmitter *ORE;
738 /// \brief LoopVersioning. It's only set up (non-null) if memchecks were
741 /// This is currently only used to add no-alias metadata based on the
742 /// memchecks. The actually versioning is performed manually.
743 std::unique_ptr<LoopVersioning> LVer;
745 /// The vectorization SIMD factor to use. Each vector will have this many
750 /// The vectorization unroll factor to use. Each scalar is vectorized to this
751 /// many different vector instructions.
754 /// The builder that we use
757 // --- Vectorization state ---
759 /// The vector-loop preheader.
760 BasicBlock *LoopVectorPreHeader;
761 /// The scalar-loop preheader.
762 BasicBlock *LoopScalarPreHeader;
763 /// Middle Block between the vector and the scalar.
764 BasicBlock *LoopMiddleBlock;
765 /// The ExitBlock of the scalar loop.
766 BasicBlock *LoopExitBlock;
767 /// The vector loop body.
768 BasicBlock *LoopVectorBody;
769 /// The scalar loop body.
770 BasicBlock *LoopScalarBody;
771 /// A list of all bypass blocks. The first block is the entry of the loop.
772 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
774 /// The new Induction variable which was added to the new block.
776 /// The induction variable of the old basic block.
777 PHINode *OldInduction;
779 /// Maps values from the original loop to their corresponding values in the
780 /// vectorized loop. A key value can map to either vector values, scalar
781 /// values or both kinds of values, depending on whether the key was
782 /// vectorized and scalarized.
783 ValueMap VectorLoopValueMap;
785 /// Store instructions that should be predicated, as a pair
786 /// <StoreInst, Predicate>
787 SmallVector<std::pair<Instruction *, Value *>, 4> PredicatedInstructions;
788 EdgeMaskCache MaskCache;
789 /// Trip count of the original loop.
791 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
792 Value *VectorTripCount;
794 /// The legality analysis.
795 LoopVectorizationLegality *Legal;
797 /// The profitablity analysis.
798 LoopVectorizationCostModel *Cost;
800 // Record whether runtime checks are added.
801 bool AddedSafetyChecks;
803 // Holds the end values for each induction variable. We save the end values
804 // so we can later fix-up the external users of the induction variables.
805 DenseMap<PHINode *, Value *> IVEndValues;
808 class InnerLoopUnroller : public InnerLoopVectorizer {
810 InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
811 LoopInfo *LI, DominatorTree *DT,
812 const TargetLibraryInfo *TLI,
813 const TargetTransformInfo *TTI, AssumptionCache *AC,
814 OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
815 LoopVectorizationLegality *LVL,
816 LoopVectorizationCostModel *CM)
817 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
818 UnrollFactor, LVL, CM) {}
821 void vectorizeMemoryInstruction(Instruction *Instr) override;
822 Value *getBroadcastInstrs(Value *V) override;
823 Value *getStepVector(Value *Val, int StartIdx, Value *Step,
824 Instruction::BinaryOps Opcode =
825 Instruction::BinaryOpsEnd) override;
826 Value *reverseVector(Value *Vec) override;
829 /// \brief Look for a meaningful debug location on the instruction or it's
831 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
836 if (I->getDebugLoc() != Empty)
839 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
840 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
841 if (OpInst->getDebugLoc() != Empty)
848 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
849 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
850 const DILocation *DIL = Inst->getDebugLoc();
851 if (DIL && Inst->getFunction()->isDebugInfoForProfiling())
852 B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
854 B.SetCurrentDebugLocation(DIL);
856 B.SetCurrentDebugLocation(DebugLoc());
860 /// \return string containing a file name and a line # for the given loop.
861 static std::string getDebugLocString(const Loop *L) {
864 raw_string_ostream OS(Result);
865 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
866 LoopDbgLoc.print(OS);
868 // Just print the module name.
869 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
876 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
877 const Instruction *Orig) {
878 // If the loop was versioned with memchecks, add the corresponding no-alias
880 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
881 LVer->annotateInstWithNoAlias(To, Orig);
884 void InnerLoopVectorizer::addMetadata(Instruction *To,
886 propagateMetadata(To, From);
887 addNewMetadata(To, From);
890 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
892 for (Value *V : To) {
893 if (Instruction *I = dyn_cast<Instruction>(V))
894 addMetadata(I, From);
898 /// \brief The group of interleaved loads/stores sharing the same stride and
899 /// close to each other.
901 /// Each member in this group has an index starting from 0, and the largest
902 /// index should be less than interleaved factor, which is equal to the absolute
903 /// value of the access's stride.
905 /// E.g. An interleaved load group of factor 4:
906 /// for (unsigned i = 0; i < 1024; i+=4) {
907 /// a = A[i]; // Member of index 0
908 /// b = A[i+1]; // Member of index 1
909 /// d = A[i+3]; // Member of index 3
913 /// An interleaved store group of factor 4:
914 /// for (unsigned i = 0; i < 1024; i+=4) {
916 /// A[i] = a; // Member of index 0
917 /// A[i+1] = b; // Member of index 1
918 /// A[i+2] = c; // Member of index 2
919 /// A[i+3] = d; // Member of index 3
922 /// Note: the interleaved load group could have gaps (missing members), but
923 /// the interleaved store group doesn't allow gaps.
924 class InterleaveGroup {
926 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
927 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
928 assert(Align && "The alignment should be non-zero");
930 Factor = std::abs(Stride);
931 assert(Factor > 1 && "Invalid interleave factor");
933 Reverse = Stride < 0;
937 bool isReverse() const { return Reverse; }
938 unsigned getFactor() const { return Factor; }
939 unsigned getAlignment() const { return Align; }
940 unsigned getNumMembers() const { return Members.size(); }
942 /// \brief Try to insert a new member \p Instr with index \p Index and
943 /// alignment \p NewAlign. The index is related to the leader and it could be
944 /// negative if it is the new leader.
946 /// \returns false if the instruction doesn't belong to the group.
947 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
948 assert(NewAlign && "The new member's alignment should be non-zero");
950 int Key = Index + SmallestKey;
952 // Skip if there is already a member with the same index.
953 if (Members.count(Key))
956 if (Key > LargestKey) {
957 // The largest index is always less than the interleave factor.
958 if (Index >= static_cast<int>(Factor))
962 } else if (Key < SmallestKey) {
963 // The largest index is always less than the interleave factor.
964 if (LargestKey - Key >= static_cast<int>(Factor))
970 // It's always safe to select the minimum alignment.
971 Align = std::min(Align, NewAlign);
972 Members[Key] = Instr;
976 /// \brief Get the member with the given index \p Index
978 /// \returns nullptr if contains no such member.
979 Instruction *getMember(unsigned Index) const {
980 int Key = SmallestKey + Index;
981 if (!Members.count(Key))
984 return Members.find(Key)->second;
987 /// \brief Get the index for the given member. Unlike the key in the member
988 /// map, the index starts from 0.
989 unsigned getIndex(Instruction *Instr) const {
990 for (auto I : Members)
991 if (I.second == Instr)
992 return I.first - SmallestKey;
994 llvm_unreachable("InterleaveGroup contains no such member");
997 Instruction *getInsertPos() const { return InsertPos; }
998 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
1001 unsigned Factor; // Interleave Factor.
1004 DenseMap<int, Instruction *> Members;
1008 // To avoid breaking dependences, vectorized instructions of an interleave
1009 // group should be inserted at either the first load or the last store in
1012 // E.g. %even = load i32 // Insert Position
1013 // %add = add i32 %even // Use of %even
1017 // %odd = add i32 // Def of %odd
1018 // store i32 %odd // Insert Position
1019 Instruction *InsertPos;
1022 /// \brief Drive the analysis of interleaved memory accesses in the loop.
1024 /// Use this class to analyze interleaved accesses only when we can vectorize
1025 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
1026 /// on interleaved accesses is unsafe.
1028 /// The analysis collects interleave groups and records the relationships
1029 /// between the member and the group in a map.
1030 class InterleavedAccessInfo {
1032 InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
1033 DominatorTree *DT, LoopInfo *LI)
1034 : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(nullptr),
1035 RequiresScalarEpilogue(false) {}
1037 ~InterleavedAccessInfo() {
1038 SmallSet<InterleaveGroup *, 4> DelSet;
1039 // Avoid releasing a pointer twice.
1040 for (auto &I : InterleaveGroupMap)
1041 DelSet.insert(I.second);
1042 for (auto *Ptr : DelSet)
1046 /// \brief Analyze the interleaved accesses and collect them in interleave
1047 /// groups. Substitute symbolic strides using \p Strides.
1048 void analyzeInterleaving(const ValueToValueMap &Strides);
1050 /// \brief Check if \p Instr belongs to any interleave group.
1051 bool isInterleaved(Instruction *Instr) const {
1052 return InterleaveGroupMap.count(Instr);
1055 /// \brief Return the maximum interleave factor of all interleaved groups.
1056 unsigned getMaxInterleaveFactor() const {
1057 unsigned MaxFactor = 1;
1058 for (auto &Entry : InterleaveGroupMap)
1059 MaxFactor = std::max(MaxFactor, Entry.second->getFactor());
1063 /// \brief Get the interleave group that \p Instr belongs to.
1065 /// \returns nullptr if doesn't have such group.
1066 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
1067 if (InterleaveGroupMap.count(Instr))
1068 return InterleaveGroupMap.find(Instr)->second;
1072 /// \brief Returns true if an interleaved group that may access memory
1073 /// out-of-bounds requires a scalar epilogue iteration for correctness.
1074 bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
1076 /// \brief Initialize the LoopAccessInfo used for dependence checking.
1077 void setLAI(const LoopAccessInfo *Info) { LAI = Info; }
1080 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
1081 /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
1082 /// The interleaved access analysis can also add new predicates (for example
1083 /// by versioning strides of pointers).
1084 PredicatedScalarEvolution &PSE;
1088 const LoopAccessInfo *LAI;
1090 /// True if the loop may contain non-reversed interleaved groups with
1091 /// out-of-bounds accesses. We ensure we don't speculatively access memory
1092 /// out-of-bounds by executing at least one scalar epilogue iteration.
1093 bool RequiresScalarEpilogue;
1095 /// Holds the relationships between the members and the interleave group.
1096 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
1098 /// Holds dependences among the memory accesses in the loop. It maps a source
1099 /// access to a set of dependent sink accesses.
1100 DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
1102 /// \brief The descriptor for a strided memory access.
1103 struct StrideDescriptor {
1104 StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
1106 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
1108 StrideDescriptor() = default;
1110 // The access's stride. It is negative for a reverse access.
1112 const SCEV *Scev = nullptr; // The scalar expression of this access
1113 uint64_t Size = 0; // The size of the memory object.
1114 unsigned Align = 0; // The alignment of this access.
1117 /// \brief A type for holding instructions and their stride descriptors.
1118 typedef std::pair<Instruction *, StrideDescriptor> StrideEntry;
1120 /// \brief Create a new interleave group with the given instruction \p Instr,
1121 /// stride \p Stride and alignment \p Align.
1123 /// \returns the newly created interleave group.
1124 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
1126 assert(!InterleaveGroupMap.count(Instr) &&
1127 "Already in an interleaved access group");
1128 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
1129 return InterleaveGroupMap[Instr];
1132 /// \brief Release the group and remove all the relationships.
1133 void releaseGroup(InterleaveGroup *Group) {
1134 for (unsigned i = 0; i < Group->getFactor(); i++)
1135 if (Instruction *Member = Group->getMember(i))
1136 InterleaveGroupMap.erase(Member);
1141 /// \brief Collect all the accesses with a constant stride in program order.
1142 void collectConstStrideAccesses(
1143 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
1144 const ValueToValueMap &Strides);
1146 /// \brief Returns true if \p Stride is allowed in an interleaved group.
1147 static bool isStrided(int Stride) {
1148 unsigned Factor = std::abs(Stride);
1149 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1152 /// \brief Returns true if \p BB is a predicated block.
1153 bool isPredicated(BasicBlock *BB) const {
1154 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1157 /// \brief Returns true if LoopAccessInfo can be used for dependence queries.
1158 bool areDependencesValid() const {
1159 return LAI && LAI->getDepChecker().getDependences();
1162 /// \brief Returns true if memory accesses \p A and \p B can be reordered, if
1163 /// necessary, when constructing interleaved groups.
1165 /// \p A must precede \p B in program order. We return false if reordering is
1166 /// not necessary or is prevented because \p A and \p B may be dependent.
1167 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1168 StrideEntry *B) const {
1170 // Code motion for interleaved accesses can potentially hoist strided loads
1171 // and sink strided stores. The code below checks the legality of the
1172 // following two conditions:
1174 // 1. Potentially moving a strided load (B) before any store (A) that
1177 // 2. Potentially moving a strided store (A) after any load or store (B)
1180 // It's legal to reorder A and B if we know there isn't a dependence from A
1181 // to B. Note that this determination is conservative since some
1182 // dependences could potentially be reordered safely.
1184 // A is potentially the source of a dependence.
1185 auto *Src = A->first;
1186 auto SrcDes = A->second;
1188 // B is potentially the sink of a dependence.
1189 auto *Sink = B->first;
1190 auto SinkDes = B->second;
1192 // Code motion for interleaved accesses can't violate WAR dependences.
1193 // Thus, reordering is legal if the source isn't a write.
1194 if (!Src->mayWriteToMemory())
1197 // At least one of the accesses must be strided.
1198 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1201 // If dependence information is not available from LoopAccessInfo,
1202 // conservatively assume the instructions can't be reordered.
1203 if (!areDependencesValid())
1206 // If we know there is a dependence from source to sink, assume the
1207 // instructions can't be reordered. Otherwise, reordering is legal.
1208 return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
1211 /// \brief Collect the dependences from LoopAccessInfo.
1213 /// We process the dependences once during the interleaved access analysis to
1214 /// enable constant-time dependence queries.
1215 void collectDependences() {
1216 if (!areDependencesValid())
1218 auto *Deps = LAI->getDepChecker().getDependences();
1219 for (auto Dep : *Deps)
1220 Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1224 /// Utility class for getting and setting loop vectorizer hints in the form
1225 /// of loop metadata.
1226 /// This class keeps a number of loop annotations locally (as member variables)
1227 /// and can, upon request, write them back as metadata on the loop. It will
1228 /// initially scan the loop for existing metadata, and will update the local
1229 /// values based on information in the loop.
1230 /// We cannot write all values to metadata, as the mere presence of some info,
1231 /// for example 'force', means a decision has been made. So, we need to be
1232 /// careful NOT to add them if the user hasn't specifically asked so.
1233 class LoopVectorizeHints {
1234 enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE };
1236 /// Hint - associates name and validation with the hint value.
1239 unsigned Value; // This may have to change for non-numeric values.
1242 Hint(const char *Name, unsigned Value, HintKind Kind)
1243 : Name(Name), Value(Value), Kind(Kind) {}
1245 bool validate(unsigned Val) {
1248 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1250 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1258 /// Vectorization width.
1260 /// Vectorization interleave factor.
1262 /// Vectorization forced
1265 /// Return the loop metadata prefix.
1266 static StringRef Prefix() { return "llvm.loop."; }
1268 /// True if there is any unsafe math in the loop.
1269 bool PotentiallyUnsafe;
1273 FK_Undefined = -1, ///< Not selected.
1274 FK_Disabled = 0, ///< Forcing disabled.
1275 FK_Enabled = 1, ///< Forcing enabled.
1278 LoopVectorizeHints(const Loop *L, bool DisableInterleaving,
1279 OptimizationRemarkEmitter &ORE)
1280 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1282 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1283 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1284 PotentiallyUnsafe(false), TheLoop(L), ORE(ORE) {
1285 // Populate values with existing loop metadata.
1286 getHintsFromMetadata();
1288 // force-vector-interleave overrides DisableInterleaving.
1289 if (VectorizerParams::isInterleaveForced())
1290 Interleave.Value = VectorizerParams::VectorizationInterleave;
1292 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1293 << "LV: Interleaving disabled by the pass manager\n");
1296 /// Mark the loop L as already vectorized by setting the width to 1.
1297 void setAlreadyVectorized() {
1298 Width.Value = Interleave.Value = 1;
1299 Hint Hints[] = {Width, Interleave};
1300 writeHintsToMetadata(Hints);
1303 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
1304 if (getForce() == LoopVectorizeHints::FK_Disabled) {
1305 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1306 emitRemarkWithHints();
1310 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1311 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1312 emitRemarkWithHints();
1316 if (getWidth() == 1 && getInterleave() == 1) {
1317 // FIXME: Add a separate metadata to indicate when the loop has already
1318 // been vectorized instead of setting width and count to 1.
1319 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1320 // FIXME: Add interleave.disable metadata. This will allow
1321 // vectorize.disable to be used without disabling the pass and errors
1322 // to differentiate between disabled vectorization and a width of 1.
1323 ORE.emit(OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
1324 "AllDisabled", L->getStartLoc(),
1326 << "loop not vectorized: vectorization and interleaving are "
1327 "explicitly disabled, or vectorize width and interleave "
1328 "count are both set to 1");
1335 /// Dumps all the hint information.
1336 void emitRemarkWithHints() const {
1337 using namespace ore;
1338 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1339 ORE.emit(OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
1340 TheLoop->getStartLoc(),
1341 TheLoop->getHeader())
1342 << "loop not vectorized: vectorization is explicitly disabled");
1344 OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
1345 TheLoop->getStartLoc(), TheLoop->getHeader());
1346 R << "loop not vectorized";
1347 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1348 R << " (Force=" << NV("Force", true);
1349 if (Width.Value != 0)
1350 R << ", Vector Width=" << NV("VectorWidth", Width.Value);
1351 if (Interleave.Value != 0)
1352 R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
1359 unsigned getWidth() const { return Width.Value; }
1360 unsigned getInterleave() const { return Interleave.Value; }
1361 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1363 /// \brief If hints are provided that force vectorization, use the AlwaysPrint
1364 /// pass name to force the frontend to print the diagnostic.
1365 const char *vectorizeAnalysisPassName() const {
1366 if (getWidth() == 1)
1368 if (getForce() == LoopVectorizeHints::FK_Disabled)
1370 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1372 return OptimizationRemarkAnalysis::AlwaysPrint;
1375 bool allowReordering() const {
1376 // When enabling loop hints are provided we allow the vectorizer to change
1377 // the order of operations that is given by the scalar loop. This is not
1378 // enabled by default because can be unsafe or inefficient. For example,
1379 // reordering floating-point operations will change the way round-off
1380 // error accumulates in the loop.
1381 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1384 bool isPotentiallyUnsafe() const {
1385 // Avoid FP vectorization if the target is unsure about proper support.
1386 // This may be related to the SIMD unit in the target not handling
1387 // IEEE 754 FP ops properly, or bad single-to-double promotions.
1388 // Otherwise, a sequence of vectorized loops, even without reduction,
1389 // could lead to different end results on the destination vectors.
1390 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1393 void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
1396 /// Find hints specified in the loop metadata and update local values.
1397 void getHintsFromMetadata() {
1398 MDNode *LoopID = TheLoop->getLoopID();
1402 // First operand should refer to the loop id itself.
1403 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1404 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1406 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1407 const MDString *S = nullptr;
1408 SmallVector<Metadata *, 4> Args;
1410 // The expected hint is either a MDString or a MDNode with the first
1411 // operand a MDString.
1412 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1413 if (!MD || MD->getNumOperands() == 0)
1415 S = dyn_cast<MDString>(MD->getOperand(0));
1416 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1417 Args.push_back(MD->getOperand(i));
1419 S = dyn_cast<MDString>(LoopID->getOperand(i));
1420 assert(Args.size() == 0 && "too many arguments for MDString");
1426 // Check if the hint starts with the loop metadata prefix.
1427 StringRef Name = S->getString();
1428 if (Args.size() == 1)
1429 setHint(Name, Args[0]);
1433 /// Checks string hint with one operand and set value if valid.
1434 void setHint(StringRef Name, Metadata *Arg) {
1435 if (!Name.startswith(Prefix()))
1437 Name = Name.substr(Prefix().size(), StringRef::npos);
1439 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1442 unsigned Val = C->getZExtValue();
1444 Hint *Hints[] = {&Width, &Interleave, &Force};
1445 for (auto H : Hints) {
1446 if (Name == H->Name) {
1447 if (H->validate(Val))
1450 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1456 /// Create a new hint from name / value pair.
1457 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1458 LLVMContext &Context = TheLoop->getHeader()->getContext();
1459 Metadata *MDs[] = {MDString::get(Context, Name),
1460 ConstantAsMetadata::get(
1461 ConstantInt::get(Type::getInt32Ty(Context), V))};
1462 return MDNode::get(Context, MDs);
1465 /// Matches metadata with hint name.
1466 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1467 MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
1471 for (auto H : HintTypes)
1472 if (Name->getString().endswith(H.Name))
1477 /// Sets current hints into loop metadata, keeping other values intact.
1478 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1479 if (HintTypes.size() == 0)
1482 // Reserve the first element to LoopID (see below).
1483 SmallVector<Metadata *, 4> MDs(1);
1484 // If the loop already has metadata, then ignore the existing operands.
1485 MDNode *LoopID = TheLoop->getLoopID();
1487 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1488 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1489 // If node in update list, ignore old value.
1490 if (!matchesHintMetadataName(Node, HintTypes))
1491 MDs.push_back(Node);
1495 // Now, add the missing hints.
1496 for (auto H : HintTypes)
1497 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1499 // Replace current metadata node with new one.
1500 LLVMContext &Context = TheLoop->getHeader()->getContext();
1501 MDNode *NewLoopID = MDNode::get(Context, MDs);
1502 // Set operand 0 to refer to the loop id itself.
1503 NewLoopID->replaceOperandWith(0, NewLoopID);
1505 TheLoop->setLoopID(NewLoopID);
1508 /// The loop these hints belong to.
1509 const Loop *TheLoop;
1511 /// Interface to emit optimization remarks.
1512 OptimizationRemarkEmitter &ORE;
1515 static void emitMissedWarning(Function *F, Loop *L,
1516 const LoopVectorizeHints &LH,
1517 OptimizationRemarkEmitter *ORE) {
1518 LH.emitRemarkWithHints();
1520 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1521 if (LH.getWidth() != 1)
1522 ORE->emit(DiagnosticInfoOptimizationFailure(
1523 DEBUG_TYPE, "FailedRequestedVectorization",
1524 L->getStartLoc(), L->getHeader())
1525 << "loop not vectorized: "
1526 << "failed explicitly specified loop vectorization");
1527 else if (LH.getInterleave() != 1)
1528 ORE->emit(DiagnosticInfoOptimizationFailure(
1529 DEBUG_TYPE, "FailedRequestedInterleaving", L->getStartLoc(),
1531 << "loop not interleaved: "
1532 << "failed explicitly specified loop interleaving");
1536 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1537 /// to what vectorization factor.
1538 /// This class does not look at the profitability of vectorization, only the
1539 /// legality. This class has two main kinds of checks:
1540 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1541 /// will change the order of memory accesses in a way that will change the
1542 /// correctness of the program.
1543 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1544 /// checks for a number of different conditions, such as the availability of a
1545 /// single induction variable, that all types are supported and vectorize-able,
1546 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1547 /// This class is also used by InnerLoopVectorizer for identifying
1548 /// induction variable and the different reduction variables.
1549 class LoopVectorizationLegality {
1551 LoopVectorizationLegality(
1552 Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT,
1553 TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F,
1554 const TargetTransformInfo *TTI,
1555 std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
1556 OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R,
1557 LoopVectorizeHints *H)
1558 : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT),
1559 GetLAA(GetLAA), LAI(nullptr), ORE(ORE), InterleaveInfo(PSE, L, DT, LI),
1560 PrimaryInduction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
1561 Requirements(R), Hints(H) {}
1563 /// ReductionList contains the reduction descriptors for all
1564 /// of the reductions that were found in the loop.
1565 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1567 /// InductionList saves induction variables and maps them to the
1568 /// induction descriptor.
1569 typedef MapVector<PHINode *, InductionDescriptor> InductionList;
1571 /// RecurrenceSet contains the phi nodes that are recurrences other than
1572 /// inductions and reductions.
1573 typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet;
1575 /// Returns true if it is legal to vectorize this loop.
1576 /// This does not mean that it is profitable to vectorize this
1577 /// loop, only that it is legal to do so.
1578 bool canVectorize();
1580 /// Returns the primary induction variable.
1581 PHINode *getPrimaryInduction() { return PrimaryInduction; }
1583 /// Returns the reduction variables found in the loop.
1584 ReductionList *getReductionVars() { return &Reductions; }
1586 /// Returns the induction variables found in the loop.
1587 InductionList *getInductionVars() { return &Inductions; }
1589 /// Return the first-order recurrences found in the loop.
1590 RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
1592 /// Returns the widest induction type.
1593 Type *getWidestInductionType() { return WidestIndTy; }
1595 /// Returns True if V is an induction variable in this loop.
1596 bool isInductionVariable(const Value *V);
1598 /// Returns True if PN is a reduction variable in this loop.
1599 bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
1601 /// Returns True if Phi is a first-order recurrence in this loop.
1602 bool isFirstOrderRecurrence(const PHINode *Phi);
1604 /// Return true if the block BB needs to be predicated in order for the loop
1605 /// to be vectorized.
1606 bool blockNeedsPredication(BasicBlock *BB);
1608 /// Check if this pointer is consecutive when vectorizing. This happens
1609 /// when the last index of the GEP is the induction variable, or that the
1610 /// pointer itself is an induction variable.
1611 /// This check allows us to vectorize A[idx] into a wide load/store.
1613 /// 0 - Stride is unknown or non-consecutive.
1614 /// 1 - Address is consecutive.
1615 /// -1 - Address is consecutive, and decreasing.
1616 int isConsecutivePtr(Value *Ptr);
1618 /// Returns true if the value V is uniform within the loop.
1619 bool isUniform(Value *V);
1621 /// Returns the information that we collected about runtime memory check.
1622 const RuntimePointerChecking *getRuntimePointerChecking() const {
1623 return LAI->getRuntimePointerChecking();
1626 const LoopAccessInfo *getLAI() const { return LAI; }
1628 /// \brief Check if \p Instr belongs to any interleaved access group.
1629 bool isAccessInterleaved(Instruction *Instr) {
1630 return InterleaveInfo.isInterleaved(Instr);
1633 /// \brief Return the maximum interleave factor of all interleaved groups.
1634 unsigned getMaxInterleaveFactor() const {
1635 return InterleaveInfo.getMaxInterleaveFactor();
1638 /// \brief Get the interleaved access group that \p Instr belongs to.
1639 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1640 return InterleaveInfo.getInterleaveGroup(Instr);
1643 /// \brief Returns true if an interleaved group requires a scalar iteration
1644 /// to handle accesses with gaps.
1645 bool requiresScalarEpilogue() const {
1646 return InterleaveInfo.requiresScalarEpilogue();
1649 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1651 bool hasStride(Value *V) { return LAI->hasStride(V); }
1653 /// Returns true if the target machine supports masked store operation
1654 /// for the given \p DataType and kind of access to \p Ptr.
1655 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1656 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1658 /// Returns true if the target machine supports masked load operation
1659 /// for the given \p DataType and kind of access to \p Ptr.
1660 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1661 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1663 /// Returns true if the target machine supports masked scatter operation
1664 /// for the given \p DataType.
1665 bool isLegalMaskedScatter(Type *DataType) {
1666 return TTI->isLegalMaskedScatter(DataType);
1668 /// Returns true if the target machine supports masked gather operation
1669 /// for the given \p DataType.
1670 bool isLegalMaskedGather(Type *DataType) {
1671 return TTI->isLegalMaskedGather(DataType);
1673 /// Returns true if the target machine can represent \p V as a masked gather
1674 /// or scatter operation.
1675 bool isLegalGatherOrScatter(Value *V) {
1676 auto *LI = dyn_cast<LoadInst>(V);
1677 auto *SI = dyn_cast<StoreInst>(V);
1680 auto *Ptr = getPointerOperand(V);
1681 auto *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1682 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1685 /// Returns true if vector representation of the instruction \p I
1687 bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
1688 unsigned getNumStores() const { return LAI->getNumStores(); }
1689 unsigned getNumLoads() const { return LAI->getNumLoads(); }
1690 unsigned getNumPredStores() const { return NumPredStores; }
1692 /// Returns true if \p I is an instruction that will be scalarized with
1693 /// predication. Such instructions include conditional stores and
1694 /// instructions that may divide by zero.
1695 bool isScalarWithPredication(Instruction *I);
1697 /// Returns true if \p I is a memory instruction with consecutive memory
1698 /// access that can be widened.
1699 bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
1702 /// Check if a single basic block loop is vectorizable.
1703 /// At this point we know that this is a loop with a constant trip count
1704 /// and we only need to check individual instructions.
1705 bool canVectorizeInstrs();
1707 /// When we vectorize loops we may change the order in which
1708 /// we read and write from memory. This method checks if it is
1709 /// legal to vectorize the code, considering only memory constrains.
1710 /// Returns true if the loop is vectorizable
1711 bool canVectorizeMemory();
1713 /// Return true if we can vectorize this loop using the IF-conversion
1715 bool canVectorizeWithIfConvert();
1717 /// Return true if all of the instructions in the block can be speculatively
1718 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1719 /// and we know that we can read from them without segfault.
1720 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1722 /// Updates the vectorization state by adding \p Phi to the inductions list.
1723 /// This can set \p Phi as the main induction of the loop if \p Phi is a
1724 /// better choice for the main induction than the existing one.
1725 void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
1726 SmallPtrSetImpl<Value *> &AllowedExit);
1728 /// Create an analysis remark that explains why vectorization failed
1730 /// \p RemarkName is the identifier for the remark. If \p I is passed it is
1731 /// an instruction that prevents vectorization. Otherwise the loop is used
1732 /// for the location of the remark. \return the remark object that can be
1734 OptimizationRemarkAnalysis
1735 createMissedAnalysis(StringRef RemarkName, Instruction *I = nullptr) const {
1736 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1737 RemarkName, TheLoop, I);
1740 /// \brief If an access has a symbolic strides, this maps the pointer value to
1741 /// the stride symbol.
1742 const ValueToValueMap *getSymbolicStrides() {
1743 // FIXME: Currently, the set of symbolic strides is sometimes queried before
1744 // it's collected. This happens from canVectorizeWithIfConvert, when the
1745 // pointer is checked to reference consecutive elements suitable for a
1747 return LAI ? &LAI->getSymbolicStrides() : nullptr;
1750 unsigned NumPredStores;
1752 /// The loop that we evaluate.
1754 /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
1755 /// Applies dynamic knowledge to simplify SCEV expressions in the context
1756 /// of existing SCEV assumptions. The analysis will also add a minimal set
1757 /// of new predicates if this is required to enable vectorization and
1759 PredicatedScalarEvolution &PSE;
1760 /// Target Library Info.
1761 TargetLibraryInfo *TLI;
1762 /// Target Transform Info
1763 const TargetTransformInfo *TTI;
1766 // LoopAccess analysis.
1767 std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1768 // And the loop-accesses info corresponding to this loop. This pointer is
1769 // null until canVectorizeMemory sets it up.
1770 const LoopAccessInfo *LAI;
1771 /// Interface to emit optimization remarks.
1772 OptimizationRemarkEmitter *ORE;
1774 /// The interleave access information contains groups of interleaved accesses
1775 /// with the same stride and close to each other.
1776 InterleavedAccessInfo InterleaveInfo;
1778 // --- vectorization state --- //
1780 /// Holds the primary induction variable. This is the counter of the
1782 PHINode *PrimaryInduction;
1783 /// Holds the reduction variables.
1784 ReductionList Reductions;
1785 /// Holds all of the induction variables that we found in the loop.
1786 /// Notice that inductions don't need to start at zero and that induction
1787 /// variables can be pointers.
1788 InductionList Inductions;
1789 /// Holds the phi nodes that are first-order recurrences.
1790 RecurrenceSet FirstOrderRecurrences;
1791 /// Holds the widest induction type encountered.
1794 /// Allowed outside users. This holds the induction and reduction
1795 /// vars which can be accessed from outside the loop.
1796 SmallPtrSet<Value *, 4> AllowedExit;
1798 /// Can we assume the absence of NaNs.
1799 bool HasFunNoNaNAttr;
1801 /// Vectorization requirements that will go through late-evaluation.
1802 LoopVectorizationRequirements *Requirements;
1804 /// Used to emit an analysis of any legality issues.
1805 LoopVectorizeHints *Hints;
1807 /// While vectorizing these instructions we have to generate a
1808 /// call to the appropriate masked intrinsic
1809 SmallPtrSet<const Instruction *, 8> MaskedOp;
1812 /// LoopVectorizationCostModel - estimates the expected speedups due to
1814 /// In many cases vectorization is not profitable. This can happen because of
1815 /// a number of reasons. In this class we mainly attempt to predict the
1816 /// expected speedup/slowdowns due to the supported instruction set. We use the
1817 /// TargetTransformInfo to query the different backends for the cost of
1818 /// different operations.
1819 class LoopVectorizationCostModel {
1821 LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1822 LoopInfo *LI, LoopVectorizationLegality *Legal,
1823 const TargetTransformInfo &TTI,
1824 const TargetLibraryInfo *TLI, DemandedBits *DB,
1825 AssumptionCache *AC,
1826 OptimizationRemarkEmitter *ORE, const Function *F,
1827 const LoopVectorizeHints *Hints)
1828 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1829 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {}
1831 /// \return An upper bound for the vectorization factor, or None if
1832 /// vectorization should be avoided up front.
1833 Optional<unsigned> computeMaxVF(bool OptForSize);
1835 /// Information about vectorization costs
1836 struct VectorizationFactor {
1837 unsigned Width; // Vector width with best cost
1838 unsigned Cost; // Cost of the loop with that width
1840 /// \return The most profitable vectorization factor and the cost of that VF.
1841 /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1842 /// then this vectorization factor will be selected if vectorization is
1844 VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
1846 /// Setup cost-based decisions for user vectorization factor.
1847 void selectUserVectorizationFactor(unsigned UserVF) {
1848 collectUniformsAndScalars(UserVF);
1849 collectInstsToScalarize(UserVF);
1852 /// \return The size (in bits) of the smallest and widest types in the code
1853 /// that needs to be vectorized. We ignore values that remain scalar such as
1854 /// 64 bit loop indices.
1855 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1857 /// \return The desired interleave count.
1858 /// If interleave count has been specified by metadata it will be returned.
1859 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1860 /// are the selected vectorization factor and the cost of the selected VF.
1861 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1864 /// Memory access instruction may be vectorized in more than one way.
1865 /// Form of instruction after vectorization depends on cost.
1866 /// This function takes cost-based decisions for Load/Store instructions
1867 /// and collects them in a map. This decisions map is used for building
1868 /// the lists of loop-uniform and loop-scalar instructions.
1869 /// The calculated cost is saved with widening decision in order to
1870 /// avoid redundant calculations.
1871 void setCostBasedWideningDecision(unsigned VF);
1873 /// \brief A struct that represents some properties of the register usage
1875 struct RegisterUsage {
1876 /// Holds the number of loop invariant values that are used in the loop.
1877 unsigned LoopInvariantRegs;
1878 /// Holds the maximum number of concurrent live intervals in the loop.
1879 unsigned MaxLocalUsers;
1880 /// Holds the number of instructions in the loop.
1881 unsigned NumInstructions;
1884 /// \return Returns information about the register usages of the loop for the
1885 /// given vectorization factors.
1886 SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1888 /// Collect values we want to ignore in the cost model.
1889 void collectValuesToIgnore();
1891 /// \returns The smallest bitwidth each instruction can be represented with.
1892 /// The vector equivalents of these instructions should be truncated to this
1894 const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1898 /// \returns True if it is more profitable to scalarize instruction \p I for
1899 /// vectorization factor \p VF.
1900 bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
1901 auto Scalars = InstsToScalarize.find(VF);
1902 assert(Scalars != InstsToScalarize.end() &&
1903 "VF not yet analyzed for scalarization profitability");
1904 return Scalars->second.count(I);
1907 /// Returns true if \p I is known to be uniform after vectorization.
1908 bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
1911 assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity");
1912 auto UniformsPerVF = Uniforms.find(VF);
1913 return UniformsPerVF->second.count(I);
1916 /// Returns true if \p I is known to be scalar after vectorization.
1917 bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
1920 assert(Scalars.count(VF) && "Scalar values are not calculated for VF");
1921 auto ScalarsPerVF = Scalars.find(VF);
1922 return ScalarsPerVF->second.count(I);
1925 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1926 /// for vectorization factor \p VF.
1927 bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
1928 return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1929 !isScalarAfterVectorization(I, VF);
1932 /// Decision that was taken during cost calculation for memory instruction.
1941 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1942 /// instruction \p I and vector width \p VF.
1943 void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
1945 assert(VF >= 2 && "Expected VF >=2");
1946 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1949 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1950 /// interleaving group \p Grp and vector width \p VF.
1951 void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
1952 InstWidening W, unsigned Cost) {
1953 assert(VF >= 2 && "Expected VF >=2");
1954 /// Broadcast this decicion to all instructions inside the group.
1955 /// But the cost will be assigned to one instruction only.
1956 for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1957 if (auto *I = Grp->getMember(i)) {
1958 if (Grp->getInsertPos() == I)
1959 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1961 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1966 /// Return the cost model decision for the given instruction \p I and vector
1967 /// width \p VF. Return CM_Unknown if this instruction did not pass
1968 /// through the cost modeling.
1969 InstWidening getWideningDecision(Instruction *I, unsigned VF) {
1970 assert(VF >= 2 && "Expected VF >=2");
1971 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1972 auto Itr = WideningDecisions.find(InstOnVF);
1973 if (Itr == WideningDecisions.end())
1975 return Itr->second.first;
1978 /// Return the vectorization cost for the given instruction \p I and vector
1980 unsigned getWideningCost(Instruction *I, unsigned VF) {
1981 assert(VF >= 2 && "Expected VF >=2");
1982 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1983 assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated");
1984 return WideningDecisions[InstOnVF].second;
1987 /// Return True if instruction \p I is an optimizable truncate whose operand
1988 /// is an induction variable. Such a truncate will be removed by adding a new
1989 /// induction variable with the destination type.
1990 bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
1992 // If the instruction is not a truncate, return false.
1993 auto *Trunc = dyn_cast<TruncInst>(I);
1997 // Get the source and destination types of the truncate.
1998 Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1999 Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
2001 // If the truncate is free for the given types, return false. Replacing a
2002 // free truncate with an induction variable would add an induction variable
2003 // update instruction to each iteration of the loop. We exclude from this
2004 // check the primary induction variable since it will need an update
2005 // instruction regardless.
2006 Value *Op = Trunc->getOperand(0);
2007 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
2010 // If the truncated value is not an induction variable, return false.
2011 return Legal->isInductionVariable(Op);
2015 /// \return An upper bound for the vectorization factor, larger than zero.
2016 /// One is returned if vectorization should best be avoided due to cost.
2017 unsigned computeFeasibleMaxVF(bool OptForSize);
2019 /// The vectorization cost is a combination of the cost itself and a boolean
2020 /// indicating whether any of the contributing operations will actually
2022 /// vector values after type legalization in the backend. If this latter value
2024 /// false, then all operations will be scalarized (i.e. no vectorization has
2025 /// actually taken place).
2026 typedef std::pair<unsigned, bool> VectorizationCostTy;
2028 /// Returns the expected execution cost. The unit of the cost does
2029 /// not matter because we use the 'cost' units to compare different
2030 /// vector widths. The cost that is returned is *not* normalized by
2031 /// the factor width.
2032 VectorizationCostTy expectedCost(unsigned VF);
2034 /// Returns the execution time cost of an instruction for a given vector
2035 /// width. Vector width of one means scalar.
2036 VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
2038 /// The cost-computation logic from getInstructionCost which provides
2039 /// the vector type as an output parameter.
2040 unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
2042 /// Calculate vectorization cost of memory instruction \p I.
2043 unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
2045 /// The cost computation for scalarized memory instruction.
2046 unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
2048 /// The cost computation for interleaving group of memory instructions.
2049 unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
2051 /// The cost computation for Gather/Scatter instruction.
2052 unsigned getGatherScatterCost(Instruction *I, unsigned VF);
2054 /// The cost computation for widening instruction \p I with consecutive
2056 unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
2058 /// The cost calculation for Load instruction \p I with uniform pointer -
2059 /// scalar load + broadcast.
2060 unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
2062 /// Returns whether the instruction is a load or store and will be a emitted
2063 /// as a vector operation.
2064 bool isConsecutiveLoadOrStore(Instruction *I);
2066 /// Create an analysis remark that explains why vectorization failed
2068 /// \p RemarkName is the identifier for the remark. \return the remark object
2069 /// that can be streamed to.
2070 OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
2071 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
2072 RemarkName, TheLoop);
2075 /// Map of scalar integer values to the smallest bitwidth they can be legally
2076 /// represented as. The vector equivalents of these values should be truncated
2078 MapVector<Instruction *, uint64_t> MinBWs;
2080 /// A type representing the costs for instructions if they were to be
2081 /// scalarized rather than vectorized. The entries are Instruction-Cost
2083 typedef DenseMap<Instruction *, unsigned> ScalarCostsTy;
2085 /// A set containing all BasicBlocks that are known to present after
2086 /// vectorization as a predicated block.
2087 SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
2089 /// A map holding scalar costs for different vectorization factors. The
2090 /// presence of a cost for an instruction in the mapping indicates that the
2091 /// instruction will be scalarized when vectorizing with the associated
2092 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
2093 DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
2095 /// Holds the instructions known to be uniform after vectorization.
2096 /// The data is collected per VF.
2097 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
2099 /// Holds the instructions known to be scalar after vectorization.
2100 /// The data is collected per VF.
2101 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
2103 /// Returns the expected difference in cost from scalarizing the expression
2104 /// feeding a predicated instruction \p PredInst. The instructions to
2105 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
2106 /// non-negative return value implies the expression will be scalarized.
2107 /// Currently, only single-use chains are considered for scalarization.
2108 int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
2111 /// Collects the instructions to scalarize for each predicated instruction in
2113 void collectInstsToScalarize(unsigned VF);
2115 /// Collect the instructions that are uniform after vectorization. An
2116 /// instruction is uniform if we represent it with a single scalar value in
2117 /// the vectorized loop corresponding to each vector iteration. Examples of
2118 /// uniform instructions include pointer operands of consecutive or
2119 /// interleaved memory accesses. Note that although uniformity implies an
2120 /// instruction will be scalar, the reverse is not true. In general, a
2121 /// scalarized instruction will be represented by VF scalar values in the
2122 /// vectorized loop, each corresponding to an iteration of the original
2124 void collectLoopUniforms(unsigned VF);
2126 /// Collect the instructions that are scalar after vectorization. An
2127 /// instruction is scalar if it is known to be uniform or will be scalarized
2128 /// during vectorization. Non-uniform scalarized instructions will be
2129 /// represented by VF values in the vectorized loop, each corresponding to an
2130 /// iteration of the original scalar loop.
2131 void collectLoopScalars(unsigned VF);
2133 /// Collect Uniform and Scalar values for the given \p VF.
2134 /// The sets depend on CM decision for Load/Store instructions
2135 /// that may be vectorized as interleave, gather-scatter or scalarized.
2136 void collectUniformsAndScalars(unsigned VF) {
2137 // Do the analysis once.
2138 if (VF == 1 || Uniforms.count(VF))
2140 setCostBasedWideningDecision(VF);
2141 collectLoopUniforms(VF);
2142 collectLoopScalars(VF);
2145 /// Keeps cost model vectorization decision and cost for instructions.
2146 /// Right now it is used for memory instructions only.
2147 typedef DenseMap<std::pair<Instruction *, unsigned>,
2148 std::pair<InstWidening, unsigned>>
2151 DecisionList WideningDecisions;
2154 /// The loop that we evaluate.
2156 /// Predicated scalar evolution analysis.
2157 PredicatedScalarEvolution &PSE;
2158 /// Loop Info analysis.
2160 /// Vectorization legality.
2161 LoopVectorizationLegality *Legal;
2162 /// Vector target information.
2163 const TargetTransformInfo &TTI;
2164 /// Target Library Info.
2165 const TargetLibraryInfo *TLI;
2166 /// Demanded bits analysis.
2168 /// Assumption cache.
2169 AssumptionCache *AC;
2170 /// Interface to emit optimization remarks.
2171 OptimizationRemarkEmitter *ORE;
2173 const Function *TheFunction;
2174 /// Loop Vectorize Hint.
2175 const LoopVectorizeHints *Hints;
2176 /// Values to ignore in the cost model.
2177 SmallPtrSet<const Value *, 16> ValuesToIgnore;
2178 /// Values to ignore in the cost model when VF > 1.
2179 SmallPtrSet<const Value *, 16> VecValuesToIgnore;
2182 /// LoopVectorizationPlanner - drives the vectorization process after having
2183 /// passed Legality checks.
2184 class LoopVectorizationPlanner {
2186 LoopVectorizationPlanner(LoopVectorizationCostModel &CM) : CM(CM) {}
2188 ~LoopVectorizationPlanner() {}
2190 /// Plan how to best vectorize, return the best VF and its cost.
2191 LoopVectorizationCostModel::VectorizationFactor plan(bool OptForSize,
2195 /// The profitablity analysis.
2196 LoopVectorizationCostModel &CM;
2199 /// \brief This holds vectorization requirements that must be verified late in
2200 /// the process. The requirements are set by legalize and costmodel. Once
2201 /// vectorization has been determined to be possible and profitable the
2202 /// requirements can be verified by looking for metadata or compiler options.
2203 /// For example, some loops require FP commutativity which is only allowed if
2204 /// vectorization is explicitly specified or if the fast-math compiler option
2205 /// has been provided.
2206 /// Late evaluation of these requirements allows helpful diagnostics to be
2207 /// composed that tells the user what need to be done to vectorize the loop. For
2208 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
2209 /// evaluation should be used only when diagnostics can generated that can be
2210 /// followed by a non-expert user.
2211 class LoopVectorizationRequirements {
2213 LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE)
2214 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr), ORE(ORE) {}
2216 void addUnsafeAlgebraInst(Instruction *I) {
2217 // First unsafe algebra instruction.
2218 if (!UnsafeAlgebraInst)
2219 UnsafeAlgebraInst = I;
2222 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
2224 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
2225 const char *PassName = Hints.vectorizeAnalysisPassName();
2226 bool Failed = false;
2227 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
2229 OptimizationRemarkAnalysisFPCommute(PassName, "CantReorderFPOps",
2230 UnsafeAlgebraInst->getDebugLoc(),
2231 UnsafeAlgebraInst->getParent())
2232 << "loop not vectorized: cannot prove it is safe to reorder "
2233 "floating-point operations");
2237 // Test if runtime memcheck thresholds are exceeded.
2238 bool PragmaThresholdReached =
2239 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
2240 bool ThresholdReached =
2241 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
2242 if ((ThresholdReached && !Hints.allowReordering()) ||
2243 PragmaThresholdReached) {
2244 ORE.emit(OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
2247 << "loop not vectorized: cannot prove it is safe to reorder "
2248 "memory operations");
2249 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
2257 unsigned NumRuntimePointerChecks;
2258 Instruction *UnsafeAlgebraInst;
2260 /// Interface to emit optimization remarks.
2261 OptimizationRemarkEmitter &ORE;
2264 static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
2266 if (!hasCyclesInLoopBody(L))
2270 for (Loop *InnerL : L)
2271 addAcyclicInnerLoop(*InnerL, V);
2274 /// The LoopVectorize Pass.
2275 struct LoopVectorize : public FunctionPass {
2276 /// Pass identification, replacement for typeid
2279 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
2280 : FunctionPass(ID) {
2281 Impl.DisableUnrolling = NoUnrolling;
2282 Impl.AlwaysVectorize = AlwaysVectorize;
2283 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2286 LoopVectorizePass Impl;
2288 bool runOnFunction(Function &F) override {
2289 if (skipFunction(F))
2292 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2293 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2294 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2295 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2296 auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2297 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2298 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2299 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2300 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2301 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2302 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2303 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2305 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2306 [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2308 return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2312 void getAnalysisUsage(AnalysisUsage &AU) const override {
2313 AU.addRequired<AssumptionCacheTracker>();
2314 AU.addRequired<BlockFrequencyInfoWrapperPass>();
2315 AU.addRequired<DominatorTreeWrapperPass>();
2316 AU.addRequired<LoopInfoWrapperPass>();
2317 AU.addRequired<ScalarEvolutionWrapperPass>();
2318 AU.addRequired<TargetTransformInfoWrapperPass>();
2319 AU.addRequired<AAResultsWrapperPass>();
2320 AU.addRequired<LoopAccessLegacyAnalysis>();
2321 AU.addRequired<DemandedBitsWrapperPass>();
2322 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2323 AU.addPreserved<LoopInfoWrapperPass>();
2324 AU.addPreserved<DominatorTreeWrapperPass>();
2325 AU.addPreserved<BasicAAWrapperPass>();
2326 AU.addPreserved<GlobalsAAWrapperPass>();
2330 } // end anonymous namespace
2332 //===----------------------------------------------------------------------===//
2333 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2334 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2335 //===----------------------------------------------------------------------===//
2337 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2338 // We need to place the broadcast of invariant variables outside the loop.
2339 Instruction *Instr = dyn_cast<Instruction>(V);
2340 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
2341 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
2343 // Place the code for broadcasting invariant variables in the new preheader.
2344 IRBuilder<>::InsertPointGuard Guard(Builder);
2346 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2348 // Broadcast the scalar into all locations in the vector.
2349 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2354 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2355 const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
2356 Value *Start = II.getStartValue();
2358 // Construct the initial value of the vector IV in the vector loop preheader
2359 auto CurrIP = Builder.saveIP();
2360 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2361 if (isa<TruncInst>(EntryVal)) {
2362 assert(Start->getType()->isIntegerTy() &&
2363 "Truncation requires an integer type");
2364 auto *TruncType = cast<IntegerType>(EntryVal->getType());
2365 Step = Builder.CreateTrunc(Step, TruncType);
2366 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2368 Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2369 Value *SteppedStart =
2370 getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2372 // We create vector phi nodes for both integer and floating-point induction
2373 // variables. Here, we determine the kind of arithmetic we will perform.
2374 Instruction::BinaryOps AddOp;
2375 Instruction::BinaryOps MulOp;
2376 if (Step->getType()->isIntegerTy()) {
2377 AddOp = Instruction::Add;
2378 MulOp = Instruction::Mul;
2380 AddOp = II.getInductionOpcode();
2381 MulOp = Instruction::FMul;
2384 // Multiply the vectorization factor by the step using integer or
2385 // floating-point arithmetic as appropriate.
2386 Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
2387 Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
2389 // Create a vector splat to use in the induction update.
2391 // FIXME: If the step is non-constant, we create the vector splat with
2392 // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2393 // handle a constant vector splat.
2394 Value *SplatVF = isa<Constant>(Mul)
2395 ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2396 : Builder.CreateVectorSplat(VF, Mul);
2397 Builder.restoreIP(CurrIP);
2399 // We may need to add the step a number of times, depending on the unroll
2400 // factor. The last of those goes into the PHI.
2401 PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2402 &*LoopVectorBody->getFirstInsertionPt());
2403 Instruction *LastInduction = VecInd;
2404 VectorParts Entry(UF);
2405 for (unsigned Part = 0; Part < UF; ++Part) {
2406 Entry[Part] = LastInduction;
2407 LastInduction = cast<Instruction>(addFastMathFlag(
2408 Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
2410 VectorLoopValueMap.initVector(EntryVal, Entry);
2411 if (isa<TruncInst>(EntryVal))
2412 addMetadata(Entry, EntryVal);
2414 // Move the last step to the end of the latch block. This ensures consistent
2415 // placement of all induction updates.
2416 auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2417 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2418 auto *ICmp = cast<Instruction>(Br->getCondition());
2419 LastInduction->moveBefore(ICmp);
2420 LastInduction->setName("vec.ind.next");
2422 VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2423 VecInd->addIncoming(LastInduction, LoopVectorLatch);
2426 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2427 return Cost->isScalarAfterVectorization(I, VF) ||
2428 Cost->isProfitableToScalarize(I, VF);
2431 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2432 if (shouldScalarizeInstruction(IV))
2434 auto isScalarInst = [&](User *U) -> bool {
2435 auto *I = cast<Instruction>(U);
2436 return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2438 return any_of(IV->users(), isScalarInst);
2441 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
2443 assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2444 "Primary induction variable must have an integer type");
2446 auto II = Legal->getInductionVars()->find(IV);
2447 assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
2449 auto ID = II->second;
2450 assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2452 // The scalar value to broadcast. This will be derived from the canonical
2453 // induction variable.
2454 Value *ScalarIV = nullptr;
2456 // The value from the original loop to which we are mapping the new induction
2458 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2460 // True if we have vectorized the induction variable.
2461 auto VectorizedIV = false;
2463 // Determine if we want a scalar version of the induction variable. This is
2464 // true if the induction variable itself is not widened, or if it has at
2465 // least one user in the loop that is not widened.
2466 auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
2468 // Generate code for the induction step. Note that induction steps are
2469 // required to be loop-invariant
2470 assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
2471 "Induction step should be loop invariant");
2472 auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2473 Value *Step = nullptr;
2474 if (PSE.getSE()->isSCEVable(IV->getType())) {
2475 SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2476 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2477 LoopVectorPreHeader->getTerminator());
2479 Step = cast<SCEVUnknown>(ID.getStep())->getValue();
2482 // Try to create a new independent vector induction variable. If we can't
2483 // create the phi node, we will splat the scalar induction variable in each
2485 if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
2486 createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2487 VectorizedIV = true;
2490 // If we haven't yet vectorized the induction variable, or if we will create
2491 // a scalar one, we need to define the scalar induction variable and step
2492 // values. If we were given a truncation type, truncate the canonical
2493 // induction variable and step. Otherwise, derive these values from the
2494 // induction descriptor.
2495 if (!VectorizedIV || NeedsScalarIV) {
2496 ScalarIV = Induction;
2497 if (IV != OldInduction) {
2498 ScalarIV = IV->getType()->isIntegerTy()
2499 ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2500 : Builder.CreateCast(Instruction::SIToFP, Induction,
2502 ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
2503 ScalarIV->setName("offset.idx");
2506 auto *TruncType = cast<IntegerType>(Trunc->getType());
2507 assert(Step->getType()->isIntegerTy() &&
2508 "Truncation requires an integer step");
2509 ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2510 Step = Builder.CreateTrunc(Step, TruncType);
2514 // If we haven't yet vectorized the induction variable, splat the scalar
2515 // induction variable, and build the necessary step vectors.
2516 if (!VectorizedIV) {
2517 Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2518 VectorParts Entry(UF);
2519 for (unsigned Part = 0; Part < UF; ++Part)
2521 getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
2522 VectorLoopValueMap.initVector(EntryVal, Entry);
2524 addMetadata(Entry, Trunc);
2527 // If an induction variable is only used for counting loop iterations or
2528 // calculating addresses, it doesn't need to be widened. Create scalar steps
2529 // that can be used by instructions we will later scalarize. Note that the
2530 // addition of the scalar steps will not increase the number of instructions
2531 // in the loop in the common case prior to InstCombine. We will be trading
2532 // one vector extract for each scalar step.
2534 buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2537 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2538 Instruction::BinaryOps BinOp) {
2539 // Create and check the types.
2540 assert(Val->getType()->isVectorTy() && "Must be a vector");
2541 int VLen = Val->getType()->getVectorNumElements();
2543 Type *STy = Val->getType()->getScalarType();
2544 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2545 "Induction Step must be an integer or FP");
2546 assert(Step->getType() == STy && "Step has wrong type");
2548 SmallVector<Constant *, 8> Indices;
2550 if (STy->isIntegerTy()) {
2551 // Create a vector of consecutive numbers from zero to VF.
2552 for (int i = 0; i < VLen; ++i)
2553 Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2555 // Add the consecutive indices to the vector value.
2556 Constant *Cv = ConstantVector::get(Indices);
2557 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2558 Step = Builder.CreateVectorSplat(VLen, Step);
2559 assert(Step->getType() == Val->getType() && "Invalid step vec");
2560 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2561 // which can be found from the original scalar operations.
2562 Step = Builder.CreateMul(Cv, Step);
2563 return Builder.CreateAdd(Val, Step, "induction");
2566 // Floating point induction.
2567 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2568 "Binary Opcode should be specified for FP induction");
2569 // Create a vector of consecutive numbers from zero to VF.
2570 for (int i = 0; i < VLen; ++i)
2571 Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2573 // Add the consecutive indices to the vector value.
2574 Constant *Cv = ConstantVector::get(Indices);
2576 Step = Builder.CreateVectorSplat(VLen, Step);
2578 // Floating point operations had to be 'fast' to enable the induction.
2579 FastMathFlags Flags;
2580 Flags.setUnsafeAlgebra();
2582 Value *MulOp = Builder.CreateFMul(Cv, Step);
2583 if (isa<Instruction>(MulOp))
2584 // Have to check, MulOp may be a constant
2585 cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2587 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2588 if (isa<Instruction>(BOp))
2589 cast<Instruction>(BOp)->setFastMathFlags(Flags);
2593 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2595 const InductionDescriptor &ID) {
2597 // We shouldn't have to build scalar steps if we aren't vectorizing.
2598 assert(VF > 1 && "VF should be greater than one");
2600 // Get the value type and ensure it and the step have the same integer type.
2601 Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2602 assert(ScalarIVTy == Step->getType() &&
2603 "Val and Step should have the same type");
2605 // We build scalar steps for both integer and floating-point induction
2606 // variables. Here, we determine the kind of arithmetic we will perform.
2607 Instruction::BinaryOps AddOp;
2608 Instruction::BinaryOps MulOp;
2609 if (ScalarIVTy->isIntegerTy()) {
2610 AddOp = Instruction::Add;
2611 MulOp = Instruction::Mul;
2613 AddOp = ID.getInductionOpcode();
2614 MulOp = Instruction::FMul;
2617 // Determine the number of scalars we need to generate for each unroll
2618 // iteration. If EntryVal is uniform, we only need to generate the first
2619 // lane. Otherwise, we generate all VF values.
2621 Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1 : VF;
2623 // Compute the scalar steps and save the results in VectorLoopValueMap.
2624 ScalarParts Entry(UF);
2625 for (unsigned Part = 0; Part < UF; ++Part) {
2626 Entry[Part].resize(VF);
2627 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2628 auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2629 auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2630 auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2631 Entry[Part][Lane] = Add;
2634 VectorLoopValueMap.initScalar(EntryVal, Entry);
2637 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2639 const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() :
2642 int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
2643 if (Stride == 1 || Stride == -1)
2648 bool LoopVectorizationLegality::isUniform(Value *V) {
2649 return LAI->isUniform(V);
2652 const InnerLoopVectorizer::VectorParts &
2653 InnerLoopVectorizer::getVectorValue(Value *V) {
2654 assert(V != Induction && "The new induction variable should not be used.");
2655 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2656 assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2658 // If we have a stride that is replaced by one, do it here.
2659 if (Legal->hasStride(V))
2660 V = ConstantInt::get(V->getType(), 1);
2662 // If we have this scalar in the map, return it.
2663 if (VectorLoopValueMap.hasVector(V))
2664 return VectorLoopValueMap.VectorMapStorage[V];
2666 // If the value has not been vectorized, check if it has been scalarized
2667 // instead. If it has been scalarized, and we actually need the value in
2668 // vector form, we will construct the vector values on demand.
2669 if (VectorLoopValueMap.hasScalar(V)) {
2671 // Initialize a new vector map entry.
2672 VectorParts Entry(UF);
2674 // If we've scalarized a value, that value should be an instruction.
2675 auto *I = cast<Instruction>(V);
2677 // If we aren't vectorizing, we can just copy the scalar map values over to
2680 for (unsigned Part = 0; Part < UF; ++Part)
2681 Entry[Part] = getScalarValue(V, Part, 0);
2682 return VectorLoopValueMap.initVector(V, Entry);
2685 // Get the last scalar instruction we generated for V. If the value is
2686 // known to be uniform after vectorization, this corresponds to lane zero
2687 // of the last unroll iteration. Otherwise, the last instruction is the one
2688 // we created for the last vector lane of the last unroll iteration.
2689 unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2690 auto *LastInst = cast<Instruction>(getScalarValue(V, UF - 1, LastLane));
2692 // Set the insert point after the last scalarized instruction. This ensures
2693 // the insertelement sequence will directly follow the scalar definitions.
2694 auto OldIP = Builder.saveIP();
2695 auto NewIP = std::next(BasicBlock::iterator(LastInst));
2696 Builder.SetInsertPoint(&*NewIP);
2698 // However, if we are vectorizing, we need to construct the vector values.
2699 // If the value is known to be uniform after vectorization, we can just
2700 // broadcast the scalar value corresponding to lane zero for each unroll
2701 // iteration. Otherwise, we construct the vector values using insertelement
2702 // instructions. Since the resulting vectors are stored in
2703 // VectorLoopValueMap, we will only generate the insertelements once.
2704 for (unsigned Part = 0; Part < UF; ++Part) {
2705 Value *VectorValue = nullptr;
2706 if (Cost->isUniformAfterVectorization(I, VF)) {
2707 VectorValue = getBroadcastInstrs(getScalarValue(V, Part, 0));
2709 VectorValue = UndefValue::get(VectorType::get(V->getType(), VF));
2710 for (unsigned Lane = 0; Lane < VF; ++Lane)
2711 VectorValue = Builder.CreateInsertElement(
2712 VectorValue, getScalarValue(V, Part, Lane),
2713 Builder.getInt32(Lane));
2715 Entry[Part] = VectorValue;
2717 Builder.restoreIP(OldIP);
2718 return VectorLoopValueMap.initVector(V, Entry);
2721 // If this scalar is unknown, assume that it is a constant or that it is
2722 // loop invariant. Broadcast V and save the value for future uses.
2723 Value *B = getBroadcastInstrs(V);
2724 return VectorLoopValueMap.initVector(V, VectorParts(UF, B));
2727 Value *InnerLoopVectorizer::getScalarValue(Value *V, unsigned Part,
2730 // If the value is not an instruction contained in the loop, it should
2731 // already be scalar.
2732 if (OrigLoop->isLoopInvariant(V))
2736 !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2737 : true && "Uniform values only have lane zero");
2739 // If the value from the original loop has not been vectorized, it is
2740 // represented by UF x VF scalar values in the new loop. Return the requested
2742 if (VectorLoopValueMap.hasScalar(V))
2743 return VectorLoopValueMap.ScalarMapStorage[V][Part][Lane];
2745 // If the value has not been scalarized, get its entry in VectorLoopValueMap
2746 // for the given unroll part. If this entry is not a vector type (i.e., the
2747 // vectorization factor is one), there is no need to generate an
2748 // extractelement instruction.
2749 auto *U = getVectorValue(V)[Part];
2750 if (!U->getType()->isVectorTy()) {
2751 assert(VF == 1 && "Value not scalarized has non-vector type");
2755 // Otherwise, the value from the original loop has been vectorized and is
2756 // represented by UF vector values. Extract and return the requested scalar
2757 // value from the appropriate vector lane.
2758 return Builder.CreateExtractElement(U, Builder.getInt32(Lane));
2761 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2762 assert(Vec->getType()->isVectorTy() && "Invalid type");
2763 SmallVector<Constant *, 8> ShuffleMask;
2764 for (unsigned i = 0; i < VF; ++i)
2765 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2767 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2768 ConstantVector::get(ShuffleMask),
2772 // Try to vectorize the interleave group that \p Instr belongs to.
2774 // E.g. Translate following interleaved load group (factor = 3):
2775 // for (i = 0; i < N; i+=3) {
2776 // R = Pic[i]; // Member of index 0
2777 // G = Pic[i+1]; // Member of index 1
2778 // B = Pic[i+2]; // Member of index 2
2779 // ... // do something to R, G, B
2782 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2783 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2784 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2785 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2787 // Or translate following interleaved store group (factor = 3):
2788 // for (i = 0; i < N; i+=3) {
2789 // ... do something to R, G, B
2790 // Pic[i] = R; // Member of index 0
2791 // Pic[i+1] = G; // Member of index 1
2792 // Pic[i+2] = B; // Member of index 2
2795 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2796 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2797 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2798 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2799 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2800 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2801 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2802 assert(Group && "Fail to get an interleaved access group.");
2804 // Skip if current instruction is not the insert position.
2805 if (Instr != Group->getInsertPos())
2808 Value *Ptr = getPointerOperand(Instr);
2810 // Prepare for the vector type of the interleaved load/store.
2811 Type *ScalarTy = getMemInstValueType(Instr);
2812 unsigned InterleaveFactor = Group->getFactor();
2813 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2814 Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2816 // Prepare for the new pointers.
2817 setDebugLocFromInst(Builder, Ptr);
2818 SmallVector<Value *, 2> NewPtrs;
2819 unsigned Index = Group->getIndex(Instr);
2821 // If the group is reverse, adjust the index to refer to the last vector lane
2822 // instead of the first. We adjust the index from the first vector lane,
2823 // rather than directly getting the pointer for lane VF - 1, because the
2824 // pointer operand of the interleaved access is supposed to be uniform. For
2825 // uniform instructions, we're only required to generate a value for the
2826 // first vector lane in each unroll iteration.
2827 if (Group->isReverse())
2828 Index += (VF - 1) * Group->getFactor();
2830 for (unsigned Part = 0; Part < UF; Part++) {
2831 Value *NewPtr = getScalarValue(Ptr, Part, 0);
2833 // Notice current instruction could be any index. Need to adjust the address
2834 // to the member of index 0.
2836 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2837 // b = A[i]; // Member of index 0
2838 // Current pointer is pointed to A[i+1], adjust it to A[i].
2840 // E.g. A[i+1] = a; // Member of index 1
2841 // A[i] = b; // Member of index 0
2842 // A[i+2] = c; // Member of index 2 (Current instruction)
2843 // Current pointer is pointed to A[i+2], adjust it to A[i].
2844 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2846 // Cast to the vector pointer type.
2847 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2850 setDebugLocFromInst(Builder, Instr);
2851 Value *UndefVec = UndefValue::get(VecTy);
2853 // Vectorize the interleaved load group.
2854 if (isa<LoadInst>(Instr)) {
2856 // For each unroll part, create a wide load for the group.
2857 SmallVector<Value *, 2> NewLoads;
2858 for (unsigned Part = 0; Part < UF; Part++) {
2859 auto *NewLoad = Builder.CreateAlignedLoad(
2860 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2861 addMetadata(NewLoad, Instr);
2862 NewLoads.push_back(NewLoad);
2865 // For each member in the group, shuffle out the appropriate data from the
2867 for (unsigned I = 0; I < InterleaveFactor; ++I) {
2868 Instruction *Member = Group->getMember(I);
2870 // Skip the gaps in the group.
2874 VectorParts Entry(UF);
2875 Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2876 for (unsigned Part = 0; Part < UF; Part++) {
2877 Value *StridedVec = Builder.CreateShuffleVector(
2878 NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2880 // If this member has different type, cast the result type.
2881 if (Member->getType() != ScalarTy) {
2882 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2883 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2887 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2889 VectorLoopValueMap.initVector(Member, Entry);
2894 // The sub vector type for current instruction.
2895 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2897 // Vectorize the interleaved store group.
2898 for (unsigned Part = 0; Part < UF; Part++) {
2899 // Collect the stored vector from each member.
2900 SmallVector<Value *, 4> StoredVecs;
2901 for (unsigned i = 0; i < InterleaveFactor; i++) {
2902 // Interleaved store group doesn't allow a gap, so each index has a member
2903 Instruction *Member = Group->getMember(i);
2904 assert(Member && "Fail to get a member from an interleaved store group");
2907 getVectorValue(cast<StoreInst>(Member)->getValueOperand())[Part];
2908 if (Group->isReverse())
2909 StoredVec = reverseVector(StoredVec);
2911 // If this member has different type, cast it to an unified type.
2912 if (StoredVec->getType() != SubVT)
2913 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2915 StoredVecs.push_back(StoredVec);
2918 // Concatenate all vectors into a wide vector.
2919 Value *WideVec = concatenateVectors(Builder, StoredVecs);
2921 // Interleave the elements in the wide vector.
2922 Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2923 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2926 Instruction *NewStoreInstr =
2927 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2928 addMetadata(NewStoreInstr, Instr);
2932 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2933 // Attempt to issue a wide load.
2934 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2935 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2937 assert((LI || SI) && "Invalid Load/Store instruction");
2939 LoopVectorizationCostModel::InstWidening Decision =
2940 Cost->getWideningDecision(Instr, VF);
2941 assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
2942 "CM decision should be taken at this point");
2943 if (Decision == LoopVectorizationCostModel::CM_Interleave)
2944 return vectorizeInterleaveGroup(Instr);
2946 Type *ScalarDataTy = getMemInstValueType(Instr);
2947 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2948 Value *Ptr = getPointerOperand(Instr);
2949 unsigned Alignment = getMemInstAlignment(Instr);
2950 // An alignment of 0 means target abi alignment. We need to use the scalar's
2951 // target abi alignment in such a case.
2952 const DataLayout &DL = Instr->getModule()->getDataLayout();
2954 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2955 unsigned AddressSpace = getMemInstAddressSpace(Instr);
2957 // Scalarize the memory instruction if necessary.
2958 if (Decision == LoopVectorizationCostModel::CM_Scalarize)
2959 return scalarizeInstruction(Instr, Legal->isScalarWithPredication(Instr));
2961 // Determine if the pointer operand of the access is either consecutive or
2962 // reverse consecutive.
2963 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2964 bool Reverse = ConsecutiveStride < 0;
2965 bool CreateGatherScatter =
2966 (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2968 VectorParts VectorGep;
2970 // Handle consecutive loads/stores.
2971 if (ConsecutiveStride) {
2972 Ptr = getScalarValue(Ptr, 0, 0);
2974 // At this point we should vector version of GEP for Gather or Scatter
2975 assert(CreateGatherScatter && "The instruction should be scalarized");
2976 VectorGep = getVectorValue(Ptr);
2979 VectorParts Mask = createBlockInMask(Instr->getParent());
2982 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2983 "We do not allow storing to uniform addresses");
2984 setDebugLocFromInst(Builder, SI);
2985 // We don't want to update the value in the map as it might be used in
2986 // another expression. So don't use a reference type for "StoredVal".
2987 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2989 for (unsigned Part = 0; Part < UF; ++Part) {
2990 Instruction *NewSI = nullptr;
2991 if (CreateGatherScatter) {
2992 Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr;
2993 NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part],
2994 Alignment, MaskPart);
2996 // Calculate the pointer for the specific unroll-part.
2998 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3001 // If we store to reverse consecutive memory locations, then we need
3002 // to reverse the order of elements in the stored value.
3003 StoredVal[Part] = reverseVector(StoredVal[Part]);
3004 // If the address is consecutive but reversed, then the
3005 // wide store needs to start at the last vector element.
3007 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3009 Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3010 Mask[Part] = reverseVector(Mask[Part]);
3014 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3016 if (Legal->isMaskRequired(SI))
3017 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
3021 Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
3023 addMetadata(NewSI, SI);
3029 assert(LI && "Must have a load instruction");
3030 setDebugLocFromInst(Builder, LI);
3031 VectorParts Entry(UF);
3032 for (unsigned Part = 0; Part < UF; ++Part) {
3034 if (CreateGatherScatter) {
3035 Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr;
3036 NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment, MaskPart,
3037 0, "wide.masked.gather");
3038 Entry[Part] = NewLI;
3040 // Calculate the pointer for the specific unroll-part.
3042 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3045 // If the address is consecutive but reversed, then the
3046 // wide load needs to start at the last vector element.
3047 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3048 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3049 Mask[Part] = reverseVector(Mask[Part]);
3053 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3054 if (Legal->isMaskRequired(LI))
3055 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
3056 UndefValue::get(DataTy),
3057 "wide.masked.load");
3059 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
3060 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
3062 addMetadata(NewLI, LI);
3064 VectorLoopValueMap.initVector(Instr, Entry);
3067 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
3068 bool IfPredicateInstr) {
3069 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3070 DEBUG(dbgs() << "LV: Scalarizing"
3071 << (IfPredicateInstr ? " and predicating:" : ":") << *Instr
3073 // Holds vector parameters or scalars, in case of uniform vals.
3074 SmallVector<VectorParts, 4> Params;
3076 setDebugLocFromInst(Builder, Instr);
3078 // Does this instruction return a value ?
3079 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3081 // Initialize a new scalar map entry.
3082 ScalarParts Entry(UF);
3085 if (IfPredicateInstr)
3086 Cond = createBlockInMask(Instr->getParent());
3088 // Determine the number of scalars we need to generate for each unroll
3089 // iteration. If the instruction is uniform, we only need to generate the
3090 // first lane. Otherwise, we generate all VF values.
3091 unsigned Lanes = Cost->isUniformAfterVectorization(Instr, VF) ? 1 : VF;
3093 // For each vector unroll 'part':
3094 for (unsigned Part = 0; Part < UF; ++Part) {
3095 Entry[Part].resize(VF);
3096 // For each scalar that we create:
3097 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
3100 Value *Cmp = nullptr;
3101 if (IfPredicateInstr) {
3103 if (Cmp->getType()->isVectorTy())
3104 Cmp = Builder.CreateExtractElement(Cmp, Builder.getInt32(Lane));
3105 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
3106 ConstantInt::get(Cmp->getType(), 1));
3109 Instruction *Cloned = Instr->clone();
3111 Cloned->setName(Instr->getName() + ".cloned");
3113 // Replace the operands of the cloned instructions with their scalar
3114 // equivalents in the new loop.
3115 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
3116 auto *NewOp = getScalarValue(Instr->getOperand(op), Part, Lane);
3117 Cloned->setOperand(op, NewOp);
3119 addNewMetadata(Cloned, Instr);
3121 // Place the cloned scalar in the new loop.
3122 Builder.Insert(Cloned);
3124 // Add the cloned scalar to the scalar map entry.
3125 Entry[Part][Lane] = Cloned;
3127 // If we just cloned a new assumption, add it the assumption cache.
3128 if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
3129 if (II->getIntrinsicID() == Intrinsic::assume)
3130 AC->registerAssumption(II);
3133 if (IfPredicateInstr)
3134 PredicatedInstructions.push_back(std::make_pair(Cloned, Cmp));
3137 VectorLoopValueMap.initScalar(Instr, Entry);
3140 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3141 Value *End, Value *Step,
3143 BasicBlock *Header = L->getHeader();
3144 BasicBlock *Latch = L->getLoopLatch();
3145 // As we're just creating this loop, it's possible no latch exists
3146 // yet. If so, use the header as this will be a single block loop.
3150 IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3151 Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3152 setDebugLocFromInst(Builder, OldInst);
3153 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3155 Builder.SetInsertPoint(Latch->getTerminator());
3156 setDebugLocFromInst(Builder, OldInst);
3158 // Create i+1 and fill the PHINode.
3159 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3160 Induction->addIncoming(Start, L->getLoopPreheader());
3161 Induction->addIncoming(Next, Latch);
3162 // Create the compare.
3163 Value *ICmp = Builder.CreateICmpEQ(Next, End);
3164 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
3166 // Now we have two terminators. Remove the old one from the block.
3167 Latch->getTerminator()->eraseFromParent();
3172 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3176 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3177 // Find the loop boundaries.
3178 ScalarEvolution *SE = PSE.getSE();
3179 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3180 assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
3181 "Invalid loop count");
3183 Type *IdxTy = Legal->getWidestInductionType();
3185 // The exit count might have the type of i64 while the phi is i32. This can
3186 // happen if we have an induction variable that is sign extended before the
3187 // compare. The only way that we get a backedge taken count is that the
3188 // induction variable was signed and as such will not overflow. In such a case
3189 // truncation is legal.
3190 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
3191 IdxTy->getPrimitiveSizeInBits())
3192 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3193 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3195 // Get the total trip count from the count by adding 1.
3196 const SCEV *ExitCount = SE->getAddExpr(
3197 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3199 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3201 // Expand the trip count and place the new instructions in the preheader.
3202 // Notice that the pre-header does not change, only the loop body.
3203 SCEVExpander Exp(*SE, DL, "induction");
3205 // Count holds the overall loop count (N).
3206 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3207 L->getLoopPreheader()->getTerminator());
3209 if (TripCount->getType()->isPointerTy())
3211 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3212 L->getLoopPreheader()->getTerminator());
3217 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3218 if (VectorTripCount)
3219 return VectorTripCount;
3221 Value *TC = getOrCreateTripCount(L);
3222 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3224 // Now we need to generate the expression for the part of the loop that the
3225 // vectorized body will execute. This is equal to N - (N % Step) if scalar
3226 // iterations are not required for correctness, or N - Step, otherwise. Step
3227 // is equal to the vectorization factor (number of SIMD elements) times the
3228 // unroll factor (number of SIMD instructions).
3229 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
3230 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3232 // If there is a non-reversed interleaved group that may speculatively access
3233 // memory out-of-bounds, we need to ensure that there will be at least one
3234 // iteration of the scalar epilogue loop. Thus, if the step evenly divides
3235 // the trip count, we set the remainder to be equal to the step. If the step
3236 // does not evenly divide the trip count, no adjustment is necessary since
3237 // there will already be scalar iterations. Note that the minimum iterations
3238 // check ensures that N >= Step.
3239 if (VF > 1 && Legal->requiresScalarEpilogue()) {
3240 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3241 R = Builder.CreateSelect(IsZero, Step, R);
3244 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3246 return VectorTripCount;
3249 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3250 BasicBlock *Bypass) {
3251 Value *Count = getOrCreateTripCount(L);
3252 BasicBlock *BB = L->getLoopPreheader();
3253 IRBuilder<> Builder(BB->getTerminator());
3255 // Generate code to check that the loop's trip count that we computed by
3256 // adding one to the backedge-taken count will not overflow.
3257 Value *CheckMinIters = Builder.CreateICmpULT(
3258 Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
3261 BB->splitBasicBlock(BB->getTerminator(), "min.iters.checked");
3262 // Update dominator tree immediately if the generated block is a
3263 // LoopBypassBlock because SCEV expansions to generate loop bypass
3264 // checks may query it before the current function is finished.
3265 DT->addNewBlock(NewBB, BB);
3266 if (L->getParentLoop())
3267 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3268 ReplaceInstWithInst(BB->getTerminator(),
3269 BranchInst::Create(Bypass, NewBB, CheckMinIters));
3270 LoopBypassBlocks.push_back(BB);
3273 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
3274 BasicBlock *Bypass) {
3275 Value *TC = getOrCreateVectorTripCount(L);
3276 BasicBlock *BB = L->getLoopPreheader();
3277 IRBuilder<> Builder(BB->getTerminator());
3279 // Now, compare the new count to zero. If it is zero skip the vector loop and
3280 // jump to the scalar loop.
3281 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
3284 // Generate code to check that the loop's trip count that we computed by
3285 // adding one to the backedge-taken count will not overflow.
3286 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3287 // Update dominator tree immediately if the generated block is a
3288 // LoopBypassBlock because SCEV expansions to generate loop bypass
3289 // checks may query it before the current function is finished.
3290 DT->addNewBlock(NewBB, BB);
3291 if (L->getParentLoop())
3292 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3293 ReplaceInstWithInst(BB->getTerminator(),
3294 BranchInst::Create(Bypass, NewBB, Cmp));
3295 LoopBypassBlocks.push_back(BB);
3298 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3299 BasicBlock *BB = L->getLoopPreheader();
3301 // Generate the code to check that the SCEV assumptions that we made.
3302 // We want the new basic block to start at the first instruction in a
3303 // sequence of instructions that form a check.
3304 SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
3307 Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
3309 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3313 // Create a new block containing the stride check.
3314 BB->setName("vector.scevcheck");
3315 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3316 // Update dominator tree immediately if the generated block is a
3317 // LoopBypassBlock because SCEV expansions to generate loop bypass
3318 // checks may query it before the current function is finished.
3319 DT->addNewBlock(NewBB, BB);
3320 if (L->getParentLoop())
3321 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3322 ReplaceInstWithInst(BB->getTerminator(),
3323 BranchInst::Create(Bypass, NewBB, SCEVCheck));
3324 LoopBypassBlocks.push_back(BB);
3325 AddedSafetyChecks = true;
3328 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
3329 BasicBlock *BB = L->getLoopPreheader();
3331 // Generate the code that checks in runtime if arrays overlap. We put the
3332 // checks into a separate block to make the more common case of few elements
3334 Instruction *FirstCheckInst;
3335 Instruction *MemRuntimeCheck;
3336 std::tie(FirstCheckInst, MemRuntimeCheck) =
3337 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
3338 if (!MemRuntimeCheck)
3341 // Create a new block containing the memory check.
3342 BB->setName("vector.memcheck");
3343 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3344 // Update dominator tree immediately if the generated block is a
3345 // LoopBypassBlock because SCEV expansions to generate loop bypass
3346 // checks may query it before the current function is finished.
3347 DT->addNewBlock(NewBB, BB);
3348 if (L->getParentLoop())
3349 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3350 ReplaceInstWithInst(BB->getTerminator(),
3351 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
3352 LoopBypassBlocks.push_back(BB);
3353 AddedSafetyChecks = true;
3355 // We currently don't use LoopVersioning for the actual loop cloning but we
3356 // still use it to add the noalias metadata.
3357 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3359 LVer->prepareNoAliasMetadata();
3362 void InnerLoopVectorizer::createEmptyLoop() {
3364 In this function we generate a new loop. The new loop will contain
3365 the vectorized instructions while the old loop will continue to run the
3368 [ ] <-- loop iteration number check.
3371 | [ ] <-- vector loop bypass (may consist of multiple blocks).
3374 || [ ] <-- vector pre header.
3378 | [ ]_| <-- vector loop.
3381 | -[ ] <--- middle-block.
3384 -|- >[ ] <--- new preheader.
3388 | [ ]_| <-- old scalar loop to handle remainder.
3391 >[ ] <-- exit block.
3395 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3396 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3397 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3398 assert(VectorPH && "Invalid loop structure");
3399 assert(ExitBlock && "Must have an exit block");
3401 // Some loops have a single integer induction variable, while other loops
3402 // don't. One example is c++ iterators that often have multiple pointer
3403 // induction variables. In the code below we also support a case where we
3404 // don't have a single induction variable.
3406 // We try to obtain an induction variable from the original loop as hard
3407 // as possible. However if we don't find one that:
3409 // - counts from zero, stepping by one
3410 // - is the size of the widest induction variable type
3411 // then we create a new one.
3412 OldInduction = Legal->getPrimaryInduction();
3413 Type *IdxTy = Legal->getWidestInductionType();
3415 // Split the single block loop into the two loop structure described above.
3416 BasicBlock *VecBody =
3417 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
3418 BasicBlock *MiddleBlock =
3419 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
3420 BasicBlock *ScalarPH =
3421 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
3423 // Create and register the new vector loop.
3424 Loop *Lp = new Loop();
3425 Loop *ParentLoop = OrigLoop->getParentLoop();
3427 // Insert the new loop into the loop nest and register the new basic blocks
3428 // before calling any utilities such as SCEV that require valid LoopInfo.
3430 ParentLoop->addChildLoop(Lp);
3431 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
3432 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
3434 LI->addTopLevelLoop(Lp);
3436 Lp->addBasicBlockToLoop(VecBody, *LI);
3438 // Find the loop boundaries.
3439 Value *Count = getOrCreateTripCount(Lp);
3441 Value *StartIdx = ConstantInt::get(IdxTy, 0);
3443 // We need to test whether the backedge-taken count is uint##_max. Adding one
3444 // to it will cause overflow and an incorrect loop trip count in the vector
3445 // body. In case of overflow we want to directly jump to the scalar remainder
3447 emitMinimumIterationCountCheck(Lp, ScalarPH);
3448 // Now, compare the new count to zero. If it is zero skip the vector loop and
3449 // jump to the scalar loop.
3450 emitVectorLoopEnteredCheck(Lp, ScalarPH);
3451 // Generate the code to check any assumptions that we've made for SCEV
3453 emitSCEVChecks(Lp, ScalarPH);
3455 // Generate the code that checks in runtime if arrays overlap. We put the
3456 // checks into a separate block to make the more common case of few elements
3458 emitMemRuntimeChecks(Lp, ScalarPH);
3460 // Generate the induction variable.
3461 // The loop step is equal to the vectorization factor (num of SIMD elements)
3462 // times the unroll factor (num of SIMD instructions).
3463 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3464 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
3466 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3467 getDebugLocFromInstOrOperands(OldInduction));
3469 // We are going to resume the execution of the scalar loop.
3470 // Go over all of the induction variables that we found and fix the
3471 // PHIs that are left in the scalar version of the loop.
3472 // The starting values of PHI nodes depend on the counter of the last
3473 // iteration in the vectorized loop.
3474 // If we come from a bypass edge then we need to start from the original
3477 // This variable saves the new starting index for the scalar loop. It is used
3478 // to test if there are any tail iterations left once the vector loop has
3480 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
3481 for (auto &InductionEntry : *List) {
3482 PHINode *OrigPhi = InductionEntry.first;
3483 InductionDescriptor II = InductionEntry.second;
3485 // Create phi nodes to merge from the backedge-taken check block.
3486 PHINode *BCResumeVal = PHINode::Create(
3487 OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
3488 Value *&EndValue = IVEndValues[OrigPhi];
3489 if (OrigPhi == OldInduction) {
3490 // We know what the end value is.
3491 EndValue = CountRoundDown;
3493 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
3494 Type *StepType = II.getStep()->getType();
3495 Instruction::CastOps CastOp =
3496 CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
3497 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
3498 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3499 EndValue = II.transform(B, CRD, PSE.getSE(), DL);
3500 EndValue->setName("ind.end");
3503 // The new PHI merges the original incoming value, in case of a bypass,
3504 // or the value at the end of the vectorized loop.
3505 BCResumeVal->addIncoming(EndValue, MiddleBlock);
3507 // Fix the scalar body counter (PHI node).
3508 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
3510 // The old induction's phi node in the scalar body needs the truncated
3512 for (BasicBlock *BB : LoopBypassBlocks)
3513 BCResumeVal->addIncoming(II.getStartValue(), BB);
3514 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
3517 // Add a check in the middle block to see if we have completed
3518 // all of the iterations in the first vector loop.
3519 // If (N - N%VF) == N, then we *don't* need to run the remainder.
3521 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3522 CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
3523 ReplaceInstWithInst(MiddleBlock->getTerminator(),
3524 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
3526 // Get ready to start creating new instructions into the vectorized body.
3527 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
3530 LoopVectorPreHeader = Lp->getLoopPreheader();
3531 LoopScalarPreHeader = ScalarPH;
3532 LoopMiddleBlock = MiddleBlock;
3533 LoopExitBlock = ExitBlock;
3534 LoopVectorBody = VecBody;
3535 LoopScalarBody = OldBasicBlock;
3537 // Keep all loop hints from the original loop on the vector loop (we'll
3538 // replace the vectorizer-specific hints below).
3539 if (MDNode *LID = OrigLoop->getLoopID())
3542 LoopVectorizeHints Hints(Lp, true, *ORE);
3543 Hints.setAlreadyVectorized();
3546 // Fix up external users of the induction variable. At this point, we are
3547 // in LCSSA form, with all external PHIs that use the IV having one input value,
3548 // coming from the remainder loop. We need those PHIs to also have a correct
3549 // value for the IV when arriving directly from the middle block.
3550 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3551 const InductionDescriptor &II,
3552 Value *CountRoundDown, Value *EndValue,
3553 BasicBlock *MiddleBlock) {
3554 // There are two kinds of external IV usages - those that use the value
3555 // computed in the last iteration (the PHI) and those that use the penultimate
3556 // value (the value that feeds into the phi from the loop latch).
3557 // We allow both, but they, obviously, have different values.
3559 assert(OrigLoop->getExitBlock() && "Expected a single exit block");
3561 DenseMap<Value *, Value *> MissingVals;
3563 // An external user of the last iteration's value should see the value that
3564 // the remainder loop uses to initialize its own IV.
3565 Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3566 for (User *U : PostInc->users()) {
3567 Instruction *UI = cast<Instruction>(U);
3568 if (!OrigLoop->contains(UI)) {
3569 assert(isa<PHINode>(UI) && "Expected LCSSA form");
3570 MissingVals[UI] = EndValue;
3574 // An external user of the penultimate value need to see EndValue - Step.
3575 // The simplest way to get this is to recompute it from the constituent SCEVs,
3576 // that is Start + (Step * (CRD - 1)).
3577 for (User *U : OrigPhi->users()) {
3578 auto *UI = cast<Instruction>(U);
3579 if (!OrigLoop->contains(UI)) {
3580 const DataLayout &DL =
3581 OrigLoop->getHeader()->getModule()->getDataLayout();
3582 assert(isa<PHINode>(UI) && "Expected LCSSA form");
3584 IRBuilder<> B(MiddleBlock->getTerminator());
3585 Value *CountMinusOne = B.CreateSub(
3586 CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3587 Value *CMO = B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType(),
3589 Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3590 Escape->setName("ind.escape");
3591 MissingVals[UI] = Escape;
3595 for (auto &I : MissingVals) {
3596 PHINode *PHI = cast<PHINode>(I.first);
3597 // One corner case we have to handle is two IVs "chasing" each-other,
3598 // that is %IV2 = phi [...], [ %IV1, %latch ]
3599 // In this case, if IV1 has an external use, we need to avoid adding both
3600 // "last value of IV1" and "penultimate value of IV2". So, verify that we
3601 // don't already have an incoming value for the middle block.
3602 if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3603 PHI->addIncoming(I.second, MiddleBlock);
3608 struct CSEDenseMapInfo {
3609 static bool canHandle(const Instruction *I) {
3610 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3611 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3613 static inline Instruction *getEmptyKey() {
3614 return DenseMapInfo<Instruction *>::getEmptyKey();
3616 static inline Instruction *getTombstoneKey() {
3617 return DenseMapInfo<Instruction *>::getTombstoneKey();
3619 static unsigned getHashValue(const Instruction *I) {
3620 assert(canHandle(I) && "Unknown instruction!");
3621 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3622 I->value_op_end()));
3624 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3625 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3626 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3628 return LHS->isIdenticalTo(RHS);
3633 ///\brief Perform cse of induction variable instructions.
3634 static void cse(BasicBlock *BB) {
3635 // Perform simple cse.
3636 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3637 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3638 Instruction *In = &*I++;
3640 if (!CSEDenseMapInfo::canHandle(In))
3643 // Check if we can replace this instruction with any of the
3644 // visited instructions.
3645 if (Instruction *V = CSEMap.lookup(In)) {
3646 In->replaceAllUsesWith(V);
3647 In->eraseFromParent();
3655 /// \brief Estimate the overhead of scalarizing an instruction. This is a
3656 /// convenience wrapper for the type-based getScalarizationOverhead API.
3657 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3658 const TargetTransformInfo &TTI) {
3663 Type *RetTy = ToVectorTy(I->getType(), VF);
3664 if (!RetTy->isVoidTy() &&
3665 (!isa<LoadInst>(I) ||
3666 !TTI.supportsEfficientVectorElementLoadStore()))
3667 Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3669 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3670 SmallVector<const Value *, 4> Operands(CI->arg_operands());
3671 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3673 else if (!isa<StoreInst>(I) ||
3674 !TTI.supportsEfficientVectorElementLoadStore()) {
3675 SmallVector<const Value *, 4> Operands(I->operand_values());
3676 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3682 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3683 // Return the cost of the instruction, including scalarization overhead if it's
3684 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3685 // i.e. either vector version isn't available, or is too expensive.
3686 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3687 const TargetTransformInfo &TTI,
3688 const TargetLibraryInfo *TLI,
3689 bool &NeedToScalarize) {
3690 Function *F = CI->getCalledFunction();
3691 StringRef FnName = CI->getCalledFunction()->getName();
3692 Type *ScalarRetTy = CI->getType();
3693 SmallVector<Type *, 4> Tys, ScalarTys;
3694 for (auto &ArgOp : CI->arg_operands())
3695 ScalarTys.push_back(ArgOp->getType());
3697 // Estimate cost of scalarized vector call. The source operands are assumed
3698 // to be vectors, so we need to extract individual elements from there,
3699 // execute VF scalar calls, and then gather the result into the vector return
3701 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3703 return ScalarCallCost;
3705 // Compute corresponding vector type for return value and arguments.
3706 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3707 for (Type *ScalarTy : ScalarTys)
3708 Tys.push_back(ToVectorTy(ScalarTy, VF));
3710 // Compute costs of unpacking argument values for the scalar calls and
3711 // packing the return values to a vector.
3712 unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3714 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3716 // If we can't emit a vector call for this function, then the currently found
3717 // cost is the cost we need to return.
3718 NeedToScalarize = true;
3719 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3722 // If the corresponding vector cost is cheaper, return its cost.
3723 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3724 if (VectorCallCost < Cost) {
3725 NeedToScalarize = false;
3726 return VectorCallCost;
3731 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3732 // factor VF. Return the cost of the instruction, including scalarization
3733 // overhead if it's needed.
3734 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3735 const TargetTransformInfo &TTI,
3736 const TargetLibraryInfo *TLI) {
3737 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3738 assert(ID && "Expected intrinsic call!");
3741 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3742 FMF = FPMO->getFastMathFlags();
3744 SmallVector<Value *, 4> Operands(CI->arg_operands());
3745 return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3748 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3749 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3750 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3751 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3753 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3754 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3755 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3756 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3759 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3760 // For every instruction `I` in MinBWs, truncate the operands, create a
3761 // truncated version of `I` and reextend its result. InstCombine runs
3762 // later and will remove any ext/trunc pairs.
3764 SmallPtrSet<Value *, 4> Erased;
3765 for (const auto &KV : Cost->getMinimalBitwidths()) {
3766 // If the value wasn't vectorized, we must maintain the original scalar
3767 // type. The absence of the value from VectorLoopValueMap indicates that it
3768 // wasn't vectorized.
3769 if (!VectorLoopValueMap.hasVector(KV.first))
3771 VectorParts &Parts = VectorLoopValueMap.getVector(KV.first);
3772 for (Value *&I : Parts) {
3773 if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3775 Type *OriginalTy = I->getType();
3776 Type *ScalarTruncatedTy =
3777 IntegerType::get(OriginalTy->getContext(), KV.second);
3778 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3779 OriginalTy->getVectorNumElements());
3780 if (TruncatedTy == OriginalTy)
3783 IRBuilder<> B(cast<Instruction>(I));
3784 auto ShrinkOperand = [&](Value *V) -> Value * {
3785 if (auto *ZI = dyn_cast<ZExtInst>(V))
3786 if (ZI->getSrcTy() == TruncatedTy)
3787 return ZI->getOperand(0);
3788 return B.CreateZExtOrTrunc(V, TruncatedTy);
3791 // The actual instruction modification depends on the instruction type,
3793 Value *NewI = nullptr;
3794 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3795 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3796 ShrinkOperand(BO->getOperand(1)));
3797 cast<BinaryOperator>(NewI)->copyIRFlags(I);
3798 } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3800 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3801 ShrinkOperand(CI->getOperand(1)));
3802 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3803 NewI = B.CreateSelect(SI->getCondition(),
3804 ShrinkOperand(SI->getTrueValue()),
3805 ShrinkOperand(SI->getFalseValue()));
3806 } else if (auto *CI = dyn_cast<CastInst>(I)) {
3807 switch (CI->getOpcode()) {
3809 llvm_unreachable("Unhandled cast!");
3810 case Instruction::Trunc:
3811 NewI = ShrinkOperand(CI->getOperand(0));
3813 case Instruction::SExt:
3814 NewI = B.CreateSExtOrTrunc(
3816 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3818 case Instruction::ZExt:
3819 NewI = B.CreateZExtOrTrunc(
3821 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3824 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3825 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3826 auto *O0 = B.CreateZExtOrTrunc(
3827 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3828 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3829 auto *O1 = B.CreateZExtOrTrunc(
3830 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3832 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3833 } else if (isa<LoadInst>(I)) {
3834 // Don't do anything with the operands, just extend the result.
3836 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3837 auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3838 auto *O0 = B.CreateZExtOrTrunc(
3839 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3840 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3841 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3842 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3843 auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3844 auto *O0 = B.CreateZExtOrTrunc(
3845 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3846 NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3848 llvm_unreachable("Unhandled instruction type!");
3851 // Lastly, extend the result.
3852 NewI->takeName(cast<Instruction>(I));
3853 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3854 I->replaceAllUsesWith(Res);
3855 cast<Instruction>(I)->eraseFromParent();
3861 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3862 for (const auto &KV : Cost->getMinimalBitwidths()) {
3863 // If the value wasn't vectorized, we must maintain the original scalar
3864 // type. The absence of the value from VectorLoopValueMap indicates that it
3865 // wasn't vectorized.
3866 if (!VectorLoopValueMap.hasVector(KV.first))
3868 VectorParts &Parts = VectorLoopValueMap.getVector(KV.first);
3869 for (Value *&I : Parts) {
3870 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3871 if (Inst && Inst->use_empty()) {
3872 Value *NewI = Inst->getOperand(0);
3873 Inst->eraseFromParent();
3880 void InnerLoopVectorizer::vectorizeLoop() {
3881 //===------------------------------------------------===//
3883 // Notice: any optimization or new instruction that go
3884 // into the code below should be also be implemented in
3887 //===------------------------------------------------===//
3889 // Collect instructions from the original loop that will become trivially dead
3890 // in the vectorized loop. We don't need to vectorize these instructions. For
3891 // example, original induction update instructions can become dead because we
3892 // separately emit induction "steps" when generating code for the new loop.
3893 // Similarly, we create a new latch condition when setting up the structure
3894 // of the new loop, so the old one can become dead.
3895 SmallPtrSet<Instruction *, 4> DeadInstructions;
3896 collectTriviallyDeadInstructions(DeadInstructions);
3898 // Scan the loop in a topological order to ensure that defs are vectorized
3900 LoopBlocksDFS DFS(OrigLoop);
3903 // Vectorize all instructions in the original loop that will not become
3904 // trivially dead when vectorized.
3905 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
3906 for (Instruction &I : *BB)
3907 if (!DeadInstructions.count(&I))
3908 vectorizeInstruction(I);
3910 // Insert truncates and extends for any truncated instructions as hints to
3913 truncateToMinimalBitwidths();
3915 // At this point every instruction in the original loop is widened to a
3916 // vector form. Now we need to fix the recurrences in the loop. These PHI
3917 // nodes are currently empty because we did not want to introduce cycles.
3918 // This is the second stage of vectorizing recurrences.
3919 fixCrossIterationPHIs();
3921 // Update the dominator tree.
3923 // FIXME: After creating the structure of the new loop, the dominator tree is
3924 // no longer up-to-date, and it remains that way until we update it
3925 // here. An out-of-date dominator tree is problematic for SCEV,
3926 // because SCEVExpander uses it to guide code generation. The
3927 // vectorizer use SCEVExpanders in several places. Instead, we should
3928 // keep the dominator tree up-to-date as we go.
3931 // Fix-up external users of the induction variables.
3932 for (auto &Entry : *Legal->getInductionVars())
3933 fixupIVUsers(Entry.first, Entry.second,
3934 getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3935 IVEndValues[Entry.first], LoopMiddleBlock);
3938 predicateInstructions();
3940 // Remove redundant induction instructions.
3941 cse(LoopVectorBody);
3944 void InnerLoopVectorizer::fixCrossIterationPHIs() {
3945 // In order to support recurrences we need to be able to vectorize Phi nodes.
3946 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3947 // stage #2: We now need to fix the recurrences by adding incoming edges to
3948 // the currently empty PHI nodes. At this point every instruction in the
3949 // original loop is widened to a vector form so we can use them to construct
3950 // the incoming edges.
3951 for (Instruction &I : *OrigLoop->getHeader()) {
3952 PHINode *Phi = dyn_cast<PHINode>(&I);
3955 // Handle first-order recurrences and reductions that need to be fixed.
3956 if (Legal->isFirstOrderRecurrence(Phi))
3957 fixFirstOrderRecurrence(Phi);
3958 else if (Legal->isReductionVariable(Phi))
3963 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3965 // This is the second phase of vectorizing first-order recurrences. An
3966 // overview of the transformation is described below. Suppose we have the
3969 // for (int i = 0; i < n; ++i)
3970 // b[i] = a[i] - a[i - 1];
3972 // There is a first-order recurrence on "a". For this loop, the shorthand
3973 // scalar IR looks like:
3980 // i = phi [0, scalar.ph], [i+1, scalar.body]
3981 // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3984 // br cond, scalar.body, ...
3986 // In this example, s1 is a recurrence because it's value depends on the
3987 // previous iteration. In the first phase of vectorization, we created a
3988 // temporary value for s1. We now complete the vectorization and produce the
3989 // shorthand vector IR shown below (for VF = 4, UF = 1).
3992 // v_init = vector(..., ..., ..., a[-1])
3996 // i = phi [0, vector.ph], [i+4, vector.body]
3997 // v1 = phi [v_init, vector.ph], [v2, vector.body]
3998 // v2 = a[i, i+1, i+2, i+3];
3999 // v3 = vector(v1(3), v2(0, 1, 2))
4000 // b[i, i+1, i+2, i+3] = v2 - v3
4001 // br cond, vector.body, middle.block
4008 // s_init = phi [x, middle.block], [a[-1], otherwise]
4011 // After execution completes the vector loop, we extract the next value of
4012 // the recurrence (x) to use as the initial value in the scalar loop.
4014 // Get the original loop preheader and single loop latch.
4015 auto *Preheader = OrigLoop->getLoopPreheader();
4016 auto *Latch = OrigLoop->getLoopLatch();
4018 // Get the initial and previous values of the scalar recurrence.
4019 auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4020 auto *Previous = Phi->getIncomingValueForBlock(Latch);
4022 // Create a vector from the initial value.
4023 auto *VectorInit = ScalarInit;
4025 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4026 VectorInit = Builder.CreateInsertElement(
4027 UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4028 Builder.getInt32(VF - 1), "vector.recur.init");
4031 // We constructed a temporary phi node in the first phase of vectorization.
4032 // This phi node will eventually be deleted.
4033 VectorParts &PhiParts = VectorLoopValueMap.getVector(Phi);
4034 Builder.SetInsertPoint(cast<Instruction>(PhiParts[0]));
4036 // Create a phi node for the new recurrence. The current value will either be
4037 // the initial value inserted into a vector or loop-varying vector value.
4038 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4039 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4041 // Get the vectorized previous value.
4042 auto &PreviousParts = getVectorValue(Previous);
4044 // Set the insertion point after the previous value if it is an instruction.
4045 // Note that the previous value may have been constant-folded so it is not
4046 // guaranteed to be an instruction in the vector loop.
4047 if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousParts[UF - 1]))
4048 Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4050 Builder.SetInsertPoint(
4051 &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1])));
4053 // We will construct a vector for the recurrence by combining the values for
4054 // the current and previous iterations. This is the required shuffle mask.
4055 SmallVector<Constant *, 8> ShuffleMask(VF);
4056 ShuffleMask[0] = Builder.getInt32(VF - 1);
4057 for (unsigned I = 1; I < VF; ++I)
4058 ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4060 // The vector from which to take the initial value for the current iteration
4061 // (actual or unrolled). Initially, this is the vector phi node.
4062 Value *Incoming = VecPhi;
4064 // Shuffle the current and previous vector and update the vector parts.
4065 for (unsigned Part = 0; Part < UF; ++Part) {
4068 ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part],
4069 ConstantVector::get(ShuffleMask))
4071 PhiParts[Part]->replaceAllUsesWith(Shuffle);
4072 cast<Instruction>(PhiParts[Part])->eraseFromParent();
4073 PhiParts[Part] = Shuffle;
4074 Incoming = PreviousParts[Part];
4077 // Fix the latch value of the new recurrence in the vector loop.
4078 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4080 // Extract the last vector element in the middle block. This will be the
4081 // initial value for the recurrence when jumping to the scalar loop.
4082 auto *ExtractForScalar = Incoming;
4084 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4085 ExtractForScalar = Builder.CreateExtractElement(
4086 ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
4088 // Extract the second last element in the middle block if the
4089 // Phi is used outside the loop. We need to extract the phi itself
4090 // and not the last element (the phi update in the current iteration). This
4091 // will be the value when jumping to the exit block from the LoopMiddleBlock,
4092 // when the scalar loop is not run at all.
4093 Value *ExtractForPhiUsedOutsideLoop = nullptr;
4095 ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4096 Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
4097 // When loop is unrolled without vectorizing, initialize
4098 // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4099 // `Incoming`. This is analogous to the vectorized case above: extracting the
4100 // second last element when VF > 1.
4102 ExtractForPhiUsedOutsideLoop = PreviousParts[UF - 2];
4104 // Fix the initial value of the original recurrence in the scalar loop.
4105 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4106 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4107 for (auto *BB : predecessors(LoopScalarPreHeader)) {
4108 auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4109 Start->addIncoming(Incoming, BB);
4112 Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4113 Phi->setName("scalar.recur");
4115 // Finally, fix users of the recurrence outside the loop. The users will need
4116 // either the last value of the scalar recurrence or the last value of the
4117 // vector recurrence we extracted in the middle block. Since the loop is in
4118 // LCSSA form, we just need to find the phi node for the original scalar
4119 // recurrence in the exit block, and then add an edge for the middle block.
4120 for (auto &I : *LoopExitBlock) {
4121 auto *LCSSAPhi = dyn_cast<PHINode>(&I);
4124 if (LCSSAPhi->getIncomingValue(0) == Phi) {
4125 LCSSAPhi->addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4131 void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
4132 Constant *Zero = Builder.getInt32(0);
4134 // Get it's reduction variable descriptor.
4135 assert(Legal->isReductionVariable(Phi) &&
4136 "Unable to find the reduction variable");
4137 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
4139 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
4140 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4141 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4142 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
4143 RdxDesc.getMinMaxRecurrenceKind();
4144 setDebugLocFromInst(Builder, ReductionStartValue);
4146 // We need to generate a reduction vector from the incoming scalar.
4147 // To do so, we need to generate the 'identity' vector and override
4148 // one of the elements with the incoming scalar reduction. We need
4149 // to do it in the vector-loop preheader.
4150 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
4152 // This is the vector-clone of the value that leaves the loop.
4153 const VectorParts &VectorExit = getVectorValue(LoopExitInst);
4154 Type *VecTy = VectorExit[0]->getType();
4156 // Find the reduction identity variable. Zero for addition, or, xor,
4157 // one for multiplication, -1 for And.
4160 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
4161 RK == RecurrenceDescriptor::RK_FloatMinMax) {
4162 // MinMax reduction have the start value as their identify.
4164 VectorStart = Identity = ReductionStartValue;
4166 VectorStart = Identity =
4167 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
4170 // Handle other reduction kinds:
4171 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
4172 RK, VecTy->getScalarType());
4175 // This vector is the Identity vector where the first element is the
4176 // incoming scalar reduction.
4177 VectorStart = ReductionStartValue;
4179 Identity = ConstantVector::getSplat(VF, Iden);
4181 // This vector is the Identity vector where the first element is the
4182 // incoming scalar reduction.
4184 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
4188 // Fix the vector-loop phi.
4190 // Reductions do not have to start at zero. They can start with
4191 // any loop invariant values.
4192 const VectorParts &VecRdxPhi = getVectorValue(Phi);
4193 BasicBlock *Latch = OrigLoop->getLoopLatch();
4194 Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
4195 const VectorParts &Val = getVectorValue(LoopVal);
4196 for (unsigned part = 0; part < UF; ++part) {
4197 // Make sure to add the reduction stat value only to the
4198 // first unroll part.
4199 Value *StartVal = (part == 0) ? VectorStart : Identity;
4200 cast<PHINode>(VecRdxPhi[part])
4201 ->addIncoming(StartVal, LoopVectorPreHeader);
4202 cast<PHINode>(VecRdxPhi[part])
4203 ->addIncoming(Val[part], LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4206 // Before each round, move the insertion point right between
4207 // the PHIs and the values we are going to write.
4208 // This allows us to write both PHINodes and the extractelement
4210 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4212 VectorParts &RdxParts = VectorLoopValueMap.getVector(LoopExitInst);
4213 setDebugLocFromInst(Builder, LoopExitInst);
4215 // If the vector reduction can be performed in a smaller type, we truncate
4216 // then extend the loop exit value to enable InstCombine to evaluate the
4217 // entire expression in the smaller type.
4218 if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
4219 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4220 Builder.SetInsertPoint(LoopVectorBody->getTerminator());
4221 for (unsigned part = 0; part < UF; ++part) {
4222 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
4223 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4224 : Builder.CreateZExt(Trunc, VecTy);
4225 for (Value::user_iterator UI = RdxParts[part]->user_begin();
4226 UI != RdxParts[part]->user_end();)
4228 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
4229 RdxParts[part] = Extnd;
4234 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4235 for (unsigned part = 0; part < UF; ++part)
4236 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
4239 // Reduce all of the unrolled parts into a single vector.
4240 Value *ReducedPartRdx = RdxParts[0];
4241 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
4242 setDebugLocFromInst(Builder, ReducedPartRdx);
4243 for (unsigned part = 1; part < UF; ++part) {
4244 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4245 // Floating point operations had to be 'fast' to enable the reduction.
4246 ReducedPartRdx = addFastMathFlag(
4247 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
4248 ReducedPartRdx, "bin.rdx"));
4250 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
4251 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
4255 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
4256 // and vector ops, reducing the set of values being computed by half each
4258 assert(isPowerOf2_32(VF) &&
4259 "Reduction emission only supported for pow2 vectors!");
4260 Value *TmpVec = ReducedPartRdx;
4261 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
4262 for (unsigned i = VF; i != 1; i >>= 1) {
4263 // Move the upper half of the vector to the lower half.
4264 for (unsigned j = 0; j != i / 2; ++j)
4265 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
4267 // Fill the rest of the mask with undef.
4268 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
4269 UndefValue::get(Builder.getInt32Ty()));
4271 Value *Shuf = Builder.CreateShuffleVector(
4272 TmpVec, UndefValue::get(TmpVec->getType()),
4273 ConstantVector::get(ShuffleMask), "rdx.shuf");
4275 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4276 // Floating point operations had to be 'fast' to enable the reduction.
4277 TmpVec = addFastMathFlag(Builder.CreateBinOp(
4278 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
4280 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
4284 // The result is in the first element of the vector.
4286 Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
4288 // If the reduction can be performed in a smaller type, we need to extend
4289 // the reduction to the wider type before we branch to the original loop.
4290 if (Phi->getType() != RdxDesc.getRecurrenceType())
4293 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4294 : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4297 // Create a phi node that merges control-flow from the backedge-taken check
4298 // block and the middle block.
4299 PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4300 LoopScalarPreHeader->getTerminator());
4301 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4302 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4303 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4305 // Now, we need to fix the users of the reduction variable
4306 // inside and outside of the scalar remainder loop.
4307 // We know that the loop is in LCSSA form. We need to update the
4308 // PHI nodes in the exit blocks.
4309 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
4310 LEE = LoopExitBlock->end();
4311 LEI != LEE; ++LEI) {
4312 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
4316 // All PHINodes need to have a single entry edge, or two if
4317 // we already fixed them.
4318 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
4320 // We found a reduction value exit-PHI. Update it with the
4321 // incoming bypass edge.
4322 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst)
4323 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4324 } // end of the LCSSA phi scan.
4326 // Fix the scalar loop reduction variable with the incoming reduction sum
4327 // from the vector body and from the backedge value.
4328 int IncomingEdgeBlockIdx =
4329 Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4330 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4331 // Pick the other block.
4332 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4333 Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4334 Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4337 void InnerLoopVectorizer::fixLCSSAPHIs() {
4338 for (Instruction &LEI : *LoopExitBlock) {
4339 auto *LCSSAPhi = dyn_cast<PHINode>(&LEI);
4342 if (LCSSAPhi->getNumIncomingValues() == 1)
4343 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
4348 void InnerLoopVectorizer::collectTriviallyDeadInstructions(
4349 SmallPtrSetImpl<Instruction *> &DeadInstructions) {
4350 BasicBlock *Latch = OrigLoop->getLoopLatch();
4352 // We create new control-flow for the vectorized loop, so the original
4353 // condition will be dead after vectorization if it's only used by the
4355 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4356 if (Cmp && Cmp->hasOneUse())
4357 DeadInstructions.insert(Cmp);
4359 // We create new "steps" for induction variable updates to which the original
4360 // induction variables map. An original update instruction will be dead if
4361 // all its users except the induction variable are dead.
4362 for (auto &Induction : *Legal->getInductionVars()) {
4363 PHINode *Ind = Induction.first;
4364 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4365 if (all_of(IndUpdate->users(), [&](User *U) -> bool {
4366 return U == Ind || DeadInstructions.count(cast<Instruction>(U));
4368 DeadInstructions.insert(IndUpdate);
4372 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4374 // The basic block and loop containing the predicated instruction.
4375 auto *PredBB = PredInst->getParent();
4376 auto *VectorLoop = LI->getLoopFor(PredBB);
4378 // Initialize a worklist with the operands of the predicated instruction.
4379 SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4381 // Holds instructions that we need to analyze again. An instruction may be
4382 // reanalyzed if we don't yet know if we can sink it or not.
4383 SmallVector<Instruction *, 8> InstsToReanalyze;
4385 // Returns true if a given use occurs in the predicated block. Phi nodes use
4386 // their operands in their corresponding predecessor blocks.
4387 auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4388 auto *I = cast<Instruction>(U.getUser());
4389 BasicBlock *BB = I->getParent();
4390 if (auto *Phi = dyn_cast<PHINode>(I))
4391 BB = Phi->getIncomingBlock(
4392 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4393 return BB == PredBB;
4396 // Iteratively sink the scalarized operands of the predicated instruction
4397 // into the block we created for it. When an instruction is sunk, it's
4398 // operands are then added to the worklist. The algorithm ends after one pass
4399 // through the worklist doesn't sink a single instruction.
4403 // Add the instructions that need to be reanalyzed to the worklist, and
4404 // reset the changed indicator.
4405 Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4406 InstsToReanalyze.clear();
4409 while (!Worklist.empty()) {
4410 auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4412 // We can't sink an instruction if it is a phi node, is already in the
4413 // predicated block, is not in the loop, or may have side effects.
4414 if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4415 !VectorLoop->contains(I) || I->mayHaveSideEffects())
4418 // It's legal to sink the instruction if all its uses occur in the
4419 // predicated block. Otherwise, there's nothing to do yet, and we may
4420 // need to reanalyze the instruction.
4421 if (!all_of(I->uses(), isBlockOfUsePredicated)) {
4422 InstsToReanalyze.push_back(I);
4426 // Move the instruction to the beginning of the predicated block, and add
4427 // it's operands to the worklist.
4428 I->moveBefore(&*PredBB->getFirstInsertionPt());
4429 Worklist.insert(I->op_begin(), I->op_end());
4431 // The sinking may have enabled other instructions to be sunk, so we will
4438 void InnerLoopVectorizer::predicateInstructions() {
4440 // For each instruction I marked for predication on value C, split I into its
4441 // own basic block to form an if-then construct over C. Since I may be fed by
4442 // an extractelement instruction or other scalar operand, we try to
4443 // iteratively sink its scalar operands into the predicated block. If I feeds
4444 // an insertelement instruction, we try to move this instruction into the
4445 // predicated block as well. For non-void types, a phi node will be created
4446 // for the resulting value (either vector or scalar).
4448 // So for some predicated instruction, e.g. the conditional sdiv in:
4452 // %add = add nsw i32 %mul, %0
4453 // %cmp5 = icmp sgt i32 %2, 7
4454 // br i1 %cmp5, label %if.then, label %if.end
4457 // %div = sdiv i32 %0, %1
4461 // %x.0 = phi i32 [ %div, %if.then ], [ %add, %for.body ]
4463 // the sdiv at this point is scalarized and if-converted using a select.
4464 // The inactive elements in the vector are not used, but the predicated
4465 // instruction is still executed for all vector elements, essentially:
4469 // %17 = add nsw <2 x i32> %16, %wide.load
4470 // %29 = extractelement <2 x i32> %wide.load, i32 0
4471 // %30 = extractelement <2 x i32> %wide.load51, i32 0
4472 // %31 = sdiv i32 %29, %30
4473 // %32 = insertelement <2 x i32> undef, i32 %31, i32 0
4474 // %35 = extractelement <2 x i32> %wide.load, i32 1
4475 // %36 = extractelement <2 x i32> %wide.load51, i32 1
4476 // %37 = sdiv i32 %35, %36
4477 // %38 = insertelement <2 x i32> %32, i32 %37, i32 1
4478 // %predphi = select <2 x i1> %26, <2 x i32> %38, <2 x i32> %17
4480 // Predication will now re-introduce the original control flow to avoid false
4481 // side-effects by the sdiv instructions on the inactive elements, yielding
4486 // %5 = add nsw <2 x i32> %4, %wide.load
4487 // %8 = icmp sgt <2 x i32> %wide.load52, <i32 7, i32 7>
4488 // %9 = extractelement <2 x i1> %8, i32 0
4489 // br i1 %9, label %pred.sdiv.if, label %pred.sdiv.continue
4492 // %10 = extractelement <2 x i32> %wide.load, i32 0
4493 // %11 = extractelement <2 x i32> %wide.load51, i32 0
4494 // %12 = sdiv i32 %10, %11
4495 // %13 = insertelement <2 x i32> undef, i32 %12, i32 0
4496 // br label %pred.sdiv.continue
4498 // pred.sdiv.continue:
4499 // %14 = phi <2 x i32> [ undef, %vector.body ], [ %13, %pred.sdiv.if ]
4500 // %15 = extractelement <2 x i1> %8, i32 1
4501 // br i1 %15, label %pred.sdiv.if54, label %pred.sdiv.continue55
4504 // %16 = extractelement <2 x i32> %wide.load, i32 1
4505 // %17 = extractelement <2 x i32> %wide.load51, i32 1
4506 // %18 = sdiv i32 %16, %17
4507 // %19 = insertelement <2 x i32> %14, i32 %18, i32 1
4508 // br label %pred.sdiv.continue55
4510 // pred.sdiv.continue55:
4511 // %20 = phi <2 x i32> [ %14, %pred.sdiv.continue ], [ %19, %pred.sdiv.if54 ]
4512 // %predphi = select <2 x i1> %8, <2 x i32> %20, <2 x i32> %5
4514 for (auto KV : PredicatedInstructions) {
4515 BasicBlock::iterator I(KV.first);
4516 BasicBlock *Head = I->getParent();
4517 auto *BB = SplitBlock(Head, &*std::next(I), DT, LI);
4518 auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
4519 /*BranchWeights=*/nullptr, DT, LI);
4521 sinkScalarOperands(&*I);
4523 I->getParent()->setName(Twine("pred.") + I->getOpcodeName() + ".if");
4524 BB->setName(Twine("pred.") + I->getOpcodeName() + ".continue");
4526 // If the instruction is non-void create a Phi node at reconvergence point.
4527 if (!I->getType()->isVoidTy()) {
4528 Value *IncomingTrue = nullptr;
4529 Value *IncomingFalse = nullptr;
4531 if (I->hasOneUse() && isa<InsertElementInst>(*I->user_begin())) {
4532 // If the predicated instruction is feeding an insert-element, move it
4533 // into the Then block; Phi node will be created for the vector.
4534 InsertElementInst *IEI = cast<InsertElementInst>(*I->user_begin());
4536 IncomingTrue = IEI; // the new vector with the inserted element.
4537 IncomingFalse = IEI->getOperand(0); // the unmodified vector
4539 // Phi node will be created for the scalar predicated instruction.
4541 IncomingFalse = UndefValue::get(I->getType());
4544 BasicBlock *PostDom = I->getParent()->getSingleSuccessor();
4545 assert(PostDom && "Then block has multiple successors");
4547 PHINode::Create(IncomingTrue->getType(), 2, "", &PostDom->front());
4548 IncomingTrue->replaceAllUsesWith(Phi);
4549 Phi->addIncoming(IncomingFalse, Head);
4550 Phi->addIncoming(IncomingTrue, I->getParent());
4554 DEBUG(DT->verifyDomTree());
4557 InnerLoopVectorizer::VectorParts
4558 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
4559 assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
4561 // Look for cached value.
4562 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
4563 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
4564 if (ECEntryIt != MaskCache.end())
4565 return ECEntryIt->second;
4567 VectorParts SrcMask = createBlockInMask(Src);
4569 // The terminator has to be a branch inst!
4570 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
4571 assert(BI && "Unexpected terminator found");
4573 if (BI->isConditional()) {
4574 VectorParts EdgeMask = getVectorValue(BI->getCondition());
4576 if (BI->getSuccessor(0) != Dst)
4577 for (unsigned part = 0; part < UF; ++part)
4578 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
4580 for (unsigned part = 0; part < UF; ++part)
4581 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
4583 MaskCache[Edge] = EdgeMask;
4587 MaskCache[Edge] = SrcMask;
4591 InnerLoopVectorizer::VectorParts
4592 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
4593 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
4595 // Loop incoming mask is all-one.
4596 if (OrigLoop->getHeader() == BB) {
4597 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
4598 return getVectorValue(C);
4601 // This is the block mask. We OR all incoming edges, and with zero.
4602 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
4603 VectorParts BlockMask = getVectorValue(Zero);
4606 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
4607 VectorParts EM = createEdgeMask(*it, BB);
4608 for (unsigned part = 0; part < UF; ++part)
4609 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
4615 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
4617 PHINode *P = cast<PHINode>(PN);
4618 // In order to support recurrences we need to be able to vectorize Phi nodes.
4619 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4620 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4621 // this value when we vectorize all of the instructions that use the PHI.
4622 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4623 VectorParts Entry(UF);
4624 for (unsigned part = 0; part < UF; ++part) {
4625 // This is phase one of vectorizing PHIs.
4627 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4628 Entry[part] = PHINode::Create(
4629 VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4631 VectorLoopValueMap.initVector(P, Entry);
4635 setDebugLocFromInst(Builder, P);
4636 // Check for PHI nodes that are lowered to vector selects.
4637 if (P->getParent() != OrigLoop->getHeader()) {
4638 // We know that all PHIs in non-header blocks are converted into
4639 // selects, so we don't have to worry about the insertion order and we
4640 // can just use the builder.
4641 // At this point we generate the predication tree. There may be
4642 // duplications since this is a simple recursive scan, but future
4643 // optimizations will clean it up.
4645 unsigned NumIncoming = P->getNumIncomingValues();
4647 // Generate a sequence of selects of the form:
4648 // SELECT(Mask3, In3,
4649 // SELECT(Mask2, In2,
4651 VectorParts Entry(UF);
4652 for (unsigned In = 0; In < NumIncoming; In++) {
4654 createEdgeMask(P->getIncomingBlock(In), P->getParent());
4655 const VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
4657 for (unsigned part = 0; part < UF; ++part) {
4658 // We might have single edge PHIs (blocks) - use an identity
4659 // 'select' for the first PHI operand.
4661 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]);
4663 // Select between the current value and the previous incoming edge
4664 // based on the incoming mask.
4665 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part],
4669 VectorLoopValueMap.initVector(P, Entry);
4673 // This PHINode must be an induction variable.
4674 // Make sure that we know about it.
4675 assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
4677 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4678 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4680 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4681 // which can be found from the original scalar operations.
4682 switch (II.getKind()) {
4683 case InductionDescriptor::IK_NoInduction:
4684 llvm_unreachable("Unknown induction");
4685 case InductionDescriptor::IK_IntInduction:
4686 case InductionDescriptor::IK_FpInduction:
4687 return widenIntOrFpInduction(P);
4688 case InductionDescriptor::IK_PtrInduction: {
4689 // Handle the pointer induction variable case.
4690 assert(P->getType()->isPointerTy() && "Unexpected type.");
4691 // This is the normalized GEP that starts counting at zero.
4692 Value *PtrInd = Induction;
4693 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4694 // Determine the number of scalars we need to generate for each unroll
4695 // iteration. If the instruction is uniform, we only need to generate the
4696 // first lane. Otherwise, we generate all VF values.
4697 unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4698 // These are the scalar results. Notice that we don't generate vector GEPs
4699 // because scalar GEPs result in better code.
4700 ScalarParts Entry(UF);
4701 for (unsigned Part = 0; Part < UF; ++Part) {
4702 Entry[Part].resize(VF);
4703 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4704 Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
4705 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4706 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4707 SclrGep->setName("next.gep");
4708 Entry[Part][Lane] = SclrGep;
4711 VectorLoopValueMap.initScalar(P, Entry);
4717 /// A helper function for checking whether an integer division-related
4718 /// instruction may divide by zero (in which case it must be predicated if
4719 /// executed conditionally in the scalar code).
4720 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4721 /// Non-zero divisors that are non compile-time constants will not be
4722 /// converted into multiplication, so we will still end up scalarizing
4723 /// the division, but can do so w/o predication.
4724 static bool mayDivideByZero(Instruction &I) {
4725 assert((I.getOpcode() == Instruction::UDiv ||
4726 I.getOpcode() == Instruction::SDiv ||
4727 I.getOpcode() == Instruction::URem ||
4728 I.getOpcode() == Instruction::SRem) &&
4729 "Unexpected instruction");
4730 Value *Divisor = I.getOperand(1);
4731 auto *CInt = dyn_cast<ConstantInt>(Divisor);
4732 return !CInt || CInt->isZero();
4735 void InnerLoopVectorizer::vectorizeInstruction(Instruction &I) {
4736 // Scalarize instructions that should remain scalar after vectorization.
4738 !(isa<BranchInst>(&I) || isa<PHINode>(&I) || isa<DbgInfoIntrinsic>(&I)) &&
4739 shouldScalarizeInstruction(&I)) {
4740 scalarizeInstruction(&I, Legal->isScalarWithPredication(&I));
4744 switch (I.getOpcode()) {
4745 case Instruction::Br:
4746 // Nothing to do for PHIs and BR, since we already took care of the
4747 // loop control flow instructions.
4749 case Instruction::PHI: {
4750 // Vectorize PHINodes.
4751 widenPHIInstruction(&I, UF, VF);
4754 case Instruction::GetElementPtr: {
4755 // Construct a vector GEP by widening the operands of the scalar GEP as
4756 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4757 // results in a vector of pointers when at least one operand of the GEP
4758 // is vector-typed. Thus, to keep the representation compact, we only use
4759 // vector-typed operands for loop-varying values.
4760 auto *GEP = cast<GetElementPtrInst>(&I);
4761 VectorParts Entry(UF);
4763 if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
4764 // If we are vectorizing, but the GEP has only loop-invariant operands,
4765 // the GEP we build (by only using vector-typed operands for
4766 // loop-varying values) would be a scalar pointer. Thus, to ensure we
4767 // produce a vector of pointers, we need to either arbitrarily pick an
4768 // operand to broadcast, or broadcast a clone of the original GEP.
4769 // Here, we broadcast a clone of the original.
4771 // TODO: If at some point we decide to scalarize instructions having
4772 // loop-invariant operands, this special case will no longer be
4773 // required. We would add the scalarization decision to
4774 // collectLoopScalars() and teach getVectorValue() to broadcast
4775 // the lane-zero scalar value.
4776 auto *Clone = Builder.Insert(GEP->clone());
4777 for (unsigned Part = 0; Part < UF; ++Part)
4778 Entry[Part] = Builder.CreateVectorSplat(VF, Clone);
4780 // If the GEP has at least one loop-varying operand, we are sure to
4781 // produce a vector of pointers. But if we are only unrolling, we want
4782 // to produce a scalar GEP for each unroll part. Thus, the GEP we
4783 // produce with the code below will be scalar (if VF == 1) or vector
4784 // (otherwise). Note that for the unroll-only case, we still maintain
4785 // values in the vector mapping with initVector, as we do for other
4787 for (unsigned Part = 0; Part < UF; ++Part) {
4789 // The pointer operand of the new GEP. If it's loop-invariant, we
4790 // won't broadcast it.
4791 auto *Ptr = OrigLoop->isLoopInvariant(GEP->getPointerOperand())
4792 ? GEP->getPointerOperand()
4793 : getVectorValue(GEP->getPointerOperand())[Part];
4795 // Collect all the indices for the new GEP. If any index is
4796 // loop-invariant, we won't broadcast it.
4797 SmallVector<Value *, 4> Indices;
4798 for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
4799 if (OrigLoop->isLoopInvariant(U.get()))
4800 Indices.push_back(U.get());
4802 Indices.push_back(getVectorValue(U.get())[Part]);
4805 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4806 // but it should be a vector, otherwise.
4807 auto *NewGEP = GEP->isInBounds()
4808 ? Builder.CreateInBoundsGEP(Ptr, Indices)
4809 : Builder.CreateGEP(Ptr, Indices);
4810 assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
4811 "NewGEP is not a pointer vector");
4812 Entry[Part] = NewGEP;
4816 VectorLoopValueMap.initVector(&I, Entry);
4817 addMetadata(Entry, GEP);
4820 case Instruction::UDiv:
4821 case Instruction::SDiv:
4822 case Instruction::SRem:
4823 case Instruction::URem:
4824 // Scalarize with predication if this instruction may divide by zero and
4825 // block execution is conditional, otherwise fallthrough.
4826 if (Legal->isScalarWithPredication(&I)) {
4827 scalarizeInstruction(&I, true);
4830 case Instruction::Add:
4831 case Instruction::FAdd:
4832 case Instruction::Sub:
4833 case Instruction::FSub:
4834 case Instruction::Mul:
4835 case Instruction::FMul:
4836 case Instruction::FDiv:
4837 case Instruction::FRem:
4838 case Instruction::Shl:
4839 case Instruction::LShr:
4840 case Instruction::AShr:
4841 case Instruction::And:
4842 case Instruction::Or:
4843 case Instruction::Xor: {
4844 // Just widen binops.
4845 auto *BinOp = cast<BinaryOperator>(&I);
4846 setDebugLocFromInst(Builder, BinOp);
4847 const VectorParts &A = getVectorValue(BinOp->getOperand(0));
4848 const VectorParts &B = getVectorValue(BinOp->getOperand(1));
4850 // Use this vector value for all users of the original instruction.
4851 VectorParts Entry(UF);
4852 for (unsigned Part = 0; Part < UF; ++Part) {
4853 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
4855 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4856 VecOp->copyIRFlags(BinOp);
4861 VectorLoopValueMap.initVector(&I, Entry);
4862 addMetadata(Entry, BinOp);
4865 case Instruction::Select: {
4867 // If the selector is loop invariant we can create a select
4868 // instruction with a scalar condition. Otherwise, use vector-select.
4869 auto *SE = PSE.getSE();
4870 bool InvariantCond =
4871 SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4872 setDebugLocFromInst(Builder, &I);
4874 // The condition can be loop invariant but still defined inside the
4875 // loop. This means that we can't just use the original 'cond' value.
4876 // We have to take the 'vectorized' value and pick the first lane.
4877 // Instcombine will make this a no-op.
4878 const VectorParts &Cond = getVectorValue(I.getOperand(0));
4879 const VectorParts &Op0 = getVectorValue(I.getOperand(1));
4880 const VectorParts &Op1 = getVectorValue(I.getOperand(2));
4882 auto *ScalarCond = getScalarValue(I.getOperand(0), 0, 0);
4884 VectorParts Entry(UF);
4885 for (unsigned Part = 0; Part < UF; ++Part) {
4886 Entry[Part] = Builder.CreateSelect(
4887 InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]);
4890 VectorLoopValueMap.initVector(&I, Entry);
4891 addMetadata(Entry, &I);
4895 case Instruction::ICmp:
4896 case Instruction::FCmp: {
4897 // Widen compares. Generate vector compares.
4898 bool FCmp = (I.getOpcode() == Instruction::FCmp);
4899 auto *Cmp = dyn_cast<CmpInst>(&I);
4900 setDebugLocFromInst(Builder, Cmp);
4901 const VectorParts &A = getVectorValue(Cmp->getOperand(0));
4902 const VectorParts &B = getVectorValue(Cmp->getOperand(1));
4903 VectorParts Entry(UF);
4904 for (unsigned Part = 0; Part < UF; ++Part) {
4907 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
4908 cast<FCmpInst>(C)->copyFastMathFlags(Cmp);
4910 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
4915 VectorLoopValueMap.initVector(&I, Entry);
4916 addMetadata(Entry, &I);
4920 case Instruction::Store:
4921 case Instruction::Load:
4922 vectorizeMemoryInstruction(&I);
4924 case Instruction::ZExt:
4925 case Instruction::SExt:
4926 case Instruction::FPToUI:
4927 case Instruction::FPToSI:
4928 case Instruction::FPExt:
4929 case Instruction::PtrToInt:
4930 case Instruction::IntToPtr:
4931 case Instruction::SIToFP:
4932 case Instruction::UIToFP:
4933 case Instruction::Trunc:
4934 case Instruction::FPTrunc:
4935 case Instruction::BitCast: {
4936 auto *CI = dyn_cast<CastInst>(&I);
4937 setDebugLocFromInst(Builder, CI);
4939 // Optimize the special case where the source is a constant integer
4940 // induction variable. Notice that we can only optimize the 'trunc' case
4941 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
4942 // (c) other casts depend on pointer size.
4943 if (Cost->isOptimizableIVTruncate(CI, VF)) {
4944 widenIntOrFpInduction(cast<PHINode>(CI->getOperand(0)),
4945 cast<TruncInst>(CI));
4949 /// Vectorize casts.
4951 (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4953 const VectorParts &A = getVectorValue(CI->getOperand(0));
4954 VectorParts Entry(UF);
4955 for (unsigned Part = 0; Part < UF; ++Part)
4956 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
4957 VectorLoopValueMap.initVector(&I, Entry);
4958 addMetadata(Entry, &I);
4962 case Instruction::Call: {
4963 // Ignore dbg intrinsics.
4964 if (isa<DbgInfoIntrinsic>(I))
4966 setDebugLocFromInst(Builder, &I);
4968 Module *M = I.getParent()->getParent()->getParent();
4969 auto *CI = cast<CallInst>(&I);
4971 StringRef FnName = CI->getCalledFunction()->getName();
4972 Function *F = CI->getCalledFunction();
4973 Type *RetTy = ToVectorTy(CI->getType(), VF);
4974 SmallVector<Type *, 4> Tys;
4975 for (Value *ArgOperand : CI->arg_operands())
4976 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4978 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4979 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
4980 ID == Intrinsic::lifetime_start)) {
4981 scalarizeInstruction(&I);
4984 // The flag shows whether we use Intrinsic or a usual Call for vectorized
4985 // version of the instruction.
4986 // Is it beneficial to perform intrinsic call compared to lib call?
4987 bool NeedToScalarize;
4988 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4989 bool UseVectorIntrinsic =
4990 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4991 if (!UseVectorIntrinsic && NeedToScalarize) {
4992 scalarizeInstruction(&I);
4996 VectorParts Entry(UF);
4997 for (unsigned Part = 0; Part < UF; ++Part) {
4998 SmallVector<Value *, 4> Args;
4999 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
5000 Value *Arg = CI->getArgOperand(i);
5001 // Some intrinsics have a scalar argument - don't replace it with a
5003 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
5004 const VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
5005 Arg = VectorArg[Part];
5007 Args.push_back(Arg);
5011 if (UseVectorIntrinsic) {
5012 // Use vector version of the intrinsic.
5013 Type *TysForDecl[] = {CI->getType()};
5015 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5016 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5018 // Use vector version of the library call.
5019 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
5020 assert(!VFnName.empty() && "Vector function name is empty.");
5021 VectorF = M->getFunction(VFnName);
5023 // Generate a declaration
5024 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
5026 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
5027 VectorF->copyAttributesFrom(F);
5030 assert(VectorF && "Can't create vector function.");
5032 SmallVector<OperandBundleDef, 1> OpBundles;
5033 CI->getOperandBundlesAsDefs(OpBundles);
5034 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5036 if (isa<FPMathOperator>(V))
5037 V->copyFastMathFlags(CI);
5042 VectorLoopValueMap.initVector(&I, Entry);
5043 addMetadata(Entry, &I);
5048 // All other instructions are unsupported. Scalarize them.
5049 scalarizeInstruction(&I);
5054 void InnerLoopVectorizer::updateAnalysis() {
5055 // Forget the original basic block.
5056 PSE.getSE()->forgetLoop(OrigLoop);
5058 // Update the dominator tree information.
5059 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
5060 "Entry does not dominate exit.");
5062 DT->addNewBlock(LI->getLoopFor(LoopVectorBody)->getHeader(),
5063 LoopVectorPreHeader);
5064 DT->addNewBlock(LoopMiddleBlock,
5065 LI->getLoopFor(LoopVectorBody)->getLoopLatch());
5066 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
5067 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
5068 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
5070 DEBUG(DT->verifyDomTree());
5073 /// \brief Check whether it is safe to if-convert this phi node.
5075 /// Phi nodes with constant expressions that can trap are not safe to if
5077 static bool canIfConvertPHINodes(BasicBlock *BB) {
5078 for (Instruction &I : *BB) {
5079 auto *Phi = dyn_cast<PHINode>(&I);
5082 for (Value *V : Phi->incoming_values())
5083 if (auto *C = dyn_cast<Constant>(V))
5090 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
5091 if (!EnableIfConversion) {
5092 ORE->emit(createMissedAnalysis("IfConversionDisabled")
5093 << "if-conversion is disabled");
5097 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
5099 // A list of pointers that we can safely read and write to.
5100 SmallPtrSet<Value *, 8> SafePointes;
5102 // Collect safe addresses.
5103 for (BasicBlock *BB : TheLoop->blocks()) {
5104 if (blockNeedsPredication(BB))
5107 for (Instruction &I : *BB)
5108 if (auto *Ptr = getPointerOperand(&I))
5109 SafePointes.insert(Ptr);
5112 // Collect the blocks that need predication.
5113 BasicBlock *Header = TheLoop->getHeader();
5114 for (BasicBlock *BB : TheLoop->blocks()) {
5115 // We don't support switch statements inside loops.
5116 if (!isa<BranchInst>(BB->getTerminator())) {
5117 ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
5118 << "loop contains a switch statement");
5122 // We must be able to predicate all blocks that need to be predicated.
5123 if (blockNeedsPredication(BB)) {
5124 if (!blockCanBePredicated(BB, SafePointes)) {
5125 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
5126 << "control flow cannot be substituted for a select");
5129 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
5130 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
5131 << "control flow cannot be substituted for a select");
5136 // We can if-convert this loop.
5140 bool LoopVectorizationLegality::canVectorize() {
5141 // We must have a loop in canonical form. Loops with indirectbr in them cannot
5142 // be canonicalized.
5143 if (!TheLoop->getLoopPreheader()) {
5144 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5145 << "loop control flow is not understood by vectorizer");
5149 // FIXME: The code is currently dead, since the loop gets sent to
5150 // LoopVectorizationLegality is already an innermost loop.
5152 // We can only vectorize innermost loops.
5153 if (!TheLoop->empty()) {
5154 ORE->emit(createMissedAnalysis("NotInnermostLoop")
5155 << "loop is not the innermost loop");
5159 // We must have a single backedge.
5160 if (TheLoop->getNumBackEdges() != 1) {
5161 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5162 << "loop control flow is not understood by vectorizer");
5166 // We must have a single exiting block.
5167 if (!TheLoop->getExitingBlock()) {
5168 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5169 << "loop control flow is not understood by vectorizer");
5173 // We only handle bottom-tested loops, i.e. loop in which the condition is
5174 // checked at the end of each iteration. With that we can assume that all
5175 // instructions in the loop are executed the same number of times.
5176 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5177 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5178 << "loop control flow is not understood by vectorizer");
5182 // We need to have a loop header.
5183 DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
5186 // Check if we can if-convert non-single-bb loops.
5187 unsigned NumBlocks = TheLoop->getNumBlocks();
5188 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
5189 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
5193 // ScalarEvolution needs to be able to find the exit count.
5194 const SCEV *ExitCount = PSE.getBackedgeTakenCount();
5195 if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
5196 ORE->emit(createMissedAnalysis("CantComputeNumberOfIterations")
5197 << "could not determine number of loop iterations");
5198 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
5202 // Check if we can vectorize the instructions and CFG in this loop.
5203 if (!canVectorizeInstrs()) {
5204 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
5208 // Go over each instruction and look at memory deps.
5209 if (!canVectorizeMemory()) {
5210 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
5214 DEBUG(dbgs() << "LV: We can vectorize this loop"
5215 << (LAI->getRuntimePointerChecking()->Need
5216 ? " (with a runtime bound check)"
5220 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
5222 // If an override option has been passed in for interleaved accesses, use it.
5223 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
5224 UseInterleaved = EnableInterleavedMemAccesses;
5226 // Analyze interleaved memory accesses.
5228 InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
5230 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
5231 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
5232 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
5234 if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
5235 ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
5236 << "Too many SCEV assumptions need to be made and checked "
5238 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
5242 // Okay! We can vectorize. At this point we don't have any other mem analysis
5243 // which may limit our maximum vectorization factor, so just return true with
5248 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
5249 if (Ty->isPointerTy())
5250 return DL.getIntPtrType(Ty);
5252 // It is possible that char's or short's overflow when we ask for the loop's
5253 // trip count, work around this by changing the type size.
5254 if (Ty->getScalarSizeInBits() < 32)
5255 return Type::getInt32Ty(Ty->getContext());
5260 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
5261 Ty0 = convertPointerToIntegerType(DL, Ty0);
5262 Ty1 = convertPointerToIntegerType(DL, Ty1);
5263 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
5268 /// \brief Check that the instruction has outside loop users and is not an
5269 /// identified reduction variable.
5270 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
5271 SmallPtrSetImpl<Value *> &AllowedExit) {
5272 // Reduction and Induction instructions are allowed to have exit users. All
5273 // other instructions must not have external users.
5274 if (!AllowedExit.count(Inst))
5275 // Check that all of the users of the loop are inside the BB.
5276 for (User *U : Inst->users()) {
5277 Instruction *UI = cast<Instruction>(U);
5278 // This user may be a reduction exit value.
5279 if (!TheLoop->contains(UI)) {
5280 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
5287 void LoopVectorizationLegality::addInductionPhi(
5288 PHINode *Phi, const InductionDescriptor &ID,
5289 SmallPtrSetImpl<Value *> &AllowedExit) {
5290 Inductions[Phi] = ID;
5291 Type *PhiTy = Phi->getType();
5292 const DataLayout &DL = Phi->getModule()->getDataLayout();
5294 // Get the widest type.
5295 if (!PhiTy->isFloatingPointTy()) {
5297 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
5299 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
5302 // Int inductions are special because we only allow one IV.
5303 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
5304 ID.getConstIntStepValue() &&
5305 ID.getConstIntStepValue()->isOne() &&
5306 isa<Constant>(ID.getStartValue()) &&
5307 cast<Constant>(ID.getStartValue())->isNullValue()) {
5309 // Use the phi node with the widest type as induction. Use the last
5310 // one if there are multiple (no good reason for doing this other
5311 // than it is expedient). We've checked that it begins at zero and
5312 // steps by one, so this is a canonical induction variable.
5313 if (!PrimaryInduction || PhiTy == WidestIndTy)
5314 PrimaryInduction = Phi;
5317 // Both the PHI node itself, and the "post-increment" value feeding
5318 // back into the PHI node may have external users.
5319 AllowedExit.insert(Phi);
5320 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
5322 DEBUG(dbgs() << "LV: Found an induction variable.\n");
5326 bool LoopVectorizationLegality::canVectorizeInstrs() {
5327 BasicBlock *Header = TheLoop->getHeader();
5329 // Look for the attribute signaling the absence of NaNs.
5330 Function &F = *Header->getParent();
5332 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
5334 // For each block in the loop.
5335 for (BasicBlock *BB : TheLoop->blocks()) {
5336 // Scan the instructions in the block and look for hazards.
5337 for (Instruction &I : *BB) {
5338 if (auto *Phi = dyn_cast<PHINode>(&I)) {
5339 Type *PhiTy = Phi->getType();
5340 // Check that this PHI type is allowed.
5341 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
5342 !PhiTy->isPointerTy()) {
5343 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5344 << "loop control flow is not understood by vectorizer");
5345 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
5349 // If this PHINode is not in the header block, then we know that we
5350 // can convert it to select during if-conversion. No need to check if
5351 // the PHIs in this block are induction or reduction variables.
5353 // Check that this instruction has no outside users or is an
5354 // identified reduction value with an outside user.
5355 if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
5357 ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi)
5358 << "value could not be identified as "
5359 "an induction or reduction variable");
5363 // We only allow if-converted PHIs with exactly two incoming values.
5364 if (Phi->getNumIncomingValues() != 2) {
5365 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5366 << "control flow not understood by vectorizer");
5367 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
5371 RecurrenceDescriptor RedDes;
5372 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
5373 if (RedDes.hasUnsafeAlgebra())
5374 Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
5375 AllowedExit.insert(RedDes.getLoopExitInstr());
5376 Reductions[Phi] = RedDes;
5380 InductionDescriptor ID;
5381 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
5382 addInductionPhi(Phi, ID, AllowedExit);
5383 if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
5384 Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
5388 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) {
5389 FirstOrderRecurrences.insert(Phi);
5393 // As a last resort, coerce the PHI to a AddRec expression
5394 // and re-try classifying it a an induction PHI.
5395 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
5396 addInductionPhi(Phi, ID, AllowedExit);
5400 ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
5401 << "value that could not be identified as "
5402 "reduction is used outside the loop");
5403 DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
5405 } // end of PHI handling
5407 // We handle calls that:
5408 // * Are debug info intrinsics.
5409 // * Have a mapping to an IR intrinsic.
5410 // * Have a vector version available.
5411 auto *CI = dyn_cast<CallInst>(&I);
5412 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
5413 !isa<DbgInfoIntrinsic>(CI) &&
5414 !(CI->getCalledFunction() && TLI &&
5415 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5416 ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
5417 << "call instruction cannot be vectorized");
5418 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
5422 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
5423 // second argument is the same (i.e. loop invariant)
5424 if (CI && hasVectorInstrinsicScalarOpd(
5425 getVectorIntrinsicIDForCall(CI, TLI), 1)) {
5426 auto *SE = PSE.getSE();
5427 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
5428 ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
5429 << "intrinsic instruction cannot be vectorized");
5430 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
5435 // Check that the instruction return type is vectorizable.
5436 // Also, we can't vectorize extractelement instructions.
5437 if ((!VectorType::isValidElementType(I.getType()) &&
5438 !I.getType()->isVoidTy()) ||
5439 isa<ExtractElementInst>(I)) {
5440 ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
5441 << "instruction return type cannot be vectorized");
5442 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
5446 // Check that the stored type is vectorizable.
5447 if (auto *ST = dyn_cast<StoreInst>(&I)) {
5448 Type *T = ST->getValueOperand()->getType();
5449 if (!VectorType::isValidElementType(T)) {
5450 ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
5451 << "store instruction cannot be vectorized");
5455 // FP instructions can allow unsafe algebra, thus vectorizable by
5456 // non-IEEE-754 compliant SIMD units.
5457 // This applies to floating-point math operations and calls, not memory
5458 // operations, shuffles, or casts, as they don't change precision or
5460 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
5461 !I.hasUnsafeAlgebra()) {
5462 DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
5463 Hints->setPotentiallyUnsafe();
5466 // Reduction instructions are allowed to have exit users.
5467 // All other instructions must not have external users.
5468 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
5469 ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
5470 << "value cannot be used outside the loop");
5477 if (!PrimaryInduction) {
5478 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
5479 if (Inductions.empty()) {
5480 ORE->emit(createMissedAnalysis("NoInductionVariable")
5481 << "loop induction variable could not be identified");
5486 // Now we know the widest induction type, check if our found induction
5487 // is the same size. If it's not, unset it here and InnerLoopVectorizer
5488 // will create another.
5489 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5490 PrimaryInduction = nullptr;
5495 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
5497 // We should not collect Scalars more than once per VF. Right now, this
5498 // function is called from collectUniformsAndScalars(), which already does
5499 // this check. Collecting Scalars for VF=1 does not make any sense.
5500 assert(VF >= 2 && !Scalars.count(VF) &&
5501 "This function should not be visited twice for the same VF");
5503 SmallSetVector<Instruction *, 8> Worklist;
5505 // These sets are used to seed the analysis with pointers used by memory
5506 // accesses that will remain scalar.
5507 SmallSetVector<Instruction *, 8> ScalarPtrs;
5508 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5510 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5511 // The pointer operands of loads and stores will be scalar as long as the
5512 // memory access is not a gather or scatter operation. The value operand of a
5513 // store will remain scalar if the store is scalarized.
5514 auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5515 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5516 assert(WideningDecision != CM_Unknown &&
5517 "Widening decision should be ready at this moment");
5518 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5519 if (Ptr == Store->getValueOperand())
5520 return WideningDecision == CM_Scalarize;
5521 assert(Ptr == getPointerOperand(MemAccess) &&
5522 "Ptr is neither a value or pointer operand");
5523 return WideningDecision != CM_GatherScatter;
5526 // A helper that returns true if the given value is a bitcast or
5527 // getelementptr instruction contained in the loop.
5528 auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5529 return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5530 isa<GetElementPtrInst>(V)) &&
5531 !TheLoop->isLoopInvariant(V);
5534 // A helper that evaluates a memory access's use of a pointer. If the use
5535 // will be a scalar use, and the pointer is only used by memory accesses, we
5536 // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
5537 // PossibleNonScalarPtrs.
5538 auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5540 // We only care about bitcast and getelementptr instructions contained in
5542 if (!isLoopVaryingBitCastOrGEP(Ptr))
5545 // If the pointer has already been identified as scalar (e.g., if it was
5546 // also identified as uniform), there's nothing to do.
5547 auto *I = cast<Instruction>(Ptr);
5548 if (Worklist.count(I))
5551 // If the use of the pointer will be a scalar use, and all users of the
5552 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5553 // place the pointer in PossibleNonScalarPtrs.
5554 if (isScalarUse(MemAccess, Ptr) && all_of(I->users(), [&](User *U) {
5555 return isa<LoadInst>(U) || isa<StoreInst>(U);
5557 ScalarPtrs.insert(I);
5559 PossibleNonScalarPtrs.insert(I);
5562 // We seed the scalars analysis with three classes of instructions: (1)
5563 // instructions marked uniform-after-vectorization, (2) bitcast and
5564 // getelementptr instructions used by memory accesses requiring a scalar use,
5565 // and (3) pointer induction variables and their update instructions (we
5566 // currently only scalarize these).
5568 // (1) Add to the worklist all instructions that have been identified as
5569 // uniform-after-vectorization.
5570 Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5572 // (2) Add to the worklist all bitcast and getelementptr instructions used by
5573 // memory accesses requiring a scalar use. The pointer operands of loads and
5574 // stores will be scalar as long as the memory accesses is not a gather or
5575 // scatter operation. The value operand of a store will remain scalar if the
5576 // store is scalarized.
5577 for (auto *BB : TheLoop->blocks())
5578 for (auto &I : *BB) {
5579 if (auto *Load = dyn_cast<LoadInst>(&I)) {
5580 evaluatePtrUse(Load, Load->getPointerOperand());
5581 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5582 evaluatePtrUse(Store, Store->getPointerOperand());
5583 evaluatePtrUse(Store, Store->getValueOperand());
5586 for (auto *I : ScalarPtrs)
5587 if (!PossibleNonScalarPtrs.count(I)) {
5588 DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5592 // (3) Add to the worklist all pointer induction variables and their update
5595 // TODO: Once we are able to vectorize pointer induction variables we should
5596 // no longer insert them into the worklist here.
5597 auto *Latch = TheLoop->getLoopLatch();
5598 for (auto &Induction : *Legal->getInductionVars()) {
5599 auto *Ind = Induction.first;
5600 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5601 if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
5603 Worklist.insert(Ind);
5604 Worklist.insert(IndUpdate);
5605 DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5606 DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5609 // Expand the worklist by looking through any bitcasts and getelementptr
5610 // instructions we've already identified as scalar. This is similar to the
5611 // expansion step in collectLoopUniforms(); however, here we're only
5612 // expanding to include additional bitcasts and getelementptr instructions.
5614 while (Idx != Worklist.size()) {
5615 Instruction *Dst = Worklist[Idx++];
5616 if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5618 auto *Src = cast<Instruction>(Dst->getOperand(0));
5619 if (all_of(Src->users(), [&](User *U) -> bool {
5620 auto *J = cast<Instruction>(U);
5621 return !TheLoop->contains(J) || Worklist.count(J) ||
5622 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5623 isScalarUse(J, Src));
5625 Worklist.insert(Src);
5626 DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5630 // An induction variable will remain scalar if all users of the induction
5631 // variable and induction variable update remain scalar.
5632 for (auto &Induction : *Legal->getInductionVars()) {
5633 auto *Ind = Induction.first;
5634 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5636 // We already considered pointer induction variables, so there's no reason
5637 // to look at their users again.
5639 // TODO: Once we are able to vectorize pointer induction variables we
5640 // should no longer skip over them here.
5641 if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
5644 // Determine if all users of the induction variable are scalar after
5646 auto ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
5647 auto *I = cast<Instruction>(U);
5648 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5653 // Determine if all users of the induction variable update instruction are
5654 // scalar after vectorization.
5655 auto ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5656 auto *I = cast<Instruction>(U);
5657 return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5659 if (!ScalarIndUpdate)
5662 // The induction variable and its update instruction will remain scalar.
5663 Worklist.insert(Ind);
5664 Worklist.insert(IndUpdate);
5665 DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5666 DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5669 Scalars[VF].insert(Worklist.begin(), Worklist.end());
5672 bool LoopVectorizationLegality::isScalarWithPredication(Instruction *I) {
5673 if (!blockNeedsPredication(I->getParent()))
5675 switch(I->getOpcode()) {
5678 case Instruction::Store:
5679 return !isMaskRequired(I);
5680 case Instruction::UDiv:
5681 case Instruction::SDiv:
5682 case Instruction::SRem:
5683 case Instruction::URem:
5684 return mayDivideByZero(*I);
5689 bool LoopVectorizationLegality::memoryInstructionCanBeWidened(Instruction *I,
5691 // Get and ensure we have a valid memory instruction.
5692 LoadInst *LI = dyn_cast<LoadInst>(I);
5693 StoreInst *SI = dyn_cast<StoreInst>(I);
5694 assert((LI || SI) && "Invalid memory instruction");
5696 auto *Ptr = getPointerOperand(I);
5698 // In order to be widened, the pointer should be consecutive, first of all.
5699 if (!isConsecutivePtr(Ptr))
5702 // If the instruction is a store located in a predicated block, it will be
5704 if (isScalarWithPredication(I))
5707 // If the instruction's allocated size doesn't equal it's type size, it
5708 // requires padding and will be scalarized.
5709 auto &DL = I->getModule()->getDataLayout();
5710 auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5711 if (hasIrregularType(ScalarTy, DL, VF))
5717 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
5719 // We should not collect Uniforms more than once per VF. Right now,
5720 // this function is called from collectUniformsAndScalars(), which
5721 // already does this check. Collecting Uniforms for VF=1 does not make any
5724 assert(VF >= 2 && !Uniforms.count(VF) &&
5725 "This function should not be visited twice for the same VF");
5727 // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5728 // not analyze again. Uniforms.count(VF) will return 1.
5729 Uniforms[VF].clear();
5731 // We now know that the loop is vectorizable!
5732 // Collect instructions inside the loop that will remain uniform after
5735 // Global values, params and instructions outside of current loop are out of
5737 auto isOutOfScope = [&](Value *V) -> bool {
5738 Instruction *I = dyn_cast<Instruction>(V);
5739 return (!I || !TheLoop->contains(I));
5742 SetVector<Instruction *> Worklist;
5743 BasicBlock *Latch = TheLoop->getLoopLatch();
5745 // Start with the conditional branch. If the branch condition is an
5746 // instruction contained in the loop that is only used by the branch, it is
5748 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5749 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
5750 Worklist.insert(Cmp);
5751 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
5754 // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5755 // are pointers that are treated like consecutive pointers during
5756 // vectorization. The pointer operands of interleaved accesses are an
5758 SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5760 // Holds pointer operands of instructions that are possibly non-uniform.
5761 SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5763 auto isUniformDecision = [&](Instruction *I, unsigned VF) {
5764 InstWidening WideningDecision = getWideningDecision(I, VF);
5765 assert(WideningDecision != CM_Unknown &&
5766 "Widening decision should be ready at this moment");
5768 return (WideningDecision == CM_Widen ||
5769 WideningDecision == CM_Interleave);
5771 // Iterate over the instructions in the loop, and collect all
5772 // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5773 // that a consecutive-like pointer operand will be scalarized, we collect it
5774 // in PossibleNonUniformPtrs instead. We use two sets here because a single
5775 // getelementptr instruction can be used by both vectorized and scalarized
5776 // memory instructions. For example, if a loop loads and stores from the same
5777 // location, but the store is conditional, the store will be scalarized, and
5778 // the getelementptr won't remain uniform.
5779 for (auto *BB : TheLoop->blocks())
5780 for (auto &I : *BB) {
5782 // If there's no pointer operand, there's nothing to do.
5783 auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I));
5787 // True if all users of Ptr are memory accesses that have Ptr as their
5789 auto UsersAreMemAccesses = all_of(Ptr->users(), [&](User *U) -> bool {
5790 return getPointerOperand(U) == Ptr;
5793 // Ensure the memory instruction will not be scalarized or used by
5794 // gather/scatter, making its pointer operand non-uniform. If the pointer
5795 // operand is used by any instruction other than a memory access, we
5796 // conservatively assume the pointer operand may be non-uniform.
5797 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5798 PossibleNonUniformPtrs.insert(Ptr);
5800 // If the memory instruction will be vectorized and its pointer operand
5801 // is consecutive-like, or interleaving - the pointer operand should
5804 ConsecutiveLikePtrs.insert(Ptr);
5807 // Add to the Worklist all consecutive and consecutive-like pointers that
5808 // aren't also identified as possibly non-uniform.
5809 for (auto *V : ConsecutiveLikePtrs)
5810 if (!PossibleNonUniformPtrs.count(V)) {
5811 DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
5815 // Expand Worklist in topological order: whenever a new instruction
5816 // is added , its users should be either already inside Worklist, or
5817 // out of scope. It ensures a uniform instruction will only be used
5818 // by uniform instructions or out of scope instructions.
5820 while (idx != Worklist.size()) {
5821 Instruction *I = Worklist[idx++];
5823 for (auto OV : I->operand_values()) {
5824 if (isOutOfScope(OV))
5826 auto *OI = cast<Instruction>(OV);
5827 if (all_of(OI->users(), [&](User *U) -> bool {
5828 auto *J = cast<Instruction>(U);
5829 return !TheLoop->contains(J) || Worklist.count(J) ||
5830 (OI == getPointerOperand(J) && isUniformDecision(J, VF));
5832 Worklist.insert(OI);
5833 DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
5838 // Returns true if Ptr is the pointer operand of a memory access instruction
5839 // I, and I is known to not require scalarization.
5840 auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5841 return getPointerOperand(I) == Ptr && isUniformDecision(I, VF);
5844 // For an instruction to be added into Worklist above, all its users inside
5845 // the loop should also be in Worklist. However, this condition cannot be
5846 // true for phi nodes that form a cyclic dependence. We must process phi
5847 // nodes separately. An induction variable will remain uniform if all users
5848 // of the induction variable and induction variable update remain uniform.
5849 // The code below handles both pointer and non-pointer induction variables.
5850 for (auto &Induction : *Legal->getInductionVars()) {
5851 auto *Ind = Induction.first;
5852 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5854 // Determine if all users of the induction variable are uniform after
5856 auto UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
5857 auto *I = cast<Instruction>(U);
5858 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5859 isVectorizedMemAccessUse(I, Ind);
5864 // Determine if all users of the induction variable update instruction are
5865 // uniform after vectorization.
5866 auto UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5867 auto *I = cast<Instruction>(U);
5868 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5869 isVectorizedMemAccessUse(I, IndUpdate);
5871 if (!UniformIndUpdate)
5874 // The induction variable and its update instruction will remain uniform.
5875 Worklist.insert(Ind);
5876 Worklist.insert(IndUpdate);
5877 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
5878 DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n");
5881 Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5884 bool LoopVectorizationLegality::canVectorizeMemory() {
5885 LAI = &(*GetLAA)(*TheLoop);
5886 InterleaveInfo.setLAI(LAI);
5887 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
5889 OptimizationRemarkAnalysis VR(Hints->vectorizeAnalysisPassName(),
5890 "loop not vectorized: ", *LAR);
5893 if (!LAI->canVectorizeMemory())
5896 if (LAI->hasStoreToLoopInvariantAddress()) {
5897 ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
5898 << "write to a loop invariant address could not be vectorized");
5899 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
5903 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5904 PSE.addPredicate(LAI->getPSE().getUnionPredicate());
5909 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5910 Value *In0 = const_cast<Value *>(V);
5911 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5915 return Inductions.count(PN);
5918 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
5919 return FirstOrderRecurrences.count(Phi);
5922 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5923 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
5926 bool LoopVectorizationLegality::blockCanBePredicated(
5927 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
5928 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
5930 for (Instruction &I : *BB) {
5931 // Check that we don't have a constant expression that can trap as operand.
5932 for (Value *Operand : I.operands()) {
5933 if (auto *C = dyn_cast<Constant>(Operand))
5937 // We might be able to hoist the load.
5938 if (I.mayReadFromMemory()) {
5939 auto *LI = dyn_cast<LoadInst>(&I);
5942 if (!SafePtrs.count(LI->getPointerOperand())) {
5943 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
5944 isLegalMaskedGather(LI->getType())) {
5945 MaskedOp.insert(LI);
5948 // !llvm.mem.parallel_loop_access implies if-conversion safety.
5949 if (IsAnnotatedParallel)
5955 if (I.mayWriteToMemory()) {
5956 auto *SI = dyn_cast<StoreInst>(&I);
5957 // We only support predication of stores in basic blocks with one
5962 // Build a masked store if it is legal for the target.
5963 if (isLegalMaskedStore(SI->getValueOperand()->getType(),
5964 SI->getPointerOperand()) ||
5965 isLegalMaskedScatter(SI->getValueOperand()->getType())) {
5966 MaskedOp.insert(SI);
5970 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
5971 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
5973 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
5974 !isSinglePredecessor)
5984 void InterleavedAccessInfo::collectConstStrideAccesses(
5985 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
5986 const ValueToValueMap &Strides) {
5988 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5990 // Since it's desired that the load/store instructions be maintained in
5991 // "program order" for the interleaved access analysis, we have to visit the
5992 // blocks in the loop in reverse postorder (i.e., in a topological order).
5993 // Such an ordering will ensure that any load/store that may be executed
5994 // before a second load/store will precede the second load/store in
5995 // AccessStrideInfo.
5996 LoopBlocksDFS DFS(TheLoop);
5998 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
5999 for (auto &I : *BB) {
6000 auto *LI = dyn_cast<LoadInst>(&I);
6001 auto *SI = dyn_cast<StoreInst>(&I);
6005 Value *Ptr = getPointerOperand(&I);
6006 // We don't check wrapping here because we don't know yet if Ptr will be
6007 // part of a full group or a group with gaps. Checking wrapping for all
6008 // pointers (even those that end up in groups with no gaps) will be overly
6009 // conservative. For full groups, wrapping should be ok since if we would
6010 // wrap around the address space we would do a memory access at nullptr
6011 // even without the transformation. The wrapping checks are therefore
6012 // deferred until after we've formed the interleaved groups.
6013 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
6014 /*Assume=*/true, /*ShouldCheckWrap=*/false);
6016 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
6017 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
6018 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
6020 // An alignment of 0 means target ABI alignment.
6021 unsigned Align = getMemInstAlignment(&I);
6023 Align = DL.getABITypeAlignment(PtrTy->getElementType());
6025 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
6029 // Analyze interleaved accesses and collect them into interleaved load and
6032 // When generating code for an interleaved load group, we effectively hoist all
6033 // loads in the group to the location of the first load in program order. When
6034 // generating code for an interleaved store group, we sink all stores to the
6035 // location of the last store. This code motion can change the order of load
6036 // and store instructions and may break dependences.
6038 // The code generation strategy mentioned above ensures that we won't violate
6039 // any write-after-read (WAR) dependences.
6041 // E.g., for the WAR dependence: a = A[i]; // (1)
6044 // The store group of (2) is always inserted at or below (2), and the load
6045 // group of (1) is always inserted at or above (1). Thus, the instructions will
6046 // never be reordered. All other dependences are checked to ensure the
6047 // correctness of the instruction reordering.
6049 // The algorithm visits all memory accesses in the loop in bottom-up program
6050 // order. Program order is established by traversing the blocks in the loop in
6051 // reverse postorder when collecting the accesses.
6053 // We visit the memory accesses in bottom-up order because it can simplify the
6054 // construction of store groups in the presence of write-after-write (WAW)
6057 // E.g., for the WAW dependence: A[i] = a; // (1)
6059 // A[i + 1] = c; // (3)
6061 // We will first create a store group with (3) and (2). (1) can't be added to
6062 // this group because it and (2) are dependent. However, (1) can be grouped
6063 // with other accesses that may precede it in program order. Note that a
6064 // bottom-up order does not imply that WAW dependences should not be checked.
6065 void InterleavedAccessInfo::analyzeInterleaving(
6066 const ValueToValueMap &Strides) {
6067 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
6069 // Holds all accesses with a constant stride.
6070 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
6071 collectConstStrideAccesses(AccessStrideInfo, Strides);
6073 if (AccessStrideInfo.empty())
6076 // Collect the dependences in the loop.
6077 collectDependences();
6079 // Holds all interleaved store groups temporarily.
6080 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
6081 // Holds all interleaved load groups temporarily.
6082 SmallSetVector<InterleaveGroup *, 4> LoadGroups;
6084 // Search in bottom-up program order for pairs of accesses (A and B) that can
6085 // form interleaved load or store groups. In the algorithm below, access A
6086 // precedes access B in program order. We initialize a group for B in the
6087 // outer loop of the algorithm, and then in the inner loop, we attempt to
6088 // insert each A into B's group if:
6090 // 1. A and B have the same stride,
6091 // 2. A and B have the same memory object size, and
6092 // 3. A belongs in B's group according to its distance from B.
6094 // Special care is taken to ensure group formation will not break any
6096 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
6098 Instruction *B = BI->first;
6099 StrideDescriptor DesB = BI->second;
6101 // Initialize a group for B if it has an allowable stride. Even if we don't
6102 // create a group for B, we continue with the bottom-up algorithm to ensure
6103 // we don't break any of B's dependences.
6104 InterleaveGroup *Group = nullptr;
6105 if (isStrided(DesB.Stride)) {
6106 Group = getInterleaveGroup(B);
6108 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n');
6109 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
6111 if (B->mayWriteToMemory())
6112 StoreGroups.insert(Group);
6114 LoadGroups.insert(Group);
6117 for (auto AI = std::next(BI); AI != E; ++AI) {
6118 Instruction *A = AI->first;
6119 StrideDescriptor DesA = AI->second;
6121 // Our code motion strategy implies that we can't have dependences
6122 // between accesses in an interleaved group and other accesses located
6123 // between the first and last member of the group. Note that this also
6124 // means that a group can't have more than one member at a given offset.
6125 // The accesses in a group can have dependences with other accesses, but
6126 // we must ensure we don't extend the boundaries of the group such that
6127 // we encompass those dependent accesses.
6129 // For example, assume we have the sequence of accesses shown below in a
6132 // (1, 2) is a group | A[i] = a; // (1)
6133 // | A[i-1] = b; // (2) |
6134 // A[i-3] = c; // (3)
6135 // A[i] = d; // (4) | (2, 4) is not a group
6137 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
6138 // but not with (4). If we did, the dependent access (3) would be within
6139 // the boundaries of the (2, 4) group.
6140 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
6142 // If a dependence exists and A is already in a group, we know that A
6143 // must be a store since A precedes B and WAR dependences are allowed.
6144 // Thus, A would be sunk below B. We release A's group to prevent this
6145 // illegal code motion. A will then be free to form another group with
6146 // instructions that precede it.
6147 if (isInterleaved(A)) {
6148 InterleaveGroup *StoreGroup = getInterleaveGroup(A);
6149 StoreGroups.remove(StoreGroup);
6150 releaseGroup(StoreGroup);
6153 // If a dependence exists and A is not already in a group (or it was
6154 // and we just released it), B might be hoisted above A (if B is a
6155 // load) or another store might be sunk below A (if B is a store). In
6156 // either case, we can't add additional instructions to B's group. B
6157 // will only form a group with instructions that it precedes.
6161 // At this point, we've checked for illegal code motion. If either A or B
6162 // isn't strided, there's nothing left to do.
6163 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
6166 // Ignore A if it's already in a group or isn't the same kind of memory
6168 if (isInterleaved(A) || A->mayReadFromMemory() != B->mayReadFromMemory())
6171 // Check rules 1 and 2. Ignore A if its stride or size is different from
6173 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
6176 // Ignore A if the memory object of A and B don't belong to the same
6178 if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
6181 // Calculate the distance from A to B.
6182 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
6183 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
6186 int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
6188 // Check rule 3. Ignore A if its distance to B is not a multiple of the
6190 if (DistanceToB % static_cast<int64_t>(DesB.Size))
6193 // Ignore A if either A or B is in a predicated block. Although we
6194 // currently prevent group formation for predicated accesses, we may be
6195 // able to relax this limitation in the future once we handle more
6196 // complicated blocks.
6197 if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
6200 // The index of A is the index of B plus A's distance to B in multiples
6203 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
6205 // Try to insert A into B's group.
6206 if (Group->insertMember(A, IndexA, DesA.Align)) {
6207 DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
6208 << " into the interleave group with" << *B << '\n');
6209 InterleaveGroupMap[A] = Group;
6211 // Set the first load in program order as the insert position.
6212 if (A->mayReadFromMemory())
6213 Group->setInsertPos(A);
6215 } // Iteration over A accesses.
6216 } // Iteration over B accesses.
6218 // Remove interleaved store groups with gaps.
6219 for (InterleaveGroup *Group : StoreGroups)
6220 if (Group->getNumMembers() != Group->getFactor())
6221 releaseGroup(Group);
6223 // Remove interleaved groups with gaps (currently only loads) whose memory
6224 // accesses may wrap around. We have to revisit the getPtrStride analysis,
6225 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
6226 // not check wrapping (see documentation there).
6227 // FORNOW we use Assume=false;
6228 // TODO: Change to Assume=true but making sure we don't exceed the threshold
6229 // of runtime SCEV assumptions checks (thereby potentially failing to
6230 // vectorize altogether).
6231 // Additional optional optimizations:
6232 // TODO: If we are peeling the loop and we know that the first pointer doesn't
6233 // wrap then we can deduce that all pointers in the group don't wrap.
6234 // This means that we can forcefully peel the loop in order to only have to
6235 // check the first pointer for no-wrap. When we'll change to use Assume=true
6236 // we'll only need at most one runtime check per interleaved group.
6238 for (InterleaveGroup *Group : LoadGroups) {
6240 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
6241 // load would wrap around the address space we would do a memory access at
6242 // nullptr even without the transformation.
6243 if (Group->getNumMembers() == Group->getFactor())
6246 // Case 2: If first and last members of the group don't wrap this implies
6247 // that all the pointers in the group don't wrap.
6248 // So we check only group member 0 (which is always guaranteed to exist),
6249 // and group member Factor - 1; If the latter doesn't exist we rely on
6250 // peeling (if it is a non-reveresed accsess -- see Case 3).
6251 Value *FirstMemberPtr = getPointerOperand(Group->getMember(0));
6252 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
6253 /*ShouldCheckWrap=*/true)) {
6254 DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6255 "first group member potentially pointer-wrapping.\n");
6256 releaseGroup(Group);
6259 Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
6261 Value *LastMemberPtr = getPointerOperand(LastMember);
6262 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
6263 /*ShouldCheckWrap=*/true)) {
6264 DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6265 "last group member potentially pointer-wrapping.\n");
6266 releaseGroup(Group);
6269 // Case 3: A non-reversed interleaved load group with gaps: We need
6270 // to execute at least one scalar epilogue iteration. This will ensure
6271 // we don't speculatively access memory out-of-bounds. We only need
6272 // to look for a member at index factor - 1, since every group must have
6273 // a member at index zero.
6274 if (Group->isReverse()) {
6275 releaseGroup(Group);
6278 DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
6279 RequiresScalarEpilogue = true;
6284 Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
6285 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
6286 ORE->emit(createMissedAnalysis("ConditionalStore")
6287 << "store that is conditionally executed prevents vectorization");
6288 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
6292 if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
6293 return computeFeasibleMaxVF(OptForSize);
6295 if (Legal->getRuntimePointerChecking()->Need) {
6296 ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
6297 << "runtime pointer checks needed. Enable vectorization of this "
6298 "loop with '#pragma clang loop vectorize(enable)' when "
6299 "compiling with -Os/-Oz");
6301 << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
6305 // If we optimize the program for size, avoid creating the tail loop.
6306 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6307 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
6309 // If we don't know the precise trip count, don't try to vectorize.
6312 createMissedAnalysis("UnknownLoopCountComplexCFG")
6313 << "unable to calculate the loop count due to complex control flow");
6314 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6318 unsigned MaxVF = computeFeasibleMaxVF(OptForSize);
6320 if (TC % MaxVF != 0) {
6321 // If the trip count that we found modulo the vectorization factor is not
6322 // zero then we require a tail.
6323 // FIXME: look for a smaller MaxVF that does divide TC rather than give up.
6324 // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a
6325 // smaller MaxVF that does not require a scalar epilog.
6327 ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
6328 << "cannot optimize for size and vectorize at the "
6329 "same time. Enable vectorization of this loop "
6330 "with '#pragma clang loop vectorize(enable)' "
6331 "when compiling with -Os/-Oz");
6332 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6339 unsigned LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize) {
6340 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
6341 unsigned SmallestType, WidestType;
6342 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
6343 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
6344 unsigned MaxSafeDepDist = -1U;
6346 // Get the maximum safe dependence distance in bits computed by LAA. If the
6347 // loop contains any interleaved accesses, we divide the dependence distance
6348 // by the maximum interleave factor of all interleaved groups. Note that
6349 // although the division ensures correctness, this is a fairly conservative
6350 // computation because the maximum distance computed by LAA may not involve
6351 // any of the interleaved accesses.
6352 if (Legal->getMaxSafeDepDistBytes() != -1U)
6354 Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor();
6357 ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist);
6358 unsigned MaxVectorSize = WidestRegister / WidestType;
6360 DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
6361 << WidestType << " bits.\n");
6362 DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister
6365 if (MaxVectorSize == 0) {
6366 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
6370 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
6371 " into one vector!");
6373 unsigned MaxVF = MaxVectorSize;
6374 if (MaximizeBandwidth && !OptForSize) {
6375 // Collect all viable vectorization factors.
6376 SmallVector<unsigned, 8> VFs;
6377 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
6378 for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
6381 // For each VF calculate its register usage.
6382 auto RUs = calculateRegisterUsage(VFs);
6384 // Select the largest VF which doesn't require more registers than existing
6386 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
6387 for (int i = RUs.size() - 1; i >= 0; --i) {
6388 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
6397 LoopVectorizationCostModel::VectorizationFactor
6398 LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
6399 float Cost = expectedCost(1).first;
6401 const float ScalarCost = Cost;
6404 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
6406 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6407 // Ignore scalar width, because the user explicitly wants vectorization.
6408 if (ForceVectorization && MaxVF > 1) {
6410 Cost = expectedCost(Width).first / (float)Width;
6413 for (unsigned i = 2; i <= MaxVF; i *= 2) {
6414 // Notice that the vector loop needs to be executed less times, so
6415 // we need to divide the cost of the vector loops by the width of
6416 // the vector elements.
6417 VectorizationCostTy C = expectedCost(i);
6418 float VectorCost = C.first / (float)i;
6419 DEBUG(dbgs() << "LV: Vector loop of width " << i
6420 << " costs: " << (int)VectorCost << ".\n");
6421 if (!C.second && !ForceVectorization) {
6423 dbgs() << "LV: Not considering vector loop of width " << i
6424 << " because it will not generate any vector instructions.\n");
6427 if (VectorCost < Cost) {
6433 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
6434 << "LV: Vectorization seems to be not beneficial, "
6435 << "but was forced by a user.\n");
6436 DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
6437 VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
6441 std::pair<unsigned, unsigned>
6442 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6443 unsigned MinWidth = -1U;
6444 unsigned MaxWidth = 8;
6445 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6448 for (BasicBlock *BB : TheLoop->blocks()) {
6449 // For each instruction in the loop.
6450 for (Instruction &I : *BB) {
6451 Type *T = I.getType();
6453 // Skip ignored values.
6454 if (ValuesToIgnore.count(&I))
6457 // Only examine Loads, Stores and PHINodes.
6458 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6461 // Examine PHI nodes that are reduction variables. Update the type to
6462 // account for the recurrence type.
6463 if (auto *PN = dyn_cast<PHINode>(&I)) {
6464 if (!Legal->isReductionVariable(PN))
6466 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
6467 T = RdxDesc.getRecurrenceType();
6470 // Examine the stored values.
6471 if (auto *ST = dyn_cast<StoreInst>(&I))
6472 T = ST->getValueOperand()->getType();
6474 // Ignore loaded pointer types and stored pointer types that are not
6477 // FIXME: The check here attempts to predict whether a load or store will
6478 // be vectorized. We only know this for certain after a VF has
6479 // been selected. Here, we assume that if an access can be
6480 // vectorized, it will be. We should also look at extending this
6481 // optimization to non-pointer types.
6483 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6484 !Legal->isAccessInterleaved(&I) && !Legal->isLegalGatherOrScatter(&I))
6487 MinWidth = std::min(MinWidth,
6488 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6489 MaxWidth = std::max(MaxWidth,
6490 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6494 return {MinWidth, MaxWidth};
6497 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
6499 unsigned LoopCost) {
6501 // -- The interleave heuristics --
6502 // We interleave the loop in order to expose ILP and reduce the loop overhead.
6503 // There are many micro-architectural considerations that we can't predict
6504 // at this level. For example, frontend pressure (on decode or fetch) due to
6505 // code size, or the number and capabilities of the execution ports.
6507 // We use the following heuristics to select the interleave count:
6508 // 1. If the code has reductions, then we interleave to break the cross
6509 // iteration dependency.
6510 // 2. If the loop is really small, then we interleave to reduce the loop
6512 // 3. We don't interleave if we think that we will spill registers to memory
6513 // due to the increased register pressure.
6515 // When we optimize for size, we don't interleave.
6519 // We used the distance for the interleave count.
6520 if (Legal->getMaxSafeDepDistBytes() != -1U)
6523 // Do not interleave loops with a relatively small trip count.
6524 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6525 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
6528 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
6529 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6533 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6534 TargetNumRegisters = ForceTargetNumScalarRegs;
6536 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6537 TargetNumRegisters = ForceTargetNumVectorRegs;
6540 RegisterUsage R = calculateRegisterUsage({VF})[0];
6541 // We divide by these constants so assume that we have at least one
6542 // instruction that uses at least one register.
6543 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
6544 R.NumInstructions = std::max(R.NumInstructions, 1U);
6546 // We calculate the interleave count using the following formula.
6547 // Subtract the number of loop invariants from the number of available
6548 // registers. These registers are used by all of the interleaved instances.
6549 // Next, divide the remaining registers by the number of registers that is
6550 // required by the loop, in order to estimate how many parallel instances
6551 // fit without causing spills. All of this is rounded down if necessary to be
6552 // a power of two. We want power of two interleave count to simplify any
6553 // addressing operations or alignment considerations.
6554 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
6557 // Don't count the induction variable as interleaved.
6558 if (EnableIndVarRegisterHeur)
6559 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
6560 std::max(1U, (R.MaxLocalUsers - 1)));
6562 // Clamp the interleave ranges to reasonable counts.
6563 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
6565 // Check if the user has overridden the max.
6567 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6568 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6570 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6571 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6574 // If we did not calculate the cost for VF (because the user selected the VF)
6575 // then we calculate the cost of VF here.
6577 LoopCost = expectedCost(VF).first;
6579 // Clamp the calculated IC to be between the 1 and the max interleave count
6580 // that the target allows.
6581 if (IC > MaxInterleaveCount)
6582 IC = MaxInterleaveCount;
6586 // Interleave if we vectorized this loop and there is a reduction that could
6587 // benefit from interleaving.
6588 if (VF > 1 && Legal->getReductionVars()->size()) {
6589 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6593 // Note that if we've already vectorized the loop we will have done the
6594 // runtime check and so interleaving won't require further checks.
6595 bool InterleavingRequiresRuntimePointerCheck =
6596 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
6598 // We want to interleave small loops in order to reduce the loop overhead and
6599 // potentially expose ILP opportunities.
6600 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
6601 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6602 // We assume that the cost overhead is 1 and we use the cost model
6603 // to estimate the cost of the loop and interleave until the cost of the
6604 // loop overhead is about 5% of the cost of the loop.
6606 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6608 // Interleave until store/load ports (estimated by max interleave count) are
6610 unsigned NumStores = Legal->getNumStores();
6611 unsigned NumLoads = Legal->getNumLoads();
6612 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6613 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6615 // If we have a scalar reduction (vector reductions are already dealt with
6616 // by this point), we can increase the critical path length if the loop
6617 // we're interleaving is inside another loop. Limit, by default to 2, so the
6618 // critical path only gets increased by one reduction operation.
6619 if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) {
6620 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6621 SmallIC = std::min(SmallIC, F);
6622 StoresIC = std::min(StoresIC, F);
6623 LoadsIC = std::min(LoadsIC, F);
6626 if (EnableLoadStoreRuntimeInterleave &&
6627 std::max(StoresIC, LoadsIC) > SmallIC) {
6628 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6629 return std::max(StoresIC, LoadsIC);
6632 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6636 // Interleave if this is a large loop (small loops are already dealt with by
6637 // this point) that could benefit from interleaving.
6638 bool HasReductions = (Legal->getReductionVars()->size() > 0);
6639 if (TTI.enableAggressiveInterleaving(HasReductions)) {
6640 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6644 DEBUG(dbgs() << "LV: Not Interleaving.\n");
6648 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6649 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
6650 // This function calculates the register usage by measuring the highest number
6651 // of values that are alive at a single location. Obviously, this is a very
6652 // rough estimation. We scan the loop in a topological order in order and
6653 // assign a number to each instruction. We use RPO to ensure that defs are
6654 // met before their users. We assume that each instruction that has in-loop
6655 // users starts an interval. We record every time that an in-loop value is
6656 // used, so we have a list of the first and last occurrences of each
6657 // instruction. Next, we transpose this data structure into a multi map that
6658 // holds the list of intervals that *end* at a specific location. This multi
6659 // map allows us to perform a linear search. We scan the instructions linearly
6660 // and record each time that a new interval starts, by placing it in a set.
6661 // If we find this value in the multi-map then we remove it from the set.
6662 // The max register usage is the maximum size of the set.
6663 // We also search for instructions that are defined outside the loop, but are
6664 // used inside the loop. We need this number separately from the max-interval
6665 // usage number because when we unroll, loop-invariant values do not take
6667 LoopBlocksDFS DFS(TheLoop);
6671 RU.NumInstructions = 0;
6673 // Each 'key' in the map opens a new interval. The values
6674 // of the map are the index of the 'last seen' usage of the
6675 // instruction that is the key.
6676 typedef DenseMap<Instruction *, unsigned> IntervalMap;
6677 // Maps instruction to its index.
6678 DenseMap<unsigned, Instruction *> IdxToInstr;
6679 // Marks the end of each interval.
6680 IntervalMap EndPoint;
6681 // Saves the list of instruction indices that are used in the loop.
6682 SmallSet<Instruction *, 8> Ends;
6683 // Saves the list of values that are used in the loop but are
6684 // defined outside the loop, such as arguments and constants.
6685 SmallPtrSet<Value *, 8> LoopInvariants;
6688 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6689 RU.NumInstructions += BB->size();
6690 for (Instruction &I : *BB) {
6691 IdxToInstr[Index++] = &I;
6693 // Save the end location of each USE.
6694 for (Value *U : I.operands()) {
6695 auto *Instr = dyn_cast<Instruction>(U);
6697 // Ignore non-instruction values such as arguments, constants, etc.
6701 // If this instruction is outside the loop then record it and continue.
6702 if (!TheLoop->contains(Instr)) {
6703 LoopInvariants.insert(Instr);
6707 // Overwrite previous end points.
6708 EndPoint[Instr] = Index;
6714 // Saves the list of intervals that end with the index in 'key'.
6715 typedef SmallVector<Instruction *, 2> InstrList;
6716 DenseMap<unsigned, InstrList> TransposeEnds;
6718 // Transpose the EndPoints to a list of values that end at each index.
6719 for (auto &Interval : EndPoint)
6720 TransposeEnds[Interval.second].push_back(Interval.first);
6722 SmallSet<Instruction *, 8> OpenIntervals;
6724 // Get the size of the widest register.
6725 unsigned MaxSafeDepDist = -1U;
6726 if (Legal->getMaxSafeDepDistBytes() != -1U)
6727 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
6728 unsigned WidestRegister =
6729 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
6730 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6732 SmallVector<RegisterUsage, 8> RUs(VFs.size());
6733 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
6735 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6737 // A lambda that gets the register usage for the given type and VF.
6738 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
6739 if (Ty->isTokenTy())
6741 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
6742 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
6745 for (unsigned int i = 0; i < Index; ++i) {
6746 Instruction *I = IdxToInstr[i];
6748 // Remove all of the instructions that end at this location.
6749 InstrList &List = TransposeEnds[i];
6750 for (Instruction *ToRemove : List)
6751 OpenIntervals.erase(ToRemove);
6753 // Ignore instructions that are never used within the loop.
6757 // Skip ignored values.
6758 if (ValuesToIgnore.count(I))
6761 // For each VF find the maximum usage of registers.
6762 for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6764 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
6767 collectUniformsAndScalars(VFs[j]);
6768 // Count the number of live intervals.
6769 unsigned RegUsage = 0;
6770 for (auto Inst : OpenIntervals) {
6771 // Skip ignored values for VF > 1.
6772 if (VecValuesToIgnore.count(Inst) ||
6773 isScalarAfterVectorization(Inst, VFs[j]))
6775 RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
6777 MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
6780 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6781 << OpenIntervals.size() << '\n');
6783 // Add the current instruction to the list of open intervals.
6784 OpenIntervals.insert(I);
6787 for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6788 unsigned Invariant = 0;
6790 Invariant = LoopInvariants.size();
6792 for (auto Inst : LoopInvariants)
6793 Invariant += GetRegUsage(Inst->getType(), VFs[i]);
6796 DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
6797 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
6798 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
6799 DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
6801 RU.LoopInvariantRegs = Invariant;
6802 RU.MaxLocalUsers = MaxUsages[i];
6809 void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
6811 // If we aren't vectorizing the loop, or if we've already collected the
6812 // instructions to scalarize, there's nothing to do. Collection may already
6813 // have occurred if we have a user-selected VF and are now computing the
6814 // expected cost for interleaving.
6815 if (VF < 2 || InstsToScalarize.count(VF))
6818 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6819 // not profitable to scalarize any instructions, the presence of VF in the
6820 // map will indicate that we've analyzed it already.
6821 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6823 // Find all the instructions that are scalar with predication in the loop and
6824 // determine if it would be better to not if-convert the blocks they are in.
6825 // If so, we also record the instructions to scalarize.
6826 for (BasicBlock *BB : TheLoop->blocks()) {
6827 if (!Legal->blockNeedsPredication(BB))
6829 for (Instruction &I : *BB)
6830 if (Legal->isScalarWithPredication(&I)) {
6831 ScalarCostsTy ScalarCosts;
6832 if (computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6833 ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6835 // Remember that BB will remain after vectorization.
6836 PredicatedBBsAfterVectorization.insert(BB);
6841 int LoopVectorizationCostModel::computePredInstDiscount(
6842 Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
6845 assert(!isUniformAfterVectorization(PredInst, VF) &&
6846 "Instruction marked uniform-after-vectorization will be predicated");
6848 // Initialize the discount to zero, meaning that the scalar version and the
6849 // vector version cost the same.
6852 // Holds instructions to analyze. The instructions we visit are mapped in
6853 // ScalarCosts. Those instructions are the ones that would be scalarized if
6854 // we find that the scalar version costs less.
6855 SmallVector<Instruction *, 8> Worklist;
6857 // Returns true if the given instruction can be scalarized.
6858 auto canBeScalarized = [&](Instruction *I) -> bool {
6860 // We only attempt to scalarize instructions forming a single-use chain
6861 // from the original predicated block that would otherwise be vectorized.
6862 // Although not strictly necessary, we give up on instructions we know will
6863 // already be scalar to avoid traversing chains that are unlikely to be
6865 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6866 isScalarAfterVectorization(I, VF))
6869 // If the instruction is scalar with predication, it will be analyzed
6870 // separately. We ignore it within the context of PredInst.
6871 if (Legal->isScalarWithPredication(I))
6874 // If any of the instruction's operands are uniform after vectorization,
6875 // the instruction cannot be scalarized. This prevents, for example, a
6876 // masked load from being scalarized.
6878 // We assume we will only emit a value for lane zero of an instruction
6879 // marked uniform after vectorization, rather than VF identical values.
6880 // Thus, if we scalarize an instruction that uses a uniform, we would
6881 // create uses of values corresponding to the lanes we aren't emitting code
6882 // for. This behavior can be changed by allowing getScalarValue to clone
6883 // the lane zero values for uniforms rather than asserting.
6884 for (Use &U : I->operands())
6885 if (auto *J = dyn_cast<Instruction>(U.get()))
6886 if (isUniformAfterVectorization(J, VF))
6889 // Otherwise, we can scalarize the instruction.
6893 // Returns true if an operand that cannot be scalarized must be extracted
6894 // from a vector. We will account for this scalarization overhead below. Note
6895 // that the non-void predicated instructions are placed in their own blocks,
6896 // and their return values are inserted into vectors. Thus, an extract would
6897 // still be required.
6898 auto needsExtract = [&](Instruction *I) -> bool {
6899 return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
6902 // Compute the expected cost discount from scalarizing the entire expression
6903 // feeding the predicated instruction. We currently only consider expressions
6904 // that are single-use instruction chains.
6905 Worklist.push_back(PredInst);
6906 while (!Worklist.empty()) {
6907 Instruction *I = Worklist.pop_back_val();
6909 // If we've already analyzed the instruction, there's nothing to do.
6910 if (ScalarCosts.count(I))
6913 // Compute the cost of the vector instruction. Note that this cost already
6914 // includes the scalarization overhead of the predicated instruction.
6915 unsigned VectorCost = getInstructionCost(I, VF).first;
6917 // Compute the cost of the scalarized instruction. This cost is the cost of
6918 // the instruction as if it wasn't if-converted and instead remained in the
6919 // predicated block. We will scale this cost by block probability after
6920 // computing the scalarization overhead.
6921 unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
6923 // Compute the scalarization overhead of needed insertelement instructions
6925 if (Legal->isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6926 ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
6928 ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
6931 // Compute the scalarization overhead of needed extractelement
6932 // instructions. For each of the instruction's operands, if the operand can
6933 // be scalarized, add it to the worklist; otherwise, account for the
6935 for (Use &U : I->operands())
6936 if (auto *J = dyn_cast<Instruction>(U.get())) {
6937 assert(VectorType::isValidElementType(J->getType()) &&
6938 "Instruction has non-scalar type");
6939 if (canBeScalarized(J))
6940 Worklist.push_back(J);
6941 else if (needsExtract(J))
6942 ScalarCost += TTI.getScalarizationOverhead(
6943 ToVectorTy(J->getType(),VF), false, true);
6946 // Scale the total scalar cost by block probability.
6947 ScalarCost /= getReciprocalPredBlockProb();
6949 // Compute the discount. A non-negative discount means the vector version
6950 // of the instruction costs more, and scalarizing would be beneficial.
6951 Discount += VectorCost - ScalarCost;
6952 ScalarCosts[I] = ScalarCost;
6958 LoopVectorizationCostModel::VectorizationCostTy
6959 LoopVectorizationCostModel::expectedCost(unsigned VF) {
6960 VectorizationCostTy Cost;
6962 // Collect Uniform and Scalar instructions after vectorization with VF.
6963 collectUniformsAndScalars(VF);
6965 // Collect the instructions (and their associated costs) that will be more
6966 // profitable to scalarize.
6967 collectInstsToScalarize(VF);
6970 for (BasicBlock *BB : TheLoop->blocks()) {
6971 VectorizationCostTy BlockCost;
6973 // For each instruction in the old loop.
6974 for (Instruction &I : *BB) {
6975 // Skip dbg intrinsics.
6976 if (isa<DbgInfoIntrinsic>(I))
6979 // Skip ignored values.
6980 if (ValuesToIgnore.count(&I))
6983 VectorizationCostTy C = getInstructionCost(&I, VF);
6985 // Check if we should override the cost.
6986 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6987 C.first = ForceTargetInstructionCost;
6989 BlockCost.first += C.first;
6990 BlockCost.second |= C.second;
6991 DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "
6992 << VF << " For instruction: " << I << '\n');
6995 // If we are vectorizing a predicated block, it will have been
6996 // if-converted. This means that the block's instructions (aside from
6997 // stores and instructions that may divide by zero) will now be
6998 // unconditionally executed. For the scalar case, we may not always execute
6999 // the predicated block. Thus, scale the block's cost by the probability of
7001 if (VF == 1 && Legal->blockNeedsPredication(BB))
7002 BlockCost.first /= getReciprocalPredBlockProb();
7004 Cost.first += BlockCost.first;
7005 Cost.second |= BlockCost.second;
7011 /// \brief Gets Address Access SCEV after verifying that the access pattern
7012 /// is loop invariant except the induction variable dependence.
7014 /// This SCEV can be sent to the Target in order to estimate the address
7015 /// calculation cost.
7016 static const SCEV *getAddressAccessSCEV(
7018 LoopVectorizationLegality *Legal,
7019 ScalarEvolution *SE,
7020 const Loop *TheLoop) {
7021 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
7025 // We are looking for a gep with all loop invariant indices except for one
7026 // which should be an induction variable.
7027 unsigned NumOperands = Gep->getNumOperands();
7028 for (unsigned i = 1; i < NumOperands; ++i) {
7029 Value *Opd = Gep->getOperand(i);
7030 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
7031 !Legal->isInductionVariable(Opd))
7035 // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
7036 return SE->getSCEV(Ptr);
7039 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
7040 return Legal->hasStride(I->getOperand(0)) ||
7041 Legal->hasStride(I->getOperand(1));
7044 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
7046 Type *ValTy = getMemInstValueType(I);
7047 auto SE = PSE.getSE();
7049 unsigned Alignment = getMemInstAlignment(I);
7050 unsigned AS = getMemInstAddressSpace(I);
7051 Value *Ptr = getPointerOperand(I);
7052 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
7054 // Figure out whether the access is strided and get the stride value
7055 // if it's known in compile time
7056 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, SE, TheLoop);
7058 // Get the cost of the scalar memory instruction and address computation.
7059 unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
7062 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
7065 // Get the overhead of the extractelement and insertelement instructions
7066 // we might create due to scalarization.
7067 Cost += getScalarizationOverhead(I, VF, TTI);
7069 // If we have a predicated store, it may not be executed for each vector
7070 // lane. Scale the cost by the probability of executing the predicated
7072 if (Legal->isScalarWithPredication(I))
7073 Cost /= getReciprocalPredBlockProb();
7078 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
7080 Type *ValTy = getMemInstValueType(I);
7081 Type *VectorTy = ToVectorTy(ValTy, VF);
7082 unsigned Alignment = getMemInstAlignment(I);
7083 Value *Ptr = getPointerOperand(I);
7084 unsigned AS = getMemInstAddressSpace(I);
7085 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
7087 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7088 "Stride should be 1 or -1 for consecutive memory access");
7090 if (Legal->isMaskRequired(I))
7091 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
7093 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
7095 bool Reverse = ConsecutiveStride < 0;
7097 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
7101 unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7103 LoadInst *LI = cast<LoadInst>(I);
7104 Type *ValTy = LI->getType();
7105 Type *VectorTy = ToVectorTy(ValTy, VF);
7106 unsigned Alignment = LI->getAlignment();
7107 unsigned AS = LI->getPointerAddressSpace();
7109 return TTI.getAddressComputationCost(ValTy) +
7110 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
7111 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7114 unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7116 Type *ValTy = getMemInstValueType(I);
7117 Type *VectorTy = ToVectorTy(ValTy, VF);
7118 unsigned Alignment = getMemInstAlignment(I);
7119 Value *Ptr = getPointerOperand(I);
7121 return TTI.getAddressComputationCost(VectorTy) +
7122 TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
7123 Legal->isMaskRequired(I), Alignment);
7126 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7128 Type *ValTy = getMemInstValueType(I);
7129 Type *VectorTy = ToVectorTy(ValTy, VF);
7130 unsigned AS = getMemInstAddressSpace(I);
7132 auto Group = Legal->getInterleavedAccessGroup(I);
7133 assert(Group && "Fail to get an interleaved access group.");
7135 unsigned InterleaveFactor = Group->getFactor();
7136 Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7138 // Holds the indices of existing members in an interleaved load group.
7139 // An interleaved store group doesn't need this as it doesn't allow gaps.
7140 SmallVector<unsigned, 4> Indices;
7141 if (isa<LoadInst>(I)) {
7142 for (unsigned i = 0; i < InterleaveFactor; i++)
7143 if (Group->getMember(i))
7144 Indices.push_back(i);
7147 // Calculate the cost of the whole interleaved group.
7148 unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy,
7149 Group->getFactor(), Indices,
7150 Group->getAlignment(), AS);
7152 if (Group->isReverse())
7153 Cost += Group->getNumMembers() *
7154 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
7158 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7161 // Calculate scalar cost only. Vectorization cost should be ready at this
7164 Type *ValTy = getMemInstValueType(I);
7165 unsigned Alignment = getMemInstAlignment(I);
7166 unsigned AS = getMemInstAlignment(I);
7168 return TTI.getAddressComputationCost(ValTy) +
7169 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
7171 return getWideningCost(I, VF);
7174 LoopVectorizationCostModel::VectorizationCostTy
7175 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
7176 // If we know that this instruction will remain uniform, check the cost of
7177 // the scalar version.
7178 if (isUniformAfterVectorization(I, VF))
7181 if (VF > 1 && isProfitableToScalarize(I, VF))
7182 return VectorizationCostTy(InstsToScalarize[VF][I], false);
7185 unsigned C = getInstructionCost(I, VF, VectorTy);
7187 bool TypeNotScalarized =
7188 VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF;
7189 return VectorizationCostTy(C, TypeNotScalarized);
7192 void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
7195 for (BasicBlock *BB : TheLoop->blocks()) {
7196 // For each instruction in the old loop.
7197 for (Instruction &I : *BB) {
7198 Value *Ptr = getPointerOperand(&I);
7202 if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
7203 // Scalar load + broadcast
7204 unsigned Cost = getUniformMemOpCost(&I, VF);
7205 setWideningDecision(&I, VF, CM_Scalarize, Cost);
7209 // We assume that widening is the best solution when possible.
7210 if (Legal->memoryInstructionCanBeWidened(&I, VF)) {
7211 unsigned Cost = getConsecutiveMemOpCost(&I, VF);
7212 setWideningDecision(&I, VF, CM_Widen, Cost);
7216 // Choose between Interleaving, Gather/Scatter or Scalarization.
7217 unsigned InterleaveCost = UINT_MAX;
7218 unsigned NumAccesses = 1;
7219 if (Legal->isAccessInterleaved(&I)) {
7220 auto Group = Legal->getInterleavedAccessGroup(&I);
7221 assert(Group && "Fail to get an interleaved access group.");
7223 // Make one decision for the whole group.
7224 if (getWideningDecision(&I, VF) != CM_Unknown)
7227 NumAccesses = Group->getNumMembers();
7228 InterleaveCost = getInterleaveGroupCost(&I, VF);
7231 unsigned GatherScatterCost =
7232 Legal->isLegalGatherOrScatter(&I)
7233 ? getGatherScatterCost(&I, VF) * NumAccesses
7236 unsigned ScalarizationCost =
7237 getMemInstScalarizationCost(&I, VF) * NumAccesses;
7239 // Choose better solution for the current VF,
7240 // write down this decision and use it during vectorization.
7242 InstWidening Decision;
7243 if (InterleaveCost <= GatherScatterCost &&
7244 InterleaveCost < ScalarizationCost) {
7245 Decision = CM_Interleave;
7246 Cost = InterleaveCost;
7247 } else if (GatherScatterCost < ScalarizationCost) {
7248 Decision = CM_GatherScatter;
7249 Cost = GatherScatterCost;
7251 Decision = CM_Scalarize;
7252 Cost = ScalarizationCost;
7254 // If the instructions belongs to an interleave group, the whole group
7255 // receives the same decision. The whole group receives the cost, but
7256 // the cost will actually be assigned to one instruction.
7257 if (auto Group = Legal->getInterleavedAccessGroup(&I))
7258 setWideningDecision(Group, VF, Decision, Cost);
7260 setWideningDecision(&I, VF, Decision, Cost);
7265 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7268 Type *RetTy = I->getType();
7269 if (canTruncateToMinimalBitwidth(I, VF))
7270 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7271 VectorTy = ToVectorTy(RetTy, VF);
7272 auto SE = PSE.getSE();
7274 // TODO: We need to estimate the cost of intrinsic calls.
7275 switch (I->getOpcode()) {
7276 case Instruction::GetElementPtr:
7277 // We mark this instruction as zero-cost because the cost of GEPs in
7278 // vectorized code depends on whether the corresponding memory instruction
7279 // is scalarized or not. Therefore, we handle GEPs with the memory
7280 // instruction cost.
7282 case Instruction::Br: {
7283 // In cases of scalarized and predicated instructions, there will be VF
7284 // predicated blocks in the vectorized loop. Each branch around these
7285 // blocks requires also an extract of its vector compare i1 element.
7286 bool ScalarPredicatedBB = false;
7287 BranchInst *BI = cast<BranchInst>(I);
7288 if (VF > 1 && BI->isConditional() &&
7289 (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7290 PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7291 ScalarPredicatedBB = true;
7293 if (ScalarPredicatedBB) {
7294 // Return cost for branches around scalarized and predicated blocks.
7296 VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7297 return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
7298 (TTI.getCFInstrCost(Instruction::Br) * VF));
7299 } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
7300 // The back-edge branch will remain, as will all scalar branches.
7301 return TTI.getCFInstrCost(Instruction::Br);
7303 // This branch will be eliminated by if-conversion.
7305 // Note: We currently assume zero cost for an unconditional branch inside
7306 // a predicated block since it will become a fall-through, although we
7307 // may decide in the future to call TTI for all branches.
7309 case Instruction::PHI: {
7310 auto *Phi = cast<PHINode>(I);
7312 // First-order recurrences are replaced by vector shuffles inside the loop.
7313 if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
7314 return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
7315 VectorTy, VF - 1, VectorTy);
7317 // TODO: IF-converted IFs become selects.
7320 case Instruction::UDiv:
7321 case Instruction::SDiv:
7322 case Instruction::URem:
7323 case Instruction::SRem:
7324 // If we have a predicated instruction, it may not be executed for each
7325 // vector lane. Get the scalarization cost and scale this amount by the
7326 // probability of executing the predicated block. If the instruction is not
7327 // predicated, we fall through to the next case.
7328 if (VF > 1 && Legal->isScalarWithPredication(I)) {
7331 // These instructions have a non-void type, so account for the phi nodes
7332 // that we will create. This cost is likely to be zero. The phi node
7333 // cost, if any, should be scaled by the block probability because it
7334 // models a copy at the end of each predicated block.
7335 Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
7337 // The cost of the non-predicated instruction.
7338 Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
7340 // The cost of insertelement and extractelement instructions needed for
7342 Cost += getScalarizationOverhead(I, VF, TTI);
7344 // Scale the cost by the probability of executing the predicated blocks.
7345 // This assumes the predicated block for each vector lane is equally
7347 return Cost / getReciprocalPredBlockProb();
7349 case Instruction::Add:
7350 case Instruction::FAdd:
7351 case Instruction::Sub:
7352 case Instruction::FSub:
7353 case Instruction::Mul:
7354 case Instruction::FMul:
7355 case Instruction::FDiv:
7356 case Instruction::FRem:
7357 case Instruction::Shl:
7358 case Instruction::LShr:
7359 case Instruction::AShr:
7360 case Instruction::And:
7361 case Instruction::Or:
7362 case Instruction::Xor: {
7363 // Since we will replace the stride by 1 the multiplication should go away.
7364 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7366 // Certain instructions can be cheaper to vectorize if they have a constant
7367 // second vector operand. One example of this are shifts on x86.
7368 TargetTransformInfo::OperandValueKind Op1VK =
7369 TargetTransformInfo::OK_AnyValue;
7370 TargetTransformInfo::OperandValueKind Op2VK =
7371 TargetTransformInfo::OK_AnyValue;
7372 TargetTransformInfo::OperandValueProperties Op1VP =
7373 TargetTransformInfo::OP_None;
7374 TargetTransformInfo::OperandValueProperties Op2VP =
7375 TargetTransformInfo::OP_None;
7376 Value *Op2 = I->getOperand(1);
7378 // Check for a splat or for a non uniform vector of constants.
7379 if (isa<ConstantInt>(Op2)) {
7380 ConstantInt *CInt = cast<ConstantInt>(Op2);
7381 if (CInt && CInt->getValue().isPowerOf2())
7382 Op2VP = TargetTransformInfo::OP_PowerOf2;
7383 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7384 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
7385 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
7386 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
7388 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
7389 if (CInt && CInt->getValue().isPowerOf2())
7390 Op2VP = TargetTransformInfo::OP_PowerOf2;
7391 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7393 } else if (Legal->isUniform(Op2)) {
7394 Op2VK = TargetTransformInfo::OK_UniformValue;
7396 SmallVector<const Value *, 4> Operands(I->operand_values());
7397 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK,
7398 Op2VK, Op1VP, Op2VP, Operands);
7400 case Instruction::Select: {
7401 SelectInst *SI = cast<SelectInst>(I);
7402 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7403 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7404 Type *CondTy = SI->getCondition()->getType();
7406 CondTy = VectorType::get(CondTy, VF);
7408 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
7410 case Instruction::ICmp:
7411 case Instruction::FCmp: {
7412 Type *ValTy = I->getOperand(0)->getType();
7413 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7414 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7415 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7416 VectorTy = ToVectorTy(ValTy, VF);
7417 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
7419 case Instruction::Store:
7420 case Instruction::Load: {
7421 VectorTy = ToVectorTy(getMemInstValueType(I), VF);
7422 return getMemoryInstructionCost(I, VF);
7424 case Instruction::ZExt:
7425 case Instruction::SExt:
7426 case Instruction::FPToUI:
7427 case Instruction::FPToSI:
7428 case Instruction::FPExt:
7429 case Instruction::PtrToInt:
7430 case Instruction::IntToPtr:
7431 case Instruction::SIToFP:
7432 case Instruction::UIToFP:
7433 case Instruction::Trunc:
7434 case Instruction::FPTrunc:
7435 case Instruction::BitCast: {
7436 // We optimize the truncation of induction variables having constant
7437 // integer steps. The cost of these truncations is the same as the scalar
7439 if (isOptimizableIVTruncate(I, VF)) {
7440 auto *Trunc = cast<TruncInst>(I);
7441 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7442 Trunc->getSrcTy(), Trunc);
7445 Type *SrcScalarTy = I->getOperand(0)->getType();
7446 Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
7447 if (canTruncateToMinimalBitwidth(I, VF)) {
7448 // This cast is going to be shrunk. This may remove the cast or it might
7449 // turn it into slightly different cast. For example, if MinBW == 16,
7450 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7452 // Calculate the modified src and dest types.
7453 Type *MinVecTy = VectorTy;
7454 if (I->getOpcode() == Instruction::Trunc) {
7455 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7457 largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7458 } else if (I->getOpcode() == Instruction::ZExt ||
7459 I->getOpcode() == Instruction::SExt) {
7460 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7462 smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7466 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
7468 case Instruction::Call: {
7469 bool NeedToScalarize;
7470 CallInst *CI = cast<CallInst>(I);
7471 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
7472 if (getVectorIntrinsicIDForCall(CI, TLI))
7473 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
7477 // The cost of executing VF copies of the scalar instruction. This opcode
7478 // is unknown. Assume that it is the same as 'mul'.
7479 return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
7480 getScalarizationOverhead(I, VF, TTI);
7484 char LoopVectorize::ID = 0;
7485 static const char lv_name[] = "Loop Vectorization";
7486 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7487 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7488 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7489 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7490 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7491 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7492 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7493 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7494 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7495 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7496 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7497 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7498 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7499 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7502 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
7503 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
7507 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7509 // Check if the pointer operand of a load or store instruction is
7511 if (auto *Ptr = getPointerOperand(Inst))
7512 return Legal->isConsecutivePtr(Ptr);
7516 void LoopVectorizationCostModel::collectValuesToIgnore() {
7517 // Ignore ephemeral values.
7518 CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7520 // Ignore type-promoting instructions we identified during reduction
7522 for (auto &Reduction : *Legal->getReductionVars()) {
7523 RecurrenceDescriptor &RedDes = Reduction.second;
7524 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7525 VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7529 LoopVectorizationCostModel::VectorizationFactor
7530 LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) {
7532 // Width 1 means no vectorize, cost 0 means uncomputed cost.
7533 const LoopVectorizationCostModel::VectorizationFactor NoVectorization = {1U,
7535 Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
7536 if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize.
7537 return NoVectorization;
7540 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7541 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
7542 // Collect the instructions (and their associated costs) that will be more
7543 // profitable to scalarize.
7544 CM.selectUserVectorizationFactor(UserVF);
7548 unsigned MaxVF = MaybeMaxVF.getValue();
7549 assert(MaxVF != 0 && "MaxVF is zero.");
7551 return NoVectorization;
7553 // Select the optimal vectorization factor.
7554 return CM.selectVectorizationFactor(MaxVF);
7557 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
7558 auto *SI = dyn_cast<StoreInst>(Instr);
7559 bool IfPredicateInstr = (SI && Legal->blockNeedsPredication(SI->getParent()));
7561 return scalarizeInstruction(Instr, IfPredicateInstr);
7564 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
7566 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7568 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
7569 Instruction::BinaryOps BinOp) {
7570 // When unrolling and the VF is 1, we only need to add a simple scalar.
7571 Type *Ty = Val->getType();
7572 assert(!Ty->isVectorTy() && "Val must be a scalar");
7574 if (Ty->isFloatingPointTy()) {
7575 Constant *C = ConstantFP::get(Ty, (double)StartIdx);
7577 // Floating point operations had to be 'fast' to enable the unrolling.
7578 Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
7579 return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
7581 Constant *C = ConstantInt::get(Ty, StartIdx);
7582 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
7585 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7586 SmallVector<Metadata *, 4> MDs;
7587 // Reserve first location for self reference to the LoopID metadata node.
7588 MDs.push_back(nullptr);
7589 bool IsUnrollMetadata = false;
7590 MDNode *LoopID = L->getLoopID();
7592 // First find existing loop unrolling disable metadata.
7593 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7594 auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7596 const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7598 S && S->getString().startswith("llvm.loop.unroll.disable");
7600 MDs.push_back(LoopID->getOperand(i));
7604 if (!IsUnrollMetadata) {
7605 // Add runtime unroll disable metadata.
7606 LLVMContext &Context = L->getHeader()->getContext();
7607 SmallVector<Metadata *, 1> DisableOperands;
7608 DisableOperands.push_back(
7609 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7610 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7611 MDs.push_back(DisableNode);
7612 MDNode *NewLoopID = MDNode::get(Context, MDs);
7613 // Set operand 0 to refer to the loop id itself.
7614 NewLoopID->replaceOperandWith(0, NewLoopID);
7615 L->setLoopID(NewLoopID);
7619 bool LoopVectorizePass::processLoop(Loop *L) {
7620 assert(L->empty() && "Only process inner loops.");
7623 const std::string DebugLocStr = getDebugLocString(L);
7626 DEBUG(dbgs() << "\nLV: Checking a loop in \""
7627 << L->getHeader()->getParent()->getName() << "\" from "
7628 << DebugLocStr << "\n");
7630 LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
7632 DEBUG(dbgs() << "LV: Loop hints:"
7634 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
7636 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
7639 << " width=" << Hints.getWidth()
7640 << " unroll=" << Hints.getInterleave() << "\n");
7642 // Function containing loop
7643 Function *F = L->getHeader()->getParent();
7645 // Looking at the diagnostic output is the only way to determine if a loop
7646 // was vectorized (other than looking at the IR or machine code), so it
7647 // is important to generate an optimization remark for each loop. Most of
7648 // these messages are generated as OptimizationRemarkAnalysis. Remarks
7649 // generated as OptimizationRemark and OptimizationRemarkMissed are
7650 // less verbose reporting vectorized loops and unvectorized loops that may
7651 // benefit from vectorization, respectively.
7653 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
7654 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
7658 // Check the loop for a trip count threshold:
7659 // do not vectorize loops with a tiny trip count.
7660 const unsigned MaxTC = SE->getSmallConstantMaxTripCount(L);
7661 if (MaxTC > 0u && MaxTC < TinyTripCountVectorThreshold) {
7662 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
7663 << "This loop is not worth vectorizing.");
7664 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
7665 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
7667 DEBUG(dbgs() << "\n");
7668 ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
7670 << "vectorization is not beneficial "
7671 "and is not explicitly forced");
7676 PredicatedScalarEvolution PSE(*SE, *L);
7678 // Check if it is legal to vectorize the loop.
7679 LoopVectorizationRequirements Requirements(*ORE);
7680 LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE,
7681 &Requirements, &Hints);
7682 if (!LVL.canVectorize()) {
7683 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
7684 emitMissedWarning(F, L, Hints, ORE);
7688 // Check the function attributes to find out if this function should be
7689 // optimized for size.
7691 Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
7693 // Compute the weighted frequency of this loop being executed and see if it
7694 // is less than 20% of the function entry baseline frequency. Note that we
7695 // always have a canonical loop here because we think we *can* vectorize.
7696 // FIXME: This is hidden behind a flag due to pervasive problems with
7697 // exactly what block frequency models.
7698 if (LoopVectorizeWithBlockFrequency) {
7699 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
7700 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
7701 LoopEntryFreq < ColdEntryFreq)
7705 // Check the function attributes to see if implicit floats are allowed.
7706 // FIXME: This check doesn't seem possibly correct -- what if the loop is
7707 // an integer loop and the vector instructions selected are purely integer
7708 // vector instructions?
7709 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7710 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
7711 "attribute is used.\n");
7712 ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
7713 "NoImplicitFloat", L)
7714 << "loop not vectorized due to NoImplicitFloat attribute");
7715 emitMissedWarning(F, L, Hints, ORE);
7719 // Check if the target supports potentially unsafe FP vectorization.
7720 // FIXME: Add a check for the type of safety issue (denormal, signaling)
7721 // for the target we're vectorizing for, to make sure none of the
7722 // additional fp-math flags can help.
7723 if (Hints.isPotentiallyUnsafe() &&
7724 TTI->isFPVectorizationPotentiallyUnsafe()) {
7725 DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
7727 createMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
7728 << "loop not vectorized due to unsafe FP support.");
7729 emitMissedWarning(F, L, Hints, ORE);
7733 // Use the cost model.
7734 LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
7736 CM.collectValuesToIgnore();
7738 // Use the planner for vectorization.
7739 LoopVectorizationPlanner LVP(CM);
7741 // Get user vectorization factor.
7742 unsigned UserVF = Hints.getWidth();
7744 // Plan how to best vectorize, return the best VF and its cost.
7745 LoopVectorizationCostModel::VectorizationFactor VF =
7746 LVP.plan(OptForSize, UserVF);
7748 // Select the interleave count.
7749 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
7751 // Get user interleave count.
7752 unsigned UserIC = Hints.getInterleave();
7754 // Identify the diagnostic messages that should be produced.
7755 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7756 bool VectorizeLoop = true, InterleaveLoop = true;
7757 if (Requirements.doesNotMeet(F, L, Hints)) {
7758 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
7760 emitMissedWarning(F, L, Hints, ORE);
7764 if (VF.Width == 1) {
7765 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
7766 VecDiagMsg = std::make_pair(
7767 "VectorizationNotBeneficial",
7768 "the cost-model indicates that vectorization is not beneficial");
7769 VectorizeLoop = false;
7772 if (IC == 1 && UserIC <= 1) {
7773 // Tell the user interleaving is not beneficial.
7774 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
7775 IntDiagMsg = std::make_pair(
7776 "InterleavingNotBeneficial",
7777 "the cost-model indicates that interleaving is not beneficial");
7778 InterleaveLoop = false;
7780 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
7781 IntDiagMsg.second +=
7782 " and is explicitly disabled or interleave count is set to 1";
7784 } else if (IC > 1 && UserIC == 1) {
7785 // Tell the user interleaving is beneficial, but it explicitly disabled.
7787 << "LV: Interleaving is beneficial but is explicitly disabled.");
7788 IntDiagMsg = std::make_pair(
7789 "InterleavingBeneficialButDisabled",
7790 "the cost-model indicates that interleaving is beneficial "
7791 "but is explicitly disabled or interleave count is set to 1");
7792 InterleaveLoop = false;
7795 // Override IC if user provided an interleave count.
7796 IC = UserIC > 0 ? UserIC : IC;
7798 // Emit diagnostic messages, if any.
7799 const char *VAPassName = Hints.vectorizeAnalysisPassName();
7800 if (!VectorizeLoop && !InterleaveLoop) {
7801 // Do not vectorize or interleaving the loop.
7802 ORE->emit(OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
7803 L->getStartLoc(), L->getHeader())
7804 << VecDiagMsg.second);
7805 ORE->emit(OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
7806 L->getStartLoc(), L->getHeader())
7807 << IntDiagMsg.second);
7809 } else if (!VectorizeLoop && InterleaveLoop) {
7810 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7811 ORE->emit(OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
7812 L->getStartLoc(), L->getHeader())
7813 << VecDiagMsg.second);
7814 } else if (VectorizeLoop && !InterleaveLoop) {
7815 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
7816 << DebugLocStr << '\n');
7817 ORE->emit(OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
7818 L->getStartLoc(), L->getHeader())
7819 << IntDiagMsg.second);
7820 } else if (VectorizeLoop && InterleaveLoop) {
7821 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
7822 << DebugLocStr << '\n');
7823 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7826 using namespace ore;
7827 if (!VectorizeLoop) {
7828 assert(IC > 1 && "interleave count should not be 1 or 0");
7829 // If we decided that it is not legal to vectorize the loop, then
7831 InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
7833 Unroller.vectorize();
7835 ORE->emit(OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
7837 << "interleaved loop (interleaved count: "
7838 << NV("InterleaveCount", IC) << ")");
7840 // If we decided that it is *legal* to vectorize the loop, then do it.
7841 InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
7846 // Add metadata to disable runtime unrolling a scalar loop when there are
7847 // no runtime checks about strides and memory. A scalar loop that is
7848 // rarely used is not worth unrolling.
7849 if (!LB.areSafetyChecksAdded())
7850 AddRuntimeUnrollDisableMetaData(L);
7852 // Report the vectorization decision.
7853 ORE->emit(OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
7855 << "vectorized loop (vectorization width: "
7856 << NV("VectorizationFactor", VF.Width)
7857 << ", interleaved count: " << NV("InterleaveCount", IC) << ")");
7860 // Mark the loop as already vectorized to avoid vectorizing again.
7861 Hints.setAlreadyVectorized();
7863 DEBUG(verifyFunction(*L->getHeader()->getParent()));
7867 bool LoopVectorizePass::runImpl(
7868 Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
7869 DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
7870 DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
7871 std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
7872 OptimizationRemarkEmitter &ORE_) {
7886 // Compute some weights outside of the loop over the loops. Compute this
7887 // using a BranchProbability to re-use its scaling math.
7888 const BranchProbability ColdProb(1, 5); // 20%
7889 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
7892 // 1. the target claims to have no vector registers, and
7893 // 2. interleaving won't help ILP.
7895 // The second condition is necessary because, even if the target has no
7896 // vector registers, loop vectorization may still enable scalar
7898 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
7901 bool Changed = false;
7903 // The vectorizer requires loops to be in simplified form.
7904 // Since simplification may add new inner loops, it has to run before the
7905 // legality and profitability checks. This means running the loop vectorizer
7906 // will simplify all loops, regardless of whether anything end up being
7909 Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
7911 // Build up a worklist of inner-loops to vectorize. This is necessary as
7912 // the act of vectorizing or partially unrolling a loop creates new loops
7913 // and can invalidate iterators across the loops.
7914 SmallVector<Loop *, 8> Worklist;
7917 addAcyclicInnerLoop(*L, Worklist);
7919 LoopsAnalyzed += Worklist.size();
7921 // Now walk the identified inner loops.
7922 while (!Worklist.empty()) {
7923 Loop *L = Worklist.pop_back_val();
7925 // For the inner loops we actually process, form LCSSA to simplify the
7927 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
7929 Changed |= processLoop(L);
7932 // Process each loop nest in the function.
7938 PreservedAnalyses LoopVectorizePass::run(Function &F,
7939 FunctionAnalysisManager &AM) {
7940 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
7941 auto &LI = AM.getResult<LoopAnalysis>(F);
7942 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
7943 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
7944 auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
7945 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
7946 auto &AA = AM.getResult<AAManager>(F);
7947 auto &AC = AM.getResult<AssumptionAnalysis>(F);
7948 auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
7949 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
7951 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
7952 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
7953 [&](Loop &L) -> const LoopAccessInfo & {
7954 LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI};
7955 return LAM.getResult<LoopAccessAnalysis>(L, AR);
7958 runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
7960 return PreservedAnalyses::all();
7961 PreservedAnalyses PA;
7962 PA.preserve<LoopAnalysis>();
7963 PA.preserve<DominatorTreeAnalysis>();
7964 PA.preserve<BasicAA>();
7965 PA.preserve<GlobalsAA>();