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. Legalization of the IR is done
12 // in the codegen. However, the vectorizer uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
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 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Target/TargetLibraryInfo.h"
83 #include "llvm/Transforms/Scalar.h"
84 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
85 #include "llvm/Transforms/Utils/Local.h"
91 static cl::opt<unsigned>
92 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
93 cl::desc("Sets the SIMD width. Zero is autoselect."));
95 static cl::opt<unsigned>
96 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
97 cl::desc("Sets the vectorization unroll count. "
98 "Zero is autoselect."));
101 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
102 cl::desc("Enable if-conversion during vectorization."));
104 /// We don't vectorize loops with a known constant trip count below this number.
105 static cl::opt<unsigned>
106 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
108 cl::desc("Don't vectorize loops with a constant "
109 "trip count that is smaller than this "
112 /// We don't unroll loops with a known constant trip count below this number.
113 static const unsigned TinyTripCountUnrollThreshold = 128;
115 /// When performing a runtime memory check, do not check more than this
116 /// number of pointers. Notice that the check is quadratic!
117 static const unsigned RuntimeMemoryCheckThreshold = 4;
119 /// We use a metadata with this name to indicate that a scalar loop was
120 /// vectorized and that we don't need to re-vectorize it if we run into it
123 AlreadyVectorizedMDName = "llvm.vectorizer.already_vectorized";
127 // Forward declarations.
128 class LoopVectorizationLegality;
129 class LoopVectorizationCostModel;
131 /// InnerLoopVectorizer vectorizes loops which contain only one basic
132 /// block to a specified vectorization factor (VF).
133 /// This class performs the widening of scalars into vectors, or multiple
134 /// scalars. This class also implements the following features:
135 /// * It inserts an epilogue loop for handling loops that don't have iteration
136 /// counts that are known to be a multiple of the vectorization factor.
137 /// * It handles the code generation for reduction variables.
138 /// * Scalarization (implementation using scalars) of un-vectorizable
140 /// InnerLoopVectorizer does not perform any vectorization-legality
141 /// checks, and relies on the caller to check for the different legality
142 /// aspects. The InnerLoopVectorizer relies on the
143 /// LoopVectorizationLegality class to provide information about the induction
144 /// and reduction variables that were found to a given vectorization factor.
145 class InnerLoopVectorizer {
147 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
148 DominatorTree *DT, DataLayout *DL,
149 const TargetLibraryInfo *TLI, unsigned VecWidth,
150 unsigned UnrollFactor)
151 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
152 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
153 OldInduction(0), WidenMap(UnrollFactor) {}
155 // Perform the actual loop widening (vectorization).
156 void vectorize(LoopVectorizationLegality *Legal) {
157 // Create a new empty loop. Unlink the old loop and connect the new one.
158 createEmptyLoop(Legal);
159 // Widen each instruction in the old loop to a new one in the new loop.
160 // Use the Legality module to find the induction and reduction variables.
161 vectorizeLoop(Legal);
162 // Register the new loop and update the analysis passes.
167 /// A small list of PHINodes.
168 typedef SmallVector<PHINode*, 4> PhiVector;
169 /// When we unroll loops we have multiple vector values for each scalar.
170 /// This data structure holds the unrolled and vectorized values that
171 /// originated from one scalar instruction.
172 typedef SmallVector<Value*, 2> VectorParts;
174 /// Add code that checks at runtime if the accessed arrays overlap.
175 /// Returns the comparator value or NULL if no check is needed.
176 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
178 /// Create an empty loop, based on the loop ranges of the old loop.
179 void createEmptyLoop(LoopVectorizationLegality *Legal);
180 /// Copy and widen the instructions from the old loop.
181 void vectorizeLoop(LoopVectorizationLegality *Legal);
183 /// A helper function that computes the predicate of the block BB, assuming
184 /// that the header block of the loop is set to True. It returns the *entry*
185 /// mask for the block BB.
186 VectorParts createBlockInMask(BasicBlock *BB);
187 /// A helper function that computes the predicate of the edge between SRC
189 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
191 /// A helper function to vectorize a single BB within the innermost loop.
192 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
195 /// Insert the new loop to the loop hierarchy and pass manager
196 /// and update the analysis passes.
197 void updateAnalysis();
199 /// This instruction is un-vectorizable. Implement it as a sequence
201 void scalarizeInstruction(Instruction *Instr);
203 /// Vectorize Load and Store instructions,
204 void vectorizeMemoryInstruction(Instruction *Instr,
205 LoopVectorizationLegality *Legal);
207 /// Create a broadcast instruction. This method generates a broadcast
208 /// instruction (shuffle) for loop invariant values and for the induction
209 /// value. If this is the induction variable then we extend it to N, N+1, ...
210 /// this is needed because each iteration in the loop corresponds to a SIMD
212 Value *getBroadcastInstrs(Value *V);
214 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
215 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
216 /// The sequence starts at StartIndex.
217 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
219 /// When we go over instructions in the basic block we rely on previous
220 /// values within the current basic block or on loop invariant values.
221 /// When we widen (vectorize) values we place them in the map. If the values
222 /// are not within the map, they have to be loop invariant, so we simply
223 /// broadcast them into a vector.
224 VectorParts &getVectorValue(Value *V);
226 /// Generate a shuffle sequence that will reverse the vector Vec.
227 Value *reverseVector(Value *Vec);
229 /// This is a helper class that holds the vectorizer state. It maps scalar
230 /// instructions to vector instructions. When the code is 'unrolled' then
231 /// then a single scalar value is mapped to multiple vector parts. The parts
232 /// are stored in the VectorPart type.
234 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
236 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
238 /// \return True if 'Key' is saved in the Value Map.
239 bool has(Value *Key) const { return MapStorage.count(Key); }
241 /// Initializes a new entry in the map. Sets all of the vector parts to the
242 /// save value in 'Val'.
243 /// \return A reference to a vector with splat values.
244 VectorParts &splat(Value *Key, Value *Val) {
245 VectorParts &Entry = MapStorage[Key];
246 Entry.assign(UF, Val);
250 ///\return A reference to the value that is stored at 'Key'.
251 VectorParts &get(Value *Key) {
252 VectorParts &Entry = MapStorage[Key];
255 assert(Entry.size() == UF);
260 /// The unroll factor. Each entry in the map stores this number of vector
264 /// Map storage. We use std::map and not DenseMap because insertions to a
265 /// dense map invalidates its iterators.
266 std::map<Value *, VectorParts> MapStorage;
269 /// The original loop.
271 /// Scev analysis to use.
279 /// Target Library Info.
280 const TargetLibraryInfo *TLI;
282 /// The vectorization SIMD factor to use. Each vector will have this many
285 /// The vectorization unroll factor to use. Each scalar is vectorized to this
286 /// many different vector instructions.
289 /// The builder that we use
292 // --- Vectorization state ---
294 /// The vector-loop preheader.
295 BasicBlock *LoopVectorPreHeader;
296 /// The scalar-loop preheader.
297 BasicBlock *LoopScalarPreHeader;
298 /// Middle Block between the vector and the scalar.
299 BasicBlock *LoopMiddleBlock;
300 ///The ExitBlock of the scalar loop.
301 BasicBlock *LoopExitBlock;
302 ///The vector loop body.
303 BasicBlock *LoopVectorBody;
304 ///The scalar loop body.
305 BasicBlock *LoopScalarBody;
306 /// A list of all bypass blocks. The first block is the entry of the loop.
307 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
309 /// The new Induction variable which was added to the new block.
311 /// The induction variable of the old basic block.
312 PHINode *OldInduction;
313 /// Maps scalars to widened vectors.
317 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
318 /// to what vectorization factor.
319 /// This class does not look at the profitability of vectorization, only the
320 /// legality. This class has two main kinds of checks:
321 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
322 /// will change the order of memory accesses in a way that will change the
323 /// correctness of the program.
324 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
325 /// checks for a number of different conditions, such as the availability of a
326 /// single induction variable, that all types are supported and vectorize-able,
327 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
328 /// This class is also used by InnerLoopVectorizer for identifying
329 /// induction variable and the different reduction variables.
330 class LoopVectorizationLegality {
332 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
333 DominatorTree *DT, TargetTransformInfo* TTI,
334 AliasAnalysis *AA, TargetLibraryInfo *TLI)
335 : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), TLI(TLI),
338 /// This enum represents the kinds of reductions that we support.
340 RK_NoReduction, ///< Not a reduction.
341 RK_IntegerAdd, ///< Sum of integers.
342 RK_IntegerMult, ///< Product of integers.
343 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
344 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
345 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
346 RK_FloatAdd, ///< Sum of floats.
347 RK_FloatMult ///< Product of floats.
350 /// This enum represents the kinds of inductions that we support.
352 IK_NoInduction, ///< Not an induction variable.
353 IK_IntInduction, ///< Integer induction variable. Step = 1.
354 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
355 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
356 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
359 /// This POD struct holds information about reduction variables.
360 struct ReductionDescriptor {
361 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
362 Kind(RK_NoReduction) {}
364 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
365 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
367 // The starting value of the reduction.
368 // It does not have to be zero!
370 // The instruction who's value is used outside the loop.
371 Instruction *LoopExitInstr;
372 // The kind of the reduction.
376 // This POD struct holds information about the memory runtime legality
377 // check that a group of pointers do not overlap.
378 struct RuntimePointerCheck {
379 RuntimePointerCheck() : Need(false) {}
381 /// Reset the state of the pointer runtime information.
389 /// Insert a pointer and calculate the start and end SCEVs.
390 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
392 /// This flag indicates if we need to add the runtime check.
394 /// Holds the pointers that we need to check.
395 SmallVector<Value*, 2> Pointers;
396 /// Holds the pointer value at the beginning of the loop.
397 SmallVector<const SCEV*, 2> Starts;
398 /// Holds the pointer value at the end of the loop.
399 SmallVector<const SCEV*, 2> Ends;
402 /// A POD for saving information about induction variables.
403 struct InductionInfo {
404 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
405 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
412 /// ReductionList contains the reduction descriptors for all
413 /// of the reductions that were found in the loop.
414 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
416 /// InductionList saves induction variables and maps them to the
417 /// induction descriptor.
418 typedef MapVector<PHINode*, InductionInfo> InductionList;
420 /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
421 /// respective Store/Load instruction(s) to calculate aliasing.
422 typedef DenseMap<Value*, Instruction* > AliasMap;
423 typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
425 /// Returns true if it is legal to vectorize this loop.
426 /// This does not mean that it is profitable to vectorize this
427 /// loop, only that it is legal to do so.
430 /// Returns the Induction variable.
431 PHINode *getInduction() { return Induction; }
433 /// Returns the reduction variables found in the loop.
434 ReductionList *getReductionVars() { return &Reductions; }
436 /// Returns the induction variables found in the loop.
437 InductionList *getInductionVars() { return &Inductions; }
439 /// Returns True if V is an induction variable in this loop.
440 bool isInductionVariable(const Value *V);
442 /// Return true if the block BB needs to be predicated in order for the loop
443 /// to be vectorized.
444 bool blockNeedsPredication(BasicBlock *BB);
446 /// Check if this pointer is consecutive when vectorizing. This happens
447 /// when the last index of the GEP is the induction variable, or that the
448 /// pointer itself is an induction variable.
449 /// This check allows us to vectorize A[idx] into a wide load/store.
451 /// 0 - Stride is unknown or non consecutive.
452 /// 1 - Address is consecutive.
453 /// -1 - Address is consecutive, and decreasing.
454 int isConsecutivePtr(Value *Ptr);
456 /// Returns true if the value V is uniform within the loop.
457 bool isUniform(Value *V);
459 /// Returns true if this instruction will remain scalar after vectorization.
460 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
462 /// Returns the information that we collected about runtime memory check.
463 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
465 /// Check if a single basic block loop is vectorizable.
466 /// At this point we know that this is a loop with a constant trip count
467 /// and we only need to check individual instructions.
468 bool canVectorizeInstrs();
470 /// When we vectorize loops we may change the order in which
471 /// we read and write from memory. This method checks if it is
472 /// legal to vectorize the code, considering only memory constrains.
473 /// Returns true if the loop is vectorizable
474 bool canVectorizeMemory();
476 /// Return true if we can vectorize this loop using the IF-conversion
478 bool canVectorizeWithIfConvert();
480 /// Collect the variables that need to stay uniform after vectorization.
481 void collectLoopUniforms();
483 /// Return true if all of the instructions in the block can be speculatively
485 bool blockCanBePredicated(BasicBlock *BB);
487 /// Returns True, if 'Phi' is the kind of reduction variable for type
488 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
489 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
490 /// Returns true if the instruction I can be a reduction variable of type
492 bool isReductionInstr(Instruction *I, ReductionKind Kind);
493 /// Returns the induction kind of Phi. This function may return NoInduction
494 /// if the PHI is not an induction variable.
495 InductionKind isInductionVariable(PHINode *Phi);
496 /// Return true if can compute the address bounds of Ptr within the loop.
497 bool hasComputableBounds(Value *Ptr);
498 /// Return true if there is the chance of write reorder.
499 bool hasPossibleGlobalWriteReorder(Value *Object,
501 AliasMultiMap &WriteObjects,
502 unsigned MaxByteWidth);
503 /// Return the AA location for a load or a store.
504 AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
507 /// The loop that we evaluate.
511 /// DataLayout analysis.
516 TargetTransformInfo *TTI;
519 /// Target Library Info.
520 TargetLibraryInfo *TLI;
522 // --- vectorization state --- //
524 /// Holds the integer induction variable. This is the counter of the
527 /// Holds the reduction variables.
528 ReductionList Reductions;
529 /// Holds all of the induction variables that we found in the loop.
530 /// Notice that inductions don't need to start at zero and that induction
531 /// variables can be pointers.
532 InductionList Inductions;
534 /// Allowed outside users. This holds the reduction
535 /// vars which can be accessed from outside the loop.
536 SmallPtrSet<Value*, 4> AllowedExit;
537 /// This set holds the variables which are known to be uniform after
539 SmallPtrSet<Instruction*, 4> Uniforms;
540 /// We need to check that all of the pointers in this list are disjoint
542 RuntimePointerCheck PtrRtCheck;
545 /// LoopVectorizationCostModel - estimates the expected speedups due to
547 /// In many cases vectorization is not profitable. This can happen because of
548 /// a number of reasons. In this class we mainly attempt to predict the
549 /// expected speedup/slowdowns due to the supported instruction set. We use the
550 /// TargetTransformInfo to query the different backends for the cost of
551 /// different operations.
552 class LoopVectorizationCostModel {
554 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
555 LoopVectorizationLegality *Legal,
556 const TargetTransformInfo &TTI,
557 DataLayout *DL, const TargetLibraryInfo *TLI)
558 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
560 /// Information about vectorization costs
561 struct VectorizationFactor {
562 unsigned Width; // Vector width with best cost
563 unsigned Cost; // Cost of the loop with that width
565 /// \return The most profitable vectorization factor and the cost of that VF.
566 /// This method checks every power of two up to VF. If UserVF is not ZERO
567 /// then this vectorization factor will be selected if vectorization is
569 VectorizationFactor selectVectorizationFactor(bool OptForSize,
572 /// \return The size (in bits) of the widest type in the code that
573 /// needs to be vectorized. We ignore values that remain scalar such as
574 /// 64 bit loop indices.
575 unsigned getWidestType();
577 /// \return The most profitable unroll factor.
578 /// If UserUF is non-zero then this method finds the best unroll-factor
579 /// based on register pressure and other parameters.
580 /// VF and LoopCost are the selected vectorization factor and the cost of the
582 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
585 /// \brief A struct that represents some properties of the register usage
587 struct RegisterUsage {
588 /// Holds the number of loop invariant values that are used in the loop.
589 unsigned LoopInvariantRegs;
590 /// Holds the maximum number of concurrent live intervals in the loop.
591 unsigned MaxLocalUsers;
592 /// Holds the number of instructions in the loop.
593 unsigned NumInstructions;
596 /// \return information about the register usage of the loop.
597 RegisterUsage calculateRegisterUsage();
600 /// Returns the expected execution cost. The unit of the cost does
601 /// not matter because we use the 'cost' units to compare different
602 /// vector widths. The cost that is returned is *not* normalized by
603 /// the factor width.
604 unsigned expectedCost(unsigned VF);
606 /// Returns the execution time cost of an instruction for a given vector
607 /// width. Vector width of one means scalar.
608 unsigned getInstructionCost(Instruction *I, unsigned VF);
610 /// A helper function for converting Scalar types to vector types.
611 /// If the incoming type is void, we return void. If the VF is 1, we return
613 static Type* ToVectorTy(Type *Scalar, unsigned VF);
615 /// Returns whether the instruction is a load or store and will be a emitted
616 /// as a vector operation.
617 bool isConsecutiveLoadOrStore(Instruction *I);
619 /// The loop that we evaluate.
623 /// Loop Info analysis.
625 /// Vectorization legality.
626 LoopVectorizationLegality *Legal;
627 /// Vector target information.
628 const TargetTransformInfo &TTI;
629 /// Target data layout information.
631 /// Target Library Info.
632 const TargetLibraryInfo *TLI;
635 /// The LoopVectorize Pass.
636 struct LoopVectorize : public LoopPass {
637 /// Pass identification, replacement for typeid
640 explicit LoopVectorize() : LoopPass(ID) {
641 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
647 TargetTransformInfo *TTI;
650 TargetLibraryInfo *TLI;
652 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
653 // We only vectorize innermost loops.
657 SE = &getAnalysis<ScalarEvolution>();
658 DL = getAnalysisIfAvailable<DataLayout>();
659 LI = &getAnalysis<LoopInfo>();
660 TTI = &getAnalysis<TargetTransformInfo>();
661 DT = &getAnalysis<DominatorTree>();
662 AA = getAnalysisIfAvailable<AliasAnalysis>();
663 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
665 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
666 L->getHeader()->getParent()->getName() << "\"\n");
668 // Check if it is legal to vectorize the loop.
669 LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA, TLI);
670 if (!LVL.canVectorize()) {
671 DEBUG(dbgs() << "LV: Not vectorizing.\n");
675 // Use the cost model.
676 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
678 // Check the function attributes to find out if this function should be
679 // optimized for size.
680 Function *F = L->getHeader()->getParent();
681 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
682 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
683 unsigned FnIndex = AttributeSet::FunctionIndex;
684 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
685 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
688 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
689 "attribute is used.\n");
693 // Select the optimal vectorization factor.
694 LoopVectorizationCostModel::VectorizationFactor VF;
695 VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
696 // Select the unroll factor.
697 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
701 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
705 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
706 F->getParent()->getModuleIdentifier()<<"\n");
707 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
709 // If we decided that it is *legal* to vectorize the loop then do it.
710 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
713 DEBUG(verifyFunction(*L->getHeader()->getParent()));
717 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
718 LoopPass::getAnalysisUsage(AU);
719 AU.addRequiredID(LoopSimplifyID);
720 AU.addRequiredID(LCSSAID);
721 AU.addRequired<DominatorTree>();
722 AU.addRequired<LoopInfo>();
723 AU.addRequired<ScalarEvolution>();
724 AU.addRequired<TargetTransformInfo>();
725 AU.addPreserved<LoopInfo>();
726 AU.addPreserved<DominatorTree>();
731 } // end anonymous namespace
733 //===----------------------------------------------------------------------===//
734 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
735 // LoopVectorizationCostModel.
736 //===----------------------------------------------------------------------===//
739 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
740 Loop *Lp, Value *Ptr) {
741 const SCEV *Sc = SE->getSCEV(Ptr);
742 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
743 assert(AR && "Invalid addrec expression");
744 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
745 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
746 Pointers.push_back(Ptr);
747 Starts.push_back(AR->getStart());
748 Ends.push_back(ScEnd);
751 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
752 // Save the current insertion location.
753 Instruction *Loc = Builder.GetInsertPoint();
755 // We need to place the broadcast of invariant variables outside the loop.
756 Instruction *Instr = dyn_cast<Instruction>(V);
757 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
758 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
760 // Place the code for broadcasting invariant variables in the new preheader.
762 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
764 // Broadcast the scalar into all locations in the vector.
765 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
767 // Restore the builder insertion point.
769 Builder.SetInsertPoint(Loc);
774 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
776 assert(Val->getType()->isVectorTy() && "Must be a vector");
777 assert(Val->getType()->getScalarType()->isIntegerTy() &&
778 "Elem must be an integer");
780 Type *ITy = Val->getType()->getScalarType();
781 VectorType *Ty = cast<VectorType>(Val->getType());
782 int VLen = Ty->getNumElements();
783 SmallVector<Constant*, 8> Indices;
785 // Create a vector of consecutive numbers from zero to VF.
786 for (int i = 0; i < VLen; ++i) {
787 int Idx = Negate ? (-i): i;
788 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
791 // Add the consecutive indices to the vector value.
792 Constant *Cv = ConstantVector::get(Indices);
793 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
794 return Builder.CreateAdd(Val, Cv, "induction");
797 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
798 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
799 // Make sure that the pointer does not point to structs.
800 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
803 // If this value is a pointer induction variable we know it is consecutive.
804 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
805 if (Phi && Inductions.count(Phi)) {
806 InductionInfo II = Inductions[Phi];
807 if (IK_PtrInduction == II.IK)
809 else if (IK_ReversePtrInduction == II.IK)
813 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
817 unsigned NumOperands = Gep->getNumOperands();
818 Value *LastIndex = Gep->getOperand(NumOperands - 1);
820 Value *GpPtr = Gep->getPointerOperand();
821 // If this GEP value is a consecutive pointer induction variable and all of
822 // the indices are constant then we know it is consecutive. We can
823 Phi = dyn_cast<PHINode>(GpPtr);
824 if (Phi && Inductions.count(Phi)) {
826 // Make sure that the pointer does not point to structs.
827 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
828 if (GepPtrType->getElementType()->isAggregateType())
831 // Make sure that all of the index operands are loop invariant.
832 for (unsigned i = 1; i < NumOperands; ++i)
833 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
836 InductionInfo II = Inductions[Phi];
837 if (IK_PtrInduction == II.IK)
839 else if (IK_ReversePtrInduction == II.IK)
843 // Check that all of the gep indices are uniform except for the last.
844 for (unsigned i = 0; i < NumOperands - 1; ++i)
845 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
848 // We can emit wide load/stores only if the last index is the induction
850 const SCEV *Last = SE->getSCEV(LastIndex);
851 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
852 const SCEV *Step = AR->getStepRecurrence(*SE);
854 // The memory is consecutive because the last index is consecutive
855 // and all other indices are loop invariant.
858 if (Step->isAllOnesValue())
865 bool LoopVectorizationLegality::isUniform(Value *V) {
866 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
869 InnerLoopVectorizer::VectorParts&
870 InnerLoopVectorizer::getVectorValue(Value *V) {
871 assert(V != Induction && "The new induction variable should not be used.");
872 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
874 // If we have this scalar in the map, return it.
876 return WidenMap.get(V);
878 // If this scalar is unknown, assume that it is a constant or that it is
879 // loop invariant. Broadcast V and save the value for future uses.
880 Value *B = getBroadcastInstrs(V);
881 return WidenMap.splat(V, B);
884 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
885 assert(Vec->getType()->isVectorTy() && "Invalid type");
886 SmallVector<Constant*, 8> ShuffleMask;
887 for (unsigned i = 0; i < VF; ++i)
888 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
890 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
891 ConstantVector::get(ShuffleMask),
896 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
897 LoopVectorizationLegality *Legal) {
898 // Attempt to issue a wide load.
899 LoadInst *LI = dyn_cast<LoadInst>(Instr);
900 StoreInst *SI = dyn_cast<StoreInst>(Instr);
902 assert((LI || SI) && "Invalid Load/Store instruction");
904 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
905 Type *DataTy = VectorType::get(ScalarDataTy, VF);
906 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
907 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
909 // If the pointer is loop invariant or if it is non consecutive,
910 // scalarize the load.
911 int Stride = Legal->isConsecutivePtr(Ptr);
912 bool Reverse = Stride < 0;
913 bool UniformLoad = LI && Legal->isUniform(Ptr);
914 if (Stride == 0 || UniformLoad)
915 return scalarizeInstruction(Instr);
917 Constant *Zero = Builder.getInt32(0);
918 VectorParts &Entry = WidenMap.get(Instr);
920 // Handle consecutive loads/stores.
921 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
922 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
923 Value *PtrOperand = Gep->getPointerOperand();
924 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
925 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
927 // Create the new GEP with the new induction variable.
928 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
929 Gep2->setOperand(0, FirstBasePtr);
930 Gep2->setName("gep.indvar.base");
931 Ptr = Builder.Insert(Gep2);
933 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
934 OrigLoop) && "Base ptr must be invariant");
936 // The last index does not have to be the induction. It can be
937 // consecutive and be a function of the index. For example A[I+1];
938 unsigned NumOperands = Gep->getNumOperands();
940 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
941 VectorParts &GEPParts = getVectorValue(LastGepOperand);
942 Value *LastIndex = GEPParts[0];
943 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
945 // Create the new GEP with the new induction variable.
946 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
947 Gep2->setOperand(NumOperands - 1, LastIndex);
948 Gep2->setName("gep.indvar.idx");
949 Ptr = Builder.Insert(Gep2);
951 // Use the induction element ptr.
952 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
953 VectorParts &PtrVal = getVectorValue(Ptr);
954 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
959 assert(!Legal->isUniform(SI->getPointerOperand()) &&
960 "We do not allow storing to uniform addresses");
962 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
963 for (unsigned Part = 0; Part < UF; ++Part) {
964 // Calculate the pointer for the specific unroll-part.
965 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
968 // If we store to reverse consecutive memory locations then we need
969 // to reverse the order of elements in the stored value.
970 StoredVal[Part] = reverseVector(StoredVal[Part]);
971 // If the address is consecutive but reversed, then the
972 // wide store needs to start at the last vector element.
973 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
974 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
977 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
978 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
982 for (unsigned Part = 0; Part < UF; ++Part) {
983 // Calculate the pointer for the specific unroll-part.
984 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
987 // If the address is consecutive but reversed, then the
988 // wide store needs to start at the last vector element.
989 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
990 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
993 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
994 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
995 cast<LoadInst>(LI)->setAlignment(Alignment);
996 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1000 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1001 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1002 // Holds vector parameters or scalars, in case of uniform vals.
1003 SmallVector<VectorParts, 4> Params;
1005 // Find all of the vectorized parameters.
1006 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1007 Value *SrcOp = Instr->getOperand(op);
1009 // If we are accessing the old induction variable, use the new one.
1010 if (SrcOp == OldInduction) {
1011 Params.push_back(getVectorValue(SrcOp));
1015 // Try using previously calculated values.
1016 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1018 // If the src is an instruction that appeared earlier in the basic block
1019 // then it should already be vectorized.
1020 if (SrcInst && OrigLoop->contains(SrcInst)) {
1021 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1022 // The parameter is a vector value from earlier.
1023 Params.push_back(WidenMap.get(SrcInst));
1025 // The parameter is a scalar from outside the loop. Maybe even a constant.
1026 VectorParts Scalars;
1027 Scalars.append(UF, SrcOp);
1028 Params.push_back(Scalars);
1032 assert(Params.size() == Instr->getNumOperands() &&
1033 "Invalid number of operands");
1035 // Does this instruction return a value ?
1036 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1038 Value *UndefVec = IsVoidRetTy ? 0 :
1039 UndefValue::get(VectorType::get(Instr->getType(), VF));
1040 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1041 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1043 // For each scalar that we create:
1044 for (unsigned Width = 0; Width < VF; ++Width) {
1045 // For each vector unroll 'part':
1046 for (unsigned Part = 0; Part < UF; ++Part) {
1047 Instruction *Cloned = Instr->clone();
1049 Cloned->setName(Instr->getName() + ".cloned");
1050 // Replace the operands of the cloned instrucions with extracted scalars.
1051 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1052 Value *Op = Params[op][Part];
1053 // Param is a vector. Need to extract the right lane.
1054 if (Op->getType()->isVectorTy())
1055 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1056 Cloned->setOperand(op, Op);
1059 // Place the cloned scalar in the new loop.
1060 Builder.Insert(Cloned);
1062 // If the original scalar returns a value we need to place it in a vector
1063 // so that future users will be able to use it.
1065 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1066 Builder.getInt32(Width));
1072 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1074 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1075 Legal->getRuntimePointerCheck();
1077 if (!PtrRtCheck->Need)
1080 Instruction *MemoryRuntimeCheck = 0;
1081 unsigned NumPointers = PtrRtCheck->Pointers.size();
1082 SmallVector<Value* , 2> Starts;
1083 SmallVector<Value* , 2> Ends;
1085 SCEVExpander Exp(*SE, "induction");
1087 // Use this type for pointer arithmetic.
1088 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1090 for (unsigned i = 0; i < NumPointers; ++i) {
1091 Value *Ptr = PtrRtCheck->Pointers[i];
1092 const SCEV *Sc = SE->getSCEV(Ptr);
1094 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1095 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1097 Starts.push_back(Ptr);
1098 Ends.push_back(Ptr);
1100 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1102 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1103 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1104 Starts.push_back(Start);
1105 Ends.push_back(End);
1109 IRBuilder<> ChkBuilder(Loc);
1111 for (unsigned i = 0; i < NumPointers; ++i) {
1112 for (unsigned j = i+1; j < NumPointers; ++j) {
1113 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1114 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1115 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc");
1116 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc");
1118 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1119 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1120 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1121 if (MemoryRuntimeCheck)
1122 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1125 MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1129 return MemoryRuntimeCheck;
1133 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1135 In this function we generate a new loop. The new loop will contain
1136 the vectorized instructions while the old loop will continue to run the
1139 [ ] <-- vector loop bypass (may consist of multiple blocks).
1142 | [ ] <-- vector pre header.
1146 | [ ]_| <-- vector loop.
1149 >[ ] <--- middle-block.
1152 | [ ] <--- new preheader.
1156 | [ ]_| <-- old scalar loop to handle remainder.
1159 >[ ] <-- exit block.
1163 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1164 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1165 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1166 assert(ExitBlock && "Must have an exit block");
1168 // Mark the old scalar loop with metadata that tells us not to vectorize this
1169 // loop again if we run into it.
1170 MDNode *MD = MDNode::get(OldBasicBlock->getContext(), ArrayRef<Value*>());
1171 OldBasicBlock->getTerminator()->setMetadata(AlreadyVectorizedMDName, MD);
1173 // Some loops have a single integer induction variable, while other loops
1174 // don't. One example is c++ iterators that often have multiple pointer
1175 // induction variables. In the code below we also support a case where we
1176 // don't have a single induction variable.
1177 OldInduction = Legal->getInduction();
1178 Type *IdxTy = OldInduction ? OldInduction->getType() :
1179 DL->getIntPtrType(SE->getContext());
1181 // Find the loop boundaries.
1182 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1183 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1185 // Get the total trip count from the count by adding 1.
1186 ExitCount = SE->getAddExpr(ExitCount,
1187 SE->getConstant(ExitCount->getType(), 1));
1189 // Expand the trip count and place the new instructions in the preheader.
1190 // Notice that the pre-header does not change, only the loop body.
1191 SCEVExpander Exp(*SE, "induction");
1193 // Count holds the overall loop count (N).
1194 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1195 BypassBlock->getTerminator());
1197 // The loop index does not have to start at Zero. Find the original start
1198 // value from the induction PHI node. If we don't have an induction variable
1199 // then we know that it starts at zero.
1200 Value *StartIdx = OldInduction ?
1201 OldInduction->getIncomingValueForBlock(BypassBlock):
1202 ConstantInt::get(IdxTy, 0);
1204 assert(BypassBlock && "Invalid loop structure");
1205 LoopBypassBlocks.push_back(BypassBlock);
1207 // Split the single block loop into the two loop structure described above.
1208 BasicBlock *VectorPH =
1209 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1210 BasicBlock *VecBody =
1211 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1212 BasicBlock *MiddleBlock =
1213 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1214 BasicBlock *ScalarPH =
1215 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1217 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1219 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1221 // Generate the induction variable.
1222 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1223 // The loop step is equal to the vectorization factor (num of SIMD elements)
1224 // times the unroll factor (num of SIMD instructions).
1225 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1227 // This is the IR builder that we use to add all of the logic for bypassing
1228 // the new vector loop.
1229 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1231 // We may need to extend the index in case there is a type mismatch.
1232 // We know that the count starts at zero and does not overflow.
1233 if (Count->getType() != IdxTy) {
1234 // The exit count can be of pointer type. Convert it to the correct
1236 if (ExitCount->getType()->isPointerTy())
1237 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1239 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1242 // Add the start index to the loop count to get the new end index.
1243 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1245 // Now we need to generate the expression for N - (N % VF), which is
1246 // the part that the vectorized body will execute.
1247 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1248 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1249 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1250 "end.idx.rnd.down");
1252 // Now, compare the new count to zero. If it is zero skip the vector loop and
1253 // jump to the scalar loop.
1254 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1257 BasicBlock *LastBypassBlock = BypassBlock;
1259 // Generate the code that checks in runtime if arrays overlap. We put the
1260 // checks into a separate block to make the more common case of few elements
1262 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1263 BypassBlock->getTerminator());
1264 if (MemRuntimeCheck) {
1265 // Create a new block containing the memory check.
1266 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1268 LoopBypassBlocks.push_back(CheckBlock);
1270 // Replace the branch into the memory check block with a conditional branch
1271 // for the "few elements case".
1272 Instruction *OldTerm = BypassBlock->getTerminator();
1273 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1274 OldTerm->eraseFromParent();
1276 Cmp = MemRuntimeCheck;
1277 LastBypassBlock = CheckBlock;
1280 LastBypassBlock->getTerminator()->eraseFromParent();
1281 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1284 // We are going to resume the execution of the scalar loop.
1285 // Go over all of the induction variables that we found and fix the
1286 // PHIs that are left in the scalar version of the loop.
1287 // The starting values of PHI nodes depend on the counter of the last
1288 // iteration in the vectorized loop.
1289 // If we come from a bypass edge then we need to start from the original
1292 // This variable saves the new starting index for the scalar loop.
1293 PHINode *ResumeIndex = 0;
1294 LoopVectorizationLegality::InductionList::iterator I, E;
1295 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1296 for (I = List->begin(), E = List->end(); I != E; ++I) {
1297 PHINode *OrigPhi = I->first;
1298 LoopVectorizationLegality::InductionInfo II = I->second;
1299 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1300 MiddleBlock->getTerminator());
1301 Value *EndValue = 0;
1303 case LoopVectorizationLegality::IK_NoInduction:
1304 llvm_unreachable("Unknown induction");
1305 case LoopVectorizationLegality::IK_IntInduction: {
1306 // Handle the integer induction counter:
1307 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1308 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1309 // We know what the end value is.
1310 EndValue = IdxEndRoundDown;
1311 // We also know which PHI node holds it.
1312 ResumeIndex = ResumeVal;
1315 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1316 // Convert the CountRoundDown variable to the PHI size.
1317 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1318 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1319 Value *CRD = CountRoundDown;
1320 if (CRDSize > IISize)
1321 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1322 II.StartValue->getType(), "tr.crd",
1323 LoopBypassBlocks.back()->getTerminator());
1324 else if (CRDSize < IISize)
1325 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1326 II.StartValue->getType(),
1328 LoopBypassBlocks.back()->getTerminator());
1329 // Handle reverse integer induction counter:
1331 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1332 LoopBypassBlocks.back()->getTerminator());
1335 case LoopVectorizationLegality::IK_PtrInduction: {
1336 // For pointer induction variables, calculate the offset using
1339 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1340 LoopBypassBlocks.back()->getTerminator());
1343 case LoopVectorizationLegality::IK_ReversePtrInduction: {
1344 // The value at the end of the loop for the reverse pointer is calculated
1345 // by creating a GEP with a negative index starting from the start value.
1346 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1347 Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1349 LoopBypassBlocks.back()->getTerminator());
1350 EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1352 LoopBypassBlocks.back()->getTerminator());
1357 // The new PHI merges the original incoming value, in case of a bypass,
1358 // or the value at the end of the vectorized loop.
1359 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1360 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1361 ResumeVal->addIncoming(EndValue, VecBody);
1363 // Fix the scalar body counter (PHI node).
1364 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1365 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1368 // If we are generating a new induction variable then we also need to
1369 // generate the code that calculates the exit value. This value is not
1370 // simply the end of the counter because we may skip the vectorized body
1371 // in case of a runtime check.
1373 assert(!ResumeIndex && "Unexpected resume value found");
1374 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1375 MiddleBlock->getTerminator());
1376 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1377 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1378 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1381 // Make sure that we found the index where scalar loop needs to continue.
1382 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1383 "Invalid resume Index");
1385 // Add a check in the middle block to see if we have completed
1386 // all of the iterations in the first vector loop.
1387 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1388 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1389 ResumeIndex, "cmp.n",
1390 MiddleBlock->getTerminator());
1392 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1393 // Remove the old terminator.
1394 MiddleBlock->getTerminator()->eraseFromParent();
1396 // Create i+1 and fill the PHINode.
1397 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1398 Induction->addIncoming(StartIdx, VectorPH);
1399 Induction->addIncoming(NextIdx, VecBody);
1400 // Create the compare.
1401 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1402 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1404 // Now we have two terminators. Remove the old one from the block.
1405 VecBody->getTerminator()->eraseFromParent();
1407 // Get ready to start creating new instructions into the vectorized body.
1408 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1410 // Create and register the new vector loop.
1411 Loop* Lp = new Loop();
1412 Loop *ParentLoop = OrigLoop->getParentLoop();
1414 // Insert the new loop into the loop nest and register the new basic blocks.
1416 ParentLoop->addChildLoop(Lp);
1417 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1418 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1419 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1420 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1421 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1423 LI->addTopLevelLoop(Lp);
1426 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1429 LoopVectorPreHeader = VectorPH;
1430 LoopScalarPreHeader = ScalarPH;
1431 LoopMiddleBlock = MiddleBlock;
1432 LoopExitBlock = ExitBlock;
1433 LoopVectorBody = VecBody;
1434 LoopScalarBody = OldBasicBlock;
1437 /// This function returns the identity element (or neutral element) for
1438 /// the operation K.
1440 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1442 case LoopVectorizationLegality:: RK_IntegerXor:
1443 case LoopVectorizationLegality:: RK_IntegerAdd:
1444 case LoopVectorizationLegality:: RK_IntegerOr:
1445 // Adding, Xoring, Oring zero to a number does not change it.
1446 return ConstantInt::get(Tp, 0);
1447 case LoopVectorizationLegality:: RK_IntegerMult:
1448 // Multiplying a number by 1 does not change it.
1449 return ConstantInt::get(Tp, 1);
1450 case LoopVectorizationLegality:: RK_IntegerAnd:
1451 // AND-ing a number with an all-1 value does not change it.
1452 return ConstantInt::get(Tp, -1, true);
1453 case LoopVectorizationLegality:: RK_FloatMult:
1454 // Multiplying a number by 1 does not change it.
1455 return ConstantFP::get(Tp, 1.0L);
1456 case LoopVectorizationLegality:: RK_FloatAdd:
1457 // Adding zero to a number does not change it.
1458 return ConstantFP::get(Tp, 0.0L);
1460 llvm_unreachable("Unknown reduction kind");
1464 static Intrinsic::ID
1465 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1466 // If we have an intrinsic call, check if it is trivially vectorizable.
1467 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1468 switch (II->getIntrinsicID()) {
1469 case Intrinsic::sqrt:
1470 case Intrinsic::sin:
1471 case Intrinsic::cos:
1472 case Intrinsic::exp:
1473 case Intrinsic::exp2:
1474 case Intrinsic::log:
1475 case Intrinsic::log10:
1476 case Intrinsic::log2:
1477 case Intrinsic::fabs:
1478 case Intrinsic::floor:
1479 case Intrinsic::ceil:
1480 case Intrinsic::trunc:
1481 case Intrinsic::rint:
1482 case Intrinsic::nearbyint:
1483 case Intrinsic::pow:
1484 case Intrinsic::fma:
1485 case Intrinsic::fmuladd:
1486 return II->getIntrinsicID();
1488 return Intrinsic::not_intrinsic;
1493 return Intrinsic::not_intrinsic;
1496 Function *F = CI->getCalledFunction();
1497 // We're going to make assumptions on the semantics of the functions, check
1498 // that the target knows that it's available in this environment.
1499 if (!F || !TLI->getLibFunc(F->getName(), Func))
1500 return Intrinsic::not_intrinsic;
1502 // Otherwise check if we have a call to a function that can be turned into a
1503 // vector intrinsic.
1510 return Intrinsic::sin;
1514 return Intrinsic::cos;
1518 return Intrinsic::exp;
1520 case LibFunc::exp2f:
1521 case LibFunc::exp2l:
1522 return Intrinsic::exp2;
1526 return Intrinsic::log;
1527 case LibFunc::log10:
1528 case LibFunc::log10f:
1529 case LibFunc::log10l:
1530 return Intrinsic::log10;
1532 case LibFunc::log2f:
1533 case LibFunc::log2l:
1534 return Intrinsic::log2;
1536 case LibFunc::fabsf:
1537 case LibFunc::fabsl:
1538 return Intrinsic::fabs;
1539 case LibFunc::floor:
1540 case LibFunc::floorf:
1541 case LibFunc::floorl:
1542 return Intrinsic::floor;
1544 case LibFunc::ceilf:
1545 case LibFunc::ceill:
1546 return Intrinsic::ceil;
1547 case LibFunc::trunc:
1548 case LibFunc::truncf:
1549 case LibFunc::truncl:
1550 return Intrinsic::trunc;
1552 case LibFunc::rintf:
1553 case LibFunc::rintl:
1554 return Intrinsic::rint;
1555 case LibFunc::nearbyint:
1556 case LibFunc::nearbyintf:
1557 case LibFunc::nearbyintl:
1558 return Intrinsic::nearbyint;
1562 return Intrinsic::pow;
1565 return Intrinsic::not_intrinsic;
1568 /// This function translates the reduction kind to an LLVM binary operator.
1569 static Instruction::BinaryOps
1570 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1572 case LoopVectorizationLegality::RK_IntegerAdd:
1573 return Instruction::Add;
1574 case LoopVectorizationLegality::RK_IntegerMult:
1575 return Instruction::Mul;
1576 case LoopVectorizationLegality::RK_IntegerOr:
1577 return Instruction::Or;
1578 case LoopVectorizationLegality::RK_IntegerAnd:
1579 return Instruction::And;
1580 case LoopVectorizationLegality::RK_IntegerXor:
1581 return Instruction::Xor;
1582 case LoopVectorizationLegality::RK_FloatMult:
1583 return Instruction::FMul;
1584 case LoopVectorizationLegality::RK_FloatAdd:
1585 return Instruction::FAdd;
1587 llvm_unreachable("Unknown reduction operation");
1592 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1593 //===------------------------------------------------===//
1595 // Notice: any optimization or new instruction that go
1596 // into the code below should be also be implemented in
1599 //===------------------------------------------------===//
1600 Constant *Zero = Builder.getInt32(0);
1602 // In order to support reduction variables we need to be able to vectorize
1603 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1604 // stages. First, we create a new vector PHI node with no incoming edges.
1605 // We use this value when we vectorize all of the instructions that use the
1606 // PHI. Next, after all of the instructions in the block are complete we
1607 // add the new incoming edges to the PHI. At this point all of the
1608 // instructions in the basic block are vectorized, so we can use them to
1609 // construct the PHI.
1610 PhiVector RdxPHIsToFix;
1612 // Scan the loop in a topological order to ensure that defs are vectorized
1614 LoopBlocksDFS DFS(OrigLoop);
1617 // Vectorize all of the blocks in the original loop.
1618 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1619 be = DFS.endRPO(); bb != be; ++bb)
1620 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1622 // At this point every instruction in the original loop is widened to
1623 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1624 // that we vectorized. The PHI nodes are currently empty because we did
1625 // not want to introduce cycles. Notice that the remaining PHI nodes
1626 // that we need to fix are reduction variables.
1628 // Create the 'reduced' values for each of the induction vars.
1629 // The reduced values are the vector values that we scalarize and combine
1630 // after the loop is finished.
1631 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1633 PHINode *RdxPhi = *it;
1634 assert(RdxPhi && "Unable to recover vectorized PHI");
1636 // Find the reduction variable descriptor.
1637 assert(Legal->getReductionVars()->count(RdxPhi) &&
1638 "Unable to find the reduction variable");
1639 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1640 (*Legal->getReductionVars())[RdxPhi];
1642 // We need to generate a reduction vector from the incoming scalar.
1643 // To do so, we need to generate the 'identity' vector and overide
1644 // one of the elements with the incoming scalar reduction. We need
1645 // to do it in the vector-loop preheader.
1646 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1648 // This is the vector-clone of the value that leaves the loop.
1649 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1650 Type *VecTy = VectorExit[0]->getType();
1652 // Find the reduction identity variable. Zero for addition, or, xor,
1653 // one for multiplication, -1 for And.
1654 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1655 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1657 // This vector is the Identity vector where the first element is the
1658 // incoming scalar reduction.
1659 Value *VectorStart = Builder.CreateInsertElement(Identity,
1660 RdxDesc.StartValue, Zero);
1662 // Fix the vector-loop phi.
1663 // We created the induction variable so we know that the
1664 // preheader is the first entry.
1665 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1667 // Reductions do not have to start at zero. They can start with
1668 // any loop invariant values.
1669 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1670 BasicBlock *Latch = OrigLoop->getLoopLatch();
1671 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1672 VectorParts &Val = getVectorValue(LoopVal);
1673 for (unsigned part = 0; part < UF; ++part) {
1674 // Make sure to add the reduction stat value only to the
1675 // first unroll part.
1676 Value *StartVal = (part == 0) ? VectorStart : Identity;
1677 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1678 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1681 // Before each round, move the insertion point right between
1682 // the PHIs and the values we are going to write.
1683 // This allows us to write both PHINodes and the extractelement
1685 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1687 VectorParts RdxParts;
1688 for (unsigned part = 0; part < UF; ++part) {
1689 // This PHINode contains the vectorized reduction variable, or
1690 // the initial value vector, if we bypass the vector loop.
1691 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1692 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1693 Value *StartVal = (part == 0) ? VectorStart : Identity;
1694 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1695 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1696 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1697 RdxParts.push_back(NewPhi);
1700 // Reduce all of the unrolled parts into a single vector.
1701 Value *ReducedPartRdx = RdxParts[0];
1702 for (unsigned part = 1; part < UF; ++part) {
1703 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1704 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1708 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1709 // and vector ops, reducing the set of values being computed by half each
1711 assert(isPowerOf2_32(VF) &&
1712 "Reduction emission only supported for pow2 vectors!");
1713 Value *TmpVec = ReducedPartRdx;
1714 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1715 for (unsigned i = VF; i != 1; i >>= 1) {
1716 // Move the upper half of the vector to the lower half.
1717 for (unsigned j = 0; j != i/2; ++j)
1718 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1720 // Fill the rest of the mask with undef.
1721 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1722 UndefValue::get(Builder.getInt32Ty()));
1725 Builder.CreateShuffleVector(TmpVec,
1726 UndefValue::get(TmpVec->getType()),
1727 ConstantVector::get(ShuffleMask),
1730 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1731 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1734 // The result is in the first element of the vector.
1735 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1737 // Now, we need to fix the users of the reduction variable
1738 // inside and outside of the scalar remainder loop.
1739 // We know that the loop is in LCSSA form. We need to update the
1740 // PHI nodes in the exit blocks.
1741 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1742 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1743 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1744 if (!LCSSAPhi) continue;
1746 // All PHINodes need to have a single entry edge, or two if
1747 // we already fixed them.
1748 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1750 // We found our reduction value exit-PHI. Update it with the
1751 // incoming bypass edge.
1752 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1753 // Add an edge coming from the bypass.
1754 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1757 }// end of the LCSSA phi scan.
1759 // Fix the scalar loop reduction variable with the incoming reduction sum
1760 // from the vector body and from the backedge value.
1761 int IncomingEdgeBlockIdx =
1762 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1763 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1764 // Pick the other block.
1765 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1766 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1767 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1768 }// end of for each redux variable.
1770 // The Loop exit block may have single value PHI nodes where the incoming
1771 // value is 'undef'. While vectorizing we only handled real values that
1772 // were defined inside the loop. Here we handle the 'undef case'.
1774 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1775 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1776 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1777 if (!LCSSAPhi) continue;
1778 if (LCSSAPhi->getNumIncomingValues() == 1)
1779 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1784 InnerLoopVectorizer::VectorParts
1785 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1786 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1789 VectorParts SrcMask = createBlockInMask(Src);
1791 // The terminator has to be a branch inst!
1792 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1793 assert(BI && "Unexpected terminator found");
1795 if (BI->isConditional()) {
1796 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1798 if (BI->getSuccessor(0) != Dst)
1799 for (unsigned part = 0; part < UF; ++part)
1800 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1802 for (unsigned part = 0; part < UF; ++part)
1803 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1810 InnerLoopVectorizer::VectorParts
1811 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1812 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1814 // Loop incoming mask is all-one.
1815 if (OrigLoop->getHeader() == BB) {
1816 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1817 return getVectorValue(C);
1820 // This is the block mask. We OR all incoming edges, and with zero.
1821 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1822 VectorParts BlockMask = getVectorValue(Zero);
1825 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1826 VectorParts EM = createEdgeMask(*it, BB);
1827 for (unsigned part = 0; part < UF; ++part)
1828 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1835 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1836 BasicBlock *BB, PhiVector *PV) {
1837 // For each instruction in the old loop.
1838 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1839 VectorParts &Entry = WidenMap.get(it);
1840 switch (it->getOpcode()) {
1841 case Instruction::Br:
1842 // Nothing to do for PHIs and BR, since we already took care of the
1843 // loop control flow instructions.
1845 case Instruction::PHI:{
1846 PHINode* P = cast<PHINode>(it);
1847 // Handle reduction variables:
1848 if (Legal->getReductionVars()->count(P)) {
1849 for (unsigned part = 0; part < UF; ++part) {
1850 // This is phase one of vectorizing PHIs.
1851 Type *VecTy = VectorType::get(it->getType(), VF);
1852 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1853 LoopVectorBody-> getFirstInsertionPt());
1859 // Check for PHI nodes that are lowered to vector selects.
1860 if (P->getParent() != OrigLoop->getHeader()) {
1861 // We know that all PHIs in non header blocks are converted into
1862 // selects, so we don't have to worry about the insertion order and we
1863 // can just use the builder.
1865 // At this point we generate the predication tree. There may be
1866 // duplications since this is a simple recursive scan, but future
1867 // optimizations will clean it up.
1868 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1871 for (unsigned part = 0; part < UF; ++part) {
1872 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1873 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1874 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1880 // This PHINode must be an induction variable.
1881 // Make sure that we know about it.
1882 assert(Legal->getInductionVars()->count(P) &&
1883 "Not an induction variable");
1885 LoopVectorizationLegality::InductionInfo II =
1886 Legal->getInductionVars()->lookup(P);
1889 case LoopVectorizationLegality::IK_NoInduction:
1890 llvm_unreachable("Unknown induction");
1891 case LoopVectorizationLegality::IK_IntInduction: {
1892 assert(P == OldInduction && "Unexpected PHI");
1893 Value *Broadcasted = getBroadcastInstrs(Induction);
1894 // After broadcasting the induction variable we need to make the
1895 // vector consecutive by adding 0, 1, 2 ...
1896 for (unsigned part = 0; part < UF; ++part)
1897 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1900 case LoopVectorizationLegality::IK_ReverseIntInduction:
1901 case LoopVectorizationLegality::IK_PtrInduction:
1902 case LoopVectorizationLegality::IK_ReversePtrInduction:
1903 // Handle reverse integer and pointer inductions.
1904 Value *StartIdx = 0;
1905 // If we have a single integer induction variable then use it.
1906 // Otherwise, start counting at zero.
1908 LoopVectorizationLegality::InductionInfo OldII =
1909 Legal->getInductionVars()->lookup(OldInduction);
1910 StartIdx = OldII.StartValue;
1912 StartIdx = ConstantInt::get(Induction->getType(), 0);
1914 // This is the normalized GEP that starts counting at zero.
1915 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1918 // Handle the reverse integer induction variable case.
1919 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1920 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1921 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1923 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1926 // This is a new value so do not hoist it out.
1927 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1928 // After broadcasting the induction variable we need to make the
1929 // vector consecutive by adding ... -3, -2, -1, 0.
1930 for (unsigned part = 0; part < UF; ++part)
1931 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1935 // Handle the pointer induction variable case.
1936 assert(P->getType()->isPointerTy() && "Unexpected type.");
1938 // Is this a reverse induction ptr or a consecutive induction ptr.
1939 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
1942 // This is the vector of results. Notice that we don't generate
1943 // vector geps because scalar geps result in better code.
1944 for (unsigned part = 0; part < UF; ++part) {
1945 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1946 for (unsigned int i = 0; i < VF; ++i) {
1947 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
1948 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
1951 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1953 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
1955 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1957 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1958 Builder.getInt32(i),
1961 Entry[part] = VecVal;
1968 case Instruction::Add:
1969 case Instruction::FAdd:
1970 case Instruction::Sub:
1971 case Instruction::FSub:
1972 case Instruction::Mul:
1973 case Instruction::FMul:
1974 case Instruction::UDiv:
1975 case Instruction::SDiv:
1976 case Instruction::FDiv:
1977 case Instruction::URem:
1978 case Instruction::SRem:
1979 case Instruction::FRem:
1980 case Instruction::Shl:
1981 case Instruction::LShr:
1982 case Instruction::AShr:
1983 case Instruction::And:
1984 case Instruction::Or:
1985 case Instruction::Xor: {
1986 // Just widen binops.
1987 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1988 VectorParts &A = getVectorValue(it->getOperand(0));
1989 VectorParts &B = getVectorValue(it->getOperand(1));
1991 // Use this vector value for all users of the original instruction.
1992 for (unsigned Part = 0; Part < UF; ++Part) {
1993 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1995 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1996 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1997 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1998 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1999 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2001 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2002 VecOp->setIsExact(BinOp->isExact());
2008 case Instruction::Select: {
2010 // If the selector is loop invariant we can create a select
2011 // instruction with a scalar condition. Otherwise, use vector-select.
2012 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2015 // The condition can be loop invariant but still defined inside the
2016 // loop. This means that we can't just use the original 'cond' value.
2017 // We have to take the 'vectorized' value and pick the first lane.
2018 // Instcombine will make this a no-op.
2019 VectorParts &Cond = getVectorValue(it->getOperand(0));
2020 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2021 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2022 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2023 Builder.getInt32(0));
2024 for (unsigned Part = 0; Part < UF; ++Part) {
2025 Entry[Part] = Builder.CreateSelect(
2026 InvariantCond ? ScalarCond : Cond[Part],
2033 case Instruction::ICmp:
2034 case Instruction::FCmp: {
2035 // Widen compares. Generate vector compares.
2036 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2037 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2038 VectorParts &A = getVectorValue(it->getOperand(0));
2039 VectorParts &B = getVectorValue(it->getOperand(1));
2040 for (unsigned Part = 0; Part < UF; ++Part) {
2043 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2045 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2051 case Instruction::Store:
2052 case Instruction::Load:
2053 vectorizeMemoryInstruction(it, Legal);
2055 case Instruction::ZExt:
2056 case Instruction::SExt:
2057 case Instruction::FPToUI:
2058 case Instruction::FPToSI:
2059 case Instruction::FPExt:
2060 case Instruction::PtrToInt:
2061 case Instruction::IntToPtr:
2062 case Instruction::SIToFP:
2063 case Instruction::UIToFP:
2064 case Instruction::Trunc:
2065 case Instruction::FPTrunc:
2066 case Instruction::BitCast: {
2067 CastInst *CI = dyn_cast<CastInst>(it);
2068 /// Optimize the special case where the source is the induction
2069 /// variable. Notice that we can only optimize the 'trunc' case
2070 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2071 /// c. other casts depend on pointer size.
2072 if (CI->getOperand(0) == OldInduction &&
2073 it->getOpcode() == Instruction::Trunc) {
2074 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2076 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2077 for (unsigned Part = 0; Part < UF; ++Part)
2078 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2081 /// Vectorize casts.
2082 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2084 VectorParts &A = getVectorValue(it->getOperand(0));
2085 for (unsigned Part = 0; Part < UF; ++Part)
2086 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2090 case Instruction::Call: {
2091 Module *M = BB->getParent()->getParent();
2092 CallInst *CI = cast<CallInst>(it);
2093 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2094 assert(ID && "Not an intrinsic call!");
2095 for (unsigned Part = 0; Part < UF; ++Part) {
2096 SmallVector<Value*, 4> Args;
2097 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2098 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2099 Args.push_back(Arg[Part]);
2101 Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2102 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2103 Entry[Part] = Builder.CreateCall(F, Args);
2109 // All other instructions are unsupported. Scalarize them.
2110 scalarizeInstruction(it);
2113 }// end of for_each instr.
2116 void InnerLoopVectorizer::updateAnalysis() {
2117 // Forget the original basic block.
2118 SE->forgetLoop(OrigLoop);
2120 // Update the dominator tree information.
2121 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2122 "Entry does not dominate exit.");
2124 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2125 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2126 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2127 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2128 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2129 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2130 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2131 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2133 DEBUG(DT->verifyAnalysis());
2136 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2137 if (!EnableIfConversion)
2140 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2141 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2143 // Collect the blocks that need predication.
2144 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2145 BasicBlock *BB = LoopBlocks[i];
2147 // We don't support switch statements inside loops.
2148 if (!isa<BranchInst>(BB->getTerminator()))
2151 // We must have at most two predecessors because we need to convert
2152 // all PHIs to selects.
2153 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2157 // We must be able to predicate all blocks that need to be predicated.
2158 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2162 // We can if-convert this loop.
2166 bool LoopVectorizationLegality::canVectorize() {
2167 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2169 // We can only vectorize innermost loops.
2170 if (TheLoop->getSubLoopsVector().size())
2173 // We must have a single backedge.
2174 if (TheLoop->getNumBackEdges() != 1)
2177 // We must have a single exiting block.
2178 if (!TheLoop->getExitingBlock())
2181 unsigned NumBlocks = TheLoop->getNumBlocks();
2183 // Check if we can if-convert non single-bb loops.
2184 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2185 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2189 // We need to have a loop header.
2190 BasicBlock *Latch = TheLoop->getLoopLatch();
2191 DEBUG(dbgs() << "LV: Found a loop: " <<
2192 TheLoop->getHeader()->getName() << "\n");
2194 // ScalarEvolution needs to be able to find the exit count.
2195 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2196 if (ExitCount == SE->getCouldNotCompute()) {
2197 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2201 // Do not loop-vectorize loops with a tiny trip count.
2202 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2203 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2204 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2205 "This loop is not worth vectorizing.\n");
2209 // Check if we can vectorize the instructions and CFG in this loop.
2210 if (!canVectorizeInstrs()) {
2211 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2215 // Go over each instruction and look at memory deps.
2216 if (!canVectorizeMemory()) {
2217 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2221 // Collect all of the variables that remain uniform after vectorization.
2222 collectLoopUniforms();
2224 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2225 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2228 // Okay! We can vectorize. At this point we don't have any other mem analysis
2229 // which may limit our maximum vectorization factor, so just return true with
2234 bool LoopVectorizationLegality::canVectorizeInstrs() {
2235 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2236 BasicBlock *Header = TheLoop->getHeader();
2238 // If we marked the scalar loop as "already vectorized" then no need
2239 // to vectorize it again.
2240 if (Header->getTerminator()->getMetadata(AlreadyVectorizedMDName)) {
2241 DEBUG(dbgs() << "LV: This loop was vectorized before\n");
2245 // For each block in the loop.
2246 for (Loop::block_iterator bb = TheLoop->block_begin(),
2247 be = TheLoop->block_end(); bb != be; ++bb) {
2249 // Scan the instructions in the block and look for hazards.
2250 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2253 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2254 // This should not happen because the loop should be normalized.
2255 if (Phi->getNumIncomingValues() != 2) {
2256 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2260 // Check that this PHI type is allowed.
2261 if (!Phi->getType()->isIntegerTy() &&
2262 !Phi->getType()->isFloatingPointTy() &&
2263 !Phi->getType()->isPointerTy()) {
2264 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2268 // If this PHINode is not in the header block, then we know that we
2269 // can convert it to select during if-conversion. No need to check if
2270 // the PHIs in this block are induction or reduction variables.
2274 // This is the value coming from the preheader.
2275 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2276 // Check if this is an induction variable.
2277 InductionKind IK = isInductionVariable(Phi);
2279 if (IK_NoInduction != IK) {
2280 // Int inductions are special because we only allow one IV.
2281 if (IK == IK_IntInduction) {
2283 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2289 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2290 Inductions[Phi] = InductionInfo(StartValue, IK);
2294 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2295 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2298 if (AddReductionVar(Phi, RK_IntegerMult)) {
2299 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2302 if (AddReductionVar(Phi, RK_IntegerOr)) {
2303 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2306 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2307 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2310 if (AddReductionVar(Phi, RK_IntegerXor)) {
2311 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2314 if (AddReductionVar(Phi, RK_FloatMult)) {
2315 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2318 if (AddReductionVar(Phi, RK_FloatAdd)) {
2319 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2323 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2325 }// end of PHI handling
2327 // We still don't handle functions.
2328 CallInst *CI = dyn_cast<CallInst>(it);
2329 if (CI && !getIntrinsicIDForCall(CI, TLI)) {
2330 DEBUG(dbgs() << "LV: Found a call site.\n");
2334 // Check that the instruction return type is vectorizable.
2335 if (!VectorType::isValidElementType(it->getType()) &&
2336 !it->getType()->isVoidTy()) {
2337 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2341 // Check that the stored type is vectorizable.
2342 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2343 Type *T = ST->getValueOperand()->getType();
2344 if (!VectorType::isValidElementType(T))
2348 // Reduction instructions are allowed to have exit users.
2349 // All other instructions must not have external users.
2350 if (!AllowedExit.count(it))
2351 //Check that all of the users of the loop are inside the BB.
2352 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2354 Instruction *U = cast<Instruction>(*I);
2355 // This user may be a reduction exit value.
2356 if (!TheLoop->contains(U)) {
2357 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2366 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2367 assert(getInductionVars()->size() && "No induction variables");
2373 void LoopVectorizationLegality::collectLoopUniforms() {
2374 // We now know that the loop is vectorizable!
2375 // Collect variables that will remain uniform after vectorization.
2376 std::vector<Value*> Worklist;
2377 BasicBlock *Latch = TheLoop->getLoopLatch();
2379 // Start with the conditional branch and walk up the block.
2380 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2382 while (Worklist.size()) {
2383 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2384 Worklist.pop_back();
2386 // Look at instructions inside this loop.
2387 // Stop when reaching PHI nodes.
2388 // TODO: we need to follow values all over the loop, not only in this block.
2389 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2392 // This is a known uniform.
2395 // Insert all operands.
2396 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2397 Worklist.push_back(I->getOperand(i));
2402 AliasAnalysis::Location
2403 LoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
2404 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
2405 return AA->getLocation(Store);
2406 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
2407 return AA->getLocation(Load);
2409 llvm_unreachable("Should be either load or store instruction");
2413 LoopVectorizationLegality::hasPossibleGlobalWriteReorder(
2416 AliasMultiMap& WriteObjects,
2417 unsigned MaxByteWidth) {
2419 AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
2421 std::vector<Instruction*>::iterator
2422 it = WriteObjects[Object].begin(),
2423 end = WriteObjects[Object].end();
2425 for (; it != end; ++it) {
2426 Instruction* I = *it;
2430 AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
2431 if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
2432 ThatLoc.getWithNewSize(MaxByteWidth)))
2438 bool LoopVectorizationLegality::canVectorizeMemory() {
2440 if (TheLoop->isAnnotatedParallel()) {
2442 << "LV: A loop annotated parallel, ignore memory dependency "
2447 typedef SmallVector<Value*, 16> ValueVector;
2448 typedef SmallPtrSet<Value*, 16> ValueSet;
2449 // Holds the Load and Store *instructions*.
2452 PtrRtCheck.Pointers.clear();
2453 PtrRtCheck.Need = false;
2456 for (Loop::block_iterator bb = TheLoop->block_begin(),
2457 be = TheLoop->block_end(); bb != be; ++bb) {
2459 // Scan the BB and collect legal loads and stores.
2460 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2463 // If this is a load, save it. If this instruction can read from memory
2464 // but is not a load, then we quit. Notice that we don't handle function
2465 // calls that read or write.
2466 if (it->mayReadFromMemory()) {
2467 LoadInst *Ld = dyn_cast<LoadInst>(it);
2468 if (!Ld) return false;
2469 if (!Ld->isSimple()) {
2470 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2473 Loads.push_back(Ld);
2477 // Save 'store' instructions. Abort if other instructions write to memory.
2478 if (it->mayWriteToMemory()) {
2479 StoreInst *St = dyn_cast<StoreInst>(it);
2480 if (!St) return false;
2481 if (!St->isSimple()) {
2482 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2485 Stores.push_back(St);
2490 // Now we have two lists that hold the loads and the stores.
2491 // Next, we find the pointers that they use.
2493 // Check if we see any stores. If there are no stores, then we don't
2494 // care if the pointers are *restrict*.
2495 if (!Stores.size()) {
2496 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2500 // Holds the read and read-write *pointers* that we find. These maps hold
2501 // unique values for pointers (so no need for multi-map).
2503 AliasMap ReadWrites;
2505 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2506 // multiple times on the same object. If the ptr is accessed twice, once
2507 // for read and once for write, it will only appear once (on the write
2508 // list). This is okay, since we are going to check for conflicts between
2509 // writes and between reads and writes, but not between reads and reads.
2512 ValueVector::iterator I, IE;
2513 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2514 StoreInst *ST = cast<StoreInst>(*I);
2515 Value* Ptr = ST->getPointerOperand();
2517 if (isUniform(Ptr)) {
2518 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2522 // If we did *not* see this pointer before, insert it to
2523 // the read-write list. At this phase it is only a 'write' list.
2524 if (Seen.insert(Ptr))
2525 ReadWrites.insert(std::make_pair(Ptr, ST));
2528 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2529 LoadInst *LD = cast<LoadInst>(*I);
2530 Value* Ptr = LD->getPointerOperand();
2531 // If we did *not* see this pointer before, insert it to the
2532 // read list. If we *did* see it before, then it is already in
2533 // the read-write list. This allows us to vectorize expressions
2534 // such as A[i] += x; Because the address of A[i] is a read-write
2535 // pointer. This only works if the index of A[i] is consecutive.
2536 // If the address of i is unknown (for example A[B[i]]) then we may
2537 // read a few words, modify, and write a few words, and some of the
2538 // words may be written to the same address.
2539 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2540 Reads.insert(std::make_pair(Ptr, LD));
2543 // If we write (or read-write) to a single destination and there are no
2544 // other reads in this loop then is it safe to vectorize.
2545 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2546 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2550 // Find pointers with computable bounds. We are going to use this information
2551 // to place a runtime bound check.
2552 bool CanDoRT = true;
2553 AliasMap::iterator MI, ME;
2554 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2555 Value *V = (*MI).first;
2556 if (hasComputableBounds(V)) {
2557 PtrRtCheck.insert(SE, TheLoop, V);
2558 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2564 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2565 Value *V = (*MI).first;
2566 if (hasComputableBounds(V)) {
2567 PtrRtCheck.insert(SE, TheLoop, V);
2568 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2575 // Check that we did not collect too many pointers or found a
2576 // unsizeable pointer.
2577 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2583 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2586 bool NeedRTCheck = false;
2588 // Biggest vectorized access possible, vector width * unroll factor.
2589 // TODO: We're being very pessimistic here, find a way to know the
2590 // real access width before getting here.
2591 unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
2592 TTI->getMaximumUnrollFactor();
2593 // Now that the pointers are in two lists (Reads and ReadWrites), we
2594 // can check that there are no conflicts between each of the writes and
2595 // between the writes to the reads.
2596 // Note that WriteObjects duplicates the stores (indexed now by underlying
2597 // objects) to avoid pointing to elements inside ReadWrites.
2598 // TODO: Maybe create a new type where they can interact without duplication.
2599 AliasMultiMap WriteObjects;
2600 ValueVector TempObjects;
2602 // Check that the read-writes do not conflict with other read-write
2604 bool AllWritesIdentified = true;
2605 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2606 Value *Val = (*MI).first;
2607 Instruction *Inst = (*MI).second;
2609 GetUnderlyingObjects(Val, TempObjects, DL);
2610 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2612 if (!isIdentifiedObject(*UI)) {
2613 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
2615 AllWritesIdentified = false;
2618 // Never seen it before, can't alias.
2619 if (WriteObjects[*UI].empty()) {
2620 DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
2621 WriteObjects[*UI].push_back(Inst);
2624 // Direct alias found.
2625 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2626 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2630 DEBUG(dbgs() << "LV: Found a conflicting global value:"
2632 DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
2633 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2635 // If global alias, make sure they do alias.
2636 if (hasPossibleGlobalWriteReorder(*UI,
2640 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2645 // Didn't alias, insert into map for further reference.
2646 WriteObjects[*UI].push_back(Inst);
2648 TempObjects.clear();
2651 /// Check that the reads don't conflict with the read-writes.
2652 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2653 Value *Val = (*MI).first;
2654 GetUnderlyingObjects(Val, TempObjects, DL);
2655 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2657 // If all of the writes are identified then we don't care if the read
2658 // pointer is identified or not.
2659 if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
2660 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
2664 // Never seen it before, can't alias.
2665 if (WriteObjects[*UI].empty())
2667 // Direct alias found.
2668 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2669 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2673 DEBUG(dbgs() << "LV: Found a global value: "
2675 Instruction *Inst = (*MI).second;
2676 DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
2677 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2679 // If global alias, make sure they do alias.
2680 if (hasPossibleGlobalWriteReorder(*UI,
2684 DEBUG(dbgs() << "LV: Found a possible read-write reorder:"
2689 TempObjects.clear();
2692 PtrRtCheck.Need = NeedRTCheck;
2693 if (NeedRTCheck && !CanDoRT) {
2694 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2695 "the array bounds.\n");
2700 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2701 " need a runtime memory check.\n");
2705 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2706 ReductionKind Kind) {
2707 if (Phi->getNumIncomingValues() != 2)
2710 // Reduction variables are only found in the loop header block.
2711 if (Phi->getParent() != TheLoop->getHeader())
2714 // Obtain the reduction start value from the value that comes from the loop
2716 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2718 // ExitInstruction is the single value which is used outside the loop.
2719 // We only allow for a single reduction value to be used outside the loop.
2720 // This includes users of the reduction, variables (which form a cycle
2721 // which ends in the phi node).
2722 Instruction *ExitInstruction = 0;
2723 // Indicates that we found a binary operation in our scan.
2724 bool FoundBinOp = false;
2726 // Iter is our iterator. We start with the PHI node and scan for all of the
2727 // users of this instruction. All users must be instructions that can be
2728 // used as reduction variables (such as ADD). We may have a single
2729 // out-of-block user. The cycle must end with the original PHI.
2730 Instruction *Iter = Phi;
2732 // If the instruction has no users then this is a broken
2733 // chain and can't be a reduction variable.
2734 if (Iter->use_empty())
2737 // Did we find a user inside this loop already ?
2738 bool FoundInBlockUser = false;
2739 // Did we reach the initial PHI node already ?
2740 bool FoundStartPHI = false;
2742 // Is this a bin op ?
2743 FoundBinOp |= !isa<PHINode>(Iter);
2745 // Remember the current instruction.
2746 Instruction *OldIter = Iter;
2748 // For each of the *users* of iter.
2749 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2751 Instruction *U = cast<Instruction>(*it);
2752 // We already know that the PHI is a user.
2754 FoundStartPHI = true;
2758 // Check if we found the exit user.
2759 BasicBlock *Parent = U->getParent();
2760 if (!TheLoop->contains(Parent)) {
2761 // Exit if you find multiple outside users.
2762 if (ExitInstruction != 0)
2764 ExitInstruction = Iter;
2767 // We allow in-loop PHINodes which are not the original reduction PHI
2768 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2769 // structure) then don't skip this PHI.
2770 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2771 U->getParent() != TheLoop->getHeader() &&
2772 TheLoop->contains(U) &&
2773 Iter->hasNUsesOrMore(2))
2776 // We can't have multiple inside users.
2777 if (FoundInBlockUser)
2779 FoundInBlockUser = true;
2781 // Any reduction instr must be of one of the allowed kinds.
2782 if (!isReductionInstr(U, Kind))
2785 // Reductions of instructions such as Div, and Sub is only
2786 // possible if the LHS is the reduction variable.
2787 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2793 // If all uses were skipped this can't be a reduction variable.
2794 if (Iter == OldIter)
2797 // We found a reduction var if we have reached the original
2798 // phi node and we only have a single instruction with out-of-loop
2800 if (FoundStartPHI) {
2801 // This instruction is allowed to have out-of-loop users.
2802 AllowedExit.insert(ExitInstruction);
2804 // Save the description of this reduction variable.
2805 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2806 Reductions[Phi] = RD;
2807 // We've ended the cycle. This is a reduction variable if we have an
2808 // outside user and it has a binary op.
2809 return FoundBinOp && ExitInstruction;
2815 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2816 ReductionKind Kind) {
2817 bool FP = I->getType()->isFloatingPointTy();
2818 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2820 switch (I->getOpcode()) {
2823 case Instruction::PHI:
2824 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2828 case Instruction::Sub:
2829 case Instruction::Add:
2830 return Kind == RK_IntegerAdd;
2831 case Instruction::SDiv:
2832 case Instruction::UDiv:
2833 case Instruction::Mul:
2834 return Kind == RK_IntegerMult;
2835 case Instruction::And:
2836 return Kind == RK_IntegerAnd;
2837 case Instruction::Or:
2838 return Kind == RK_IntegerOr;
2839 case Instruction::Xor:
2840 return Kind == RK_IntegerXor;
2841 case Instruction::FMul:
2842 return Kind == RK_FloatMult && FastMath;
2843 case Instruction::FAdd:
2844 return Kind == RK_FloatAdd && FastMath;
2848 LoopVectorizationLegality::InductionKind
2849 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2850 Type *PhiTy = Phi->getType();
2851 // We only handle integer and pointer inductions variables.
2852 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2853 return IK_NoInduction;
2855 // Check that the PHI is consecutive.
2856 const SCEV *PhiScev = SE->getSCEV(Phi);
2857 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2859 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2860 return IK_NoInduction;
2862 const SCEV *Step = AR->getStepRecurrence(*SE);
2864 // Integer inductions need to have a stride of one.
2865 if (PhiTy->isIntegerTy()) {
2867 return IK_IntInduction;
2868 if (Step->isAllOnesValue())
2869 return IK_ReverseIntInduction;
2870 return IK_NoInduction;
2873 // Calculate the pointer stride and check if it is consecutive.
2874 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2876 return IK_NoInduction;
2878 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2879 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2880 if (C->getValue()->equalsInt(Size))
2881 return IK_PtrInduction;
2882 else if (C->getValue()->equalsInt(0 - Size))
2883 return IK_ReversePtrInduction;
2885 return IK_NoInduction;
2888 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2889 Value *In0 = const_cast<Value*>(V);
2890 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2894 return Inductions.count(PN);
2897 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2898 assert(TheLoop->contains(BB) && "Unknown block used");
2900 // Blocks that do not dominate the latch need predication.
2901 BasicBlock* Latch = TheLoop->getLoopLatch();
2902 return !DT->dominates(BB, Latch);
2905 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2906 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2907 // We don't predicate loads/stores at the moment.
2908 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2911 // The instructions below can trap.
2912 switch (it->getOpcode()) {
2914 case Instruction::UDiv:
2915 case Instruction::SDiv:
2916 case Instruction::URem:
2917 case Instruction::SRem:
2925 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2926 const SCEV *PhiScev = SE->getSCEV(Ptr);
2927 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2931 return AR->isAffine();
2934 LoopVectorizationCostModel::VectorizationFactor
2935 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2937 // Width 1 means no vectorize
2938 VectorizationFactor Factor = { 1U, 0U };
2939 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2940 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2944 // Find the trip count.
2945 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2946 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2948 unsigned WidestType = getWidestType();
2949 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2950 unsigned MaxVectorSize = WidestRegister / WidestType;
2951 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2952 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2954 if (MaxVectorSize == 0) {
2955 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2959 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2960 " into one vector!");
2962 unsigned VF = MaxVectorSize;
2964 // If we optimize the program for size, avoid creating the tail loop.
2966 // If we are unable to calculate the trip count then don't try to vectorize.
2968 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2972 // Find the maximum SIMD width that can fit within the trip count.
2973 VF = TC % MaxVectorSize;
2978 // If the trip count that we found modulo the vectorization factor is not
2979 // zero then we require a tail.
2981 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2987 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2988 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2990 Factor.Width = UserVF;
2994 float Cost = expectedCost(1);
2996 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2997 for (unsigned i=2; i <= VF; i*=2) {
2998 // Notice that the vector loop needs to be executed less times, so
2999 // we need to divide the cost of the vector loops by the width of
3000 // the vector elements.
3001 float VectorCost = expectedCost(i) / (float)i;
3002 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
3003 (int)VectorCost << ".\n");
3004 if (VectorCost < Cost) {
3010 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
3011 Factor.Width = Width;
3012 Factor.Cost = Width * Cost;
3016 unsigned LoopVectorizationCostModel::getWidestType() {
3017 unsigned MaxWidth = 8;
3020 for (Loop::block_iterator bb = TheLoop->block_begin(),
3021 be = TheLoop->block_end(); bb != be; ++bb) {
3022 BasicBlock *BB = *bb;
3024 // For each instruction in the loop.
3025 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3026 Type *T = it->getType();
3028 // Only examine Loads, Stores and PHINodes.
3029 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
3032 // Examine PHI nodes that are reduction variables.
3033 if (PHINode *PN = dyn_cast<PHINode>(it))
3034 if (!Legal->getReductionVars()->count(PN))
3037 // Examine the stored values.
3038 if (StoreInst *ST = dyn_cast<StoreInst>(it))
3039 T = ST->getValueOperand()->getType();
3041 // Ignore loaded pointer types and stored pointer types that are not
3042 // consecutive. However, we do want to take consecutive stores/loads of
3043 // pointer vectors into account.
3044 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
3047 MaxWidth = std::max(MaxWidth,
3048 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
3056 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
3059 unsigned LoopCost) {
3061 // -- The unroll heuristics --
3062 // We unroll the loop in order to expose ILP and reduce the loop overhead.
3063 // There are many micro-architectural considerations that we can't predict
3064 // at this level. For example frontend pressure (on decode or fetch) due to
3065 // code size, or the number and capabilities of the execution ports.
3067 // We use the following heuristics to select the unroll factor:
3068 // 1. If the code has reductions the we unroll in order to break the cross
3069 // iteration dependency.
3070 // 2. If the loop is really small then we unroll in order to reduce the loop
3072 // 3. We don't unroll if we think that we will spill registers to memory due
3073 // to the increased register pressure.
3075 // Use the user preference, unless 'auto' is selected.
3079 // When we optimize for size we don't unroll.
3083 // Do not unroll loops with a relatively small trip count.
3084 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
3085 TheLoop->getLoopLatch());
3086 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
3089 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
3090 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
3091 " vector registers\n");
3093 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
3094 // We divide by these constants so assume that we have at least one
3095 // instruction that uses at least one register.
3096 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
3097 R.NumInstructions = std::max(R.NumInstructions, 1U);
3099 // We calculate the unroll factor using the following formula.
3100 // Subtract the number of loop invariants from the number of available
3101 // registers. These registers are used by all of the unrolled instances.
3102 // Next, divide the remaining registers by the number of registers that is
3103 // required by the loop, in order to estimate how many parallel instances
3104 // fit without causing spills.
3105 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
3107 // Clamp the unroll factor ranges to reasonable factors.
3108 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
3110 // If we did not calculate the cost for VF (because the user selected the VF)
3111 // then we calculate the cost of VF here.
3113 LoopCost = expectedCost(VF);
3115 // Clamp the calculated UF to be between the 1 and the max unroll factor
3116 // that the target allows.
3117 if (UF > MaxUnrollSize)
3122 if (Legal->getReductionVars()->size()) {
3123 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3127 // We want to unroll tiny loops in order to reduce the loop overhead.
3128 // We assume that the cost overhead is 1 and we use the cost model
3129 // to estimate the cost of the loop and unroll until the cost of the
3130 // loop overhead is about 5% of the cost of the loop.
3131 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3132 if (LoopCost < 20) {
3133 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3134 unsigned NewUF = 20/LoopCost + 1;
3135 return std::min(NewUF, UF);
3138 DEBUG(dbgs() << "LV: Not Unrolling. \n");
3142 LoopVectorizationCostModel::RegisterUsage
3143 LoopVectorizationCostModel::calculateRegisterUsage() {
3144 // This function calculates the register usage by measuring the highest number
3145 // of values that are alive at a single location. Obviously, this is a very
3146 // rough estimation. We scan the loop in a topological order in order and
3147 // assign a number to each instruction. We use RPO to ensure that defs are
3148 // met before their users. We assume that each instruction that has in-loop
3149 // users starts an interval. We record every time that an in-loop value is
3150 // used, so we have a list of the first and last occurrences of each
3151 // instruction. Next, we transpose this data structure into a multi map that
3152 // holds the list of intervals that *end* at a specific location. This multi
3153 // map allows us to perform a linear search. We scan the instructions linearly
3154 // and record each time that a new interval starts, by placing it in a set.
3155 // If we find this value in the multi-map then we remove it from the set.
3156 // The max register usage is the maximum size of the set.
3157 // We also search for instructions that are defined outside the loop, but are
3158 // used inside the loop. We need this number separately from the max-interval
3159 // usage number because when we unroll, loop-invariant values do not take
3161 LoopBlocksDFS DFS(TheLoop);
3165 R.NumInstructions = 0;
3167 // Each 'key' in the map opens a new interval. The values
3168 // of the map are the index of the 'last seen' usage of the
3169 // instruction that is the key.
3170 typedef DenseMap<Instruction*, unsigned> IntervalMap;
3171 // Maps instruction to its index.
3172 DenseMap<unsigned, Instruction*> IdxToInstr;
3173 // Marks the end of each interval.
3174 IntervalMap EndPoint;
3175 // Saves the list of instruction indices that are used in the loop.
3176 SmallSet<Instruction*, 8> Ends;
3177 // Saves the list of values that are used in the loop but are
3178 // defined outside the loop, such as arguments and constants.
3179 SmallPtrSet<Value*, 8> LoopInvariants;
3182 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3183 be = DFS.endRPO(); bb != be; ++bb) {
3184 R.NumInstructions += (*bb)->size();
3185 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3187 Instruction *I = it;
3188 IdxToInstr[Index++] = I;
3190 // Save the end location of each USE.
3191 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3192 Value *U = I->getOperand(i);
3193 Instruction *Instr = dyn_cast<Instruction>(U);
3195 // Ignore non-instruction values such as arguments, constants, etc.
3196 if (!Instr) continue;
3198 // If this instruction is outside the loop then record it and continue.
3199 if (!TheLoop->contains(Instr)) {
3200 LoopInvariants.insert(Instr);
3204 // Overwrite previous end points.
3205 EndPoint[Instr] = Index;
3211 // Saves the list of intervals that end with the index in 'key'.
3212 typedef SmallVector<Instruction*, 2> InstrList;
3213 DenseMap<unsigned, InstrList> TransposeEnds;
3215 // Transpose the EndPoints to a list of values that end at each index.
3216 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3218 TransposeEnds[it->second].push_back(it->first);
3220 SmallSet<Instruction*, 8> OpenIntervals;
3221 unsigned MaxUsage = 0;
3224 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3225 for (unsigned int i = 0; i < Index; ++i) {
3226 Instruction *I = IdxToInstr[i];
3227 // Ignore instructions that are never used within the loop.
3228 if (!Ends.count(I)) continue;
3230 // Remove all of the instructions that end at this location.
3231 InstrList &List = TransposeEnds[i];
3232 for (unsigned int j=0, e = List.size(); j < e; ++j)
3233 OpenIntervals.erase(List[j]);
3235 // Count the number of live interals.
3236 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3238 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3239 OpenIntervals.size() <<"\n");
3241 // Add the current instruction to the list of open intervals.
3242 OpenIntervals.insert(I);
3245 unsigned Invariant = LoopInvariants.size();
3246 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3247 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3248 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3250 R.LoopInvariantRegs = Invariant;
3251 R.MaxLocalUsers = MaxUsage;
3255 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3259 for (Loop::block_iterator bb = TheLoop->block_begin(),
3260 be = TheLoop->block_end(); bb != be; ++bb) {
3261 unsigned BlockCost = 0;
3262 BasicBlock *BB = *bb;
3264 // For each instruction in the old loop.
3265 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3266 unsigned C = getInstructionCost(it, VF);
3268 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3269 VF << " For instruction: "<< *it << "\n");
3272 // We assume that if-converted blocks have a 50% chance of being executed.
3273 // When the code is scalar then some of the blocks are avoided due to CF.
3274 // When the code is vectorized we execute all code paths.
3275 if (Legal->blockNeedsPredication(*bb) && VF == 1)
3285 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3286 // If we know that this instruction will remain uniform, check the cost of
3287 // the scalar version.
3288 if (Legal->isUniformAfterVectorization(I))
3291 Type *RetTy = I->getType();
3292 Type *VectorTy = ToVectorTy(RetTy, VF);
3294 // TODO: We need to estimate the cost of intrinsic calls.
3295 switch (I->getOpcode()) {
3296 case Instruction::GetElementPtr:
3297 // We mark this instruction as zero-cost because the cost of GEPs in
3298 // vectorized code depends on whether the corresponding memory instruction
3299 // is scalarized or not. Therefore, we handle GEPs with the memory
3300 // instruction cost.
3302 case Instruction::Br: {
3303 return TTI.getCFInstrCost(I->getOpcode());
3305 case Instruction::PHI:
3306 //TODO: IF-converted IFs become selects.
3308 case Instruction::Add:
3309 case Instruction::FAdd:
3310 case Instruction::Sub:
3311 case Instruction::FSub:
3312 case Instruction::Mul:
3313 case Instruction::FMul:
3314 case Instruction::UDiv:
3315 case Instruction::SDiv:
3316 case Instruction::FDiv:
3317 case Instruction::URem:
3318 case Instruction::SRem:
3319 case Instruction::FRem:
3320 case Instruction::Shl:
3321 case Instruction::LShr:
3322 case Instruction::AShr:
3323 case Instruction::And:
3324 case Instruction::Or:
3325 case Instruction::Xor:
3326 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
3327 case Instruction::Select: {
3328 SelectInst *SI = cast<SelectInst>(I);
3329 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3330 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3331 Type *CondTy = SI->getCondition()->getType();
3333 CondTy = VectorType::get(CondTy, VF);
3335 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3337 case Instruction::ICmp:
3338 case Instruction::FCmp: {
3339 Type *ValTy = I->getOperand(0)->getType();
3340 VectorTy = ToVectorTy(ValTy, VF);
3341 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3343 case Instruction::Store:
3344 case Instruction::Load: {
3345 StoreInst *SI = dyn_cast<StoreInst>(I);
3346 LoadInst *LI = dyn_cast<LoadInst>(I);
3347 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3349 VectorTy = ToVectorTy(ValTy, VF);
3351 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3352 unsigned AS = SI ? SI->getPointerAddressSpace() :
3353 LI->getPointerAddressSpace();
3354 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3355 // We add the cost of address computation here instead of with the gep
3356 // instruction because only here we know whether the operation is
3359 return TTI.getAddressComputationCost(VectorTy) +
3360 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3362 // Scalarized loads/stores.
3363 int Stride = Legal->isConsecutivePtr(Ptr);
3364 bool Reverse = Stride < 0;
3367 // The cost of extracting from the value vector and pointer vector.
3368 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3369 for (unsigned i = 0; i < VF; ++i) {
3370 // The cost of extracting the pointer operand.
3371 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3372 // In case of STORE, the cost of ExtractElement from the vector.
3373 // In case of LOAD, the cost of InsertElement into the returned
3375 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3376 Instruction::InsertElement,
3380 // The cost of the scalar loads/stores.
3381 Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3382 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3387 // Wide load/stores.
3388 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3389 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3392 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3396 case Instruction::ZExt:
3397 case Instruction::SExt:
3398 case Instruction::FPToUI:
3399 case Instruction::FPToSI:
3400 case Instruction::FPExt:
3401 case Instruction::PtrToInt:
3402 case Instruction::IntToPtr:
3403 case Instruction::SIToFP:
3404 case Instruction::UIToFP:
3405 case Instruction::Trunc:
3406 case Instruction::FPTrunc:
3407 case Instruction::BitCast: {
3408 // We optimize the truncation of induction variable.
3409 // The cost of these is the same as the scalar operation.
3410 if (I->getOpcode() == Instruction::Trunc &&
3411 Legal->isInductionVariable(I->getOperand(0)))
3412 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3413 I->getOperand(0)->getType());
3415 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3416 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3418 case Instruction::Call: {
3419 CallInst *CI = cast<CallInst>(I);
3420 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3421 assert(ID && "Not an intrinsic call!");
3422 Type *RetTy = ToVectorTy(CI->getType(), VF);
3423 SmallVector<Type*, 4> Tys;
3424 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3425 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3426 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3429 // We are scalarizing the instruction. Return the cost of the scalar
3430 // instruction, plus the cost of insert and extract into vector
3431 // elements, times the vector width.
3434 if (!RetTy->isVoidTy() && VF != 1) {
3435 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3437 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3440 // The cost of inserting the results plus extracting each one of the
3442 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3445 // The cost of executing VF copies of the scalar instruction. This opcode
3446 // is unknown. Assume that it is the same as 'mul'.
3447 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3453 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3454 if (Scalar->isVoidTy() || VF == 1)
3456 return VectorType::get(Scalar, VF);
3459 char LoopVectorize::ID = 0;
3460 static const char lv_name[] = "Loop Vectorization";
3461 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3462 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3463 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3464 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3465 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3466 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3469 Pass *createLoopVectorizePass() {
3470 return new LoopVectorize();
3474 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3475 // Check for a store.
3476 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
3477 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3479 // Check for a load.
3480 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
3481 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;